Ejemplo n.º 1
0
func (cmd *SSH) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires APP_NAME as argument") + "\n\n" + commandregistry.Commands.CommandUsage("ssh"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
	}

	if fc.IsSet("i") && fc.Int("i") < 0 {
		cmd.ui.Failed(fmt.Sprintf(T("Incorrect Usage:")+" %s\n\n%s", T("Value for flag 'app-instance-index' cannot be negative"), commandregistry.Commands.CommandUsage("ssh")))
		return nil, fmt.Errorf("Incorrect usage: app-instance-index cannot be negative")
	}

	var err error
	cmd.opts, err = options.NewSSHOptions(fc)

	if err != nil {
		cmd.ui.Failed(fmt.Sprintf(T("Incorrect Usage:")+" %s\n\n%s", err.Error(), commandregistry.Commands.CommandUsage("ssh")))
		return nil, err
	}

	cmd.appReq = requirementsFactory.NewApplicationRequirement(cmd.opts.AppName)

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedSpaceRequirement(),
		cmd.appReq,
	}

	return reqs, nil
}
Ejemplo n.º 2
0
func (cmd *UpdateUserProvidedService) Execute(c flags.FlagContext) error {
	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()
	if !serviceInstance.IsUserProvided() {
		return errors.New(T("Service Instance is not user provided"))
	}

	drainURL := c.String("l")
	credentials := strings.Trim(c.String("p"), `'"`)
	routeServiceURL := c.String("r")

	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil {
			return err
		}

		err = json.Unmarshal(jsonBytes, &credentialsMap)
		if err != nil {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask(param)
			}
		}
	}

	cmd.ui.Say(T("Updating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceName": terminal.EntityNameColor(serviceInstance.Name),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	serviceInstance.Params = credentialsMap
	serviceInstance.SysLogDrainURL = drainURL
	serviceInstance.RouteServiceURL = routeServiceURL

	err := cmd.userProvidedServiceInstanceRepo.Update(serviceInstance.ServiceInstanceFields)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	cmd.ui.Say(T("TIP: Use '{{.CFRestageCommand}}' for any bound apps to ensure your env variable changes take effect",
		map[string]interface{}{
			"CFRestageCommand": terminal.CommandColor(cf.Name + " restage"),
		}))

	if routeServiceURL == "" && credentials == "" && drainURL == "" {
		cmd.ui.Warn(T("No flags specified. No changes were made."))
	}
	return nil
}
Ejemplo n.º 3
0
func (cmd *Curl) Execute(c flags.FlagContext) error {
	path := c.Args()[0]
	headers := c.StringSlice("H")

	var method string
	var body string

	if c.IsSet("d") {
		method = "POST"

		jsonBytes, err := util.GetContentsFromOptionalFlagValue(c.String("d"))
		if err != nil {
			return err
		}
		body = string(jsonBytes)
	}

	if c.IsSet("X") {
		method = c.String("X")
	}

	reqHeader := strings.Join(headers, "\n")

	responseHeader, responseBody, apiErr := cmd.curlRepo.Request(method, path, reqHeader, body)
	if apiErr != nil {
		return errors.New(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()}))
	}

	if trace.LoggingToStdout && !cmd.pluginCall {
		return nil
	}

	if c.Bool("i") {
		cmd.ui.Say(responseHeader)
	}

	if c.String("output") != "" {
		err := cmd.writeToFile(responseBody, c.String("output"))
		if err != nil {
			return errors.New(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": err}))
		}
	} else {
		if strings.Contains(responseHeader, "application/json") {
			buffer := bytes.Buffer{}
			err := json.Indent(&buffer, []byte(responseBody), "", "   ")
			if err == nil {
				responseBody = buffer.String()
			}
		}

		cmd.ui.Say(responseBody)
	}
	return nil
}
Ejemplo n.º 4
0
func (cmd *BindRouteService) Execute(c flags.FlagContext) error {
	var port int

	host := c.String("hostname")
	domain := cmd.domainReq.GetDomain()
	path := c.String("path")
	if !strings.HasPrefix(path, "/") && len(path) > 0 {
		path = fmt.Sprintf("/%s", path)
	}

	var parameters string

	if c.IsSet("parameters") {
		jsonBytes, err := util.GetContentsFromFlagValue(c.String("parameters"))
		if err != nil {
			return err
		}
		parameters = string(jsonBytes)
	}

	route, err := cmd.routeRepo.Find(host, domain, path, port)
	if err != nil {
		return err
	}

	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()

	cmd.ui.Say(T("Binding route {{.URL}} to service instance {{.ServiceInstanceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceInstanceName": terminal.EntityNameColor(serviceInstance.Name),
			"URL":         terminal.EntityNameColor(route.URL()),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err = cmd.routeServiceBindingRepo.Bind(serviceInstance.GUID, route.GUID, serviceInstance.IsUserProvided(), parameters)
	if err != nil {
		if httpErr, ok := err.(errors.HTTPError); ok && httpErr.ErrorCode() == errors.ServiceInstanceAlreadyBoundToSameRoute {
			cmd.ui.Warn(T("Route {{.URL}} is already bound to service instance {{.ServiceInstanceName}}.",
				map[string]interface{}{
					"URL": route.URL(),
					"ServiceInstanceName": serviceInstance.Name,
				}))
		} else {
			return err
		}
	}

	cmd.ui.Ok()
	return nil
}
Ejemplo n.º 5
0
func (cmd *UnmapRoute) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 2 {
		cmd.ui.Failed(T("Incorrect Usage. Requires app_name, domain_name as arguments\n\n") + commandregistry.Commands.CommandUsage("unmap-route"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 2)
	}

	if fc.IsSet("port") && (fc.IsSet("hostname") || fc.IsSet("path")) {
		cmd.ui.Failed(T("Cannot specify port together with hostname and/or path."))
		return nil, fmt.Errorf("Cannot specify port together with hostname and/or path.")
	}

	domainName := fc.Args()[1]

	cmd.appReq = requirementsFactory.NewApplicationRequirement(fc.Args()[0])
	cmd.domainReq = requirementsFactory.NewDomainRequirement(domainName)

	var reqs []requirements.Requirement

	if fc.String("path") != "" {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--path'", cf.RoutePathMinimumAPIVersion))
	}

	if fc.IsSet("port") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--port'", cf.TCPRoutingMinimumAPIVersion))
	}

	reqs = append(reqs, []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		cmd.appReq,
		cmd.domainReq,
	}...)

	return reqs, nil
}
Ejemplo n.º 6
0
func (cmd *PurgeServiceOffering) Execute(c flags.FlagContext) error {
	serviceName := c.Args()[0]

	var offering models.ServiceOffering
	if c.IsSet("p") {
		var err error
		offering, err = cmd.serviceRepo.FindServiceOfferingByLabelAndProvider(serviceName, c.String("p"))
		if err != nil {
			if _, ok := err.(*errors.ModelNotFoundError); ok {
				cmd.ui.Warn(T("Service offering does not exist\nTIP: If you are trying to purge a v1 service offering, you must set the -p flag."))
				return nil
			}
			return err
		}
	} else {
		offerings, err := cmd.serviceRepo.FindServiceOfferingsByLabel(serviceName)
		if err != nil {
			if _, ok := err.(*errors.ModelNotFoundError); ok {
				cmd.ui.Warn(T("Service offering does not exist\nTIP: If you are trying to purge a v1 service offering, you must set the -p flag."))
				return nil
			}
			return err
		}
		offering = offerings[0]
	}

	confirmed := c.Bool("f")
	if !confirmed {
		cmd.ui.Warn(scaryWarningMessage())
		confirmed = cmd.ui.Confirm(T("Really purge service offering {{.ServiceName}} from Cloud Foundry?",
			map[string]interface{}{"ServiceName": serviceName},
		))
	}

	if !confirmed {
		return nil
	}

	cmd.ui.Say(T("Purging service {{.ServiceName}}...", map[string]interface{}{"ServiceName": serviceName}))

	err := cmd.serviceRepo.PurgeServiceOffering(offering)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	return nil
}
Ejemplo n.º 7
0
func (cmd *Files) Execute(c flags.FlagContext) error {
	app := cmd.appReq.GetApplication()

	var instance int
	if c.IsSet("i") {
		instance = c.Int("i")
		if instance < 0 {
			return errors.New(T("Invalid instance: {{.Instance}}\nInstance must be a positive integer",
				map[string]interface{}{
					"Instance": instance,
				}))
		}
		if instance >= app.InstanceCount {
			return errors.New(T("Invalid instance: {{.Instance}}\nInstance must be less than {{.InstanceCount}}",
				map[string]interface{}{
					"Instance":      instance,
					"InstanceCount": app.InstanceCount,
				}))
		}
	}

	cmd.ui.Say(T("Getting files for app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
		map[string]interface{}{
			"AppName":   terminal.EntityNameColor(app.Name),
			"OrgName":   terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"Username":  terminal.EntityNameColor(cmd.config.Username())}))

	path := "/"
	if len(c.Args()) > 1 {
		path = c.Args()[1]
	}

	list, err := cmd.appFilesRepo.ListFiles(app.GUID, instance, path)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	cmd.ui.Say("")

	if list == "" {
		cmd.ui.Say("Empty file or folder")
	} else {
		cmd.ui.Say("%s", list)
	}
	return nil
}
Ejemplo n.º 8
0
func (cmd *PurgeServiceOffering) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("purge-service-offering"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("p") {
		reqs = append(reqs, requirementsFactory.NewMaxAPIVersionRequirement("Option '-p'", cf.ServiceAuthTokenMaximumAPIVersion))
	}

	return reqs, nil
}
Ejemplo n.º 9
0
func (cmd *UpdateSpaceQuota) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("update-space-quota"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedOrgRequirement(),
	}

	if fc.IsSet("a") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-a'", cf.SpaceAppInstanceLimitMinimumAPIVersion))
	}

	return reqs, nil
}
Ejemplo n.º 10
0
func (cmd *UpdateService) Execute(c flags.FlagContext) error {
	planName := c.String("p")
	params := c.String("c")

	tagsSet := c.IsSet("t")
	tagsList := c.String("t")

	if planName == "" && params == "" && tagsSet == false {
		cmd.ui.Ok()
		cmd.ui.Say(T("No changes were made"))
		return nil
	}

	serviceInstanceName := c.Args()[0]
	serviceInstance, err := cmd.serviceRepo.FindInstanceByName(serviceInstanceName)
	if err != nil {
		return err
	}

	paramsMap, err := json.ParseJSONFromFileOrString(params)
	if err != nil {
		return errors.New(T("Invalid configuration provided for -c flag. Please provide a valid JSON object or path to a file containing a valid JSON object."))
	}

	tags := uihelpers.ParseTags(tagsList)

	var plan models.ServicePlanFields
	if planName != "" {
		plan, err = cmd.findPlan(serviceInstance, planName)
		if err != nil {
			return err
		}
	}

	cmd.printUpdatingServiceInstanceMessage(serviceInstanceName)

	err = cmd.serviceRepo.UpdateServiceInstance(serviceInstance.GUID, plan.GUID, paramsMap, tags)
	if err != nil {
		return err
	}
	err = printSuccessMessageForServiceInstance(serviceInstanceName, cmd.serviceRepo, cmd.ui)
	if err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 11
0
func (cmd *CreateUserProvidedService) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("create-user-provided-service"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedSpaceRequirement(),
	}

	if fc.IsSet("r") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-r'", cf.MultipleAppPortsMinimumAPIVersion))
	}

	return reqs, nil
}
Ejemplo n.º 12
0
func (cmd *Target) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	usageReq := requirements.NewUsageRequirement(commandregistry.CLICommandUsagePresenter(cmd),
		T("No argument required"),
		func() bool {
			return len(fc.Args()) != 0
		},
	)

	reqs := []requirements.Requirement{
		usageReq,
		requirementsFactory.NewAPIEndpointRequirement(),
	}

	if fc.IsSet("o") || fc.IsSet("s") {
		reqs = append(reqs, requirementsFactory.NewLoginRequirement())
	}

	return reqs, nil
}
Ejemplo n.º 13
0
func (cmd *CreateServiceBroker) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 4 {
		cmd.ui.Failed(T("Incorrect Usage. Requires SERVICE_BROKER, USERNAME, PASSWORD, URL as arguments\n\n") + commandregistry.Commands.CommandUsage("create-service-broker"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 4)
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("space-scoped") {
		reqs = append(
			reqs,
			requirementsFactory.NewTargetedSpaceRequirement(),
			requirementsFactory.NewMinAPIVersionRequirement("--space-scoped", cf.SpaceScopedMaximumAPIVersion),
		)
	}

	return reqs, nil
}
Ejemplo n.º 14
0
func (cmd *CreateQuota) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("create-quota"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("a") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-a'", cf.OrgAppInstanceLimitMinimumAPIVersion))
	}

	if fc.IsSet("reserved-route-ports") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--reserved-route-ports'", cf.ReservedRoutePortsMinimumAPIVersion))
	}

	return reqs, nil
}
Ejemplo n.º 15
0
func NewSSHOptions(fc flags.FlagContext) (*SSHOptions, error) {
	sshOptions := &SSHOptions{}

	sshOptions.AppName = fc.Args()[0]
	sshOptions.Index = uint(fc.Int("i"))
	sshOptions.SkipHostValidation = fc.Bool("k")
	sshOptions.SkipRemoteExecution = fc.Bool("N")
	sshOptions.Command = fc.StringSlice("c")

	if fc.IsSet("L") {
		for _, arg := range fc.StringSlice("L") {
			forwardSpec, err := sshOptions.parseLocalForwardingSpec(arg)
			if err != nil {
				return sshOptions, err
			}
			sshOptions.ForwardSpecs = append(sshOptions.ForwardSpecs, *forwardSpec)
		}
	}

	if fc.IsSet("t") && fc.Bool("t") {
		sshOptions.TerminalRequest = RequestTTYYes
	}

	if fc.IsSet("tt") && fc.Bool("tt") {
		sshOptions.TerminalRequest = RequestTTYForce
	}

	if fc.Bool("T") {
		sshOptions.TerminalRequest = RequestTTYNo
	}

	return sshOptions, nil
}
Ejemplo n.º 16
0
func (cmd *CreateUserProvidedService) Execute(c flags.FlagContext) error {
	name := c.Args()[0]
	drainURL := c.String("l")
	routeServiceURL := c.String("r")
	credentials := strings.Trim(c.String("p"), `"'`)
	credentialsMap := make(map[string]interface{})

	if c.IsSet("p") {
		jsonBytes, err := util.GetContentsFromFlagValue(credentials)
		if err != nil {
			return err
		}

		err = json.Unmarshal(jsonBytes, &credentialsMap)
		if err != nil {
			for _, param := range strings.Split(credentials, ",") {
				param = strings.Trim(param, " ")
				credentialsMap[param] = cmd.ui.Ask(param)
			}
		}
	}

	cmd.ui.Say(T("Creating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceName": terminal.EntityNameColor(name),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err := cmd.userProvidedServiceInstanceRepo.Create(name, drainURL, routeServiceURL, credentialsMap)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	return nil
}
Ejemplo n.º 17
0
func (cmd *Push) Execute(c flags.FlagContext) error {
	appsFromManifest, err := cmd.getAppParamsFromManifest(c)
	if err != nil {
		return err
	}

	errs := cmd.actor.ValidateAppParams(appsFromManifest)
	if len(errs) > 0 {
		errStr := T("Invalid application configuration") + ":"

		for _, e := range errs {
			errStr = fmt.Sprintf("%s\n%s", errStr, e.Error())
		}

		return fmt.Errorf("%s", errStr)
	}

	appFromContext, err := cmd.getAppParamsFromContext(c)
	if err != nil {
		return err
	}

	err = cmd.ValidateContextAndAppParams(appsFromManifest, appFromContext)
	if err != nil {
		return err
	}

	appSet, err := cmd.createAppSetFromContextAndManifest(appFromContext, appsFromManifest)
	if err != nil {
		return err
	}

	_, err = cmd.authRepo.RefreshAuthToken()
	if err != nil {
		return err
	}

	for _, appParams := range appSet {
		if appParams.Name == nil {
			return errors.New(T("Error: No name found for app"))
		}

		err = cmd.fetchStackGUID(&appParams)
		if err != nil {
			return err
		}

		if c.IsSet("docker-image") {
			diego := true
			appParams.Diego = &diego
		}

		var app, existingApp models.Application
		existingApp, err = cmd.appRepo.Read(*appParams.Name)
		switch err.(type) {
		case nil:
			cmd.ui.Say(T("Updating app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
				map[string]interface{}{
					"AppName":   terminal.EntityNameColor(existingApp.Name),
					"OrgName":   terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
					"SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name),
					"Username":  terminal.EntityNameColor(cmd.config.Username())}))

			if appParams.EnvironmentVars != nil {
				for key, val := range existingApp.EnvironmentVars {
					if _, ok := (*appParams.EnvironmentVars)[key]; !ok {
						(*appParams.EnvironmentVars)[key] = val
					}
				}
			}

			app, err = cmd.appRepo.Update(existingApp.GUID, appParams)
			if err != nil {
				return err
			}
		case *errors.ModelNotFoundError:
			spaceGUID := cmd.config.SpaceFields().GUID
			appParams.SpaceGUID = &spaceGUID

			cmd.ui.Say(T("Creating app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
				map[string]interface{}{
					"AppName":   terminal.EntityNameColor(*appParams.Name),
					"OrgName":   terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
					"SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name),
					"Username":  terminal.EntityNameColor(cmd.config.Username())}))

			app, err = cmd.appRepo.Create(appParams)
			if err != nil {
				return err
			}
		default:
			return err
		}

		cmd.ui.Ok()
		cmd.ui.Say("")

		err = cmd.updateRoutes(app, appParams, appFromContext)
		if err != nil {
			return err
		}

		if c.String("docker-image") == "" {
			err = cmd.actor.ProcessPath(*appParams.Path, cmd.processPathCallback(*appParams.Path, app))
			if err != nil {
				return errors.New(
					T("Error processing app files: {{.Error}}",
						map[string]interface{}{
							"Error": err.Error(),
						}),
				)
			}
		}

		if appParams.ServicesToBind != nil {
			err = cmd.bindAppToServices(appParams.ServicesToBind, app)
			if err != nil {
				return err
			}
		}

		err = cmd.restart(app, appParams, c)
		if err != nil {
			return errors.New(
				T("Error restarting application: {{.Error}}",
					map[string]interface{}{
						"Error": err.Error(),
					}),
			)
		}
	}
	return nil
}
Ejemplo n.º 18
0
func (cmd *Push) getAppParamsFromContext(c flags.FlagContext) (models.AppParams, error) {
	noHostBool := c.Bool("no-hostname")
	appParams := models.AppParams{
		NoRoute:        c.Bool("no-route"),
		UseRandomRoute: c.Bool("random-route"),
		NoHostname:     &noHostBool,
	}

	if len(c.Args()) > 0 {
		appParams.Name = &c.Args()[0]
	}

	if c.String("n") != "" {
		appParams.Hosts = []string{c.String("n")}
	}

	if c.String("route-path") != "" {
		routePath := c.String("route-path")
		appParams.RoutePath = &routePath
	}

	if c.String("app-ports") != "" {
		appPortStrings := strings.Split(c.String("app-ports"), ",")
		appPorts := make([]int, len(appPortStrings))

		for i, s := range appPortStrings {
			p, err := strconv.Atoi(s)
			if err != nil {
				return models.AppParams{}, errors.New(T("Invalid app port: {{.AppPort}}\nApp port must be a number", map[string]interface{}{
					"AppPort": s,
				}))
			}
			appPorts[i] = p
		}

		appParams.AppPorts = &appPorts
	}

	if c.String("b") != "" {
		buildpack := c.String("b")
		if buildpack == "null" || buildpack == "default" {
			buildpack = ""
		}
		appParams.BuildpackURL = &buildpack
	}

	if c.String("c") != "" {
		command := c.String("c")
		if command == "null" || command == "default" {
			command = ""
		}
		appParams.Command = &command
	}

	if c.String("d") != "" {
		appParams.Domains = []string{c.String("d")}
	}

	if c.IsSet("i") {
		instances := c.Int("i")
		if instances < 1 {
			return models.AppParams{}, errors.New(T("Invalid instance count: {{.InstancesCount}}\nInstance count must be a positive integer",
				map[string]interface{}{"InstancesCount": instances}))
		}
		appParams.InstanceCount = &instances
	}

	if c.String("k") != "" {
		diskQuota, err := formatters.ToMegabytes(c.String("k"))
		if err != nil {
			return models.AppParams{}, errors.New(T("Invalid disk quota: {{.DiskQuota}}\n{{.Err}}",
				map[string]interface{}{"DiskQuota": c.String("k"), "Err": err.Error()}))
		}
		appParams.DiskQuota = &diskQuota
	}

	if c.String("m") != "" {
		memory, err := formatters.ToMegabytes(c.String("m"))
		if err != nil {
			return models.AppParams{}, errors.New(T("Invalid memory limit: {{.MemLimit}}\n{{.Err}}",
				map[string]interface{}{"MemLimit": c.String("m"), "Err": err.Error()}))
		}
		appParams.Memory = &memory
	}

	if c.String("docker-image") != "" {
		dockerImage := c.String("docker-image")
		appParams.DockerImage = &dockerImage
	}

	if c.String("p") != "" {
		path := c.String("p")
		appParams.Path = &path
	}

	if c.String("s") != "" {
		stackName := c.String("s")
		appParams.StackName = &stackName
	}

	if c.String("t") != "" {
		timeout, err := strconv.Atoi(c.String("t"))
		if err != nil {
			return models.AppParams{}, fmt.Errorf("Error: %s", fmt.Errorf(T("Invalid timeout param: {{.Timeout}}\n{{.Err}}",
				map[string]interface{}{"Timeout": c.String("t"), "Err": err.Error()})))
		}

		appParams.HealthCheckTimeout = &timeout
	}

	if healthCheckType := c.String("u"); healthCheckType != "" {
		if healthCheckType != "port" && healthCheckType != "none" {
			return models.AppParams{}, fmt.Errorf("Error: %s", fmt.Errorf(T("Invalid health-check-type param: {{.healthCheckType}}",
				map[string]interface{}{"healthCheckType": healthCheckType})))
		}

		appParams.HealthCheckType = &healthCheckType
	}

	return appParams, nil
}
Ejemplo n.º 19
0
)

var _ = Describe("Flag Constructors", func() {

	var (
		fc flags.FlagContext
	)

	BeforeEach(func() {
		fc = flags.New()
	})

	Describe("NewStringFlag()", func() {
		It("init the flag context with a new string flagset", func() {
			fc.Parse("-s", "test")
			Expect(fc.IsSet("s")).To(BeFalse())
			Expect(fc.String("s")).To(Equal(""))

			fc.NewStringFlag("s", "s2", "setting new string flag")
			fc.Parse("-s", "test2")
			Expect(fc.IsSet("s")).To(BeTrue())
			Expect(fc.IsSet("s2")).To(BeTrue())
			Expect(fc.String("s")).To(Equal("test2"))
			Expect(fc.String("s2")).To(Equal("test2"))
		})
	})

	Describe("NewStringFlagWithDefault()", func() {
		It("init the flag context with a new string flagset with default value", func() {
			fc.Parse("-s", "test")
			Expect(fc.IsSet("s")).To(BeFalse())
Ejemplo n.º 20
0
func (cmd *ConfigCommands) Execute(context flags.FlagContext) error {
	if !context.IsSet("trace") && !context.IsSet("async-timeout") && !context.IsSet("color") && !context.IsSet("locale") {
		return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("config"))
	}

	if context.IsSet("async-timeout") {
		asyncTimeout := context.Int("async-timeout")
		if asyncTimeout < 0 {
			return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("config"))
		}

		cmd.config.SetAsyncTimeout(uint(asyncTimeout))
	}

	if context.IsSet("trace") {
		cmd.config.SetTrace(context.String("trace"))
	}

	if context.IsSet("color") {
		value := context.String("color")
		switch value {
		case "true":
			cmd.config.SetColorEnabled("true")
		case "false":
			cmd.config.SetColorEnabled("false")
		default:
			return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("config"))
		}
	}

	if context.IsSet("locale") {
		locale := context.String("locale")

		if locale == "CLEAR" {
			cmd.config.SetLocale("")
			return nil
		}

		if IsSupportedLocale(locale) {
			cmd.config.SetLocale(locale)
			return nil
		}

		unsupportedLocaleMessage := T("Could not find locale '{{.UnsupportedLocale}}'. The known locales are:\n", map[string]interface{}{
			"UnsupportedLocale": locale,
		})
		supportedLocales := SupportedLocales()
		sort.Strings(supportedLocales)
		for i := range supportedLocales {
			unsupportedLocaleMessage = unsupportedLocaleMessage + "\n" + supportedLocales[i]
		}

		return errors.New(unsupportedLocaleMessage)
	}
	return nil
}
Ejemplo n.º 21
0
func (cmd *UpdateSpaceQuota) Execute(c flags.FlagContext) error {
	name := c.Args()[0]

	spaceQuota, err := cmd.spaceQuotaRepo.FindByName(name)
	if err != nil {
		return err
	}

	allowPaidServices := c.Bool("allow-paid-service-plans")
	disallowPaidServices := c.Bool("disallow-paid-service-plans")
	if allowPaidServices && disallowPaidServices {
		return errors.New(T("Please choose either allow or disallow. Both flags are not permitted to be passed in the same command."))
	}

	if allowPaidServices {
		spaceQuota.NonBasicServicesAllowed = true
	}

	if disallowPaidServices {
		spaceQuota.NonBasicServicesAllowed = false
	}

	if c.String("i") != "" {
		var memory int64
		var formatError error

		memFlag := c.String("i")

		if memFlag == "-1" {
			memory = -1
		} else {
			memory, formatError = formatters.ToMegabytes(memFlag)
			if formatError != nil {
				return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("update-space-quota"))
			}
		}

		spaceQuota.InstanceMemoryLimit = memory
	}

	if c.String("m") != "" {
		memory, formatError := formatters.ToMegabytes(c.String("m"))

		if formatError != nil {
			return errors.New(T("Incorrect Usage") + "\n\n" + commandregistry.Commands.CommandUsage("update-space-quota"))
		}

		spaceQuota.MemoryLimit = memory
	}

	if c.String("n") != "" {
		spaceQuota.Name = c.String("n")
	}

	if c.IsSet("s") {
		spaceQuota.ServicesLimit = c.Int("s")
	}

	if c.IsSet("r") {
		spaceQuota.RoutesLimit = c.Int("r")
	}

	if c.IsSet("a") {
		spaceQuota.AppInstanceLimit = c.Int("a")
	}

	if c.IsSet("reserved-route-ports") {
		spaceQuota.ReservedRoutePortsLimit = json.Number(strconv.Itoa(c.Int("reserved-route-ports")))
	}

	cmd.ui.Say(T("Updating space quota {{.Quota}} as {{.Username}}...",
		map[string]interface{}{
			"Quota":    terminal.EntityNameColor(name),
			"Username": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err = cmd.spaceQuotaRepo.Update(spaceQuota)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	return nil
}
Ejemplo n.º 22
0
func (cmd *Scale) Execute(c flags.FlagContext) error {
	currentApp := cmd.appReq.GetApplication()
	if !anyFlagsSet(c) {
		cmd.ui.Say(T("Showing current scale of app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
			map[string]interface{}{
				"AppName":     terminal.EntityNameColor(currentApp.Name),
				"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
				"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
				"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
			}))
		cmd.ui.Ok()
		cmd.ui.Say("")

		cmd.ui.Say("%s %s", terminal.HeaderColor(T("memory:")), formatters.ByteSize(currentApp.Memory*bytesInAMegabyte))
		cmd.ui.Say("%s %s", terminal.HeaderColor(T("disk:")), formatters.ByteSize(currentApp.DiskQuota*bytesInAMegabyte))
		cmd.ui.Say("%s %d", terminal.HeaderColor(T("instances:")), currentApp.InstanceCount)

		return nil
	}

	params := models.AppParams{}
	shouldRestart := false

	if c.String("m") != "" {
		memory, err := formatters.ToMegabytes(c.String("m"))
		if err != nil {
			return errors.New(T("Invalid memory limit: {{.Memory}}\n{{.ErrorDescription}}",
				map[string]interface{}{
					"Memory":           c.String("m"),
					"ErrorDescription": err,
				}))
		}
		params.Memory = &memory
		shouldRestart = true
	}

	if c.String("k") != "" {
		diskQuota, err := formatters.ToMegabytes(c.String("k"))
		if err != nil {
			return errors.New(T("Invalid disk quota: {{.DiskQuota}}\n{{.ErrorDescription}}",
				map[string]interface{}{
					"DiskQuota":        c.String("k"),
					"ErrorDescription": err,
				}))
		}
		params.DiskQuota = &diskQuota
		shouldRestart = true
	}

	if c.IsSet("i") {
		instances := c.Int("i")
		params.InstanceCount = &instances
	}

	if shouldRestart && !cmd.confirmRestart(c, currentApp.Name) {
		return nil
	}

	cmd.ui.Say(T("Scaling app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"AppName":     terminal.EntityNameColor(currentApp.Name),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	updatedApp, err := cmd.appRepo.Update(currentApp.GUID, params)
	if err != nil {
		return err
	}

	cmd.ui.Ok()

	if shouldRestart {
		err = cmd.restarter.ApplicationRestart(updatedApp, cmd.config.OrganizationFields().Name, cmd.config.SpaceFields().Name)
		if err != nil {
			return err
		}
	}
	return nil
}
Ejemplo n.º 23
0
func anyFlagsSet(context flags.FlagContext) bool {
	return context.IsSet("m") || context.IsSet("k") || context.IsSet("i")
}
Ejemplo n.º 24
0
func (cmd *CreateRoute) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 2 {
		cmd.ui.Failed(T("Incorrect Usage. Requires SPACE and DOMAIN as arguments\n\n") + commandregistry.Commands.CommandUsage("create-route"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 2)
	}

	if fc.IsSet("port") && (fc.IsSet("hostname") || fc.IsSet("path")) {
		cmd.ui.Failed(T("Cannot specify port together with hostname and/or path."))
		return nil, fmt.Errorf("Cannot specify port together with hostname and/or path.")
	}

	if fc.IsSet("random-port") && (fc.IsSet("port") || fc.IsSet("hostname") || fc.IsSet("path")) {
		cmd.ui.Failed(T("Cannot specify random-port together with port, hostname and/or path."))
		return nil, fmt.Errorf("Cannot specify random-port together with port, hostname and/or path.")
	}

	domainName := fc.Args()[1]

	cmd.spaceReq = requirementsFactory.NewSpaceRequirement(fc.Args()[0])
	cmd.domainReq = requirementsFactory.NewDomainRequirement(domainName)

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedOrgRequirement(),
		cmd.spaceReq,
		cmd.domainReq,
	}

	if fc.IsSet("path") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--path'", cf.RoutePathMinimumAPIVersion))
	}

	if fc.IsSet("port") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--port'", cf.TCPRoutingMinimumAPIVersion))
	}

	if fc.IsSet("random-port") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--random-port'", cf.TCPRoutingMinimumAPIVersion))
	}

	return reqs, nil
}
Ejemplo n.º 25
0
				fCtx = flags.NewFlagContext(cmdFlagMap)
			})

			It("accepts flags with either single '-' or double '-' ", func() {
				err := fCtx.Parse("--name", "blue")
				Expect(err).NotTo(HaveOccurred())

				err = fCtx.Parse("-name", "")
				Expect(err).NotTo(HaveOccurred())
			})

			It("sets a flag with it's full name", func() {
				err := fCtx.Parse("-name", "blue")
				Expect(err).NotTo(HaveOccurred())
				Expect(fCtx.IsSet("name")).To(BeTrue())
				Expect(fCtx.IsSet("n")).To(BeTrue())
				Expect(fCtx.String("name")).To(Equal("blue"))
				Expect(fCtx.String("n")).To(Equal("blue"))
			})

			It("sets a flag with it's short name", func() {
				err := fCtx.Parse("-n", "red")
				Expect(err).NotTo(HaveOccurred())
				Expect(fCtx.IsSet("name")).To(BeTrue())
				Expect(fCtx.IsSet("n")).To(BeTrue())
				Expect(fCtx.String("name")).To(Equal("red"))
				Expect(fCtx.String("n")).To(Equal("red"))
			})

			It("checks if a flag is defined in the FlagContext", func() {
Ejemplo n.º 26
0
func (cmd *UpdateBuildpack) Execute(c flags.FlagContext) error {
	buildpack := cmd.buildpackReq.GetBuildpack()

	cmd.ui.Say(T("Updating buildpack {{.BuildpackName}}...", map[string]interface{}{"BuildpackName": terminal.EntityNameColor(buildpack.Name)}))

	updateBuildpack := false

	if c.IsSet("i") {
		position := c.Int("i")

		buildpack.Position = &position
		updateBuildpack = true
	}

	enabled := c.Bool("enable")
	disabled := c.Bool("disable")
	if enabled && disabled {
		return errors.New(T("Cannot specify both {{.Enabled}} and {{.Disabled}}.", map[string]interface{}{
			"Enabled":  "enabled",
			"Disabled": "disabled",
		}))
	}

	if enabled {
		buildpack.Enabled = &enabled
		updateBuildpack = true
	}
	if disabled {
		disabled = false
		buildpack.Enabled = &disabled
		updateBuildpack = true
	}

	lock := c.Bool("lock")
	unlock := c.Bool("unlock")
	if lock && unlock {
		return errors.New(T("Cannot specify both lock and unlock options."))
	}

	path := c.String("p")

	if path != "" && (lock || unlock) {
		return errors.New(T("Cannot specify buildpack bits and lock/unlock."))
	}

	if lock {
		buildpack.Locked = &lock
		updateBuildpack = true
	}
	if unlock {
		unlock = false
		buildpack.Locked = &unlock
		updateBuildpack = true
	}
	var (
		buildpackFile     *os.File
		buildpackFileName string
		err               error
	)
	if path != "" {
		buildpackFile, buildpackFileName, err = cmd.buildpackBitsRepo.CreateBuildpackZipFile(path)
		if err != nil {
			cmd.ui.Warn(T("Failed to create a local temporary zip file for the buildpack"))
			return err
		}
	}

	if updateBuildpack {
		newBuildpack, err := cmd.buildpackRepo.Update(buildpack)
		if err != nil {
			return errors.New(T("Error updating buildpack {{.Name}}\n{{.Error}}", map[string]interface{}{
				"Name":  terminal.EntityNameColor(buildpack.Name),
				"Error": err.Error(),
			}))
		}
		buildpack = newBuildpack
	}

	if path != "" {
		err := cmd.buildpackBitsRepo.UploadBuildpack(buildpack, buildpackFile, buildpackFileName)
		if err != nil {
			return errors.New(T("Error uploading buildpack {{.Name}}\n{{.Error}}", map[string]interface{}{
				"Name":  terminal.EntityNameColor(buildpack.Name),
				"Error": err.Error(),
			}))
		}
	}
	cmd.ui.Ok()
	return nil
}
Ejemplo n.º 27
0
func (cmd *CreateSpaceQuota) Execute(context flags.FlagContext) error {
	name := context.Args()[0]
	org := cmd.config.OrganizationFields()

	cmd.ui.Say(T("Creating space quota {{.QuotaName}} for org {{.OrgName}} as {{.Username}}...", map[string]interface{}{
		"QuotaName": terminal.EntityNameColor(name),
		"OrgName":   terminal.EntityNameColor(org.Name),
		"Username":  terminal.EntityNameColor(cmd.config.Username()),
	}))

	quota := models.SpaceQuota{
		Name:    name,
		OrgGUID: org.GUID,
	}

	memoryLimit := context.String("m")
	if memoryLimit != "" {
		parsedMemory, errr := formatters.ToMegabytes(memoryLimit)
		if errr != nil {
			return errors.New(T("Invalid memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": memoryLimit, "Err": errr}))
		}

		quota.MemoryLimit = parsedMemory
	}

	instanceMemoryLimit := context.String("i")
	var parsedMemory int64
	var err error
	if instanceMemoryLimit == "-1" || instanceMemoryLimit == "" {
		parsedMemory = -1
	} else {
		parsedMemory, err = formatters.ToMegabytes(instanceMemoryLimit)
		if err != nil {
			return errors.New(T("Invalid instance memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": instanceMemoryLimit, "Err": err}))
		}
	}

	quota.InstanceMemoryLimit = parsedMemory

	if context.IsSet("r") {
		quota.RoutesLimit = context.Int("r")
	}

	if context.IsSet("s") {
		quota.ServicesLimit = context.Int("s")
	}

	if context.IsSet("allow-paid-service-plans") {
		quota.NonBasicServicesAllowed = true
	}

	if context.IsSet("a") {
		quota.AppInstanceLimit = context.Int("a")
	} else {
		quota.AppInstanceLimit = resources.UnlimitedAppInstances
	}

	if context.IsSet("reserved-route-ports") {
		quota.ReservedRoutePortsLimit = json.Number(strconv.Itoa(context.Int("reserved-route-ports")))
	}

	err = cmd.quotaRepo.Create(quota)

	httpErr, ok := err.(errors.HTTPError)
	if ok && httpErr.ErrorCode() == errors.QuotaDefinitionNameTaken {
		cmd.ui.Ok()
		cmd.ui.Warn(T("Space Quota Definition {{.QuotaName}} already exists", map[string]interface{}{"QuotaName": quota.Name}))
		return nil
	}

	if err != nil {
		return err
	}

	cmd.ui.Ok()
	return nil
}
Ejemplo n.º 28
0
func (cmd *MapRoute) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 2 {
		cmd.ui.Failed(T("Incorrect Usage. Requires APP_NAME and DOMAIN as arguments\n\n") + commandregistry.Commands.CommandUsage("map-route"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 2)
	}

	if fc.IsSet("port") && (fc.IsSet("hostname") || fc.IsSet("path")) {
		cmd.ui.Failed(T("Cannot specify port together with hostname and/or path."))
		return nil, fmt.Errorf("Cannot specify port together with hostname and/or path.")
	}

	if fc.IsSet("random-port") && (fc.IsSet("port") || fc.IsSet("hostname") || fc.IsSet("path")) {
		cmd.ui.Failed(T("Cannot specify random-port together with port, hostname and/or path."))
		return nil, fmt.Errorf("Cannot specify random-port together with port, hostname and/or path.")
	}

	appName := fc.Args()[0]
	domainName := fc.Args()[1]

	requirement := requirementsFactory.NewApplicationRequirement(appName)
	cmd.appReq = requirement

	cmd.domainReq = requirementsFactory.NewDomainRequirement(domainName)

	var reqs []requirements.Requirement

	if fc.String("path") != "" {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--path'", cf.RoutePathMinimumAPIVersion))
	}

	var flag string
	switch {
	case fc.IsSet("port"):
		flag = "port"
	case fc.IsSet("random-port"):
		flag = "random-port"
	}

	if flag != "" {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement(fmt.Sprintf("Option '--%s'", flag), cf.TCPRoutingMinimumAPIVersion))
		reqs = append(reqs, requirementsFactory.NewDiegoApplicationRequirement(appName))
	}

	reqs = append(reqs, []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		cmd.appReq,
		cmd.domainReq,
	}...)

	return reqs, nil
}