检查资源是否被锁定

check if a resource is locked

我通常会在我的声明性管道中锁定资源,例如:

lock(resource: "MY_RESOURCE") {
   // do something
}

但现在我有几个不同的资源可以使用,有没有办法检查资源是否被锁定?

我想做这样的事情:

myResources = ["RES1", "RES2", "RES3"]
hasResource = false
for (resource in myResources) {
   if (hasresource) {
      break
   }
   if (!isLocked(resource)) {
      hasresource = true
      lock(resource) {
         // do something
      }
   }
}

(对不起,如果语法错误,我真的不经常在 groovy 中编程)

根据锁插件的来源,这应该有效:

import org.jenkins.plugins.lockableresources.LockableResourcesManager as LRM

def myResources = ["RES1", "RES2", "RES3"]
def notLocked = myResources.find{rName-> 
    LRM.get().forName(rName).with{ r-> !r.isLocked() && !r.isQueued() }
}
if(notLocked){
    lock(notLocked){
        //do smth
    }
}

检查特定资源是否在 jenkins 中被锁定

def manager = org.jenkins.plugins.lockableresources.LockableResourcesManager
def myResources = manager.get().fromName("test2")
//def myLabels = manager.get().allLabels // if you want to filter based on labels
def checkLocked = myResources.find { r -> 
                            !r.isLocked() && !r.isQueued() }
                            
                            if (checkLocked) {
                               def myResource = checkLocked.toString()
                               
                               println myResource + "is locked"
                               
                            }
                            else {
                            println "Specified Resource is not Locked"
                            }

也许不是最佳解决方案,但我们通过以下方法设法实现了这一点:

waitUntil {
  lock(resource: 'RES1', skipIfLocked: true){
    // do something with RES1
    return true; // exit the waiting loop
  }
  lock(resource: 'RES2', skipIfLocked: true){
    // do something with RES2
    return true; // exit the waiting loop
  }
  lock(resource: 'RES3', skipIfLocked: true){
    // do something with RES3
    return true; // exit the waiting loop
  }
}

我们这样做是因为我们在尝试使用已接受的答案时收到以下错误:

Scripts not permitted to use staticMethod org.jenkins.plugins.lockableresources.LockableResourcesManager get