master
go 87 lines 2.25 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package jobruntime
4
5 import (
6 "fmt"
7 "strings"
8
9 "github.com/netdata/netdata/go/plugins/plugin/framework/runtimecomp"
10 )
11
12 func (j *JobV2) registerRuntimeComponent() error {
13 if j == nil || j.runtimeService == nil || j.runtimeComponentRegistered {
14 return nil
15 }
16 store := j.runtimeStore
17 if store == nil {
18 return fmt.Errorf("nil runtime store")
19 }
20
21 componentName := j.runtimeComponentName
22 if componentName == "" {
23 componentName = j.buildRuntimeComponentName()
24 }
25
26 updateEvery := j.updateEvery
27 if updateEvery <= 0 {
28 updateEvery = 1
29 }
30
31 cfg := runtimecomp.ComponentConfig{
32 Name: componentName,
33 Store: store,
34 UpdateEvery: updateEvery,
35 Autogen: runtimecomp.AutogenPolicy{
36 Enabled: true,
37 },
38 Plugin: j.pluginName,
39 Module: "chartengine",
40 JobName: firstNonEmpty(strings.TrimSpace(j.name), strings.TrimSpace(j.fullName)),
41 JobLabels: j.runtimeComponentLabels(),
42 }
43 if err := j.runtimeService.RegisterComponent(cfg); err != nil {
44 return err
45 }
46 j.runtimeComponentName = componentName
47 j.runtimeComponentRegistered = true
48 return nil
49 }
50
51 func (j *JobV2) unregisterRuntimeComponent() {
52 if j == nil || j.runtimeService == nil || !j.runtimeComponentRegistered {
53 return
54 }
55 j.runtimeService.UnregisterComponent(j.runtimeComponentName)
56 j.runtimeComponentRegistered = false
57 }
58
59 func (j *JobV2) runtimeComponentLabels() map[string]string {
60 labels := map[string]string{
61 "_collect_module": j.moduleName,
62 }
63 if v, ok := j.labels["instance"]; ok && strings.TrimSpace(v) != "" {
64 labels["collector_instance"] = v
65 }
66 return labels
67 }
68
69 func (j *JobV2) buildRuntimeComponentName() string {
70 plugin := sanitizeRuntimeComponentPart(firstNonEmpty(j.pluginName, "go.d"))
71 fullName := sanitizeRuntimeComponentPart(firstNonEmpty(j.fullName, j.name, "job"))
72 return fmt.Sprintf("chartengine.%s.%s", plugin, fullName)
73 }
74
75 func sanitizeRuntimeComponentPart(name string) string {
76 replacer := strings.NewReplacer("/", "_", "\\", "_", " ", "_", ":", "_", "*", "_", "?", "_", "\"", "_", "<", "_", ">", "_", "|", "_")
77 return strings.TrimSpace(replacer.Replace(name))
78 }
79
80 func firstNonEmpty(items ...string) string {
81 for _, item := range items {
82 if item = strings.TrimSpace(item); item != "" {
83 return item
84 }
85 }
86 return ""
87 }