groovy 在此脚本中,如果requestState id PENDING每次都在2mminutes后重复该阶段,并且如果其未挂起,则应停止

x8diyxa7  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(71)

在此脚本中,如果requestState id PENDING每次在2分钟后重复该阶段,并且如果其未挂起则应停止。

pipeline {
  agent {
    label "cicd-npe-slave0"
  }
  options {
    buildDiscarder(logRotator(numToKeepStr: '20'))
    disableConcurrentBuilds()
  }
  parameters {
    string(name: 'access_token', defaultValue: '')
    string(name: 'body', defaultValue: '')
  }
  stages {
    stage('Execute curl command') {
      steps {
        script {
          def response = sh(script: '''curl --location 'URL' \\
            --header 'Content-Type: application/json' \\
            --header 'Authorization: Bearer xxx' \\
            --data '{
              xxxx
             }' ''', returnStdout: true).trim()
             println(response)
             def jsonSlurper = new groovy.json.JsonSlurper()
             def jsonResponse = jsonSlurper.parseText(response)
             requestState = jsonResponse.response.requestState
             echo "Request State = '${requestState}'"
        }
      }
    }
  }
}

我尝试了很多东西,得到下面的错误,为上述脚本,如果我是添加睡眠intervels

Caused: java.io.NotSerializableException: groovy.json.internal.LazyMap
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:274)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)

Finished: FAILURE
ukdjmx9f

ukdjmx9f1#

这是一个有效的解决方案,请根据您的需要进行调整。

pipeline {
  agent any
  options {
    buildDiscarder(logRotator(numToKeepStr: '20'))
    disableConcurrentBuilds()
  }
  parameters {
    string(name: 'access_token', defaultValue: '')
    string(name: 'body', defaultValue: '')
  }
  stages {
    stage('Execute curl command') {
      steps {
        script {
          timeout(180) {
                waitUntil {
                   script {
                      def response = sh(script: '''curl --location 'http://demo5333947.mockable.io/hello' \\
                     --header 'Content-Type: application/json' \\
                     --header 'Authorization: Bearer xxx' \\
                     --data '{}' ''', returnStdout: true).trim()
                      println(response)
                      def requestState = getState(response);
                      echo "Request State = '${requestState}'"
                      if(requestState.equals('PENDING')) {
                        sleep 120; // sleep for 2 mins
                        return false;
                      } else {
                        return true;
                      }
                   }
                }
            }
        }
      }
    }
  }
}

def getState(response) {
    def jsonSlurper = new groovy.json.JsonSlurper()
    def jsonResponse = jsonSlurper.parseText(response)
    println jsonResponse.response
    def requestState = jsonResponse.response.requestState
    return requestState
}

相关问题