Daniel Klöck
Daniel Klöck

Reputation: 21147

check if a resource is locked

I usually lock resources in my declarative pipeline with something like:

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

but now I have several different resources I could use, is there a way to check if a resource is locked?

I would like to do something like:

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

(sorry if the syntax is wrong, I don't really program in groovy very often)

Upvotes: 3

Views: 3599

Answers (3)

smukov
smukov

Reputation: 625

Maybe not an optimal solution, but we managed to achieve this with following approach:

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
  }
}

We did it this way due to the following error we received when we tried to use the accepted answer:

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

Upvotes: 1

Prasoon Mishra
Prasoon Mishra

Reputation: 1

To Check if a particular resource is locked or not in 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"
                            }

Upvotes: 0

daggett
daggett

Reputation: 28634

according to the sources of lock plugin this should work:

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
    }
}

Upvotes: 4

Related Questions