device_usage.go 2.1 KB

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