// StartGarbageCollection starts garbage collection threads.
16809
func (kl *Kubelet) StartGarbageCollection() {
	loggedContainerGCFailure := false
	go wait.Until(func() {
		if err := kl.containerGC.GarbageCollect(); err != nil {
			klog.Errorf("Container garbage collection failed: %v", err)
			kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.ContainerGCFailed, err.Error())
			loggedContainerGCFailure = true
		} else {
			var vLevel klog.Level = 4
			if loggedContainerGCFailure {
				vLevel = 1
				loggedContainerGCFailure = false
			}

			klog.V(vLevel).Infof("Container garbage collection succeeded")
		}
	}, ContainerGCPeriod, wait.NeverStop)

	// when the high threshold is set to 100, stub the image GC manager
	if kl.kubeletConfiguration.ImageGCHighThresholdPercent == 100 {
		klog.V(2).Infof("ImageGCHighThresholdPercent is set 100, Disable image GC")
		return
	}

	prevImageGCFailed := false
	go wait.Until(func() {
		if err := kl.imageManager.GarbageCollect(); err != nil {
			if prevImageGCFailed {
				klog.Errorf("Image garbage collection failed multiple times in a row: %v", err)
				// Only create an event for repeated failures
				kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.ImageGCFailed, err.Error())
			} else {
				klog.Errorf("Image garbage collection failed once. Stats initialization may not have completed yet: %v", err)
			}
			prevImageGCFailed = true
		} else {
			var vLevel klog.Level = 4
			if prevImageGCFailed {
				vLevel = 1
				prevImageGCFailed = false
			}

			klog.V(vLevel).Infof("Image garbage collection succeeded")
		}
	}, ImageGCPeriod, wait.NeverStop)
}
616233
func (g *GenericPLEG) Start() {
	go wait.Until(g.relist, g.relistPeriod, wait.NeverStop)
}
879920
func (c *cache) start(a *Allocator) waitChan {
	listDone := make(waitChan)

	c.mutex.Lock()

	// start with a fresh nextCache
	c.nextCache = idMap{}
	c.nextKeyCache = keyMap{}
	c.mutex.Unlock()

	c.stopWatchWg.Add(1)

	go func() {
		<-c.backend.Connected()
		logger := c.getLogger()
		logger.Info("Starting to watch allocation changes")

		watcher := c.backend.ListAndWatch(c.prefix, c.prefix, 512)

		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					goto abort
				}
				if event.Typ == kvstore.EventTypeListDone {
					c.mutex.Lock()
					// nextCache is valid, point the live cache to it
					c.cache = c.nextCache
					c.keyCache = c.nextKeyCache
					c.mutex.Unlock()

					// report that the list operation has
					// been completed and the allocator is
					// ready to use
					close(listDone)
					continue
				}

				id := c.keyToID(event.Key, c.deleteInvalidPrefixes)
				if id != 0 {
					c.mutex.Lock()

					var key AllocatorKey

					if len(event.Value) > 0 {
						var err error
						key, err = a.keyType.PutKey(string(event.Value))
						if err != nil {
							c.getLogger().WithError(err).WithField(fieldKey, event.Value).
								Warning("Unable to unmarshal allocator key")
						}
					}
					debugFields := c.getLogger().WithFields(logrus.Fields{fieldKey: key, fieldID: id})

					switch event.Typ {
					case kvstore.EventTypeCreate:
						kvstore.Trace("Adding id to cache", nil, debugFields.Data)
						c.nextCache[id] = key
						if key != nil {
							c.nextKeyCache[key.GetKey()] = id
						}
						a.idPool.Remove(id)

					case kvstore.EventTypeModify:
						kvstore.Trace("Modifying id in cache", nil, debugFields.Data)
						if k, ok := c.nextCache[id]; ok {
							delete(c.nextKeyCache, k.GetKey())
						}

						c.nextCache[id] = key
						if key != nil {
							c.nextKeyCache[key.GetKey()] = id
						}

					case kvstore.EventTypeDelete:
						kvstore.Trace("Removing id from cache", nil, debugFields.Data)

						if a.enableMasterKeyProtection {
							if value := a.localKeys.lookupID(id); value != "" {
								a.recreateMasterKey(id, value, true)
								break
							}
						}

						if k, ok := c.nextCache[id]; ok && k != nil {
							delete(c.nextKeyCache, k.GetKey())
						}

						delete(c.nextCache, id)
						a.idPool.Insert(id)
					}
					c.mutex.Unlock()

					if a.events != nil {
						a.events <- AllocatorEvent{
							Typ: event.Typ,
							ID:  idpool.ID(id),
							Key: key,
						}
					}
				}

			case <-c.stopChan:
				goto abort
			}
		}

	abort:
		watcher.Stop()
		// Signal that watcher is done
		c.stopWatchWg.Done()
	}()

	return listDone
}
31438
func (r *MemoryTTL) StartGC(gcInterval time.Duration) {
	if gcInterval <= 0 {
		return
	}

	ticker := time.NewTicker(gcInterval)
	done := make(chan struct{})

	r.Lock()
	r.gcTicker = ticker
	r.done = done
	r.Unlock()

	go func() {
		for {
			select {
			case <-ticker.C:
				now := time.Now()

				r.Lock()
				for key := range r.cache.items {
					if !r.isValidTime(key, now) {
						r.delete(key)
					}
				}
				r.Unlock()
			case <-done:
				return
			}
		}
	}()
}
608120
func (w *workManager) Start() {

	w.mutex.Lock()
	defer w.mutex.Unlock()

	if w.state == workManagerStopped {
		w.state = workManagerRunning
		go func() {
			for {
				select {
				case <-w.collectq.Err:
					//TODO: log error
				case <-w.processq.Err:
					//TODO: log error
				case <-w.publishq.Err:
					//TODO: log error
				case <-w.kill:
					return
				}
			}
		}()
	}
}
1225093
func (rl *MemoryReplayLog) Start() error {
	rl.batches = make(map[string]*ReplaySet)
	rl.entries = make(map[HashPrefix]uint32)
	return nil
}
788196
func (m *MemoryStorer) StartCleaner() {
	if m.maxAge == 0 || m.cleanInterval == 0 {
		panic("both max age and clean interval must be set to non-zero")
	}

	// init quit chan
	m.quit = make(chan struct{})

	m.wg.Add(1)

	// Start the cleaner infinite loop go routine.
	// StopCleaner() can be used to kill this go routine.
	go m.cleanerLoop()
}
147267
func (tc *TreeCache) Start() error {
	if !tc.state.Change(curator.LATENT, curator.STARTED) {
		return errors.New("already started")
	}
	if tc.createParentNodes {
		_, err := tc.client.Create().CreatingParentsIfNeeded().ForPath(tc.root.path)
		if err != nil {
			return fmt.Errorf("Failed to create parents: %s", err)
		}
	}
	tc.client.ConnectionStateListenable().AddListener(tc.connectionStateListener)
	if tc.client.ZookeeperClient().Connected() {
		tc.root.wasCreated()
	}
	return nil
}
665983
func (rh *RPCHandler) Gc(
	ctx context.Context, arg keybase1.GcArg) (err error) {
	rh.log.CDebugf(ctx, "Garbage-collecting repo %s from folder %s/%s",
		arg.Name, arg.Folder.FolderType, arg.Folder.Name)
	defer func() {
		rh.log.CDebugf(ctx, "Done garbage-collecting repo: %+v", err)
	}()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	ctx, gitConfig, tlfHandle, tempDir, err := rh.getHandleAndConfig(
		ctx, arg.Folder)
	if err != nil {
		return err
	}
	defer func() {
		rmErr := os.RemoveAll(tempDir)
		if rmErr != nil {
			rh.log.CDebugf(
				ctx, "Error cleaning storage dir %s: %+v\n", tempDir, rmErr)
		}
	}()
	defer gitConfig.Shutdown(ctx)

	gco := GCOptions{
		MaxLooseRefs:         arg.Options.MaxLooseRefs,
		PruneMinLooseObjects: arg.Options.PruneMinLooseObjects,
		PruneExpireTime:      keybase1.FromTime(arg.Options.PruneExpireTime),
		MaxObjectPacks:       arg.Options.MaxObjectPacks,
	}
	err = GCRepo(ctx, gitConfig, tlfHandle, string(arg.Name), gco)
	if err != nil {
		return err
	}

	return rh.waitForJournal(ctx, gitConfig, tlfHandle)
}
274310
func (z *Zipkin) Start(acc telegraf.Accumulator) error {
	z.handler = NewSpanHandler(z.Path)

	var wg sync.WaitGroup
	z.waitGroup = &wg

	router := mux.NewRouter()
	converter := NewLineProtocolConverter(acc)
	if err := z.handler.Register(router, converter); err != nil {
		return err
	}

	z.server = &http.Server{
		Handler: router,
	}

	addr := ":" + strconv.Itoa(z.Port)
	ln, err := net.Listen(DefaultNetwork, addr)
	if err != nil {
		return err
	}

	z.address = ln.Addr().String()
	log.Printf("I! Started the zipkin listener on %s", z.address)

	go func() {
		wg.Add(1)
		defer wg.Done()

		z.Listen(ln, acc)
	}()

	return nil
}
404768
func (c *Carbon) StartOfDecade() *Carbon {
	year := c.Year() - c.Year()%yearsPerDecade

	return create(year, time.January, 1, 0, 0, 0, 0, c.Location())
}
999532
func (m *kubeGenericRuntimeManager) GarbageCollect(gcPolicy kubecontainer.ContainerGCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error {
	return m.containerGC.GarbageCollect(gcPolicy, allSourcesReady, evictNonDeletedPods)
}
898591
func (p *MysqlProvider) GC() {
	if _, err := p.c.Exec("DELETE FROM session WHERE  expiry + ? <= UNIX_TIMESTAMP(NOW())", p.expire); err != nil {
		log.Printf("session/mysql: error garbage collecting: %v", err)
	}
}
387842
func (w *DefaultWorker) Start() (<-chan *Task, <-chan error) {
	w.smu.Lock()
	defer w.smu.Unlock()

	w.state = open
	w.lifecycle.SetQueues(w.availableTasks, w.workingTasks)
	w.janitorRunner = newJanitorRunner(w.pool, w.detector, w.janitor, w.availableTasks)

	errs1 := w.janitorRunner.Start()
	tasks, errs2 := w.lifecycle.Listen()

	return tasks, concatErrs(errs1, errs2)
}
1098126
func (a *application) runArchivist(c context.Context) error {
	cfg := a.ServiceConfig()

	coordCfg, acfg := cfg.GetCoordinator(), cfg.GetArchivist()
	switch {
	case coordCfg == nil:
		fallthrough

	case acfg == nil:
		return errors.New("missing required config: archivist")
	case acfg.GsStagingBucket == "":
		return errors.New("missing required config: archivist.gs_staging_bucket")
	}

	// Initialize our Storage.
	//
	// NOTE: We're requesting read/write access even though we only need read-only
	// access because GKE doesn't understand the read-only scope:
	// https://www.googleapis.com/auth/bigtable.readonly
	st, err := a.IntermediateStorage(c, true)
	if err != nil {
		log.WithError(err).Errorf(c, "Failed to get storage instance.")
		return err
	}
	defer st.Close()

	// Defines our Google Storage client project scoped factory.
	gsClientFactory := func(ctx context.Context, proj types.ProjectName) (gs.Client, error) {
		gsClient, err := a.GSClient(ctx, proj)
		if err != nil {
			log.WithError(err).Errorf(c, "Failed to get Google Storage client.")
			return nil, err
		}
		return gsClient, nil
	}

	// Initialize a Coordinator client that bundles requests together.
	coordClient := &bundleServicesClient.Client{
		ServicesClient:       a.Coordinator(),
		DelayThreshold:       time.Second,
		BundleCountThreshold: 100,
	}
	defer coordClient.Flush()

	ar := archivist.Archivist{
		Service:         coordClient,
		SettingsLoader:  a.GetSettingsLoader(acfg),
		Storage:         st,
		GSClientFactory: gsClientFactory,
	}

	// Application shutdown will now operate by stopping the Iterator.
	c, cancelFunc := context.WithCancel(c)
	defer cancelFunc()

	// Application shutdown will now operate by cancelling the Archivist's
	// shutdown Context.
	a.SetShutdownFunc(cancelFunc)

	// Update our settings periodicall.
	go settingsUpdater(c)

	return runForever(c, ar)
}
264617
func startMemoryProfiler() func() {
	if *flagMemProfile == "" {
		return nil
	}

	return func() {
		file, err := os.Create(*flagMemProfile)
		if err != nil {
			logrus.WithError(err).Error("Failed to create memory profile results file")
			return
		}
		defer file.Close()

		logrus.WithField("file", *flagMemProfile).Info("Dumping memory profile")
		if err := pprof.WriteHeapProfile(file); err != nil {
			logrus.WithError(err).Error("Failed to write heap profile")
		}
	}
}
632213
func (a *Allocations) GarbageCollect(args *nstructs.AllocSpecificRequest, reply *nstructs.GenericResponse) error {
	defer metrics.MeasureSince([]string{"client", "allocations", "garbage_collect"}, time.Now())

	// Check submit job permissions
	if aclObj, err := a.c.ResolveToken(args.AuthToken); err != nil {
		return err
	} else if aclObj != nil && !aclObj.AllowNsOp(args.Namespace, acl.NamespaceCapabilitySubmitJob) {
		return nstructs.ErrPermissionDenied
	}

	if !a.c.CollectAllocation(args.AllocID) {
		// Could not find alloc
		return nstructs.NewErrUnknownAllocation(args.AllocID)
	}

	return nil
}