| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package jobmgr |
| 4 | |
| 5 | import ( |
| 6 | "encoding/json" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/netdata/netdata/go/plugins/plugin/framework/confgroup" |
| 11 | "github.com/netdata/netdata/go/plugins/plugin/framework/dyncfg" |
| 12 | "gopkg.in/yaml.v2" |
| 13 | ) |
| 14 | |
| 15 | func (m *Manager) dyncfgSetConfigMeta(cfg confgroup.Config, module, name string, fn dyncfg.Function) { |
| 16 | cfg.SetProvider("dyncfg") |
| 17 | cfg.SetSource(fn.Source()) |
| 18 | cfg.SetSourceType("dyncfg") |
| 19 | cfg.SetModule(module) |
| 20 | cfg.SetName(name) |
| 21 | if def, ok := m.configDefaults.Lookup(module); ok { |
| 22 | cfg.ApplyDefaults(def) |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | func userConfigFromPayload(cfg any, jobName string, fn dyncfg.Function) ([]byte, error) { |
| 27 | if err := fn.UnmarshalPayload(cfg); err != nil { |
| 28 | return nil, err |
| 29 | } |
| 30 | |
| 31 | bs, err := yaml.Marshal(cfg) |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | |
| 36 | var yms yaml.MapSlice |
| 37 | if err := yaml.Unmarshal(bs, &yms); err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | |
| 41 | yms = slices.DeleteFunc(yms, func(item yaml.MapItem) bool { return item.Key == "name" }) |
| 42 | |
| 43 | yms = append([]yaml.MapItem{{Key: "name", Value: jobName}}, yms...) |
| 44 | |
| 45 | v := map[string]any{ |
| 46 | "jobs": []any{yms}, |
| 47 | } |
| 48 | |
| 49 | return yaml.Marshal(v) |
| 50 | } |
| 51 | |
| 52 | func configFromPayload(fn dyncfg.Function) (confgroup.Config, error) { |
| 53 | var cfg confgroup.Config |
| 54 | |
| 55 | if fn.IsContentTypeJSON() { |
| 56 | if err := json.Unmarshal(fn.Payload(), &cfg); err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | |
| 60 | return cfg.Clone() |
| 61 | } |
| 62 | |
| 63 | if err := yaml.Unmarshal(fn.Payload(), &cfg); err != nil { |
| 64 | return nil, err |
| 65 | } |
| 66 | |
| 67 | return cfg, nil |
| 68 | } |
| 69 | |
| 70 | func (m *Manager) extractModuleJobName(id string) (mn string, jn string, ok bool) { |
| 71 | if mn, ok = m.extractModuleName(id); !ok { |
| 72 | return "", "", false |
| 73 | } |
| 74 | if jn, ok = extractJobName(id); !ok { |
| 75 | return "", "", false |
| 76 | } |
| 77 | return mn, jn, true |
| 78 | } |
| 79 | |
| 80 | func (m *Manager) extractModuleName(id string) (string, bool) { |
| 81 | id = strings.TrimPrefix(id, m.dyncfgCollectorPrefixValue()) |
| 82 | before, _, ok := strings.Cut(id, ":") |
| 83 | if !ok { |
| 84 | return id, id != "" |
| 85 | } |
| 86 | return before, true |
| 87 | } |
| 88 | |
| 89 | func extractJobName(id string) (string, bool) { |
| 90 | i := strings.LastIndexByte(id, ':') |
| 91 | if i == -1 { |
| 92 | return "", false |
| 93 | } |
| 94 | return id[i+1:], true |
| 95 | } |