// checkGC should only be called from the main command-processing
// goroutine.
328065
func (r *runner) checkGC(ctx context.Context) (err error) {
	if r.gcDone {
		return nil
	}
	r.gcDone = true

	if !r.isManagedByApp() {
		r.log.CDebugf(ctx, "Skipping GC check")
		return nil
	}

	r.log.CDebugf(ctx, "Checking for GC")

	var stageSync sync.Once
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	go func() {
		timer := time.NewTimer(gcPrintStatusThreshold)
		select {
		case <-timer.C:
			stageSync.Do(func() {
				r.printStageStart(ctx,
					[]byte("Checking repo for inefficiencies... "),
					"mem.gc.prof", "cpu.gc.prof")
			})
		case <-ctx.Done():
			timer.Stop()
		}
	}()
	defer func() {
		// Prevent stage from starting after we finish the stage.
		stageSync.Do(func() {})
		if err == nil {
			r.printStageEndIfNeeded(ctx)
		}
	}()

	fs, _, err := libgit.GetRepoAndID(
		ctx, r.config, r.h, r.repo, r.uniqID)
	if _, noRepo := errors.Cause(err).(libkb.RepoDoesntExistError); noRepo {
		r.log.CDebugf(ctx, "No such repo: %v", err)
		return nil
	} else if err != nil {
		return err
	}

	lastGCTime, err := libgit.LastGCTime(ctx, fs)
	if err != nil {
		return err
	}
	if r.config.Clock().Now().Sub(lastGCTime) < minGCInterval {
		r.log.CDebugf(ctx, "Last GC happened at %s; skipping GC check",
			lastGCTime)
		return nil
	}

	storage, err := libgit.NewGitConfigWithoutRemotesStorer(fs)
	if err != nil {
		return err
	}

	gco := libgit.GCOptions{
		MaxLooseRefs:         defaultMaxLooseRefs,
		PruneMinLooseObjects: defaultPruneMinLooseObjects,
		PruneExpireTime:      time.Time{},
		MaxObjectPacks:       defaultMaxObjectPacks,
	}
	doPackRefs, _, doPruneLoose, doObjectRepack, _, err := libgit.NeedsGC(
		storage, gco)
	if err != nil {
		return err
	}
	if !doPackRefs && !doPruneLoose && !doObjectRepack {
		r.log.CDebugf(ctx, "No GC needed")
		return nil
	}
	r.log.CDebugf(ctx, "GC needed: doPackRefs=%t, doPruneLoose=%t, "+
		"doObjectRepack=%t", doPackRefs, doPruneLoose, doObjectRepack)
	command := fmt.Sprintf("keybase git gc %s", r.repo)
	if r.h.Type() == tlf.SingleTeam {
		tid := r.h.FirstResolvedWriter()
		teamName, err := r.config.KBPKI().GetNormalizedUsername(
			ctx, tid, r.config.OfflineAvailabilityForID(r.h.TlfID()))
		if err != nil {
			return err
		}
		command += fmt.Sprintf(" --team %s", teamName)
	}
	r.errput.Write([]byte("Tip: this repo could be sped up with some " +
		"garbage collection. Run this command:\n"))
	r.errput.Write([]byte("\t" + command + "\n"))
	return nil
}
273967
func (probe *GrpcHealthProbe) Check() error {
	ctx, cancel := context.WithTimeout(context.Background(), probe.timeout)
	defer cancel()

	connection, err := grpc.DialContext(ctx, probe.server, probe.dialOptions...)
	if err != nil {
		return err
	}
	defer connection.Close()

	client := hv1.NewHealthClient(connection)
	response, err := client.Check(ctx, probe.request)
	if err != nil {
		return err
	}
	if response == nil || (response != nil && response.Status != hv1.HealthCheckResponse_SERVING) {
		return ErrGRPCUnhealthy
	}

	return nil
}
282410
func (gco *GCOp) checkConflict(
	ctx context.Context, renamer ConflictRenamer, mergedOp op,
	isFile bool) (crAction, error) {
	return nil, nil
}
176572
func checkCRC(r io.Reader, expect uint32) error {
	msgCRC, err := extractUint32(r)
	if err != nil {
		return err
	}

	if msgCRC != expect {
		return fmt.Errorf("Checksum Mismatch, MessageCRC of 0x%X does not equal expected CRC of 0x%X", msgCRC, expect)

	}
	return nil
}
513175
func (cd service) Check() error {
	writableErr := neoutils.CheckWritable(cd.conn)
	if writableErr != nil {
		return writableErr
	}

	return neoutils.Check(cd.conn)
}
482495
func (c *CoreScheduler) evalGC(eval *structs.Evaluation) error {
	// Iterate over the evaluations
	ws := memdb.NewWatchSet()
	iter, err := c.snap.Evals(ws)
	if err != nil {
		return err
	}

	var oldThreshold uint64
	if eval.JobID == structs.CoreJobForceGC {
		// The GC was forced, so set the threshold to its maximum so everything
		// will GC.
		oldThreshold = math.MaxUint64
		c.logger.Debug("forced eval GC")
	} else {
		// Compute the old threshold limit for GC using the FSM
		// time table.  This is a rough mapping of a time to the
		// Raft index it belongs to.
		tt := c.srv.fsm.TimeTable()
		cutoff := time.Now().UTC().Add(-1 * c.srv.config.EvalGCThreshold)
		oldThreshold = tt.NearestIndex(cutoff)
		c.logger.Debug("eval GC scanning before cutoff index",
			"index", oldThreshold, "eval_gc_threshold", c.srv.config.EvalGCThreshold)
	}

	// Collect the allocations and evaluations to GC
	var gcAlloc, gcEval []string
	for raw := iter.Next(); raw != nil; raw = iter.Next() {
		eval := raw.(*structs.Evaluation)

		// The Evaluation GC should not handle batch jobs since those need to be
		// garbage collected in one shot
		gc, allocs, err := c.gcEval(eval, oldThreshold, false)
		if err != nil {
			return err
		}

		if gc {
			gcEval = append(gcEval, eval.ID)
		}
		gcAlloc = append(gcAlloc, allocs...)
	}

	// Fast-path the nothing case
	if len(gcEval) == 0 && len(gcAlloc) == 0 {
		return nil
	}
	c.logger.Debug("eval GC found eligibile objects",
		"evals", len(gcEval), "allocs", len(gcAlloc))

	return c.evalReap(gcEval, gcAlloc)
}
1363727
func (r *ShardedTTL) StartGC(gcInterval time.Duration) {
	r.gcInterval = gcInterval
	go func() {
		for _ = range time.Tick(gcInterval) {
			r.Lock()
			for tenantID := range r.setAts {
				for key := range r.setAts[tenantID] {
					if !r.isValid(tenantID, key) {
						r.delete(tenantID, key)
					}
				}
			}
			r.Unlock()
		}
	}()
}
684030
func OptionCheck(args []string) (err error) {
	opt := newOption(ioutil.Discard, flag.ContinueOnError)
	if e := opt.parse(args); e != nil {
		return fmt.Errorf("%v, %v", CommandName, e)
	}
	return nil
}
22284
func (s *ProjectsService) RunGC(projectName string, input *GCInput) (*Response, error) {
	u := fmt.Sprintf("projects/%s/gc'", url.QueryEscape(projectName))

	req, err := s.client.NewRequest("POST", u, input)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.Do(req, nil)
	if err != nil {
		return resp, err
	}

	return resp, err
}
1175927
func (d *frameDec) checkCRC() error {
	if !d.HasCheckSum {
		return nil
	}
	var tmp [8]byte
	gotB := d.crc.Sum(tmp[:0])
	// Flip to match file order.
	gotB[0] = gotB[7]
	gotB[1] = gotB[6]
	gotB[2] = gotB[5]
	gotB[3] = gotB[4]

	// We can overwrite upper tmp now
	want := d.rawInput.readSmall(4)
	if want == nil {
		println("CRC missing?")
		return io.ErrUnexpectedEOF
	}

	if !bytes.Equal(gotB[:4], want) {
		println("CRC Check Failed:", gotB[:4], "!=", want)
		return ErrCRCMismatch
	}
	println("CRC ok")
	return nil
}
1287307
func check(err error) {
	if err != nil {
		b := make([]byte, 2<<10)
		b = b[:runtime.Stack(b, false)]
		log.Printf("Unlikely error condition triggered: %v at %s", err, b)
		panic(err)
	}
}
751685
func ExtensionForceGC() {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)

	// Free up gc memory first
	fmt.Printf("mem stats (before): alloc: %v sys: %v\n", m.Alloc, m.Sys)
	fmt.Printf("Starting force gc\n")
	debug.FreeOSMemory()
	fmt.Printf("Done force gc\n")
	runtime.ReadMemStats(&m)
	fmt.Printf("mem stats (after): alloc: %v sys: %v\n", m.Alloc, m.Sys)

	if !ExtensionIsInited() {
		fmt.Printf("Not initialized, bailing\n")
		return
	}

	// Free all caches, and run gc again to clear out anything
	fmt.Printf("Flushing global caches\n")
	kbCtx.FlushCaches()
	if _, ok := kbCtx.LocalChatDb.GetEngine().(*libkb.MemDb); ok {
		fmt.Printf("Nuking in memory chat db\n")
		kbCtx.LocalChatDb.Nuke()
	}
	if _, ok := kbCtx.LocalDb.GetEngine().(*libkb.MemDb); ok {
		fmt.Printf("Nuking in memory local db\n")
		kbCtx.LocalDb.Nuke()
	}
	debug.FreeOSMemory()
	fmt.Printf("Done flushing global caches\n")
	runtime.ReadMemStats(&m)
	fmt.Printf("mem stats (after flush): alloc: %v sys: %v\n", m.Alloc, m.Sys)
}
174581
func (c *InstanceCache) GC(ctx context.Context, now time.Time) {
	c.withState(ctx, now, func(s *messages.InstanceCache) {
		c.gc(ctx, s, now)
	})
}
75661
func (wg *WaitGroup) Go(cb func()) {
	wg.wg.Add(1)
	go func() {
		cb()
		wg.wg.Done()
	}()
}
1216920
func (u *updater) Check() error {
	u.mu.Lock()
	defer u.mu.Unlock()

	return u.status
}
827271
func (c certificate) Check(d *certdata.Data) *errors.Errors {
	var e = errors.New(nil)

	for _, cc := range c {
		if cc.filter != nil && !cc.filter.Check(d) {
			continue
		}
		e.Append(cc.f(d))
	}

	return e
}
452770
func (r *MemoryTTL) StopGC() {
	if r.gcTicker != nil {
		r.Lock()
		r.gcTicker.Stop()
		r.gcTicker = nil
		close(r.done)
		r.done = nil
		r.Unlock()
	}
}