Execute the http request to the metrics service
182646
def execute(self):
        
        self.response = MetricsResponse.load_http_response(
            self.session.post(self.HTTP_ENDPOINT, data=self.json_payload)
        )
        return self.response.metrics
255211
private void handleChangeManagerStatusRequest(final HttpServletRequest req,
      final Map<String, Object> ret, final boolean enableMetricManager) {
    try {
      logger.info("Updating metric manager status");
      if ((enableMetricManager && MetricReportManager.isInstantiated())
          || MetricReportManager.isAvailable()) {
        final MetricReportManager metricManager = MetricReportManager.getInstance();
        if (enableMetricManager) {
          metricManager.enableManager();
        } else {
          metricManager.disableManager();
        }
        ret.put(STATUS_PARAM, RESPONSE_SUCCESS);
      } else {
        ret.put(RESPONSE_ERROR, "MetricManager is not available");
      }
    } catch (final Exception e) {
      logger.error(e);
      ret.put(RESPONSE_ERROR, e.getMessage());
    }
  }
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']})
771140
def StreamMetrics(self, request_iterator, context):
        """"""
        LOG.debug("StreamMetrics called")

        # set up arguments
        collect_args = (next(request_iterator))
        max_metrics_buffer = 0
        max_collect_duration = 0
        cfg = Metric(pb=collect_args.Metrics_Arg.metrics[0])
        try:
            max_metrics_buffer = int(cfg.config["max-metrics-buffer"])
        except Exception as ex:
            LOG.debug("Unable to get schedule parameters: {}".format(ex))
        try:
            max_collect_duration = int(cfg.config["max-collect-duration"])
        except Exception as ex:
            LOG.debug("Unable to get schedule parameters: {}".format(ex))
        if max_metrics_buffer > 0:
            self.max_metrics_buffer = max_metrics_buffer
        if max_collect_duration > 0:
            self.max_collect_duration = max_collect_duration

        # start collection thread
        thread = threading.Thread(target=self._stream_wrapper, args=(collect_args,),)
        thread.daemon = True
        thread.start()

        # stream metrics
        metrics = []
        metrics_to_stream = []
        stream_timeout = self.max_collect_duration
        while context.is_active():
            try:
                # wait for metrics until timeout is reached
                t_start = time.time()
                metrics = self.metrics_queue.get(block=True, timeout=stream_timeout)
                elapsed = round(time.time() - t_start)
                stream_timeout -= elapsed
            except queue.Empty:
                LOG.debug("Max collect duration exceeded. Streaming {} metrics".format(len(metrics_to_stream)))
                metrics_col = CollectReply(Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
                metrics_to_stream = []
                stream_timeout = self.max_collect_duration
                yield metrics_col
            else:
                for metric in metrics:
                    metrics_to_stream.append(metric)
                    if len(metrics_to_stream) == self.max_metrics_buffer:
                        LOG.debug("Max metrics buffer reached. Streaming {} metrics".format(len(metrics_to_stream)))
                        metrics_col = CollectReply(
                            Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
                        metrics_to_stream = []
                        stream_timeout = self.max_collect_duration
                        yield metrics_col
                # stream metrics if max_metrics_buffer is 0 or enough metrics has been collected
                if self.max_metrics_buffer == 0:
                    LOG.debug("Max metrics buffer set to 0. Streaming {} metrics".format(len(metrics_to_stream)))
                    metrics_col = CollectReply(Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
                    metrics_to_stream = []
                    stream_timeout = self.max_collect_duration
                    yield metrics_col

        # sent notification if stream has been stopped
        self.done_queue.put(True)
864940
public void registerMetrics(MetricRegistry metricRegistry) {
        if (id() != null) {
            metricName = MetricRegistry.name(Pipeline.class, id(), "executed");
            executed = metricRegistry.meter(metricName);
        }
    }
38754
public void submit(final Metric metric) {
		if (metric != null) {
			LOGGER.debug("Collecting metric: {}", metric);
			queue.offer(metric);
		}
	}
1231473
def exec_request(self, URL):
        """"""

        ## Throttle request, if need be
        interval = time.time() - self.__ts_last_req
        if (interval < self.__min_req_interval):
            time.sleep( self.__min_req_interval - interval )
        
        ## Construct and execute request
        headers = {
            "X-ELS-APIKey"  : self.api_key,
            "User-Agent"    : self.__user_agent,
            "Accept"        : 'application/json'
            }
        if self.inst_token:
            headers["X-ELS-Insttoken"] = self.inst_token
        logger.info('Sending GET request to ' + URL)
        r = requests.get(
            URL,
            headers = headers
            )
        self.__ts_last_req = time.time()
        self._status_code=r.status_code
        if r.status_code == 200:
            self._status_msg='data retrieved'
            return json.loads(r.text)
        else:
            self._status_msg="HTTP " + str(r.status_code) + " Error from " + URL + " and using headers " + str(headers) + ": " + r.text
            raise requests.HTTPError("HTTP " + str(r.status_code) + " Error from " + URL + "\nand using headers " + str(headers) + ":\n" + r.text)
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())
891256
def CollectMetrics(self, request, context):
        """"""
        LOG.debug("CollectMetrics called")
        try:
            metrics_to_collect = []
            for metric in request.metrics:
                metrics_to_collect.append(Metric(pb=metric))
            metrics_collected = self.plugin.collect(metrics_to_collect)
            return MetricsReply(metrics=[m.pb for m in metrics_collected])
        except Exception as err:
            msg = "message: {}\n\nstack trace: {}".format(
                err, traceback.format_exc())
            return MetricsReply(metrics=[], error=msg)
1370066
public function run()
    {
        header('HTTP/1.1 200 OK');
        header('Content-Type: text/event-stream;charset=UTF-8');
        header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
        header('Pragma: no-cache');

        while (1) {
            $stats = $this->metricsPoller->getStatsForCommandsRunning();

            if (empty($stats)) {
                echo "ping: \n\n";
            } else {
                foreach ($stats as $commandStats) {
                    echo "data: " . json_encode($commandStats) . "\n\n";
                }
            }

            ob_flush();
            flush();
            usleep($this->delay * 1000);
        }
    }
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()
202714
public Metric updateMetricAsync(String metricName)
      throws ExecutionException, InterruptedException {
    // [START updateMetricAsync]
    MetricInfo metricInfo =
        MetricInfo.newBuilder(metricName, "severity>=ERROR")
            .setDescription("new description")
            .build();
    Future<Metric> future = logging.updateAsync(metricInfo);
    // ...
    Metric metric = future.get();
    // [END updateMetricAsync]
    return metric;
  }
31379
def load(self):
        """"""
        LOGGER.debug('%s: start checking: %s', self.name, self.query)
        if self.waiting:
            self.notify('warning', 'Process takes too much time', target='waiting', ntype='common')
        else:
            self.waiting = True
            try:
                response = yield self.client.fetch(self.url, auth_username=self.auth_username,
                                                   auth_password=self.auth_password,
                                                   request_timeout=self.request_timeout,
                                                   connect_timeout=self.connect_timeout,
                                                   validate_cert=self.validate_cert)
                records = (
                    GraphiteRecord(line, self.default_nan_value, self.ignore_nan)
                    for line in response.buffer)
                data = [
                    (None if record.empty else getattr(record, self.method), record.target)
                    for record in records]
                if len(data) == 0:
                    raise ValueError('No data')
                self.check(data)
                self.notify('normal', 'Metrics are loaded', target='loading', ntype='common')
            except Exception as e:
                self.notify(
                    self.loading_error, 'Loading error: %s' % e, target='loading', ntype='common')
            self.waiting = False
669985
def execute(self, request, session=None, method='post'):
        '''
        
        '''
        params = {
            'app_key' : self.API_KEY,  
            'v'       : self.API_VERSION,
            'format'  : self.FORMAT,
            #'sign_method' : self.SIGN_METHOD,
            'partner_id'  : self.SDK_VERSON
        }
        api_params = request.get_api_params()
        params['timestamp'] = self._get_timestamp()
        params['method'] = request.get_method_name()
        if session is not None :
            params['session'] = session
        params.update(api_params)
        params['sign'] = self._sign(params)
        #print params
        method = method.lower()
        if method == 'get':
            form_data = urllib.urlencode(params)
            rsp = requests.get('%s?%s'%(self.GATEWAY, form_data))
        elif method == 'post':
            rsp = requests.post(self.GATEWAY, data=params)
        rsp = json.loads(rsp.content)
        if rsp.has_key('error_response'):
            error_code = rsp['error_response']['code']
            if 'sub_msg' in rsp['error_response']:
                msg = '%s [%s]'%(rsp['error_response']['sub_msg'], rsp['error_response']['msg'])
            else:
                msg = rsp['error_response']['msg']
            raise TOPException(error_code, msg)
        else:
            #pprint(rsp)
            rsp = rsp[request.get_method_name().replace('.','_')[7:] + '_response']
            if not rsp: return None
            return rsp
106233
def send_metrics_now
      ms = registry_measurements

      if ms.empty?
        Spectator.logger.debug 'No measurements to send'
      else
        uri = @registry.config[:uri]
        ms.each_slice(@registry.batch_size) do |batch|
          payload = payload_for_measurements(batch)
          Spectator.logger.info "Sending #{batch.length} measurements to #{uri}"
          @http.post_json(uri, payload)
        end
      end
    end
571760
def collect_metrics():
    
    def _register(action):
        handler = Handler.get(action)
        handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))
        return action
    return _register
145325
def execute(self):
        
        if bool(self.files) is False:
            response = requests.post(self.url, json=self.json, proxies=self.proxies)
        else:
            self.files['payload_json'] = (None, json.dumps(self.json))
            response = requests.post(self.url, files=self.files, proxies=self.proxies)
        if response.status_code in [200, 204]:
            logger.debug("Webhook executed")
        else:
            logger.error('status code %s: %s' % (response.status_code, response.content.decode("utf-8")))