github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/metric/emitter/dogstatsd.go (about)

     1  package emitter
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"regexp"
     7  	"strings"
     8  
     9  	"code.cloudfoundry.org/lager"
    10  	"github.com/DataDog/datadog-go/statsd"
    11  	"github.com/pf-qiu/concourse/v6/atc/metric"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  type DogstatsdEmitter struct {
    16  	client *statsd.Client
    17  }
    18  
    19  type DogstatsDBConfig struct {
    20  	Host   string `long:"datadog-agent-host" description:"Datadog agent host to expose dogstatsd metrics"`
    21  	Port   string `long:"datadog-agent-port" description:"Datadog agent port to expose dogstatsd metrics"`
    22  	Prefix string `long:"datadog-prefix" description:"Prefix for all metrics to easily find them in Datadog"`
    23  }
    24  
    25  func init() {
    26  	metric.Metrics.RegisterEmitter(&DogstatsDBConfig{})
    27  }
    28  
    29  func (config *DogstatsDBConfig) Description() string { return "Datadog" }
    30  
    31  func (config *DogstatsDBConfig) IsConfigured() bool { return config.Host != "" && config.Port != "" }
    32  
    33  func (config *DogstatsDBConfig) NewEmitter() (metric.Emitter, error) {
    34  
    35  	client, err := statsd.New(fmt.Sprintf("%s:%s", config.Host, config.Port))
    36  	if err != nil {
    37  		log.Fatal(err)
    38  		return &DogstatsdEmitter{}, err
    39  	}
    40  
    41  	if config.Prefix != "" {
    42  		if strings.HasSuffix(config.Prefix, ".") {
    43  			client.Namespace = config.Prefix
    44  		} else {
    45  			client.Namespace = fmt.Sprintf("%s.", config.Prefix)
    46  		}
    47  	}
    48  
    49  	return &DogstatsdEmitter{
    50  		client: client,
    51  	}, nil
    52  }
    53  
    54  var specialChars = regexp.MustCompile("[^a-zA-Z0-9_]+")
    55  
    56  func (emitter *DogstatsdEmitter) Emit(logger lager.Logger, event metric.Event) {
    57  	name := specialChars.ReplaceAllString(strings.Replace(strings.ToLower(event.Name), " ", "_", -1), "")
    58  
    59  	tags := []string{
    60  		fmt.Sprintf("host:%s", event.Host),
    61  	}
    62  
    63  	for k, v := range event.Attributes {
    64  		tags = append(tags, fmt.Sprintf("%s:%s", k, v))
    65  	}
    66  
    67  	err := emitter.client.Gauge(name, event.Value, tags, 1)
    68  	if err != nil {
    69  		logger.Error("failed-to-send-metric",
    70  			errors.Wrap(metric.ErrFailedToEmit, err.Error()))
    71  		return
    72  	}
    73  }