// Run runs the command to get datacenters.
968990
func (c *GetDatacentersCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	client := getClient(ctx)
	resp, err := client.ListDatacenters(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printDatacenters(c.f.tsv, resp.Datacenters...)
	return 0
}
541268
func (e *EmptyService) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) {
	return 0, nil
}
1196569
func (c *CmdSimpleFSList) Run() error {

	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	ctx := context.TODO()

	paths, err := doSimpleFSGlob(ctx, c.G(), cli, c.paths)
	if err != nil {
		return err
	}

	// If the argument was globbed, we really just want a stat of each item
	if len(paths) > 1 {
		var listResult keybase1.SimpleFSListResult
		for _, path := range paths {
			e, err := cli.SimpleFSStat(context.TODO(), keybase1.SimpleFSStatArg{Path: path})
			if err != nil {
				return err
			}
			// TODO: should stat include the path in the result?
			e.Name = path.String()
			listResult.Entries = append(listResult.Entries, e)
		}
		c.output(listResult)
	} else if len(paths) == 1 {
		path := paths[0]
		c.G().Log.Debug("SimpleFSList %s", path)

		opid, err2 := cli.SimpleFSMakeOpid(ctx)
		if err2 != nil {
			return err2
		}
		defer cli.SimpleFSClose(ctx, opid)
		filter := keybase1.ListFilter_FILTER_ALL_HIDDEN
		if c.options.all {
			filter = keybase1.ListFilter_NO_FILTER
		}
		if c.recurse {
			err = cli.SimpleFSListRecursive(ctx, keybase1.SimpleFSListRecursiveArg{
				OpID:   opid,
				Path:   path,
				Filter: filter,
			})
		} else {
			err = cli.SimpleFSList(ctx, keybase1.SimpleFSListArg{
				OpID:   opid,
				Path:   path,
				Filter: filter,
			})
		}
		if err != nil {
			return err
		}

		err = cli.SimpleFSWait(ctx, opid)
		if err != nil {
			return err
		}
		gotList := false
		for {
			listResult, err := cli.SimpleFSReadList(ctx, opid)
			// Eat the error here because it may just mean the results
			// are complete. TODO: should KBFS return non-error here
			// until the opid is closed?
			if err != nil || len(listResult.Entries) == 0 {
				if gotList == true {
					err = nil
				}
				return err
			}
			gotList = true
			err = c.output(listResult)
			if err != nil {
				return err
			}
		}
	}
	return err
}
978548
func (c *GetOSesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	client := getClient(ctx)
	resp, err := client.ListOSes(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printOSes(c.f.tsv, resp.Oses...)
	return 0
}
73675
func (c *CmdListTrackers) Run() error {
	cli, err := GetUserClient(c.G())
	if err != nil {
		return err
	}
	if err := RegisterProtocolsWithContext(nil, c.G()); err != nil {
		return err
	}

	arg := keybase1.ListTrackers2Arg{
		Assertion: c.assertion,
		Reverse:   false,
	}
	uss, err := cli.ListTrackers2(context.TODO(), arg)
	if err != nil {
		return err
	}
	return c.output(uss)
}
537745
func (ss *simpleSource) Run() error {

	out, err := exec.Command(ss.command, ss.args...).Output()
	if err != nil {
		return err
	}

	ss.rawData = out
	return nil
}
72291
func (s *ExtensionManagerServer) Run() error {
	errc := make(chan error)
	go func() {
		errc <- s.Start()
	}()

	// Watch for the osquery process going away. If so, initiate shutdown.
	go func() {
		for {
			time.Sleep(s.pingInterval)

			status, err := s.serverClient.Ping()
			if err != nil {
				errc <- errors.Wrap(err, "extension ping failed")
				break
			}
			if status.Code != 0 {
				errc <- errors.Errorf("ping returned status %d", status.Code)
				break
			}
		}
	}()

	err := <-errc
	if err := s.Shutdown(context.Background()); err != nil {
		return err
	}
	return err
}
836438
func (c *revokeCloudCommand) Run(ctx *cmd.Context) error {
	client, err := c.getCloudAPI()
	if err != nil {
		return err
	}
	defer client.Close()

	return block.ProcessBlockedError(client.RevokeCloud(c.User, c.Access, c.Clouds...), block.BlockChange)
}
1079728
func (c *CmdGitMdget) Run() error {
	cli, err := GetGitClient(c.G())
	ctx := context.Background()
	if err != nil {
		return err
	}

	var res []keybase1.GitRepoResult
	if len(c.folder) > 0 {
		folder, err := ParseTLF(c.folder)
		if err != nil {
			return err
		}
		res, err = cli.GetGitMetadata(ctx, folder)
		if err != nil {
			return err
		}
	} else {
		res, err = cli.GetAllGitMetadata(ctx)
		if err != nil {
			return err
		}
	}

	jsonStr, err := json.MarshalIndent(res, "", "    ")
	if err != nil {
		return err
	}

	fmt.Println(string(jsonStr))
	return nil
}
423940
func (cmd *CompactCommand) Run(args ...string) (err error) {
	// Parse flags.
	fs := flag.NewFlagSet("", flag.ContinueOnError)
	fs.SetOutput(ioutil.Discard)
	fs.StringVar(&cmd.DstPath, "o", "", "")
	fs.Int64Var(&cmd.TxMaxSize, "tx-max-size", 65536, "")
	if err := fs.Parse(args); err == flag.ErrHelp {
		fmt.Fprintln(cmd.Stderr, cmd.Usage())
		return ErrUsage
	} else if err != nil {
		return err
	} else if cmd.DstPath == "" {
		return fmt.Errorf("output file required")
	}

	// Require database paths.
	cmd.SrcPath = fs.Arg(0)
	if cmd.SrcPath == "" {
		return ErrPathRequired
	}

	// Ensure source file exists.
	fi, err := os.Stat(cmd.SrcPath)
	if os.IsNotExist(err) {
		return ErrFileNotFound
	} else if err != nil {
		return err
	}
	initialSize := fi.Size()

	// Open source database.
	src, err := bolt.Open(cmd.SrcPath, 0444, nil)
	if err != nil {
		return err
	}
	defer src.Close()

	// Open destination database.
	dst, err := bolt.Open(cmd.DstPath, fi.Mode(), nil)
	if err != nil {
		return err
	}
	defer dst.Close()

	// Run compaction.
	if err := cmd.compact(dst, src); err != nil {
		return err
	}

	// Report stats on new size.
	fi, err = os.Stat(cmd.DstPath)
	if err != nil {
		return err
	} else if fi.Size() == 0 {
		return fmt.Errorf("zero db size")
	}
	fmt.Fprintf(cmd.Stdout, "%d -> %d bytes (gain=%.2fx)\n", initialSize, fi.Size(), float64(initialSize)/float64(fi.Size()))

	return nil
}
543904
func (c *listImagesCommand) Run(ctx *cmd.Context) (err error) {
	api, err := getImageMetadataListAPI(c)
	if err != nil {
		return err
	}
	defer api.Close()

	found, err := api.List(c.Stream, c.Region, c.Series, c.Arches, c.VirtType, c.RootStorageType)
	if err != nil {
		return err
	}
	if len(found) == 0 {
		return nil
	}

	info, errs := convertDetailsToInfo(found)
	if len(errs) > 0 {
		// display individual error
		fmt.Fprintf(ctx.Stderr, strings.Join(errs, "\n"))
	}

	var output interface{}
	switch c.out.Name() {
	case "yaml", "json":
		output = groupMetadata(info)
	default:
		{
			sort.Sort(metadataInfos(info))
			output = info
		}
	}
	return c.out.Write(ctx, output)
}
347648
func (c *enableCommand) Run(_ *cmd.Context) error {
	api, err := c.apiFunc(c)
	if err != nil {
		return errors.Annotate(err, "cannot connect to the API")
	}
	defer api.Close()

	return api.SwitchBlockOff(c.target)
}
234943
func (c *DeploymentConfigController) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

	klog.Infof("Starting deploymentconfig controller")

	// Wait for the rc and dc stores to sync before starting any work in this controller.
	if !cache.WaitForCacheSync(stopCh, c.dcStoreSynced, c.rcListerSynced) {
		return
	}

	klog.Info("deploymentconfig controller caches are synced. Starting workers.")

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

	metrics.InitializeMetricsCollector(c.rcLister)

	<-stopCh

	klog.Infof("Shutting down deploymentconfig controller")
}
1104757
func (c *CmdSimpleFSPs) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	ops, err := cli.SimpleFSGetOps(context.TODO())

	c.output(ops)

	return err
}
759270
func (c *GetVMsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	client := getClient(ctx)
	resp, err := client.ListVMs(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printVMs(c.f.tsv, resp.Vms...)
	return 0
}
1248074
func (c *CmdSimpleFSSyncEnable) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	ctx := context.TODO()
	arg := keybase1.SimpleFSSetFolderSyncConfigArg{
		Config: keybase1.FolderSyncConfig{
			Mode: keybase1.FolderSyncMode_ENABLED,
		},
		Path: c.path,
	}

	subpath := pathMinusTlf(c.path)
	if subpath != "" {
		arg.Path, err = toTlfPath(c.path)
		if err != nil {
			return err
		}
		res, err := cli.SimpleFSFolderSyncConfigAndStatus(ctx, arg.Path)
		if err != nil {
			return err
		}

		if res.Config.Mode == keybase1.FolderSyncMode_ENABLED {
			return fmt.Errorf("Must disable full syncing on %s first", arg.Path)
		}

		for _, p := range res.Config.Paths {
			if p == subpath {
				// Already enabled.
				return nil
			}
		}

		arg.Config.Mode = keybase1.FolderSyncMode_PARTIAL
		arg.Config.Paths = append(res.Config.Paths, subpath)
	}

	return cli.SimpleFSSetFolderSyncConfig(ctx, arg)
}
865538
func (c *BootstrapCommand) Run(_ *cmd.Context) error {

	bootstrapParamsData, err := ioutil.ReadFile(c.BootstrapParamsFile)
	if err != nil {
		return errors.Annotate(err, "reading bootstrap params file")
	}
	var args instancecfg.StateInitializationParams
	if err := args.Unmarshal(bootstrapParamsData); err != nil {
		return errors.Trace(err)
	}

	isCAAS := args.ControllerCloud.Type == caasprovider.CAASProviderType

	if isCAAS {
		if err := c.ensureConfigFilesForCaas(); err != nil {
			return errors.Trace(err)
		}
	}

	if err := c.ReadConfig(c.Tag().String()); err != nil {
		return errors.Annotate(err, "cannot read config")
	}
	agentConfig := c.CurrentConfig()

	// agent.Jobs is an optional field in the agent config, and was
	// introduced after 1.17.2. We default to allowing units on
	// machine-0 if missing.
	jobs := agentConfig.Jobs()
	if len(jobs) == 0 {
		jobs = []multiwatcher.MachineJob{
			multiwatcher.JobManageModel,
			multiwatcher.JobHostUnits,
		}
	}

	// Get the bootstrap machine's addresses from the provider.
	cloudSpec, err := environs.MakeCloudSpec(
		args.ControllerCloud,
		args.ControllerCloudRegion,
		args.ControllerCloudCredential,
	)
	if err != nil {
		return errors.Trace(err)
	}

	openParams := environs.OpenParams{
		ControllerUUID: args.ControllerConfig.ControllerUUID(),
		Cloud:          cloudSpec,
		Config:         args.ControllerModelConfig,
	}
	var env environs.BootstrapEnviron
	if isCAAS {
		env, err = environsNewCAAS(openParams)
	} else {
		env, err = environsNewIAAS(openParams)
	}
	if err != nil {
		return errors.Trace(err)
	}

	newConfigAttrs := make(map[string]interface{})

	// Check to see if a newer agent version has been requested
	// by the bootstrap client.
	desiredVersion, ok := args.ControllerModelConfig.AgentVersion()
	if ok && desiredVersion != jujuversion.Current {
		if isCAAS {
			// For CAAS, the agent-version in controller config should
			// always equals to current juju version.
			return errors.NotSupportedf(
				"desired juju version %q, current version %q for k8s controllers",
				desiredVersion, jujuversion.Current,
			)
		}

		// If we have been asked for a newer version, ensure the newer
		// tools can actually be found, or else bootstrap won't complete.
		streams := envtools.PreferredStreams(&desiredVersion, args.ControllerModelConfig.Development(), args.ControllerModelConfig.AgentStream())
		logger.Infof("newer agent binaries requested, looking for %v in streams: %v", desiredVersion, strings.Join(streams, ","))
		hostSeries, err := series.HostSeries()
		if err != nil {
			return errors.Trace(err)
		}
		filter := tools.Filter{
			Number: desiredVersion,
			Arch:   arch.HostArch(),
			Series: hostSeries,
		}
		_, toolsErr := envtools.FindTools(env, -1, -1, streams, filter)
		if toolsErr == nil {
			logger.Infof("agent binaries are available, upgrade will occur after bootstrap")
		}
		if errors.IsNotFound(toolsErr) {
			// Newer tools not available, so revert to using the tools
			// matching the current agent version.
			logger.Warningf("newer agent binaries for %q not available, sticking with version %q", desiredVersion, jujuversion.Current)
			newConfigAttrs["agent-version"] = jujuversion.Current.String()
		} else if toolsErr != nil {
			logger.Errorf("cannot find newer agent binaries: %v", toolsErr)
			return toolsErr
		}
	}

	callCtx := context.NewCloudCallContext()
	// At this stage, cloud credential has not yet been stored server-side
	// as there is no server-side. If these cloud calls will fail with
	// invalid credential, just log it.
	callCtx.InvalidateCredentialFunc = func(reason string) error {
		logger.Errorf("Cloud credential %q is not accepted by cloud provider: %v", args.ControllerCloudCredentialName, reason)
		return nil
	}

	info, ok := agentConfig.StateServingInfo()
	if !ok {
		return fmt.Errorf("bootstrap machine config has no state serving info")
	}
	if err := ensureKeys(isCAAS, args, &info, newConfigAttrs); err != nil {
		return errors.Trace(err)
	}
	addrs, err := getAddressesForMongo(isCAAS, env, callCtx, args)
	if err != nil {
		return errors.Trace(err)
	}

	if err = c.ChangeConfig(func(agentConfig agent.ConfigSetter) error {
		agentConfig.SetStateServingInfo(info)
		mmprof, err := mongo.NewMemoryProfile(args.ControllerConfig.MongoMemoryProfile())
		if err != nil {
			logger.Errorf("could not set requested memory profile: %v", err)
		} else {
			agentConfig.SetMongoMemoryProfile(mmprof)
		}
		return nil
	}); err != nil {
		return fmt.Errorf("cannot write agent config: %v", err)
	}

	agentConfig = c.CurrentConfig()

	// Create system-identity file
	if err := agent.WriteSystemIdentityFile(agentConfig); err != nil {
		return errors.Trace(err)
	}

	if err := c.startMongo(isCAAS, addrs, agentConfig); err != nil {
		return errors.Annotate(err, "failed to start mongo")
	}

	controllerModelCfg, err := env.Config().Apply(newConfigAttrs)
	if err != nil {
		return errors.Annotate(err, "failed to update model config")
	}
	args.ControllerModelConfig = controllerModelCfg

	// Initialise state, and store any agent config (e.g. password) changes.
	var controller *state.Controller
	var m *state.Machine
	err = c.ChangeConfig(func(agentConfig agent.ConfigSetter) error {
		var stateErr error
		dialOpts := mongo.DefaultDialOpts()

		// Set a longer socket timeout than usual, as the machine
		// will be starting up and disk I/O slower than usual. This
		// has been known to cause timeouts in queries.
		dialOpts.SocketTimeout = c.Timeout
		if dialOpts.SocketTimeout < minSocketTimeout {
			dialOpts.SocketTimeout = minSocketTimeout
		}

		// We shouldn't attempt to dial peers until we have some.
		dialOpts.Direct = true

		adminTag := names.NewLocalUserTag(adminUserName)
		controller, m, stateErr = agentInitializeState(
			adminTag,
			agentConfig,
			agentbootstrap.InitializeStateParams{
				StateInitializationParams: args,
				BootstrapMachineAddresses: addrs,
				BootstrapMachineJobs:      jobs,
				SharedSecret:              info.SharedSecret,
				Provider:                  environs.Provider,
				StorageProviderRegistry:   stateenvirons.NewStorageProviderRegistry(env),
			},
			dialOpts,
			stateenvirons.GetNewPolicyFunc(),
		)
		return stateErr
	})
	if err != nil {
		return err
	}
	defer controller.Close()
	st := controller.SystemState()

	// Set up default container networking mode
	model, err := st.Model()
	if err != nil {
		return err
	}
	if err = model.AutoConfigureContainerNetworking(env); err != nil {
		if errors.IsNotSupported(err) {
			logger.Debugf("Not performing container networking autoconfiguration on a non-networking environment")
		} else {
			return err
		}
	}

	// Fetch spaces from substrate
	if err = st.ReloadSpaces(env); err != nil {
		if errors.IsNotSupported(err) {
			logger.Debugf("Not performing spaces load on a non-networking environment")
		} else {
			return err
		}
	}

	if !isCAAS {
		// Populate the tools catalogue.
		if err := c.populateTools(st, env); err != nil {
			return errors.Trace(err)
		}
		// Add custom image metadata to environment storage.
		if len(args.CustomImageMetadata) > 0 {
			if err := c.saveCustomImageMetadata(st, env, args.CustomImageMetadata); err != nil {
				return err
			}
		}
	}

	// Populate the GUI archive catalogue.
	if err := c.populateGUIArchive(st, env); err != nil {
		// Do not stop the bootstrapping process for Juju GUI archive errors.
		logger.Warningf("cannot set up Juju GUI: %s", err)
	} else {
		logger.Debugf("Juju GUI successfully set up")
	}

	// bootstrap machine always gets the vote
	return m.SetHasVote(true)
}