github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/apiserver/metricsender/metricsender.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 // Package metricsender contains functions for sending 5 // metrics from a state server to a remote metric collector. 6 package metricsender 7 8 import ( 9 "github.com/juju/errors" 10 "github.com/juju/loggo" 11 12 "github.com/juju/juju/apiserver/metricsender/wireformat" 13 "github.com/juju/juju/state" 14 ) 15 16 var sendLogger = loggo.GetLogger("juju.apiserver.metricsender") 17 18 // MetricSender defines the interface used to send metrics 19 // to a collection service. 20 type MetricSender interface { 21 Send([]*wireformat.MetricBatch) (*wireformat.Response, error) 22 } 23 24 // SendMetrics will send any unsent metrics 25 // over the MetricSender interface in batches 26 // no larger than batchSize. 27 func SendMetrics(st *state.State, sender MetricSender, batchSize int) error { 28 for { 29 metrics, err := st.MetricsToSend(batchSize) 30 if err != nil { 31 return errors.Trace(err) 32 } 33 if len(metrics) == 0 { 34 sendLogger.Infof("nothing to send") 35 break 36 } 37 wireData := make([]*wireformat.MetricBatch, len(metrics)) 38 for i, m := range metrics { 39 wireData[i] = wireformat.ToWire(m) 40 } 41 response, err := sender.Send(wireData) 42 if err != nil { 43 sendLogger.Errorf("%+v", err) 44 return errors.Trace(err) 45 } 46 if response != nil { 47 for _, envResp := range response.EnvResponses { 48 err = st.SetMetricBatchesSent(envResp.AcknowledgedBatches) 49 if err != nil { 50 sendLogger.Errorf("failed to set sent on metrics %v", err) 51 } 52 for unitName, status := range envResp.UnitStatuses { 53 unit, err := st.Unit(unitName) 54 if err != nil { 55 sendLogger.Errorf("failed to retrieve unit %q: %v", unitName, err) 56 } else { 57 err = unit.SetMeterStatus(status.Status, status.Info) 58 if err != nil { 59 sendLogger.Errorf("failed to set unit %q meter status to %v: %v", unitName, status, err) 60 } 61 } 62 } 63 } 64 } 65 } 66 67 unsent, err := st.CountofUnsentMetrics() 68 if err != nil { 69 return errors.Trace(err) 70 } 71 sent, err := st.CountofSentMetrics() 72 if err != nil { 73 return errors.Trace(err) 74 } 75 sendLogger.Infof("metrics collection summary: sent:%d unsent:%d", sent, unsent) 76 77 return nil 78 }