github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/payload/context/status-set.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package context
     5  
     6  import (
     7  	"github.com/juju/cmd"
     8  	"github.com/juju/errors"
     9  
    10  	jujucmd "github.com/juju/juju/cmd"
    11  	"github.com/juju/juju/payload"
    12  )
    13  
    14  // StatusSetCmdName is the name of the payload status-set command.
    15  const StatusSetCmdName = "payload-status-set"
    16  
    17  // NewStatusSetCmd returns a new StatusSetCmd that wraps the given context.
    18  func NewStatusSetCmd(ctx HookContext) (*StatusSetCmd, error) {
    19  	return &StatusSetCmd{hookContextFunc: componentHookContext(ctx)}, nil
    20  }
    21  
    22  // StatusSetCmd is a command that registers a payload with juju.
    23  type StatusSetCmd struct {
    24  	cmd.CommandBase
    25  
    26  	hookContextFunc func() (Component, error)
    27  	class           string
    28  	id              string
    29  	status          string
    30  }
    31  
    32  // Info implements cmd.Command.
    33  func (c StatusSetCmd) Info() *cmd.Info {
    34  	return jujucmd.Info(&cmd.Info{
    35  		Name:    StatusSetCmdName,
    36  		Args:    "<class> <id> <status>",
    37  		Purpose: "update the status of a payload",
    38  		Doc: `
    39  "payload-status-set" is used to update the current status of a registered payload.
    40  The <class> and <id> provided must match a payload that has been previously
    41  registered with juju using payload-register. The <status> must be one of the
    42  follow: starting, started, stopping, stopped
    43  `,
    44  	})
    45  }
    46  
    47  // Init implements cmd.Command.
    48  func (c *StatusSetCmd) Init(args []string) error {
    49  	if len(args) < 3 {
    50  		return errors.Errorf("missing required arguments")
    51  	}
    52  	c.class = args[0]
    53  	c.id = args[1]
    54  	c.status = args[2]
    55  	return cmd.CheckEmpty(args[3:])
    56  }
    57  
    58  // Run implements cmd.Command.
    59  func (c *StatusSetCmd) Run(ctx *cmd.Context) error {
    60  	if err := c.validate(ctx); err != nil {
    61  		return errors.Trace(err)
    62  	}
    63  	hctx, err := c.hookContextFunc()
    64  	if err != nil {
    65  		return errors.Trace(err)
    66  	}
    67  
    68  	if err := hctx.SetStatus(c.class, c.id, c.status); err != nil {
    69  		return errors.Trace(err)
    70  	}
    71  
    72  	// TODO(ericsnow) Is the flush really necessary?
    73  
    74  	// We flush to state immediately so that status reflects the
    75  	// payload correctly.
    76  	if err := hctx.Flush(); err != nil {
    77  		return errors.Trace(err)
    78  	}
    79  
    80  	return nil
    81  }
    82  
    83  func (c *StatusSetCmd) validate(ctx *cmd.Context) error {
    84  	return payload.ValidateState(c.status)
    85  }