// ReadStatsdDatagramSocket reads statsd metrics packets from connection off a unix datagram socket.
195465
func (s *Server) ReadStatsdDatagramSocket(serverConn *net.UnixConn, packetPool *sync.Pool) {
	for {
		buf := packetPool.Get().([]byte)
		n, _, err := serverConn.ReadFromUnix(buf)
		if err != nil {
			select {
			case <-s.shutdown:
				log.WithError(err).Info("Ignoring ReadFrom error while shutting down")
				return
			default:
				log.WithError(err).Error("Error reading packet from Unix domain socket")
				continue
			}
		}

		s.processMetricPacket(n, buf, packetPool)
	}
}
866383
func (e *Endpoint) ReadMetrics(em *EndpointMetrics) {
	e.metrics.Lock()
	defer e.metrics.Unlock()

	*em = e.metrics.EndpointMetrics
	// Map still need to copied in a threadsafe manner.
	em.Statuses = make(map[string]int)
	for k, v := range e.metrics.Statuses {
		em.Statuses[k] = v
	}
}
732498
func emitDatapointsOverStatsd(datapoints []producers.Datapoint, client *statsd.StatsdClient) error {
	data := make(map[string]string)
	for _, dp := range datapoints {
		name, val, ok := convertDatapointToStatsd(dp)
		// we silently drop metrics which could not be converted
		if ok {
			data[name] = val
		}
	}
	client.Send(data, 1)
	return nil
}
608669
func (s *Server) ReadSSFPacketSocket(serverConn net.PacketConn, packetPool *sync.Pool) {
	// TODO This is duplicated from ReadMetricSocket and feels like it could be it's
	// own function?
	p := packetPool.Get().([]byte)
	if len(p) == 0 {
		log.WithField("len", len(p)).Fatal(
			"packetPool making empty slices: trace_max_length_bytes must be >= 0")
	}
	packetPool.Put(p)

	for {
		buf := packetPool.Get().([]byte)
		n, _, err := serverConn.ReadFrom(buf)
		if err != nil {
			// In tests, the probably-best way to
			// terminate this reader is to issue a shutdown and close the listening
			// socket, which returns an error, so let's handle it here:
			select {
			case <-s.shutdown:
				log.WithError(err).Info("Ignoring ReadFrom error while shutting down")
				return
			default:
				log.WithError(err).Error("Error reading from UDP trace socket")
				continue
			}
		}

		s.HandleTracePacket(buf[:n])
		packetPool.Put(buf)
	}
}
724269
func ReadStats(sysfs string) ([]*Stats, error) {
	matches, err := filepath.Glob(path.Join(sysfs, "fs/bcache/*-*"))
	if err != nil {
		return nil, err
	}

	stats := make([]*Stats, 0, len(matches))
	for _, uuidPath := range matches {
		// "*-*" in glob above indicates the name of the bcache.
		name := filepath.Base(uuidPath)

		// stats
		s, err := GetStats(uuidPath)
		if err != nil {
			return nil, err
		}

		s.Name = name
		stats = append(stats, s)
	}

	return stats, nil
}
676878
func (p *Provider) ReadDataDiff(
	info *terraform.InstanceInfo,
	c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) {

	r, ok := p.DataSourcesMap[info.Type]
	if !ok {
		return nil, fmt.Errorf("unknown data source: %s", info.Type)
	}

	return r.Diff(nil, c, p.meta)
}
315108
func assertGetDatagram(le *logpb.LogEntry) *logpb.Datagram {
	if dg := le.GetDatagram(); dg == nil {
		panic(
			errors.Annotate(
				InvalidStreamType,
				fmt.Sprintf("got %T, expected *logpb.LogEntry_Datagram", le.Content),
			).Err(),
		)
	} else {
		return dg
	}
}
1050493
func (c *Client) GetMetricsSnapshot(pid *Pid) (*MetricsSnapshot, error) {
	u := c.GetURLForMetricsSnapshotPid(*pid)
	resp, err := c.GetHTTPResponse(&u)
	return c.parseMetricsSnapshotResponse(resp, err)
}
915047
func (gc *GenericChannelAspect) GetStats() interface{} {
	gc.gcdLock.RLock()
	defer gc.gcdLock.RUnlock()

	var mod bytes.Buffer
	enc := gob.NewEncoder(&mod)
	dec := gob.NewDecoder(&mod)

	err := enc.Encode(gc.Gcd)
	if err != nil {
		return err
	}

	var cpy map[string]GenericChannelData
	err = dec.Decode(&cpy)
	if err != nil {
		return err
	}

	return cpy
}
654515
func (shardSwap *shardSchemaSwap) readShardMetadata(metadata *shardSwapMetadata, waitGroup *sync.WaitGroup) {
	defer waitGroup.Done()

	tablet, err := shardSwap.getMasterTablet()
	if err != nil {
		metadata.err = err
		return
	}
	query := fmt.Sprintf(
		"SELECT name, value FROM _vt.shard_metadata WHERE db_name = '%s' and name in ('%s', '%s', '%s')",
		topoproto.TabletDbName(tablet), lastStartedMetadataName, lastFinishedMetadataName, currentSQLMetadataName)
	queryResult, err := shardSwap.executeAdminQuery(tablet, query, 3 /* maxRows */)
	if err != nil {
		metadata.err = err
		return
	}
	for _, row := range queryResult.Rows {
		switch row[0].ToString() {
		case lastStartedMetadataName:
			swapID, err := sqltypes.ToUint64(row[1])
			if err != nil {
				log.Warningf("Could not parse value of last started schema swap id %v, ignoring the value: %v", row[1], err)
			} else {
				metadata.lastStartedSwap = swapID
			}
		case lastFinishedMetadataName:
			swapID, err := sqltypes.ToUint64(row[1])
			if err != nil {
				log.Warningf("Could not parse value of last finished schema swap id %v, ignoring the value: %v", row[1], err)
			} else {
				metadata.lastFinishedSwap = swapID
			}
		case currentSQLMetadataName:
			metadata.currentSQL = row[1].ToString()
		}
	}
}
754557
func (c *StatsConnection) GetNodeStats() (*api.NodeStats, error) {
	stats, err := c.statsClient.DumpStats(NodeStatsPrefix)
	if err != nil {
		return nil, err
	}

	nodeStats := &api.NodeStats{}

	var setPerNode = func(perNode []uint64, fn func(c *api.NodeCounters, v uint64)) {
		if nodeStats.Nodes == nil {
			nodeStats.Nodes = make([]api.NodeCounters, len(perNode))
			for i := range perNode {
				nodeStats.Nodes[i].NodeIndex = uint32(i)
			}
		}
		for i, v := range perNode {
			if len(nodeStats.Nodes) <= i {
				break
			}
			nodeCounters := nodeStats.Nodes[i]
			fn(&nodeCounters, v)
			nodeStats.Nodes[i] = nodeCounters
		}
	}

	for _, stat := range stats {
		switch stat.Name {
		case NodeStats_Names:
			if names, ok := stat.Data.(adapter.NameStat); !ok {
				return nil, fmt.Errorf("invalid stat type for %s", stat.Name)
			} else {
				if nodeStats.Nodes == nil {
					nodeStats.Nodes = make([]api.NodeCounters, len(names))
					for i := range names {
						nodeStats.Nodes[i].NodeIndex = uint32(i)
					}
				}
				for i, name := range names {
					nodeStats.Nodes[i].NodeName = string(name)
				}
			}
		case NodeStats_Clocks:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Clocks = v
			})
		case NodeStats_Vectors:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Vectors = v
			})
		case NodeStats_Calls:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Calls = v
			})
		case NodeStats_Suspends:
			setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
				c.Suspends = v
			})
		}
	}

	return nodeStats, nil
}
499624
func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error {
	if err := s.processFlags(flags); err != nil {
		return err
	}

	// Check that our recv window is not exceeded
	length := hdr.Length()
	if length == 0 {
		return nil
	}

	// Wrap in a limited reader
	conn = &io.LimitedReader{R: conn, N: int64(length)}

	// Copy into buffer
	s.recvLock.Lock()

	if length > s.recvWindow {
		s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length)
		return ErrRecvWindowExceeded
	}

	if s.recvBuf == nil {
		// Allocate the receive buffer just-in-time to fit the full data frame.
		// This way we can read in the whole packet without further allocations.
		s.recvBuf = bytes.NewBuffer(make([]byte, 0, length))
	}
	if _, err := io.Copy(s.recvBuf, conn); err != nil {
		s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err)
		s.recvLock.Unlock()
		return err
	}

	// Decrement the receive window
	s.recvWindow -= length
	s.recvLock.Unlock()

	// Unblock any readers
	asyncNotify(s.recvNotifyCh)
	return nil
}
491540
func NewStatsdBuffer(interval time.Duration, client Statsd) *StatsdBuffer {
	sb := &StatsdBuffer{
		flushInterval: interval,
		statsd:        client,
		eventChannel:  make(chan event.Event, 100),
		events:        make(map[string]event.Event),
		closeChannel:  make(chan closeRequest),
		Logger:        log.New(os.Stdout, "[BufferedStatsdClient] ", log.Ldate|log.Ltime),
		Verbose:       true,
	}
	go sb.collector()
	return sb
}
665560
func (s *Server) ReadSSFStreamSocket(serverConn net.Conn) {
	defer func() {
		serverConn.Close()
	}()

	// initialize the capacity to the max size
	// based on the number of tags we add later
	tags := make([]string, 1, 3)
	tags[0] = "ssf_format:framed"

	for {
		msg, err := protocol.ReadSSF(serverConn)
		if err != nil {
			if err == io.EOF {
				// Client hangup, close this
				s.Statsd.Count("frames.disconnects", 1, nil, 1.0)
				return
			}
			if protocol.IsFramingError(err) {
				log.WithError(err).
					WithField("remote", serverConn.RemoteAddr()).
					Info("Frame error reading from SSF connection. Closing.")
				tags = append(tags, []string{"packet_type:unknown", "reason:framing"}...)
				s.Statsd.Incr("ssf.error_total", tags, 1.0)
				return
			}
			// Non-frame errors means we can continue reading:
			log.WithError(err).
				WithField("remote", serverConn.RemoteAddr()).
				Error("Error processing an SSF frame")
			tags = append(tags, []string{"packet_type:unknown", "reason:processing"}...)
			s.Statsd.Incr("ssf.error_total", tags, 1.0)
			tags = tags[:1]
			continue
		}
		s.handleSSF(msg, "framed")
	}
}
1011182
func ReadDiskStats(stats *DiskStats) error {
	// Open the process disk IO counter file
	inf, err := os.Open(fmt.Sprintf("/proc/%d/io", os.Getpid()))
	if err != nil {
		return err
	}
	defer inf.Close()
	in := bufio.NewReader(inf)

	// Iterate over the IO counter, and extract what we need
	for {
		// Read the next line and split to key and value
		line, err := in.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
		parts := strings.Split(line, ":")
		if len(parts) != 2 {
			continue
		}
		key := strings.TrimSpace(parts[0])
		value, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
		if err != nil {
			return err
		}

		// Update the counter based on the key
		switch key {
		case "syscr":
			stats.ReadCount = value
		case "syscw":
			stats.WriteCount = value
		case "rchar":
			stats.ReadBytes = value
		case "wchar":
			stats.WriteBytes = value
		}
	}
}
544164
func ReadDSFTags(r io.ReadSeeker) (Metadata, error) {
	dsd, err := readString(r, 4)
	if err != nil {
		return nil, err
	}
	if dsd != "DSD " {
		return nil, errors.New("expected 'DSD '")
	}

	_, err = r.Seek(int64(16), io.SeekCurrent)
	if err != nil {
		return nil, err
	}

	n4, err := readBytes(r, 8)
	if err != nil {
		return nil, err
	}
	id3Pointer := getIntLittleEndian(n4)

	_, err = r.Seek(int64(id3Pointer), io.SeekStart)
	if err != nil {
		return nil, err
	}

	id3, err := ReadID3v2Tags(r)
	if err != nil {
		return nil, err
	}

	return metadataDSF{id3}, nil
}
1022762
func NewStatsd(addr, prefix string) (*Statsd, error) {
	c, err := statsd.NewClient(addr, prefix)
	if err != nil {
		return nil, err
	}
	return &Statsd{
		client: c,
	}, nil
}