// sophie.CollectCloser interface
975231
func (kvw *Writer) Collect(key, val sophie.SophieWriter) error {
	// write key
	kvw.objBuf.Reset()
	key.WriteTo(&kvw.objBuf)
	if err := sophie.VInt(len(kvw.objBuf)).WriteTo(kvw.writer); err != nil {
		return err
	}
	if _, err := kvw.writer.Write([]byte(kvw.objBuf)); err != nil {
		return err
	}
	// write val
	kvw.objBuf.Reset()
	val.WriteTo(&kvw.objBuf)
	if err := sophie.VInt(len(kvw.objBuf)).WriteTo(kvw.writer); err != nil {
		return err
	}
	if _, err := kvw.writer.Write([]byte(kvw.objBuf)); err != nil {
		return err
	}
	// success
	return nil
}
1258078
func (m *MultiError) Collect(err error) {
	if err != nil {
		m.Errors = append(m.Errors, err)
	}
}
481094
func (c *Collector) Collect(ctx context.Context, count uint64) {
	start := time.Now()
	for i := uint64(0); i < count; i++ {
		conn, err := c.ln.Accept()
		if err != nil {
			log.G(ctx).WithError(err).Error("failure accepting connection")
			continue
		}
		c.t.UpdateSince(start)
		conn.Close()
	}
}
40087
func (c *KafkaCollector) Collect(s *zipkincore.Span) error {
	c.producer.Input() <- &sarama.ProducerMessage{
		Topic: c.topic,
		Key:   nil,
		Value: sarama.ByteEncoder(kafkaSerialize(s)),
	}
	return nil
}
953431
func ToReadCloser(r io.Reader) io.ReadCloser {
	if rc, ok := r.(io.ReadCloser); ok {
		return rc
	}

	return struct {
		io.Reader
		io.Closer
	}{
		r,
		ioutil.NopCloser(nil),
	}
}
991630
func (f *FileStore) Close() error {
	// Make the object appear closed to other method calls.
	f.mu.Lock()

	files := f.files

	f.lastFileStats = nil
	f.files = nil
	f.tracker.ClearFileCounts()

	// Let other methods access this closed object while we do the actual closing.
	f.mu.Unlock()

	for _, file := range files {
		err := file.Close()
		if err != nil {
			return err
		}
	}

	return nil
}
879457
func (c *appsCollector) Collect(ch chan<- prometheus.Metric) {
	result, err := c.lister.List(labels.Everything())
	if err != nil {
		klog.V(4).Infof("Collecting metrics for apps failed: %v", err)
		return
	}

	var available, failed, cancelled float64

	latestFailedRollouts := map[string]failedRollout{}

	for _, d := range result {
		dcName := util.DeploymentConfigNameFor(d)
		if len(dcName) == 0 {
			continue
		}
		latestVersion := util.DeploymentVersionFor(d)
		key := d.Namespace + "/" + dcName

		if util.IsTerminatedDeployment(d) {
			if util.IsDeploymentCancelled(d) {
				cancelled++
				continue
			}
			if util.IsFailedDeployment(d) {
				failed++
				// Track the latest failed rollout per deployment config
				// continue only when this is the latest version (add if below)
				if r, exists := latestFailedRollouts[key]; exists && latestVersion <= r.latestVersion {
					continue
				}
				latestFailedRollouts[key] = failedRollout{
					timestamp:     float64(d.CreationTimestamp.Unix()),
					latestVersion: latestVersion,
				}
				continue
			}
			if util.IsCompleteDeployment(d) {
				// If a completed rollout is found AFTER we recorded a failed rollout,
				// do not record the lastFailedRollout as the latest rollout is not
				// failed.
				if r, hasFailedRollout := latestFailedRollouts[key]; hasFailedRollout && r.latestVersion < latestVersion {
					delete(latestFailedRollouts, key)
				}
				available++
				continue
			}
		}

		// TODO: Figure out under what circumstances the phase is not set.
		phase := strings.ToLower(string(util.DeploymentStatusFor(d)))
		if len(phase) == 0 {
			phase = "unknown"
		}

		// Record duration in seconds for active rollouts
		// TODO: possible time skew?
		durationSeconds := c.nowFn().Unix() - d.CreationTimestamp.Unix()
		ch <- prometheus.MustNewConstMetric(
			activeRolloutDurationSecondsDesc,
			prometheus.CounterValue,
			float64(durationSeconds),
			[]string{
				d.Namespace,
				dcName,
				phase,
				fmt.Sprintf("%d", latestVersion),
			}...)
	}

	// Record latest failed rollouts
	for dc, r := range latestFailedRollouts {
		parts := strings.Split(dc, "/")
		ch <- prometheus.MustNewConstMetric(
			lastFailedRolloutTimeDesc,
			prometheus.GaugeValue,
			r.timestamp,
			[]string{
				parts[0],
				parts[1],
				fmt.Sprintf("%d", r.latestVersion),
			}...)
	}

	ch <- prometheus.MustNewConstMetric(completeRolloutCountDesc, prometheus.GaugeValue, available, []string{availablePhase}...)
	ch <- prometheus.MustNewConstMetric(completeRolloutCountDesc, prometheus.GaugeValue, failed, []string{failedPhase}...)
	ch <- prometheus.MustNewConstMetric(completeRolloutCountDesc, prometheus.GaugeValue, cancelled, []string{cancelledPhase}...)
}
1087797
func CollectResult(ctx context.Context, gcOut <-chan gc.Result, cb func(cid.Cid)) error {
	var errors []error
loop:
	for {
		select {
		case res, ok := <-gcOut:
			if !ok {
				break loop
			}
			if res.Error != nil {
				errors = append(errors, res.Error)
			} else if res.KeyRemoved.Defined() && cb != nil {
				cb(res.KeyRemoved)
			}
		case <-ctx.Done():
			errors = append(errors, ctx.Err())
			break loop
		}
	}

	switch len(errors) {
	case 0:
		return nil
	case 1:
		return errors[0]
	default:
		return NewMultiError(errors...)
	}
}
1320896
func (ms *MemSorters) CollectTo(part int, key, val sophie.SophieWriter) error {
	ms.RLock()
	sorter, ok := ms.sorters[part]
	ms.RUnlock()
	if !ok {
		ms.Lock()
		sorter, ok = ms.sorters[part]
		if !ok {
			sorter = &memSorter{}
			ms.sorters[part] = sorter
		}
		ms.Unlock()
	}
	sorter.Lock()
	defer sorter.Unlock()

	sorter.KeyOffs.Add(len(sorter.Buffer))
	key.WriteTo(&sorter.Buffer)
	sorter.ValOffs.Add(len(sorter.Buffer))
	val.WriteTo(&sorter.Buffer)
	sorter.ValEnds.Add(len(sorter.Buffer))

	return nil
}
318875
func (c *Chan) CollectSome(limit int64) []Path {
	acc := make([]Path, 0, 0)
	c.DoSome(func(ts Path) {
		acc = append(acc, ts)
	}, limit)
	return acc
}
1293932
func (m *Metrics) Collect() (a map[string]AggregatedMetrics) {
	a = make(map[string]AggregatedMetrics)

	for _, fnName := range m.FunctionNames {
		metric := Metric{
			Config:       m.Config,
			FunctionName: fnName,
		}

		a[fnName] = metric.Collect()
	}

	return
}
1283819
func collectHeapProfile(filename string) (done func()) {
	heapProf, err := os.Create(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create file for heap profile: %v\n", err)
		return
	}
	return func() {
		runtime.GC() // get up-to-date statistics
		if err := pprof.WriteHeapProfile(heapProf); err != nil {
			_ = heapProf.Close()
			fmt.Fprintf(os.Stderr, "failed to write heap profile to file: %v\n", err)
			return
		}
		if err := heapProf.Close(); err != nil {
			fmt.Fprintf(os.Stderr, "failed to close file for heap profile: %v\n", err)
			return
		}
	}
}
352878
func (c *fileCacheable) ReadCloser() (io.ReadCloser, error) {
	// Check if the file has to be returned directly because
	// it is too large.
	if c.tooLarge {
		f, err := os.Open(c.fullname)
		if err != nil {
			return nil, errors.Annotate(err, ErrFileLoading, errorMessages, c.name)
		}
		return f, nil
	}
	// It's a cached buffer, so return this.
	return &fileBuffer{bytes.NewBuffer(c.data)}, nil
}
664231
func (db *database) GetCollection(name string) (collection mongo.Collection, closer SessionCloser) {
	info, found := db.schema[name]
	if !found {
		logger.Errorf("using unknown collection %q", name)
		if featureflag.Enabled(feature.DeveloperMode) {
			logger.Errorf("from %s", string(debug.Stack()))
		}
	}

	// Copy session if necessary.
	if db.ownSession {
		collection = mongo.WrapCollection(db.raw.C(name))
		closer = dontCloseAnything
	} else {
		collection, closer = mongo.CollectionFromName(db.raw, name)
	}

	// Apply model filtering.
	if !info.global {
		collection = &modelStateCollection{
			WriteCollection: collection.Writeable(),
			modelUUID:       db.modelUUID,
		}
	}

	// Prevent layer-breaking.
	if !info.rawAccess {
		// TODO(fwereade): it would be nice to tweak the mongo.Collection
		// interface a bit to drop Writeable in this situation, but it's
		// not convenient yet.
	}
	return collection, closer
}
1235565
func (h *Handler) PrometheusCollectors() []prometheus.Collector {
	return []prometheus.Collector{
		h.requests,
		h.requestDur,
	}
}
718661
func (d *Death) closeInMass(closable ...io.Closer) (err error) {

	count := len(closable)
	sentToClose := make(map[int]closer)
	//call close async
	doneClosers := make(chan closer, count)
	for i, c := range closable {
		name, pkgPath := getPkgPath(c)
		closer := closer{Index: i, C: c, Name: name, PKGPath: pkgPath}
		go d.closeObjects(closer, doneClosers)
		sentToClose[i] = closer
	}

	// wait on channel for notifications.
	timer := time.NewTimer(d.timeout)
	failedClosers := []closer{}
	for {
		select {
		case <-timer.C:
			s := "failed to close: "
			pkgs := []string{}
			for _, c := range sentToClose {
				pkgs = append(pkgs, fmt.Sprintf("%s/%s", c.PKGPath, c.Name))
				d.log.Error("Failed to close: ", c.PKGPath, "/", c.Name)
			}
			return fmt.Errorf("%s", fmt.Sprintf("%s %s", s, strings.Join(pkgs, ", ")))
		case closer := <-doneClosers:
			delete(sentToClose, closer.Index)
			count--
			if closer.Err != nil {
				failedClosers = append(failedClosers, closer)
			}

			d.log.Debug(count, " object(s) left")
			if count != 0 || len(sentToClose) != 0 {
				continue
			}

			if len(failedClosers) != 0 {
				errString := generateErrString(failedClosers)
				return fmt.Errorf("errors from closers: %s", errString)
			}

			return nil
		}
	}
}
118589
func (a *Group) Collect(waitables ...Waitable) {
	a.Lock()
	a.waitables = append(a.waitables, waitables...)
	a.Unlock()
}