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

     1  package mpprocfd
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"os"
     7  	"regexp"
     8  
     9  	mp "github.com/mackerelio/go-mackerel-plugin-helper"
    10  	"github.com/mackerelio/golib/logging"
    11  )
    12  
    13  var logger = logging.GetLogger("metrics.plugin.proc-fd")
    14  
    15  // ProcfdPlugin for fetching metrics
    16  type ProcfdPlugin struct {
    17  	Process           string
    18  	NormalizedProcess string
    19  	MetricName        string
    20  }
    21  
    22  // FetchMetrics fetch the metrics
    23  func (p ProcfdPlugin) FetchMetrics() (map[string]interface{}, error) {
    24  	fds, err := openFd.getNumOpenFileDesc()
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	stat := make(map[string]interface{})
    30  
    31  	// Compute maximum open file descriptor
    32  	var maxFD uint64
    33  	for _, fd := range fds {
    34  		if fd > maxFD {
    35  			maxFD = fd
    36  		}
    37  	}
    38  	stat["max_fd"] = maxFD
    39  
    40  	return stat, nil
    41  }
    42  
    43  // GraphDefinition Graph definition
    44  func (p ProcfdPlugin) GraphDefinition() map[string]mp.Graphs {
    45  	return map[string]mp.Graphs{
    46  		fmt.Sprintf("proc-fd.%s", p.NormalizedProcess): {
    47  			Label: fmt.Sprintf("Opening fd by %s", p.NormalizedProcess),
    48  			Unit:  "integer",
    49  			Metrics: []mp.Metrics{
    50  				{Name: "max_fd", Label: "Maximum opening fd", Diff: false, Type: "uint64"},
    51  			},
    52  		},
    53  	}
    54  }
    55  
    56  func normalizeForMetricName(process string) string {
    57  	// Mackerel accepts following characters in custom metric names
    58  	// [-a-zA-Z0-9_.]
    59  	re := regexp.MustCompile("[^-a-zA-Z0-9_.]")
    60  	return re.ReplaceAllString(process, "_")
    61  }
    62  
    63  // Do the plugin
    64  func Do() {
    65  	optProcess := flag.String("process", "", "Process name")
    66  	optTempfile := flag.String("tempfile", "", "Temp file name")
    67  	flag.Parse()
    68  
    69  	if *optProcess == "" {
    70  		logger.Warningf("Process name is required")
    71  		flag.PrintDefaults()
    72  		os.Exit(1)
    73  	}
    74  
    75  	var fd ProcfdPlugin
    76  	fd.Process = *optProcess
    77  	openFd = RealOpenFd{fd.Process}
    78  	fd.NormalizedProcess = normalizeForMetricName(*optProcess)
    79  
    80  	helper := mp.NewMackerelPlugin(fd)
    81  	helper.Tempfile = *optTempfile
    82  
    83  	helper.Run()
    84  }