Exemplo n.º 1
0
func (cmd *PurgeServiceInstance) Execute(c flags.FlagContext) {
	instanceName := c.Args()[0]

	instance, err := cmd.serviceRepo.FindInstanceByName(instanceName)
	if err != nil {
		if _, ok := err.(*errors.ModelNotFoundError); ok {
			cmd.ui.Warn(T("Service instance {{.InstanceName}} not found", map[string]interface{}{"InstanceName": instanceName}))
			return
		}

		cmd.ui.Failed(err.Error())
	}

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

		if !confirmed {
			return
		}
	}

	cmd.ui.Say(T("Purging service {{.InstanceName}}...", map[string]interface{}{"InstanceName": instanceName}))
	err = cmd.serviceRepo.PurgeServiceInstance(instance)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
Exemplo n.º 2
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 = REQUEST_TTY_YES
	}

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

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

	return sshOptions, nil
}
func (cmd *OrgUsers) printer(c flags.FlagContext) userprint.UserPrinter {
	var roles []string
	if c.Bool("a") {
		roles = []string{models.ORG_USER}
	} else {
		roles = []string{models.ORG_MANAGER, models.BILLING_MANAGER, models.ORG_AUDITOR}
	}

	if cmd.pluginCall {
		return userprint.NewOrgUsersPluginPrinter(
			cmd.pluginModel,
			cmd.userLister(),
			roles,
		)
	}
	return &userprint.OrgUsersUiPrinter{
		Ui:         cmd.ui,
		UserLister: cmd.userLister(),
		Roles:      roles,
		RoleDisplayNames: map[string]string{
			models.ORG_USER:        T("USERS"),
			models.ORG_MANAGER:     T("ORG MANAGER"),
			models.BILLING_MANAGER: T("BILLING MANAGER"),
			models.ORG_AUDITOR:     T("ORG AUDITOR"),
		},
	}
}
Exemplo n.º 4
0
func (cmd *DeleteOrphanedRoutes) Execute(c flags.FlagContext) {
	force := c.Bool("f")
	if !force {
		response := cmd.ui.Confirm(T("Really delete orphaned routes?{{.Prompt}}",
			map[string]interface{}{"Prompt": terminal.PromptColor(">")}))

		if !response {
			return
		}
	}

	cmd.ui.Say(T("Getting routes as {{.Username}} ...\n",
		map[string]interface{}{"Username": terminal.EntityNameColor(cmd.config.Username())}))

	apiErr := cmd.routeRepo.ListRoutes(func(route models.Route) bool {

		if len(route.Apps) == 0 {
			cmd.ui.Say(T("Deleting route {{.Route}}...",
				map[string]interface{}{"Route": terminal.EntityNameColor(route.Host + "." + route.Domain.Name)}))
			apiErr := cmd.routeRepo.Delete(route.Guid)
			if apiErr != nil {
				cmd.ui.Failed(apiErr.Error())
				return false
			}
		}
		return true
	})

	if apiErr != nil {
		cmd.ui.Failed(T("Failed fetching routes.\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()}))
		return
	}
	cmd.ui.Ok()
}
Exemplo n.º 5
0
Arquivo: api.go Projeto: yingkitw/cli
func (cmd Api) Execute(c flags.FlagContext) {
	if c.Bool("unset") {
		cmd.ui.Say(T("Unsetting api endpoint..."))
		cmd.config.SetAPIEndpoint("")

		cmd.ui.Ok()
		cmd.ui.Say(T("\nNo api endpoint set."))

	} else if len(c.Args()) == 0 {
		if cmd.config.APIEndpoint() == "" {
			cmd.ui.Say(fmt.Sprintf(T("No api endpoint set. Use '{{.Name}}' to set an endpoint",
				map[string]interface{}{"Name": terminal.CommandColor(cf.Name + " api")})))
		} else {
			cmd.ui.Say(T("API endpoint: {{.APIEndpoint}} (API version: {{.APIVersion}})",
				map[string]interface{}{"APIEndpoint": terminal.EntityNameColor(cmd.config.APIEndpoint()),
					"APIVersion": terminal.EntityNameColor(cmd.config.APIVersion())}))
		}
	} else {
		endpoint := c.Args()[0]

		cmd.ui.Say(T("Setting api endpoint to {{.Endpoint}}...",
			map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)}))
		cmd.setAPIEndpoint(endpoint, c.Bool("skip-ssl-validation"), cmd.MetaData().Name)
		cmd.ui.Ok()

		cmd.ui.Say("")
		cmd.ui.ShowConfiguration(cmd.config)
	}
}
func (cmd *DeleteServiceAuthTokenFields) Execute(c flags.FlagContext) {
	tokenLabel := c.Args()[0]
	tokenProvider := c.Args()[1]

	if c.Bool("f") == false {
		if !cmd.ui.ConfirmDelete(T("service auth token"), fmt.Sprintf("%s %s", tokenLabel, tokenProvider)) {
			return
		}
	}

	cmd.ui.Say(T("Deleting service auth token as {{.CurrentUser}}",
		map[string]interface{}{
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))
	token, apiErr := cmd.authTokenRepo.FindByLabelAndProvider(tokenLabel, tokenProvider)

	switch apiErr.(type) {
	case nil:
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Service Auth Token {{.Label}} {{.Provider}} does not exist.", map[string]interface{}{"Label": tokenLabel, "Provider": tokenProvider}))
		return
	default:
		cmd.ui.Failed(apiErr.Error())
	}

	apiErr = cmd.authTokenRepo.Delete(token)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
}
func (cmd *CreateServiceBroker) Execute(c flags.FlagContext) {
	name := c.Args()[0]
	username := c.Args()[1]
	password := c.Args()[2]
	url := c.Args()[3]

	var err error
	if c.Bool("space-scoped") {
		cmd.ui.Say(T("Creating service broker {{.Name}} in org {{.Org}} / space {{.Space}} as {{.Username}}...",
			map[string]interface{}{
				"Name":     terminal.EntityNameColor(name),
				"Org":      terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
				"Space":    terminal.EntityNameColor(cmd.config.SpaceFields().Name),
				"Username": terminal.EntityNameColor(cmd.config.Username())}))
		err = cmd.serviceBrokerRepo.Create(name, url, username, password, cmd.config.SpaceFields().Guid)
	} else {
		cmd.ui.Say(T("Creating service broker {{.Name}} as {{.Username}}...",
			map[string]interface{}{
				"Name":     terminal.EntityNameColor(name),
				"Username": terminal.EntityNameColor(cmd.config.Username())}))
		err = cmd.serviceBrokerRepo.Create(name, url, username, password, "")
	}

	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
Exemplo n.º 8
0
func (cmd *OrgUsers) printer(c flags.FlagContext) userprint.UserPrinter {
	var roles []models.Role
	if c.Bool("a") {
		roles = []models.Role{models.RoleOrgUser}
	} else {
		roles = []models.Role{models.RoleOrgManager, models.RoleBillingManager, models.RoleOrgAuditor}
	}

	if cmd.pluginCall {
		return userprint.NewOrgUsersPluginPrinter(
			cmd.pluginModel,
			cmd.userLister(),
			roles,
		)
	}
	return &userprint.OrgUsersUIPrinter{
		UI:         cmd.ui,
		UserLister: cmd.userLister(),
		Roles:      roles,
		RoleDisplayNames: map[models.Role]string{
			models.RoleOrgUser:        T("USERS"),
			models.RoleOrgManager:     T("ORG MANAGER"),
			models.RoleBillingManager: T("BILLING MANAGER"),
			models.RoleOrgAuditor:     T("ORG AUDITOR"),
		},
	}
}
Exemplo n.º 9
0
func (cmd *DeleteQuota) Execute(c flags.FlagContext) error {
	quotaName := c.Args()[0]

	if !c.Bool("f") {
		response := cmd.ui.ConfirmDelete("quota", quotaName)
		if !response {
			return nil
		}
	}

	cmd.ui.Say(T("Deleting quota {{.QuotaName}} as {{.Username}}...", map[string]interface{}{
		"QuotaName": terminal.EntityNameColor(quotaName),
		"Username":  terminal.EntityNameColor(cmd.config.Username()),
	}))

	quota, err := cmd.quotaRepo.FindByName(quotaName)

	switch (err).(type) {
	case nil: // no error
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Quota {{.QuotaName}} does not exist", map[string]interface{}{"QuotaName": quotaName}))
		return nil
	default:
		return err
	}

	err = cmd.quotaRepo.Delete(quota.GUID)
	if err != nil {
		return err
	}

	cmd.ui.Ok()
	return err
}
Exemplo n.º 10
0
func (cmd *ShowService) Execute(c flags.FlagContext) {
	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()

	if cmd.pluginCall {
		cmd.populatePluginModel(serviceInstance)
		return
	}

	if c.Bool("guid") {
		cmd.ui.Say(serviceInstance.Guid)
	} else {
		cmd.ui.Say("")
		cmd.ui.Say(T("Service instance: {{.ServiceName}}", map[string]interface{}{"ServiceName": terminal.EntityNameColor(serviceInstance.Name)}))

		if serviceInstance.IsUserProvided() {
			cmd.ui.Say(T("Service: {{.ServiceDescription}}",
				map[string]interface{}{
					"ServiceDescription": terminal.EntityNameColor(T("user-provided")),
				}))
		} else {
			cmd.ui.Say(T("Service: {{.ServiceDescription}}",
				map[string]interface{}{
					"ServiceDescription": terminal.EntityNameColor(serviceInstance.ServiceOffering.Label),
				}))
			cmd.ui.Say(T("Plan: {{.ServicePlanName}}",
				map[string]interface{}{
					"ServicePlanName": terminal.EntityNameColor(serviceInstance.ServicePlan.Name),
				}))
			cmd.ui.Say(T("Description: {{.ServiceDescription}}", map[string]interface{}{"ServiceDescription": terminal.EntityNameColor(serviceInstance.ServiceOffering.Description)}))
			cmd.ui.Say(T("Documentation url: {{.URL}}",
				map[string]interface{}{
					"URL": terminal.EntityNameColor(serviceInstance.ServiceOffering.DocumentationUrl),
				}))
			cmd.ui.Say(T("Dashboard: {{.URL}}",
				map[string]interface{}{
					"URL": terminal.EntityNameColor(serviceInstance.DashboardUrl),
				}))
			cmd.ui.Say("")
			cmd.ui.Say(T("Last Operation"))
			cmd.ui.Say(T("Status: {{.State}}",
				map[string]interface{}{
					"State": terminal.EntityNameColor(ServiceInstanceStateToStatus(serviceInstance.LastOperation.Type, serviceInstance.LastOperation.State, serviceInstance.IsUserProvided())),
				}))
			cmd.ui.Say(T("Message: {{.Message}}",
				map[string]interface{}{
					"Message": terminal.EntityNameColor(serviceInstance.LastOperation.Description),
				}))
			if "" != serviceInstance.LastOperation.CreatedAt {
				cmd.ui.Say(T("Started: {{.Started}}",
					map[string]interface{}{
						"Started": terminal.EntityNameColor(serviceInstance.LastOperation.CreatedAt),
					}))
			}
			cmd.ui.Say(T("Updated: {{.Updated}}",
				map[string]interface{}{
					"Updated": terminal.EntityNameColor(serviceInstance.LastOperation.UpdatedAt),
				}))
		}
	}
}
Exemplo n.º 11
0
func (cmd *ListStack) Execute(c flags.FlagContext) {
	stackName := c.Args()[0]

	stack, apiErr := cmd.stacksRepo.FindByName(stackName)

	if c.Bool("guid") {
		cmd.ui.Say(stack.GUID)
	} else {
		if apiErr != nil {
			cmd.ui.Failed(apiErr.Error())
			return
		}

		cmd.ui.Say(T("Getting stack '{{.Stack}}' in org {{.OrganizationName}} / space {{.SpaceName}} as {{.Username}}...",
			map[string]interface{}{"Stack": stackName,
				"OrganizationName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
				"SpaceName":        terminal.EntityNameColor(cmd.config.SpaceFields().Name),
				"Username":         terminal.EntityNameColor(cmd.config.Username())}))

		cmd.ui.Ok()
		cmd.ui.Say("")
		table := cmd.ui.Table([]string{T("name"), T("description")})
		table.Add(stack.Name, stack.Description)
		table.Print()
	}
}
func (cmd *DeleteUser) Execute(c flags.FlagContext) {
	username := c.Args()[0]
	force := c.Bool("f")

	if !force && !cmd.ui.ConfirmDelete(T("user"), username) {
		return
	}

	cmd.ui.Say(T("Deleting user {{.TargetUser}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"TargetUser":  terminal.EntityNameColor(username),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	user, apiErr := cmd.userRepo.FindByUsername(username)
	switch apiErr.(type) {
	case nil:
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("User {{.TargetUser}} does not exist.", map[string]interface{}{"TargetUser": username}))
		return
	default:
		cmd.ui.Failed(apiErr.Error())
		return
	}

	apiErr = cmd.userRepo.Delete(user.Guid)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
}
Exemplo n.º 13
0
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c flags.FlagContext) (buildpack models.Buildpack, apiErr error) {
	position, err := strconv.Atoi(c.Args()[2])
	if err != nil {
		apiErr = fmt.Errorf(T("Error {{.ErrorDescription}} is being passed in as the argument for 'Position' but 'Position' requires an integer.  For more syntax help, see `cf create-buildpack -h`.", map[string]interface{}{"ErrorDescription": c.Args()[2]}))
		return
	}

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

	var enableOption *bool
	if enabled {
		enableOption = &enabled
	}
	if disabled {
		disabled = false
		enableOption = &disabled
	}

	buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil)

	return
}
Exemplo n.º 14
0
func (cmd *DeleteSpaceQuota) Execute(c flags.FlagContext) {
	quotaName := c.Args()[0]

	if !c.Bool("f") {
		response := cmd.ui.ConfirmDelete("quota", quotaName)
		if !response {
			return
		}
	}

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

	quota, apiErr := cmd.spaceQuotaRepo.FindByName(quotaName)
	switch (apiErr).(type) {
	case nil: // no error
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Quota {{.QuotaName}} does not exist", map[string]interface{}{"QuotaName": quotaName}))
		return
	default:
		cmd.ui.Failed(apiErr.Error())
	}

	apiErr = cmd.spaceQuotaRepo.Delete(quota.Guid)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
	}

	cmd.ui.Ok()
}
Exemplo n.º 15
0
func (cmd *MapRoute) Execute(c flags.FlagContext) {
	hostName := c.String("n")
	path := c.String("path")
	domain := cmd.domainReq.GetDomain()
	app := cmd.appReq.GetApplication()

	port := c.Int("port")
	randomPort := c.Bool("random-port")
	route, apiErr := cmd.routeCreator.CreateRoute(hostName, path, port, randomPort, domain, cmd.config.SpaceFields())
	if apiErr != nil {
		cmd.ui.Failed(T("Error resolving route:\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()}))
	}
	cmd.ui.Say(T("Adding route {{.URL}} to app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
		map[string]interface{}{
			"URL":       terminal.EntityNameColor(route.URL()),
			"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())}))

	apiErr = cmd.routeRepo.Bind(route.GUID, app.GUID)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
}
func (cmd *DeleteSecurityGroup) Execute(context flags.FlagContext) {
	name := context.Args()[0]
	cmd.ui.Say(T("Deleting security group {{.security_group}} as {{.username}}",
		map[string]interface{}{
			"security_group": terminal.EntityNameColor(name),
			"username":       terminal.EntityNameColor(cmd.configRepo.Username()),
		}))

	if !context.Bool("f") {
		response := cmd.ui.ConfirmDelete(T("security group"), name)
		if !response {
			return
		}
	}

	group, err := cmd.securityGroupRepo.Read(name)
	switch err.(type) {
	case nil:
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Security group {{.security_group}} does not exist", map[string]interface{}{"security_group": name}))
		return
	default:
		cmd.ui.Failed(err.Error())
	}

	err = cmd.securityGroupRepo.Delete(group.Guid)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
Exemplo n.º 17
0
func (cmd *PurgeServiceInstance) Execute(c flags.FlagContext) {
	instanceName := c.Args()[0]

	instance, apiErr := cmd.serviceRepo.FindInstanceByName(instanceName)

	switch apiErr.(type) {
	case nil:
	case *errors.ModelNotFoundError:
		cmd.ui.Warn(T("Service instance {{.InstanceName}} not found",
			map[string]interface{}{"InstanceName": instanceName},
		))
		return
	default:
		cmd.ui.Failed(apiErr.Error())
	}

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

	if !confirmed {
		return
	}
	cmd.ui.Say(T("Purging service {{.InstanceName}}...", map[string]interface{}{"InstanceName": instanceName}))
	err := cmd.serviceRepo.PurgeServiceInstance(instance)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
Exemplo n.º 18
0
func (cmd *PurgeServiceOffering) Execute(c flags.FlagContext) {
	serviceName := c.Args()[0]

	offering, apiErr := cmd.serviceRepo.FindServiceOfferingByLabelAndProvider(serviceName, c.String("p"))

	switch apiErr.(type) {
	case nil:
	case *errors.ModelNotFoundError:
		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
	default:
		cmd.ui.Failed(apiErr.Error())
	}

	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
	}
	cmd.ui.Say(T("Purging service {{.ServiceName}}...", map[string]interface{}{"ServiceName": serviceName}))
	err := cmd.serviceRepo.PurgeServiceOffering(offering)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
Exemplo n.º 19
0
Arquivo: push.go Projeto: plamenai/cli
func (cmd *Push) getAppParamsFromManifest(c flags.FlagContext) []models.AppParams {
	if c.Bool("no-manifest") {
		return []models.AppParams{}
	}

	var path string
	if c.String("f") != "" {
		path = c.String("f")
	} else {
		var err error
		path, err = os.Getwd()
		if err != nil {
			cmd.ui.Failed(T("Could not determine the current working directory!"), err)
		}
	}

	m, err := cmd.manifestRepo.ReadManifest(path)

	if err != nil {
		if m.Path == "" && c.String("f") == "" {
			return []models.AppParams{}
		}
		cmd.ui.Failed(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()}))
	}

	apps, err := m.Applications()
	if err != nil {
		cmd.ui.Failed("Error reading manifest file:\n%s", err)
	}

	cmd.ui.Say(T("Using manifest file {{.Path}}\n",
		map[string]interface{}{"Path": terminal.EntityNameColor(m.Path)}))
	return apps
}
Exemplo n.º 20
0
func (cmd *DeleteServiceBroker) Execute(c flags.FlagContext) {
	brokerName := c.Args()[0]
	if !c.Bool("f") && !cmd.ui.ConfirmDelete(T("service-broker"), brokerName) {
		return
	}

	cmd.ui.Say(T("Deleting service broker {{.Name}} as {{.Username}}...",
		map[string]interface{}{
			"Name":     terminal.EntityNameColor(brokerName),
			"Username": terminal.EntityNameColor(cmd.config.Username()),
		}))

	broker, apiErr := cmd.repo.FindByName(brokerName)

	switch apiErr.(type) {
	case nil:
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Service Broker {{.Name}} does not exist.", map[string]interface{}{"Name": brokerName}))
		return
	default:
		cmd.ui.Failed(apiErr.Error())
		return
	}

	apiErr = cmd.repo.Delete(broker.GUID)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
	return
}
Exemplo n.º 21
0
func (cmd *DeleteSpace) Execute(c flags.FlagContext) error {
	spaceName := c.Args()[0]

	if !c.Bool("f") {
		if !cmd.ui.ConfirmDelete(T("space"), spaceName) {
			return nil
		}
	}

	cmd.ui.Say(T("Deleting space {{.TargetSpace}} in org {{.TargetOrg}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"TargetSpace": terminal.EntityNameColor(spaceName),
			"TargetOrg":   terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	space := cmd.spaceReq.GetSpace()

	err := cmd.spaceRepo.Delete(space.GUID)
	if err != nil {
		return err
	}

	cmd.ui.Ok()

	if cmd.config.SpaceFields().GUID == space.GUID {
		cmd.config.SetSpaceFields(models.SpaceFields{})
		cmd.ui.Say(T("TIP: No space targeted, use '{{.CfTargetCommand}}' to target a space",
			map[string]interface{}{"CfTargetCommand": cf.Name + " target -s"}))
	}

	return nil
}
Exemplo n.º 22
0
func (cmd *BindRouteService) Execute(c flags.FlagContext) {
	host := c.String("hostname")
	domain := cmd.domainReq.GetDomain()
	path := "" // path is not currently supported

	route, err := cmd.routeRepo.Find(host, domain, path)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	serviceInstance := cmd.serviceInstanceReq.GetServiceInstance()
	if !serviceInstance.IsUserProvided() {
		var requiresRouteForwarding bool
		for _, requirement := range serviceInstance.ServiceOffering.Requires {
			if requirement == "route_forwarding" {
				requiresRouteForwarding = true
				break
			}
		}

		confirmed := c.Bool("force")
		if requiresRouteForwarding && !confirmed {
			confirmed = cmd.ui.Confirm(T("Binding may cause requests for route {{.URL}} to be altered by service instance {{.ServiceInstanceName}}. Do you want to proceed?",
				map[string]interface{}{
					"URL": route.URL(),
					"ServiceInstanceName": serviceInstance.Name,
				}))

			if !confirmed {
				cmd.ui.Warn(T("Bind cancelled"))
				return
			}
		}
	}

	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.BindRoute(route, serviceInstance)
	if err != nil {
		if httpErr, ok := err.(errors.HttpError); ok && httpErr.ErrorCode() == errors.ROUTE_ALREADY_BOUND_TO_SAME_SERVICE {
			cmd.ui.Warn(T("Route {{.URL}} is already bound to service instance {{.ServiceInstanceName}}.",
				map[string]interface{}{
					"URL": route.URL(),
					"ServiceInstanceName": serviceInstance.Name,
				}))
		} else {
			cmd.ui.Failed(err.Error())
		}
	}

	cmd.ui.Ok()
}
Exemplo n.º 23
0
func (cmd *ShowOrg) Execute(c flags.FlagContext) {
	org := cmd.orgReq.GetOrganization()

	if c.Bool("guid") {
		cmd.ui.Say(org.Guid)
	} else {
		cmd.ui.Say(T("Getting info for org {{.OrgName}} as {{.Username}}...",
			map[string]interface{}{
				"OrgName":  terminal.EntityNameColor(org.Name),
				"Username": terminal.EntityNameColor(cmd.config.Username())}))
		cmd.ui.Ok()
		cmd.ui.Say("")

		table := terminal.NewTable(cmd.ui, []string{terminal.EntityNameColor(org.Name) + ":", "", ""})

		domains := []string{}
		for _, domain := range org.Domains {
			domains = append(domains, domain.Name)
		}

		spaces := []string{}
		for _, space := range org.Spaces {
			spaces = append(spaces, space.Name)
		}

		spaceQuotas := []string{}
		for _, spaceQuota := range org.SpaceQuotas {
			spaceQuotas = append(spaceQuotas, spaceQuota.Name)
		}

		quota := org.QuotaDefinition

		appInstanceLimit := strconv.Itoa(quota.AppInstanceLimit)
		if quota.AppInstanceLimit == resources.UnlimitedAppInstances {
			appInstanceLimit = T("unlimited")
		}

		orgQuotaFields := []string{
			T("{{.MemoryLimit}}M memory limit", map[string]interface{}{"MemoryLimit": quota.MemoryLimit}),
			T("{{.InstanceMemoryLimit}} instance memory limit", map[string]interface{}{"InstanceMemoryLimit": formatters.InstanceMemoryLimit(quota.InstanceMemoryLimit)}),
			T("{{.RoutesLimit}} routes", map[string]interface{}{"RoutesLimit": quota.RoutesLimit}),
			T("{{.ServicesLimit}} services", map[string]interface{}{"ServicesLimit": quota.ServicesLimit}),
			T("paid services {{.NonBasicServicesAllowed}}", map[string]interface{}{"NonBasicServicesAllowed": formatters.Allowed(quota.NonBasicServicesAllowed)}),
			T("{{.AppInstanceLimit}} app instance limit", map[string]interface{}{"AppInstanceLimit": appInstanceLimit}),
		}
		orgQuota := fmt.Sprintf("%s (%s)", quota.Name, strings.Join(orgQuotaFields, ", "))

		if cmd.pluginCall {
			cmd.populatePluginModel(org, quota)
		} else {
			table.Add("", T("domains:"), terminal.EntityNameColor(strings.Join(domains, ", ")))
			table.Add("", T("quota:"), terminal.EntityNameColor(orgQuota))
			table.Add("", T("spaces:"), terminal.EntityNameColor(strings.Join(spaces, ", ")))
			table.Add("", T("space quotas:"), terminal.EntityNameColor(strings.Join(spaceQuotas, ", ")))

			table.Print()
		}
	}
}
Exemplo n.º 24
0
func (cmd *Logs) Execute(c flags.FlagContext) {
	app := cmd.appReq.GetApplication()

	if c.Bool("recent") {
		cmd.recentLogsFor(app)
	} else {
		cmd.tailLogsFor(app)
	}
}
Exemplo n.º 25
0
Arquivo: app.go Projeto: vframbach/cli
func (cmd *ShowApp) Execute(c flags.FlagContext) {
	app := cmd.appReq.GetApplication()

	if c.Bool("guid") {
		cmd.ui.Say(app.Guid)
	} else {
		cmd.ShowApp(app, cmd.config.OrganizationFields().Name, cmd.config.SpaceFields().Name)
	}
}
Exemplo n.º 26
0
func (cmd *Login) Execute(c flags.FlagContext) error {
	cmd.config.ClearSession()

	endpoint, skipSSL := cmd.decideEndpoint(c)

	api := API{
		ui:           cmd.ui,
		config:       cmd.config,
		endpointRepo: cmd.endpointRepo,
	}
	err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name)
	if err != nil {
		return err
	}

	defer func() {
		cmd.ui.Say("")
		cmd.ui.ShowConfiguration(cmd.config)
	}()

	// We thought we would never need to explicitly branch in this code
	// for anything as simple as authentication, but it turns out that our
	// assumptions did not match reality.

	// When SAML is enabled (but not configured) then the UAA/Login server
	// will always returns password prompts that includes the Passcode field.
	// Users can authenticate with:
	//   EITHER   username and password
	//   OR       a one-time passcode

	if c.Bool("sso") {
		err = cmd.authenticateSSO(c)
		if err != nil {
			return err
		}
	} else {
		err = cmd.authenticate(c)
		if err != nil {
			return err
		}
	}

	orgIsSet, err := cmd.setOrganization(c)
	if err != nil {
		return err
	}

	if orgIsSet {
		err = cmd.setSpace(c)
		if err != nil {
			return err
		}
	}
	cmd.ui.NotifyUpdateIfNeeded(cmd.config)
	return nil
}
Exemplo n.º 27
0
Arquivo: scale.go Projeto: ralfcam/cli
func (cmd *Scale) confirmRestart(context flags.FlagContext, appName string) bool {
	if context.Bool("f") {
		return true
	} else {
		result := cmd.ui.Confirm(T("This will cause the app to restart. Are you sure you want to scale {{.AppName}}?",
			map[string]interface{}{"AppName": terminal.EntityNameColor(appName)}))
		cmd.ui.Say("")
		return result
	}
}
Exemplo n.º 28
0
func (cmd *DeleteServiceKey) Execute(c flags.FlagContext) {
	serviceInstanceName := c.Args()[0]
	serviceKeyName := c.Args()[1]

	if !c.Bool("f") {
		if !cmd.ui.ConfirmDelete(T("service key"), serviceKeyName) {
			return
		}
	}

	cmd.ui.Say(T("Deleting key {{.ServiceKeyName}} for service instance {{.ServiceInstanceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceKeyName":      terminal.EntityNameColor(serviceKeyName),
			"ServiceInstanceName": terminal.EntityNameColor(serviceInstanceName),
			"CurrentUser":         terminal.EntityNameColor(cmd.config.Username()),
		}))

	serviceInstance, err := cmd.serviceRepo.FindInstanceByName(serviceInstanceName)
	if err != nil {
		cmd.ui.Ok()
		cmd.ui.Warn(T("Service instance {{.ServiceInstanceName}} does not exist.",
			map[string]interface{}{
				"ServiceInstanceName": serviceInstanceName,
			}))
		return
	}

	serviceKey, err := cmd.serviceKeyRepo.GetServiceKey(serviceInstance.GUID, serviceKeyName)
	if err != nil || serviceKey.Fields.GUID == "" {
		switch err.(type) {
		case *errors.NotAuthorizedError:
			cmd.ui.Say(T("No service key {{.ServiceKeyName}} found for service instance {{.ServiceInstanceName}}",
				map[string]interface{}{
					"ServiceKeyName":      terminal.EntityNameColor(serviceKeyName),
					"ServiceInstanceName": terminal.EntityNameColor(serviceInstanceName)}))
			return
		default:
			cmd.ui.Ok()
			cmd.ui.Warn(T("Service key {{.ServiceKeyName}} does not exist for service instance {{.ServiceInstanceName}}.",
				map[string]interface{}{
					"ServiceKeyName":      serviceKeyName,
					"ServiceInstanceName": serviceInstanceName,
				}))
			return
		}
	}

	err = cmd.serviceKeyRepo.DeleteServiceKey(serviceKey.Fields.GUID)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return
	}

	cmd.ui.Ok()
}
Exemplo n.º 29
0
Arquivo: curl.go Projeto: Reejoshi/cli
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 {
		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
}
Exemplo n.º 30
0
Arquivo: app.go Projeto: VStarkov/cli
func (cmd *ShowApp) Execute(c flags.FlagContext) {
	app := cmd.appReq.GetApplication()

	if cmd.pluginCall {
		cmd.pluginAppModel.Name = app.Name
		cmd.pluginAppModel.State = app.State
		cmd.pluginAppModel.Guid = app.Guid
		cmd.pluginAppModel.BuildpackUrl = app.BuildpackUrl
		cmd.pluginAppModel.Command = app.Command
		cmd.pluginAppModel.Diego = app.Diego
		cmd.pluginAppModel.DetectedStartCommand = app.DetectedStartCommand
		cmd.pluginAppModel.DiskQuota = app.DiskQuota
		cmd.pluginAppModel.EnvironmentVars = app.EnvironmentVars
		cmd.pluginAppModel.InstanceCount = app.InstanceCount
		cmd.pluginAppModel.Memory = app.Memory
		cmd.pluginAppModel.RunningInstances = app.RunningInstances
		cmd.pluginAppModel.HealthCheckTimeout = app.HealthCheckTimeout
		cmd.pluginAppModel.SpaceGuid = app.SpaceGuid
		cmd.pluginAppModel.PackageUpdatedAt = app.PackageUpdatedAt
		cmd.pluginAppModel.PackageState = app.PackageState
		cmd.pluginAppModel.StagingFailedReason = app.StagingFailedReason

		cmd.pluginAppModel.Stack = &plugin_models.GetApp_Stack{
			Name: app.Stack.Name,
			Guid: app.Stack.Guid,
		}

		for i, _ := range app.Routes {
			cmd.pluginAppModel.Routes = append(cmd.pluginAppModel.Routes, plugin_models.GetApp_RouteSummary{
				Host: app.Routes[i].Host,
				Guid: app.Routes[i].Guid,
				Domain: plugin_models.GetApp_DomainFields{
					Name:                   app.Routes[i].Domain.Name,
					Guid:                   app.Routes[i].Domain.Guid,
					Shared:                 app.Routes[i].Domain.Shared,
					OwningOrganizationGuid: app.Routes[i].Domain.OwningOrganizationGuid,
				},
			})
		}

		for i, _ := range app.Services {
			cmd.pluginAppModel.Services = append(cmd.pluginAppModel.Services, plugin_models.GetApp_ServiceSummary{
				Name: app.Services[i].Name,
				Guid: app.Services[i].Guid,
			})
		}
	}

	if c.Bool("guid") {
		cmd.ui.Say(app.Guid)
	} else {
		cmd.ShowApp(app, cmd.config.OrganizationFields().Name, cmd.config.SpaceFields().Name)
	}
}