code: def _kubectl_port_forward(
      service: str,
      namespace: str,
      target_port: int,
      local_port: Optional[int] = None,
  ) -> Generator[int, None, None]:
      """Context manager which creates a kubectl port-forward process targeting a
      K8s service.
  
      Terminates the port-forwarding process upon exit.
  
      Args:
          service: Name of a K8s service.
          namespace: Namespace to which the service belongs.
          target_port: The port targeted by the service.
          local_port: Forward from this port. Optional. By default, uses the port exposed
          by the service.
  
      Yields:
          The local port. The service can then be accessed at 127.0.0.1:<local_port>.
      """
      # First, figure out which port the service exposes for the given target port.
      service_port = _get_service_port(service, namespace, target_port)
      if not local_port:
          local_port = service_port
  
      process = subprocess.Popen(
          [
              "kubectl",
              "-n",
              namespace,
              "port-forward",
              f"service/{service}",
              f"{local_port}:{service_port}",
          ]
      )
  
      def terminate_process():
          process.terminate()
          # Wait 10 seconds for the process to terminate.
          # This cleans up the zombie entry from the process table.
          # 10 seconds is a deliberately excessive amount of time to wait.
          process.wait(timeout=10)
  
      # Ensure clean-up in case of interrupt.
      atexit.register(terminate_process)
      # terminate_process is ok to execute multiple times.
  
      try:
          yield local_port
      finally:
          terminate_process()
  
imports: import atexit
  import contextlib
  import logging
  import pathlib
  import subprocess
  import tempfile
  import time
  from typing import Any, Dict, Generator, List, Optional
  import yaml
  import os
  import ray
  from ray.job_submission import JobStatus, JobSubmissionClient
label_desc: Use image node_id 16 for calling a global function with example usage: _kubectl_port_forward(service, namespace, target_port, local_port) without return types