github.com/cloudfoundry-attic/garden-linux@v0.333.2-candidate/metrics/periodic_metron_notifier.go (about)

     1  package metrics
     2  
     3  import (
     4  	"time"
     5  
     6  	dropsonde_metrics "github.com/cloudfoundry/dropsonde/metrics"
     7  	"github.com/pivotal-golang/clock"
     8  	"github.com/pivotal-golang/lager"
     9  )
    10  
    11  type Metric string
    12  
    13  func (name Metric) Send(value int) {
    14  	dropsonde_metrics.SendValue(string(name), float64(value), "Metric")
    15  }
    16  
    17  type Duration string
    18  
    19  func (name Duration) Send(duration time.Duration) {
    20  	dropsonde_metrics.SendValue(string(name), float64(duration), "nanos")
    21  }
    22  
    23  const (
    24  	loopDevices   = Metric("LoopDevices")
    25  	backingStores = Metric("BackingStores")
    26  	depotDirs     = Metric("DepotDirs")
    27  
    28  	metricsReportingDuration = Duration("MetricsReporting")
    29  )
    30  
    31  type PeriodicMetronNotifier struct {
    32  	Interval time.Duration
    33  	Logger   lager.Logger
    34  	Clock    clock.Clock
    35  
    36  	metrics Metrics
    37  	stopped chan struct{}
    38  }
    39  
    40  func NewPeriodicMetronNotifier(
    41  	logger lager.Logger,
    42  	metrics Metrics,
    43  	interval time.Duration,
    44  	clock clock.Clock,
    45  ) *PeriodicMetronNotifier {
    46  	return &PeriodicMetronNotifier{
    47  		Interval: interval,
    48  		Logger:   logger,
    49  		Clock:    clock,
    50  		metrics:  metrics,
    51  
    52  		stopped: make(chan struct{}),
    53  	}
    54  }
    55  
    56  func (notifier PeriodicMetronNotifier) Start() {
    57  	logger := notifier.Logger.Session("metrics-notifier", lager.Data{"interval": notifier.Interval.String()})
    58  	logger.Info("starting")
    59  	ticker := notifier.Clock.NewTicker(notifier.Interval)
    60  
    61  	go func() {
    62  		defer ticker.Stop()
    63  
    64  		logger.Info("started", lager.Data{"time": notifier.Clock.Now()})
    65  		defer logger.Info("finished")
    66  
    67  		for {
    68  			select {
    69  			case <-ticker.C():
    70  				startedAt := notifier.Clock.Now()
    71  
    72  				loopDevices.Send(notifier.metrics.LoopDevices())
    73  				backingStores.Send(notifier.metrics.BackingStores())
    74  				depotDirs.Send(notifier.metrics.DepotDirs())
    75  
    76  				finishedAt := notifier.Clock.Now()
    77  				metricsReportingDuration.Send(finishedAt.Sub(startedAt))
    78  			case <-notifier.stopped:
    79  				return
    80  			}
    81  		}
    82  	}()
    83  }
    84  
    85  func (notifier PeriodicMetronNotifier) Stop() {
    86  	close(notifier.stopped)
    87  }