get info

get all

all items information

import org.jenkins.plugins.lockableresources.LockableResourcesManager

LockableResourcesManager manager = new org.jenkins.plugins.lockableresources.LockableResourcesManager()
// or LockableResourcesManager manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()

manager.getResources().each{ r ->
  println """
    ${r.name}: ${r.getClass()}
              locked? : ${r.locked} : ${r.isLocked()}
            reserved? : ${r.reserved} : ${r.isReserved()}
                label : ${r.labels} : ${r.getLabels()}
          description : ${r.description} : ${r.getDescription()}
                queue : ${r.queueItemProject ?: ''}
          reserved by : ${r.reservedBy ?: ''}
                build : ${r.build ?: ''}
       queuingStarted : ${r.queuingStarted ?: ''}
       queuedContexts : ${r.queuedContexts ?: ''}

"""
}

labels

import org.jenkins.plugins.lockableresources.LockableResourcesManager

stage('all label') {
  println '~~> all labels:'
  println new LockableResourcesManager().getAllLabels()
}

resources

import org.jenkins.plugins.lockableresources.LockableResourcesManager
println new LockableResourcesManager().getResources()
  • or
    println org.jenkins.plugins.lockableresources.LockableResourcesManager.get().getResources()
    

Get resource by label

import org.jenkins.plugins.lockableresources.LockableResourcesManager

stage('get label') {
  String l = 'my-label'
  println "~~> resources for ${l}:"
  println new LockableResourcesManager().getResourcesWithLabel( l, null )
}
  • or
    import org.jenkins.plugins.lockableresources.LockableResourcesManager
    println new LockableResourcesManager().getResourcesWithLabel( l, [:] )
    

if label validated

import org.jenkins.plugins.lockableresources.LockableResourcesManager

stage('does label validated') {
  String l = 'my-label'
  println '~~> is ${l} valid:'
  println new LockableResourcesManager().isValidLabel(l)
}

Get free number of label

import org.jenkins.plugins.lockableresources.LockableResourcesManager

stage('number of free') {
  String l = 'my-label'
  println new LockableResourcesManager().getFreeResourceAmount(l)
}

Get all resource

stage('get all resoruces') {
  def all_lockable_resources = GlobalConfiguration.all().get(org.jenkins.plugins.lockableresources.LockableResourcesManager.class).resources

  println "~~> free resource for ${l}"
  println all_lockable_resources
  // remove
  all_lockable_resources.removeAll { it.name.contains('somestr')}
}

management

remove by label (or name)

stage('remove') {
    def manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()
    def resources = manager.getResources().findAll {
        // println it.locked ? "${it} locked" : "${it.labels}"
        ( !it.locked ) && (
            it.name.equals('marslo') ||
            it.labels.contains('marslo') ||
            it.name.startsWith('marslo')
        )
    }
    currentBuild.description = "${resources.size()} locks"
    resources.each {
        println "Removing ${it.name} ~~> ${it.labels}"
        manager.getResources().remove(it)
    }
    manager.save()
}
  • remove all
    String lockName = 'lock name'
    def manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()
    manager.getResources().removeAll { r -> lockNames.contains(r.name) && !r.locked && !r.reserved }
    manager.save()
    

create new item

stage('create') {
  def manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()
  def myr = manager.createResourceWithLabel('marslo', 'marslo-label')
}
  • or

    import org.jenkins.plugins.lockableresources.*
    
    stage('create') {
      LockableResourcesManager manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()
      String name  = 'marslo'
      String label = 'marslo-label'
    
      manager.createResource( name )
      manager.fromName(name).setLabels( label )
      manager.fromName(name).setEphemeral( false )
      manager.save()
    }
    

pickup qualified available resources randomly

[!TIP]

setup test labels

import org.jenkins.plugins.lockableresources.*

LockableResourcesManager manager = org.jenkins
                                      .plugins
                                      .lockableresources
                                      .LockableResourcesManager
                                      .get()
manager.createResourceWithLabel('marslo-test-1', 'windows,64bit,firefox')
manager.createResourceWithLabel('marslo-test-2', 'CentOS,32bit,chrome')
manager.createResourceWithLabel('marslo-test-3', 'RHEL,64bit,firefox')

clean up environment

import org.jenkins.plugins.lockableresources.*

LockableResourcesManager manager = org.jenkins
                                      .plugins
                                      .lockableresources
                                      .LockableResourcesManager
                                      .get()
(1..3).each {
  manager.resources.remove( manager.fromName("marslo-test-${it}") )
}
import org.jenkins.plugins.lockableresources.*

LockableResourcesManager manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()

List criteria = [ '64bit', 'firefox' ]
List all = manager.resources.findAll { r ->
    !r.locked &&
    !r.reserved &&
    criteria.every{ c -> r.labels.split(',').collect{ it.toLowerCase() }.contains(c.toLowerCase()) }
  }
Collections.shuffle(all)
println (all?.first() ?: '')

change label by certain condition

Objective :

add the keyword marslo_ as prefix of labels whose label isn't belongs to keyword list.

prevent repeat to add :

  • List keyword = [ 'project1', 'project2', 'keyword', 'marslo_' ]
  • or
  • r.setLabels( 'marslo_' + r.labels.split('marslo_').last() )

import org.jenkins.plugins.lockableresources.*

LockableResourcesManager manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()
List keyword = [ 'project1', 'project2', 'keyword' ]

manager.getResources().findAll { r ->
  r.labels && ! keyword.any{ r.labels.toLowerCase().startsWith(it) }
}.collect { r ->
  r.setLabels( 'marslo_' + r.labels.split('marslo_').last() )
}
  • show result
    println manager.resources.findAll { r ->
      r.labels && ! keyword.any{ r.labels.toLowerCase().startsWith(it) }
    } collect {
      [ (r.name), r.labels ]
    }
    

reserve & unlock

by cli

$ resource='marslo'
$ curl -XGET -uadmin:passwd https://my.jenkins.com/lockable-resources/reserve?resource=${resource}
$ curl -XGET -uadmin:passwd https://my.jenkins.com/lockable-resources/unreserve?resource=${resource}

by api

stage('reserve & unlock') {
    def manager = org.jenkins.plugins.lockableresources.LockableResourcesManager.get()
    println manager.fromName('marslo')?.isReserved()

    println '~~> lock marslo:'
    manager.reserve([ manager.fromName('marslo') ], 'Marslo Jiao')
    println manager.fromName('marslo')?.isReserved()

    println '~~> unlock marslo:'
    manager.reset([ manager.fromName('marslo') ])
    println manager.fromName('marslo')?.isReserved()
}

examples

print "START\n"
def all_lockable_resources = org.jenkins.plugins.lockableresources.LockableResourcesManager.get().resources
all_lockable_resources.each { r->
  if ( r.isLocked() || r.isReserved() ) {
    println "Lock " + r + " is locked or reserved by " + r.getBuild() + " BECARSE " + r.getLockCause()

    b = r.getBuild()

    if ( b ) {
      if ( b.isBuilding() )             println ( "build:" + b + " is building" )
      if ( b.getResult().equals(null) ) println ( "build:" + b + " result is not in yet" )

      if ( ! b.isBuilding() && ! b.getResult().equals(null) ) {
        println "build:" + b + " is not building and result is " + b.getResult() + " yet the lock " + r + " is locked."

        println "ACTION RELEASE LOCK " + r
        println "getLockCause:"   + r.getLockCause()
        println "getDescription:" + r.getDescription()
        println "getReservedBy:"  + r.getReservedBy()
        println "isReserved:"     + r.isReserved()
        println "isLocked:"       + r.isLocked()
        println "isQueued:"       + r.isQueued()

        //release the lock
        r.reset()

        println "getLockCause:"   + r.getLockCause()
        println "getDescription:" + r.getDescription()
        println "getReservedBy:"  + r.getReservedBy()
        println "isReserved:"     + r.isReserved()
        println "isLocked:"       + r.isLocked()
        println "isQueued:"       + r.isQueued()
      }

    }
  }
}

functions

isLabelExists

def isLabelExists( String label ) {
  org.jenkins.plugins
     .lockableresources
     .LockableResourcesManager
     .get()
     .getResources()
     .findAll{ it.labels == label } != []
}
  • or
    withManager{ manager ->
      manager
        .resources
        .findAll{ it.labels == label } != []
    }
    

isResourceExists

def isResourceExists( String name ) {
  org.jenkins.plugins
     .lockableresources
     .LockableResourcesManager
     .get()
     .fromName(name) != null
}
  • or
    def isResourceExists( String name ) {
      withManager{ manager -> manager.fromName(name) != null }
    }
    
  • or using findAll for multiple find
    def isResourceExists( String name ) {
      org.jenkins.plugins
         .lockableresources
         .LockableResourcesManager
         .get()
         .getResources()
         .findAll{ it.name == name } != []
    }
    
    • or
      withManager{ manager ->
        manager.getResources()
               .findAll{ it.name == name } != []
      }
      

get label by name

  • using fromName(String)

    def getLabelByName( String name ) {
      org.jenkins.plugins
         .lockableresources
         .LockableResourcesManager
         .get()
         .getResources()
         .fromName( name )
         .getLabes()
    }
    
    • or
      def getLabelByName( String name ) {
        withManager{ manager -> manager.fromName( name )?.labels ?: '' }
      }
      
  • using findAll multiple

    def getLabelByName( String name ) {
      org.jenkins.plugins
         .lockableresources
         .LockableResourcesManager
         .get()
         .getResources()
         .findAll{ it.name == name }
         .collect{ it.labels }
         .join(' ')
    }
    
    • or
      withManager{ manager ->
        manager.getResources()
               .findAll{ it.name == name }
               .collect{ it.labels }
               .join(' ')
      }
      

set Label

def setLabel( String name, String label, String trigger = '', Boolean force = false, String description = '' ) {
  LockableResourcesManager manager = LockableResourcesManager.get()
  description   = ( description ? "${description} | " : '' ) +
                  "created automatically by @${trigger ?: 'jenkins'} via Jenkins job ${env.BUILD_URL}"
  if ( isResourceExists(name) && !force ) {
    println( "ERROR: resource ${name} has already tied to label: ${manager.fromName(name)?.labels}. Exit..." )
  } else {
    // manager.createResourceWithLabel( name, label )     // will ignore label re-add if resource exists
    if ( ! isResourceExists(name) ) manager.createResource( name )
    manager.fromName(name).setLabels( label )
    manager.fromName(name).setDescription( description )
    manager.fromName(name).setEphemeral( false )
    manager.save()
    if ( ! isResourceExists(name) ) println( "ERROR: resource ${name} failed to be added in resource pool. Exit..." )
  }
}

with Closure

import org.jenkins.plugins.lockableresources.LockableResourcesManager

def withManager( Closure body ) {
  LockableResourcesManager manager = org.jenkins.plugins
                                                .lockableresources
                                                .LockableResourcesManager
                                                .get()
  body( manager )
}

get resource status

def getResourceLabelStatus( String name ) {
  Map status = [:]
  withManager { manager ->
    if ( isResourceExists(name) ) {
      LockableResource r   = manager.fromName(name)
      status.'locked'      = r.isLocked()
      status.'reserved'    = r.isReserved()
      status.'lockedBy'    = r.getBuild()      ?: ''
      status.'reservedBy'  = r.getReservedBy() ?: ''
      status.'lockedCause' = r.getLockCause()  ?: ''
    }
  }
  return status
}

removeLabelByName

/**
 * remove the label from resource pool if the label isn't reserved or locked
 *
 * @param name       the agent name
 * @param force      whether force remove the label or not
 *
 * @see              <a href="https://javadoc.jenkins.io/plugin/lockable-resources/org/jenkins/plugins/lockableresources/LockableResourcesManager.html">org.jenkins.plugins.lockableresources.LockableResourcesManager</a>
 * @see              <a href="https://javadoc.jenkins.io/plugin/lockable-resources/org/jenkins/plugins/lockableresources/LockableResource.html">org.jenkins.plugins.lockableresources.LockableResource</a>
 * @see              {@link #withManager(Closure)}
**/
def removeLabelByName( String name, Boolean force = false ) {
  withManager { manager ->

    if ( isResourceExists(name) ) {
      if ( force ) manager.fromName(name).reset()
      Map resource = getResourceLabelStatus( name )
      if ( ! resource.getOrDefault('locked', true) && ! resource.getOrDefault('reserved', true) ) {
        if ( manager.resources.remove( manager.fromName(name) ) && !isResourceExists(name) ) {
          println ( "INFO: resource ${name} has been successfully removed." )
        } else {
          println ( "WARN: resource ${name} failed to be removed. still tied to label: ${getLabelByName(name)}" )
        }
      } else {
        println ( "WARN: resource ${name} ( label: ${getLabelByName(name)} ) cannot be removed due to " +
                  ( resource.locked   ? "locked by ${resource.lockedBy}"     : '' ) +
                  ( resource.reserved ? "reserved by ${resource.reservedBy}" : '' )
      }
    } else {
      println( "WARN: resource ${name} doesn't exist in resrouce pool. Skip..." )
      println( "Available resources are: ${manager.resources}" )
    }

  } // withManager
}
Copyright © marslo 2020-2023 all right reserved,powered by GitbookLast Modified: 2024-03-12 15:01:28

results matching ""

    No results matching ""