Generic method that posts a plugin to the metrics website
2429
private void postPlugin(final boolean isPing) throws IOException {
        String serverVersion = getFullServerVersion();
        int playersOnline = getPlayersOnline();

        // END server software specific section -- all code below does not use any code outside of this class / Java

        // Construct the post data
        StringBuilder json = new StringBuilder(1024);
        json.append('{');

        // The plugin's description file containg all of the plugin data such as name, version, author, etc
        appendJSONPair(json, "guid", guid);
        appendJSONPair(json, "plugin_version", pluginVersion);
        appendJSONPair(json, "server_version", serverVersion);
        appendJSONPair(json, "players_online", Integer.toString(playersOnline));

        // New data as of R6
        String osname = System.getProperty("os.name");
        String osarch = System.getProperty("os.arch");
        String osversion = System.getProperty("os.version");
        String java_version = System.getProperty("java.version");
        int coreCount = Runtime.getRuntime().availableProcessors();

        // normalize os arch .. amd64 -> x86_64
        if (osarch.equals("amd64")) {
            osarch = "x86_64";
        }

        appendJSONPair(json, "osname", osname);
        appendJSONPair(json, "osarch", osarch);
        appendJSONPair(json, "osversion", osversion);
        appendJSONPair(json, "cores", Integer.toString(coreCount));
        // appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
        appendJSONPair(json, "java_version", java_version);

        // If we're pinging, append it
        if (isPing) {
            appendJSONPair(json, "ping", "1");
        }

        if (graphs.size() > 0) {
            synchronized (graphs) {
                json.append(',');
                json.append('"');
                json.append("graphs");
                json.append('"');
                json.append(':');
                json.append('{');

                boolean firstGraph = true;

                final Iterator<Graph> iter = graphs.iterator();

                while (iter.hasNext()) {
                    Graph graph = iter.next();

                    StringBuilder graphJson = new StringBuilder();
                    graphJson.append('{');

                    for (Plotter plotter : graph.getPlotters()) {
                        appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
                    }

                    graphJson.append('}');

                    if (!firstGraph) {
                        json.append(',');
                    }

                    json.append(escapeJSON(graph.getName()));
                    json.append(':');
                    json.append(graphJson);

                    firstGraph = false;
                }

                json.append('}');
            }
        }

        // close json
        json.append('}');

        // Create the url
        URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));

        // Connect to the website
        URLConnection connection;

        // Mineshafter creates a socks proxy, so we can safely bypass it
        // It does not reroute POST requests so we need to go around it
        if (isMineshafterPresent()) {
            connection = url.openConnection(Proxy.NO_PROXY);
        } else {
            connection = url.openConnection();
        }

        byte[] uncompressed = json.toString().getBytes();
        byte[] compressed = gzip(json.toString());

        // Headers
        connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.addRequestProperty("Content-Encoding", "gzip");
        connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
        connection.addRequestProperty("Accept", "application/json");
        connection.addRequestProperty("Connection", "close");

        connection.setDoOutput(true);

        if (debug) {
            System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
        }

        // Write the data
        OutputStream os = connection.getOutputStream();
        os.write(compressed);
        os.flush();

        // Now read the response
        final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String response = reader.readLine();

        // close resources
        os.close();
        reader.close();

        if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
            if (response == null) {
                response = "null";
            } else if (response.startsWith("7")) {
                response = response.substring(response.startsWith("7,") ? 2 : 1);
            }

            throw new IOException(response);
        } else {
            // Is this the first update this hour?
            if (response.equals("1") || response.contains("This is your first update this hour")) {
                synchronized (graphs) {
                    final Iterator<Graph> iter = graphs.iterator();

                    while (iter.hasNext()) {
                        final Graph graph = iter.next();

                        for (Plotter plotter : graph.getPlotters()) {
                            plotter.reset();
                        }
                    }
                }
            }
        }
    }
1209813
@Override
    public void submitMetric(PrincipalUser submitter, Metric metric) {
        submitMetrics(submitter, Arrays.asList(new Metric[] { metric }));
    }
1193633
function(eventObj, callback) {
    var url = eventObj.url;
    var params = eventObj.params;
    if (eventObj.httpVerb === POST_METHOD) {
      var req = new XMLHttpRequest();
      req.open(POST_METHOD, url, true);
      req.setRequestHeader('Content-Type', 'application/json');
      req.onreadystatechange = function() {
        if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') {
          try {
            callback(params);
          } catch (e) {
            // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface)
          }
        }
      };
      req.send(JSON.stringify(params));
    } else {
      // add param for cors headers to be sent by the log endpoint
      url += '?wxhr=true';
      if (params) {
        url += '&' + toQueryString(params);
      }

      var req = new XMLHttpRequest();
      req.open(GET_METHOD, url, true);
      req.onreadystatechange = function() {
        if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') {
          try {
            callback();
          } catch (e) {
            // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface)
          }
        }
      };
      req.send();
    }
  }
1267103
async def get_metrics(self, element):
        """"""
        await self.get_data()
        await self.get_plugins()

        if element in self.plugins:
            self.values = self.data[element]
        else:
            raise exceptions.GlancesApiError("Element data not available")
1253314
private void postMetricMetadata(String metricName, DatadogMetricMetadata metadata) {
        // already posted the metadata for this metric
        if (verifiedMetadata.contains(metricName))
            return;

        try {
            httpClient
                    .put(config.uri() + "/api/v1/metrics/" + URLEncoder.encode(metricName, "UTF-8")
                            + "?api_key=" + config.apiKey() + "&application_key=" + config.applicationKey())
                    .withJsonContent(metadata.editMetadataBody())
                    .send()
                    .onSuccess(response -> verifiedMetadata.add(metricName))
                    .onError(response -> {
                        if (logger.isErrorEnabled()) {
                            String msg = response.body();

                            // Ignore when the response content contains "metric_name not found".
                            // Metrics that are newly created in Datadog are not immediately available
                            // for metadata modification. We will keep trying this request on subsequent publishes,
                            // where it will eventually succeed.
                            if (!msg.contains("metric_name not found")) {
                                logger.error("failed to send metric metadata to datadog: {}", msg);
                            }
                        }
                    });
        } catch (Throwable e) {
            logger.warn("failed to send metric metadata to datadog", e);
        }
    }
1155926
def log_metrics(self, metrics_by_name, info):
        
        if self.metrics is None:
            # If, for whatever reason, the metrics collection has not been set
            # do not try to save anything there.
            return
        for key in metrics_by_name:
            query = {"run_id": self.run_entry['_id'],
                     "name": key}
            push = {"steps": {"$each": metrics_by_name[key]["steps"]},
                    "values": {"$each": metrics_by_name[key]["values"]},
                    "timestamps": {"$each": metrics_by_name[key]["timestamps"]}
                    }
            update = {"$push": push}
            result = self.metrics.update_one(query, update, upsert=True)
            if result.upserted_id is not None:
                # This is the first time we are storing this metric
                info.setdefault("metrics", []) \
                    .append({"name": key, "id": str(result.upserted_id)})
1209048
function (domain, poString, callback) {
        var icuObject = this.poStringToICUSync(domain, poString);
        callback(null, icuObject);
    }
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());
    */
}
75816
protected void processOneMetric(List<String> resultStrings, Server server, Result result, Object value, String addTagName,
									String addTagValue) {
		String metricName = this.metricNameStrategy.formatName(result);

		//
		// Skip any non-numeric values since OpenTSDB only supports numeric metrics.
		//
		if (isNumeric(value)) {
			StringBuilder resultString = new StringBuilder();

			formatResultString(resultString, metricName, result.getEpoch() / 1000L, value);
			addTags(resultString, server);

			if (addTagName != null) {
				addTag(resultString, addTagName, addTagValue);
			}

			if (!typeNames.isEmpty()) {
				this.addTypeNamesTags(resultString, result);
			}

			resultStrings.add(resultString.toString());
		} else {
			log.debug("Skipping non-numeric value for metric {}; value={}", metricName, value);
		}
	}
571760
def collect_metrics():
    
    def _register(action):
        handler = Handler.get(action)
        handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))
        return action
    return _register
280731
function recomputePluginOrdering() {
  if (!EventPluginOrder) {
    // Wait until an `EventPluginOrder` is injected.
    return;
  }
  for (var pluginName in namesToPlugins) {
    var PluginModule = namesToPlugins[pluginName];
    var pluginIndex = EventPluginOrder.indexOf(pluginName);
    ("production" !== "development" ? invariant(
      pluginIndex > -1,
      'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
      'the plugin ordering, `%s`.',
      pluginName
    ) : invariant(pluginIndex > -1));
    if (EventPluginRegistry.plugins[pluginIndex]) {
      continue;
    }
    ("production" !== "development" ? invariant(
      PluginModule.extractEvents,
      'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
      'method, but `%s` does not.',
      pluginName
    ) : invariant(PluginModule.extractEvents));
    EventPluginRegistry.plugins[pluginIndex] = PluginModule;
    var publishedEvents = PluginModule.eventTypes;
    for (var eventName in publishedEvents) {
      ("production" !== "development" ? invariant(
        publishEventForPlugin(
          publishedEvents[eventName],
          PluginModule,
          eventName
        ),
        'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.',
        eventName,
        pluginName
      ) : invariant(publishEventForPlugin(
        publishedEvents[eventName],
        PluginModule,
        eventName
      )));
    }
  }
}
94814
function(obj, methodName, methodArgs, probeData) {
        // Start metrics
        that.metricsProbeStart(probeData);
        that.requestProbeStart(probeData);
        // End metrics
        aspect.aroundCallback(
          methodArgs,
          probeData,
          function(target, args, probeData) {
            // Get HTTP request method from options
            var ri = getRequestItems(methodArgs[0]);
            that.metricsProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers);
            that.requestProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers);
          },
          function(target, args, probeData, ret) {
            // Don't need to do anything after the callback
            return ret;
          }
        );
      }
432505
def GetMetricTypes(self, request, context):
        """"""
        LOG.debug("GetMetricTypes called")
        try:
            metrics = self.plugin.update_catalog(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)
40669
def register_plugin(cls, model, plugin):
        '''
        
        '''
        logger.info("Plugin registered for %s: %s", model, plugin)
        cls.plugins[model] = plugin
690612
function(opts, method) {

      // create function vars
      var cts = this.cts,
          xhr = new XMLHttpRequest(),
          data = u.param(opts.data, opts.json);

      // XMLHttpRequest state change function
      xhr.onreadystatechange = function(){
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 400){
            // call success callback
            opts.success(u.parse(xhr.response || xhr.responseText), xhr.statusText);
          }
          else {
            // call error callback
            opts.error(u.parse(xhr.response || xhr.responseText), xhr.statusText);
          }
        }
      };

      if (xhr.upload) {
        // XMLHttpRequest upload progress function
        xhr.upload.onprogress = function(event) {
          if (event.lengthComputable) {
            // call progress callback
            opts.up(event.total, event.loaded);
          }
        };
      }

      // XMLHttpRequest download progress function
      xhr.onprogress = function(event) {
        if (event.lengthComputable) {
          // call progress callback
          opts.down(event.total, event.loaded);
        }
      };

      // open request and set headers
      xhr.open(method, opts.url, opts.async);
      xhr.setRequestHeader('Content-type', (opts.json ? cts.json : cts.form));
      xhr.setRequestHeader('Accept', cts.json);

      opts.headers && u.each(opts.headers, function(header, value) {
        xhr.setRequestHeader(header, value);
      });

      // if set, send authorization header
      if (opts.auth) {
        xhr.setRequestHeader('Authorization', opts.auth);
      }

      // send the request
      xhr.send(data || null);

      return xhr;

    }
1223115
def request(method, url, **kwargs):
    """"""
    _set_content_type(kwargs)
    if _content_type_is_json(kwargs) and kwargs.get('data') is not None:
        kwargs['data'] = dumps(kwargs['data'])
    _log_request(method, url, kwargs)
    response = requests.request(method, url, **kwargs)
    _log_response(response)
    return response
747011
private void sendRegisterRequest() {
    Metrics.MetricPublisher publisher = Metrics.MetricPublisher.newBuilder().
        setHostname(hostname).
        setPort(instance.getInfo().getTaskId()).
        setComponentName(instance.getInfo().getComponentName()).
        setInstanceId(instance.getInstanceId()).
        setInstanceIndex(instance.getInfo().getComponentIndex()).
        build();
    Metrics.MetricPublisherRegisterRequest request =
        Metrics.MetricPublisherRegisterRequest.newBuilder().
            setPublisher(publisher).
            build();

    // The timeout would be the reconnect-interval-seconds
    sendRequest(request, null,
        Metrics.MetricPublisherRegisterResponse.newBuilder(),
        systemConfig.getInstanceReconnectMetricsmgrInterval());
  }