github.com/netdata/go.d.plugin@v0.58.1/modules/consul/consul.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package consul 4 5 import ( 6 _ "embed" 7 "net/http" 8 "sync" 9 "time" 10 11 "github.com/blang/semver/v4" 12 13 "github.com/netdata/go.d.plugin/agent/module" 14 "github.com/netdata/go.d.plugin/pkg/prometheus" 15 "github.com/netdata/go.d.plugin/pkg/web" 16 ) 17 18 //go:embed "config_schema.json" 19 var configSchema string 20 21 func init() { 22 module.Register("consul", module.Creator{ 23 JobConfigSchema: configSchema, 24 Defaults: module.Defaults{ 25 UpdateEvery: 1, 26 }, 27 Create: func() module.Module { return New() }, 28 }) 29 } 30 31 func New() *Consul { 32 return &Consul{ 33 Config: Config{ 34 HTTP: web.HTTP{ 35 Request: web.Request{URL: "http://127.0.0.1:8500"}, 36 Client: web.Client{Timeout: web.Duration{Duration: time.Second * 2}}, 37 }, 38 }, 39 charts: &module.Charts{}, 40 addGlobalChartsOnce: &sync.Once{}, 41 addServerAutopilotChartsOnce: &sync.Once{}, 42 checks: make(map[string]bool), 43 } 44 } 45 46 type Config struct { 47 web.HTTP `yaml:",inline"` 48 49 ACLToken string `yaml:"acl_token"` 50 } 51 52 type Consul struct { 53 module.Base 54 55 Config `yaml:",inline"` 56 57 charts *module.Charts 58 addGlobalChartsOnce *sync.Once 59 addServerAutopilotChartsOnce *sync.Once 60 61 httpClient *http.Client 62 prom prometheus.Prometheus 63 64 cfg *consulConfig 65 version *semver.Version 66 67 hasLeaderCharts bool 68 hasFollowerCharts bool 69 checks map[string]bool 70 } 71 72 func (c *Consul) Init() bool { 73 if err := c.validateConfig(); err != nil { 74 c.Errorf("config validation: %v", err) 75 return false 76 } 77 78 httpClient, err := c.initHTTPClient() 79 if err != nil { 80 c.Errorf("init HTTP client: %v", err) 81 return false 82 } 83 c.httpClient = httpClient 84 85 prom, err := c.initPrometheusClient(httpClient) 86 if err != nil { 87 c.Errorf("init Prometheus client: %v", err) 88 return false 89 } 90 c.prom = prom 91 92 return true 93 } 94 95 func (c *Consul) Check() bool { 96 return len(c.Collect()) > 0 97 } 98 99 func (c *Consul) Charts() *module.Charts { 100 return c.charts 101 } 102 103 func (c *Consul) Collect() map[string]int64 { 104 mx, err := c.collect() 105 if err != nil { 106 c.Error(err) 107 } 108 109 if len(mx) == 0 { 110 return nil 111 } 112 return mx 113 } 114 115 func (c *Consul) Cleanup() { 116 if c.httpClient != nil { 117 c.httpClient.CloseIdleConnections() 118 } 119 }