// Reads stats from all configured clusters. Accumulates stats.
// Returns one of the errors encountered while gathering stats (if any).
484609
func (r *Couchbase) Gather(acc telegraf.Accumulator) error {
	if len(r.Servers) == 0 {
		r.gatherServer("http://localhost:8091/", acc, nil)
		return nil
	}

	var wg sync.WaitGroup

	for _, serv := range r.Servers {
		wg.Add(1)
		go func(serv string) {
			defer wg.Done()
			acc.AddError(r.gatherServer(serv, acc, nil))
		}(serv)
	}

	wg.Wait()

	return nil
}
327912
func (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.StatsResponse, error) {
	log.G(ctx).Debugf("Stats: %s", r.ID)

	return nil, errdefs.ErrNotImplemented
}
160696
func (s *Store) Stats() (map[string]interface{}, error) {
	finfos, err := ioutil.ReadDir(s.dir)
	if err != nil {
		return nil, err
	}

	var numBytesUsedDisk uint64
	for _, finfo := range finfos {
		if !finfo.IsDir() {
			numBytesUsedDisk += uint64(finfo.Size())
		}
	}

	s.m.Lock()
	totPersists := s.totPersists
	totCompactions := s.totCompactions
	totCompactionsPartial := s.totCompactionsPartial
	numLastCompactionBeforeBytes := s.numLastCompactionBeforeBytes
	numLastCompactionAfterBytes := s.numLastCompactionAfterBytes
	totCompactionDecreaseBytes := s.totCompactionDecreaseBytes
	totCompactionIncreaseBytes := s.totCompactionIncreaseBytes
	maxCompactionDecreaseBytes := s.maxCompactionDecreaseBytes
	maxCompactionIncreaseBytes := s.maxCompactionIncreaseBytes
	totCompactionBeforeBytes := s.totCompactionBeforeBytes
	totCompactionWrittenBytes := s.totCompactionWrittenBytes
	s.m.Unlock()

	footer, err := s.snapshot()
	if err != nil {
		return nil, err
	}

	var numSegments uint64
	if footer != nil {
		footer.m.Lock()
		if footer.ss != nil {
			numSegments = uint64(len(footer.ss.a))
		}
		footer.m.Unlock()
	}

	footer.Close()

	files, numFilesOpen := s.allFiles()

	return map[string]interface{}{
		"num_bytes_used_disk":              numBytesUsedDisk,
		"total_persists":                   totPersists,
		"total_compactions":                totCompactions,
		"total_compactions_partial":        totCompactionsPartial,
		"total_compaction_before_bytes":    totCompactionBeforeBytes,
		"total_compaction_written_bytes":   totCompactionWrittenBytes,
		"num_segments":                     numSegments,
		"num_last_compaction_before_bytes": numLastCompactionBeforeBytes,
		"num_last_compaction_after_bytes":  numLastCompactionAfterBytes,
		"total_compaction_decrease_bytes":  totCompactionDecreaseBytes,
		"total_compaction_increase_bytes":  totCompactionIncreaseBytes,
		"max_compaction_decrease_bytes":    maxCompactionDecreaseBytes,
		"max_compaction_increase_bytes":    maxCompactionIncreaseBytes,
		"num_files":                        len(files),
		"num_files_open":                   numFilesOpen,
		"files":                            files,
	}, nil
}
1072452
func (p *BulkProcessor) Stats() BulkProcessorStats {
	p.statsMu.Lock()
	defer p.statsMu.Unlock()
	return *p.stats.dup()
}
1295692
func (mc MongoClient) ReadingCount() (int, error) {
	s := mc.getSessionCopy()
	defer s.Close()

	count, err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(bson.M{}).Count()
	if err != nil {
		return 0, errorMap(err)
	}
	return count, nil
}
445390
func (b *Bucket) GetStats(which string) map[string]map[string]string {
	rv := map[string]map[string]string{}
	for server, gs := range b.GatherStats(which) {
		if len(gs.Stats) > 0 {
			rv[server] = gs.Stats
		}
	}
	return rv
}
252705
func (e Total) Stats() []string {
	return []string{fmt.Sprintf("%s:%d|t", e.Name, e.Value)}
}
476051
func (t *TSMReader) Stats() FileStat {
	minTime, maxTime := t.index.TimeRange()
	minKey, maxKey := t.index.KeyRange()
	return FileStat{
		Path:         t.Path(),
		Size:         t.Size(),
		LastModified: t.LastModified(),
		MinTime:      minTime,
		MaxTime:      maxTime,
		MinKey:       minKey,
		MaxKey:       maxKey,
		HasTombstone: t.tombstoner.HasTombstones(),
	}
}
665430
func (s *SearchSource) Stats(statsGroup ...string) *SearchSource {
	s.stats = append(s.stats, statsGroup...)
	return s
}
832561
func (r *Reader) ReadAll() (records [][]string, err error) {
	for {
		record, err := r.Read()
		if err == io.EOF {
			return records, nil
		}
		if err != nil {
			return nil, err
		}
		records = append(records, record)
	}
}
713538
func (r *JSONMetricReader) Read() (_ []MetricBatch, err error) {
	defer func() {
		if err != nil {
			err = &errMetricsData{err}
		}
	}()

	var batches []MetricBatch

	walker := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return errors.Trace(err)
		}
		if info.IsDir() && path != r.dir {
			return filepath.SkipDir
		} else if !strings.HasSuffix(info.Name(), ".meta") {
			return nil
		}

		batch, err := decodeBatch(path)
		if err != nil {
			return errors.Trace(err)
		}
		batch.Metrics, err = decodeMetrics(filepath.Join(r.dir, batch.UUID))
		if err != nil {
			return errors.Trace(err)
		}
		if len(batch.Metrics) > 0 {
			batches = append(batches, batch)
		}
		return nil
	}
	if err := filepath.Walk(r.dir, walker); err != nil {
		return nil, errors.Trace(err)
	}
	return batches, nil
}
992327
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
	buf := bytes.NewBuffer(make([]byte, 0, capacity))
	// If the buffer overflows, we will get bytes.ErrTooLarge.
	// Return that as an error. Any other panic remains.
	defer func() {
		e := recover()
		if e == nil {
			return
		}
		if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
			err = panicErr
		} else {
			panic(e)
		}
	}()
	_, err = buf.ReadFrom(r)
	return buf.Bytes(), err
}
11714
func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error {
	if e.client == nil {
		client, err := e.createHttpClient()

		if err != nil {
			return err
		}
		e.client = client
	}

	var wg sync.WaitGroup
	wg.Add(len(e.Servers))

	for _, serv := range e.Servers {
		go func(s string, acc telegraf.Accumulator) {
			defer wg.Done()
			url := e.nodeStatsUrl(s)
			e.isMaster = false

			if e.ClusterStats {
				// get cat/master information here so NodeStats can determine
				// whether this node is the Master
				if err := e.setCatMaster(s + "/_cat/master"); err != nil {
					acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
					return
				}
			}

			// Always gather node states
			if err := e.gatherNodeStats(url, acc); err != nil {
				acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
				return
			}

			if e.ClusterHealth {
				url = s + "/_cluster/health"
				if e.ClusterHealthLevel != "" {
					url = url + "?level=" + e.ClusterHealthLevel
				}
				if err := e.gatherClusterHealth(url, acc); err != nil {
					acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
					return
				}
			}

			if e.ClusterStats && (e.isMaster || !e.ClusterStatsOnlyFromMaster || !e.Local) {
				if err := e.gatherClusterStats(s+"/_cluster/stats", acc); err != nil {
					acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
					return
				}
			}
		}(serv, acc)
	}

	wg.Wait()
	return nil
}
257874
func (a *AggregateStats) ReadFrom(r io.Reader) (int64, error) {
	return encoding.ReadFrom(
		r, &a.PacketCount, &a.ByteCount, &a.FlowCount, &defaultPad4)
}
905712
func (p *parallelReader) Read() ([][]byte, error) {
	newBuf := make([][]byte, len(p.readers))
	var newBufLK sync.RWMutex

	if p.offset+p.shardSize > p.shardFileSize {
		p.shardSize = p.shardFileSize - p.offset
	}

	readTriggerCh := make(chan bool, len(p.readers))
	for i := 0; i < p.dataBlocks; i++ {
		// Setup read triggers for p.dataBlocks number of reads so that it reads in parallel.
		readTriggerCh <- true
	}

	readerIndex := 0
	var wg sync.WaitGroup
	// if readTrigger is true, it implies next disk.ReadAt() should be tried
	// if readTrigger is false, it implies previous disk.ReadAt() was successful and there is no need
	// to try reading the next disk.
	for readTrigger := range readTriggerCh {
		newBufLK.RLock()
		canDecode := p.canDecode(newBuf)
		newBufLK.RUnlock()
		if canDecode {
			break
		}
		if readerIndex == len(p.readers) {
			break
		}
		if !readTrigger {
			continue
		}
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			disk := p.readers[i]
			if disk == nil {
				// Since disk is nil, trigger another read.
				readTriggerCh <- true
				return
			}
			if p.buf[i] == nil {
				// Reading first time on this disk, hence the buffer needs to be allocated.
				// Subsequent reads will re-use this buffer.
				p.buf[i] = make([]byte, p.shardSize)
			}
			// For the last shard, the shardsize might be less than previous shard sizes.
			// Hence the following statement ensures that the buffer size is reset to the right size.
			p.buf[i] = p.buf[i][:p.shardSize]
			_, err := disk.ReadAt(p.buf[i], p.offset)
			if err != nil {
				p.readers[i] = nil
				// Since ReadAt returned error, trigger another read.
				readTriggerCh <- true
				return
			}
			newBufLK.Lock()
			newBuf[i] = p.buf[i]
			newBufLK.Unlock()
			// Since ReadAt returned success, there is no need to trigger another read.
			readTriggerCh <- false
		}(readerIndex)
		readerIndex++
	}
	wg.Wait()

	if p.canDecode(newBuf) {
		p.offset += p.shardSize
		return newBuf, nil
	}

	return nil, errXLReadQuorum
}
1002060
func (c *Client) Stats() map[string]map[string]string {
	c.heartbeatLock.Lock()
	defer c.heartbeatLock.Unlock()
	stats := map[string]map[string]string{
		"client": {
			"node_id":         c.NodeID(),
			"known_servers":   strings.Join(c.GetServers(), ","),
			"num_allocations": strconv.Itoa(c.NumAllocs()),
			"last_heartbeat":  fmt.Sprintf("%v", time.Since(c.lastHeartbeat)),
			"heartbeat_ttl":   fmt.Sprintf("%v", c.heartbeatTTL),
		},
		"runtime": hstats.RuntimeStats(),
	}
	return stats
}
128334
func (c *MemberlistManager) clusterStats() {
	primReady := 0
	primNotReady := 0
	secReady := 0
	secNotReady := 0
	queryReady := 0
	queryNotReady := 0
	partitions := make(map[int32]int)
	for _, p := range c.members {
		if p.Primary {
			if p.IsReady() {
				primReady++
			} else {
				primNotReady++
			}
		} else if p.Mode != ModeQuery {
			if p.IsReady() {
				secReady++
			} else {
				secNotReady++
			}
		} else {
			if p.IsReady() {
				queryReady++
			} else {
				queryNotReady++
			}
		}
		for _, partition := range p.Partitions {
			partitions[partition]++
		}
	}

	totalPrimaryReady.Set(primReady)
	totalPrimaryNotReady.Set(primNotReady)
	totalSecondaryReady.Set(secReady)
	totalSecondaryNotReady.Set(secNotReady)
	totalQueryReady.Set(queryReady)
	totalQueryNotReady.Set(queryNotReady)

	totalPartitions.Set(len(partitions))
}