device_usage.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package kubemodel
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. )
  7. // @bingen:generate:DeviceUsage
  8. type DeviceUsage struct {
  9. ContainerUID string `json:"containerUid"`
  10. DeviceUID string `json:"deviceUid"`
  11. UsageSeconds Measurement `json:"usageSeconds"`
  12. UsagePercentageMax float64 `json:"usagePercentageMax"`
  13. MemoryByteSecondsUsed Measurement `json:"memoryByteSecondsUsed"`
  14. DeviceType string `json:"deviceType,omitempty"`
  15. DurationSeconds Measurement `json:"durationSeconds,omitempty"`
  16. Start time.Time `json:"start"`
  17. End time.Time `json:"end"`
  18. }
  19. func (u *DeviceUsage) Validate() error {
  20. if u.ContainerUID == "" {
  21. return errors.New("ContainerUID is required")
  22. }
  23. if u.DeviceUID == "" {
  24. return errors.New("DeviceUID is required")
  25. }
  26. if u.UsagePercentageMax < 0 || u.UsagePercentageMax > 100 {
  27. return fmt.Errorf("UsagePercentageMax must be 0-100, got %.2f", u.UsagePercentageMax)
  28. }
  29. return nil
  30. }
  31. func (u *DeviceUsage) Clone() *DeviceUsage {
  32. if u == nil {
  33. return nil
  34. }
  35. cloned := &DeviceUsage{
  36. ContainerUID: u.ContainerUID,
  37. DeviceUID: u.DeviceUID,
  38. UsageSeconds: u.UsageSeconds,
  39. UsagePercentageMax: u.UsagePercentageMax,
  40. MemoryByteSecondsUsed: u.MemoryByteSecondsUsed,
  41. DeviceType: u.DeviceType,
  42. DurationSeconds: u.DurationSeconds,
  43. Start: u.Start,
  44. End: u.End,
  45. }
  46. return cloned
  47. }
  48. func (u *DeviceUsage) UsageAverage() Measurement {
  49. if u.DurationSeconds == 0 {
  50. return 0
  51. }
  52. return (u.UsageSeconds / u.DurationSeconds) * 100
  53. }
  54. func (u *DeviceUsage) MemoryByteUsageAverage() Measurement {
  55. if u.DurationSeconds == 0 {
  56. return 0
  57. }
  58. return u.MemoryByteSecondsUsed / u.DurationSeconds
  59. }
  60. func (kms *KubeModelSet) RegisterUsage(id, containerID, deviceId string) error {
  61. if id == "" {
  62. err := fmt.Errorf("UID is nil for DeviceUsage")
  63. kms.Error(err)
  64. return err
  65. }
  66. if _, ok := kms.DeviceUsages[id]; !ok {
  67. kms.DeviceUsages[id] = &DeviceUsage{
  68. ContainerUID: containerID,
  69. DeviceUID: deviceId,
  70. }
  71. kms.Metadata.ObjectCount++
  72. }
  73. return nil
  74. }