// HTTPStats returns the client's underlying httputil.StatsTransport, if in use.
// If another transport is being used, nil is returned.
431072
func (c *Client) HTTPStats() *httputil.StatsTransport {
	st, _ := c.httpClient.Transport.(*httputil.StatsTransport)
	return st
}
868260
func (dg *discoveryGateway) RegisterStats() {
	stats.NewGaugeDurationFunc(
		"TopologyWatcherMaxRefreshLag",
		"maximum time since the topology watcher refreshed a cell",
		dg.topologyWatcherMaxRefreshLag,
	)

	stats.NewGaugeFunc(
		"TopologyWatcherChecksum",
		"crc32 checksum of the topology watcher state",
		dg.topologyWatcherChecksum,
	)
}
1283
func NewStatsClient(cr statscollector.Collector) (StatsClient, error) {

	sc := &statsClient{
		collector:     cr,
		rpchdl:        rpcwrapper.NewRPCWrapper(),
		secret:        os.Getenv(constants.EnvStatsSecret),
		statsChannel:  os.Getenv(constants.EnvStatsChannel),
		statsInterval: defaultStatsIntervalMiliseconds * time.Millisecond,
		userRetention: defaultUserRetention * time.Minute,
		stop:          make(chan bool),
	}

	if sc.statsChannel == "" {
		return nil, errors.New("no path to stats socket provided")
	}

	if sc.secret == "" {
		return nil, errors.New("no secret provided for stats channel")
	}

	return sc, nil
}
436239
func (s *CustomOriginConfig) SetHTTPSPort(v int64) *CustomOriginConfig {
	s.HTTPSPort = &v
	return s
}
1126963
func (u *User) RequestStats() {
	packet := MumbleProto.UserStats{
		Session: &u.Session,
	}
	u.client.Conn.WriteProto(&packet)
}
452656
func (ds *dockerService) ContainerStats(_ context.Context, r *runtimeapi.ContainerStatsRequest) (*runtimeapi.ContainerStatsResponse, error) {
	stats, err := ds.getContainerStats(r.ContainerId)
	if err != nil {
		return nil, err
	}
	return &runtimeapi.ContainerStatsResponse{Stats: stats}, nil
}
196337
func RequestStats() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		c.Next()

		req := metrics.GetOrRegisterMeter(ginRequestMetric, nil)
		req.Mark(1)

		latency := metrics.GetOrRegisterTimer(ginLatencyMetric, nil)
		latency.UpdateSince(start)

		status := metrics.GetOrRegisterMeter(fmt.Sprintf("%s.%d", ginStatusMetric, c.Writer.Status()), nil)
		status.Mark(1)
	}
}
1321769
func (c *Client) Stat(ctx context.Context, key, container string) (size int64, reterr error) {
	req := newReq(ctx, c.keyURL(container, key))
	req.Method = "HEAD"
	c.Auth.SignRequest(req)
	res, err := c.transport().RoundTrip(req)
	if err != nil {
		return 0, err
	}
	if res.Body != nil {
		defer res.Body.Close()
	}
	switch res.StatusCode {
	case http.StatusNotFound:
		return 0, os.ErrNotExist
	case http.StatusOK:
		return strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64)
	}
	return 0, fmt.Errorf("azure: Unexpected status code %d statting object %v", res.StatusCode, key)
}
1000093
func (c *ServerContext) reportStats(conn utils.Stater) {
	// Never emit session data events for the proxy or from a Teleport node if
	// sessions are being recorded at the proxy (this would result in double
	// events).
	if c.GetServer().Component() == teleport.ComponentProxy {
		return
	}
	if c.ClusterConfig.GetSessionRecording() == services.RecordAtProxy &&
		c.GetServer().Component() == teleport.ComponentNode {
		return
	}

	// Get the TX and RX bytes.
	txBytes, rxBytes := conn.Stat()

	// Build and emit session data event. Note that TX and RX are reversed
	// below, that is because the connection is held from the perspective of
	// the server not the client, but the logs are from the perspective of the
	// client.
	eventFields := events.EventFields{
		events.DataTransmitted: rxBytes,
		events.DataReceived:    txBytes,
		events.SessionServerID: c.GetServer().ID(),
		events.EventLogin:      c.Identity.Login,
		events.EventUser:       c.Identity.TeleportUser,
		events.LocalAddr:       c.Conn.LocalAddr().String(),
		events.RemoteAddr:      c.Conn.RemoteAddr().String(),
	}
	if c.session != nil {
		eventFields[events.SessionEventID] = c.session.id
	}
	c.GetServer().GetAuditLog().EmitAuditEvent(events.SessionData, eventFields)

	// Emit TX and RX bytes to their respective Prometheus counters.
	serverTX.Add(float64(txBytes))
	serverRX.Add(float64(rxBytes))
}
1188606
func sendStatsd(addr string, span *ssf.SSFSpan) error {
	client, err := statsd.New(addr)
	if err != nil {
		return err
	}
	// Report all the metrics in the span:
	for _, metric := range span.Metrics {
		tags := make([]string, 0, len(metric.Tags))
		for name, val := range metric.Tags {
			tags = append(tags, fmt.Sprintf("%s:%s", name, val))
		}
		switch metric.Metric {
		case ssf.SSFSample_COUNTER:
			err = client.Count(metric.Name, int64(metric.Value), tags, 1.0)
		case ssf.SSFSample_GAUGE:
			err = client.Gauge(metric.Name, float64(metric.Value), tags, 1.0)
		case ssf.SSFSample_HISTOGRAM:
			if metric.Unit == "ms" {
				// Treating the "ms" unit special is a
				// bit wonky, but it seems like the
				// right tool for the job here:
				err = client.TimeInMilliseconds(metric.Name, float64(metric.Value), tags, 1.0)
			} else {
				err = client.Histogram(metric.Name, float64(metric.Value), tags, 1.0)
			}
		case ssf.SSFSample_SET:
			err = client.Set(metric.Name, metric.Message, tags, 1.0)
		}
		if err != nil {
			return err
		}
	}
	return nil
}
281727
func (clnt *Client) Stats() (map[string]interface{}, error) {
	resStats := clnt.cluster.statsCopy()

	clusterStats := nodeStats{}
	for _, stats := range resStats {
		clusterStats.aggregate(&stats)
	}

	resStats["cluster-aggregated-stats"] = clusterStats

	b, err := json.Marshal(resStats)
	if err != nil {
		return nil, err
	}

	res := map[string]interface{}{}
	err = json.Unmarshal(b, &res)
	if err != nil {
		return nil, err
	}

	res["open-connections"] = clusterStats.ConnectionsOpen

	return res, nil
}
945460
func (s *Stat) NetIOStats() []*NetIOStats {
	s.Lock()
	defer s.Unlock()

	var res []*NetIOStats

	do(func() {
		var nSize C.size_t
		var cArray *C.sg_network_io_stats = C.sg_get_network_io_stats_diff(&nSize)
		length := int(nSize)
		slice := (*[1 << 16]C.sg_network_io_stats)(unsafe.Pointer(cArray))[:length:length]

		for _, v := range slice {
			n := &NetIOStats{
				IntName:    C.GoString(v.interface_name),
				TX:         int(v.tx),
				RX:         int(v.rx),
				IPackets:   int(v.ipackets),
				OPackets:   int(v.opackets),
				IErrors:    int(v.ierrors),
				OErrors:    int(v.oerrors),
				Collisions: int(v.collisions),
				Period:     time.Duration(int(v.systime)) * time.Second,
				TimeTaken:  time.Now(),
			}

			res = append(res, n)
		}
	})
	return res
}
1240326
func NewStatsdReporter(
	config *config.Config,
	serverType string,
	tagsMap map[string]string,
	clientOrNil ...Client,
) (*StatsdReporter, error) {
	host := config.GetString("pitaya.metrics.statsd.host")
	prefix := config.GetString("pitaya.metrics.statsd.prefix")
	rate, err := strconv.ParseFloat(config.GetString("pitaya.metrics.statsd.rate"), 64)
	if err != nil {
		return nil, err
	}
	sr := &StatsdReporter{
		rate:       rate,
		serverType: serverType,
	}

	sr.buildDefaultTags(tagsMap)

	if len(clientOrNil) > 0 {
		sr.client = clientOrNil[0]
	} else {
		c, err := statsd.New(host)
		if err != nil {
			return nil, err
		}
		c.Namespace = prefix
		sr.client = c
	}
	return sr, nil
}
899757
func (m *MockConnector) ConnectionStats() go_nats.Statistics {
	ret := m.ctrl.Call(m, "ConnectionStats")
	ret0, _ := ret[0].(go_nats.Statistics)
	return ret0
}
491771
func routeStat(r *client) *RouteStat {
	if r == nil {
		return nil
	}
	r.mu.Lock()
	rs := &RouteStat{
		ID: r.cid,
		Sent: DataStats{
			Msgs:  atomic.LoadInt64(&r.outMsgs),
			Bytes: atomic.LoadInt64(&r.outBytes),
		},
		Received: DataStats{
			Msgs:  atomic.LoadInt64(&r.inMsgs),
			Bytes: atomic.LoadInt64(&r.inBytes),
		},
		Pending: int(r.out.pb),
	}
	r.mu.Unlock()
	return rs
}
1266418
func (n *Node) ProtocolStats() ProtocolStats {
	timing := n.gossip.ProtocolTiming()
	return ProtocolStats{
		Timing{
			Type:     "histogram",
			Min:      timing.Min(),
			Max:      timing.Max(),
			Sum:      timing.Sum(),
			Variance: timing.Variance(),
			Mean:     timing.Mean(),
			StdDev:   timing.StdDev(),
			Count:    timing.Count(),
			Median:   timing.Percentile(0.5),
			P75:      timing.Percentile(0.75),
			P95:      timing.Percentile(0.95),
			P99:      timing.Percentile(0.99),
			P999:     timing.Percentile(0.999),
		},
		n.gossip.ProtocolRate(),
		n.clientRate.Rate1(),
		n.serverRate.Rate1(),
		n.totalRate.Rate1(),
	}
}
64711
func (cli *Client) ContainerStats(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) {
	query := url.Values{}
	query.Set("stream", "0")
	if stream {
		query.Set("stream", "1")
	}

	resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil)
	if err != nil {
		return types.ContainerStats{}, err
	}

	osType := getDockerOS(resp.header.Get("Server"))
	return types.ContainerStats{Body: resp.body, OSType: osType}, err
}