// RunOnAllMachines attempts to run the specified command on all the machines.
2350
func (a *ActionAPI) RunOnAllMachines(run params.RunParams) (results params.ActionResults, err error) {
	if err := a.checkCanAdmin(); err != nil {
		return results, err
	}

	if err := a.check.ChangeAllowed(); err != nil {
		return results, errors.Trace(err)
	}

	machines, err := a.state.AllMachines()
	if err != nil {
		return results, err
	}
	machineTags := make([]names.Tag, len(machines))
	for i, machine := range machines {
		machineTags[i] = machine.Tag()
	}

	actionParams := a.createActionsParams(machineTags, run.Commands, run.Timeout)

	return queueActions(a, actionParams)
}
1055316
func ListMachines(runCmd runFunc) (map[string]string, error) {
	if runCmd == nil {
		runCmd = run
	}

	output, err := runCmd("", virsh, "-q", "list", "--all")
	if err != nil {
		return nil, err
	}
	// Split the output into lines.
	// Regex matching is the easiest way to match the lines.
	//   id hostname status
	// separated by whitespace, with whitespace at the start too.
	result := make(map[string]string)
	for _, s := range machineListPattern.FindAllStringSubmatchIndex(output, -1) {
		hostnameAndStatus := machineListPattern.ExpandString(nil, "$hostname $status", output, s)
		parts := strings.SplitN(string(hostnameAndStatus), " ", 2)
		result[parts[0]] = parts[1]
	}
	return result, nil
}
1150463
func (c *removeCommand) Run(ctx *cmd.Context) (err error) {
	client, err := getRemoveImageAPI(&c.CachedImagesCommandBase)
	if err != nil {
		return err
	}
	defer client.Close()

	return client.DeleteImage(c.Kind, c.Series, c.Arch)
}
448063
func (r *RunListener) RunCommands(args RunCommandsArgs) (results *exec.ExecResponse, err error) {
	logger.Tracef("run commands: %s", args.Commands)
	return r.CommandRunner.RunCommands(args)
}
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)
}
628163
func (mrr *MultiRoutineRunner) Run(fn func()) {
	mrr.once.Do(mrr.init)
	mrr.q <- fn
}
500854
func (u *Uniter) RunCommands(args RunCommandsArgs) (results *exec.ExecResponse, err error) {
	// TODO(axw) drop this when we move the run-listener to an independent
	// worker. This exists purely for the tests.
	return u.runListener.RunCommands(args)
}
126734
func (f *FakeCommandRunner) Run(cmd string) error {
	_, err := f.CombinedOutput(cmd)
	return err
}
290063
func (mr *MockCommandRunnerMockRecorder) RunCommands(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunCommands", reflect.TypeOf((*MockCommandRunner)(nil).RunCommands), arg0)
}
955999
func (a *Agent) runProcessors(
	src <-chan telegraf.Metric,
	agg chan<- telegraf.Metric,
) error {
	for metric := range src {
		metrics := a.applyProcessors(metric)

		for _, metric := range metrics {
			agg <- metric
		}
	}

	return nil
}
270119
func (u *DropsondeUnmarshaller) Run(inputChan <-chan []byte, outputChan chan<- *events.Envelope) {
	for message := range inputChan {
		envelope, err := u.UnmarshallMessage(message)
		if err != nil {
			continue
		}
		outputChan <- envelope
	}
}
381281
func (f *AutostartFlag) VirtualMachines(args []string) ([]*object.VirtualMachine, error) {
	ctx := context.TODO()
	if len(args) == 0 {
		return nil, errors.New("no argument")
	}

	finder, err := f.Finder()
	if err != nil {
		return nil, err
	}

	var out []*object.VirtualMachine
	for _, arg := range args {
		vms, err := finder.VirtualMachineList(ctx, arg)
		if err != nil {
			return nil, err
		}

		out = append(out, vms...)
	}

	return out, nil
}
611945
func (o LoginOptions) Run() error {
	if err := o.GatherInfo(); err != nil {
		return err
	}

	newFileCreated, err := o.SaveConfig()
	if err != nil {
		return err
	}

	if newFileCreated {
		fmt.Fprintf(o.Out, "Welcome! See '%s help' to get started.\n", o.CommandName)
	}
	return nil
}
329182
func (c *migrateCommand) Run(ctx *cmd.Context) error {
	spec, err := c.getMigrationSpec()
	if err != nil {
		return err
	}
	modelName, err := c.ModelName()
	if err != nil {
		return errors.Trace(err)
	}
	uuids, err := c.ModelUUIDs([]string{modelName})
	if err != nil {
		return errors.Trace(err)
	}
	spec.ModelUUID = uuids[0]
	if err := c.checkMigrationFeasibility(spec); err != nil {
		return errors.Trace(err)
	}
	controllerName, err := c.ControllerName()
	if err != nil {
		return err
	}
	api, err := c.getMigrationAPI(controllerName)
	if err != nil {
		return err
	}
	defer func() { _ = api.Close() }()
	id, err := api.InitiateMigration(*spec)
	if err != nil {
		return err
	}
	ctx.Infof("Migration started with ID %q", id)
	return nil
}
393419
func Run() {
	app.HelpFlag.Short('h')
	app.Version(version.String())
	app.VersionFlag.Short('V')

	config := aggregateConfiguration()
	err := config.Check()
	goad.HandleErr(err)

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) // but interrupts from kbd are blocked by termbox

	result := start(config, sigChan)
	defer printSummary(result)
	if config.Output != "" {
		defer saveJSONSummary(*outputFile, result)
	}
}
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")
	}
}
229548
func (ctx *BatchedContext) Run(errChan chan error) error {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	for {
		select {
		case <-ctx.workAvailable:
			ctx.DoWork()
			if err := ctx.Errors(); err != nil {
				if errChan == nil {
					return err
				}
				errChan <- err

			}
		case w := <-ctx.Work():
			ctx.ErrChan() <- w()
		}
	}
}