code: def run(
      args: "argparse.Namespace",
      name: str,
      container_name: str,
      net_mode: Optional[str],
      runtime_ctrl_address: str,
      envs: Dict,
      is_started: Union["multiprocessing.Event", "threading.Event"],
      is_shutdown: Union["multiprocessing.Event", "threading.Event"],
      is_ready: Union["multiprocessing.Event", "threading.Event"],
      is_signal_handlers_installed: Union[
          "multiprocessing.Event", "threading.Event"
      ],
  ):
      """Method to be run in a process that stream logs from a Container
  
      This method is the target for the Pod's `thread` or `process`
  
      .. note::
          :meth:`run` is running in subprocess/thread, the exception can not be propagated to the main process.
          Hence, please do not raise any exception here.
  
      .. note::
          Please note that env variables are process-specific. Subprocess inherits envs from
          the main process. But Subprocess's envs do NOT affect the main process. It does NOT
          mess up user local system envs.
  
      :param args: namespace args from the Pod
      :param name: name of the Pod to have proper logging
      :param container_name: name to set the Container to
      :param net_mode: The network mode where to run the container
      :param runtime_ctrl_address: The control address of the runtime in the container
      :param envs: Dictionary of environment variables to be set in the docker image
      :param is_started: concurrency event to communicate runtime is properly started. Used for better logging
      :param is_signal_handlers_installed: concurrency event to communicate runtime is ready to get SIGTERM from orchestration
      :param is_shutdown: concurrency event to communicate runtime is terminated
      :param is_ready: concurrency event to communicate runtime is ready to receive messages
      """
      import docker
      import asyncio
  
      log_kwargs = copy.deepcopy(vars(args))
      log_kwargs["log_config"] = "docker"
      logger = JinaLogger(name, **log_kwargs)
  
      cancel = False
      fail_to_start = False
  
      def _set_cancel(*args, **kwargs):
          cancel = True
  
      if not __windows__:
          try:
              for signame in {signal.SIGINT, signal.SIGTERM}:
                  signal.signal(signame, _set_cancel)
          except (ValueError, RuntimeError) as exc:
              logger.warning(
                  f"The process starting the container for {name} will not be able to handle termination signals. "
                  f" {repr(exc)}"
              )
      else:
          with ImportExtensions(
              required=True,
              logger=logger,
              help_text="""If you see a 'DLL load failed' error, please reinstall `pywin32`.
                  If you're using conda, please use the command `conda install -c anaconda pywin32`""",
          ):
              import win32api
  
          win32api.SetConsoleCtrlHandler(_set_cancel, True)
  
      is_signal_handlers_installed.set()
      client = docker.from_env()
  
      try:
          container = _docker_run(
              client=client,
              args=args,
              container_name=container_name,
              envs=envs,
              net_mode=net_mode,
              logger=logger,
          )
          client.close()
  
          def _is_ready():
              from jina.serve.runtimes.servers import BaseServer
  
              return BaseServer.is_ready(
                  ctrl_address=runtime_ctrl_address,
                  protocol=getattr(args, "protocol", ["grpc"])[0],
              )
  
          def _is_container_alive(container) -> bool:
              import docker.errors
  
              try:
                  container.reload()
              except docker.errors.NotFound:
                  return False
              return True
  
          async def _check_readiness(container):
              while (
                  _is_container_alive(container)
                  and not _is_ready()
                  and not cancel
              ):
                  await asyncio.sleep(0.1)
              if _is_container_alive(container):
                  is_started.set()
                  is_ready.set()
              else:
                  fail_to_start = True
  
          async def _stream_starting_logs(container):
              for line in container.logs(stream=True):
                  if (
                      not is_started.is_set()
                      and not fail_to_start
                      and not cancel
                  ):
                      await asyncio.sleep(0.01)
                  msg = line.decode().rstrip()  # type: str
                  logger.debug(re.sub(r"\u001b\[.*?[@-~]", "", msg))
  
          async def _run_async(container):
              await asyncio.gather(
                  *[
                      _check_readiness(container),
                      _stream_starting_logs(container),
                  ]
              )
  
          asyncio.run(_run_async(container))
      finally:
          client.close()
          if not is_started.is_set():
              logger.error(
                  f"Process terminated, the container fails to start, check the arguments or entrypoint"
              )
          is_shutdown.set()
          logger.debug(f"process terminated")
  
imports: import argparse
  import copy
  import multiprocessing
  import os
  import platform
  import re
  import signal
  import time
  from typing import TYPE_CHECKING, Dict, Optional, Union
  from jina.constants import __docker_host__, __windows__
  from jina.enums import PodRoleType, DockerNetworkMode
  from jina.excepts import BadImageNameError, DockerVersionError
  from jina.helper import random_name, slugify
  from jina.importer import ImportExtensions
  from jina.logging.logger import JinaLogger
  from jina.orchestrate.helper import generate_default_volume_and_workspace
  from jina.orchestrate.pods import BasePod
  from jina.orchestrate.pods.container_helper import get_docker_network, get_gpu_device_requests
  from jina.parsers import set_gateway_parser
label_desc: Use image node_id 2 for calling a global function with example usage: run(args, name, container_name, net_mode, runtime_ctrl_address, envs, is_started, is_shutdown, is_ready, is_signal_handlers_installed) and returns: BaseServer, True, False