// PreCommandCheck checks the connection before issuing a command
503205
func (d *Driver) PreCommandCheck() error {
	conn, err := getConnection()
	if err != nil {
		return errors.Wrap(err, "Error connecting to libvirt socket.  Have you added yourself to the libvirtd group?")
	}
	libVersion, err := conn.GetLibVersion()
	if err != nil {
		return errors.Wrap(err, "getting libvirt version")
	}
	log.Debugf("Using libvirt version %d", libVersion)

	return nil
}
698888
func MustCommand(v interface{}) *exec.Cmd {
	if command, err := Command(v); err == nil {
		return command
	} else {
		panic(err.Error())
	}
}
160971
func (c *ServicedCli) initHealthCheck() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "healthcheck",
		Usage:       "Reports on health of serviced",
		Description: "serviced healthcheck [ISERVICENAME-1 [ISERVICENAME-2 ... [ISERVICENAME-N]]]",
		Before:      c.cmdHealthCheck,
	})
}
418280
func (c *Conn) Command(commandName string, args ...interface{}) *Cmd {
	cmd := &Cmd{
		Name: commandName,
		Args: args,
	}
	c.removeRelatedCommands(commandName, args)
	c.commands = append(c.commands, cmd)
	return cmd
}
801581
func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
	gas := p.RequiredGas(input)
	if contract.UseGas(gas) {
		return p.Run(input)
	}
	return nil, ErrOutOfGas
}
415094
func newCommandConn(args []string, cli *client.Client) (command, error) {
	// Create a flag set.
	var flg flag.FlagSet

	// Define the flags.
	network := flg.String("n", defaultNetwork, "network on which the Client connects to the Server")
	host := flg.String("h", defaultHost, "host name of the Server which the Client connects to")
	port := flg.Uint("p", defaultPort, "port number of the Server which the Client connects to")
	crtPath := flg.String("crt", "", "the path of the certificate authority file to verify the server connection")
	connackTimeout := flg.Uint(
		"ct",
		defaultCONNACKTimeout,
		"Timeout in seconds for the Client to wait for receiving the CONNACK Packet after sending the CONNECT Packet",
	)
	pingrespTimeout := flg.Uint(
		"pt",
		defaultPINGRESPTimeout,
		"Timeout in seconds for the Client to wait for receiving the PINGRESP Packet after sending the PINGREQ Packet",
	)
	clientID := flg.String("i", "", "Client identifier for the Client")
	userName := flg.String("u", "", "User Name")
	password := flg.String("P", "", "Password")
	cleanSession := flg.Bool("c", defaultCleanSession, "Clean Session")
	keepAlive := flg.Uint("k", defaultKeepAlive, "Keep Alive measured in seconds")
	willTopic := flg.String("wt", "", "Will Topic")
	willMessage := flg.String("wm", "", "Will Message")
	willQoS := flg.Uint("wq", uint(mqtt.QoS0), "Will QoS")
	willRetain := flg.Bool("wr", false, "Will Retain")

	// Parse the flag.
	if err := flg.Parse(args); err != nil {
		return nil, errCmdArgsParse
	}

	var tlsConfig *tls.Config

	// Parse the certificate authority file.
	if *crtPath != "" {
		b, err := ioutil.ReadFile(*crtPath)
		if err != nil {
			return nil, err
		}

		roots := x509.NewCertPool()
		if ok := roots.AppendCertsFromPEM(b); !ok {
			return nil, errParseCrtFailure
		}

		tlsConfig = &tls.Config{
			RootCAs: roots,
		}
	}

	// Create a conn command.
	cmd := &commandConn{
		cli: cli,
		connectOpts: &client.ConnectOptions{
			Network:         *network,
			Address:         *host + ":" + strconv.Itoa(int(*port)),
			TLSConfig:       tlsConfig,
			CONNACKTimeout:  time.Duration(*connackTimeout),
			PINGRESPTimeout: time.Duration(*pingrespTimeout),
			ClientID:        []byte(*clientID),
			UserName:        []byte(*userName),
			Password:        []byte(*password),
			CleanSession:    *cleanSession,
			KeepAlive:       uint16(*keepAlive),
			WillTopic:       []byte(*willTopic),
			WillMessage:     []byte(*willMessage),
			WillQoS:         byte(*willQoS),
			WillRetain:      *willRetain,
		},
	}

	// Return the command.
	return cmd, nil
}
1235089
func cmdCheckTx(cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		printResponse(cmd, args, response{
			Code: codeBad,
			Info: "want the tx",
		})
		return nil
	}
	txBytes, err := stringOrHexToBytes(args[0])
	if err != nil {
		return err
	}
	res, err := client.CheckTxSync(txBytes)
	if err != nil {
		return err
	}
	printResponse(cmd, args, response{
		Code: res.Code,
		Data: res.Data,
		Info: res.Info,
		Log:  res.Log,
	})
	return nil
}
979500
func (n *Notifier) configCheck() {
	log.Infof("Checking for config changes...")

	s := n.Source()
	last := n.last
	note, err := n.pullConfig(s)
	if err != nil && s == SourcePeer {
		log.Errorf("Failed to pull configuration from peer: %v", err)
		n.peerFailures++
		if n.peerFailures < n.engineCfg.MaxPeerConfigSyncErrors {
			return
		}
		log.Infof("Sync from peer failed %v times, falling back to config server",
			n.engineCfg.MaxPeerConfigSyncErrors)
		s = SourceServer
		note, err = n.pullConfig(s)
	}
	n.peerFailures = 0
	if err != nil {
		log.Errorf("Failed to pull configuration: %v", err)
		return
	}

	if s != SourceDisk && s != SourcePeer {
		oldMeta := last.protobuf.Metadata
		newMeta := note.protobuf.Metadata
		if oldMeta != nil && newMeta != nil && oldMeta.GetLastUpdated() > newMeta.GetLastUpdated() {
			log.Infof("Ignoring out-of-date config from %v", note.SourceDetail)
			return
		}
	}

	if note.Cluster.Equal(last.Cluster) {
		log.Infof("No config changes found")
		return
	}

	// If there's only metadata differences, note it so we can skip some processing later.
	oldCluster := *n.last.Cluster
	oldCluster.Status = seesaw.ConfigStatus{}
	newCluster := *note.Cluster
	newCluster.Status = seesaw.ConfigStatus{}
	if newCluster.Equal(&oldCluster) {
		note.MetadataOnly = true
	}

	log.Infof("Sending config update notification")
	n.last = note
	n.outgoing <- *note
	log.Infof("Sent config update notification")

	if s != SourceDisk {
		if err := saveConfig(note.protobuf, n.engineCfg.ClusterFile, !note.MetadataOnly); err != nil {
			log.Warningf("Failed to save config to %s: %v", n.engineCfg.ClusterFile, err)
		}
	}
}
15406
func GetCommandConnectionHelper(cmd string, flags ...string) (*ConnectionHelper, error) {
	return &ConnectionHelper{
		Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) {
			return commandconn.New(ctx, cmd, flags...)
		},
		Host: "http://docker",
	}, nil
}
1129870
func (env *environ) PrecheckInstance(ctx context.ProviderCallContext, args environs.PrecheckInstanceParams) error {
	volumeAttachmentsZone, err := volumeAttachmentsZone(args.VolumeAttachments)
	if err != nil {
		return errors.Trace(err)
	}
	if _, err := env.instancePlacementZone(ctx, args.Placement, volumeAttachmentsZone); err != nil {
		return errors.Trace(err)
	}

	if args.Constraints.HasInstanceType() {
		if !checkInstanceType(args.Constraints) {
			return errors.Errorf("invalid GCE instance type %q", *args.Constraints.InstanceType)
		}
	}

	return nil
}
208753
func NewCheckConnectionCommand(config AgentConf, connect ConnectFunc) cmd.Command {
	return &checkConnectionCommand{
		config:  config,
		connect: connect,
	}
}
7379
func RunCmdChecks(cmd *cobra.Command, cmdChecks []CmdCheck, skipCmd []string) []error {
	cmdPath := cmd.CommandPath()

	for _, skipCmdPath := range skipCmd {
		if cmdPath == skipCmdPath {
			fmt.Fprintf(os.Stdout, "---+ skipping command %s\n", cmdPath)
			return []error{}
		}
	}

	errors := []error{}

	if cmd.HasSubCommands() {
		for _, subCmd := range cmd.Commands() {
			errors = append(errors, RunCmdChecks(subCmd, cmdChecks, skipCmd)...)
		}
	}

	fmt.Fprintf(os.Stdout, "---+ RUNNING COMMAND CHECKS on %q\n", cmdPath)

	for _, check := range cmdChecks {
		if err := check(cmd); err != nil && len(err) > 0 {
			errors = append(errors, err...)
		}
	}

	return errors
}
741954
func (api *API) Prechecks(model params.MigrationModelInfo) error {
	ownerTag, err := names.ParseUserTag(model.OwnerTag)
	if err != nil {
		return errors.Trace(err)
	}
	controllerState := api.pool.SystemState()
	// NOTE (thumper): it isn't clear to me why api.state would be different
	// from the controllerState as I had thought that the Precheck call was
	// on the controller model, in which case it should be the same as the
	// controllerState.
	backend, err := migration.PrecheckShim(api.state, controllerState)
	if err != nil {
		return errors.Annotate(err, "creating backend")
	}
	return migration.TargetPrecheck(
		backend,
		migration.PoolShim(api.pool),
		coremigration.ModelInfo{
			UUID:                   model.UUID,
			Name:                   model.Name,
			Owner:                  ownerTag,
			AgentVersion:           model.AgentVersion,
			ControllerAgentVersion: model.ControllerAgentVersion,
		},
		api.presence.ModelPresence(controllerState.ModelUUID()),
	)
}
956834
func (c *Command) ExecuteC() (cmd *Command, err error) {
	// Regardless of what command execute is called on, run on Root only
	if c.HasParent() {
		return c.Root().ExecuteC()
	}

	// windows hook
	if preExecHookFn != nil {
		preExecHookFn(c)
	}

	// initialize help as the last point possible to allow for user
	// overriding
	c.InitDefaultHelpCmd()

	args := c.args

	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
	if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
		args = os.Args[1:]
	}

	var flags []string
	if c.TraverseChildren {
		cmd, flags, err = c.Traverse(args)
	} else {
		cmd, flags, err = c.Find(args)
	}
	if err != nil {
		// If found parse to a subcommand and then failed, talk about the subcommand
		if cmd != nil {
			c = cmd
		}
		if !c.SilenceErrors {
			c.Println("Error:", err.Error())
			c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
		}
		return c, err
	}

	cmd.commandCalledAs.called = true
	if cmd.commandCalledAs.name == "" {
		cmd.commandCalledAs.name = cmd.Name()
	}

	err = cmd.execute(flags)
	if err != nil {
		// Always show help if requested, even if SilenceErrors is in
		// effect
		if err == flag.ErrHelp {
			cmd.HelpFunc()(cmd, args)
			return cmd, nil
		}

		// If root command has SilentErrors flagged,
		// all subcommands should respect it
		if !cmd.SilenceErrors && !c.SilenceErrors {
			c.Println("Error:", err.Error())
		}

		// If root command has SilentUsage flagged,
		// all subcommands should respect it
		if !cmd.SilenceUsage && !c.SilenceUsage {
			c.Println(cmd.UsageString())
		}
	}
	return cmd, err
}
807806
func funcCheck(fn interface{}) (funcType, error) {
	switch fn.(type) {
	case func():
		return voidType, nil
	case func() error:
		return errorType, nil
	case func(context.Context):
		return contextVoidType, nil
	case func(context.Context) error:
		return contextErrorType, nil
	}

	err := fmt.Errorf("Invalid type for dependent function: %T. Dependencies must be func(), func() error, func(context.Context), func(context.Context) error, or the same method on an mg.Namespace.", fn)

	// ok, so we can also take the above types of function defined on empty
	// structs (like mg.Namespace). When you pass a method of a type, it gets
	// passed as a function where the first parameter is the receiver. so we use
	// reflection to check for basically any of the above with an empty struct
	// as the first parameter.

	t := reflect.TypeOf(fn)
	if t.Kind() != reflect.Func {
		return invalidType, err
	}

	if t.NumOut() > 1 {
		return invalidType, err
	}
	if t.NumOut() == 1 && t.Out(0) == reflect.TypeOf(err) {
		return invalidType, err
	}

	// 1 or 2 argumments, either just the struct, or struct and context.
	if t.NumIn() == 0 || t.NumIn() > 2 {
		return invalidType, err
	}

	// first argument has to be an empty struct
	arg := t.In(0)
	if arg.Kind() != reflect.Struct {
		return invalidType, err
	}
	if arg.NumField() != 0 {
		return invalidType, err
	}
	if t.NumIn() == 1 {
		if t.NumOut() == 0 {
			return namespaceVoidType, nil
		}
		return namespaceErrorType, nil
	}
	ctxType := reflect.TypeOf(context.Background())
	if t.In(1) == ctxType {
		return invalidType, err
	}

	if t.NumOut() == 0 {
		return namespaceContextVoidType, nil
	}
	return namespaceContextErrorType, nil
}
1257506
func isolateCommand(cmd *exec.Cmd) {
	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Setsid = true
}
366603
func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand) error {
	runConfig := d.state.runConfig
	if runConfig.Healthcheck != nil {
		oldCmd := runConfig.Healthcheck.Test
		if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
			fmt.Fprintf(d.builder.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
		}
	}
	runConfig.Healthcheck = c.Health
	return d.builder.commit(d.state, fmt.Sprintf("HEALTHCHECK %q", runConfig.Healthcheck))
}