Provision slave container and wait for it's availability.
322885
private void provisionWithWait(DockerComputerSingle computer, TaskListener listener)
            throws Exception {
        final PrintStream logger = listener.getLogger();

        final Run run = computer.getRun();
        final DockerSlaveSingle slave = computer.getNode();
        if (isNull(slave)) {
            throw new IllegalStateException("Can't get slave for " + computer.getNode());
        }
        final DockerClient client = slave.getConnector().getClient();
        final DockerContainerLifecycle containerLifecycle = slave.getConfig().getDockerContainerLifecycle();

        final String imageId = containerLifecycle.getImage();

        //pull image
        logger.println("Pulling image " + imageId + "...");
        containerLifecycle.getPullImage().exec(client, imageId, listener);

        logger.println("Trying to create container for " + imageId);
        LOG.info("Trying to create container for {}", imageId);
        final DockerCreateContainer createContainer = containerLifecycle.getCreateContainer();
        CreateContainerCmd containerConfig = client.createContainerCmd(imageId);
        // template specific options
        createContainer.fillContainerConfig(containerConfig, null);

        // cloud specific options
        appendContainerConfig(containerConfig);

        // create
        CreateContainerResponse createResp = containerConfig.exec();
        String cId = createResp.getId();
        setContainerId(cId);
        logger.println("Created container " + cId + ", for " + run.getDisplayName());
        LOG.debug("Created container {}, for {}", cId, run.getDisplayName());
        // start
        StartContainerCmd startCommand = client.startContainerCmd(cId);
        startCommand.exec();
        logger.println("Started container " + cId);
        LOG.debug("Started container '{}', for '{}'.", cId, run.getDisplayName());

        boolean running = false;
        long launchTime = System.currentTimeMillis();
        while (!running &&
                TimeUnit2.SECONDS.toMillis(launchTimeout) > System.currentTimeMillis() - launchTime) {
            try {
                InspectContainerResponse inspectResp = client.inspectContainerCmd(cId).exec();
                if (isTrue(inspectResp.getState().getRunning())) {
                    logger.println("Container is running.");
                    LOG.debug("Container '{}' is running.", cId);
                    running = true;
                } else {
                    logger.println("Container is not running...");
                }
            } catch (ProcessingException ignore) {
            }
            Thread.sleep(1000);
        }

        if (!running) {
            listener.error("Failed to run container for %s, clean-up container", imageId);
            LOG.error("Failed to run container for {}, clean-up container", imageId);
            printLog(client, listener, cId);
            throw new IllegalStateException("Container is not running!");
        }

        // now real launch
        final String rootUrl = getJenkinsUrl(Jenkins.getInstance().getRootUrl());
//        Objects.requireNonNull(rootUrl, "Jenkins root url is not specified!");
        if (isNull(rootUrl)) {
            listener.fatalError("Jenkins root url is not specified!");
            containerLifecycle.getRemoveContainer().exec(client, cId);
            throw new IllegalStateException("Jenkins root url is not specified!");
        }

        final DockerSlaveSingle node = computer.getNode();
        if (isNull(node)) {
            listener.error("Failed to run container for %s", imageId);
            printLog(client, listener, containerId);
            throw new IllegalStateException("Node for computer: '" + computer.getName() +
                    "' can't be null, probably remote node disappeared.");
        }

        // exec jnlp connection in running container
        // TODO implement PID 1 replacement
        String startCmd =
                "cat << EOF > /tmp/config.sh.tmp && cd /tmp && mv config.sh.tmp config.sh\n" +
                        "JENKINS_URL=\"" + rootUrl + NL +
                        "JENKINS_USER=\"" + getUser() + NL +
                        "JENKINS_HOME=\"" + node.getRemoteFS() + NL +
                        "COMPUTER_URL=\"" + computer.getUrl() + NL +
                        "COMPUTER_SECRET=\"" + computer.getJnlpMac() + NL +
                        "JAVA_OPTS=\"" + getJvmOpts() + NL +
                        "SLAVE_OPTS=\"" + getSlaveOpts() + NL +
                        "NO_CERTIFICATE_CHECK=\"" + isNoCertificateCheck() + NL +
                        "NO_RECONNECT_SLAVE=\"" + isNoReconnect() + NL +
                        "EOF" + "\n";

        try {
            final ExecCreateCmdResponse createCmdResponse = client.execCreateCmd(cId)
                    .withTty(true)
                    .withAttachStdin(false)
                    .withAttachStderr(true)
                    .withAttachStdout(true)
                    .withCmd("/bin/sh", "-cxe", startCmd.replace("$", "\\$"))
                    .exec();

            logger.println("Starting connection command for " + cId);
            LOG.info("Starting connection command for {}", cId);

            try (ExecStartResultCallback exec = client.execStartCmd(createCmdResponse.getId())
                    .withDetach(true)
                    .withTty(true)
                    .exec(new ExecStartResultCallback())
            ) {
                exec.awaitCompletion(10, SECONDS);
            } catch (NotFoundException ex) {
                listener.error("Can't execute command: " + ex.getMessage().trim());
                LOG.error("Can't execute jnlp connection command: '{}'", ex.getMessage().trim());
                throw ex;
            }
        } catch (Throwable ex) {
            listener.error("Can't execute command: " + ex.getMessage().trim());
            LOG.error("Can't execute jnlp connection command: '{}'", ex.getMessage().trim());
            throw ex;
        }

        LOG.info("Successfully executed jnlp connection for '{}'", cId);
        logger.println("Successfully executed jnlp connection for " + cId);

        // TODO better strategy
        launchTime = System.currentTimeMillis();
        while (computer.isReallyOffline() &&
                TimeUnit2.SECONDS.toMillis(launchTimeout) > System.currentTimeMillis() - launchTime) {
            logger.println("Waiting slave connection...");
            Thread.sleep(1000);
        }

        if (computer.isReallyOffline()) {
            LOG.info("Launch timeout, terminating slave based on '{}'", cId);
            logger.println("Launch timeout, terminating slave.");
            printLog(client, listener, cId);
            throw new IllegalStateException("Agent didn't connect after timeout.");
        }

        LOG.info("Launched slave '{}' '{}' based on '{}'",
                computer.getSlaveVersion(), computer.getName(), cId);
        logger.println("Launched slave for " + cId);
    }
90579
async def wait(self, container = None):
        '''
        
        '''
        if hasattr(self, '_result'):
            if hasattr(self, '_exception'):
                raise self._exception
            else:
                return self._result
        else:
            ev = await FutureEvent.createMatcher(self)
            if hasattr(ev, 'exception'):
                raise ev.exception
            else:
                return ev.result
150616
public void awaitAvailable() throws InterruptedException {
        synchronized (SERVICE_AVILABILITY_LOCK) {
            while (!available) {
                LOG.info("Waiting for service {} to become available...", getName());
                LOG.debug(getDependencyGraph());
                SERVICE_AVILABILITY_LOCK.wait();
            }
        }
    }
645312
private boolean waitForAvailabilityInternal() {
      final Directory directory = indexManager.getDirectoryProvider().getDirectory();
      try {
         Lock lock = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME);
         lock.close();
         return true;
      } catch (LockObtainFailedException lofe) {
         return false;
      } catch (IOException e) {
         log.error(e);
         return false;
      }
   }
181272
def wait(self, timeout=None):
    

    if not self.__running:
      raise RuntimeError("ThreadPool ain't running")
    self.__queue.wait(timeout)
96944
def _wait_event(self, reading):
        ""
        with self._registered(reading, not reading):
            (self._readable if reading else self._writable).wait()

        if scheduler.state.interrupted:
            raise IOError(errno.EINTR, "interrupted system call")
447290
private void waitForDisabled(String distId) {
        long maxTime = 1800000; // 30 min
        long start = System.currentTimeMillis();

        boolean deployed = isDeployed(distId);
        while (!deployed) {
            if (System.currentTimeMillis() < start + maxTime) {
                sleep(10000);
                deployed = isDeployed(distId);
            } else {
                String error = "Timeout Reached waiting for distribution to " +
                               "be disabled. Please wait a few minutes and try again.";
                throw new RuntimeException(error);
            }
        }
    }
677484
def wait_for_exists(self, timeout=0, *args, **selectors):
        
        return self.device(**selectors).wait.exists(timeout=timeout)
86621
def _wait_for_reader(self):
        """"""
        if self.max_size <= 0:  # Unlimited queue
            return
        if self.write_item_offset - self.cached_remote_offset <= self.max_size:
            return  # Hasn't reached max size
        remote_offset = internal_kv._internal_kv_get(self.read_ack_key)
        if remote_offset is None:
            # logger.debug("[writer] Waiting for reader to start...")
            while remote_offset is None:
                time.sleep(0.01)
                remote_offset = internal_kv._internal_kv_get(self.read_ack_key)
        remote_offset = int(remote_offset)
        if self.write_item_offset - remote_offset > self.max_size:
            logger.debug(
                "[writer] Waiting for reader to catch up {} to {} - {}".format(
                    remote_offset, self.write_item_offset, self.max_size))
            while self.write_item_offset - remote_offset > self.max_size:
                time.sleep(0.01)
                remote_offset = int(
                    internal_kv._internal_kv_get(self.read_ack_key))
        self.cached_remote_offset = remote_offset
563981
def waitStarted(self):
        """"""
        ns = None
        while not ns:
            try:
                time.sleep(3)
                ns = Pyro.naming.NameServerLocator(
                    identification=self.identification).getNS()
            except Pyro.errors.NamingError as er:
                pass
772965
def wait_until_host_is_available(host, get_ip=false)
      resolved_host = Resolv.getaddresses(host).first
      if resolved_host.nil?
        print("Waiting for #{host} to resolve")
        wait_until('ready!') { resolved_host = Resolv.getaddresses(host).first }
      end
      host = resolved_host if get_ip
      unless remote_is_available?(host)
        print("Waiting for #{host} to accept connections")
        wait_until('ready!') { remote_is_available?(host) }
      end
      return host
    end
1138283
def wait_process(self):
        """"""
        self.process.wait()
        if self.analyze_data:
            self.receiving_thread.join()
838957
def wait_for(options={}, &block)
      Wait.new(Cloudpassage::wait_options.merge(options)).until do
        instance_eval &block
      end
    end
943068
def wait(self, condition):
        
        return WebDriverWait(self.driver, self.timeout).until(condition)
512291
function doSomethingUninteresting(data) {
  // simulate latency
  var wait = randomWait(1000);
  return Promise.delay(wait).then(
    () => `It took me ${wait} milliseconds to notice you gave me ${data}.`
  );
}
1080071
public void waitForApproval(boolean isWorkspaceInitialized)
   {

      if (disabled)
      {
         if (LOG.isTraceEnabled())
         {
            LOG.trace("The RepositoryCreationSynchronizer has been disabled so no need to make it wait.");
         }
         return;
      }
      if (rpcService == null)
      {
         if (LOG.isTraceEnabled())
         {
            LOG.trace("No RPCService has been defined so we assume that we are in"
               + " a non cluster environment so no need to make it wait.");
         }
         return;
      }

      // The RPC Service has been defined so we assume that we are in a cluster environment
      if (!isWorkspaceInitialized)
      {
         // Set locally the value
         needToInitWorkspace();
         // A workspace has not been initialized, we need to notify everybody
         if (LOG.isDebugEnabled())
         {
            LOG.debug("Notify all the nodes that there is at least one workspace to initialize.");
         }
         try
         {
            rpcService.executeCommandOnAllNodes(needToInitWorkspaceCommand, false);
         }
         catch (Exception e)
         {
            LOG.warn("Could not notify all the nodes that there is at least one workspace to initialize.", e);
         }
      }
      if (lock.getCount() <= 0)
      {
         // We already have been released so no need to wait
         if (LOG.isTraceEnabled())
         {
            LOG.trace("We already have been released so no need to make it wait.");
         }
         return;
      }
      try
      {
         if (!needToInitWorkspace && isWorkspaceInitialized)
         {
            // Asking the coordinator if we have to wait since the workspace could be currently
            // initialized by the coordinator
            if (LOG.isDebugEnabled())
            {
               LOG.debug("Ask the coordinator if the local node needs to wait.");
            }
            Object result = rpcService.executeCommandOnCoordinator(shouldIWaitCommand, 0);
            if (LOG.isDebugEnabled())
            {
               LOG.debug("The response from the coordinator was " + result);
            }
            if (result instanceof Boolean && (Boolean)result)
            {
               // We wait to be release by the coordinator
               waitForCoordinator();
            }
         }
         else
         {
            // We wait to be release by the coordinator
            waitForCoordinator();
         }
      }
      catch (RPCException e)
      {
         LOG.warn("An error occured while executing the method waitForApproval()", e);
      }
   }
1362324
public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,
        CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)
        throws Exception {
        if (testClass == null) {
            // nothing to do, since we're not in ClassScoped context
            return;
        }
        if (details == null) {
            log.warning(String.format("No environment for %s", testClass.getName()));
            return;
        }
        log.info(String.format("Waiting for environment for %s", testClass.getName()));
        try {
            delay(client, details.getResources());
        } catch (Throwable t) {
            throw new IllegalArgumentException("Error waiting for template resources to deploy: " + testClass.getName(), t);
        }
    }