code: def docker_monitor(self, cidfile, tmpdir_prefix, cleanup_cidfile, process):
          # type: (Text, Text, bool, subprocess.Popen) -> None
          
          # Todo: consider switching to `docker create` / `docker start`
          # instead of `docker run` as `docker create` outputs the container ID
          # to stdout, but the container is frozen, thus allowing us to start the
          # monitoring process without dealing with the cidfile or too-fast
          # container execution
          cid = None
          while cid is None:
              time.sleep(1)
              if process.returncode is not None:
                  if cleanup_cidfile:
                      os.remove(cidfile)
                  return
              try:
                  with open(cidfile) as cidhandle:
                      cid = cidhandle.readline().strip()
              except (OSError, IOError):
                  cid = None
          max_mem = self.docker_get_memory(cid)
          tmp_dir, tmp_prefix = os.path.split(tmpdir_prefix)
          stats_file = tempfile.NamedTemporaryFile(prefix=tmp_prefix, dir=tmp_dir)
          with open(stats_file.name, mode="w") as stats_file_handle:
              stats_proc = subprocess.Popen(
                  ['docker', 'stats', '--no-trunc', '--format', '{{.MemPerc}}',
                   cid], stdout=stats_file_handle, stderr=subprocess.DEVNULL)
              process.wait()
              stats_proc.kill()
          max_mem_percent = 0
          with open(stats_file.name, mode="r") as stats:
              for line in stats:
                  try:
                      mem_percent = float(re.sub(
                          CONTROL_CODE_RE, '', line).replace('%', ''))
                      if mem_percent > max_mem_percent:
                          max_mem_percent = mem_percent
                  except ValueError:
                      break
          _logger.info(u"[job %s] Max memory used: %iMiB", self.name,
                       int((max_mem_percent * max_mem) / (2 ** 20)))
          if cleanup_cidfile:
              os.remove(cidfile)
docs: Record memory usage of the running Docker container.