bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/scollector/collectors/railgun_linux.go (about)

     1  package collectors
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  	"regexp"
     7  	"strings"
     8  	"time"
     9  
    10  	"bosun.org/metadata"
    11  	"bosun.org/opentsdb"
    12  	"bosun.org/util"
    13  )
    14  
    15  func init() {
    16  	collectors = append(collectors, &IntervalCollector{F: c_railgun, Enable: enableRailgun, Interval: time.Minute})
    17  }
    18  
    19  var (
    20  	rgListenRE = regexp.MustCompile(`^stats.listen\s+?=\s+?([0-9.:]+)`)
    21  	rgURL      string
    22  )
    23  
    24  func parseRailURL() string {
    25  	var config string
    26  	var url string
    27  	util.ReadCommand(func(line string) error {
    28  		fields := strings.Fields(line)
    29  		if len(fields) == 0 || !strings.Contains(fields[0], "rg-listener") {
    30  			return nil
    31  		}
    32  		for i, s := range fields {
    33  			if s == "-config" && len(fields) > i {
    34  				config = fields[i+1]
    35  			}
    36  		}
    37  		return nil
    38  	}, "ps", "-e", "-o", "args")
    39  	if config == "" {
    40  		return config
    41  	}
    42  	readLine(config, func(s string) error {
    43  		if m := rgListenRE.FindStringSubmatch(s); len(m) > 0 {
    44  			url = "http://" + m[1]
    45  		}
    46  		return nil
    47  	})
    48  	return url
    49  }
    50  
    51  func enableRailgun() bool {
    52  	rgURL = parseRailURL()
    53  	return enableURL(rgURL)()
    54  }
    55  
    56  func c_railgun() (opentsdb.MultiDataPoint, error) {
    57  	var md opentsdb.MultiDataPoint
    58  	res, err := http.Get(rgURL)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  	defer res.Body.Close()
    63  	var r map[string]interface{}
    64  	j := json.NewDecoder(res.Body)
    65  	if err := j.Decode(&r); err != nil {
    66  		return nil, err
    67  	}
    68  	for k, v := range r {
    69  		if _, ok := v.(float64); ok {
    70  			Add(&md, "railgun."+k, v, nil, metadata.Unknown, metadata.None, "")
    71  		}
    72  	}
    73  	return md, nil
    74  }