// Gather stat using http protocol
424713
func (g *phpfpm) gatherHttp(addr string, acc telegraf.Accumulator) error {
	u, err := url.Parse(addr)
	if err != nil {
		return fmt.Errorf("Unable parse server address '%s': %s", addr, err)
	}

	req, err := http.NewRequest("GET", fmt.Sprintf("%s://%s%s", u.Scheme,
		u.Host, u.Path), nil)
	res, err := g.client.Do(req)
	if err != nil {
		return fmt.Errorf("Unable to connect to phpfpm status page '%s': %v",
			addr, err)
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		return fmt.Errorf("Unable to get valid stat result from '%s': %v",
			addr, err)
	}

	importMetric(res.Body, acc, addr)
	return nil
}
520540
func (s *Snmp) Gather(acc telegraf.Accumulator) error {
	if err := s.init(); err != nil {
		return err
	}

	var wg sync.WaitGroup
	for i, agent := range s.Agents {
		wg.Add(1)
		go func(i int, agent string) {
			defer wg.Done()
			gs, err := s.getConnection(i)
			if err != nil {
				acc.AddError(Errorf(err, "agent %s", agent))
				return
			}

			// First is the top-level fields. We treat the fields as table prefixes with an empty index.
			t := Table{
				Name:   s.Name,
				Fields: s.Fields,
			}
			topTags := map[string]string{}
			if err := s.gatherTable(acc, gs, t, topTags, false); err != nil {
				acc.AddError(Errorf(err, "agent %s", agent))
			}

			// Now is the real tables.
			for _, t := range s.Tables {
				if err := s.gatherTable(acc, gs, t, topTags, true); err != nil {
					acc.AddError(Errorf(err, "agent %s: gathering table %s", agent, t.Name))
				}
			}
		}(i, agent)
	}
	wg.Wait()

	return nil
}
753410
func (s *Unbound) Gather(acc telegraf.Accumulator) error {

	// Always exclude histrogram statistics
	statExcluded := []string{"histogram.*"}
	filterExcluded, err := filter.Compile(statExcluded)
	if err != nil {
		return err
	}

	out, err := s.run(s.Binary, s.Timeout, s.UseSudo, s.Server, s.ThreadAsTag)
	if err != nil {
		return fmt.Errorf("error gathering metrics: %s", err)
	}

	// Process values
	fields := make(map[string]interface{})
	fieldsThreads := make(map[string]map[string]interface{})

	scanner := bufio.NewScanner(out)
	for scanner.Scan() {

		cols := strings.Split(scanner.Text(), "=")

		// Check split correctness
		if len(cols) != 2 {
			continue
		}

		stat := cols[0]
		value := cols[1]

		// Filter value
		if filterExcluded.Match(stat) {
			continue
		}

		fieldValue, err := strconv.ParseFloat(value, 64)
		if err != nil {
			acc.AddError(fmt.Errorf("Expected a numerical value for %s = %v",
				stat, value))
			continue
		}

		// is this a thread related value?
		if s.ThreadAsTag && strings.HasPrefix(stat, "thread") {
			// split the stat
			statTokens := strings.Split(stat, ".")
			// make sure we split something
			if len(statTokens) > 1 {
				// set the thread identifier
				threadID := strings.TrimPrefix(statTokens[0], "thread")
				// make sure we have a proper thread ID
				if _, err = strconv.Atoi(threadID); err == nil {
					// create new slice without the thread identifier (skip first token)
					threadTokens := statTokens[1:]
					// re-define stat
					field := strings.Join(threadTokens[:], "_")
					if fieldsThreads[threadID] == nil {
						fieldsThreads[threadID] = make(map[string]interface{})
					}
					fieldsThreads[threadID][field] = fieldValue
				}
			}
		} else {
			field := strings.Replace(stat, ".", "_", -1)
			fields[field] = fieldValue
		}

	}

	acc.AddFields("unbound", fields, nil)

	if s.ThreadAsTag && len(fieldsThreads) > 0 {
		for thisThreadID, thisThreadFields := range fieldsThreads {
			thisThreadTag := map[string]string{"thread": thisThreadID}
			acc.AddFields("unbound_threads", thisThreadFields, thisThreadTag)
		}
	}

	return nil
}
274406
func (c *Client) Stat(name, bucket string) (size int64, reterr error) {
	req := newReq("http://" + bucket + "." + c.hostname() + "/" + name)
	req.Method = "HEAD"
	c.Auth.SignRequest(req)
	res, err := c.httpClient().Do(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("s3: Unexpected status code %d statting object %v", res.StatusCode, name)
}
759018
func (c *metricsCollector) Collect(ch chan<- prometheus.Metric) {
	c.requests.Collect(ch)
}
1319654
func Collect(staticConfiguration *static.Configuration) error {
	anonConfig, err := anonymize.Do(staticConfiguration, false)
	if err != nil {
		return err
	}

	log.Infof("Anonymous stats sent to %s: %s", collectorURL, anonConfig)

	hashConf, err := hashstructure.Hash(staticConfiguration, nil)
	if err != nil {
		return err
	}

	data := &data{
		Version:       version.Version,
		Codename:      version.Codename,
		BuildDate:     version.BuildDate,
		Hash:          strconv.FormatUint(hashConf, 10),
		Configuration: base64.StdEncoding.EncodeToString([]byte(anonConfig)),
	}

	buf := new(bytes.Buffer)
	err = json.NewEncoder(buf).Encode(data)
	if err != nil {
		return err
	}

	_, err = makeHTTPClient().Post(collectorURL, "application/json; charset=utf-8", buf)
	return err
}
255583
func (s *Stackdriver) Gather(acc telegraf.Accumulator) error {
	ctx := context.Background()

	if s.RateLimit == 0 {
		s.RateLimit = defaultRateLimit
	}

	err := s.initializeStackdriverClient(ctx)
	if err != nil {
		return err
	}

	start, end := s.updateWindow(s.prevEnd)
	s.prevEnd = end

	tsConfs, err := s.generatetimeSeriesConfs(ctx, start, end)
	if err != nil {
		return err
	}

	lmtr := limiter.NewRateLimiter(s.RateLimit, time.Second)
	defer lmtr.Stop()

	grouper := &lockedSeriesGrouper{
		SeriesGrouper: metric.NewSeriesGrouper(),
	}

	var wg sync.WaitGroup
	wg.Add(len(tsConfs))
	for _, tsConf := range tsConfs {
		<-lmtr.C
		go func(tsConf *timeSeriesConf) {
			defer wg.Done()
			acc.AddError(s.gatherTimeSeries(ctx, grouper, tsConf))
		}(tsConf)
	}
	wg.Wait()

	for _, metric := range grouper.Metrics() {
		acc.AddMetric(metric)
	}

	return nil
}
300179
func (m *monitor) Collect(in chan<- prometheus.Metric) {
	// Gauge
	m.connections.Collect(in)
	m.requests.Collect(in)

	// HistogramVec
	m.requestDuration.Collect(in)

	// CounterVec
	m.requestsTotal.Collect(in)
	m.messagesReceived.Collect(in)
	m.messagesSend.Collect(in)
	m.errors.Collect(in)
}
371829
func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
	var (
		checkedMetricChan   = make(chan Metric, capMetricChan)
		uncheckedMetricChan = make(chan Metric, capMetricChan)
		metricHashes        = map[uint64]struct{}{}
		wg                  sync.WaitGroup
		errs                MultiError          // The collected errors to return in the end.
		registeredDescIDs   map[uint64]struct{} // Only used for pedantic checks
	)

	r.mtx.RLock()
	goroutineBudget := len(r.collectorsByID) + len(r.uncheckedCollectors)
	metricFamiliesByName := make(map[string]*dto.MetricFamily, len(r.dimHashesByName))
	checkedCollectors := make(chan Collector, len(r.collectorsByID))
	uncheckedCollectors := make(chan Collector, len(r.uncheckedCollectors))
	for _, collector := range r.collectorsByID {
		checkedCollectors <- collector
	}
	for _, collector := range r.uncheckedCollectors {
		uncheckedCollectors <- collector
	}
	// In case pedantic checks are enabled, we have to copy the map before
	// giving up the RLock.
	if r.pedanticChecksEnabled {
		registeredDescIDs = make(map[uint64]struct{}, len(r.descIDs))
		for id := range r.descIDs {
			registeredDescIDs[id] = struct{}{}
		}
	}
	r.mtx.RUnlock()

	wg.Add(goroutineBudget)

	collectWorker := func() {
		for {
			select {
			case collector := <-checkedCollectors:
				collector.Collect(checkedMetricChan)
			case collector := <-uncheckedCollectors:
				collector.Collect(uncheckedMetricChan)
			default:
				return
			}
			wg.Done()
		}
	}

	// Start the first worker now to make sure at least one is running.
	go collectWorker()
	goroutineBudget--

	// Close checkedMetricChan and uncheckedMetricChan once all collectors
	// are collected.
	go func() {
		wg.Wait()
		close(checkedMetricChan)
		close(uncheckedMetricChan)
	}()

	// Drain checkedMetricChan and uncheckedMetricChan in case of premature return.
	defer func() {
		if checkedMetricChan != nil {
			for range checkedMetricChan {
			}
		}
		if uncheckedMetricChan != nil {
			for range uncheckedMetricChan {
			}
		}
	}()

	// Copy the channel references so we can nil them out later to remove
	// them from the select statements below.
	cmc := checkedMetricChan
	umc := uncheckedMetricChan

	for {
		select {
		case metric, ok := <-cmc:
			if !ok {
				cmc = nil
				break
			}
			errs.Append(processMetric(
				metric, metricFamiliesByName,
				metricHashes,
				registeredDescIDs,
			))
		case metric, ok := <-umc:
			if !ok {
				umc = nil
				break
			}
			errs.Append(processMetric(
				metric, metricFamiliesByName,
				metricHashes,
				nil,
			))
		default:
			if goroutineBudget <= 0 || len(checkedCollectors)+len(uncheckedCollectors) == 0 {
				// All collectors are already being worked on or
				// we have already as many goroutines started as
				// there are collectors. Do the same as above,
				// just without the default.
				select {
				case metric, ok := <-cmc:
					if !ok {
						cmc = nil
						break
					}
					errs.Append(processMetric(
						metric, metricFamiliesByName,
						metricHashes,
						registeredDescIDs,
					))
				case metric, ok := <-umc:
					if !ok {
						umc = nil
						break
					}
					errs.Append(processMetric(
						metric, metricFamiliesByName,
						metricHashes,
						nil,
					))
				}
				break
			}
			// Start more workers.
			go collectWorker()
			goroutineBudget--
			runtime.Gosched()
		}
		// Once both checkedMetricChan and uncheckdMetricChan are closed
		// and drained, the contraption above will nil out cmc and umc,
		// and then we can leave the collect loop here.
		if cmc == nil && umc == nil {
			break
		}
	}
	return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap()
}
1067588
func (g *haproxy) Gather(acc telegraf.Accumulator) error {
	if len(g.Servers) == 0 {
		return g.gatherServer("http://127.0.0.1:1936/haproxy?stats", acc)
	}

	endpoints := make([]string, 0, len(g.Servers))

	for _, endpoint := range g.Servers {

		if strings.HasPrefix(endpoint, "http") {
			endpoints = append(endpoints, endpoint)
			continue
		}

		socketPath := getSocketAddr(endpoint)

		matches, err := filepath.Glob(socketPath)

		if err != nil {
			return err
		}

		if len(matches) == 0 {
			endpoints = append(endpoints, socketPath)
		} else {
			for _, match := range matches {
				endpoints = append(endpoints, match)
			}
		}
	}

	var wg sync.WaitGroup
	wg.Add(len(endpoints))
	for _, server := range endpoints {
		go func(serv string) {
			defer wg.Done()
			if err := g.gatherServer(serv, acc); err != nil {
				acc.AddError(err)
			}
		}(server)
	}

	wg.Wait()
	return nil
}
425235
func (r *Riak) gatherServer(s string, acc telegraf.Accumulator) error {
	// Parse the given URL to extract the server tag
	u, err := url.Parse(s)
	if err != nil {
		return fmt.Errorf("riak unable to parse given server url %s: %s", s, err)
	}

	// Perform the GET request to the riak /stats endpoint
	resp, err := r.client.Get(s + "/stats")
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Successful responses will always return status code 200
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("riak responded with unexepcted status code %d", resp.StatusCode)
	}

	// Decode the response JSON into a new stats struct
	stats := &riakStats{}
	if err := json.NewDecoder(resp.Body).Decode(stats); err != nil {
		return fmt.Errorf("unable to decode riak response: %s", err)
	}

	// Build a map of tags
	tags := map[string]string{
		"nodename": stats.Nodename,
		"server":   u.Host,
	}

	// Build a map of field values
	fields := map[string]interface{}{
		"cpu_avg1":                     stats.CpuAvg1,
		"cpu_avg15":                    stats.CpuAvg15,
		"cpu_avg5":                     stats.CpuAvg5,
		"memory_code":                  stats.MemoryCode,
		"memory_ets":                   stats.MemoryEts,
		"memory_processes":             stats.MemoryProcesses,
		"memory_system":                stats.MemorySystem,
		"memory_total":                 stats.MemoryTotal,
		"node_get_fsm_objsize_100":     stats.NodeGetFsmObjsize100,
		"node_get_fsm_objsize_95":      stats.NodeGetFsmObjsize95,
		"node_get_fsm_objsize_99":      stats.NodeGetFsmObjsize99,
		"node_get_fsm_objsize_mean":    stats.NodeGetFsmObjsizeMean,
		"node_get_fsm_objsize_median":  stats.NodeGetFsmObjsizeMedian,
		"node_get_fsm_siblings_100":    stats.NodeGetFsmSiblings100,
		"node_get_fsm_siblings_95":     stats.NodeGetFsmSiblings95,
		"node_get_fsm_siblings_99":     stats.NodeGetFsmSiblings99,
		"node_get_fsm_siblings_mean":   stats.NodeGetFsmSiblingsMean,
		"node_get_fsm_siblings_median": stats.NodeGetFsmSiblingsMedian,
		"node_get_fsm_time_100":        stats.NodeGetFsmTime100,
		"node_get_fsm_time_95":         stats.NodeGetFsmTime95,
		"node_get_fsm_time_99":         stats.NodeGetFsmTime99,
		"node_get_fsm_time_mean":       stats.NodeGetFsmTimeMean,
		"node_get_fsm_time_median":     stats.NodeGetFsmTimeMedian,
		"node_gets":                    stats.NodeGets,
		"node_gets_total":              stats.NodeGetsTotal,
		"node_put_fsm_time_100":        stats.NodePutFsmTime100,
		"node_put_fsm_time_95":         stats.NodePutFsmTime95,
		"node_put_fsm_time_99":         stats.NodePutFsmTime99,
		"node_put_fsm_time_mean":       stats.NodePutFsmTimeMean,
		"node_put_fsm_time_median":     stats.NodePutFsmTimeMedian,
		"node_puts":                    stats.NodePuts,
		"node_puts_total":              stats.NodePutsTotal,
		"pbc_active":                   stats.PbcActive,
		"pbc_connects":                 stats.PbcConnects,
		"pbc_connects_total":           stats.PbcConnectsTotal,
		"vnode_gets":                   stats.VnodeGets,
		"vnode_gets_total":             stats.VnodeGetsTotal,
		"vnode_index_reads":            stats.VnodeIndexReads,
		"vnode_index_reads_total":      stats.VnodeIndexReadsTotal,
		"vnode_index_writes":           stats.VnodeIndexWrites,
		"vnode_index_writes_total":     stats.VnodeIndexWritesTotal,
		"vnode_puts":                   stats.VnodePuts,
		"vnode_puts_total":             stats.VnodePutsTotal,
		"read_repairs":                 stats.ReadRepairs,
		"read_repairs_total":           stats.ReadRepairsTotal,
	}

	// Accumulate the tags and values
	acc.AddFields("riak", fields, tags)

	return nil
}
1332423
func (g *Gatherer) Gather(client *Client, acc telegraf.Accumulator) error {
	var tags map[string]string

	if client.config.ProxyConfig != nil {
		tags = map[string]string{"jolokia_proxy_url": client.URL}
	} else {
		tags = map[string]string{"jolokia_agent_url": client.URL}
	}

	requests := makeReadRequests(g.metrics)
	responses, err := client.read(requests)
	if err != nil {
		return err
	}

	g.gatherResponses(responses, tags, acc)
	return nil
}
257177
func (c *s3Client) Stat(isIncomplete, isFetchMeta bool, sse encrypt.ServerSide) (*clientContent, *probe.Error) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	bucket, object := c.url2BucketAndObject()
	// Bucket name cannot be empty, stat on URL has no meaning.
	if bucket == "" {
		return nil, probe.NewError(BucketNameEmpty{})
	}

	if object == "" {
		content, err := c.bucketStat(bucket)
		if err != nil {
			return nil, err.Trace(bucket)
		}
		return content, nil
	}

	// The following code tries to calculate if a given prefix/object does really exist
	// using minio-go listing API. The following inputs are supported:
	//     - /path/to/existing/object
	//     - /path/to/existing_directory
	//     - /path/to/existing_directory/
	//     - /path/to/empty_directory
	//     - /path/to/empty_directory/

	nonRecursive := false
	objectMetadata := &clientContent{}

	// Prefix to pass to minio-go listing in order to fetch a given object/directory
	prefix := strings.TrimRight(object, string(c.targetURL.Separator))

	// If the request is for incomplete upload stat, handle it here.
	if isIncomplete {
		for objectMultipartInfo := range c.api.ListIncompleteUploads(bucket, prefix, nonRecursive, nil) {
			if objectMultipartInfo.Err != nil {
				return nil, probe.NewError(objectMultipartInfo.Err)
			}

			if objectMultipartInfo.Key == object {
				objectMetadata.URL = *c.targetURL
				objectMetadata.Time = objectMultipartInfo.Initiated
				objectMetadata.Size = objectMultipartInfo.Size
				objectMetadata.Type = os.FileMode(0664)
				objectMetadata.Metadata = map[string]string{}
				objectMetadata.EncryptionHeaders = map[string]string{}
				return objectMetadata, nil
			}

			if strings.HasSuffix(objectMultipartInfo.Key, string(c.targetURL.Separator)) {
				objectMetadata.URL = *c.targetURL
				objectMetadata.Type = os.ModeDir
				objectMetadata.Metadata = map[string]string{}
				objectMetadata.EncryptionHeaders = map[string]string{}

				return objectMetadata, nil
			}
		}
		return nil, probe.NewError(ObjectMissing{})
	}

	opts := minio.StatObjectOptions{}
	opts.ServerSideEncryption = sse

	for objectStat := range c.listObjectWrapper(bucket, prefix, nonRecursive, nil) {
		if objectStat.Err != nil {
			return nil, probe.NewError(objectStat.Err)
		}
		if strings.HasSuffix(objectStat.Key, string(c.targetURL.Separator)) {
			objectMetadata.URL = *c.targetURL
			objectMetadata.Type = os.ModeDir

			if isFetchMeta {
				stat, err := c.getObjectStat(bucket, object, opts)
				if err != nil {
					return nil, err
				}
				objectMetadata.ETag = stat.ETag
				objectMetadata.Metadata = stat.Metadata
				objectMetadata.EncryptionHeaders = stat.EncryptionHeaders
				objectMetadata.Expires = stat.Expires
			}
			return objectMetadata, nil
		} else if objectStat.Key == object {
			objectMetadata.URL = *c.targetURL
			objectMetadata.Time = objectStat.LastModified
			objectMetadata.Size = objectStat.Size
			objectMetadata.ETag = objectStat.ETag
			objectMetadata.Type = os.FileMode(0664)
			objectMetadata.Metadata = map[string]string{}
			objectMetadata.Expires = objectStat.Expires
			objectMetadata.EncryptionHeaders = map[string]string{}
			if isFetchMeta {
				stat, err := c.getObjectStat(bucket, object, opts)
				if err != nil {
					return nil, err
				}
				objectMetadata.Metadata = stat.Metadata
				objectMetadata.EncryptionHeaders = stat.EncryptionHeaders
				objectMetadata.Expires = stat.Expires
			}
			return objectMetadata, nil
		}
	}
	return c.getObjectStat(bucket, object, opts)
}
189506
func (h *StatsHandler) Collect(in chan<- prometheus.Metric) {
	for _, c := range h.handlers {
		c.Collect(in)
	}
}
548602
func (c *ShardedClient) Stat(statsKey string) StatResponse {
	statEntries := make(map[int](map[string]string))

	var err error
	for shard, conn := range c.manager.GetAllShards() {
		response := c.statHelper(shard, conn, statsKey)
		if response.Error() != nil {
			if err == nil {
				err = response.Error()
			} else {
				err = errors.Wrap(response.Error(), err.Error())
			}
		}

		for shardId, entries := range response.Entries() {
			statEntries[shardId] = entries
		}
	}

	if err != nil {
		return NewStatErrorResponse(err, statEntries)
	}

	return NewStatResponse(StatusNoError, statEntries)
}
479618
func (h *HTTPResponse) Gather(acc telegraf.Accumulator) error {
	// Compile the body regex if it exist
	if h.compiledStringMatch == nil {
		var err error
		h.compiledStringMatch, err = regexp.Compile(h.ResponseStringMatch)
		if err != nil {
			return fmt.Errorf("Failed to compile regular expression %s : %s", h.ResponseStringMatch, err)
		}
	}

	// Set default values
	if h.ResponseTimeout.Duration < time.Second {
		h.ResponseTimeout.Duration = time.Second * 5
	}
	// Check send and expected string
	if h.Method == "" {
		h.Method = "GET"
	}
	if h.Address == "" {
		h.Address = "http://localhost"
	}
	addr, err := url.Parse(h.Address)
	if err != nil {
		return err
	}
	if addr.Scheme != "http" && addr.Scheme != "https" {
		return errors.New("Only http and https are supported")
	}

	// Prepare data
	var fields map[string]interface{}
	var tags map[string]string

	if h.client == nil {
		client, err := h.createHttpClient()
		if err != nil {
			return err
		}
		h.client = client
	}

	// Gather data
	fields, tags, err = h.httpGather()
	if err != nil {
		return err
	}

	// Add metrics
	acc.AddFields("http_response", fields, tags)
	return nil
}
1048671
func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error) {
	switch u.Query().Get("format") {
	case "", "tar", "tgz":
		// ok
	default:
		log.Printf("unknown archive format: %q", u)
		return nil, vix.Error(vix.InvalidArg)
	}

	return &archive{
		name: u.Path,
		size: math.MaxInt64,
	}, nil
}