Exemple #1
0
def _base_title() -> Optional[Text]:
    """Concatenate base values for the title based on build information.

  Returns:
    The base text for the title as a string.
  """
    build_info = buildinfo.BuildInfo()
    getid = build_info.ImageID()
    base = []

    if winpe.check_winpe():
        base.append('WinPE')
    if constants.FLAGS.config_root_path:
        base.append(constants.FLAGS.config_root_path.strip('/'))
    if getid:
        base.append(getid)

    # Convert list to a string, using map() to account for nonetypes
    return ' - '.join(map(str, base))
Exemple #2
0
def Setup():
    """Sets up the logging environment."""
    build_info = buildinfo.BuildInfo()
    log_file = r'%s\%s' % (GetLogsPath(), constants.BUILD_LOG_FILE)
    file_util.CreateDirectories(log_file)

    debug_fmt = ('%(levelname).1s%(asctime)s.%(msecs)03d %(process)d {} '
                 '%(filename)s:%(lineno)d] %(message)s').format(
                     build_info.ImageID())
    info_fmt = '%(levelname).1s%(asctime)s %(filename)s:%(lineno)d] %(message)s'

    debug_formatter = logging.Formatter(debug_fmt, datefmt=DATE_FMT)
    info_formatter = logging.Formatter(info_fmt, datefmt=DATE_FMT)

    # Set default logger
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    # Create empty list of handlers to enable multiple streams.
    logger.handlers = []

    # Create console handler and set level
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    ch.setFormatter(info_formatter)
    logger.addHandler(ch)

    # Create file handler and set level
    try:
        fh = logging.FileHandler(log_file)
    except IOError:
        raise LogError('Failed to open log file %s.' % log_file)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(debug_formatter)
    logger.addHandler(fh)

    # Create Event Log handler and set level
    if not winpe.check_winpe():
        eh = logging.handlers.NTEventLogHandler('GlazierBuildLog')
        eh.setLevel(logging.DEBUG)
        eh.setFormatter(debug_formatter)
        logger.addHandler(eh)
Exemple #3
0
def check_id() -> str:
    """Call set_id if image identifier is not set and in WinPE.

  Check build_info (dumped via buildinfodump) in host if image_id does
  not exist.

  Returns:
    Image identifier as a string if already set.
  """
    image_id = None
    try:
        image_id = registry.get_value('image_id', path=constants.REG_ROOT)
    except registry.Error as e:
        logging.error(str(e))

    if image_id:
        return image_id
    if winpe.check_winpe():
        return _set_id()

    return _check_file()
Exemple #4
0
  def _OpenStream(
      self,
      url: Text,
      max_retries: int = 5,
      status_codes: Optional[List[int]] = None) -> 'http.client.HTTPResponse':
    """Opens a connection to a remote resource.

    Args:
      url:  The address of the file to be downloaded.
      max_retries:  The number of times to attempt to download a file if the
        first attempt fails. A negative number implies infinite.
      status_codes: A list of acceptable status codes to be returned by the
        remote endpoint.

    Returns:
      file_stream: urlopen's file stream

    Raises:
      DownloadError: The resource was unreachable or failed to return with the
        expected code.
    """
    attempt = 0
    file_stream = None

    opener = urllib.request.OpenerDirector()
    for handler in self._GetHandlers():
      opener.add_handler(handler)
    urllib.request.install_opener(opener)

    url = url.strip()
    parsed = urllib.parse.urlparse(url)
    if not parsed.netloc:
      raise DownloadError('Invalid remote server URL "%s".' % url)

    while True:
      try:
        attempt += 1
        if winpe.check_winpe():
          file_stream = urllib.request.urlopen(url, cafile=self._ca_cert_file)
        else:
          file_stream = urllib.request.urlopen(url)
      except urllib.error.HTTPError:
        logging.error('File not found on remote server: %s.', url)
      except urllib.error.URLError as e:
        logging.error(
            'Error connecting to remote server to download file '
            '"%s". The error was: %s', url, e)
        try:
          logging.info('Trying again with machine context...')
          ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
          file_stream = urllib.request.urlopen(url, context=ctx)
        except urllib.error.HTTPError:
          logging.error('File not found on remote server: %s.', url)
        except urllib.error.URLError as e:
          logging.error(
              'Error connecting to remote server to download file '
              '"%s". The error was: %s', url, e)
      if file_stream:
        if file_stream.getcode() in (status_codes or [200]):
          return file_stream
        elif file_stream.getcode() in [302]:
          url = file_stream.geturl()
        else:
          raise DownloadError('Invalid return code for file %s. [%d]' %
                              (url, file_stream.getcode()))

      self._AttemptResource(attempt, max_retries, 'file download')
Exemple #5
0
 def _GooGet(self) -> str:
   if winpe.check_winpe():
     return str(constants.WINPE_GOOGETROOT)
   else:
     return str(constants.SYS_GOOGETROOT)
Exemple #6
0
def _Powershell() -> str:
  if winpe.check_winpe():
    return constants.WINPE_POWERSHELL
  else:
    return constants.SYS_POWERSHELL
Exemple #7
0
def GetLogsPath():
  path = constants.SYS_LOGS_PATH
  if winpe.check_winpe():
    path = constants.WINPE_LOGS_PATH
  return path
Exemple #8
0
def _System32() -> Text:
    if winpe.check_winpe():
        return constants.WINPE_SYSTEM32
    else:
        return constants.SYS_SYSTEM32
Exemple #9
0
 def test_check_winpe_false(self, gv):
     winpe.check_winpe.cache_clear()
     gv.return_value = 'Enterprise'
     self.assertEqual(winpe.check_winpe(), False)
Exemple #10
0
 def test_check_winpe_true(self, gv):
     winpe.check_winpe.cache_clear()
     gv.return_value = 'WindowsPE'
     self.assertEqual(winpe.check_winpe(), True)