如何在管道脚本中使Jenkins节点脱机

时间:2018-07-03 10:53:12

标签: jenkins continuous-integration jenkins-pipeline

我们要在开始耗时的集成测试之前验证Jenkins节点是否正常。如果节点不健康,我们希望将其脱机,以便有人可以连接并修复它。

1 个答案:

答案 0 :(得分:0)

经过反复尝试,我最终得到了以下解决方案:

def ExecuteTestsOnSelectedNode() {
     stage("integrationtests") {
         testSystemVerified = false
         while(!testSystemVerified) { // Retry if test system verification failed -  hopefully another node can execute this test...    
             node("nodelabel") {
                 // ... code for unstashing test assemblies omitted
                 try {
                     testSystemVerified = checkTestSystem(info, testSetup, testAssemblies);
                 }
                 catch (Exception e) {
                     echo "!!!!!!!!!!!!!!!!!! Test system verification failed !!!!!!!!!!!!!!!!!!!!!!!!\n" + e
                     throw e
                 }
                 if (testSystemVerified) {
                     // Then it is safe to execute the actual tests
                 }                  
             }
         }
     }
}

def checkTestSystem(info, testSetup, testAssemblies) {
    try {            
        // Execute some command that (quickly) verifies the health of the node
        bat "$info.test_runner $test_args"
        return true // If we get here the test system is OK
    }
    catch (hudson.AbortException e) {
        message = "!!!!!!!!!!!!!!!!!! Test system verification aborted !!!!!!!!!!!!!!!!!!!!!!!!\n" + e
        echo message
        throw e
    }
    catch (Exception e) {
        message = "!!!!!!!!!!!!!!!!!! Test system verification failed !!!!!!!!!!!!!!!!!!!!!!!!\n" + e
        echo message
        markNodeOffline(message)
        return false
    }
}

@NonCPS
def markNodeOffline(message) {
    node = getCurrentNode(env.NODE_NAME)
    computer = node.toComputer()
    computer.setTemporarilyOffline(true)
    computer.doChangeOfflineCause(message)
    computer = null
    node = null
}

@NonCPS
def getCurrentNode(nodeName) {
  for (node in Jenkins.instance.nodes) {
      if (node.getNodeName() == nodeName) {
        echo "Found node for $nodeName"
        return node
    }
  }
  throw new Exception("No node for $nodeName")
}