master
go 69 lines 1.78 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package chartemit
4
5 import (
6 "fmt"
7 "maps"
8 "sort"
9 "strings"
10
11 "github.com/netdata/netdata/go/plugins/pkg/netdataapi"
12 )
13
14 // PrepareHostInfo normalizes host-definition payloads before HOST_DEFINE.
15 //
16 // Current semantics intentionally match v1 vnode emission:
17 // - GUID/hostname must be present and wire-safe,
18 // - "_hostname" is injected when absent,
19 // - label keys and values are normalized for Netdata wire output.
20 func PrepareHostInfo(info netdataapi.HostInfo) (netdataapi.HostInfo, error) {
21 guid := strings.TrimSpace(info.GUID)
22 if guid == "" {
23 return netdataapi.HostInfo{}, fmt.Errorf("chartemit: host guid is required")
24 }
25 if sanitizeWireID(guid) != guid {
26 return netdataapi.HostInfo{}, fmt.Errorf("chartemit: host guid contains unsupported characters")
27 }
28 hostname := strings.TrimSpace(info.Hostname)
29 if hostname == "" {
30 return netdataapi.HostInfo{}, fmt.Errorf("chartemit: host hostname is required")
31 }
32 if sanitizeWireValue(hostname) != hostname {
33 return netdataapi.HostInfo{}, fmt.Errorf("chartemit: host hostname contains unsupported characters")
34 }
35
36 labels := normalizeHostInfoLabels(info.Labels)
37 if _, ok := labels["_hostname"]; !ok {
38 labels["_hostname"] = hostname
39 }
40
41 return netdataapi.HostInfo{
42 GUID: guid,
43 Hostname: hostname,
44 Labels: labels,
45 }, nil
46 }
47
48 func normalizeHostInfoLabels(in map[string]string) map[string]string {
49 labels := maps.Clone(in)
50 if len(labels) == 0 {
51 return make(map[string]string)
52 }
53
54 keys := make([]string, 0, len(labels))
55 for key := range labels {
56 keys = append(keys, key)
57 }
58 sort.Strings(keys)
59
60 out := make(map[string]string, len(labels))
61 for _, key := range keys {
62 sKey := sanitizeWireID(key)
63 if sKey == "" {
64 continue
65 }
66 out[sKey] = sanitizeWireValue(labels[key])
67 }
68 return out
69 }