Send the request and log/update metrics for the results.
961504
protected HttpResponse sendImpl() throws IOException {
    HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
    con.setConnectTimeout(connectTimeout);
    con.setReadTimeout(readTimeout);
    con.setRequestMethod(method);
    for (Map.Entry<String, String> h : reqHeaders.entrySet()) {
      entry.addRequestHeader(h.getKey(), h.getValue());
      con.setRequestProperty(h.getKey(), h.getValue());
    }
    configureHTTPS(con);

    try {
      con.setDoInput(true);

      // HttpURLConnection will change method to POST if there is a body associated
      // with a GET request. Only try to write entity if it is not empty.
      entry.markStart();
      if (entity.length > 0) {
        con.setDoOutput(true);
        try (OutputStream out = con.getOutputStream()) {
          out.write(entity);
        }
      }

      int status = con.getResponseCode();
      entry.markEnd().withHttpStatus(status);

      // A null key is used to return the status line, remove it before sending to
      // the log entry or creating the response object
      Map<String, List<String>> headers = new LinkedHashMap<>(con.getHeaderFields());
      headers.remove(null);
      for (Map.Entry<String, List<String>> h : headers.entrySet()) {
        for (String v : h.getValue()) {
          entry.addResponseHeader(h.getKey(), v);
        }
      }

      try (InputStream in = (status >= 400) ? con.getErrorStream() : con.getInputStream()) {
        byte[] data = readAll(in);
        return new HttpResponse(status, headers, data);
      }
    } catch (IOException e) {
      entry.markEnd().withException(e);
      throw e;
    } finally {
      entry.log();
    }
  }
239730
def send_response(self, code, message=None):
        """"""
        self.log_request(code)
        if message is None:
            message = code in self.responses and self.responses[code][0] or ""
        if self.request_version != "HTTP/0.9":
            hdr = "%s %d %s\r\n" % (self.protocol_version, code, message)
            self.wfile.write(hdr.encode("ascii"))
76280
def process(self, metric):
        
        if self._match_metric(metric):
            self.metrics.append(metric)
        if self.should_flush():
            self._send()
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))
663370
def process(self, metric):
        
        for rmq_server in self.connections.keys():
            try:
                if ((self.connections[rmq_server] is None or
                     self.connections[rmq_server].is_open is False)):
                    self._bind(rmq_server)

                channel = self.channels[rmq_server]
                channel.basic_publish(exchange=self.rmq_exchange,
                                      routing_key='', body="%s" % metric)
            except Exception as exception:
                self.log.error(
                    "Failed publishing to %s, attempting reconnect",
                    rmq_server)
                self.log.debug("Caught exception: %s", exception)
                self._unbind(rmq_server)
                self._bind(rmq_server)
1324543
def metric_details(request, pk, format=None):
    
    metric = get_object_or_404(Metric, pk=pk)
    # get
    if request.method == 'GET':
        try:
            results = metric.select(q=request.query_params.get('q', metric.query))
        except InfluxDBClientError as e:
            return Response({'detail': e.content}, status=e.code)
        return Response(list(results.get_points(metric.name)))
    # post
    else:
        if not request.data:
            return Response({'detail': 'expected values in POST data or JSON payload'},
                            status=400)
        data = request.data.copy()
        # try converting strings to floats when sending form-data
        if request.content_type != 'application/json':
            for key, value in data.items():
                try:
                    data[key] = float(value) if '.' in value else int(value)
                except ValueError:
                    pass
        # write
        metric.write(data)
        return Response({'detail': 'ok'})
312390
def Process(self, request, context):
        """"""
        LOG.debug("Process called")
        try:
            metrics = self.plugin.process(
                [Metric(pb=m) for m in request.Metrics],
                ConfigMap(pb=request.Config)
            )
            return MetricsReply(metrics=[m.pb for m in metrics])
        except Exception as err:
            msg = "message: {}\n\nstack trace: {}".format(
                err, traceback.format_exc())
            return MetricsReply(metrics=[], error=msg)
1086936
def send_request(self, request):
        """"""
        # throttle the number of requests to each host
        self.aggregate.wait_for_host(self.urlparts[1])
        kwargs = self.get_request_kwargs()
        kwargs["allow_redirects"] = False
        self._send_request(request, **kwargs)
51844
def update(self):
        
        # build requests for this iteration
        reqs = self.build_requests()
        for r in reqs:
            r.block = self.block
        results = self.send_requests(*reqs)

        # call callback with the results
        self.callback(results)
387612
protected void sendRequests() {
        if ( ! requestUnderway ) {
            requestUnderway = true;
            delayed( new Runnable() {
                @Override
                public void run() {
                    synchronized (requests) {
                        Object req[];
                        if ( openFutureRequests.get() > 0 && requests.size() == 0 ) {
                            req = new Object[] { "SP", lastSeenSeq };
                        } else {
                            req = new Object[requests.size() + 1];
                            for (int i = 0; i < requests.size(); i++) {
                                req[i] = requests.get(i);
                            }
                            req[req.length - 1] = lastSeenSeq;
                            requests.clear();
                        }

                        sendCallArray(req).then(new Callback<Integer>() {
                            @Override
                            public void receive(Integer result, Object error) {
                                synchronized (requests ) {
                                    requestUnderway = false;
                                    if ( requests.size() > 0 || (result != null && result > 0 && openFutureRequests.get() > 0 ) ) {
                                        myExec.execute(new Runnable() {
                                            @Override
                                            public void run() {
                                            sendRequests();
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            }, 1);
        }
    }
1234048
def post(self, result, **kwargs):
        """"""
        internal_assert(isinstance(result, str), "got non-string parse result", result)
        return self.apply_procs(self.postprocs, kwargs, result)
1205431
function processGetMetrics(req,res){

    processAuth(req,res).then(function (authResult){
        if(!authResult){
            return;
        }
        res.status(200).set('Content-Type', 'text/plain');
        res.end(promClient.register.metrics());
    });

    /*
    if(!processAuth(req,res)) {
        return;
    }

    res.status(200).set('Content-Type', 'text/plain');
    res.end(promClient.register.metrics());
    */
}
433801
def _handler_http(self, result):
        
        monitor = result['monitor']
        self.thread_debug("process_http", data=monitor, module='handler')
        self.stats.http_handled += 1

        # splunk will pick this up
        logargs = {
            'type':"metric",
            'endpoint': result['url'],
            'pipeline': monitor['pipeline'],
            'service': monitor['service'],
            'instance': monitor['instance'],
            'status': result['status'],
            'elapsed-ms': round(result['elapsedms'], 5),
            'code': result['code']
        }
        self.NOTIFY(result['message'], **logargs)

        # if our status has changed, also update Reflex Engine
        if result['status'] != self.instances[monitor['instance']]['status']:
            # do some retry/counter steps on failure?
            self.instances[monitor['instance']]['status'] = result['status']
            self.rcs.patch('instance',
                           monitor['instance'],
                           {'status': result['status']})
1320311
def refresh_metrics(self):
        """"""
        metrics = self.get_metrics()
        dbmetrics = (
            db.session.query(DruidMetric)
            .filter(DruidMetric.datasource_id == self.datasource_id)
            .filter(DruidMetric.metric_name.in_(metrics.keys()))
        )
        dbmetrics = {metric.metric_name: metric for metric in dbmetrics}
        for metric in metrics.values():
            dbmetric = dbmetrics.get(metric.metric_name)
            if dbmetric:
                for attr in ['json', 'metric_type']:
                    setattr(dbmetric, attr, getattr(metric, attr))
            else:
                with db.session.no_autoflush:
                    metric.datasource_id = self.datasource_id
                    db.session.add(metric)
998126
protected void statsRequestStart()
    {
        if (_statsOn)
        {
            if (_reqTime>0)
                statsRequestEnd();
            _requests++;
            _tmpTime=_request.getTimeStamp();
            _reqTime=_tmpTime;
            _httpServer.statsGotRequest();
        }
    }
1327246
def _send(self):
        
        self.queue.submit()
        self.queue_max_timestamp = int(time.time() + self.queue_max_interval)
        self.current_n_measurements = 0
308371
def send_result(self, additional_dict):
        '''
        
        '''
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        response = {
            'jsonrpc': self.req_rpc_version,
            'id': self.req_id,
        }
        response.update(additional_dict)
        jresponse = json.dumps(response)
        self.send_header("Content-length", len(jresponse))
        self.end_headers()
        self.wfile.write(jresponse.encode())