// Gather filters all metrics to only those that match the Matcher.
494102
func (f *Filter) Gather() ([]*dto.MetricFamily, error) {
	mfs, err := f.Gatherer.Gather()
	if err != nil {
		return nil, err
	}
	return f.Matcher.Match(mfs), nil
}
435432
func (ipt *Iptables) Gather(acc telegraf.Accumulator) error {
	if ipt.Table == "" || len(ipt.Chains) == 0 {
		return nil
	}
	// best effort : we continue through the chains even if an error is encountered,
	// but we keep track of the last error.
	for _, chain := range ipt.Chains {
		data, e := ipt.lister(ipt.Table, chain)
		if e != nil {
			acc.AddError(e)
			continue
		}
		e = ipt.parseAndGather(data, acc)
		if e != nil {
			acc.AddError(e)
			continue
		}
	}
	return nil
}
1344100
func (s *Salesforce) Gather(acc telegraf.Accumulator) error {
	limits, err := s.fetchLimits()
	if err != nil {
		return err
	}

	tags := map[string]string{
		"organization_id": s.OrganizationID,
		"host":            s.ServerURL.Host,
	}

	fields := make(map[string]interface{})
	for k, v := range limits {
		key := internal.SnakeCase(k)
		fields[key+"_max"] = v.Max
		fields[key+"_remaining"] = v.Remaining
	}

	acc.AddFields("salesforce", fields, tags)
	return nil
}
487737
func (c *totalVolumesCollector) Collect(ch chan<- prometheus.Metric) {
	for stateName, pluginCount := range c.getVolumeCount() {
		for pluginName, count := range pluginCount {
			metric, err := prometheus.NewConstMetric(totalVolumesDesc,
				prometheus.GaugeValue,
				float64(count),
				pluginName,
				stateName)
			if err != nil {
				klog.Warningf("Failed to create metric : %v", err)
			}
			ch <- metric
		}
	}
}
342737
func (d *indexData) gatherBranches(docID uint32, mt matchTree, known map[matchTree]bool) []string {
	foundBranchQuery := false
	var branches []string

	visitMatches(mt, known, func(mt matchTree) {
		bq, ok := mt.(*branchQueryMatchTree)
		if ok {
			foundBranchQuery = true
			branches = append(branches,
				d.branchNames[uint(bq.mask)])
		}
	})

	if !foundBranchQuery {
		mask := d.fileBranchMasks[docID]
		id := uint32(1)
		for mask != 0 {
			if mask&0x1 != 0 {
				branches = append(branches, d.branchNames[uint(id)])
			}
			id <<= 1
			mask >>= 1
		}
	}
	return branches
}
682801
func (s *Store) Collect(ch chan<- prometheus.Metric) {
	s.metrics.Collect(ch)
}
957090
func (n *NeptuneApex) Gather(acc telegraf.Accumulator) error {
	var wg sync.WaitGroup
	for _, server := range n.Servers {
		wg.Add(1)
		go func(server string) {
			defer wg.Done()
			acc.AddError(n.gatherServer(acc, server))
		}(server)
	}
	wg.Wait()
	return nil
}
851944
func Gather(config *Config) interface{} {

	flag.Parse()

	if config.Verbose {
		if b, err := json.MarshalIndent(config, "    ", "    "); err != nil {
			log.Printf("ERROR: unable to marshal config to string: %s\n", err)
		} else {
			log.Printf("INFO: reaping blueplanet information from the environment variables with configuration:\n    %s\n",
				string(b))
		}
	}

	env := os.Environ()
	bpData := make(map[string]interface{})
	for _, s := range env {
		// Rather annoying that we get the environment as an array of "=" separated strings given that I really want
		// to turn this into data, so split the string on "=" so we have a key and a value
		nv := strings.SplitN(s, "=", 2)
		if include(nv[0], config.IncludePrefixList) {
			// Before we add this into the data to push to the hook, lets check to see if the environment
			// overrides the target URL. The var to override would be BP_HOOK_URL_REDIRECT_<name>. The name
			// will be the name of the BP hook such as southbound-update, which is also the name of the executable.
			if config.Verbose {
				log.Printf("INFO: processing environment variable '%s'\n", nv[0])
			}
			if !ignore(nv[0], config.ExcludeList) {
				if hasDataSuffix(nv[0], config.DataSuffixList) {
					// If we have a data var then this "should be" string version of a JSON object or array, so lets
					// convert it to a proper JSON structure.
					if config.Verbose {
						log.Printf("INFO: processing value of '%s' as JSON data\n", nv[0])
					}
					var obj interface{}
					if err := json.Unmarshal([]byte(nv[1]), &obj); err != nil {
						// If we can't parse it, then log the warning and set it as a string value
						log.Printf("WARN: unable to unmarshal data value '%s' as JSON, passing vaue as string instead: %s\n", nv[1], err)
						bpData[nv[0]] = nv[1]
					} else {
						bpData[nv[0]] = obj
					}
				} else {
					bpData[nv[0]] = nv[1]
				}
			}
		} else if config.Verbose {
			log.Printf("INFO: ignoring environment variable '%s' because it does not start with prefix '%s'\n",
				nv[0], config.IncludePrefixList)
		}
	}

	return bpData
}
1207693
func (m *Metric) Collect() (a AggregatedMetrics) {
	for n := range m.collect(m.gen()) {
		value := aggregate(n.Value)

		switch n.Name {
		case "Duration":
			a.Duration = value
		case "Errors":
			a.Errors = value
		case "Invocations":
			a.Invocations = value
		case "Throttles":
			a.Throttles = value
		}
	}

	return
}
57439
func (c *goCollector) Collect(ch chan<- Metric) {
	ch <- MustNewConstMetric(c.goroutinesDesc, GaugeValue, float64(runtime.NumGoroutine()))
	n, _ := runtime.ThreadCreateProfile(nil)
	ch <- MustNewConstMetric(c.threadsDesc, GaugeValue, float64(n))

	var stats debug.GCStats
	stats.PauseQuantiles = make([]time.Duration, 5)
	debug.ReadGCStats(&stats)

	quantiles := make(map[float64]float64)
	for idx, pq := range stats.PauseQuantiles[1:] {
		quantiles[float64(idx+1)/float64(len(stats.PauseQuantiles)-1)] = pq.Seconds()
	}
	quantiles[0.0] = stats.PauseQuantiles[0].Seconds()
	ch <- MustNewConstSummary(c.gcDesc, uint64(stats.NumGC), stats.PauseTotal.Seconds(), quantiles)

	ch <- MustNewConstMetric(c.goInfoDesc, GaugeValue, 1)

	ms := &runtime.MemStats{}
	runtime.ReadMemStats(ms)
	for _, i := range c.metrics {
		ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms))
	}
}
766116
func (d *Dovecot) Gather(acc telegraf.Accumulator) error {
	if !validQuery[d.Type] {
		return fmt.Errorf("Error: %s is not a valid query type\n",
			d.Type)
	}

	if len(d.Servers) == 0 {
		d.Servers = append(d.Servers, "127.0.0.1:24242")
	}

	if len(d.Filters) <= 0 {
		d.Filters = append(d.Filters, "")
	}

	var wg sync.WaitGroup
	for _, server := range d.Servers {
		for _, filter := range d.Filters {
			wg.Add(1)
			go func(s string, f string) {
				defer wg.Done()
				acc.AddError(d.gatherServer(s, acc, d.Type, f))
			}(server, filter)
		}
	}

	wg.Wait()
	return nil
}
587051
func (l *LogParserPlugin) Gather(acc telegraf.Accumulator) error {
	l.Lock()
	defer l.Unlock()

	// always start from the beginning of files that appear while we're running
	return l.tailNewfiles(true)
}
233579
func (i *IPVS) Gather(acc telegraf.Accumulator) error {
	if i.handle == nil {
		h, err := ipvs.New("") // TODO: make the namespace configurable
		if err != nil {
			return errors.New("Unable to open IPVS handle")
		}
		i.handle = h
	}

	services, err := i.handle.GetServices()
	if err != nil {
		i.handle.Close()
		i.handle = nil // trigger a reopen on next call to gather
		return errors.New("Failed to list IPVS services")
	}
	for _, s := range services {
		fields := map[string]interface{}{
			"connections": s.Stats.Connections,
			"pkts_in":     s.Stats.PacketsIn,
			"pkts_out":    s.Stats.PacketsOut,
			"bytes_in":    s.Stats.BytesIn,
			"bytes_out":   s.Stats.BytesOut,
			"pps_in":      s.Stats.PPSIn,
			"pps_out":     s.Stats.PPSOut,
			"cps":         s.Stats.CPS,
		}
		acc.AddGauge("ipvs_virtual_server", fields, serviceTags(s))

		destinations, err := i.handle.GetDestinations(s)
		if err != nil {
			log.Println("E! Failed to list destinations for a virtual server")
			continue // move on to the next virtual server
		}

		for _, d := range destinations {
			fields := map[string]interface{}{
				"active_connections":   d.ActiveConnections,
				"inactive_connections": d.InactiveConnections,
				"connections":          d.Stats.Connections,
				"pkts_in":              d.Stats.PacketsIn,
				"pkts_out":             d.Stats.PacketsOut,
				"bytes_in":             d.Stats.BytesIn,
				"bytes_out":            d.Stats.BytesOut,
				"pps_in":               d.Stats.PPSIn,
				"pps_out":              d.Stats.PPSOut,
				"cps":                  d.Stats.CPS,
			}
			destTags := destinationTags(d)
			if s.FWMark > 0 {
				destTags["virtual_fwmark"] = strconv.Itoa(int(s.FWMark))
			} else {
				destTags["virtual_protocol"] = protocolToString(s.Protocol)
				destTags["virtual_address"] = s.Address.String()
				destTags["virtual_port"] = strconv.Itoa(int(s.Port))
			}
			acc.AddGauge("ipvs_real_server", fields, destTags)
		}
	}

	return nil
}
98563
func (e *Exporter) gatherData() error {
	var err error

	err = e.getStatus()
	if err != nil {
		return err
	}
	err = e.getMemPoolDepth()
	if err != nil {
		return err
	}
	err = e.getPeers()
	if err != nil {
		return err
	}
	blocks, err := e.getBlocks()
	if err != nil {
		return err
	}
	err = e.getTxBuckets(blocks.BlockMetas)
	if err != nil {
		return err
	}
	err = e.getBlockTimeBuckets(blocks.BlockMetas)
	if err != nil {
		return err
	}
	e.getAccountStats()

	return nil
}
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
}
53464
func (j *Jenkins) Gather(acc telegraf.Accumulator) error {
	if j.client == nil {
		client, err := j.newHTTPClient()
		if err != nil {
			return err
		}
		if err = j.initialize(client); err != nil {
			return err
		}
	}

	j.gatherNodesData(acc)
	j.gatherJobs(acc)

	return nil
}
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
}