// Collect calls function f for each Task update.
766768
func (v TaskView) Collect(ctx context.Context, f func([]types.TaskInfo)) error {
	// Using TaskHistoryCollector would be less clunky, but it isn't supported on ESX at all.
	ref := v.Reference()
	filter := new(property.WaitFilter).Add(ref, "Task", []string{"info"}, v.TraversalSpec())

	if v.Watch != nil {
		filter.Add(*v.Watch, v.Watch.Type, []string{"recentTask"})
	}

	pc := property.DefaultCollector(v.Client())

	completed := make(map[string]bool)

	return property.WaitForUpdates(ctx, pc, filter, func(updates []types.ObjectUpdate) bool {
		var infos []types.TaskInfo
		var prune []types.ManagedObjectReference
		var tasks []types.ManagedObjectReference
		var reset func()

		for _, update := range updates {
			for _, change := range update.ChangeSet {
				if change.Name == "recentTask" {
					tasks = change.Val.(types.ArrayOfManagedObjectReference).ManagedObjectReference
					if len(tasks) != 0 {
						reset = func() {
							_ = v.Reset(ctx, tasks)

							// Remember any tasks we've reported as complete already,
							// to avoid reporting multiple times when Reset is triggered.
							rtasks := make(map[string]bool)
							for i := range tasks {
								if _, ok := completed[tasks[i].Value]; ok {
									rtasks[tasks[i].Value] = true
								}
							}
							completed = rtasks
						}
					}

					continue
				}

				info, ok := change.Val.(types.TaskInfo)
				if !ok {
					continue
				}

				if !completed[info.Task.Value] {
					infos = append(infos, info)
				}

				if v.Follow && info.CompleteTime != nil {
					prune = append(prune, info.Task)
					completed[info.Task.Value] = true
				}
			}
		}

		if len(infos) != 0 {
			f(infos)
		}

		if reset != nil {
			reset()
		} else if len(prune) != 0 {
			_ = v.Remove(ctx, prune)
		}

		if len(tasks) != 0 && len(infos) == 0 {
			return false
		}

		return !v.Follow
	})
}
346021
func (c *timingsCollector) Collect(ch chan<- prometheus.Metric) {
	for cat, his := range c.t.Histograms() {
		ch <- prometheus.MustNewConstHistogram(
			c.desc,
			uint64(his.Count()),
			float64(his.Total())/1000000000,
			makeCumulativeBuckets(c.cutoffs, his.Buckets()),
			cat)
	}
}
1221600
func (ppl *Pipeline) Collect() ([]*ResultSet, error) {
	defer func() {
		ppl.resp = nil
	}()
	err := ppl.ensureProtocol()
	if err != nil {
		return nil, err
	}
	results := []*ResultSet{}
	for i := ppl.counter; i > 0; i-- {
		result, err := ppl.resp.receiveResultSet()
		if err != nil {
			ppl.database.pool.kill(ppl.resp)
			return nil, err
		}
		results = append(results, result)
	}
	ppl.database.pool.push(ppl.resp)
	return results, nil
}
894963
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
	e.mutex.Lock() // To protect metrics from concurrent collects.
	defer e.mutex.Unlock()

	up := e.scrape(ch)

	ch <- prometheus.MustNewConstMetric(haproxyUp, prometheus.GaugeValue, up)
	ch <- e.totalScrapes
	ch <- e.csvParseFailures
}
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
}
114615
func (l *Lustre2) Gather(acc telegraf.Accumulator) error {
	l.allFields = make(map[string]map[string]interface{})

	if len(l.Ost_procfiles) == 0 {
		// read/write bytes are in obdfilter/<ost_name>/stats
		err := l.GetLustreProcStats("/proc/fs/lustre/obdfilter/*/stats",
			wanted_ost_fields, acc)
		if err != nil {
			return err
		}
		// cache counters are in osd-ldiskfs/<ost_name>/stats
		err = l.GetLustreProcStats("/proc/fs/lustre/osd-ldiskfs/*/stats",
			wanted_ost_fields, acc)
		if err != nil {
			return err
		}
		// per job statistics are in obdfilter/<ost_name>/job_stats
		err = l.GetLustreProcStats("/proc/fs/lustre/obdfilter/*/job_stats",
			wanted_ost_jobstats_fields, acc)
		if err != nil {
			return err
		}
	}

	if len(l.Mds_procfiles) == 0 {
		// Metadata server stats
		err := l.GetLustreProcStats("/proc/fs/lustre/mdt/*/md_stats",
			wanted_mds_fields, acc)
		if err != nil {
			return err
		}

		// Metadata target job stats
		err = l.GetLustreProcStats("/proc/fs/lustre/mdt/*/job_stats",
			wanted_mdt_jobstats_fields, acc)
		if err != nil {
			return err
		}
	}

	for _, procfile := range l.Ost_procfiles {
		ost_fields := wanted_ost_fields
		if strings.HasSuffix(procfile, "job_stats") {
			ost_fields = wanted_ost_jobstats_fields
		}
		err := l.GetLustreProcStats(procfile, ost_fields, acc)
		if err != nil {
			return err
		}
	}
	for _, procfile := range l.Mds_procfiles {
		mdt_fields := wanted_mds_fields
		if strings.HasSuffix(procfile, "job_stats") {
			mdt_fields = wanted_mdt_jobstats_fields
		}
		err := l.GetLustreProcStats(procfile, mdt_fields, acc)
		if err != nil {
			return err
		}
	}

	for name, fields := range l.allFields {
		tags := map[string]string{
			"name": name,
		}
		if _, ok := fields["jobid"]; ok {
			if jobid, ok := fields["jobid"].(string); ok {
				tags["jobid"] = jobid
			}
			delete(fields, "jobid")
		}
		acc.AddFields("lustre2", fields, tags)
	}

	return nil
}
630581
func (g *gaugesWithSingleLabelCollector) Collect(ch chan<- prometheus.Metric) {
	for tag, val := range g.gauges.Counts() {
		ch <- prometheus.MustNewConstMetric(
			g.desc,
			g.vt,
			float64(val),
			tag)
	}
}
189506
func (h *StatsHandler) Collect(in chan<- prometheus.Metric) {
	for _, c := range h.handlers {
		c.Collect(in)
	}
}
1239887
func (g *GoMetrics) Collect() {
	now := time.Now()

	lastTotalAlloc := g.ms.TotalAlloc
	lastLookups := g.ms.Lookups
	lastMallocs := g.ms.Mallocs
	lastFrees := g.ms.Frees
	lastHeapRealeased := g.ms.HeapReleased
	lastNumGC := g.ms.NumGC
	lastNumCgoCall := g.runtime.lastNumCgoCall
	g.runtime.lastNumCgoCall = int(runtime.NumCgoCall())

	g.runtime.numCPU = runtime.NumCPU()
	g.runtime.numGoroutine = runtime.NumGoroutine()
	g.runtime.numCgoCall = g.runtime.lastNumCgoCall - lastNumCgoCall

	pauses := collectMemoryStats(&g.ms, lastNumGC)

	g.memstats.total.alloc = g.ms.Alloc
	g.memstats.total.totalAlloc = g.ms.TotalAlloc - lastTotalAlloc
	g.memstats.total.lookups = g.ms.Lookups - lastLookups
	g.memstats.total.mallocs = g.ms.Mallocs - lastMallocs
	g.memstats.total.frees = g.ms.Frees - lastFrees

	g.memstats.heap.alloc = g.ms.HeapAlloc
	g.memstats.heap.sys = g.ms.HeapSys
	g.memstats.heap.idle = g.ms.HeapIdle
	g.memstats.heap.inuse = g.ms.HeapInuse
	g.memstats.heap.released = g.ms.HeapReleased - lastHeapRealeased
	g.memstats.heap.objects = g.ms.HeapObjects

	g.memstats.stack.inuse = g.ms.StackInuse
	g.memstats.stack.sys = g.ms.StackSys
	g.memstats.mspan.inuse = g.ms.MSpanInuse
	g.memstats.mspan.sys = g.ms.MSpanSys
	g.memstats.mcache.inuse = g.ms.MCacheInuse
	g.memstats.mcache.sys = g.ms.MCacheSys
	g.memstats.buckhash.sys = g.ms.BuckHashSys
	g.memstats.gc.sys = g.ms.GCSys
	g.memstats.other.sys = g.ms.OtherSys

	g.memstats.numGC = g.ms.NumGC - lastNumGC
	g.memstats.nextGC = g.ms.NextGC
	g.memstats.gcCPUFraction = g.ms.GCCPUFraction

	if len(pauses) == 0 {
		g.memstats.gcPauseAvg = 0
		g.memstats.gcPauseMin = 0
		g.memstats.gcPauseMax = 0
	} else {
		g.memstats.gcPauseMin = pauses[0]
		g.memstats.gcPauseMax = pauses[0]
		g.memstats.gcPauseAvg = pauses[0]

		for _, pause := range pauses[1:] {
			g.memstats.gcPauseAvg += pause
			switch {
			case pause < g.memstats.gcPauseMin:
				g.memstats.gcPauseMin = pause
			case pause > g.memstats.gcPauseMax:
				g.memstats.gcPauseMax = pause
			}
		}

		g.memstats.gcPauseAvg /= time.Duration(len(pauses))
	}

	g.engine.ReportAt(now, g)
}
951788
func (e *Endpoint) Collect(ctx context.Context, acc telegraf.Accumulator) error {

	// If we never managed to do a discovery, collection will be a no-op. Therefore,
	// we need to check that a connection is available, or the collection will
	// silently fail.
	if _, err := e.clientFactory.GetClient(ctx); err != nil {
		return err
	}

	e.collectMux.RLock()
	defer e.collectMux.RUnlock()

	if ctx.Err() != nil {
		return ctx.Err()
	}

	// If discovery interval is disabled (0), discover on each collection cycle
	if e.Parent.ObjectDiscoveryInterval.Duration == 0 {
		err := e.discover(ctx)
		if err != nil {
			return err
		}
	}
	var wg sync.WaitGroup
	for k, res := range e.resourceKinds {
		if res.enabled {
			wg.Add(1)
			go func(k string) {
				defer wg.Done()
				err := e.collectResource(ctx, k, acc)
				if err != nil {
					acc.AddError(err)
				}
			}(k)
		}
	}
	wg.Wait()

	// Purge old timestamps from the cache
	e.hwMarks.Purge()
	return nil
}
218236
func CollectOptions(opts []OpOption) (*OpConfig, error) {
	cfg := OpConfig{}
	for _, o := range opts {
		if err := o(&cfg); err != nil {
			return nil, trace.Wrap(err)
		}
	}
	return &cfg, nil
}
610116
func (h *baseStatsHandler) Collect(in chan<- prometheus.Metric) {
	h.collector.Collect(in)
}
1369046
func (c *TxnCollector) Collect(ch chan<- prometheus.Metric) {
	c.txnOpsTotalCounter.Collect(ch)
}
488068
func (s *Collector) Collect(c *container.Container) chan interface{} {
	s.m.Lock()
	defer s.m.Unlock()
	publisher, exists := s.publishers[c]
	if !exists {
		publisher = pubsub.NewPublisher(100*time.Millisecond, 1024)
		s.publishers[c] = publisher
	}
	return publisher.Subscribe()
}
471897
func (b *Base) Collect() error {
	if b.Pid > 0 {
		return nil
	}

	var err error
	b.Hostname, err = os.Hostname()
	if err != nil {
		return err
	}

	b.Time = time.Now()
	b.Process = os.Args[0]
	b.Pid = os.Getpid()

	return nil
}
949537
func (g *phpfpm) Gather(acc telegraf.Accumulator) error {
	if len(g.Urls) == 0 {
		return g.gatherServer("http://127.0.0.1/status", acc)
	}

	var wg sync.WaitGroup

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

	wg.Wait()

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