Triggers a work-claiming cycle. If smart balancing is enabled, claim work based
on node and cluster load. If simple balancing is in effect, claim by count.
420549
public void claimWork() throws InterruptedException {
        if (state.get() == NodeState.Started && !waitInProgress.get() && connected.get()) {
            balancingPolicy.claimWork();
        }
    }
181727
private boolean isAddToLoadBalancerSuspended(AutoScalingGroup asg) {
        List<SuspendedProcess> suspendedProcesses = asg.getSuspendedProcesses();
        for (SuspendedProcess process : suspendedProcesses) {
            if (PROP_ADD_TO_LOAD_BALANCER.equals(process.getProcessName())) {
                return true;
            }
        }
        return false;
    }
1149356
int claimResource(ZooKeeper zookeeper, String poolNode, int poolSize)
            throws KeeperException, InterruptedException {

        logger.debug("Trying to claim a resource.");
        List<String> claimedResources = zookeeper.getChildren(poolNode, false);
        if (claimedResources.size() >= poolSize) {
            logger.debug("No resources available at the moment (pool size: {}), waiting.", poolSize);
            // No resources available. Wait for a resource to become available.
            final CountDownLatch latch = new CountDownLatch(1);
            zookeeper.getChildren(poolNode, event -> latch.countDown());
            latch.await();
            return claimResource(zookeeper, poolNode, poolSize);
        }

        // Try to claim an available resource.
        for (int i = 0; i < poolSize; i++) {
            String resourcePath = Integer.toString(i);
            if (!claimedResources.contains(resourcePath)) {
                String node;
                try {
                    logger.debug("Trying to claim seemingly available resource {}.", resourcePath);
                    node = zookeeper.create(
                            poolNode + "/" + resourcePath,
                            new byte[0],
                            ZooDefs.Ids.OPEN_ACL_UNSAFE,
                            CreateMode.EPHEMERAL
                    );
                } catch (KeeperException e) {
                    if (e.code() == KeeperException.Code.NODEEXISTS) {
                        // Failed to claim this resource for some reason.
                        continue;
                    } else {
                        // Unexpected failure.
                        throw e;
                    }
                }

                zookeeper.exists(node, event -> {
                    if (event.getType() == EventType.NodeDeleted) {
                        // Invalidate our claim when the node is deleted by some other process.
                        logger.debug("Resource-claim node unexpectedly deleted ({})", resource);
                        close(true);
                    }
                });

                logger.debug("Successfully claimed resource {}.", resourcePath);
                return i;
            }
        }

        return claimResource(zookeeper, poolNode, poolSize);
    }
738066
private void runSelectTask()
  {
    if (_lifecycle.isActive() || _lifecycle.isAfterStopping()) {
      log.warning(this + " cannot start because an instance is active");
      return;
    }

    initNative(_fd);

    synchronized (_thread) {
      _thread.notify();
    }

    if (! _lifecycle.toActive()) {
      log.warning(this + " invalid starting state");
      return;
    }

    runImpl();
  }
834860
def run(cluster, started_by: nil, **args)
      overrides_json = json_generator.generate_override_json(**args)
      info = Ecs.run_task(cluster.name, register,
                          started_by: started_by,
                          overrides_json: overrides_json)
      info.fetch("tasks")[0].fetch("taskArn")
    end
515593
function() {
			var pending	= this.pending,
				script;

			for(var name in pending) {
				if (!pending.hasOwnProperty(name)) { continue; }
				var cycle = pending[name].cycle();
				if (cycle) {
					cycle[0].allow(cycle[1]);
					this.load(cycle[0]);
					return true;
				}
			}
		}
39008
def on_discovery_add(self, discovery):
        
        discovery.connect()

        for cluster in self.configurables[Cluster].values():
            if cluster.discovery != discovery.name:
                continue

            self.launch_thread(
                cluster.name, discovery.start_watching,
                cluster, self.sync_balancer_files
            )

        self.sync_balancer_files()
1318706
private boolean isAddToLoadBalancerSuspended(String asgAccountId, String asgName) {
        AutoScalingGroup asg;
        if(asgAccountId == null || asgAccountId.equals(accountId)) {
            asg = retrieveAutoScalingGroup(asgName);
        } else {
            asg = retrieveAutoScalingGroupCrossAccount(asgAccountId, asgName);
        }
        if (asg == null) {
            logger.warn("The ASG information for {} could not be found. So returning false.", asgName);
            return false;
        }
        return isAddToLoadBalancerSuspended(asg);
    }
1135778
protected boolean addWork(final ForkJoinContext<?> context) {
	requireNotStopped(this);

	final boolean result = workQueue.addWaitingWork(context);
	if (result) {
	    addWorkerIfNeeded();
	}

	return result;
    }
277017
function() {
            if (_.size(this.tasks) > 0) {
                this.empty = false;
                var task = this.tasks.shift();
                this.startTask(task);
                this.trigger("tasks:next");
            } else {
                this.empty = true;
                this.trigger("tasks:finish");
            }      
        }
290139
def claim(task, force = false)
      raise UnauthorizedClaimAttempt unless has_role?(task.role)
      release!(task) if force
      task.claim(claim_token)
    end
903344
@SuppressWarnings("squid:S2142")
    @Override
    public void run() {
        try {
            log.finest("Starting IOBalancer thread");
            long nextRebalanceMs = currentTimeMillis() + balancerIntervalMs;
            while (!shutdown) {
                for (; ; ) {
                    long maxPollDurationMs = nextRebalanceMs - currentTimeMillis();
                    Runnable task = maxPollDurationMs <= 0 ? workQueue.poll() : workQueue.poll(maxPollDurationMs, MILLISECONDS);
                    if (task == null) {
                        // we are finished with taking task from the queue, lets
                        // do a bit of rebalancing.
                        break;
                    }
                    task.run();
                }

                ioBalancer.rebalance();
                nextRebalanceMs = currentTimeMillis() + balancerIntervalMs;
            }
        } catch (InterruptedException e) {
            log.finest("IOBalancer thread stopped");
            //this thread is about to exit, no reason restoring the interrupt flag
            ignore(e);
        } catch (Throwable e) {
            log.severe("IOBalancer failed", e);
        }
    }
177686
protected void claimWorkPeggedToMe(String workUnit)
       throws InterruptedException {
       String path = cluster.workUnitClaimPath(workUnit);

       while (true) {
           if (ZKUtils.createEphemeral(cluster.zk, path, cluster.myNodeID) || cluster.znodeIsMe(path)) {
               cluster.startWork(workUnit);
               return;
           }
           LOG.warn("Attempting to establish ownership of {}. Retrying in one second...", workUnit);
           Thread.sleep(1000);
       }
   }
930800
private void writeTaskClaim(Tenant tenant, String claimID, long claimStamp) {
        DBTransaction dbTran = DBService.instance(tenant).startTransaction();
        dbTran.addColumn(TaskManagerService.TASKS_STORE_NAME, claimID, m_hostClaimID, claimStamp);
        DBService.instance(tenant).commit(dbTran);
    }
1007606
def has_pending(self):
        
        if self.workqueue:
            return True

        for assigned_unit in self.assigned_work.values():
            if self._pending_of(assigned_unit) > 0:
                return True

        return False
249673
def on_cluster_add(self, cluster):
        
        if cluster.discovery not in self.configurables[Discovery]:
            return

        discovery = self.configurables[Discovery][cluster.discovery]

        self.launch_thread(
            cluster.name, discovery.start_watching,
            cluster, self.sync_balancer_files
        )
431644
public static ResourceClaim claimExpiring(ZooKeeperConnection zooKeeperConnection, int poolSize, String znode)
            throws IOException {
        return claimExpiring(zooKeeperConnection, poolSize, znode, DEFAULT_TIMEOUT);
    }