github.com/jaylevin/jenkins-library@v1.230.4/cmd/apiKeyValueMapUpload.go (about) 1 package cmd 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 10 "github.com/Jeffail/gabs/v2" 11 "github.com/SAP/jenkins-library/pkg/cpi" 12 piperhttp "github.com/SAP/jenkins-library/pkg/http" 13 "github.com/SAP/jenkins-library/pkg/log" 14 "github.com/SAP/jenkins-library/pkg/telemetry" 15 "github.com/pkg/errors" 16 ) 17 18 func apiKeyValueMapUpload(config apiKeyValueMapUploadOptions, telemetryData *telemetry.CustomData) { 19 // Utils can be used wherever the command.ExecRunner interface is expected. 20 // It can also be used for example as a mavenExecRunner. 21 httpClient := &piperhttp.Client{} 22 23 // For HTTP calls import piperhttp "github.com/SAP/jenkins-library/pkg/http" 24 // and use a &piperhttp.Client{} in a custom system 25 // Example: step checkmarxExecuteScan.go 26 27 // Error situations should be bubbled up until they reach the line below which will then stop execution 28 // through the log.Entry().Fatal() call leading to an os.Exit(1) in the end. 29 err := runApiKeyValueMapUpload(&config, telemetryData, httpClient) 30 if err != nil { 31 log.Entry().WithError(err).Fatal("step execution failed") 32 } 33 } 34 35 func runApiKeyValueMapUpload(config *apiKeyValueMapUploadOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) error { 36 37 serviceKey, err := cpi.ReadCpiServiceKey(config.APIServiceKey) 38 if err != nil { 39 return err 40 } 41 clientOptions := piperhttp.ClientOptions{} 42 tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} 43 token, tokenErr := cpi.CommonUtils.GetBearerToken(tokenParameters) 44 if tokenErr != nil { 45 return errors.Wrap(tokenErr, "failed to fetch Bearer Token") 46 } 47 clientOptions.Token = fmt.Sprintf("Bearer %s", token) 48 httpClient.SetOptions(clientOptions) 49 50 httpMethod := http.MethodPost 51 uploadApiKeyValueMapStatusURL := fmt.Sprintf("%s/apiportal/api/1.0/Management.svc/KeyMapEntries", serviceKey.OAuth.Host) 52 header := make(http.Header) 53 header.Add("Content-Type", "application/json") 54 header.Add("Accept", "application/json") 55 payload, jsonErr := createJSONPayload(config) 56 if jsonErr != nil { 57 return jsonErr 58 } 59 apiProxyUploadStatusResp, httpErr := httpClient.SendRequest(httpMethod, uploadApiKeyValueMapStatusURL, payload, header, nil) 60 61 if httpErr != nil { 62 return errors.Wrapf(httpErr, "HTTP %q request to %q failed with error", httpMethod, uploadApiKeyValueMapStatusURL) 63 } 64 65 if apiProxyUploadStatusResp != nil && apiProxyUploadStatusResp.Body != nil { 66 defer apiProxyUploadStatusResp.Body.Close() 67 } 68 69 if apiProxyUploadStatusResp == nil { 70 return errors.Errorf("did not retrieve a HTTP response") 71 } 72 73 if apiProxyUploadStatusResp.StatusCode == http.StatusCreated { 74 log.Entry(). 75 WithField("KeyValueMap", config.KeyValueMapName). 76 Info("Successfully created api key value map artefact in API Portal") 77 return nil 78 } 79 response, readErr := ioutil.ReadAll(apiProxyUploadStatusResp.Body) 80 81 if readErr != nil { 82 return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", apiProxyUploadStatusResp.StatusCode) 83 } 84 85 log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(response), apiProxyUploadStatusResp.StatusCode) 86 return errors.Errorf("Failed to upload API key value map artefact, Response Status code: %v", apiProxyUploadStatusResp.StatusCode) 87 } 88 89 //createJSONPayload -return http payload as byte array 90 func createJSONPayload(config *apiKeyValueMapUploadOptions) (*bytes.Buffer, error) { 91 jsonObj := gabs.New() 92 jsonObj.Set(config.Key, "name") 93 jsonObj.Set(config.KeyValueMapName, "map_name") 94 jsonObj.Set(config.Value, "value") 95 jsonRootObj := gabs.New() 96 jsonRootObj.Set(config.KeyValueMapName, "name") 97 jsonRootObj.Set(true, "encrypted") 98 jsonRootObj.Set("ENV", "scope") 99 jsonRootObj.ArrayAppend(jsonObj, "keyMapEntryValues") 100 jsonBody, jsonErr := json.Marshal(jsonRootObj) 101 if jsonErr != nil { 102 return nil, errors.Wrapf(jsonErr, "json payload is invalid for key value map %q", config.KeyValueMapName) 103 } 104 payload := bytes.NewBuffer([]byte(jsonBody)) 105 return payload, nil 106 }