github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/cmd/juju/environment/set.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package environment
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/juju/cmd"
    11  	"github.com/juju/utils/keyvalues"
    12  
    13  	"github.com/juju/juju/cmd/envcmd"
    14  	"github.com/juju/juju/cmd/juju/block"
    15  )
    16  
    17  type attributes map[string]interface{}
    18  
    19  type SetCommand struct {
    20  	envcmd.EnvCommandBase
    21  	api    SetEnvironmentAPI
    22  	values attributes
    23  }
    24  
    25  const setEnvHelpDoc = `
    26  Updates the environment of a running Juju instance.  Multiple key/value pairs
    27  can be passed on as command line arguments.
    28  `
    29  
    30  func (c *SetCommand) Info() *cmd.Info {
    31  	return &cmd.Info{
    32  		Name:    "set",
    33  		Args:    "key=[value] ...",
    34  		Purpose: "replace environment values",
    35  		Doc:     strings.TrimSpace(setEnvHelpDoc),
    36  	}
    37  }
    38  
    39  func (c *SetCommand) Init(args []string) (err error) {
    40  	if len(args) == 0 {
    41  		return fmt.Errorf("no key, value pairs specified")
    42  	}
    43  
    44  	options, err := keyvalues.Parse(args, true)
    45  	if err != nil {
    46  		return err
    47  	}
    48  
    49  	c.values = make(attributes)
    50  	for key, value := range options {
    51  		if key == "agent-version" {
    52  			return fmt.Errorf("agent-version must be set via upgrade-juju")
    53  		}
    54  		c.values[key] = value
    55  	}
    56  
    57  	return nil
    58  }
    59  
    60  type SetEnvironmentAPI interface {
    61  	Close() error
    62  	EnvironmentGet() (map[string]interface{}, error)
    63  	EnvironmentSet(config map[string]interface{}) error
    64  }
    65  
    66  func (c *SetCommand) getAPI() (SetEnvironmentAPI, error) {
    67  	if c.api != nil {
    68  		return c.api, nil
    69  	}
    70  	return c.NewAPIClient()
    71  }
    72  
    73  func (c *SetCommand) Run(ctx *cmd.Context) error {
    74  	client, err := c.getAPI()
    75  	if err != nil {
    76  		return err
    77  	}
    78  	defer client.Close()
    79  
    80  	// extra call to the API to retrieve env config
    81  	envAttrs, err := client.EnvironmentGet()
    82  	if err != nil {
    83  		return err
    84  	}
    85  	for key := range c.values {
    86  		// check if the key exists in the existing env config
    87  		// and warn the user if the key is not defined in
    88  		// the existing config
    89  		if _, exists := envAttrs[key]; !exists {
    90  			logger.Warningf("key %q is not defined in the current environment configuration: possible misspelling", key)
    91  		}
    92  
    93  	}
    94  	return block.ProcessBlockedError(client.EnvironmentSet(c.values), block.BlockChange)
    95  }