github.com/netdata/go.d.plugin@v0.58.1/modules/dnsdist/collect.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package dnsdist
     4  
     5  import (
     6  	"encoding/json"
     7  	"fmt"
     8  	"io"
     9  	"net/http"
    10  	"net/url"
    11  
    12  	"github.com/netdata/go.d.plugin/pkg/stm"
    13  	"github.com/netdata/go.d.plugin/pkg/web"
    14  )
    15  
    16  const (
    17  	urlPathJSONStat = "/jsonstat"
    18  )
    19  
    20  func (d *DNSdist) collect() (map[string]int64, error) {
    21  	statistics, err := d.scrapeStatistics()
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  
    26  	collected := make(map[string]int64)
    27  	d.collectStatistic(collected, statistics)
    28  
    29  	return collected, nil
    30  }
    31  
    32  func (d *DNSdist) collectStatistic(collected map[string]int64, statistics *statisticMetrics) {
    33  	for metric, value := range stm.ToMap(statistics) {
    34  		collected[metric] = value
    35  	}
    36  }
    37  
    38  func (d *DNSdist) scrapeStatistics() (*statisticMetrics, error) {
    39  	req, _ := web.NewHTTPRequest(d.Request)
    40  	req.URL.Path = urlPathJSONStat
    41  	req.URL.RawQuery = url.Values{"command": []string{"stats"}}.Encode()
    42  
    43  	var statistics statisticMetrics
    44  	if err := d.doOKDecode(req, &statistics); err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	return &statistics, nil
    49  }
    50  
    51  func (d *DNSdist) doOKDecode(req *http.Request, in interface{}) error {
    52  	resp, err := d.httpClient.Do(req)
    53  	if err != nil {
    54  		return fmt.Errorf("error on HTTP request '%s': %v", req.URL, err)
    55  	}
    56  	defer closeBody(resp)
    57  
    58  	if resp.StatusCode != http.StatusOK {
    59  		return fmt.Errorf("'%s' returned HTTP status code: %d", req.URL, resp.StatusCode)
    60  	}
    61  
    62  	if err := json.NewDecoder(resp.Body).Decode(in); err != nil {
    63  		return fmt.Errorf("error on decoding response from '%s': %v", req.URL, err)
    64  	}
    65  
    66  	return nil
    67  }
    68  
    69  func closeBody(resp *http.Response) {
    70  	if resp != nil && resp.Body != nil {
    71  		_, _ = io.Copy(io.Discard, resp.Body)
    72  		_ = resp.Body.Close()
    73  	}
    74  }