github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/commands/service/update_user_provided_service.go (about)

     1  package service
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"strings"
     8  
     9  	"code.cloudfoundry.org/cli/cf/flagcontext"
    10  	"code.cloudfoundry.org/cli/cf/flags"
    11  	. "code.cloudfoundry.org/cli/cf/i18n"
    12  	"code.cloudfoundry.org/cli/cf/uihelpers"
    13  
    14  	"code.cloudfoundry.org/cli/cf"
    15  	"code.cloudfoundry.org/cli/cf/api"
    16  	"code.cloudfoundry.org/cli/cf/commandregistry"
    17  	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
    18  	"code.cloudfoundry.org/cli/cf/requirements"
    19  	"code.cloudfoundry.org/cli/cf/terminal"
    20  )
    21  
    22  type UpdateUserProvidedService struct {
    23  	ui                              terminal.UI
    24  	config                          coreconfig.Reader
    25  	userProvidedServiceInstanceRepo api.UserProvidedServiceInstanceRepository
    26  	serviceInstanceReq              requirements.ServiceInstanceRequirement
    27  }
    28  
    29  func init() {
    30  	commandregistry.Register(&UpdateUserProvidedService{})
    31  }
    32  
    33  func (cmd *UpdateUserProvidedService) MetaData() commandregistry.CommandMetadata {
    34  	fs := make(map[string]flags.FlagSet)
    35  	fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Credentials, provided inline or in a file, to be exposed in the VCAP_SERVICES environment variable for bound applications")}
    36  	fs["l"] = &flags.StringFlag{ShortName: "l", Usage: T("URL to which logs for bound applications will be streamed")}
    37  	fs["r"] = &flags.StringFlag{ShortName: "r", Usage: T("URL to which requests for bound routes will be forwarded. Scheme for this URL must be https")}
    38  	fs["t"] = &flags.StringFlag{ShortName: "t", Usage: T("User provided tags")}
    39  
    40  	return commandregistry.CommandMetadata{
    41  		Name:        "update-user-provided-service",
    42  		ShortName:   "uups",
    43  		Description: T("Update user-provided service instance"),
    44  		Usage: []string{
    45  			T(`CF_NAME update-user-provided-service SERVICE_INSTANCE [-p CREDENTIALS] [-l SYSLOG_DRAIN_URL] [-r ROUTE_SERVICE_URL] [-t TAGS]
    46  
    47     Pass comma separated credential parameter names to enable interactive mode:
    48     CF_NAME update-user-provided-service SERVICE_INSTANCE -p "comma, separated, parameter, names"
    49  
    50     Pass credential parameters as JSON to create a service non-interactively:
    51     CF_NAME update-user-provided-service SERVICE_INSTANCE -p '{"key1":"value1","key2":"value2"}'
    52  
    53     Specify a path to a file containing JSON:
    54     CF_NAME update-user-provided-service SERVICE_INSTANCE -p PATH_TO_FILE`),
    55  		},
    56  		Examples: []string{
    57  			`CF_NAME update-user-provided-service my-db-mine -p '{"username":"admin", "password":"pa55woRD"}'`,
    58  			"CF_NAME update-user-provided-service my-db-mine -p /path/to/credentials.json",
    59  			`CF_NAME update-user-provided-service my-db-mine -t "list, of, tags"`,
    60  			"CF_NAME update-user-provided-service my-drain-service -l syslog://example.com",
    61  			"CF_NAME update-user-provided-service my-route-service -r https://example.com",
    62  		},
    63  		Flags: fs,
    64  	}
    65  }
    66  
    67  func (cmd *UpdateUserProvidedService) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
    68  	if len(fc.Args()) != 1 {
    69  		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("update-user-provided-service"))
    70  		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
    71  	}
    72  
    73  	cmd.serviceInstanceReq = requirementsFactory.NewServiceInstanceRequirement(fc.Args()[0])
    74  
    75  	reqs := []requirements.Requirement{
    76  		requirementsFactory.NewLoginRequirement(),
    77  	}
    78  
    79  	if fc.IsSet("t") {
    80  		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-t'", cf.UserProvidedServiceTagsMinimumAPIVersion))
    81  	}
    82  
    83  	reqs = append(reqs, cmd.serviceInstanceReq)
    84  	return reqs, nil
    85  }
    86  
    87  func (cmd *UpdateUserProvidedService) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
    88  	cmd.ui = deps.UI
    89  	cmd.config = deps.Config
    90  	cmd.userProvidedServiceInstanceRepo = deps.RepoLocator.GetUserProvidedServiceInstanceRepository()
    91  	return cmd
    92  }
    93  
    94  func (cmd *UpdateUserProvidedService) Execute(c flags.FlagContext) error {
    95  	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()
    96  	if !serviceInstance.IsUserProvided() {
    97  		return errors.New(T("Service Instance is not user provided"))
    98  	}
    99  
   100  	drainURL := c.String("l")
   101  	credentials := strings.Trim(c.String("p"), `'"`)
   102  	routeServiceURL := c.String("r")
   103  	tags := c.String("t")
   104  	tagsList := uihelpers.ParseTags(tags)
   105  
   106  	credentialsMap := make(map[string]interface{})
   107  
   108  	if c.IsSet("p") {
   109  		jsonBytes, err := flagcontext.GetContentsFromFlagValue(credentials)
   110  		if err != nil {
   111  			return err
   112  		}
   113  
   114  		err = json.Unmarshal(jsonBytes, &credentialsMap)
   115  		if err != nil {
   116  			for _, param := range strings.Split(credentials, ",") {
   117  				param = strings.Trim(param, " ")
   118  				credentialsMap[param] = cmd.ui.Ask(param)
   119  			}
   120  		}
   121  	}
   122  
   123  	cmd.ui.Say(T("Updating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
   124  		map[string]interface{}{
   125  			"ServiceName": terminal.EntityNameColor(serviceInstance.Name),
   126  			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
   127  			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
   128  			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
   129  		}))
   130  
   131  	serviceInstance.Params = credentialsMap
   132  	serviceInstance.SysLogDrainURL = drainURL
   133  	serviceInstance.RouteServiceURL = routeServiceURL
   134  	serviceInstance.Tags = tagsList
   135  
   136  	err := cmd.userProvidedServiceInstanceRepo.Update(serviceInstance.ServiceInstanceFields)
   137  	if err != nil {
   138  		return err
   139  	}
   140  
   141  	cmd.ui.Ok()
   142  	cmd.ui.Say(T("TIP: Use '{{.CFRestageCommand}}' for any bound apps to ensure your env variable changes take effect",
   143  		map[string]interface{}{
   144  			"CFRestageCommand": terminal.CommandColor(cf.Name + " restage"),
   145  		}))
   146  
   147  	if routeServiceURL == "" && credentials == "" && drainURL == "" && tags == "" {
   148  		cmd.ui.Warn(T("No flags specified. No changes were made."))
   149  	}
   150  	return nil
   151  }