|
| 1 | +package seer |
| 2 | + |
| 3 | +import "strings" |
| 4 | + |
| 5 | +func (u *UsageData) ToMap() map[string]any { |
| 6 | + result := map[string]any{ |
| 7 | + "memory": map[string]any{ |
| 8 | + "used": u.Memory.Used, |
| 9 | + "total": u.Memory.Total, |
| 10 | + "free": u.Memory.Free, |
| 11 | + }, |
| 12 | + "cpu": map[string]any{ |
| 13 | + "total": u.Cpu.Total, |
| 14 | + "count": u.Cpu.Count, |
| 15 | + "user": u.Cpu.User, |
| 16 | + "nice": u.Cpu.Nice, |
| 17 | + "system": u.Cpu.System, |
| 18 | + "idle": u.Cpu.Idle, |
| 19 | + "iowait": u.Cpu.Iowait, |
| 20 | + "irq": u.Cpu.Irq, |
| 21 | + "softirq": u.Cpu.Softirq, |
| 22 | + "steal": u.Cpu.Steal, |
| 23 | + "guest": u.Cpu.Guest, |
| 24 | + "guestNice": u.Cpu.GuestNice, |
| 25 | + "statCount": u.Cpu.StatCount, |
| 26 | + }, |
| 27 | + "disk": map[string]any{ |
| 28 | + "total": u.Disk.Total, |
| 29 | + "free": u.Disk.Free, |
| 30 | + "used": u.Disk.Used, |
| 31 | + "available": u.Disk.Available, |
| 32 | + }, |
| 33 | + } |
| 34 | + |
| 35 | + custom := convertCustomValuesToNestedMap(u.CustomValues) |
| 36 | + if custom != nil { |
| 37 | + result["custom"] = custom |
| 38 | + } |
| 39 | + |
| 40 | + return result |
| 41 | +} |
| 42 | + |
| 43 | +/* |
| 44 | +convertCustomValuesToNestedMap converts a flat map with dot-separated keys |
| 45 | +into a nested map structure where '.' is treated as a hierarchical separator. |
| 46 | +For example: {"sensor.network.bytes": 123.45} becomes |
| 47 | +{"sensor": {"network": {"bytes": 123.45}}} |
| 48 | +*/ |
| 49 | +func convertCustomValuesToNestedMap(customValues map[string]float64) map[string]any { |
| 50 | + if len(customValues) == 0 { |
| 51 | + return nil |
| 52 | + } |
| 53 | + |
| 54 | + result := make(map[string]any) |
| 55 | + for key, value := range customValues { |
| 56 | + parts := strings.Split(key, ".") |
| 57 | + cur := result |
| 58 | + for i, part := range parts { |
| 59 | + if i == len(parts)-1 { |
| 60 | + cur[part] = value |
| 61 | + } else { |
| 62 | + if next, ok := cur[part]; ok { |
| 63 | + if nextMap, ok := next.(map[string]any); ok { |
| 64 | + cur = nextMap |
| 65 | + } else { |
| 66 | + newMap := make(map[string]any) |
| 67 | + cur[part] = newMap |
| 68 | + cur = newMap |
| 69 | + } |
| 70 | + } else { |
| 71 | + newMap := make(map[string]any) |
| 72 | + cur[part] = newMap |
| 73 | + cur = newMap |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return result |
| 80 | +} |
0 commit comments