// Run is isoloated from main and os.Args to help with testing.
// Shouldn't directly print to console, just write through w.
198515
func Run(w io.Writer, appArgs []string, ask prompt.Prompt) (help.HelpMessage, error) {
	r := &runner{}
	return r.run(w, appArgs, ask)
}
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
		}
	}
}
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
}
903420
func (c *CmdSimpleFSDebug) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	return cli.SimpleFSDumpDebuggingInfo(context.TODO())
}
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
}
634213
func (konsolePipe *ConsolePipe) Run() error {
	if konsolePipe.PipePath == "" {
		return fmt.Errorf("Pipe path not configured.")
	}
	if golfilesystem.PathExists(konsolePipe.PipePath) {
		return fmt.Errorf("%s path already exists!", konsolePipe.PipePath)
	}
	ExecOutput(fmt.Sprintf("mkfifo %s", konsolePipe.PipePath))

	konsolePipe.Konsole.Command = fmt.Sprintf("%s < %s", konsolePipe.Konsole.Command, konsolePipe.PipePath)
	konsolePipe.Konsole.Run()
	return nil
}
997544
func (c *GetPlatformsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	client := getClient(ctx)
	resp, err := client.ListPlatforms(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printPlatforms(c.f.tsv, resp.Platforms...)
	return 0
}
169351
func (cmd *Command) Run(args []string) {
	cmd.Flags.SetOutput(ioutil.Discard)

	err := cmd.Flags.Parse(args)
	if err != nil {
		cmd.Usage()
		fmt.Fprintf(os.Stderr, "\nError: %v\n", err)
		os.Exit(2)
	}
	subArgs := cmd.Flags.Args()

	if len(subArgs) == 0 {
		cmd.Action(cmd, subArgs)
		return
	}

	name := subArgs[0]
	for _, subcmd := range cmd.Subcmds {
		if subcmd.Name() == name {
			subcmd.Run(subArgs[1:])
			return
		}
	}

	cmd.Action(cmd, subArgs)
}
62655
func Run() {

	flag.Parse()

	if len(flag.Args()) > 0 {
		mustLogFatal(fmt.Errorf("extra command line arguments: %s", flag.Args()))
	}

	// Set up process log before anything bad happens
	if logfile {
		log.SetOutput(os.Stdout)
	}
	log.SetFlags(log.LstdFlags)

	if version {
		showVersion()
		os.Exit(0)
	}
	if plugins {
		fmt.Println(caddy.DescribePlugins())
		os.Exit(0)
	}

	// Set CPU cap
	if err := setCPU(cpu); err != nil {
		mustLogFatal(err)
	}

	// Get Corefile input
	corefile, err := caddy.LoadCaddyfile(serverType)
	if err != nil {
		mustLogFatal(err)
	}

	// Start your engines
	instance, err := caddy.Start(corefile)
	if err != nil {
		mustLogFatal(err)
	}

	logVersion()
	if !dnsserver.Quiet {
		showVersion()
	}

	// Twiddle your thumbs
	instance.Wait()
}
268485
func (m *Main) Run(args ...string) error {
	// Create logger.
	m.logger = log.New(m.Stdout, "", log.LstdFlags)

	// Parse command line flags.
	opt, err := m.ParseFlags(args...)
	if err != nil {
		return err
	}

	// Set up advertised address and default peer set.
	m.advertiseAddr = MergeHostPort(opt.Host, opt.Addr)
	if len(opt.Peers) == 0 {
		opt.Peers = []string{m.advertiseAddr}
	}

	// Create a slice of peers with their HTTP address set instead.
	httpPeers, err := SetPortSlice(opt.Peers, opt.Addr)
	if err != nil {
		return fmt.Errorf("set port slice: %s", err)
	}
	m.peers = httpPeers

	// Initialise the default client using the peer list
	os.Setenv("DISCOVERD", strings.Join(opt.Peers, ","))
	discoverd.DefaultClient = discoverd.NewClient()

	// if there is a discoverd process already running on this
	// address perform a deployment by starting a proxy DNS server
	// and shutting down the old discoverd job
	var deploy *dd.Deployment
	var targetLogIndex dt.TargetLogIndex

	target := fmt.Sprintf("http://%s:1111", opt.Host)
	m.logger.Println("checking for existing discoverd process at", target)
	if err := discoverd.NewClientWithURL(target).Ping(target); err == nil {
		m.logger.Println("discoverd responding at", target, "taking over")

		deploy, err = dd.NewDeployment("discoverd")
		if err != nil {
			return err
		}
		m.logger.Println("Created deployment")
		if err := deploy.MarkPerforming(m.advertiseAddr, 60); err != nil {
			return err
		}
		m.logger.Println("marked", m.advertiseAddr, "as performing in deployent")
		addr, resolvers := waitHostDNSConfig()
		if opt.DNSAddr != "" {
			addr = opt.DNSAddr
		}
		if len(opt.Recursors) > 0 {
			resolvers = opt.Recursors
		}
		m.logger.Println("starting proxy DNS server")
		if err := m.openDNSServer(addr, resolvers); err != nil {
			return fmt.Errorf("Failed to start DNS server: %s", err)
		}
		m.logger.Printf("discoverd listening for DNS on %s", addr)

		targetLogIndex, err = discoverd.NewClientWithURL(target).Shutdown(target)
		if err != nil {
			return err
		}
		// Sleep for 2x the election timeout.
		// This is to work around an issue with hashicorp/raft that can allow us to be elected with
		// no log entries, hence truncating the log and losing all data!
		time.Sleep(2 * time.Second)
	} else {
		m.logger.Println("failed to contact existing discoverd server, starting up without takeover")
		m.logger.Println("err:", err)
	}

	// Open listener.
	ln, err := net.Listen("tcp4", opt.Addr)
	if err != nil {
		return err
	}
	m.ln = keepalive.Listener(ln)

	// Open mux
	m.mux = mux.New(m.ln)
	go m.mux.Serve()

	m.dataDir = opt.DataDir

	// if the advertise addr is not in the peer list we are proxying
	proxying := true
	for _, addr := range m.peers {
		if addr == m.advertiseAddr {
			proxying = false
			break
		}
	}

	if proxying {
		// Notify user that we're proxying if the store wasn't initialized.
		m.logger.Println("advertised address not in peer set, joining as proxy")
	} else {
		// Open store if we are not proxying.
		if err := m.openStore(); err != nil {
			return fmt.Errorf("Failed to open store: %s", err)
		}
	}

	// Wait for the store to catchup before switching to local store if we are doing a deployment
	if m.store != nil && targetLogIndex.LastIndex > 0 {
		for m.store.LastIndex() < targetLogIndex.LastIndex {
			m.logger.Println("Waiting for store to catchup, current:", m.store.LastIndex(), "target:", targetLogIndex.LastIndex)
			time.Sleep(100 * time.Millisecond)
		}
	}

	// If we already started the DNS server as part of a deployment above,
	// and we have an initialized store, just switch from the proxy store
	// to the initialized store.
	//
	// Else if we have a DNS address, start a DNS server right away.
	//
	// Otherwise wait for the host network to come up and then start a DNS
	// server.
	if m.dnsServer != nil && m.store != nil {
		m.dnsServer.SetStore(m.store)
	} else if opt.DNSAddr != "" {
		if err := m.openDNSServer(opt.DNSAddr, opt.Recursors); err != nil {
			return fmt.Errorf("Failed to start DNS server: %s", err)
		}
		m.logger.Printf("discoverd listening for DNS on %s", opt.DNSAddr)
	} else if opt.WaitNetDNS {
		go func() {
			addr, resolvers := waitHostDNSConfig()
			m.mu.Lock()
			if err := m.openDNSServer(addr, resolvers); err != nil {
				log.Fatalf("Failed to start DNS server: %s", err)
			}
			m.mu.Unlock()
			m.logger.Printf("discoverd listening for DNS on %s", addr)

			// Notify webhook.
			if opt.Notify != "" {
				m.Notify(opt.Notify, addr)
			}
		}()
	}

	if err := m.openHTTPServer(); err != nil {
		return fmt.Errorf("Failed to start HTTP server: %s", err)
	}

	if deploy != nil {
		if err := deploy.MarkDone(m.advertiseAddr); err != nil {
			return err
		}
		m.logger.Println("marked", m.advertiseAddr, "as done in deployment")
	}

	// Notify user that the servers are listening.
	m.logger.Printf("discoverd listening for HTTP on %s", opt.Addr)

	// Wait for leadership.
	if err := m.waitForLeader(IndefiniteTimeout); err != nil {
		return err
	}

	// Notify URL that discoverd is running.
	httpAddr := ln.Addr().String()
	host, port, _ := net.SplitHostPort(httpAddr)
	if host == "0.0.0.0" {
		httpAddr = net.JoinHostPort(os.Getenv("EXTERNAL_IP"), port)
	}
	m.Notify(opt.Notify, opt.DNSAddr)
	go func() {
		for {
			hb, err := discoverd.AddServiceAndRegister("discoverd", httpAddr)
			if err != nil {
				m.logger.Println("failed to register service/instance, retrying in 5 seconds:", err)
				time.Sleep(5 * time.Second)
				continue
			}
			m.mu.Lock()
			m.hb = hb
			m.mu.Unlock()
			break
		}
	}()
	return nil
}
728410
func Run(dir string, command string, args []string) (string, bool, error) {
	outFile := NewBufferCloser(nil)
	proc, err := StartProcess("", dir, command, args, nil, outFile)
	if err != nil {
		return "", false, err
	}

	<-proc.WaitCh

	if proc.ExitState.Success() {
		return string(outFile.Bytes()), true, nil
	} else {
		return string(outFile.Bytes()), false, nil
	}
}
1092815
func (e *nsEnterExec) Run(cmd string, args ...string) ([]byte, error) {
	nsenterArgs := []string{
		"--mount=" + hostMountNamespacePath,
		"--",
		cmd,
	}
	nsenterArgs = append(nsenterArgs, args...)
	glog.V(5).Infof("Running command : %v %v", nsenterPath, nsenterArgs)
	exe := exec.New()
	return exe.Command(nsenterPath, nsenterArgs...).CombinedOutput()
}
371131
func (config *Config) Run(cmd string) (string, error) {
	if config.DisplayOutput == true {
		fmt.Printf("run: %s\n", cmd)
	}
	return config.doRun(cmd, false)
}
323121
func (launcher *Launcher) Run() error {
	targetName := launcher.GetTarget()
	cmdStr := fmt.Sprintf("%s %s", targetName, launcher.GetArgs())
	cmd := exec.Command(targetName, launcher.GetArgs()...)
	cmd.Stderr = os.Stderr
	stdout, _ := cmd.StdoutPipe()
	if err := cmd.Start(); err != nil {
		log.WithError(err).WithField("cmd", cmdStr).Error("cmd.Start()")
		return fmt.Errorf("unable to launch process %s: %s", cmdStr, err)
	}

	launcher.setProcess(cmd.Process)
	launcher.setStdout(stdout)

	// Wait for the process to exit in the background to release all
	// resources
	go func() {
		err := cmd.Wait()
		log.WithFields(logrus.Fields{
			"exitCode": err,
			"cmd":      cmdStr,
		}).Debug("Process exited")
	}()

	return nil
}
706767
func (m *Main) Run(args ...string) error {
	// Require a command at the beginning.
	if len(args) == 0 || strings.HasPrefix(args[0], "-") {
		fmt.Fprintln(m.Stderr, m.Usage())
		return ErrUsage
	}

	// Execute command.
	switch args[0] {
	case "help":
		fmt.Fprintln(m.Stderr, m.Usage())
		return ErrUsage
	case "bench":
		return newBenchCommand(m).Run(args[1:]...)
	case "check":
		return newCheckCommand(m).Run(args[1:]...)
	case "compact":
		return newCompactCommand(m).Run(args[1:]...)
	case "dump":
		return newDumpCommand(m).Run(args[1:]...)
	case "info":
		return newInfoCommand(m).Run(args[1:]...)
	case "page":
		return newPageCommand(m).Run(args[1:]...)
	case "pages":
		return newPagesCommand(m).Run(args[1:]...)
	case "stats":
		return newStatsCommand(m).Run(args[1:]...)
	default:
		return ErrUnknownCommand
	}
}
1197911
func Run() {
	server.CloseOnAbort()

	flag.Usage = printUsage
	flag.Parse()

	if flagVersion != nil && *flagVersion {
		_, _, thisExeAbsPath := gotil.GetThisPathParts()
		fmt.Fprintf(apitypes.Stdout, "Binary: %s\n", thisExeAbsPath)
		fmt.Fprint(apitypes.Stdout, api.Version.String())
		os.Exit(0)
	}

	if flagEnv != nil && *flagEnv {
		for _, v := range os.Environ() {
			fmt.Fprintf(apitypes.Stdout, "%s\n", v)
		}
		os.Exit(0)
	}

	// if a config is specified then do not care about any other options
	if flagConfig != nil && gotil.FileExists(*flagConfig) {

		config = gofigCore.New()

		if err := config.ReadConfigFile(*flagConfig); err != nil {
			fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
			os.Exit(1)
		}

		if flagPrintConfig != nil && *flagPrintConfig {
			jstr, err := config.ToJSON()
			if err != nil {
				fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
				os.Exit(1)
			}
			fmt.Fprintln(apitypes.Stdout, jstr)
			os.Exit(0)
		}

		s, errs, err := server.Serve(nil, config)
		if err != nil {
			fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
			os.Exit(1)
		}

		err = <-errs
		if err != nil {
			fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
			os.Exit(1)
		}

		s.Close()
		os.Exit(0)
	}

	ctx := context.Background()
	ctx = ctx.WithValue(context.PathConfigKey, utils.NewPathConfig(ctx, "", ""))
	registry.ProcessRegisteredConfigs(ctx)

	cfg, err := apiconfig.NewConfig(ctx)
	if err != nil {
		fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
		os.Exit(1)
	}

	config = cfg
	for _, fs := range config.FlagSets() {
		flag.CommandLine.AddFlagSet(fs)
	}

	if flagHelp != nil && *flagHelp {
		flag.Usage()
	}

	if len(flag.Args()) == 0 {
		flag.Usage()
	}

	if flagHost != nil {
		os.Setenv("LIBSTORAGE_HOST", *flagHost)
	}

	if flagLogLvl != nil {
		os.Setenv("LIBSTORAGE_LOGGING_LEVEL", *flagLogLvl)
	}

	if lvl, err := log.ParseLevel(
		config.GetString(apitypes.ConfigLogLevel)); err == nil {
		log.SetLevel(lvl)
	}

	if flagPrintConfig != nil && *flagPrintConfig {
		jstr, err := config.ToJSON()
		if err != nil {
			fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
			os.Exit(1)
		}
		fmt.Fprintln(apitypes.Stdout, jstr)
		os.Exit(0)
	}

	buf := &bytes.Buffer{}
	fmt.Fprintf(buf, "libstorage:\n  server:\n    services:\n")
	for _, ds := range flag.Args() {
		dsp := strings.Split(ds, ":")
		dn := dsp[0]
		sn := dsp[0]
		if len(dsp) > 1 {
			sn = dsp[1]
		}
		fmt.Fprintf(buf, "      %s:\n        driver: %s\n", sn, dn)
	}
	if err := config.ReadConfig(buf); err != nil {
		fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
		os.Exit(1)
	}

	server.CloseOnAbort()

	_, errs, err := server.Serve(ctx, config)
	if err != nil {
		fmt.Fprintf(apitypes.Stderr, "%s: error: %v\n", os.Args[0], err)
		os.Exit(1)
	}

	<-errs
}
1346561
func (ar *allocRunner) Run() {
	// Close the wait channel on return
	defer close(ar.waitCh)

	// Start the task state update handler
	go ar.handleTaskStateUpdates()

	// Start the alloc update handler
	go ar.handleAllocUpdates()

	// If task update chan has been closed, that means we've been shutdown.
	select {
	case <-ar.taskStateUpdateHandlerCh:
		return
	default:
	}

	// Run the prestart hooks if non-terminal
	if ar.shouldRun() {
		if err := ar.prerun(); err != nil {
			ar.logger.Error("prerun failed", "error", err)
			goto POST
		}
	}

	// Run the runners (blocks until they exit)
	ar.runTasks()

POST:
	// Run the postrun hooks
	if err := ar.postrun(); err != nil {
		ar.logger.Error("postrun failed", "error", err)
	}

}