github.com/mwhudson/juju@v0.0.0-20160512215208-90ff01f3497f/cmd/juju/service/addrelation.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package service
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  
    12  	apiservice "github.com/juju/juju/api/service"
    13  	"github.com/juju/juju/apiserver/params"
    14  	"github.com/juju/juju/cmd/juju/block"
    15  	"github.com/juju/juju/cmd/modelcmd"
    16  )
    17  
    18  // NewAddRelationCommand returns a command to add a relation between 2 services.
    19  func NewAddRelationCommand() cmd.Command {
    20  	return modelcmd.Wrap(&addRelationCommand{})
    21  }
    22  
    23  // addRelationCommand adds a relation between two service endpoints.
    24  type addRelationCommand struct {
    25  	modelcmd.ModelCommandBase
    26  	Endpoints []string
    27  }
    28  
    29  func (c *addRelationCommand) Info() *cmd.Info {
    30  	return &cmd.Info{
    31  		Name:    "add-relation",
    32  		Args:    "<service1>[:<relation name1>] <service2>[:<relation name2>]",
    33  		Purpose: "add a relation between two services",
    34  	}
    35  }
    36  
    37  func (c *addRelationCommand) Init(args []string) error {
    38  	if len(args) != 2 {
    39  		return fmt.Errorf("a relation must involve two services")
    40  	}
    41  	c.Endpoints = args
    42  	return nil
    43  }
    44  
    45  type serviceAddRelationAPI interface {
    46  	Close() error
    47  	AddRelation(endpoints ...string) (*params.AddRelationResults, error)
    48  }
    49  
    50  func (c *addRelationCommand) getAPI() (serviceAddRelationAPI, error) {
    51  	root, err := c.NewAPIRoot()
    52  	if err != nil {
    53  		return nil, errors.Trace(err)
    54  	}
    55  	return apiservice.NewClient(root), nil
    56  }
    57  
    58  func (c *addRelationCommand) Run(_ *cmd.Context) error {
    59  	client, err := c.getAPI()
    60  	if err != nil {
    61  		return err
    62  	}
    63  	defer client.Close()
    64  	_, err = client.AddRelation(c.Endpoints...)
    65  	return block.ProcessBlockedError(err, block.BlockChange)
    66  }