Send given metrics to the Graphite server.
556424
@Override
    public void write(Iterable<QueryResult> results) {
        logger.debug("Export to '{}' results {}", graphiteServerHostAndPort, results);
        SocketWriter socketWriter = null;
        try {
            socketWriter = socketWriterPool.borrowObject(graphiteServerHostAndPort);
            for (QueryResult result : results) {
                String msg = metricPathPrefix + result.getName() + " " + result.getValue() + " " + result.getEpoch(TimeUnit.SECONDS) + "\n";
                logger.debug("Export '{}'", msg);
                socketWriter.write(msg);
            }
            socketWriter.flush();
            socketWriterPool.returnObject(graphiteServerHostAndPort, socketWriter);
        } catch (Exception e) {
            logger.warn("Failure to send result to graphite server '{}' with {}", graphiteServerHostAndPort, socketWriter, e);
            if (socketWriter != null) {
                try {
                    socketWriterPool.invalidateObject(graphiteServerHostAndPort, socketWriter);
                } catch (Exception e2) {
                    logger.warn("Exception invalidating socketWriter connected to graphite server '{}': {}", graphiteServerHostAndPort, socketWriter, e2);
                }
            }
        }
    }
864961
def process(self, metric):
        
        path = metric.getCollectorPath()
        path += '.'
        path += metric.getMetricPath()
        if self.config['apply_metric_prefix']:
            path = metric.getPathPrefix() + '.' + path

        if self.include_reg.match(path):
            if metric.metric_type == 'GAUGE':
                m_type = 'gauge'
            else:
                m_type = 'counter'
            self.queue.add(path,                # name
                           float(metric.value),  # value
                           type=m_type,
                           source=metric.host,
                           measure_time=metric.timestamp)
            self.current_n_measurements += 1
        else:
            self.log.debug("LibratoHandler: Skip %s, no include_filters match",
                           path)

        if (self.current_n_measurements >= self.queue_max_size or
                time.time() >= self.queue_max_timestamp):
            self.log.debug("LibratoHandler: Sending batch size: %d",
                           self.current_n_measurements)
            self._send()
906196
def write(self, *messages):
        """"""

        for i in self.graph.outputs_of(BEGIN):
            for message in messages:
                self[i].write(message)
708773
def send_metrics_to_cloudwatch(self, rule, metric, dimensions):
        

        timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp)

        self.log.debug(
            "CloudWatch: Attempting to publish metric: %s to %s "
            "with value (%s) for dimensions %s @%s",
            rule['name'],
            rule['namespace'],
            str(metric.value),
            str(dimensions),
            str(metric.timestamp)
        )

        try:
            self.connection.put_metric_data(
                str(rule['namespace']),
                str(rule['name']),
                str(metric.value),
                timestamp, str(rule['unit']),
                dimensions)
            self.log.debug(
                "CloudWatch: Successfully published metric: %s to"
                " %s with value (%s) for dimensions %s",
                rule['name'],
                rule['namespace'],
                str(metric.value),
                str(dimensions))
        except AttributeError as e:
            self.log.error(
                "CloudWatch: Failed publishing - %s ", str(e))
        except Exception as e:  # Rough connection re-try logic.
            self.log.error(
                "CloudWatch: Failed publishing - %s\n%s ",
                str(e),
                str(sys.exc_info()[0]))
            self._bind()
659878
def send_dict(*args, **kwargs):
    
    if not _module_instance:
        raise GraphiteSendException(
            "Must call graphitesend.init() before sending")
    _module_instance.send_dict(*args, **kwargs)
    return _module_instance
386837
async def send(self, hittype, *args, **data):
        

        if hittype not in self.valid_hittypes:
            raise KeyError('Unsupported Universal Analytics Hit Type: {0}'.format(repr(hittype)))

        self.set_timestamp(data)
        self.consume_options(data, hittype, args)

        for item in args:  # process dictionary-object arguments of transcient data
            if isinstance(item, dict):
                for key, val in self.payload(item):
                    data[key] = val

        for k, v in self.params.items():  # update only absent parameters
            if k not in data:
                data[k] = v

        data = dict(self.payload(data))

        if self.hash_client_id:
            data['cid'] = generate_uuid(data['cid'])

        # Transmit the hit to Google...
        await self.http.send(data)
393029
def export_metrics(self, metrics):
        
        metric_protos = []
        for metric in metrics:
            metric_protos.append(_get_metric_proto(metric))

        self._rpc_handler.send(
            metrics_service_pb2.ExportMetricsServiceRequest(
                metrics=metric_protos))
374426
public void send(final List<MetricAggregate> aggregates) throws IOException, HttpException {
		
		HttpClient httpClient = new HttpClient(apiConfig);
		
		// retransmit any metrics on the resend queue
		
		resendQueue.drain(httpClient, "/Metrics/SubmitMetricsByID");
		
		// build the json objects
		
		List<JsonMetric> metrics = new ArrayList<JsonMetric>(aggregates.size());
		
		for (MetricAggregate aggregate : aggregates) {
			
			Integer monitorId = monitorService.getMonitorId(aggregate.getIdentity());
			
			if (monitorId != null) {
				JsonMetric.Builder builder = JsonMetric.newBuilder();
				builder.monitorId(monitorId);
				builder.value(Double.valueOf(aggregate.getValue()));
				builder.count(Integer.valueOf(aggregate.getCount()));
				builder.occurredUtc(new Date(aggregate.getOccurredMillis()));
				builder.monitorTypeId(Integer.valueOf(aggregate.getIdentity().getType().getId()));
				builder.clientDeviceId(monitorService.getDeviceId());
				
				metrics.add(builder.build());
			} else {
				LOGGER.info("Unable to determine monitor id for aggregate metric {}", aggregate);
			}
		}
		
		if (metrics.isEmpty()) {
			return;
		}
		
		// post metrics to stackify
		
		byte[] jsonBytes = objectMapper.writer().writeValueAsBytes(metrics);
		
		try {
			httpClient.post("/Metrics/SubmitMetricsByID", jsonBytes);
		} catch (IOException t) {
			LOGGER.info("Queueing metrics for retransmission due to IOException");
			resendQueue.offer(jsonBytes, t);
			throw t;			
		} catch (HttpException t) {
			LOGGER.info("Queueing metrics for retransmission due to HttpException");
			resendQueue.offer(jsonBytes, t);
			throw t;
		}
	}
168111
def Send(self, usb, timeout_ms=None):
        """"""
        usb.BulkWrite(self.Pack(), timeout_ms)
        usb.BulkWrite(self.data, timeout_ms)
1196184
def send(transport, time, state, host, description, service, tag, attribute,
         ttl, metric_f, echo):
    """"""
    client = CommandLineClient(transport)
    event = client.create_event({
        'time': time,
        'state': state,
        'host': host,
        'description': description,
        'service': service,
        'tags': tag,
        'attributes': dict(attribute),
        'ttl': ttl,
        'metric_f': metric_f
    })

    with client:
        client.send_event(event)
    if echo:
        echo_event(client.create_dict(event))
1181711
def _send(saltdata, metric_base, opts):
    '''
    
    '''

    host = opts.get('host')
    port = opts.get('port')
    skip = opts.get('skip')
    metric_base_pattern = opts.get('carbon.metric_base_pattern')
    mode = opts.get('mode').lower() if 'mode' in opts else 'text'

    log.debug('Carbon minion configured with host: %s:%s', host, port)
    log.debug('Using carbon protocol: %s', mode)

    if not (host and port):
        log.error('Host or port not defined')
        return

    # TODO: possible to use time return from salt job to be slightly more precise?
    # convert the jid to unix timestamp?
    # {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
    timestamp = int(time.time())

    handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
    metrics = []
    log.trace('Carbon returning walking data: %s', saltdata)
    _walk(metric_base, saltdata, metrics, timestamp, skip)
    data = handler(metrics)
    log.trace('Carbon inserting data: %s', data)

    with _carbon(host, port) as sock:
        total_sent_bytes = 0
        while total_sent_bytes < len(data):
            sent_bytes = sock.send(data[total_sent_bytes:])
            if sent_bytes == 0:
                log.error('Bytes sent 0, Connection reset?')
                return

            log.debug('Sent %s bytes to carbon', sent_bytes)
            total_sent_bytes += sent_bytes
1237150
def send(self, data):
        """"""
        self._send_data(int_to_hex(len(data)))

        self._send_data(data)
1315610
def send(self, msg):
        """"""
        if self._conn:
            self._conn.write_data(msg.message, msg.response_command)
772786
def _send(self, metric):
        
        metric_name = self.get_name_from_path(metric.path)
        tmax = "60"
        dmax = "0"
        slope = "both"
        # FIXME: Badness, shouldn't *assume* double type
        metric_type = "double"
        units = ""
        group = ""
        self.gmetric.send(metric_name,
                          metric.value,
                          metric_type,
                          units,
                          slope,
                          tmax,
                          dmax,
                          group)
760682
def _send(key, value, metric_type):
    
    if STATSD_PREFIX:
        key = '.'.join([STATSD_PREFIX, key])
    try:
        STATSD_SOCKET.sendto('{0}:{1}|{2}'.format(key,
                                                  value,
                                                  metric_type).encode(),
                             STATSD_ADDR)
    except socket.error:
        LOGGER.exception(SOCKET_ERROR)
122784
private void export() {
    if (exportRpcHandler == null || exportRpcHandler.isCompleted()) {
      return;
    }

    ArrayList<Metric> metricsList = Lists.newArrayList();
    for (MetricProducer metricProducer : metricProducerManager.getAllMetricProducer()) {
      metricsList.addAll(metricProducer.getMetrics());
    }

    List<io.opencensus.proto.metrics.v1.Metric> metricProtos = Lists.newArrayList();
    for (Metric metric : metricsList) {
      // TODO(songya): determine if we should make the optimization on not sending already-existed
      // MetricDescriptors.
      // boolean registered = true;
      // if (!registeredDescriptors.contains(metric.getMetricDescriptor())) {
      //   registered = false;
      //   registeredDescriptors.add(metric.getMetricDescriptor());
      // }
      metricProtos.add(MetricsProtoUtils.toMetricProto(metric, null));
    }

    exportRpcHandler.onExport(
        // For now don't include Resource in the following messages, i.e don't allow Resource to
        // mutate after the initial message.
        ExportMetricsServiceRequest.newBuilder().addAllMetrics(metricProtos).build());
  }
806325
def metric(self, measurement_name, values, tags=None, timestamp=None):
        
        if not measurement_name or values in (None, {}):
            # Don't try to send empty data
            return

        tags = tags or {}

        # Do a shallow merge of the metric tags and global tags
        all_tags = dict(self.tags, **tags)

        # Create a metric line from the input and then send it to socket
        line = Line(measurement_name, values, all_tags, timestamp)
        self.send(line.to_line_protocol())