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 (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 *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) 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 (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 DownloadFileTo(owner, repo, file, output string) error { if output == "" { output = file } src, err := os.Stat(output) if err == nil && src.IsDir() { output = path.Join(output, file) } blobFile := Config.FindBlobFile(BlobFile{ Name: owner + "/" + repo + "/" + file, }) if blobFile == nil { return errors.New(fmt.Sprintf("Cannot find file '%s' in github.", file)) } dataDownloaded, err := GetFile(owner, repo, file) if err != nil { return err } shaCalc := sha1.New() shaCalc.Write(dataDownloaded) shaEncoded := hex.EncodeToString(shaCalc.Sum(nil)) if shaEncoded != blobFile.InternalSha1 { return errors.New("Checksum doesn't match between downloaded file and saved sha") } return ioutil.WriteFile(output, dataDownloaded, 0644) }
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("Manifest file is not found in the current directory, please provide either an app name or manifest") + "\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 (m Manifest) getAppMaps(data generic.Map) (apps []generic.Map, errs []error) { globalProperties := data.Except([]interface{}{"applications"}) if data.Has("applications") { appMaps, ok := data.Get("applications").([]interface{}) if !ok { errs = append(errs, errors.New(T("Expected applications to be a list"))) return } for _, appData := range appMaps { if !generic.IsMappable(appData) { errs = append(errs, errors.NewWithFmt(T("Expected application to be a list of key/value pairs\nError occurred in manifest near:\n'{{.YmlSnippet}}'", map[string]interface{}{"YmlSnippet": appData}))) continue } appMap := generic.DeepMerge(globalProperties, generic.NewMap(appData)) apps = append(apps, appMap) } } else { apps = append(apps, globalProperties) } return }
func (repo CloudControllerServiceRepository) DeleteService(instance models.ServiceInstance) (apiErr error) { if len(instance.ServiceBindings) > 0 { return errors.New("Cannot delete service instance, apps are still bound to it") } path := fmt.Sprintf("%s/v2/service_instances/%s", repo.config.ApiEndpoint(), instance.Guid) return repo.gateway.DeleteResource(path) }
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 (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 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 (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 (actor PushActorImpl) copyUploadableFiles(appDir string, uploadDir string) (presentFiles []resources.AppFileResource, hasFileToUpload bool, err error) { // Find which files need to be uploaded allAppFiles, err := actor.appfiles.AppFilesInDir(appDir) if err != nil { return } appFilesToUpload, presentFiles, apiErr := actor.getFilesToUpload(allAppFiles) if apiErr != nil { err = errors.New(apiErr.Error()) return } hasFileToUpload = len(appFilesToUpload) > 0 // Copy files into a temporary directory and return it err = actor.appfiles.CopyFiles(appFilesToUpload, appDir, uploadDir) if err != nil { return } // copy cfignore if present fileutils.CopyPathToPath(filepath.Join(appDir, ".cfignore"), filepath.Join(uploadDir, ".cfignore")) //error handling? return }
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 waitForJob(jobUrl, accessToken string, timeout time.Duration) (err error) { startTime := time.Now() for true { if time.Now().Sub(startTime) > timeout && timeout != 0 { return errors.NewAsyncTimeoutError(jobUrl) } var request *Request request, err = NewRequest("GET", jobUrl, accessToken, nil) response := &JobResource{} _, err = gwPerformRequestForJSONResponse(request, response) if err != nil { return } switch response.Entity.Status { case JOB_FINISHED: return case JOB_FAILED: err = errors.New(response.Entity.ErrorDetails.Description) return } accessToken = request.HttpReq.Header.Get("Authorization") time.Sleep(DEFAULT_POLLING_THROTTLE) } return }
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 *cli.Context) (buildpack models.Buildpack, apiErr error) { position, err := strconv.Atoi(c.Args()[2]) if err != nil { apiErr = errors.NewWithFmt("Invalid position. %s", err.Error()) return } enabled := c.Bool("enable") disabled := c.Bool("disable") if enabled && disabled { apiErr = errors.New("Cannot specify both enabled and disabled.") return } var enableOption *bool = nil if enabled { enableOption = &enabled } if disabled { disabled = false enableOption = &disabled } buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil) return }
func (repo ManifestDiskRepository) 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 (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 (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 (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 && httpErr.ErrorCode() == errors.SERVICE_KEY_NAME_TAKEN { return errors.NewModelAlreadyExistsError("Service key", keyName) } else if httpErr, ok := err.(errors.HttpError); ok && httpErr.ErrorCode() == errors.UNBINDABLE_SERVICE { return errors.NewUnbindableServiceError() } else if httpErr, ok := err.(errors.HttpError); ok && httpErr.ErrorCode() != "" { return errors.New(httpErr.Error()) } return nil }
func (gateway Gateway) waitForJob(jobUrl, accessToken string, timeout time.Duration) (err error) { startTime := gateway.Clock() for true { if gateway.Clock().Sub(startTime) > timeout { 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 } switch response.Entity.Status { case JOB_FINISHED: return case JOB_FAILED: err = errors.New(response.Entity.ErrorDetails.Description) return } accessToken = request.HttpReq.Header.Get("Authorization") time.Sleep(gateway.PollingThrottle) } return }
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c *cli.Context) (buildpack models.Buildpack, apiErr error) { position, err := strconv.Atoi(c.Args()[2]) if err != nil { apiErr = errors.NewWithFmt(T("Invalid position. {{.ErrorDescription}}", map[string]interface{}{"ErrorDescription": err.Error()})) 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 = nil if enabled { enableOption = &enabled } if disabled { disabled = false enableOption = &disabled } buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil) return }
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 validateEnvVars(input generic.Map) (errs []error) { generic.Each(input, func(key, value interface{}) { if value == nil { errs = append(errs, errors.New(fmt.Sprintf("env var '%s' should not be null", key))) } }) return }
func normalizeBuildpackArchive(inputFile *os.File, outputFile *os.File) error { stats, err := inputFile.Stat() if err != nil { return err } reader, err := zip.NewReader(inputFile, stats.Size()) if err != nil { return err } contents := reader.File parentPath, hasBuildpack := findBuildpackPath(contents) if !hasBuildpack { return errors.New(T("Zip archive does not contain a buildpack")) } writer := zip.NewWriter(outputFile) for _, file := range contents { name := file.Name if strings.HasPrefix(name, parentPath) { relativeFilename := strings.TrimPrefix(name, parentPath+"/") if relativeFilename == "" { continue } fileInfo := file.FileInfo() header, err := zip.FileInfoHeader(fileInfo) if err != nil { return err } header.Name = relativeFilename w, err := writer.CreateHeader(header) if err != nil { return err } r, err := file.Open() if err != nil { return err } io.Copy(w, r) err = r.Close() if err != nil { return err } } } writer.Close() outputFile.Seek(0, 0) return nil }
func (repo *FakeApplicationRepository) Update(appGuid string, params models.AppParams) (updatedApp models.Application, apiErr error) { repo.UpdateAppGuid = appGuid repo.UpdateParams = params updatedApp = repo.UpdateAppResult if repo.UpdateErr { apiErr = errors.New("Error updating app.") } return }
func validateEnvVars(input generic.Map) (errs []error) { generic.Each(input, func(key, value interface{}) { if value == nil { errs = append(errs, errors.New(fmt.Sprintf(T("env var '{{.PropertyName}}' should not be null", map[string]interface{}{"PropertyName": key})))) } }) return }