// Run sets openAPIAggregationManager and starts workers
322450
func (c *Controller) Run(staticSpec *spec.Swagger, openAPIService *handler.OpenAPIService, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()
	defer klog.Infof("Shutting down OpenAPI controller")

	klog.Infof("Starting OpenAPI controller")

	c.staticSpec = staticSpec
	c.openAPIService = openAPIService

	if !cache.WaitForCacheSync(stopCh, c.crdsSynced) {
		utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
		return
	}

	// create initial spec to avoid merging once per CRD on startup
	crds, err := c.crdLister.List(labels.Everything())
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("failed to initially list all CRDs: %v", err))
		return
	}
	for _, crd := range crds {
		if !apiextensions.IsCRDConditionTrue(crd, apiextensions.Established) {
			continue
		}
		newSpecs, changed, err := buildVersionSpecs(crd, nil)
		if err != nil {
			utilruntime.HandleError(fmt.Errorf("failed to build OpenAPI spec of CRD %s: %v", crd.Name, err))
		} else if !changed {
			continue
		}
		c.crdSpecs[crd.Name] = newSpecs
	}
	if err := c.updateSpecLocked(); err != nil {
		utilruntime.HandleError(fmt.Errorf("failed to initially create OpenAPI spec for CRDs: %v", err))
		return
	}

	// only start one worker thread since its a slow moving API
	go wait.Until(c.runWorker, time.Second, stopCh)

	<-stopCh
}
1343988
func (a *MachineAgent) Run(*cmd.Context) (err error) {
	defer a.Done(err)
	useMultipleCPUs()
	if err := a.ReadConfig(a.Tag().String()); err != nil {
		return errors.Errorf("cannot read agent configuration: %v", err)
	}

	setupAgentLogging(a.CurrentConfig())

	if err := introspection.WriteProfileFunctions(); err != nil {
		// This isn't fatal, just annoying.
		logger.Errorf("failed to write profile funcs: %v", err)
	}

	// When the API server and peergrouper have manifolds, they can
	// have dependencies on a central hub worker.
	a.centralHub = centralhub.New(a.Tag().(names.MachineTag))

	// Before doing anything else, we need to make sure the certificate generated for
	// use by mongo to validate controller connections is correct. This needs to be done
	// before any possible restart of the mongo service.
	// See bug http://pad.lv/1434680
	if err := a.AgentConfigWriter.ChangeConfig(upgradeCertificateDNSNames); err != nil {
		return errors.Annotate(err, "error upgrading server certificate")
	}

	// moved from NewMachineAgent here because the agent config could not be ready yet there.
	if err := a.registerPrometheusCollectors(); err != nil {
		return errors.Trace(err)
	}

	agentConfig := a.CurrentConfig()
	agentName := a.Tag().String()
	machineLock, err := machinelock.New(machinelock.Config{
		AgentName:   agentName,
		Clock:       clock.WallClock,
		Logger:      loggo.GetLogger("juju.machinelock"),
		LogFilename: agent.MachineLockLogFilename(agentConfig),
	})
	// There will only be an error if the required configuration
	// values are not passed in.
	if err != nil {
		return errors.Trace(err)
	}
	a.machineLock = machineLock
	a.upgradeComplete = upgradesteps.NewLock(agentConfig)

	createEngine := a.makeEngineCreator(agentName, agentConfig.UpgradedToVersion())
	charmrepo.CacheDir = filepath.Join(agentConfig.DataDir(), "charmcache")
	if err := a.createJujudSymlinks(agentConfig.DataDir()); err != nil {
		return err
	}
	a.runner.StartWorker("engine", createEngine)

	// At this point, all workers will have been configured to start
	close(a.workersStarted)
	err = a.runner.Wait()
	switch errors.Cause(err) {
	case jworker.ErrTerminateAgent:
		err = a.uninstallAgent()
	case jworker.ErrRebootMachine:
		logger.Infof("Caught reboot error")
		err = a.executeRebootOrShutdown(params.ShouldReboot)
	case jworker.ErrShutdownMachine:
		logger.Infof("Caught shutdown error")
		err = a.executeRebootOrShutdown(params.ShouldShutdown)
	}
	return cmdutil.AgentDone(logger, err)
}
597361
func (d *StaticDiscovery) Run(looper director.Looper) {
	var err error

	d.Targets, err = d.ParseConfig(d.ConfigFile)
	if err != nil {
		log.Errorf("StaticDiscovery cannot parse: %s", err.Error())
		looper.Done(nil)
	}
}
86408
func (t *workTask) Run(wg *sync.WaitGroup) {
	t.Result = t.task()
	wg.Done()
}
1311536
func (s *stateSync) run() {
	s.err = s.loop()
	close(s.done)
}
349349
func (c *Client) run() {
	// Watch for changes in allocations
	allocUpdates := make(chan *allocUpdates, 8)
	go c.watchAllocations(allocUpdates)

	for {
		select {
		case update := <-allocUpdates:
			// Don't apply updates while shutting down.
			c.shutdownLock.Lock()
			if c.shutdown {
				c.shutdownLock.Unlock()
				return
			}

			// Apply updates inside lock to prevent a concurrent
			// shutdown.
			c.runAllocs(update)
			c.shutdownLock.Unlock()

		case <-c.shutdownCh:
			return
		}
	}
}
19354
func (pget *Pget) Run() error {
	if err := pget.Ready(); err != nil {
		return pget.ErrTop(err)
	}

	if err := pget.Checking(); err != nil {
		return errors.Wrap(err, "failed to check header")
	}

	if err := pget.Download(); err != nil {
		return err
	}

	if err := pget.Utils.BindwithFiles(pget.Procs); err != nil {
		return err
	}

	return nil
}
495291
func (s *Config) Run(ctx context.Context) error {

	s.Lock()
	defer s.Unlock()

	if err := s.impl.Run(ctx); err != nil {
		return fmt.Errorf("unable to start the implementer: %s", err)
	}

	if err := s.impl.SetTargetNetworks(s.cfg); err != nil {
		return err
	}

	if s.service != nil {
		s.service.Initialize(s.filterQueue, s.impl.ACLProvider())
	}

	return nil
}
843327
func (s *Simple) run() {
	for {
		select {
		case <-time.After(s.config.GCPeriodicity):
			s.GC()
		case <-s.halt:
			s.closeError <- nil
			// there is no cleanup required, so we just return
			return
		}
	}
}
571196
func (robot *Robot) Run() error {
	Logger.Info("starting robot")

	// HACK
	Logger.Debugf("opening %s store connection", Config.StoreName)
	go func() {
		robot.Store.Open()

		Logger.Debug("loading users from store")
		robot.Users.Load()
	}()

	Logger.Debugf("starting %s adapter", Config.AdapterName)
	go robot.Adapter.Run()

	// Start the HTTP server after the adapter, as adapter.Run() adds additional
	// handlers to the router.
	Logger.Debug("starting HTTP server")
	go func() {
		if err := http.ListenAndServe(`:`+strconv.Itoa(Config.Port), Router); err != nil {
			Logger.Debug(err)
		}
	}()

	signal.Notify(robot.signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)

	stop := false
	for !stop {
		select {
		case sig := <-robot.signalChan:
			switch sig {
			case syscall.SIGINT, syscall.SIGTERM:
				stop = true
			}
		}
	}
	// Stop listening for new signals
	signal.Stop(robot.signalChan)

	// Initiate the shutdown process for our robot
	robot.Stop()

	return nil
}
166717
func (s preparedGenericAPIServer) Run(stopCh <-chan struct{}) error {
	err := s.NonBlockingRun(stopCh)
	if err != nil {
		return err
	}

	<-stopCh

	err = s.RunPreShutdownHooks()
	if err != nil {
		return err
	}

	// Wait for all requests to finish, which are bounded by the RequestTimeout variable.
	s.HandlerChainWaitGroup.Wait()

	return nil
}
1291634
func (e *Signer) Run(stopCh <-chan struct{}) {
	// Shut down queues
	defer utilruntime.HandleCrash()
	defer e.syncQueue.ShutDown()

	if !controller.WaitForCacheSync("bootstrap_signer", stopCh, e.configMapSynced, e.secretSynced) {
		return
	}

	klog.V(5).Infof("Starting workers")
	go wait.Until(e.serviceConfigMapQueue, 0, stopCh)
	<-stopCh
	klog.V(1).Infof("Shutting down")
}
1332127
func Run() {
	if Config.Debug {
		gin.SetMode(gin.DebugMode)
		log.SetLevel(log.DebugLevel)
	} else {
		gin.SetMode(gin.ReleaseMode)
		log.SetLevel(log.InfoLevel)
	}

	if Config.MongoLogging {
		mongoURIParsed, _ := url.Parse(Config.MongoURL)

		hooker, err := mgorus.NewHooker(mongoURIParsed.Host, mongoURIParsed.Path[1:], "logs")

		if err == nil {
			log.AddHook(hooker)
		}
	}

	// This will test TG tokens and creates API
	time.Sleep(time.Second * 1)
	initBots()

	for _, s := range services {
		if Config.IsStandAloneServiceInstance() {
			// save the service info as a job to Redis. The MAIN instance will process it
			serviceURL := Config.StandAloneServiceURL
			if serviceURL == "" {
				serviceURL = fmt.Sprintf("http://%s:%s", s.Name, Config.Port)
			}
			_, err := ensureStandAloneServiceJob.Schedule(1, time.Now(), s.Name, serviceURL, s.Bot().tgToken())

			if err != nil {
				log.WithError(err).Panic("ensureStandAloneServiceJob error")
			}
		}
	}

	// Configure
	router := gin.New()

	// register some HTML templates
	templ := template.Must(template.New("webpreview").Parse(htmlTemplateWebpreview))
	template.Must(templ.New("determineTZ").Parse(htmlTemplateDetermineTZ))

	router.SetHTMLTemplate(templ)

	// Middlewares
	router.Use(cloneMiddleware)
	router.Use(ginRecovery)
	router.Use(ginLogger)

	if Config.Debug {
		router.Use(gin.Logger())
	}

	if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
		router.StaticFile("/", "index.html")
	}

	router.NoRoute(func(c *gin.Context) {
		// todo: good 404
		if len(c.Request.RequestURI) > 10 && (c.Request.RequestURI[1:2] == "c" || c.Request.RequestURI[1:2] == "u" || c.Request.RequestURI[1:2] == "h") {
			c.String(404, "Hi here!! This link isn't working in a browser. Please follow the instructions in the chat")
		}
	})

	/*
		Possible URLs

		Service webhooks:

		token resolving handled by framework:
		/service_name/token
		/token - DEPRECATED, to be removed, auto-detect the service

		token resolving handled by service
		/service_name/service
		/service_name

		OAuth:
		/oauth1/service_name/auth_temp_id – OAuth1 initial redirect

		/auth/service_name - OAuth2 redirect URL
		/auth/service_name/provider_id - adds provider_id for the custom OAuth provider (e.g. self-hosted instance)


		WebPreview resolving:
		/a/token
	*/

	router.HEAD("/:param1/:param2/:param3", serviceHookHandler)
	router.GET("/:param1/:param2/:param3", serviceHookHandler)
	router.POST("/:param1/:param2/:param3", serviceHookHandler)

	router.HEAD("/:param1/:param2", serviceHookHandler)
	router.GET("/:param1/:param2", serviceHookHandler)
	router.POST("/:param1/:param2", serviceHookHandler)

	router.HEAD("/:param1", serviceHookHandler)
	router.GET("/:param1", serviceHookHandler)
	router.POST("/:param1", serviceHookHandler)

	// Start listening

	var err error

	go gracefulShutdownJobPools()

	if Config.Port == "443" || Config.Port == "1443" {
		if _, err := os.Stat(Config.ConfigDir + string(os.PathSeparator) + "ssl.crt"); !os.IsNotExist(err) {
			log.Infof("SSL: Using ssl.key/ssl.crt")
			err = router.RunTLS(":"+Config.Port, Config.ConfigDir+string(os.PathSeparator)+"ssl.crt", Config.ConfigDir+string(os.PathSeparator)+"ssl.key")
		} else {
			log.Fatalf("INTEGRAM_PORT set to 443, but ssl.crt and ssl.key files not found at '%s'", Config.ConfigDir)
		}

	} else {
		if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
			log.Warnf("WARNING! It is recommended to use Integram with a SSL.\n"+
				"Set the INTEGRAM_PORT to 443 and put integram.crt & integram.key files at '%s'", Config.ConfigDir)
		}
		err = router.Run(":" + Config.Port)
	}

	if err != nil {
		log.WithError(err).Fatal("Can't start the router")
	}
}
268076
func (m *Manager) Run(ctx context.Context) {
	// Save the context for all other jobs usage, and to indicate
	// the manager is running.
	m.mu.Lock()
	if m.ctx != nil {
		m.mu.Unlock()
		panic("Manager is already running")
	}
	m.ctx = ctx
	m.loadAndStartJobsLocked()
	// Signal the successful startup.
	close(m.started)
	m.started = make(chan struct{})
	m.mu.Unlock()

	// Wait for the context to be canceled.
	<-ctx.Done()

	// Clear context and get a copy of the running jobs.
	m.mu.Lock()
	m.ctx = nil
	runningWorkflows := m.workflows
	m.workflows = make(map[string]*runningWorkflow)
	m.mu.Unlock()

	// Abort the running jobs. They won't save their state as
	// m.ctx is nil and they know it means we're shutting down.
	for _, rw := range runningWorkflows {
		rw.cancel()
	}
	for _, rw := range runningWorkflows {
		<-rw.done
	}
}
231522
func (a Application) Run(c context.Context) error {
	if err := resolveExecutable(&a.genPath); err != nil {
		return fmt.Errorf("invalid API generator path (-google-api-go-generator): %s", err)
	}

	apiDst, err := getPackagePath(a.apiPackage)
	if err != nil {
		return fmt.Errorf("failed to find package path for [%s]: %s", a.apiPackage, err)
	}
	if a.apiSubproject != "" {
		apiDst = augPath(apiDst, a.apiSubproject)
		a.apiPackage = strings.Join([]string{a.apiPackage, a.apiSubproject}, "/")
	}
	log.Fields{
		"package": a.apiPackage,
		"path":    apiDst,
	}.Debugf(c, "Identified API destination package path.")

	// Compile our Chromium license.
	a.license, err = compileChromiumLicense(c)
	if err != nil {
		return fmt.Errorf("failed to compile Chromium license: %s", err)
	}

	c, cancelFunc := context.WithCancel(c)
	sigC := make(chan os.Signal, 1)
	signal.Notify(sigC, os.Interrupt)
	go func() {
		for range sigC {
			cancelFunc()
		}
	}()
	defer signal.Stop(sigC)

	// (1) Execute our service. Capture its discovery API.
	svc, err := loadService(c, a.servicePath)
	if err != nil {
		return fmt.Errorf("failed to load service [%s]: %s", a.servicePath, err)
	}

	err = svc.run(c, func(c context.Context, discoveryURL url.URL) error {
		discoveryURL.Path = safeURLPathJoin(discoveryURL.Path, a.serviceAPIRoot, "discovery", "v1", "apis")

		data, err := retryHTTP(c, discoveryURL, "GET", "")
		if err != nil {
			return fmt.Errorf("discovery server did not come online: %s", err)
		}

		dir := directoryList{}
		if err := json.Unmarshal(data, &dir); err != nil {
			return fmt.Errorf("failed to load directory list: %s", err)
		}

		// Ensure that our target API base directory exists.
		if err := ensureDirectory(apiDst); err != nil {
			return fmt.Errorf("failed to create destination directory: %s", err)
		}

		// Run "google-api-go-generator" against the hosted service.
		err = parallel.FanOutIn(func(taskC chan<- func() error) {
			for i, item := range dir.Items {
				item := item
				c := log.SetFields(c, log.Fields{
					"index": i,
					"api":   item.ID,
				})

				if !a.isWhitelisted(item.ID) {
					log.Infof(c, "API is not whitelisted; skipping.")
					continue
				}

				taskC <- func() error {
					return a.generateAPI(c, item, &discoveryURL, apiDst)
				}
			}
		})
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		log.Fields{
			log.ErrorKey: err,
		}.Errorf(c, "Failed to extract APIs.")
	}

	return nil
}
1022339
func (c *Controller) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

	klog.Infof("Starting controller")

	if !cache.WaitForCacheSync(stopCh, c.syncs...) {
		utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
		return
	}

	for i := 0; i < workers; i++ {
		go wait.Until(c.worker, time.Second, stopCh)
	}

	<-stopCh
	klog.Infof("Shutting down controller")
}
1328169
func (c *TriggerController) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

	klog.Infof("Starting trigger controller")

	if !cache.WaitForCacheSync(stopCh, c.syncs...) {
		utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
		return
	}

	for i := 0; i < workers; i++ {
		go wait.Until(c.imageStreamWorker, time.Second, stopCh)
	}

	for i := 0; i < workers; i++ {
		go wait.Until(c.resourceWorker, time.Second, stopCh)
	}

	<-stopCh
	klog.Infof("Shutting down trigger controller")
}