github.com/netdata/go.d.plugin@v0.58.1/modules/logstash/collect.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package logstash 4 5 import ( 6 "encoding/json" 7 "fmt" 8 "io" 9 "net/http" 10 11 "github.com/netdata/go.d.plugin/pkg/stm" 12 "github.com/netdata/go.d.plugin/pkg/web" 13 ) 14 15 const urlPathNodeStatsAPI = "/_node/stats" 16 17 func (l *Logstash) collect() (map[string]int64, error) { 18 stats, err := l.queryNodeStats() 19 if err != nil { 20 return nil, err 21 } 22 23 l.updateCharts(stats.Pipelines) 24 25 return stm.ToMap(stats), nil 26 } 27 28 func (l *Logstash) updateCharts(pipelines map[string]pipelineStats) { 29 seen := make(map[string]bool) 30 31 for id := range pipelines { 32 seen[id] = true 33 if !l.pipelines[id] { 34 l.pipelines[id] = true 35 l.addPipelineCharts(id) 36 } 37 } 38 39 for id := range l.pipelines { 40 if !seen[id] { 41 delete(l.pipelines, id) 42 l.removePipelineCharts(id) 43 } 44 } 45 } 46 47 func (l *Logstash) queryNodeStats() (*nodeStats, error) { 48 req, _ := web.NewHTTPRequest(l.Request.Copy()) 49 req.URL.Path = urlPathNodeStatsAPI 50 51 var stats nodeStats 52 53 if err := l.doWithDecode(&stats, req); err != nil { 54 return nil, err 55 } 56 57 return &stats, nil 58 } 59 60 func (l *Logstash) doWithDecode(dst interface{}, req *http.Request) error { 61 l.Debugf("executing %s '%s'", req.Method, req.URL) 62 resp, err := l.httpClient.Do(req) 63 if err != nil { 64 return err 65 } 66 defer closeBody(resp) 67 68 if resp.StatusCode != http.StatusOK { 69 return fmt.Errorf("%s returned %d status code (%s)", req.URL, resp.StatusCode, resp.Status) 70 } 71 72 content, err := io.ReadAll(resp.Body) 73 if err != nil { 74 return fmt.Errorf("error on reading response from %s : %v", req.URL, err) 75 } 76 77 if err := json.Unmarshal(content, dst); err != nil { 78 return fmt.Errorf("error on parsing response from %s : %v", req.URL, err) 79 } 80 81 return nil 82 } 83 84 func closeBody(resp *http.Response) { 85 if resp != nil && resp.Body != nil { 86 _, _ = io.Copy(io.Discard, resp.Body) 87 _ = resp.Body.Close() 88 } 89 }