github.com/netdata/go.d.plugin@v0.58.1/modules/consul/collect.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package consul 4 5 import ( 6 "encoding/json" 7 "fmt" 8 "io" 9 "net/http" 10 11 "github.com/netdata/go.d.plugin/pkg/web" 12 ) 13 14 const ( 15 precision = 1000 16 ) 17 18 func (c *Consul) collect() (map[string]int64, error) { 19 if c.cfg == nil { 20 if err := c.collectConfiguration(); err != nil { 21 return nil, err 22 } 23 24 c.addGlobalChartsOnce.Do(c.addGlobalCharts) 25 } 26 27 mx := make(map[string]int64) 28 29 if err := c.collectChecks(mx); err != nil { 30 return nil, err 31 } 32 33 if c.isServer() { 34 if !c.isCloudManaged() { 35 c.addServerAutopilotChartsOnce.Do(c.addServerAutopilotHealthCharts) 36 // 'operator/autopilot/health' is disabled in Cloud managed (403: Operation is not allowed in managed Consul clusters) 37 if err := c.collectAutopilotHealth(mx); err != nil { 38 return nil, err 39 } 40 } 41 if err := c.collectNetworkRTT(mx); err != nil { 42 return nil, err 43 } 44 } 45 46 if c.isTelemetryPrometheusEnabled() { 47 if err := c.collectMetricsPrometheus(mx); err != nil { 48 return nil, err 49 } 50 } 51 52 return mx, nil 53 } 54 55 func (c *Consul) isTelemetryPrometheusEnabled() bool { 56 return c.cfg.DebugConfig.Telemetry.PrometheusOpts.Expiration != "0s" 57 } 58 59 func (c *Consul) isCloudManaged() bool { 60 return c.cfg.DebugConfig.Cloud.ClientSecret != "" || c.cfg.DebugConfig.Cloud.ResourceID != "" 61 } 62 63 func (c *Consul) hasLicense() bool { 64 return c.cfg.Stats.License.ID != "" 65 } 66 67 func (c *Consul) isServer() bool { 68 return c.cfg.Config.Server 69 } 70 71 func (c *Consul) doOKDecode(urlPath string, in interface{}, statusCodes ...int) error { 72 req, err := web.NewHTTPRequest(c.Request.Copy()) 73 if err != nil { 74 return fmt.Errorf("error on creating request: %v", err) 75 } 76 77 req.URL.Path = urlPath 78 if c.ACLToken != "" { 79 req.Header.Set("X-Consul-Token", c.ACLToken) 80 } 81 82 resp, err := c.httpClient.Do(req) 83 if err != nil { 84 return fmt.Errorf("error on request to %s : %v", req.URL, err) 85 } 86 87 defer closeBody(resp) 88 89 codes := map[int]bool{http.StatusOK: true} 90 for _, v := range statusCodes { 91 codes[v] = true 92 } 93 94 if !codes[resp.StatusCode] { 95 return fmt.Errorf("%s returned HTTP status %d", req.URL, resp.StatusCode) 96 } 97 98 if err = json.NewDecoder(resp.Body).Decode(&in); err != nil { 99 return fmt.Errorf("error on decoding response from %s : %v", req.URL, err) 100 } 101 102 return nil 103 } 104 105 func closeBody(resp *http.Response) { 106 if resp != nil && resp.Body != nil { 107 _, _ = io.Copy(io.Discard, resp.Body) 108 _ = resp.Body.Close() 109 } 110 } 111 112 func boolToInt(v bool) int64 { 113 if v { 114 return 1 115 } 116 return 0 117 }