// public API, executes a command on leader, returns chan which will
// block until command has been replicated to our local replica
426916
func (s *server) Command(cmd string, args [][]byte) <-chan Result {

	if s.IsLeader() {
		cb := s.state.newCommand()
		cmdBytes := bytesForCommand(cb.originAddr, cb.reqNo, cmd, args)
		s.raft.Apply(cmdBytes, commandTimeout)
		return cb.result
	}
	// couldn't exec as leader, fallback to forwarding
	cb, err := s.dispatchToLeader(cmd, args)
	if err != nil {
		if cb != nil {
			cb.cancel()
		}
		ret := make(chan Result, 1)
		ret <- Result{nil, err}
		return ret
	}
	return cb.result
}
95300
func (tio *Timeout) RunCommand() (<-chan *ExitStatus, error) {
	if err := tio.start(); err != nil {
		return nil, err
	}

	exitChan := make(chan *ExitStatus)
	go func() {
		exitChan <- tio.wait(context.Background())
	}()
	return exitChan, nil
}
148856
func (c *upgradeCharmCommand) Run(ctx *cmd.Context) error {
	apiRoot, err := c.NewAPIRoot()
	if err != nil {
		return errors.Trace(err)
	}
	defer func() { _ = apiRoot.Close() }()

	// If the user has specified config or storage constraints,
	// make sure the server has facade version 2 at a minimum.
	if c.Config.Path != "" || len(c.Storage) > 0 {
		action := "updating config"
		if c.Config.Path == "" {
			action = "updating storage constraints"
		}
		if apiRoot.BestFacadeVersion("Application") < 2 {
			suffix := "this server"
			if version, ok := apiRoot.ServerVersion(); ok {
				suffix = fmt.Sprintf("server version %s", version)
			}
			return errors.New(action + " at upgrade-charm time is not supported by " + suffix)
		}
	}

	generation, err := c.ActiveBranch()
	if err != nil {
		return errors.Trace(err)
	}
	charmUpgradeClient := c.NewCharmUpgradeClient(apiRoot)
	oldURL, err := charmUpgradeClient.GetCharmURL(generation, c.ApplicationName)
	if err != nil {
		return errors.Trace(err)
	}

	newRef := c.SwitchURL
	if newRef == "" {
		newRef = c.CharmPath
	}
	if c.SwitchURL == "" && c.CharmPath == "" {
		// If the charm we are upgrading is local, then we must
		// specify a path or switch url to upgrade with.
		if oldURL.Schema == "local" {
			return errors.New("upgrading a local charm requires either --path or --switch")
		}
		// No new URL specified, but revision might have been.
		newRef = oldURL.WithRevision(c.Revision).String()
	}

	// First, ensure the charm is added to the model.
	modelConfigGetter := c.NewModelConfigGetter(apiRoot)
	modelConfig, err := getModelConfig(modelConfigGetter)
	if err != nil {
		return errors.Trace(err)
	}
	bakeryClient, err := c.BakeryClient()
	if err != nil {
		return errors.Trace(err)
	}
	conAPIRoot, err := c.NewControllerAPIRoot()
	if err != nil {
		return errors.Trace(err)
	}
	csURL, err := c.CharmStoreURLGetter(conAPIRoot)
	if err != nil {
		return errors.Trace(err)
	}

	applicationInfo, err := charmUpgradeClient.Get(generation, c.ApplicationName)
	if err != nil {
		return errors.Trace(err)
	}

	if c.Channel == "" {
		c.Channel = csclientparams.Channel(applicationInfo.Channel)
	}
	charmAdder := c.NewCharmAdder(apiRoot, bakeryClient, csURL, c.Channel)
	charmRepo := c.getCharmStore(bakeryClient, csURL, modelConfig)

	deployedSeries := applicationInfo.Series

	chID, csMac, err := c.addCharm(charmAdder, charmRepo, modelConfig, oldURL, newRef, deployedSeries, c.Force)
	if err != nil {
		if termErr, ok := errors.Cause(err).(*common.TermsRequiredError); ok {
			return errors.Trace(termErr.UserErr())
		}
		return block.ProcessBlockedError(err, block.BlockChange)
	}
	ctx.Infof("Added charm %q to the model.", chID.URL)

	// Next, upgrade resources.
	charmsClient := c.NewCharmClient(apiRoot)
	resourceLister, err := c.NewResourceLister(apiRoot)
	if err != nil {
		return errors.Trace(err)
	}
	meta, err := getMetaResources(chID.URL, charmsClient)
	if err != nil {
		return errors.Trace(err)
	}
	ids, err := c.upgradeResources(apiRoot, resourceLister, chID, csMac, meta)
	if err != nil {
		return errors.Trace(err)
	}

	// Finally, upgrade the application.
	var configYAML []byte
	if c.Config.Path != "" {
		configYAML, err = c.Config.Read(ctx)
		if err != nil {
			return errors.Trace(err)
		}
	}
	cfg := application.SetCharmConfig{
		ApplicationName:    c.ApplicationName,
		CharmID:            chID,
		ConfigSettingsYAML: string(configYAML),
		Force:              c.Force,
		ForceSeries:        c.ForceSeries,
		ForceUnits:         c.ForceUnits,
		ResourceIDs:        ids,
		StorageConstraints: c.Storage,
	}
	return block.ProcessBlockedError(charmUpgradeClient.SetCharm(generation, cfg), block.BlockChange)
}
814573
func (c *upgradeGUICommand) Run(ctx *cmd.Context) error {
	if c.list {
		// List available Juju GUI archive versions.
		allMeta, err := remoteArchiveMetadata()
		if err != nil {
			return errors.Annotate(err, "cannot list Juju GUI release versions")
		}
		for _, metadata := range allMeta {
			ctx.Infof(metadata.Version.String())
		}
		return nil
	}
	// Retrieve the GUI archive and its related info.
	archive, err := openArchive(c.versOrPath)
	if err != nil {
		return errors.Trace(err)
	}
	defer archive.r.Close()

	// Open the Juju API client.
	client, err := c.NewControllerAPIClient()
	if err != nil {
		return errors.Annotate(err, "cannot establish API connection")
	}
	defer client.Close()

	// Check currently uploaded GUI version.
	existingHash, isCurrent, err := existingVersionInfo(client, archive.vers)
	if err != nil {
		return errors.Trace(err)
	}

	// Upload the release file if required.
	if archive.hash != existingHash {
		if archive.local {
			ctx.Infof("using local Juju GUI archive")
		} else {
			ctx.Infof("fetching Juju GUI archive")
		}
		f, err := storeArchive(archive.r)
		if err != nil {
			return errors.Trace(err)
		}
		defer f.Close()
		ctx.Infof("uploading Juju GUI %s", archive.vers)
		isCurrent, err = clientUploadGUIArchive(client, f, archive.hash, archive.size, archive.vers)
		if err != nil {
			return errors.Annotate(err, "cannot upload Juju GUI")
		}
		ctx.Infof("upload completed")
	}
	// Switch to the new version if not already at the desired one.
	if isCurrent {
		ctx.Infof("Juju GUI at version %s", archive.vers)
		return nil
	}
	if err = clientSelectGUIVersion(client, archive.vers); err != nil {
		return errors.Annotate(err, "cannot switch to new Juju GUI version")
	}
	ctx.Infof("Juju GUI switched to version %s", archive.vers)
	return nil
}
382396
func (c *SocketConnection) Execute(command, args string, sync bool) (m *Message, err error) {
	return c.SendMsg(map[string]string{
		"call-command":     "execute",
		"execute-app-name": command,
		"execute-app-arg":  args,
		"event-lock":       strconv.FormatBool(sync),
	}, "", "")
}
557510
func Execute(name string, stdin string, args ...string) (string, string, error) {
	cmd := exec.Command(name, args...)
	cmd.Stdin = strings.NewReader(stdin)
	stdout, stderr := new(bytes.Buffer), new(bytes.Buffer)
	cmd.Stdout = stdout
	cmd.Stderr = stderr

	err := cmd.Run()
	return stdout.String(), stderr.String(), errors.Annotatef(err, "cannot run command %s", name)
}
917180
func (s *server) dispatchToLeader(cmd string, args [][]byte) (*commandCallback, error) {
	s.leaderLock.Lock()
	defer s.leaderLock.Unlock()
	var err error
	if s.leaderConn == nil || s.Leader() == nil || s.Leader().String() != s.leaderConn.remoteAddr().String() {
		if s.leaderConn != nil {
			s.lg.Printf("Leader changed, reconnecting, was: %s, now %s", s.leaderConn.remoteAddr(), s.Leader())
		}

		// reconnect
		if s.leaderConn != nil {
			s.leaderConn.c.Close()
		}
		newConn, err := s.rpcLayer.Dial(s.Leader().String(), 1*time.Minute)
		if err != nil {
			return nil, fmt.Errorf("Couldn't connect to leader at %s", s.Leader().String())
		}
		s.leaderConn, err = newConnToLeader(newConn, s.rpcLayer.Addr().String(), s.lg)
		if err != nil {
			s.lg.Printf("Got error connecting to leader %s from follower %s : %s", s.Leader().String(), s.rpcLayer.Addr().String(), err)
			return nil, err
		}
	}
	cb := s.state.newCommand()
	err = s.leaderConn.forwardCommand(cb, cmd, args)
	if err != nil {
		cb.cancel()
		return nil, err
	}
	return cb, nil
}
1373183
func main() {
	statikFS, err := fs.New()
	if err != nil {
		log.Fatal(err)
	}

	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS)))
	http.ListenAndServe(":8080", nil)
}
1010448
func (cmd *blockRegionCmd) Execute(args []string) error {
	// Setup the global config options and ensure they are valid.
	if err := setupGlobalConfig(); err != nil {
		return err
	}

	// Ensure expected arguments.
	if len(args) < 1 {
		return errors.New("required block hash parameter not specified")
	}
	if len(args) < 2 {
		return errors.New("required start offset parameter not " +
			"specified")
	}
	if len(args) < 3 {
		return errors.New("required region length parameter not " +
			"specified")
	}

	// Parse arguments.
	blockHash, err := chainhash.NewHashFromStr(args[0])
	if err != nil {
		return err
	}
	startOffset, err := strconv.ParseUint(args[1], 10, 32)
	if err != nil {
		return err
	}
	regionLen, err := strconv.ParseUint(args[2], 10, 32)
	if err != nil {
		return err
	}

	// Load the block database.
	db, err := loadBlockDB()
	if err != nil {
		return err
	}
	defer db.Close()

	return db.View(func(tx database.Tx) error {
		log.Infof("Fetching block region %s<%d:%d>", blockHash,
			startOffset, startOffset+regionLen-1)
		region := database.BlockRegion{
			Hash:   blockHash,
			Offset: uint32(startOffset),
			Len:    uint32(regionLen),
		}
		startTime := time.Now()
		regionBytes, err := tx.FetchBlockRegion(&region)
		if err != nil {
			return err
		}
		log.Infof("Loaded block region in %v", time.Since(startTime))
		log.Infof("Double Hash: %s", chainhash.DoubleHashH(regionBytes))
		log.Infof("Region Hex: %s", hex.EncodeToString(regionBytes))
		return nil
	})
}
419489
func (c *Command) exec(base string, stop <-chan bool) (response Response) {
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	done := make(chan error)
	args := strings.Split(strings.Replace(strings.Replace(c.Cmd, "'", "", -1), "\"", "", -1), " ")
	ex := exec.Command(args[0], args[1:]...)
	ex.Dir = base
	// make cmd path
	if c.Path != "" {
		if strings.Contains(c.Path, base) {
			ex.Dir = c.Path
		} else {
			ex.Dir = filepath.Join(base, c.Path)
		}
	}
	ex.Stdout = &stdout
	ex.Stderr = &stderr
	// Start command
	ex.Start()
	go func() { done <- ex.Wait() }()
	// Wait a result
	select {
	case <-stop:
		// Stop running command
		ex.Process.Kill()
	case err := <-done:
		// Command completed
		response.Name = c.Cmd
		response.Out = stdout.String()
		if err != nil {
			response.Err = errors.New(stderr.String() + stdout.String())
		}
	}
	return
}
188033
func (s *Status) Leader() (string, error) {
	r := s.c.newRequest("GET", "/v1/status/leader")
	_, resp, err := requireOK(s.c.doRequest(r))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	var leader string
	if err := decodeBody(resp, &leader); err != nil {
		return "", err
	}
	return leader, nil
}
60957
func main() {
	app := cli.NewApp()
	app.Name = Name
	app.Version = Version
	app.Author = "kyokomi"
	app.Email = ""
	app.Usage = ""

	app.Flags = GlobalFlags
	app.Commands = Commands
	app.CommandNotFound = CommandNotFound

	app.Run(os.Args)
}
128263
func main() {
	CheckArgs("<url>", "<directory>")
	url := os.Args[1]
	directory := os.Args[2]

	// Clone the given repository to the given directory
	Info("git clone %s %s", url, directory)

	_, err := git.PlainClone(directory, false, &git.CloneOptions{
		URL:   url,
		Depth: 1,

		// as git does, when you make a clone, pull or some other operations the
		// server sends information via the sideband, this information can being
		// collected provinding a io.Writer to the CloneOptions options
		Progress: os.Stdout,
	})

	CheckIfError(err)
}
891865
func (s *Status) Leader(args struct{}, reply *string) error {
	leader := string(s.server.raft.Leader())
	if leader != "" {
		*reply = leader
	} else {
		*reply = ""
	}
	return nil
}
456477
func runLocalCommand(cmd string, args ...string) (error, int) {
	osCmd := exec.Command(cmd, args...)
	osCmd.Stderr = os.Stderr
	osCmd.Stdout = os.Stdout
	osCmd.Start()
	err := osCmd.Wait()
	if err != nil {
		// Get the command's exit status if we can
		if exiterr, ok := err.(*exec.ExitError); ok {
			if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				return nil, status.ExitStatus()
			}
		}
		// Otherwise, generic command error
		return err, -1
	}
	return nil, 0
}
1335187
func (s *Shell) Execute(command string, arguments ...string) (*Command, error) {
	request := NewExecuteCommandRequest(s.client.url, s.id, command, arguments, &s.client.Parameters)
	defer request.Free()

	response, err := s.client.sendRequest(request)
	if err != nil {
		return nil, err
	}

	commandID, err := ParseExecuteCommandResponse(response)
	if err != nil {
		return nil, err
	}

	cmd := newCommand(s, commandID)

	return cmd, nil
}
1364434
func (c *cmdable) Command() *CommandsInfoCmd {
	cmd := NewCommandsInfoCmd("command")
	c.process(cmd)
	return cmd
}