import time
import six
import socket


def _WaitForServer(url, timeout):
  """Wait for a server to be ready.

  Args:
    url: a server url.
    timeout: max wait time.
  Returns:
    True if the service is ready. Otherwise False.
  """
  end_time = time.time() + timeout
  while True:
    remaining_time = end_time - time.time()
    if remaining_time <= 0:
      break
    try:
      six.moves.urllib.request.urlopen(url, timeout=remaining_time)
      return True
    except (socket.error, six.moves.urllib.error.URLError):
      time.sleep(0.1)
  return False