github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/worker/uniter/runner/jujuc/payload-status-set.go (about)

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