github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/src/com/sap/piper/integration/TransportManagementService.groovy (about)

     1  package com.sap.piper.integration
     2  
     3  import com.sap.piper.JsonUtils
     4  
     5  class TransportManagementService implements Serializable {
     6  
     7      final Script script
     8      final Map config
     9  
    10      def jsonUtils = new JsonUtils()
    11  
    12      TransportManagementService(Script script, Map config) {
    13          this.script = script
    14          this.config = config
    15      }
    16  
    17      def authentication(String uaaUrl, String oauthClientId, String oauthClientSecret) {
    18          echo("OAuth Token retrieval started.")
    19  
    20          if (config.verbose) {
    21              echo("UAA-URL: '${uaaUrl}', ClientId: '${oauthClientId}''")
    22          }
    23  
    24          def encodedUsernameColonPassword = "${oauthClientId}:${oauthClientSecret}".bytes.encodeBase64().toString()
    25          def urlEncodedFormData = "grant_type=password&" +
    26              "username=${urlEncodeAndReplaceSpace(oauthClientId)}&" +
    27              "password=${urlEncodeAndReplaceSpace(oauthClientSecret)}"
    28  
    29          def parameters = [
    30              url          : "${uaaUrl}/oauth/token/?grant_type=client_credentials&response_type=token",
    31              httpMode     : "POST",
    32              requestBody  : urlEncodedFormData,
    33              customHeaders: [
    34                  [
    35                      maskValue: false,
    36                      name     : 'Content-Type',
    37                      value    : 'application/x-www-form-urlencoded'
    38                  ],
    39                  [
    40                      maskValue: true,
    41                      name     : 'authorization',
    42                      value    : "Basic ${encodedUsernameColonPassword}"
    43                  ]
    44              ]
    45          ]
    46  
    47          def proxy = config.proxy ? config.proxy : script.env.HTTP_PROXY
    48  
    49          if (proxy){
    50              parameters["httpProxy"] = proxy
    51          }
    52  
    53          def response = sendApiRequest(parameters)
    54          if (response.status != 200) {
    55              prepareAndThrowException(response, "OAuth Token retrieval failed (HTTP status code '${response.status}').")
    56          }
    57  
    58          echo("OAuth Token retrieved successfully.")
    59          return jsonUtils.jsonStringToGroovyObject(response.content).access_token
    60      }
    61  
    62  
    63      def uploadFile(String url, String token, String file, String namedUser) {
    64  
    65          echo("File upload started.")
    66  
    67          if (config.verbose) {
    68              echo("URL: '${url}', File: '${file}'")
    69          }
    70  
    71          def proxy = config.proxy ? config.proxy : script.env.HTTP_PROXY
    72  
    73          def responseFileUpload = 'responseFileUpload.txt'
    74  
    75          def responseContent
    76  
    77          def responseCode = script.sh returnStdout: true,
    78                                        script:"""|#!/bin/sh -e
    79                                                  | curl ${proxy ? '--proxy ' + proxy + ' ' : ''} \\
    80                                                  |      --write-out '%{response_code}' \\
    81                                                  |      -H 'Authorization: Bearer ${token}' \\
    82                                                  |      -F 'file=@${file}' \\
    83                                                  |      -F 'namedUser=${namedUser}' \\
    84                                                  |      --output ${responseFileUpload} \\
    85                                                  |      '${url}/v2/files/upload'""".stripMargin()
    86  
    87          return jsonUtils.jsonStringToGroovyObject(getResponseBody(responseFileUpload, responseCode, '201', 'File upload'))
    88      }
    89  
    90  
    91      def uploadFileToNode(String url, String token, String nodeName, int fileId, String description, String namedUser) {
    92  
    93          echo("Node upload started.")
    94  
    95          if (config.verbose) {
    96              echo("URL: '${url}', NodeName: '${nodeName}', FileId: '${fileId}''")
    97          }
    98  
    99          def bodyMap = [nodeName: nodeName, contentType: 'MTA', description: description, storageType: 'FILE', namedUser: namedUser, entries: [[uri: fileId]]]
   100  
   101          def parameters = [
   102              url          : "${url}/v2/nodes/upload",
   103              httpMode     : "POST",
   104              contentType  : 'APPLICATION_JSON',
   105              requestBody  : jsonUtils.groovyObjectToPrettyJsonString(bodyMap),
   106              customHeaders: [
   107                  [
   108                      maskValue: true,
   109                      name     : 'authorization',
   110                      value    : "Bearer ${token}"
   111                  ]
   112              ]
   113          ]
   114  
   115          def proxy = config.proxy ? config.proxy : script.env.HTTP_PROXY
   116  
   117          if (proxy){
   118              parameters["httpProxy"] = proxy
   119          }
   120  
   121          def response = sendApiRequest(parameters)
   122          if (response.status != 200) {
   123              prepareAndThrowException(response, "Node upload failed (HTTP status code '${response.status}').")
   124          }
   125  
   126          def successMessage = "Node upload successful."
   127          if (config.verbose) {
   128              successMessage += " Response content '${response.content}'."
   129          }
   130          echo(successMessage)
   131          return jsonUtils.jsonStringToGroovyObject(response.content)
   132      }
   133  
   134      def uploadMtaExtDescriptorToNode(String url, String token, Long nodeId, String file, String mtaVersion, String description, String namedUser) {
   135  
   136          echo("MTA Extension Descriptor upload started.")
   137  
   138          if (config.verbose) {
   139              echo("URL: '${url}', NodeId: '${nodeId}', File: '${file}', MtaVersion: '${mtaVersion}'")
   140          }
   141  
   142          def proxy = config.proxy ? config.proxy : script.env.HTTP_PROXY
   143  
   144          def responseExtDescriptorUpload = 'responseExtDescriptorUpload.txt'
   145  
   146          def responseCode = script.sh returnStdout: true,
   147                                       script: """|#!/bin/sh -e
   148                                                  | curl ${proxy ? '--proxy ' + proxy + ' ' : ''} \\
   149                                                  |      --write-out '%{response_code}' \\
   150                                                  |      -H 'Authorization: Bearer ${token}' \\
   151                                                  |      -H 'tms-named-user: ${namedUser}' \\
   152                                                  |      -F 'file=@${file}' \\
   153                                                  |      -F 'mtaVersion=${mtaVersion}' \\
   154                                                  |      -F 'description=${description}' \\
   155                                                  |      --output ${responseExtDescriptorUpload} \\
   156                                                  |      '${url}/v2/nodes/${nodeId}/mtaExtDescriptors'""".stripMargin()
   157  
   158          return jsonUtils.jsonStringToGroovyObject(getResponseBody(responseExtDescriptorUpload, responseCode, '201', 'MTA Extension Descriptor upload'))
   159      }
   160  
   161      def getNodes(String url, String token) {
   162  
   163          if (config.verbose) {
   164              echo("Get nodes started. URL: '${url}'")
   165          }
   166  
   167          def parameters = [
   168              url          : "${url}/v2/nodes",
   169              httpMode     : "GET",
   170              contentType  : 'APPLICATION_JSON',
   171              customHeaders: [
   172                  [
   173                      maskValue: true,
   174                      name     : 'authorization',
   175                      value    : "Bearer ${token}"
   176                  ]
   177              ]
   178          ]
   179  
   180          def proxy = config.proxy ? config.proxy : script.env.HTTP_PROXY
   181  
   182          if (proxy){
   183              parameters["httpProxy"] = proxy
   184          }
   185  
   186          def response = sendApiRequest(parameters)
   187          if (response.status != 200) {
   188              prepareAndThrowException(response, "Get nodes failed (HTTP status code '${response.status}').")
   189          }
   190  
   191          if (config.verbose) {
   192              echo("Get nodes successful. Response content '${response.content}'.")
   193          }
   194  
   195          return jsonUtils.jsonStringToGroovyObject(response.content)
   196      }
   197  
   198      def updateMtaExtDescriptor(String url, String token, Long nodeId, Long idOfMtaExtDescriptor, String file, String mtaVersion, String description, String namedUser) {
   199  
   200          echo("MTA Extension Descriptor update started.")
   201  
   202          if (config.verbose) {
   203          echo("URL: '${url}', NodeId: '${nodeId}', IdOfMtaDescriptor: '${idOfMtaExtDescriptor}', File: '${file}', MtaVersion: '${mtaVersion}'")
   204          }
   205  
   206          def proxy = config.proxy ? config.proxy : script.env.HTTP_PROXY
   207  
   208          def responseExtDescriptorUpdate = 'responseExtDescriptorUpdate.txt'
   209  
   210          def responseCode = script.sh returnStdout: true,
   211                                       script: """|#!/bin/sh -e
   212                                                  | curl ${proxy ? '--proxy ' + proxy + ' ' : ''} \\
   213                                                  |      --write-out '%{response_code}' \\
   214                                                  |      -H 'Authorization: Bearer ${token}' \\
   215                                                  |      -H 'tms-named-user: ${namedUser}' \\
   216                                                  |      -F 'file=@${file}' \\
   217                                                  |      -F 'mtaVersion=${mtaVersion}' \\
   218                                                  |      -F 'description=${description}' \\
   219                                                  |      --output ${responseExtDescriptorUpdate} \\
   220                                                  |      -X PUT \\
   221                                                  |      '${url}/v2/nodes/${nodeId}/mtaExtDescriptors/${idOfMtaExtDescriptor}'""".stripMargin()
   222  
   223          return jsonUtils.jsonStringToGroovyObject(getResponseBody(responseExtDescriptorUpdate, responseCode, '200', 'MTA Extension Descriptor update'))
   224      }
   225  
   226      def getMtaExtDescriptor(String url, String token, Long nodeId, String mtaId, String mtaVersion) {
   227          echo("Get MTA Extension Descriptor started.")
   228  
   229          if (config.verbose) {
   230              echo("URL: '${url}', NodeId: '${nodeId}', MtaId: '${mtaId}', MtaVersion: '${mtaVersion}'")
   231          }
   232  
   233          def parameters = [
   234              url          : "${url}/v2/nodes/${nodeId}/mtaExtDescriptors?mtaId=${mtaId}&mtaVersion=${mtaVersion}",
   235              httpMode     : "GET",
   236              contentType  : 'APPLICATION_JSON',
   237              customHeaders: [
   238                  [
   239                      maskValue: true,
   240                      name     : 'authorization',
   241                      value    : "Bearer ${token}"
   242                  ]
   243              ]
   244          ]
   245  
   246          def proxy = config.proxy ? config.proxy : script.env.HTTP_PROXY
   247  
   248          if (proxy){
   249              parameters["httpProxy"] = proxy
   250          }
   251  
   252          def response = sendApiRequest(parameters)
   253          if (response.status != 200) {
   254              prepareAndThrowException(response, "Get MTA Extension Descriptor failed (HTTP status code '${response.status}').")
   255          }
   256  
   257          if (config.verbose) {
   258              echo("Response content '${response.content}'.")
   259          }
   260  
   261          // because the API is called with params, the return is always a map with either a empty list or a list containing one element
   262          Map mtaExtDescriptor = [:]
   263          Map responseContent = jsonUtils.jsonStringToGroovyObject(response.content)
   264          if(responseContent.get("mtaExtDescriptors")) {
   265              mtaExtDescriptor = responseContent.get("mtaExtDescriptors").get(0);
   266          }
   267  
   268          echo("Get MTA Extension Descriptor successful.")
   269          return mtaExtDescriptor
   270      }
   271  
   272      private sendApiRequest(parameters) {
   273          def defaultParameters = [
   274              acceptType            : 'APPLICATION_JSON',
   275              quiet                 : !config.verbose,
   276              consoleLogResponseBody: false, // must be false, otherwise this reveals the api-token in the auth-request
   277              ignoreSslErrors       : true,
   278              validResponseCodes    : "100:599"
   279          ]
   280  
   281          return script.httpRequest(defaultParameters + parameters)
   282      }
   283  
   284      private prepareAndThrowException(response, errorMessage) {
   285          if (response.status >= 300) {
   286              errorMessage += " Response content '${response.content}'."
   287          }
   288          script.error "[${getClass().getSimpleName()}] ${errorMessage}"
   289      }
   290  
   291      private echo(message) {
   292          script.echo "[${getClass().getSimpleName()}] ${message}"
   293      }
   294  
   295      private static String urlEncodeAndReplaceSpace(String data) {
   296          return URLEncoder.encode(data, "UTF-8").replace('%20', '+')
   297      }
   298  
   299  
   300      private String getResponseBody(String responseFileName, String actualStatus, String expectStatus, String action) {
   301          def responseBody = 'n/a'
   302  
   303          boolean gotResponse = script.fileExists(responseFileName)
   304          if(gotResponse) {
   305              responseBody = script.readFile(responseFileName)
   306              if(config.verbose) {
   307                  echo("Response body: ${responseBody}")
   308              }
   309          }
   310  
   311          if (actualStatus != expectStatus) {
   312              def message = "Unexpected response code received from ${action} (${actualStatus}). ${expectStatus} expected."
   313              echo "${message} Response body: ${responseBody}"
   314              script.error message
   315          }
   316  
   317          echo("${action} successful.")
   318  
   319          if (! gotResponse) {
   320              script.error "Cannot provide response for ${action}."
   321          }
   322          return responseBody
   323      }
   324  }