github.com/mackerelio/mackerel-agent-plugins@v0.89.3/mackerel-plugin-uptime/lib/uptime.go (about)

     1  package mpuptime
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  
     7  	mp "github.com/mackerelio/go-mackerel-plugin"
     8  	"github.com/mackerelio/go-osstat/uptime"
     9  	"golang.org/x/text/cases"
    10  	"golang.org/x/text/language"
    11  )
    12  
    13  // UptimePlugin mackerel plugin
    14  type UptimePlugin struct {
    15  	Prefix string
    16  }
    17  
    18  // MetricKeyPrefix interface for PluginWithPrefix
    19  func (u UptimePlugin) MetricKeyPrefix() string {
    20  	if u.Prefix == "" {
    21  		u.Prefix = "uptime"
    22  	}
    23  	return u.Prefix
    24  }
    25  
    26  // GraphDefinition interface for mackerelplugin
    27  func (u UptimePlugin) GraphDefinition() map[string]mp.Graphs {
    28  	labelPrefix := cases.Title(language.Und, cases.NoLower).String(u.Prefix)
    29  	return map[string]mp.Graphs{
    30  		"": {
    31  			Label: labelPrefix,
    32  			Unit:  mp.UnitFloat,
    33  			Metrics: []mp.Metrics{
    34  				{Name: "seconds", Label: "Seconds"},
    35  			},
    36  		},
    37  	}
    38  }
    39  
    40  // FetchMetrics interface for mackerelplugin
    41  func (u UptimePlugin) FetchMetrics() (map[string]float64, error) {
    42  	ut, err := uptime.Get()
    43  	if err != nil {
    44  		return nil, fmt.Errorf("Failed to fetch uptime metrics: %s", err) // nolint
    45  	}
    46  	return map[string]float64{"seconds": ut.Seconds()}, nil
    47  }
    48  
    49  // Do the plugin
    50  func Do() {
    51  	optPrefix := flag.String("metric-key-prefix", "uptime", "Metric key prefix")
    52  	optTempfile := flag.String("tempfile", "", "Temp file name")
    53  	flag.Parse()
    54  
    55  	u := UptimePlugin{
    56  		Prefix: *optPrefix,
    57  	}
    58  	helper := mp.NewMackerelPlugin(u)
    59  	helper.Tempfile = *optTempfile
    60  	helper.Run()
    61  }