func (cmd *Push) getAppParamsFromManifest(c flags.FlagContext) ([]models.AppParams, error) { if c.Bool("no-manifest") { return []models.AppParams{}, nil } var path string if c.String("f") != "" { path = c.String("f") } else { var err error path, err = os.Getwd() if err != nil { return nil, errors.New(fmt.Sprint(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{}, nil } return nil, errors.New(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()})) } apps, err := m.Applications() if err != nil { return nil, errors.New(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()})) } cmd.ui.Say(T("Using manifest file {{.Path}}\n", map[string]interface{}{"Path": terminal.EntityNameColor(m.Path)})) return apps, nil }
func (uaa UAARepository) Authenticate(credentials map[string]string) error { data := url.Values{ "grant_type": {"password"}, "scope": {""}, } for key, val := range credentials { data[key] = []string{val} } err := uaa.getAuthToken(data) if err != nil { httpError, ok := err.(errors.HTTPError) if ok { switch { case httpError.StatusCode() == http.StatusUnauthorized: return errors.New(T("Credentials were rejected, please try again.")) case httpError.StatusCode() >= http.StatusInternalServerError: return errors.New(T("The targeted API endpoint could not be reached.")) } } return err } return nil }
func (cmd *Push) bindAppToServices(services []string, app models.Application) error { for _, serviceName := range services { serviceInstance, err := cmd.serviceRepo.FindInstanceByName(serviceName) if err != nil { return errors.New(T("Could not find service {{.ServiceName}} to bind to {{.AppName}}", map[string]interface{}{"ServiceName": serviceName, "AppName": app.Name})) } cmd.ui.Say(T("Binding service {{.ServiceName}} to app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(serviceInstance.Name), "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())})) err = cmd.serviceBinder.BindApplication(app, serviceInstance, nil) switch httpErr := err.(type) { case errors.HTTPError: if httpErr.ErrorCode() == errors.ServiceBindingAppServiceTaken { err = nil } } if err != nil { return errors.New(T("Could not bind to service {{.ServiceName}}\nError: {{.Err}}", map[string]interface{}{"ServiceName": serviceName, "Err": err.Error()})) } cmd.ui.Ok() } return nil }
func (cmd *Password) Execute(c flags.FlagContext) error { oldPassword := cmd.ui.AskForPassword(T("Current Password")) newPassword := cmd.ui.AskForPassword(T("New Password")) verifiedPassword := cmd.ui.AskForPassword(T("Verify Password")) if verifiedPassword != newPassword { return errors.New(T("Password verification does not match")) } cmd.ui.Say(T("Changing password...")) err := cmd.pwdRepo.UpdatePassword(oldPassword, newPassword) switch typedErr := err.(type) { case nil: case errors.HTTPError: if typedErr.StatusCode() == 401 { return errors.New(T("Current password did not match")) } return err default: return err } cmd.ui.Ok() cmd.config.ClearSession() cmd.ui.Say(T("Please log in again")) return nil }
func (cmd *Push) processPathCallback(path string, app models.Application) func(string) error { return func(appDir string) error { localFiles, err := cmd.appfiles.AppFilesInDir(appDir) if err != nil { return errors.New( T("Error processing app files in '{{.Path}}': {{.Error}}", map[string]interface{}{ "Path": path, "Error": err.Error(), })) } if len(localFiles) == 0 { return errors.New( T("No app files found in '{{.Path}}'", map[string]interface{}{ "Path": path, })) } cmd.ui.Say(T("Uploading {{.AppName}}...", map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)})) err = cmd.uploadApp(app.GUID, appDir, path, localFiles) if err != nil { return errors.New(T("Error uploading application.\n{{.APIErr}}", map[string]interface{}{"APIErr": err.Error()})) } cmd.ui.Ok() return nil } }
func (cmd *Push) createAppSetFromContextAndManifest(contextApp models.AppParams, manifestApps []models.AppParams) ([]models.AppParams, error) { var err error var apps []models.AppParams switch len(manifestApps) { case 0: if contextApp.Name == nil { return nil, errors.New( T("Incorrect Usage. The push command requires an app name. The app name can be supplied as an argument or with a manifest.yml file.") + "\n\n" + commandregistry.Commands.CommandUsage("push"), ) } err = addApp(&apps, contextApp) case 1: manifestApps[0].Merge(&contextApp) err = addApp(&apps, manifestApps[0]) default: selectedAppName := contextApp.Name contextApp.Name = nil if !contextApp.IsEmpty() { return nil, errors.New(T("Incorrect Usage. Command line flags (except -f) cannot be applied when pushing multiple apps from a manifest file.")) } if selectedAppName != nil { var foundApp bool for _, appParams := range manifestApps { if appParams.Name != nil && *appParams.Name == *selectedAppName { foundApp = true err = addApp(&apps, appParams) } } if !foundApp { err = errors.New(T("Could not find app named '{{.AppName}}' in manifest", map[string]interface{}{"AppName": *selectedAppName})) } } else { for _, manifestApp := range manifestApps { err = addApp(&apps, manifestApp) } } } if err != nil { return nil, errors.New(T("Error: {{.Err}}", map[string]interface{}{"Err": err.Error()})) } return apps, nil }
func (cmd *CreateServiceKey) Execute(c flags.FlagContext) error { serviceInstance := cmd.serviceInstanceRequirement.GetServiceInstance() serviceKeyName := c.Args()[1] params := c.String("c") 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.")) } cmd.ui.Say(T("Creating service key {{.ServiceKeyName}} for service instance {{.ServiceInstanceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceInstanceName": terminal.EntityNameColor(serviceInstance.Name), "ServiceKeyName": terminal.EntityNameColor(serviceKeyName), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) err = cmd.serviceKeyRepo.CreateServiceKey(serviceInstance.GUID, serviceKeyName, paramsMap) switch err.(type) { case nil: cmd.ui.Ok() case *errors.ModelAlreadyExistsError: cmd.ui.Ok() cmd.ui.Warn(err.Error()) default: return err } return nil }
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 }
func (cmd *CreateUser) Execute(c flags.FlagContext) error { username := c.Args()[0] password := c.Args()[1] cmd.ui.Say(T("Creating user {{.TargetUser}}...", map[string]interface{}{ "TargetUser": terminal.EntityNameColor(username), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) err := cmd.userRepo.Create(username, password) switch err.(type) { case nil: case *errors.ModelAlreadyExistsError: cmd.ui.Warn("%s", err.Error()) default: return errors.New(T("Error creating user {{.TargetUser}}.\n{{.Error}}", map[string]interface{}{ "TargetUser": terminal.EntityNameColor(username), "Error": err.Error(), })) } cmd.ui.Ok() cmd.ui.Say(T("\nTIP: Assign roles with '{{.CurrentUser}} set-org-role' and '{{.CurrentUser}} set-space-role'", map[string]interface{}{"CurrentUser": cf.Name})) return nil }
func (gateway Gateway) waitForJob(jobURL, accessToken string, timeout time.Duration) error { startTime := gateway.Clock() for true { if gateway.Clock().Sub(startTime) > timeout && timeout != 0 { return errors.NewAsyncTimeoutError(jobURL) } var request *Request request, err := gateway.NewRequest("GET", jobURL, accessToken, nil) response := &JobResource{} _, err = gateway.PerformRequestForJSONResponse(request, response) if err != nil { return err } switch response.Entity.Status { case JobFinished: return nil case JobFailed: return errors.New(response.Entity.ErrorDetails.Description) } accessToken = request.HTTPReq.Header.Get("Authorization") time.Sleep(gateway.PollingThrottle) } return nil }
func (routeActor routeActor) BindRoute(app models.Application, route models.Route) error { if !app.HasRoute(route) { routeActor.ui.Say(T( "Binding {{.URL}} to {{.AppName}}...", map[string]interface{}{ "URL": terminal.EntityNameColor(route.URL()), "AppName": terminal.EntityNameColor(app.Name), }), ) err := routeActor.routeRepo.Bind(route.GUID, app.GUID) switch err := err.(type) { case nil: routeActor.ui.Ok() routeActor.ui.Say("") return nil case errors.HTTPError: if err.ErrorCode() == errors.InvalidRelation { return errors.New(T( "The route {{.URL}} is already in use.\nTIP: Change the hostname with -n HOSTNAME or use --random-route to generate a new route and then push again.", map[string]interface{}{ "URL": route.URL(), }), ) } } return err } return nil }
func (c CloudControllerServiceKeyRepository) CreateServiceKey(instanceGUID string, keyName string, params map[string]interface{}) error { path := "/v2/service_keys" request := models.ServiceKeyRequest{ Name: keyName, ServiceInstanceGUID: instanceGUID, Params: params, } jsonBytes, err := json.Marshal(request) if err != nil { return err } err = c.gateway.CreateResource(c.config.APIEndpoint(), path, bytes.NewReader(jsonBytes)) if httpErr, ok := err.(errors.HTTPError); ok { switch httpErr.ErrorCode() { case errors.ServiceKeyNameTaken: return errors.NewModelAlreadyExistsError("Service key", keyName) case errors.UnbindableService: return errors.NewUnbindableServiceError() default: return errors.New(httpErr.Error()) } } return nil }
func (repo CloudControllerUserRepository) getAuthEndpoint() (string, error) { uaaEndpoint := repo.config.UaaEndpoint() if uaaEndpoint == "" { return "", errors.New(T("UAA endpoint missing from config file")) } return uaaEndpoint, nil }
func (repo DiskRepository) readAllYAMLFiles(path string) (mergedMap generic.Map, err error) { file, err := os.Open(filepath.Clean(path)) if err != nil { return } defer file.Close() mapp, err := parseManifest(file) if err != nil { return } if !mapp.Has("inherit") { mergedMap = mapp return } inheritedPath, ok := mapp.Get("inherit").(string) if !ok { err = errors.New(T("invalid inherit path in manifest")) return } if !filepath.IsAbs(inheritedPath) { inheritedPath = filepath.Join(filepath.Dir(path), inheritedPath) } inheritedMap, err := repo.readAllYAMLFiles(inheritedPath) if err != nil { return } mergedMap = generic.DeepMerge(inheritedMap, mapp) return }
func (cmd API) setAPIEndpoint(endpoint string, skipSSL bool, cmdName string) error { if strings.HasSuffix(endpoint, "/") { endpoint = strings.TrimSuffix(endpoint, "/") } cmd.config.SetSSLDisabled(skipSSL) refresher := coreconfig.APIConfigRefresher{ Endpoint: endpoint, EndpointRepo: cmd.endpointRepo, Config: cmd.config, } warning, err := refresher.Refresh() if err != nil { cmd.config.SetAPIEndpoint("") cmd.config.SetSSLDisabled(false) switch typedErr := err.(type) { case *errors.InvalidSSLCert: cfAPICommand := terminal.CommandColor(fmt.Sprintf("%s %s --skip-ssl-validation", cf.Name, cmdName)) tipMessage := fmt.Sprintf(T("TIP: Use '{{.APICommand}}' to continue with an insecure API endpoint", map[string]interface{}{"APICommand": cfAPICommand})) return errors.New(T("Invalid SSL Cert for {{.URL}}\n{{.TipMessage}}", map[string]interface{}{"URL": typedErr.URL, "TipMessage": tipMessage})) default: return typedErr } } if warning != nil { cmd.ui.Say(terminal.WarningColor(warning.Warn())) } return nil }
func (cmd *RenameService) Execute(c flags.FlagContext) error { newName := c.Args()[1] serviceInstance := cmd.serviceInstanceReq.GetServiceInstance() cmd.ui.Say(T("Renaming service {{.ServiceName}} to {{.NewServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(serviceInstance.Name), "NewServiceName": terminal.EntityNameColor(newName), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) err := cmd.serviceRepo.RenameService(serviceInstance, newName) if err != nil { if httpError, ok := err.(errors.HTTPError); ok && httpError.ErrorCode() == errors.ServiceInstanceNameTaken { return errors.New(T("{{.ErrorDescription}}\nTIP: Use '{{.CFServicesCommand}}' to view all services in this org and space.", map[string]interface{}{ "ErrorDescription": httpError.Error(), "CFServicesCommand": cf.Name + " " + "services", })) } return err } cmd.ui.Ok() return nil }
func (repo *OldFakeBuildpackBitsRepository) UploadBuildpack(buildpack models.Buildpack, dir string) error { if repo.UploadBuildpackErr { return errors.New("Invalid buildpack") } repo.UploadBuildpackPath = dir return repo.UploadBuildpackAPIResponse }
func (cmd *DeleteSharedDomain) Execute(c flags.FlagContext) error { domainName := c.Args()[0] force := c.Bool("f") cmd.ui.Say(T("Deleting domain {{.DomainName}} as {{.Username}}...", map[string]interface{}{ "DomainName": terminal.EntityNameColor(domainName), "Username": terminal.EntityNameColor(cmd.config.Username())})) domain, err := cmd.domainRepo.FindByNameInOrg(domainName, cmd.orgReq.GetOrganizationFields().GUID) switch err.(type) { case nil: if !domain.Shared { return errors.New(T("domain {{.DomainName}} is an owned domain, not a shared domain.", map[string]interface{}{"DomainName": domainName})) } case *errors.ModelNotFoundError: cmd.ui.Ok() cmd.ui.Warn(err.Error()) return nil default: return errors.New(T("Error finding domain {{.DomainName}}\n{{.Err}}", map[string]interface{}{ "DomainName": domainName, "Err": err.Error()})) } if !force { answer := cmd.ui.Confirm(T("This domain is shared across all orgs.\nDeleting it will remove all associated routes, and will make any app with this domain unreachable.\nAre you sure you want to delete the domain {{.DomainName}}? ", map[string]interface{}{"DomainName": domainName})) if !answer { return nil } } err = cmd.domainRepo.DeleteSharedDomain(domain.GUID) if err != nil { return errors.New(T("Error deleting domain {{.DomainName}}\n{{.Err}}", map[string]interface{}{"DomainName": domainName, "Err": err.Error()})) } cmd.ui.Ok() return nil }
func (cmd *Logs) handleError(err error) error { switch err.(type) { case nil: case *errors.InvalidSSLCert: return errors.New(err.Error() + T("\nTIP: use 'cf login -a API --skip-ssl-validation' or 'cf api API --skip-ssl-validation' to suppress this error")) default: return err } return nil }
func (repo CloudControllerRepository) UpdatePassword(old string, new string) error { uaaEndpoint := repo.config.UaaEndpoint() if uaaEndpoint == "" { return errors.New(T("UAA endpoint missing from config file")) } url := fmt.Sprintf("/Users/%s/password", repo.config.UserGUID()) body := fmt.Sprintf(`{"password":"******","oldPassword":"******"}`, new, old) return repo.gateway.UpdateResource(uaaEndpoint, url, strings.NewReader(body)) }
func (cl *client) checkRedirect(req *http.Request, via []*http.Request) error { if len(via) > 1 { return errors.New(T("stopped after 1 redirect")) } prevReq := via[len(via)-1] cl.copyHeaders(prevReq, req, getBaseDomain(req.URL.String()) == getBaseDomain(via[0].URL.String())) cl.dumper.DumpRequest(req) return nil }
func (cmd Push) ValidateContextAndAppParams(appsFromManifest []models.AppParams, appFromContext models.AppParams) error { if appFromContext.NoHostname != nil && *appFromContext.NoHostname { for _, app := range appsFromManifest { if app.Routes != nil { return errors.New(T("Option '--no-hostname' cannot be used with an app manifest containing the 'routes' attribute")) } } } return nil }
func (cmd *DeleteDomain) Execute(c flags.FlagContext) error { domainName := c.Args()[0] domain, err := cmd.domainRepo.FindByNameInOrg(domainName, cmd.orgReq.GetOrganizationFields().GUID) switch err.(type) { case nil: if domain.Shared { return errors.New(T("domain {{.DomainName}} is a shared domain, not an owned domain.", map[string]interface{}{ "DomainName": domainName})) } case *errors.ModelNotFoundError: cmd.ui.Ok() cmd.ui.Warn(err.Error()) return nil default: return errors.New(T("Error finding domain {{.DomainName}}\n{{.APIErr}}", map[string]interface{}{"DomainName": domainName, "APIErr": err.Error()})) } if !c.Bool("f") { if !cmd.ui.ConfirmDelete(T("domain"), domainName) { return nil } } cmd.ui.Say(T("Deleting domain {{.DomainName}} as {{.Username}}...", map[string]interface{}{ "DomainName": terminal.EntityNameColor(domainName), "Username": terminal.EntityNameColor(cmd.config.Username())})) err = cmd.domainRepo.Delete(domain.GUID) if err != nil { return errors.New(T("Error deleting domain {{.DomainName}}\n{{.APIErr}}", map[string]interface{}{"DomainName": domainName, "APIErr": err.Error()})) } cmd.ui.Ok() return nil }
func findPlanFromOfferings(offerings models.ServiceOfferings, name string) (plan models.ServicePlanFields, err error) { for _, offering := range offerings { for _, plan := range offering.Plans { if name == plan.Name { return plan, nil } } } err = errors.New(T("Could not find plan with name {{.ServicePlanName}}", map[string]interface{}{"ServicePlanName": name}, )) return }
func (req *diegoApplicationRequirement) Execute() error { app, err := req.appRepo.Read(req.appName) if err != nil { return err } if app.Diego == false { return errors.New("The app is running on the DEA backend, which does not support this command.") } req.application = app return nil }
func (cmd *CreateService) Execute(c flags.FlagContext) error { serviceName := c.Args()[0] planName := c.Args()[1] serviceInstanceName := c.Args()[2] params := c.String("c") tags := c.String("t") tagsList := uihelpers.ParseTags(tags) 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.")) } cmd.ui.Say(T("Creating service instance {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(serviceInstanceName), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) plan, err := cmd.CreateService(serviceName, planName, serviceInstanceName, paramsMap, tagsList) switch err.(type) { case nil: err := printSuccessMessageForServiceInstance(serviceInstanceName, cmd.serviceRepo, cmd.ui) if err != nil { return err } if !plan.Free { cmd.ui.Say("") cmd.ui.Say(T("Attention: The plan `{{.PlanName}}` of service `{{.ServiceName}}` is not free. The instance `{{.ServiceInstanceName}}` will incur a cost. Contact your administrator if you think this is in error.", map[string]interface{}{ "PlanName": terminal.EntityNameColor(plan.Name), "ServiceName": terminal.EntityNameColor(serviceName), "ServiceInstanceName": terminal.EntityNameColor(serviceInstanceName), })) cmd.ui.Say("") } case *errors.ModelAlreadyExistsError: cmd.ui.Ok() cmd.ui.Warn(err.Error()) default: return err } return nil }
func (cmd Target) setSpace(spaceName string) error { cmd.config.SetSpaceFields(models.SpaceFields{}) if !cmd.config.HasOrganization() { return errors.New(T("An org must be targeted before targeting a space")) } space, apiErr := cmd.spaceRepo.FindByName(spaceName) if apiErr != nil { return fmt.Errorf(T("Unable to access space {{.SpaceName}}.\n{{.APIErr}}", map[string]interface{}{"SpaceName": spaceName, "APIErr": apiErr.Error()})) } cmd.config.SetSpaceFields(space.SpaceFields) return nil }
func (repo CloudControllerDomainRepository) defaultDomain(orgGUID string) (models.DomainFields, error) { var foundDomain *models.DomainFields err := repo.ListDomainsForOrg(orgGUID, func(domain models.DomainFields) bool { foundDomain = &domain return !domain.Shared }) if err != nil { return models.DomainFields{}, err } if foundDomain == nil { return models.DomainFields{}, errors.New(T("Could not find a default domain")) } return *foundDomain, nil }
func (routeActor routeActor) FindPort(routeName string) (string, int, error) { var err error routeSlice := strings.Split(routeName, ":") port := 0 if len(routeSlice) == 2 { port, err = strconv.Atoi(routeSlice[1]) if err != nil { return "", 0, errors.New(T("Invalid port for route {{.RouteName}}", map[string]interface{}{ "RouteName": routeName, }, )) } } return routeSlice[0], port, nil }
func addApp(apps *[]models.AppParams, app models.AppParams) error { if app.Name == nil { return errors.New(T("App name is a required field")) } if app.Path == nil { cwd, err := os.Getwd() if err != nil { return err } app.Path = &cwd } *apps = append(*apps, app) return nil }