Request stats from HAProxy Server
972585
def http_get_csv_data(self, section=None):
        
        metrics = []
        req = urllib2.Request(self._get_config_value(section, 'url'))
        try:
            handle = urllib2.urlopen(req)
            return handle.readlines()
        except Exception as e:
            if not hasattr(e, 'code') or e.code != 401:
                self.log.error("Error retrieving HAProxy stats. %s", e)
                return metrics

        # get the www-authenticate line from the headers
        # which has the authentication scheme and realm in it
        authline = e.headers['www-authenticate']

        # this regular expression is used to extract scheme and realm
        authre = (r'''(?:\s*www-authenticate\s*:)?\s*''' +
                  '''(\w*)\s+realm=['"]([^'"]+)['"]''')
        authobj = re.compile(authre, re.IGNORECASE)
        matchobj = authobj.match(authline)
        if not matchobj:
            # if the authline isn't matched by the regular expression
            # then something is wrong
            self.log.error('The authentication header is malformed.')
            return metrics

        scheme = matchobj.group(1)
        # here we've extracted the scheme
        # and the realm from the header
        if scheme.lower() != 'basic':
            self.log.error('Invalid authentication scheme.')
            return metrics

        base64string = base64.encodestring(
            '%s:%s' % (self._get_config_value(section, 'user'),
                       self._get_config_value(section, 'pass')))[:-1]
        authheader = 'Basic %s' % base64string
        req.add_header("Authorization", authheader)
        try:
            handle = urllib2.urlopen(req)
            metrics = handle.readlines()
            return metrics
        except IOError as e:
            # here we shouldn't fail if the USER/PASS is right
            self.log.error("Error retrieving HAProxy stats. " +
                           "(Invalid username or password?) %s", e)
            return metrics
1356686
function () {
    var self = this;

    // For the reported client address for a connection to be correct,
    // the developer must set the HTTP_FORWARDED_COUNT environment
    // variable to an integer representing the number of hops they
    // expect in the `x-forwarded-for` header. E.g., set to "1" if the
    // server is behind one proxy.
    //
    // This could be computed once at startup instead of every time.
    var httpForwardedCount = parseInt(process.env['HTTP_FORWARDED_COUNT']) || 0;

    if (httpForwardedCount === 0)
      return self.socket.remoteAddress;

    var forwardedFor = self.socket.headers["x-forwarded-for"];
    if (! _.isString(forwardedFor))
      return null;
    forwardedFor = forwardedFor.trim().split(/\s*,\s*/);

    // Typically the first value in the `x-forwarded-for` header is
    // the original IP address of the client connecting to the first
    // proxy.  However, the end user can easily spoof the header, in
    // which case the first value(s) will be the fake IP address from
    // the user pretending to be a proxy reporting the original IP
    // address value.  By counting HTTP_FORWARDED_COUNT back from the
    // end of the list, we ensure that we get the IP address being
    // reported by *our* first proxy.

    if (httpForwardedCount < 0 || httpForwardedCount > forwardedFor.length)
      return null;

    return forwardedFor[forwardedFor.length - httpForwardedCount];
  }
630707
function getStats () {
        pc.getStats(function (res) {
            var items = [];
            var connectionType = {};

            res.result().forEach(function (result) {
                var item = {};
                result.names().forEach(function (name) {
                    item[name] = result.stat(name);
                });
                item.id = result.id;
                item.type = result.type;
                item.timestamp = result.timestamp;

                if (item.type === 'googCandidatePair' && item.googActiveConnection === 'true') {
                    connectionType = {
                        local: {
                            candidateType: item.googLocalCandidateType,
                            ipAddress: item.googLocalAddress
                        },
                        remote: {
                            candidateType: item.googRemoteCandidateType,
                            ipAddress: item.googRemoteAddress
                        },
                        transport: item.googTransportType
                    };

                    return;
                }

                items.push(item);
            });

            traceStats(items);
            window._webdriverrtcTimeout = setTimeout(getStats.bind(window, items), interval);

            if (typeof cb === 'function') {
                cb(connectionType);
                cb = undefined;
            }
        });
    }
1048829
def traffic(stack_name: str,
            stack_version: Optional[str],
            percentage: Optional[int],
            region: Optional[str],
            remote: Optional[str],
            output: Optional[str]):
    ''''''
    lizzy = setup_lizzy_client(remote)

    if percentage is None:
        stack_reference = [stack_name]

        with Action('Requesting traffic info..'):
            stack_weights = []
            for stack in lizzy.get_stacks(stack_reference, region=region):
                if stack['status'] in ['CREATE_COMPLETE', 'UPDATE_COMPLETE']:
                    stack_id = '{stack_name}-{version}'.format_map(stack)
                    traffic = lizzy.get_traffic(stack_id, region=region)
                    stack_weights.append({
                        'stack_name': stack_name,
                        'version': stack['version'],
                        'identifier': stack_id,
                        'weight%': traffic['weight']
                    })
        cols = 'stack_name version identifier weight%'.split()
        with OutputFormat(output):
            print_table(cols,
                        sorted(stack_weights, key=lambda x: x['identifier']))
    else:
        with Action('Requesting traffic change..'):
            stack_id = '{stack_name}-{stack_version}'.format_map(locals())
            lizzy.traffic(stack_id, percentage, region=region)
307585
function displayPerformance(req) {
    let logger = Semotus.createLogger();

    logger.setContextProps(req.amorphicTracking.loggingContext);

    let diff = process.hrtime(req.amorphicTracking.startTime);
    let totalTime = (diff[0] * 1e9 + diff[1]) / 1000000;
    let taskTime = 0;

    req.amorphicTracking.serverTasks.forEach(function d(task) {
        taskTime += task.time;
    });

    logger.info({
        component: 'amorphic',
        module: 'listen',
        duration: totalTime,
        browserPerformance: req.amorphicTracking.browser,
        serverTasks: req.amorphicTracking.serverTasks,
        unaccounted: totalTime - taskTime},
        'Request Performance');
}
1268471
def retrieveVals(self):
        """"""   
        nginxInfo = NginxInfo(self._host, self._port,
                                self._user, self._password, 
                                self._statuspath, self._ssl)
        stats = nginxInfo.getServerStats()
        if stats:
            if self.hasGraph('nginx_activeconn'):
                self.setGraphVal('nginx_activeconn', 'proc', stats['writing'])
                self.setGraphVal('nginx_activeconn', 'read', stats['reading'])
                self.setGraphVal('nginx_activeconn', 'wait', stats['waiting'])
                self.setGraphVal('nginx_activeconn', 'total', 
                                 stats['connections'])
            if self.hasGraph('nginx_connections'):
                self.setGraphVal('nginx_connections', 'handled', stats['handled'])
                self.setGraphVal('nginx_connections', 'nothandled', 
                                 stats['accepts'] - stats['handled'])
            if self.hasGraph('nginx_requests'):
                self.setGraphVal('nginx_requests', 'requests', stats['requests'])
            if self.hasGraph('nginx_requestsperconn'):
                curr_stats = (stats['handled'], stats['requests'])
                hist_stats = self.restoreState()
                if hist_stats:
                    prev_stats = hist_stats[0]
                else:
                    hist_stats = []
                    prev_stats = (0,0)
                conns = max(curr_stats[0] - prev_stats[0], 0)
                reqs = max(curr_stats[1] - prev_stats[1], 0)
                if conns > 0:
                    self.setGraphVal('nginx_requestsperconn', 'requests',
                                     float(reqs) / float(conns))
                else:
                    self.setGraphVal('nginx_requestsperconn', 'requests', 0)
                hist_stats.append(curr_stats)
                self.saveState(hist_stats[-self._numSamples:])
480021
def _retrieve(self, map):
        
        self._conn.request('GET', "cache_object://%s/%s" % (self._host, map), 
                           None, self._httpHeaders)
        rp = self._conn.getresponse()
        if rp.status == 200:
            data = rp.read()
            return data
        else:
            raise Exception("Retrieval of stats from Squid Proxy Server"
                            "on host %s and port %s failed.\n"
                            "HTTP - Status: %s    Reason: %s" 
                            % (self._host, self._port, rp.status, rp.reason))
661091
def ProcessClientResourcesStats(self, client_id, status):
    
    if hasattr(status, "child_session_id"):
      flow_path = status.child_session_id
    else:
      flow_path = "aff4:/%s/flows/%s" % (status.client_id, status.flow_id)

    resources = rdf_client_stats.ClientResources()
    resources.client_id = client_id
    resources.session_id = flow_path
    resources.cpu_usage.user_cpu_time = status.cpu_time_used.user_cpu_time
    resources.cpu_usage.system_cpu_time = status.cpu_time_used.system_cpu_time
    resources.network_bytes_sent = status.network_bytes_sent
    self.context.usage_stats.RegisterResources(resources)
344676
def status(host=DEFAULT_HOST, port=DEFAULT_PORT):
    '''
    
    '''
    conn = _connect(host, port)
    try:
        stats = _check_stats(conn)[0]
    except (CommandExecutionError, IndexError):
        return False
    else:
        return {stats[0]: stats[1]}
37488
protected RequestStat createRequestStat() {
        BasicRequestStat basicRequestStat = new BasicRequestStat(origin.getName());
        RequestStat.putInSessionContext(basicRequestStat, context);
        return basicRequestStat;
    }
1340983
function getStatus(url, callback) {
  var client = new HttpClient(url);
  var executor = new Executor(client);
  var command = new Command(CommandName.GET_SERVER_STATUS);
  executor.execute(command, function(err, responseObj) {
    if (err) return callback(err);
    try {
      checkResponse(responseObj);
    } catch (ex) {
      return callback(ex);
    }
    callback(null, responseObj['value']);
  });
}
1247029
def initStats(self):
        """"""
        url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, 
                                 self._statuspath)
        response = util.get_url(url, self._user, self._password)
        self._statusDict = {}
        for line in response.splitlines():
            mobj = re.match('\s*(\d+)\s+(\d+)\s+(\d+)\s*$', line)
            if mobj:
                idx = 0
                for key in ('accepts','handled','requests'):
                    idx += 1
                    self._statusDict[key] = util.parse_value(mobj.group(idx))
            else:
                for (key,val) in re.findall('(\w+):\s*(\d+)', line):
                    self._statusDict[key.lower()] = util.parse_value(val)
21512
function Metrics(requests) {
  this.requests = requests;             // The total amount of requests send

  this.connections = 0;                 // Connections established
  this.disconnects = 0;                 // Closed connections
  this.failures = 0;                    // Connections that received an error

  this.errors = Object.create(null);    // Collection of different errors
  this.timing = Object.create(null);    // Different timings

  this.latency = new Stats();           // Latencies of the echo'd messages
  this.handshaking = new Stats();       // Handshake duration

  this.read = 0;                        // Bytes read
  this.send = 0;                        // Bytes send

  // Start tracking
  this.start();
}
849004
def post_stats(cls, stats_url, stats, timeout=2, auth_provider=None):
    
    def error(msg):
      # Report aleady closed, so just print error.
      print('WARNING: Failed to upload stats to {}. due to {}'.format(stats_url, msg),
            file=sys.stderr)
      return False

    # TODO(benjy): The upload protocol currently requires separate top-level params, with JSON
    # values.  Probably better for there to be one top-level JSON value, namely json.dumps(stats).
    # But this will first require changing the upload receiver at every shop that uses this.
    params = {k: cls._json_dump_options(v) for (k, v) in stats.items()}
    cookies = Cookies.global_instance()
    auth_provider = auth_provider or '<provider>'

    # We can't simply let requests handle redirects, as we only allow them for specific codes:
    # 307 and 308 indicate that the redirected request must use the same method, POST in this case.
    # So they indicate a true redirect of the POST itself, and we allow them.
    # The other redirect codes either must, or in practice do, cause the user agent to switch the
    # method to GET. So when they are encountered on a POST, it indicates an auth problem (a
    # redirection to a login page).
    def do_post(url, num_redirects_allowed):
      if num_redirects_allowed < 0:
        return error('too many redirects.')
      r = requests.post(url, data=params, timeout=timeout,
                        cookies=cookies.get_cookie_jar(), allow_redirects=False)
      if r.status_code in {307, 308}:
        return do_post(r.headers['location'], num_redirects_allowed - 1)
      elif r.status_code != 200:
        error('HTTP error code: {}. Reason: {}.'.format(r.status_code, r.reason))
        if 300 <= r.status_code < 400 or r.status_code == 401:
          print('Use `path/to/pants login --to={}` to authenticate against the stats '
                'upload service.'.format(auth_provider), file=sys.stderr)
        return False
      return True

    try:
      return do_post(stats_url, num_redirects_allowed=6)
    except Exception as e:  # Broad catch - we don't want to fail the build over upload errors.
      return error('Error: {}'.format(e))
124428
def get_status(self):
        """"""
        headers = {
            "X-AppName": "MusicCast/0.1(python)",
            "X-AppPort": str(self._udp_port)
        }
        req_url = ENDPOINTS["getStatus"].format(self.ip_address, 'main')
        return request(req_url, headers=headers)
1271434
def issues_stats(self):
        
        response = self.requester.get(
            '/{endpoint}/{id}/issues_stats',
            endpoint=self.endpoint, id=self.id
        )
        return response.json()
900627
public synchronized ConMgrStats getStats ()
    {
        // fill in our snapshot values
        _stats.connectionCount = _connections.size();
        _stats.handlerCount = _handlers.size();
        _stats.deathQueueSize = _deathq.size();
        _stats.outQueueSize = _outq.size();
        if (_oflowqs.size() > 0) {
            _stats.overQueueSize = 0;
            for (OverflowQueue oq : _oflowqs.values()) {
                _stats.overQueueSize += oq.size();
            }
        }
        return _stats.clone();
    }