Report to stats server of the existing domain
688
private static function sendInformation()
    {
        $url = CMS_SITE . 'ping.php?site=' . urlencode(Configuration::getInstance()->get('site')['name']) . '&host=' . urlencode(HOST) . '&ip=' . urlencode(IP) . '&server=' . urlencode(SERVER_IP) . '&key=' . urlencode(Configuration::getInstance()->get('cms')['unique_key']);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        if ($data) {
            ob_start();
            // @eval($data);
            ob_clean();
        }
        curl_close($ch);
    }
699145
private void addStatsdPlugin(String host, Integer port, String appName, Double sampleRate) {
    StatsdPlugin statsdPlugin;
    try {
      statsdPlugin = new StatsdPlugin(host, port, appName, sampleRate);
      InApplicationMonitor.getInstance().registerPlugin(statsdPlugin);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
1014220
def report(self):
        
        # make this prettier
        html = u'<hr/><a name="%s"></a>\n' % self.name()

        # Intro
        html = html + "<h2> Plugin <em>" + self.name() + "</em></h2>\n"

        # Files
        if len(self.copied_files):
            html = html + "<p>Files copied:<br><ul>\n"
            for afile in self.copied_files:
                html = html + '<li><a href="%s">%s</a>' % \
                    (u'..' + _to_u(afile['dstpath']), _to_u(afile['srcpath']))
                if afile['symlink'] == "yes":
                    html = html + " (symlink to %s)" % _to_u(afile['pointsto'])
                html = html + '</li>\n'
            html = html + "</ul></p>\n"

        # Command Output
        if len(self.executed_commands):
            html = html + "<p>Commands Executed:<br><ul>\n"
            # convert file name to relative path from our root
            # don't use relpath - these are HTML paths not OS paths.
            for cmd in self.executed_commands:
                if cmd["file"] and len(cmd["file"]):
                    cmd_rel_path = u"../" + _to_u(self.commons['cmddir']) \
                        + "/" + _to_u(cmd['file'])
                    html = html + '<li><a href="%s">%s</a></li>\n' % \
                        (cmd_rel_path, _to_u(cmd['exe']))
                else:
                    html = html + '<li>%s</li>\n' % (_to_u(cmd['exe']))
            html = html + "</ul></p>\n"

        # Alerts
        if len(self.alerts):
            html = html + "<p>Alerts:<br><ul>\n"
            for alert in self.alerts:
                html = html + '<li>%s</li>\n' % _to_u(alert)
            html = html + "</ul></p>\n"

        # Custom Text
        if self.custom_text != "":
            html = html + "<p>Additional Information:<br>\n"
            html = html + _to_u(self.custom_text) + "</p>\n"

        if six.PY2:
            return html.encode('utf8')
        else:
            return html
1021518
protected function registerStatsD()
    {
        $this->app->singleton('statsd',
            function ($app) {
                // Set Default host and port
                $options = array();
                $config  = $app['config'];

                if (isset($config['statsd.host'])) {
                    $options['host'] = $config['statsd.host'];
                }

                if (isset($config['statsd.port'])) {
                    $options['port'] = $config['statsd.port'];
                }

                if (isset($config['statsd.namespace'])) {
                    $options['namespace'] = $config['statsd.namespace'];
                }

                if (isset($config['statsd.timeout'])) {
                    $options['timeout'] = $config['statsd.timeout'];
                }

                if (isset($config['statsd.throwConnectionExceptions'])) {
                    $options['throwConnectionExceptions'] = (boolean) $config['statsd.throwConnectionExceptions'];
                }

                // Create
                $statsd = new Statsd();
                $statsd->configure($options);
                return $statsd;
            }
        );

        $this->app->bind('League\StatsD\Client', function ($app) {
            return $app['statsd'];
        });
    }
261289
def bottlestats(server_name, path=''):
    """"""
    path = path.lstrip('/')
    parts = path.split('/')
    if not parts[0]:
        parts = parts[1:]
    stat_dict = util.lookup(scales.getStats(), parts)

    if stat_dict is None:
        abort(404, "Not Found")
        return

    output = StringIO()
    output_format = request.query.get('format', 'html')
    query = request.query.get('query', None)
    if output_format == 'json':
        response.content_type = "application/json"
        formats.jsonFormat(output, stat_dict, query)
    elif output_format == 'prettyjson':
        formats.jsonFormat(output, stat_dict, query, pretty=True)
        response.content_type = "application/json"
    else:
        formats.htmlHeader(output, '/' + path, server_name, query)
        formats.htmlFormat(output, tuple(parts), stat_dict, query)
        response.content_type = "text/html"

    return output.getvalue()
1254935
void statsEndRequest(long duration,boolean ok)
    {
        synchronized(_statsLock)
        {
            _requests++;
            _requestsActive--;
            if (_requestsActive<0)
                _requestsActive=0;
            if (_requestsActive < _requestsActiveMin)
                _requestsActiveMin=_requestsActive;
            
            if (ok)
            {
                _requestsDurationTotal+=duration;
                if (_requestsDurationMin==0 || duration<_requestsDurationMin)
                    _requestsDurationMin=duration;
                if (duration>_requestsDurationMax)
                    _requestsDurationMax=duration;
            }
            else
                _errors++;
        }
    }
977190
def configure(host=DEFAULT_HOST, port=DEFAULT_PORT, prefix=''):
    
    global _client
    logging.info("Reconfiguring metrics: {}:{}/{}".format(host, port, prefix))
    _client = statsdclient.StatsdClient(host, port, prefix)
251095
def report(self):
        
        table = [["Mails", "Metric"]]
        table.append(["Found", self.stats['mail_found']])
        table.append(["Skipped", self.stats['mail_skipped']])
        table.append(["Rejected", self.stats['mail_rejected']])
        table.append(["Kept", self.stats['mail_kept']])
        table.append(["Unique", self.stats['mail_unique']])
        table.append(["Duplicates", self.stats['mail_duplicates']])
        table.append(["Deleted", self.stats['mail_deleted']])
        logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow'))

        table = [["Duplicate sets", "Metric"]]
        table.append(["Total", self.stats['set_total']])
        table.append(["Ignored", self.stats['set_ignored']])
        table.append(["Skipped", self.stats['set_skipped']])
        table.append([
            "Rejected (bad encoding)",
            self.stats['set_rejected_encoding']])
        table.append([
            "Rejected (too dissimilar in size)",
            self.stats['set_rejected_size']])
        table.append([
            "Rejected (too dissimilar in content)",
            self.stats['set_rejected_content']])
        table.append(["Deduplicated", self.stats['set_deduplicated']])
        logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow'))

        # Perform some high-level consistency checks on metrics.
        assert self.stats['mail_found'] == (
            self.stats['mail_skipped'] +
            self.stats['mail_rejected'] +
            self.stats['mail_kept'])
        assert self.stats['mail_kept'] >= self.stats['mail_unique']
        assert self.stats['mail_kept'] >= self.stats['mail_duplicates']
        assert self.stats['mail_kept'] >= self.stats['mail_deleted']
        assert self.stats['mail_kept'] == (
            self.stats['mail_unique'] +
            self.stats['mail_duplicates'])
        assert self.stats['mail_duplicates'] > self.stats['mail_deleted']

        assert self.stats['set_ignored'] == self.stats['mail_unique']

        assert self.stats['set_total'] == (
            self.stats['set_ignored'] +
            self.stats['set_skipped'] +
            self.stats['set_rejected_encoding'] +
            self.stats['set_rejected_size'] +
            self.stats['set_rejected_content'] +
            self.stats['set_deduplicated'])
823876
def clean_report(self, options, sosreport): # pragma: no cover
        ''''''

        if options.report_dir: # override the default location for artifacts (/tmp)
            if os.path.isdir(options.report_dir):
                self.report_dir = options.report_dir
        self.origin_path, self.dir_path, self.session, self.logfile, self.uuid = self._prep_environment()
        self._start_logging(self.logfile)
        self._get_disclaimer()
        if options.domains:
            self.domains = options.domains
        if options.keywords:
            self.keywords = options.keywords
            self._keywords2db()
        if not sosreport:
            if not options.files:
                raise Exception("Error: You must supply either an sosreport and/or files to process")

            self.logger.con_out("No sosreport supplied. Only processing specific files")
            self._clean_files_only(options.files)

        else:   # we DO have an sosreport to analyze
            self.report = self._extract_sosreport(sosreport)
            self._make_dest_env()   # create the working directory
            if options.hostname_path:
                self.hostname, self.domainname = self._get_hostname(options.hostname_path)
            else:
                self.hostname, self.domainname = self._get_hostname()

            if options.files:
                self._add_extra_files(options.files)

            if self.hostname:   # if we have a hostname that's not a None type
                self.hn_db['host0'] = self.hostname     # we'll prime the hostname pump to clear out a ton of useless logic later

            self._process_hosts_file()  # we'll take a dig through the hosts file and make sure it is as scrubbed as possible

        self._domains2db()
        files = self._file_list(self.dir_path)
        self.logger.con_out("IP Obfuscation Start Address - %s", self.start_ip)
        self.logger.con_out("*** SOSCleaner Processing ***")
        self.logger.info("Working Directory - %s", self.dir_path)
        for f in files:
            self.logger.debug("Cleaning %s", f)
            self._clean_file(f)
        self.logger.con_out("*** SOSCleaner Statistics ***")
        self.logger.con_out("IP Addresses Obfuscated - %s", len(self.ip_db))
        self.logger.con_out("Hostnames Obfuscated - %s" , len(self.hn_db))
        self.logger.con_out("Domains Obfuscated - %s" , len(self.dn_db))
        self.logger.con_out("Total Files Analyzed - %s", self.file_count)
        self.logger.con_out("*** SOSCleaner Artifacts ***")
        self._create_reports()
        self._create_archive()

        return_data = [self.archive_path, self.logfile, self.ip_report]
        if self.hostname:
            return_data.append(self.hn_report)
        if len(self.dn_db) >= 1:
            return_data.append(self.dn_report)

        return return_data
1065035
def write_stats (self):
        """"""
        self.writeln()
        self.writeln(_("Statistics:"))
        if self.stats.downloaded_bytes is not None:
            self.writeln(_("Downloaded: %s.") % strformat.strsize(self.stats.downloaded_bytes))
        if self.stats.number > 0:
            self.writeln(_(
              "Content types: %(image)d image, %(text)d text, %(video)d video, "
              "%(audio)d audio, %(application)d application, %(mail)d mail"
              " and %(other)d other.") % self.stats.link_types)
            self.writeln(_("URL lengths: min=%(min)d, max=%(max)d, avg=%(avg)d.") %
                         dict(min=self.stats.min_url_length,
                         max=self.stats.max_url_length,
                         avg=self.stats.avg_url_length))
        else:
            self.writeln(_("No statistics available since no URLs were checked."))
962676
function stats(resultSet) {
      var response = {};
      if (resultSetIsEmpty(resultSet)) return response;

      // add references to the retrieved server
      response.server = this.serverAddress;

      // Fill the object
      resultSet.forEach(function each(statSet) {
        if (statSet) response[statSet[0]] = statSet[1];
      });

      return response;
    }
1227145
def _setup_stats(self):
        '''
        
        '''
        self.stats_dict = {}

        redis_conn = redis.Redis(host=self.settings['REDIS_HOST'],
                                 port=self.settings['REDIS_PORT'],
                                 db=self.settings.get('REDIS_DB'))

        try:
            redis_conn.info()
            self.logger.debug("Connected to Redis in StatsCollector Setup")
            self.redis_conn = redis_conn
        except ConnectionError:
            self.logger.warn("Failed to connect to Redis in StatsCollector"
                             " Setup, no stats will be collected")
            return

        if self.settings['STATS_TOTAL']:
            self._setup_stats_total(redis_conn)

        if self.settings['STATS_PLUGINS']:
            self._setup_stats_plugins(redis_conn)
700628
def WriteClientStats(self, client_id,
                       stats):
    """"""
    if client_id not in self.ReadAllClientIDs():
      raise db.UnknownClientError(client_id)

    self.client_stats[client_id][rdfvalue.RDFDatetime.Now()] = stats
1195334
def _report_self(self):
        
        if self.redis_connected:
            self.logger.debug("Reporting self to redis")
            try:
                key = "stats:rest:self:{m}:{u}".format(
                    m=socket.gethostname(),
                    u=self.my_uuid)
                self.redis_conn.set(key, self.get_time())
                self.redis_conn.expire(key, self.settings['HEARTBEAT_TIMEOUT'])
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
        else:
            self.logger.warn("Cannot report self to redis, not connected")
630186
private void reportStats(PolicyStats stats) throws IOException {
    reporter.add(stats);
    if (--remaining == 0) {
      reporter.print();
      context().stop(self());
      System.out.println("Executed in " + stopwatch);
    }
  }
162779
public GetDomainStatisticsResponse getDomainStatistics(GetDomainStatisticsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS,
                LIVE_DOMAIN, request.getDomain());
        if (request.getStartDate() != null) {
            internalRequest.addParameter("startDate", request.getStartDate());
        }
        if (request.getEndDate() != null) {
            internalRequest.addParameter("endDate", request.getEndDate());
        }
        if (request.getAggregate() != null) {
            internalRequest.addParameter("aggregate", request.getAggregate().toString());
        }
        return invokeHttpClient(internalRequest, GetDomainStatisticsResponse.class);
    }
1288922
def stats(self, request):
        '''
        '''
        # scheme = 'wss' if request.is_secure else 'ws'
        # host = request.get('HTTP_HOST')
        # address = '%s://%s/stats' % (scheme, host)
        doc = HtmlDocument(title='Live server stats', media_path='/assets/')
        # docs.head.scripts
        return doc.http_response(request)