Example #1
0
 def Run(self):
   downloader = download.Download()
   for arg in self._args:
     src = arg[0]
     dst = arg[1]
     full_url = download.Transform(src, self._build_info)
     # support legacy untagged short filenames
     if not (download.IsRemote(full_url) or download.IsLocal(full_url)):
       full_url = download.PathCompile(self._build_info, file_name=full_url)
     try:
       file_util.CreateDirectories(dst)
     except file_util.Error as e:
       raise ActionError('Could not create destination directory %s. %s' %
                         (dst, e))
     try:
       downloader.DownloadFile(full_url, dst, show_progress=True)
     except download.DownloadError as e:
       downloader.PrintDebugInfo()
       raise ActionError('Transfer error while downloading %s: %s' %
                         (full_url, str(e)))
     if len(arg) > 2 and arg[2]:
       logging.info('Verifying SHA256 hash for %s.', dst)
       hash_ok = downloader.VerifyShaHash(dst, arg[2])
       if not hash_ok:
         raise ActionError('SHA256 hash for %s was incorrect.' % dst)
Example #2
0
    def _ProcessMsu(self, msu_file):
        """Command used to process updates downloaded.

    This command will apply updates to an image.

    If the exit code for the parsed command is anything other than zero, report
    fatal error.

    Args:
      msu_file: current file location.

    Raises:
      ActionError: Error during update application.
    """

        scratch_dir = '%s\\Updates\\' % constants.SYS_CACHE

        # create scratch directory
        file_util.CreateDirectories(scratch_dir)

        logging.info('Applying %s image to main disk.', msu_file)

        # Apply updates to  image
        try:
            execute.execute_binary(constants.WINPE_DISM, [
                '/image:c:\\', '/Add-Package'
                f'/PackagePath:{msu_file}'
                f'/ScratchDir:{scratch_dir}'
            ],
                                   shell=True)
        except execute.Error as e:
            raise ActionError('Failed to process update %s: %s' %
                              (msu_file, e))
Example #3
0
    def _ProcessMsu(self, msu_file):
        """Command used to process updates downloaded.

    This command will apply updates to an image.

    If the exit code for the parsed command is anything other than zero, report
    fatal error.

    Args:
      msu_file: current file location.

    Raises:
      ActionError: Error during update application.
    """

        scratch_dir = '%s\\Updates\\' % constants.SYS_CACHE

        # create scratch directory
        file_util.CreateDirectories(scratch_dir)

        # dism commands
        update = [
            '{} /image:c:\\ /Add-Package /PackagePath:{} /ScratchDir:{}'.
            format(constants.WINPE_DISM, msu_file, scratch_dir)
        ]

        logging.info('Applying %s image to main disk.', msu_file)

        # Apply updates to  image
        ex = Execute([update], self._build_info)
        try:
            ex.Run()
        except ActionError as e:
            raise ActionError('Unable to process update %s. (%s)' %
                              (msu_file, e))
Example #4
0
 def Run(self):
     try:
         path = self._args[0]
     except IndexError:
         raise ActionError('Unable to determine desired path from %s.' %
                           str(self._args))
     try:
         file_util.CreateDirectories(path)
     except file_util.Error as e:
         raise ActionError(e)
Example #5
0
def Dump(path, data, mode='w'):
    """Write a config file containing some data.

  Args:
    path: The filesystem path to the destination file.
    data: Data to be written to the file as yaml.
    mode: Mode to use for writing the file (default: w)
  """
    file_util.CreateDirectories(path)
    try:
        with open(path, mode) as handle:
            handle.write(yaml.dump(data))
    except IOError as e:
        raise Error('Could not save data to yaml file %s: %s' % (path, str(e)))
Example #6
0
  def Run(self):
    try:
      zip_file = self._args[0]
      out_path = self._args[1]
    except IndexError:
      raise ActionError('Unable to determine desired paths from %s.' %
                        str(self._args))

    try:
      file_util.CreateDirectories(out_path)
    except file_util.Error:
      raise ActionError('Unable to create output path %s.' % out_path)

    try:
      zf = zipfile.ZipFile(zip_file)
      zf.extractall(out_path)
    except (IOError, zipfile.BadZipfile) as e:
      raise ActionError('Bad zip file given as input.  %s' % e)
Example #7
0
    def _ProcessWim(self, wim_file):
        """Processes WIM driver files using DISM commands.

    Runs necessary commands to process a driver file in WIM format

    Args:
      wim_file: current file location.

    Raises:
      ConfigRunnerError: Failure mounting or unmounting WIM.
    """
        mount_dir = '%s\\Drivers\\' % constants.SYS_CACHE

        # dism commands
        mount = [
            '{} /Mount-Image /ImageFile:{} /MountDir:{} /ReadOnly /Index:1'.
            format(constants.WINPE_DISM, wim_file, mount_dir)
        ]
        unmount = [
            '{} /Unmount-Image /MountDir:{} /Discard'.format(
                constants.WINPE_DISM, mount_dir)
        ]

        # create mount directory
        file_util.CreateDirectories(mount_dir)

        # mount image
        ex = Execute([mount], self._build_info)
        try:
            ex.Run()
        except ActionError as e:
            raise ActionError('Unable to mount image %s. (%s)' % (wim_file, e))

        logging.info('Applying %s image to main disk.', wim_file)
        self._AddDriver(mount_dir)

        # Unmount after running
        ex = Execute([unmount], self._build_info)
        try:
            ex.Run()
        except ActionError as e:
            raise ActionError(
                'Error unmounting image. Unable to continue. (%s)' % e)
Example #8
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)
Example #9
0
def Dump(path: str, data: Any, mode: str = 'w'):
    """Write a config file containing some data.

  Args:
    path: The filesystem path to the destination file.
    data: Data to be written to the file as yaml.
    mode: Mode to use for writing the file (default: w)
  """
    file_util.CreateDirectories(path)
    tmp_f = path + '.tmp'
    # Write to a .tmp file to avoid corrupting the original if aborted mid-way.
    try:
        with open(tmp_f, mode) as handle:
            handle.write(yaml.dump(data))
    except IOError as e:
        raise Error('Could not save data to yaml file %s: %s' % (path, str(e)))
    # Replace the original with the tmp.
    try:
        file_util.Move(tmp_f, path)
    except file_util.Error as e:
        raise Error('Could not replace config file. (%s)' % str(e))
Example #10
0
 def Run(self):
     path = self._build_info.CachePath()
     try:
         file_util.CreateDirectories(path)
     except file_util.Error as e:
         raise ActionError(e)
Example #11
0
 def testCreateDirectories(self):
     self.filesystem.create_file('/test')
     self.assertRaises(file_util.Error, file_util.CreateDirectories,
                       '/test/file.txt')
     file_util.CreateDirectories('/tmp/test/path/file.log')
     self.assertTrue(self.filesystem.Exists('/tmp/test/path'))