:raises DockerException, ContainerException, RealtimeOutedException
493703
def launch_game(
        players: List[Player],
        launch_params: Dict[str, Any],
        show_all: bool,
        read_overwrite: bool,
        wait_callback: Callable
) -> None:
    
    if not players:
        raise GameException("at least one player must be specified")

    game_dir = launch_params["game_dir"]
    game_name = launch_params["game_name"]

    if os.path.exists(f"{game_dir}/{game_name}"):
        logger.info(f"removing existing game results of {game_name}")
        shutil.rmtree(f"{game_dir}/{game_name}")

    for nth_player, player in enumerate(players):
        launch_image(player, nth_player=nth_player, num_players=len(players), **launch_params)

    logger.debug("checking if game has launched properly...")
    time.sleep(1)
    start_containers = running_containers(game_name + "_")
    if len(start_containers) != len(players):
        raise DockerException("some containers exited prematurely, please check logs")

    if not launch_params["headless"]:
        for index, player in enumerate(players if show_all else players[:1]):
            port = launch_params["vnc_base_port"] + index
            host = launch_params["vnc_host"]
            logger.info(f"launching vnc viewer for {player} on address {host}:{port}")
            launch_vnc_viewer(host, port)

        logger.info("\n"
                    "In headful mode, you must specify and start the game manually.\n"
                    "Select the map, wait for bots to join the game "
                    "and then start the game.")

    logger.info(f"waiting until game {game_name} is finished...")
    running_time = time.time()
    while True:
        containers = running_containers(game_name)
        if len(containers) == 0:  # game finished
            break
        if len(containers) >= 2:  # update the last time when there were multiple containers
            running_time = time.time()
        if len(containers) == 1 and time.time() - running_time > MAX_TIME_RUNNING_SINGLE_CONTAINER:
            raise ContainerException(
                f"One lingering container has been found after single container "
                f"timeout ({MAX_TIME_RUNNING_SINGLE_CONTAINER} sec), the game probably crashed.")
        logger.debug(f"waiting. {containers}")
        wait_callback()

    exit_codes = [container_exit_code(container) for container in containers]

    # remove containers before throwing exception
    logger.debug("removing game containers")
    remove_game_containers(game_name)

    if any(exit_code == EXIT_CODE_REALTIME_OUTED for exit_code in exit_codes):
        raise RealtimeOutedException(f"some of the game containers has realtime outed.")
    if any(exit_code == 1 for exit_code in exit_codes):
        raise ContainerException(f"some of the game containers has finished with error exit code.")

    if read_overwrite:
        logger.info("overwriting bot files")
        for nth_player, player in enumerate(players):
            if isinstance(player, BotPlayer):
                logger.debug(f"overwriting files for {player}")
                distutils.dir_util.copy_tree(
                    f"{game_dir}/{game_name}/write_{nth_player}",
                    player.read_dir
                )
475483
def execute(self, container, start=None, end=None, registers=None):
        
        if registers:
            self.__cpu.registers = dict(registers)

        ip = start if start else container[0].address

        while ip and ip != end:
            try:
                instr = container.fetch(ip)
            except ReilContainerInvalidAddressError:
                logger.info("Invalid address: {:#010x}:{:#02x}".format(ip >> 8, ip & 0xff))

                raise ReilCpuInvalidAddressError()

            next_ip = self.__execute_one(instr)

            ip = next_ip if next_ip else container.get_next_address(ip)

        return dict(self.__cpu.registers), self.__mem
140831
def scale(container_count, timeout: 10)
      args = container_count.map {|service, count| "#{service}=#{count}"}
      o = opts(timeout: [timeout, 10])
      run!('scale', o, *args)
    end
872156
def call(env)
      # Set the request data for bugsnag middleware to use
      Bugsnag.configuration.set_request_data(:rack_env, env)
      if Bugsnag.configuration.auto_capture_sessions
        Bugsnag.start_session
      end

      begin
        response = @app.call(env)
      rescue Exception => raised
        # Notify bugsnag of rack exceptions
        Bugsnag.notify(raised, true) do |report|
          report.severity = "error"
          report.severity_reason = {
            :type => Bugsnag::Report::UNHANDLED_EXCEPTION_MIDDLEWARE,
            :attributes => Bugsnag::Rack::FRAMEWORK_ATTRIBUTES
          }
        end

        # Re-raise the exception
        raise
      end

      # Notify bugsnag of rack exceptions
      if env["rack.exception"]
        Bugsnag.notify(env["rack.exception"], true) do |report|
          report.severity = "error"
          report.severity_reason = {
            :type => Bugsnag::Report::UNHANDLED_EXCEPTION_MIDDLEWARE,
            :attributes => FRAMEWORK_ATTRIBUTES
          }
        end
      end

      response
    ensure
      # Clear per-request data after processing the each request
      Bugsnag.configuration.clear_request_data
    end
278773
def _raise_timeout(self, err, url, timeout_value):
        """"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python < 2.7.4
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
770390
def _run(name,
         cmd,
         output=None,
         no_start=False,
         stdin=None,
         python_shell=True,
         preserve_state=False,
         output_loglevel='debug',
         ignore_retcode=False,
         use_vt=False,
         keep_env=None):
    '''
    
    '''
    orig_state = state(name)
    exc = None
    try:
        ret = __salt__['container_resource.run'](
            name,
            cmd,
            container_type=__virtualname__,
            exec_driver=EXEC_DRIVER,
            output=output,
            no_start=no_start,
            stdin=stdin,
            python_shell=python_shell,
            output_loglevel=output_loglevel,
            ignore_retcode=ignore_retcode,
            use_vt=use_vt,
            keep_env=keep_env)
    except Exception:
        raise
    finally:
        # Make sure we stop the container if necessary, even if an exception
        # was raised.
        if preserve_state \
                and orig_state == 'stopped' \
                and state(name) != 'stopped':
            stop(name)

    if output in (None, 'all'):
        return ret
    else:
        return ret[output]
321221
def raise_exception(self, exception):
        
        self.__data = None
        self.__exception = exception
        self.__event.set()
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);
    }
45843
def work(self):
        """"""
        try:
            raise self._error
        except TypeError:
            pass
        except Exception as e:
            _logger.warning("%r", e)
            raise
        try:
            self.lock()
            self._conn.do_work()
        except compat.TimeoutException:
            _logger.debug("Connection %r timed out while waiting for lock acquisition.", self.container_id)
        finally:
            self.release()
615507
def build(client, repository_tag, docker_file, tag=None, use_cache=False):
        
        if not isinstance(client, docker.Client):
            raise TypeError("client needs to be of type docker.Client.")

        if not isinstance(docker_file, six.string_types) or not os.path.exists(docker_file):
            # TODO: need to add path stuff for git and http etc.
            raise Exception("docker file path doesn't exist: {0}".format(docker_file))

        if not isinstance(repository_tag, six.string_types):
            raise TypeError('repository must be a string')

        if not tag:
            tag = 'latest'

        if not isinstance(use_cache, bool):
            raise TypeError("use_cache must be a bool. {0} was passed.".format(use_cache))

        no_cache = not use_cache

        if ':' not in repository_tag:
            repository_tag = "{0}:{1}".format(repository_tag, tag)
        file_obj = None
        try:
            if os.path.isfile(docker_file):
                path = os.getcwd()
                docker_file = "./{0}".format(os.path.relpath(docker_file))

                # TODO: support using file_obj in the future. Needed for post pre hooks and the injector.
                # with open(docker_file) as Dockerfile:
                #     testing = Dockerfile.read()
                #     file_obj = BytesIO(testing.encode('utf-8'))

                response = client.build(
                    path=path,
                    nocache=no_cache,
                    # custom_context=True,
                    dockerfile=docker_file,
                    # fileobj=file_obj,
                    tag=repository_tag,
                    rm=True,
                    stream=True
                )
            else:
                response = client.build(path=docker_file, tag=repository_tag, rm=True, nocache=no_cache, stream=True)
        except Exception as e:
            raise e
        finally:
            if file_obj:
                file_obj.close()

        parse_stream(response)
        client.close()

        return Image(client, repository_tag)
792752
def wait_for_web_available(self):
        
        try:
            if not wait_for_service_available(
                    self._get_container_name('web'),
                    self.web_address(),
                    WEB_START_TIMEOUT_SECONDS):
                raise DatacatsError('Error while starting web container:\n' +
                                    container_logs(self._get_container_name('web'), "all",
                                                   False, None))
        except ServiceTimeout:
            raise DatacatsError('Timeout while starting web container. Logs:' +
                                container_logs(self._get_container_name('web'), "all", False, None))
1136033
def __wrap_docker_exec(func):
    ''''''
    def call(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except OSError as e:
            if e.errno == errno.ENOENT:
                raise DockerExecuteError('Failed to execute docker. Is it installed?')
            raise
    return call
1230304
def wait(self):
        
        try:
            SpawningProxy(self.containers, abort_on_error=True).wait()
        except Exception:
            # If a single container failed, stop its peers and re-raise the
            # exception
            self.stop()
            raise
258412
def request_error!(exception)
      case exception
      when HTTP::Request::UnsupportedSchemeError, Addressable::URI::InvalidURIError
        raise Down::InvalidUrl, exception.message
      when HTTP::ConnectionError
        raise Down::ConnectionError, exception.message
      when HTTP::TimeoutError
        raise Down::TimeoutError, exception.message
      when HTTP::Redirector::TooManyRedirectsError
        raise Down::TooManyRedirects, exception.message
      when OpenSSL::SSL::SSLError
        raise Down::SSLError, exception.message
      else
        raise exception
      end
    end
74319
function current()
	{
		if( ( $name = $this->_container->getNameIndex( $this->_position ) ) === false )
		{
			$msg = 'Unable to get name of file at index "%1$s" in "%2$s"';
			throw new MW_Container_Exception( sprintf( $msg, $this->_position, $this->_container->filename ) );
		}

		// $this->_container->getStream( $name ) doesn't work correctly because the stream can't be rewinded
		return new $this->_classname( 'zip://' . $this->_resourcepath . '#' . $name, $name );
	}
1201309
def _raise_error_if_container_is_missing_an_utterance(self):
        
        expected_keys = frozenset(self.utt_ids)

        for cnt in self.containers:
            keys = set(cnt.keys())

            if not keys.issuperset(expected_keys):
                raise ValueError('Container is missing data for some utterances!')
515377
def request_error!(exception)
      case exception
      when Net::OpenTimeout
        raise Down::TimeoutError, "timed out waiting for connection to open"
      when Net::ReadTimeout
        raise Down::TimeoutError, "timed out while reading data"
      when EOFError, IOError, SocketError, SystemCallError
        raise Down::ConnectionError, exception.message
      when OpenSSL::SSL::SSLError
        raise Down::SSLError, exception.message
      else
        raise exception
      end
    end