Beispiel #1
0
def _test():
    """Test function"""
    from apt.cache import Cache
    from apt.progress import DpkgInstallProgress

    cache = Cache()

    vp = "www-browser"
    #print "%s virtual: %s" % (vp, cache.isVirtualPackage(vp))
    providers = cache.get_providing_packages(vp)
    print "Providers for %s :" % vp
    for pkg in providers:
        print " %s" % pkg.name

    d = DebPackage(sys.argv[1], cache)
    print "Deb: %s" % d.pkgname
    if not d.check():
        print "can't be satified"
        print d._failure_string
    print "missing deps: %s" % d.missing_deps
    print d.required_changes

    print "Installing ..."
    ret = d.install(DpkgInstallProgress())
    print ret

    #s = DscSrcPackage(cache, "../tests/3ddesktop_0.2.9-6.dsc")
    #s.check_dep()
    #print "Missing deps: ",s.missingDeps
    #print "Print required changes: ", s.requiredChanges

    s = DscSrcPackage(cache=cache)
    d = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)"
    print s._satisfy_depends(apt_pkg.parse_depends(d))
Beispiel #2
0
 def __init__(self, options):
     # fixme, do graphic cache check
     self.options = options
     if options.quiet:
         tp = apt.progress.base.OpProgress()
     else:
         tp = apt.progress.text.OpProgress()
     # set architecture to architecture in root-dir
     if options.rootdir and os.path.exists(options.rootdir +
                                           "/usr/bin/dpkg"):
         arch = Popen(
             [options.rootdir + "/usr/bin/dpkg", "--print-architecture"],
             stdout=PIPE,
             universal_newlines=True).communicate()[0]
         if arch:
             apt_pkg.config.set("APT::Architecture", arch.strip())
     if options.apt_opts:
         for o in options.apt_opts:
             if o.find('=') < 0:
                 sys.stderr.write(
                     _("Configuration items must be specified with a =<value>\n"
                       ))
                 sys.exit(1)
             (name, value) = o.split('=', 1)
             try:
                 apt_pkg.config.set(name, value)
             except:
                 sys.stderr.write(
                     _("Couldn't set APT option %s to %s\n") %
                     (name, value))
                 sys.exit(1)
     self._cache = Cache(tp, rootdir=options.rootdir)
    def _test_for_new_dell_recovery(self, mount, assembly_tmp):
        """Tests if the distro currently on the system matches the recovery media.
           If it does, check for any potential SRUs to apply to the recovery media
        """
        logging.debug("_test_for_new_dell_recovery: testing mount %s and assembly_tmp %s" % (mount, assembly_tmp))

        output = fetch_output(['zcat', '/usr/share/doc/dell-recovery/changelog.gz'])
        package_distro = output.split('\n')[0].split()[2].strip(';')

        for info in ('info.recovery', 'info'):
            file_path = os.path.join(mount, '.disk', info)
            if os.path.exists(file_path):
                with open(file_path) as rfd:
                    rp_distro = rfd.readline().split()[2].strip('"').lower()
                    break

        if rp_distro in package_distro:
            logging.debug("_test_for_new_dell_recovery: Distro %s matches %s", rp_distro, package_distro)
            from apt.cache import Cache
            cache = Cache()
            package_version = cache['dell-recovery'].installed.version
            rp_version = self.query_have_dell_recovery(mount)

            if debian_support.version_compare(package_version, rp_version) > 0:
                logging.debug("_test_for_new_dell_recovery: Including updated dell-recovery package version, %s (original was %s)", package_version, rp_version)
                dest = os.path.join(assembly_tmp, 'debs')
                if not os.path.isdir(dest):
                    os.makedirs(dest)
                call = subprocess.Popen(['dpkg-repack', 'dell-recovery'],
                                        cwd=dest, universal_newlines=True)
                (out, err) = call.communicate()
        else:
            logging.debug("_test_for_new_dell_recovery: RP Distro %s doesn't match our distro %s, not injecting updated package", rp_distro, package_distro)
Beispiel #4
0
    def remove(*package_names) -> None:

        upgrade()

        cache = Cache()
        cache.update()
        cache.open()

        for name in package_names:

            if name not in cache:
                print('Package %s not found!' % (name, ))
                continue

            package = cache[name]

            if not package.is_installed:
                print('Package %s is not installed!' % (name, ))
                continue

            package.mark_delete(purge=True)

        cache.commit(TextFetchProgress(), InstallProgress())

        cache.close()
Beispiel #5
0
    def __init__(self):

        # Get the apt cache
        self.cache = Cache()

        # Feedback module
        self.feedback = Feedback()
Beispiel #6
0
def setup(helper, old_version=None):
    """Install and configure the module."""
    if old_version == 1:
        # Check that radicale 2.x is available for install.
        cache = Cache()
        candidate = cache['radicale'].candidate
        if candidate < '2':
            logger.error('Radicale 2.x is not available to install.')

        # Try to upgrade radicale 1.x to 2.x.
        helper.call('pre', actions.superuser_run, 'radicale', ['migrate'])
        helper.install(managed_packages, force_configuration='new')

        # Check that radicale 2.x is installed.
        current_version = get_package_version()
        if not current_version:
            logger.error('Could not determine installed version of radicale.')
        elif current_version < VERSION_2:
            logger.error('Could not install radicale 2.x.')

        # Enable radicale.
        helper.call('post', actions.superuser_run, 'radicale', ['setup'])
    else:
        helper.install(managed_packages)
        helper.call('post', actions.superuser_run, 'radicale', ['setup'])

    helper.call('post', app.enable)
Beispiel #7
0
    def install(*package_names) -> None:

        upgrade()

        cache = Cache()
        cache.update()
        cache.open()

        for name in package_names:

            if name not in cache:
                logger.error('Package %s not found!' % (name, ))
                continue

            package = cache[name]

            if package.is_installed:
                logger.warning('Package %s already installed!' % (name, ))
                continue

            package.mark_install()

        cache.commit(TextFetchProgress(), InstallProgress())

        cache.close()
Beispiel #8
0
def main():
    """main entry point"""
    args = get_args()
    installed_pkgs = set(pkg.name for pkg in Cache()
                         if pkg.is_installed and not pkg.is_auto_installed)
    additional_pkgs = installed_pkgs - get_puppet_managed_pkgs(
    ) - get_base_pkgs(args.base_packages)
    for pkg in additional_pkgs:
        print(pkg)
Beispiel #9
0
    def __init__(self, conn=None, object_path=None, bus_name=None):
        super().__init__(conn, object_path, bus_name)

        self.dbus_info = None
        self.polkit = None
        self.enforce_polkit = True
        self.cache = Cache()
        self.lock = None
        self.apt_lock = None
 def __init__(self, parent):
     QtWidgets.QLineEdit.__init__(self, parent)
     self.logger = logging.getLogger("PackageLineEdit")
     cache = FilteredCache(Cache())
     cache.set_filter(InstalledFilter())
     self._completer = QtWidgets.QCompleter(sorted(cache.keys()))
     self._completer.setModelSorting(
         QtWidgets.QCompleter.CaseSensitivelySortedModel)
     self.setCompleter(self._completer)
Beispiel #11
0
    def refresh_cache(self):
        cache_date = self.get_cache_date()

        if not self.apt_cache:
            self.apt_cache = Cache()
            self.apt_cache_date = cache_date
        elif cache_date != self.apt_cache_date:
            self.apt_cache.open(None)
            self.apt_cache_date = cache_date
Beispiel #12
0
def about(request):
    """Serve the about page"""
    cache = Cache()
    plinth = cache['plinth']
    context = {
        'title': _('About {box_name}').format(box_name=_(cfg.box_name)),
        'version': __version__,
        'new_version': not plinth.candidate.is_installed
    }
    return TemplateResponse(request, 'help_about.html', context)
def mark_upgrades():
    '''Mark packages that can upgrade to upgrade during install'''
    from apt.cache import Cache
    cache = Cache()
    to_install = []
    for key in cache.keys():
        if cache[key].is_upgradable:
            to_install.append(key)
    del cache
    return to_install
Beispiel #14
0
    def upgrade() -> None:

        cache = Cache()
        cache.update()
        cache.open()
        cache.update()
        cache.open()
        cache.upgrade(dist_upgrade=True)
        cache.fix_broken()
        cache.commit(TextFetchProgress(), InstallProgress())
        cache.close()
Beispiel #15
0
def about(request):
    """Serve the about page"""
    cache = Cache()
    freedombox = cache['freedombox']
    context = {
        'title': _('About {box_name}').format(box_name=_(cfg.box_name)),
        'version': __version__,
        'new_version': not freedombox.candidate.is_installed,
        'os_release': get_os_release(),
    }
    return TemplateResponse(request, 'help_about.html', context)
Beispiel #16
0
 def openCache(self):
     self._cache = Cache(self.cprogress)
     if self._cache._depcache.broken_count > 0:
         self.error_header = _("Broken dependencies")
         self.error_body = _("Your system has broken dependencies. "
                             "This application can not continue until "
                             "this is fixed. "
                             "To fix it run 'pkexec synaptic' or "
                             "'sudo apt-get install -f' "
                             "in a terminal window.")
         return False
     return True
def mark_packages(recovery_partition):
    '''Finds packages to install:
        * any debs from debs/main that we want unconditionally installed
          (but ONLY the latest version on the media)
        * upgrades
        * dell-recovery - if recovery partition
        * dell-eula - if it exists
    '''
    import apt_inst
    import apt_pkg
    from apt.cache import Cache

    def parse(fname):
        """ read a deb """
        control = apt_inst.DebFile(fname).control.extractdata("control")
        sections = apt_pkg.TagSection(control)
        if "Modaliases" in sections:
            modaliases = sections["Modaliases"]
        else:
            modaliases = ''
        return (sections["Architecture"], sections["Package"], modaliases)

    #process debs/main
    to_install = []
    my_arch = fetch_output(['dpkg', '--print-architecture']).strip()
    for top in [ISO_MOUNT, CDROM_MOUNT]:
        repo = os.path.join(top, 'debs', 'main')
        if os.path.isdir(repo):
            for fname in os.listdir(repo):
                if '.deb' in fname:
                    arch, package, modaliases = parse(os.path.join(
                        repo, fname))
                    if not modaliases and (arch == "all" or arch == my_arch):
                        to_install.append(package)

    #mark upgrades and dell-recovery/dell-eula
    cache = Cache()
    for key in cache.keys():
        if cache[key].is_upgradable:
            to_install.append(key)
            continue
        #only install if present on the media
        if key == 'dell-eula' and recovery_partition:
            to_install.append(key)
    del cache

    #only install if using recovery partition
    if recovery_partition:
        to_install.append('dell-recovery')

    return to_install
Beispiel #18
0
def charm_version():
    try:
        from apt.cache import Cache
        charm_vers = Cache()['charm'].versions
        for v in charm_vers:
            if v.is_installed:
                charm_ver = v.version
                break
    except ImportError:
        charm_ver = 'unavailable'
    except:
        charm_ver = 'error'

    return charm_ver
Beispiel #19
0
def update_cache():
    """ Replaces the current CACHE with a new one.

    This is required because using cache.open() or cache.update() requires
    root permissions, which we don't have. Not using this is fine for the
    unprivileged side of the code because we aren't making any changes, only
    reading state. But there may be changes happening behind the scenes, so we
    want a way to get a current cache.
    
    Returns:
        The new apt.cache.Cache object.
    """
    global CACHE
    CACHE = Cache()
    return CACHE
Beispiel #20
0
    def do_install(self, to_install, langpacks=False):
        #self.nested_progress_start()

        with Cache() as cache:

            if cache._depcache.broken_count > 0:
                print('not installing additional packages, since there are'
                      ' broken packages: %s' %
                      ', '.join(broken_packages(cache)))
                return

            with cache.actiongroup():
                for pkg in to_install:
                    mark_install(cache, pkg)

            return  # it throw exception in mark_install
    def __init__(self, board: str):
        """
        Parameters
        ----------
        board: str
            The board to make the update for.
        """
        self._board = board
        self._status_file = ""
        self._board = board
        self._cache = Cache(rootdir=ROOT_DIR)
        self._cache.update(raise_on_error=False)
        self._cache.open()
        self._deb_pkgs = []
        self._inst_list = []

        # make sure all dir exist
        Path(OLU_DIR).mkdir(parents=True, exist_ok=True)
        Path(ROOT_DIR).mkdir(parents=True, exist_ok=True)
        Path(DOWNLOAD_DIR).mkdir(parents=True, exist_ok=True)
        Path(UPDATE_CACHE_DIR).mkdir(parents=True, exist_ok=True)
        Path(STATUS_CACHE_DIR).mkdir(parents=True, exist_ok=True)

        # clear download dir
        for i in listdir(DOWNLOAD_DIR):
            if i.endswith(".deb"):
                remove(DOWNLOAD_DIR + i)

        status_files = []
        for i in listdir(STATUS_CACHE_DIR):
            status_files.append(OLMFile(load=i))
        status_files.sort()

        # find latest olu status tar file
        for i in status_files:
            if i.name == board:
                self._status_file = STATUS_CACHE_DIR + i.name
                break

        if self._status_file == "":
            msg = "No status file for {} board in cache".format(board)
            raise FileNotFoundError(msg)

        # update status file
        dpkg_data = read_dpkg_status_file(self._status_file)
        with open(DPKG_STATUS_FILE) as fptr:
            fptr.write(dpkg_data)
Beispiel #22
0
def charm_version():
    if 'SNAP' in os.environ:
        cscv = os.path.join(os.environ['SNAP'], 'charmstore-client-version')
        if os.path.exists(cscv):
            with open(cscv) as f:
                charm_ver = f.read().strip()
            return charm_ver
    try:
        from apt.cache import Cache
        charm_vers = Cache()['charm'].versions
        for v in charm_vers:
            if v.is_installed:
                charm_ver = v.version
                break
    except ImportError:
        charm_ver = 'unavailable'
    except:
        charm_ver = 'error'

    return charm_ver
Beispiel #23
0
def cached_charmstore_client_version():
    if 'SNAP' in os.environ:
        cscv = os.path.join(os.environ['SNAP'], 'charmstore-client-version')
        if not os.path.exists(cscv):
            return {'version': 'unavailable', 'git': ''}
        with open(cscv) as f:
            res_string = f.read().strip()
        return _add_snap_rev(json.loads(res_string))
    try:
        from apt.cache import Cache
        charm_vers = Cache()['charm'].versions
        for v in charm_vers:
            if v.is_installed:
                charm_ver = v.version
                break
    except ImportError:
        charm_ver = 'unavailable'
    except:
        charm_ver = 'error'

    return _add_snap_rev({'version': charm_ver})
Beispiel #24
0
    def install_extras(self):
        """Try to install packages requested by installer components."""
        # We only ever install these packages from the CD.
        sources_list = '/target/etc/apt/sources.list'
        os.rename(sources_list, "%s.apt-setup" % sources_list)
        with open("%s.apt-setup" % sources_list) as old_sources:
            with open(sources_list, 'w') as new_sources:
                found_cdrom = False
                for line in old_sources:
                    if 'cdrom:' in line:
                        print(line, end="", file=new_sources)
                        found_cdrom = True
        if not found_cdrom:
            os.rename("%s.apt-setup" % sources_list, sources_list)

        # this will install free & non-free things, but not things
        # that have multiarch Depends or Recommends. Instead, those
        # will be installed by install_restricted_extras() later
        # because this function runs before i386 foreign arch is
        # enabled
        cache = Cache()
        filtered_extra_packages = query_recorded_installed()
        for package in filtered_extra_packages.copy():
            pkg = cache.get(package)
            if not pkg:
                continue
            candidate = pkg.candidate
            dependencies = candidate.dependencies + candidate.recommends
            all_deps = itertools.chain.from_iterable(dependencies)
            for dep in all_deps:
                if ':' in dep.name:
                    filtered_extra_packages.remove(package)
                    break

        self.do_install(filtered_extra_packages)

        if found_cdrom:
            os.rename("%s.apt-setup" % sources_list, sources_list)
def _test():
    # type: () -> None
    """Test function"""
    from apt.cache import Cache
    from apt.progress.base import InstallProgress

    cache = Cache()

    vp = "www-browser"
    print("%s virtual: %s" % (vp, cache.is_virtual_package(vp)))
    providers = cache.get_providing_packages(vp)
    print("Providers for %s :" % vp)
    for pkg in providers:
        print(" %s" % pkg.name)

    d = DebPackage(sys.argv[1], cache)
    print("Deb: %s" % d.pkgname)
    if not d.check():
        print("can't be satified")
        print(d._failure_string)
    print("missing deps: %s" % d.missing_deps)
    print(d.required_changes)

    print(d.filelist)

    print("Installing ...")
    ret = d.install(InstallProgress())
    print(ret)

    #s = DscSrcPackage(cache, "../tests/3ddesktop_0.2.9-6.dsc")
    #s.check_dep()
    #print "Missing deps: ",s.missingDeps
    #print "Print required changes: ", s.requiredChanges

    s = DscSrcPackage(cache=cache)
    ds = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)"
    print(s._satisfy_depends(apt_pkg.parse_depends(ds, False)))
Beispiel #26
0
    def generate_blacklist(self):
        manifest_remove = os.path.join(self.casper_path,
                                       'filesystem.manifest-remove')
        manifest_desktop = os.path.join(self.casper_path,
                                        'filesystem.manifest-desktop')
        manifest = os.path.join(self.casper_path, 'filesystem.manifest')
        if os.path.exists(manifest_remove) and os.path.exists(manifest):
            difference = set()
            with open(manifest_remove) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        difference.add(pkg.split()[0])
            live_packages = set()
            with open(manifest) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        live_packages.add(pkg.split()[0])
            desktop_packages = live_packages - difference
        elif os.path.exists(manifest_desktop) and os.path.exists(manifest):
            desktop_packages = set()
            with open(manifest_desktop) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        desktop_packages.add(pkg.split()[0])
            live_packages = set()
            with open(manifest) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        live_packages.add(pkg.split()[0])
            difference = live_packages - desktop_packages
        else:
            difference = set()

        cache = Cache()

        use_restricted = True
        try:
            if self.db.get('apt-setup/restricted') == 'false':
                use_restricted = False
        except debconf.DebconfError:
            pass
        if not use_restricted:
            for pkg in cache.keys():
                if (cache[pkg].is_installed
                        and cache[pkg].section.startswith('restricted/')):
                    difference.add(pkg)

        # Keep packages we explicitly installed.
        keep = install_misc.query_recorded_installed()
        arch, subarch = install_misc.archdetect()

        # Less than ideal.  Since we cannot know which bootloader we'll need
        # at file copy time, we should figure out why grub still fails when
        # apt-install-direct is present during configure_bootloader (code
        # removed).
        if arch in ('amd64', 'i386'):
            if subarch == 'efi':
                keep.add('grub-efi')
                keep.add('grub-efi-amd64')
                keep.add('grub-efi-amd64-signed')
                keep.add('shim-signed')
                keep.add('mokutil')
                keep.add('fwupdate-signed')
                install_misc.record_installed(['fwupdate-signed'])
                try:
                    altmeta = self.db.get('base-installer/kernel/altmeta')
                    if altmeta:
                        altmeta = '-%s' % altmeta
                except debconf.DebconfError:
                    altmeta = ''
                keep.add('linux-signed-generic%s' % altmeta)
            else:
                keep.add('grub')
                keep.add('grub-pc')
        elif (arch in ('armel', 'armhf')
              and subarch in ('omap', 'omap4', 'mx5')):
            keep.add('flash-kernel')
            keep.add('u-boot-tools')
        elif arch == 'powerpc':
            keep.add('yaboot')
            keep.add('hfsutils')

        # Even adding ubiquity as a depends to oem-config-{gtk,kde} doesn't
        # appear to force ubiquity and libdebian-installer4 to copy all of
        # their files, so this does the trick.
        try:
            if self.db.get('oem-config/enable') == 'true':
                keep.add('ubiquity')
        except (debconf.DebconfError, IOError):
            pass

        difference -= install_misc.expand_dependencies_simple(
            cache, keep, difference)

        # Consider only packages that don't have a prerm, and which can
        # therefore have their files removed without any preliminary work.
        difference = {
            x
            for x in difference
            if not os.path.exists('/var/lib/dpkg/info/%s.prerm' % x)
        }

        confirmed_remove = set()
        with cache.actiongroup():
            for pkg in sorted(difference):
                if pkg in confirmed_remove:
                    continue
                would_remove = install_misc.get_remove_list(cache, [pkg],
                                                            recursive=True)
                if would_remove <= difference:
                    confirmed_remove |= would_remove
                    # Leave these marked for removal in the apt cache to
                    # speed up further calculations.
                else:
                    for removedpkg in would_remove:
                        cachedpkg = install_misc.get_cache_pkg(
                            cache, removedpkg)
                        cachedpkg.mark_keep()
        difference = confirmed_remove

        if len(difference) == 0:
            del cache
            self.blacklist = {}
            return

        cmd = ['dpkg', '-L']
        cmd.extend(difference)
        subp = subprocess.Popen(cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True)
        res = subp.communicate()[0].splitlines()
        u = {}
        for x in res:
            u[x] = 1
        self.blacklist = u
Beispiel #27
0
    def select_language_packs(self, save=False):
        try:
            keep_packages = self.db.get('ubiquity/keep-installed')
            keep_packages = keep_packages.replace(',', '').split()
            syslog.syslog('keeping packages due to preseeding: %s' %
                          ' '.join(keep_packages))
            record_installed(keep_packages)
        except debconf.DebconfError:
            pass

        langpacks = []
        all_langpacks = False
        try:
            langpack_db = self.db.get('pkgsel/language-packs')
            if langpack_db == 'ALL':
                apt_subp = subprocess.Popen(
                    ['apt-cache', '-n', 'search', '^language-pack-[^-][^-]*$'],
                    stdout=subprocess.PIPE,
                    universal_newlines=True)
                apt_out = apt_subp.communicate()[0].rstrip().split('\n')
                langpacks = [x.split('-')[2].strip() for x in apt_out]
                all_langpacks = True
            else:
                langpacks = langpack_db.replace(',', '').split()
        except debconf.DebconfError:
            pass
        if not langpacks:
            langpack_set = set()
            try:
                langpack_db = self.db.get('localechooser/supported-locales')
                for locale in langpack_db.replace(',', '').split():
                    langpack_set.add(locale)
            except debconf.DebconfError:
                pass
            langpack_db = self.db.get('debian-installer/locale')
            langpack_set.add(langpack_db)
            langpacks = sorted(langpack_set)

        no_install = '/var/lib/ubiquity/no-install-langpacks'
        if os.path.exists(no_install):
            osextras.unlink_force(no_install)
        if len(langpacks) == 1 and langpacks[0] in ('C', 'en'):
            # Touch
            with open(no_install, 'a'):
                os.utime(no_install, None)

        syslog.syslog('keeping language packs for: %s' % ' '.join(langpacks))

        try:
            lppatterns = self.db.get('pkgsel/language-pack-patterns').split()
        except debconf.DebconfError:
            return

        cache = Cache()

        to_install = []
        checker = osextras.find_on_path('check-language-support')
        for lp_locale in langpacks:
            lp = locale_to_language_pack(lp_locale)
            # Basic language packs, required to get localisation working at
            # all. We install these almost unconditionally; if you want to
            # get rid of even these, you can preseed pkgsel/language-packs
            # to the empty string.
            to_install.append('language-pack-%s' % lp)
            # Other language packs, typically selected by preseeding.
            for pattern in lppatterns:
                to_install.append(pattern.replace('$LL', lp))
            # More extensive language support packages.
            # If pkgsel/language-packs is ALL, then speed things up by
            # calling check-language-support just once.
            if not all_langpacks and checker:
                check_lang = subprocess.Popen([
                    'check-language-support', '-l',
                    lp_locale.split('.')[0], '--show-installed'
                ],
                                              stdout=subprocess.PIPE,
                                              universal_newlines=True)
                to_install.extend(check_lang.communicate()[0].strip().split())
            else:
                to_install.append('language-support-%s' % lp)
            if checker:
                # Keep language-support-$LL installed if it happens to be in
                # the live filesystem, since there's no point spending time
                # removing it; but don't install it if it isn't in the live
                # filesystem.
                toplevel = 'language-support-%s' % lp
                toplevel_pkg = get_cache_pkg(cache, toplevel)
                if toplevel_pkg and toplevel_pkg.is_installed:
                    to_install.append(toplevel)
        if all_langpacks and checker:
            check_lang = subprocess.Popen(
                ['check-language-support', '-a', '--show-installed'],
                stdout=subprocess.PIPE,
                universal_newlines=True)
            to_install.extend(check_lang.communicate()[0].strip().split())

        # Filter the list of language packs to include only language packs
        # that exist in the live filesystem's apt cache, so that we can tell
        # the difference between "no such language pack" and "language pack
        # not retrievable given apt configuration in /target" later on.
        to_install = [
            pkg for pkg in to_install if get_cache_pkg(cache, pkg) is not None
        ]

        install_new = True
        try:
            install_new_key = \
                self.db.get('pkgsel/install-language-support') == 'true'
            if install_new_key != '' and not misc.create_bool(install_new_key):
                install_new = False
        except debconf.DebconfError:
            pass

        if not install_new:
            # Keep packages that are on the live filesystem, but don't install
            # new ones.
            # TODO cjwatson 2010-03-18: To match pkgsel's semantics, we
            # ought to be willing to install packages from the package pool
            # on the CD as well.
            to_install = [
                pkg for pkg in to_install
                if get_cache_pkg(cache, pkg).is_installed
            ]

        del cache
        record_installed(to_install)

        langpacks_file = '/var/lib/ubiquity/langpacks'
        if os.path.exists(langpacks_file):
            osextras.unlink_force(langpacks_file)
        if install_new:
            if save:
                if not os.path.exists(os.path.dirname(langpacks_file)):
                    os.makedirs(os.path.dirname(langpacks_file))
                with open(langpacks_file, 'w') as langpacks:
                    for pkg in to_install:
                        print(pkg, file=langpacks)
                return []
            else:
                return to_install
Beispiel #28
0
    def do_install(self, to_install, langpacks=False):
        self.nested_progress_start()

        if langpacks:
            self.db.progress('START', 0, 10, 'ubiquity/langpacks/title')
        else:
            self.db.progress('START', 0, 10, 'ubiquity/install/title')
        self.db.progress('INFO', 'ubiquity/install/find_installables')

        self.progress_region(0, 1)
        fetchprogress = DebconfAcquireProgress(
            self.db, 'ubiquity/install/title',
            'ubiquity/install/apt_indices_starting',
            'ubiquity/install/apt_indices')

        with Cache() as cache:

            if cache._depcache.broken_count > 0:
                syslog.syslog(
                    'not installing additional packages, since there are'
                    ' broken packages: %s' % ', '.join(broken_packages(cache)))
                self.db.progress('STOP')
                self.nested_progress_end()
                return

            with cache.actiongroup():
                for pkg in to_install:
                    mark_install(cache, pkg)

            self.db.progress('SET', 1)
            self.progress_region(1, 10)
            if langpacks:
                fetchprogress = DebconfAcquireProgress(
                    self.db, 'ubiquity/langpacks/title', None,
                    'ubiquity/langpacks/packages')
                installprogress = DebconfInstallProgress(
                    self.db, 'ubiquity/langpacks/title',
                    'ubiquity/install/apt_info')
            else:
                fetchprogress = DebconfAcquireProgress(
                    self.db, 'ubiquity/install/title', None,
                    'ubiquity/install/fetch_remove')
                installprogress = DebconfInstallProgress(
                    self.db, 'ubiquity/install/title',
                    'ubiquity/install/apt_info',
                    'ubiquity/install/apt_error_install')
            chroot_setup(self.target)
            commit_error = None
            try:
                try:
                    if not self.commit_with_verify(cache, fetchprogress,
                                                   installprogress):
                        fetchprogress.stop()
                        installprogress.finish_update()
                        self.db.progress('STOP')
                        self.nested_progress_end()
                        return
                except IOError:
                    for line in traceback.format_exc().split('\n'):
                        syslog.syslog(syslog.LOG_ERR, line)
                    fetchprogress.stop()
                    installprogress.finish_update()
                    self.db.progress('STOP')
                    self.nested_progress_end()
                    return
                except SystemError as e:
                    for line in traceback.format_exc().split('\n'):
                        syslog.syslog(syslog.LOG_ERR, line)
                    commit_error = str(e)
            finally:
                chroot_cleanup(self.target)
            self.db.progress('SET', 10)

            cache.open(None)
            if commit_error or cache._depcache.broken_count > 0:
                if commit_error is None:
                    commit_error = ''
                brokenpkgs = broken_packages(cache)
                self.warn_broken_packages(brokenpkgs, commit_error)

            self.db.progress('STOP')

            self.nested_progress_end()
Beispiel #29
0
def get_languages(current_language_index=-1, only_installable=False):
    import gzip
    import icu

    current_language = "English"

    if only_installable:
        from apt.cache import Cache
        # workaround for an issue where euid != uid and the
        # apt cache has not yet been loaded causing a SystemError
        # when libapt-pkg tries to load the Cache the first time.
        with misc.raised_privileges():
            cache = Cache()

    languagelist = gzip.open(
        '/usr/lib/ubiquity/localechooser/languagelist.data.gz')
    language_display_map = {}
    i = 0
    for line in languagelist:
        line = misc.utf8(line)
        if line == '' or line == '\n':
            continue
        code, name, trans = line.strip('\n').split(':')[1:]
        if code in ('C', 'dz', 'km'):
            i += 1
            continue
        # KDE fails to round-trip strings containing U+FEFF ZERO WIDTH
        # NO-BREAK SPACE, and we don't care about the NBSP anyway, so strip
        # it.
        #   https://bugs.launchpad.net/bugs/1001542
        #   (comment # 5 and on)
        trans = trans.strip(" \ufeff")

        if only_installable:
            pkg_name = 'language-pack-%s' % code
            # special case these
            if pkg_name.endswith('_CN'):
                pkg_name = 'language-pack-zh-hans'
            elif pkg_name.endswith('_TW'):
                pkg_name = 'language-pack-zh-hant'
            elif pkg_name.endswith('_NO'):
                pkg_name = pkg_name.split('_NO')[0]
            elif pkg_name.endswith('_BR'):
                pkg_name = pkg_name.split('_BR')[0]
            try:
                pkg = cache[pkg_name]
                if not (pkg.installed or pkg.candidate):
                    i += 1
                    continue
            except KeyError:
                i += 1
                continue

        language_display_map[trans] = (name, code)
        if i == current_language_index:
            current_language = trans
        i += 1
    languagelist.close()

    if only_installable:
        del cache

    try:
        # Note that we always collate with the 'C' locale.  This is far
        # from ideal.  But proper collation always requires a specific
        # language for its collation rules (languages frequently have
        # custom sorting).  This at least gives us common sorting rules,
        # like stripping accents.
        collator = icu.Collator.createInstance(icu.Locale('C'))
    except:
        collator = None

    def compare_choice(x):
        if language_display_map[x][1] == 'C':
            return None  # place C first
        if collator:
            try:
                return collator.getCollationKey(x).getByteArray()
            except:
                pass
        # Else sort by unicode code point, which isn't ideal either,
        # but also has the virtue of sorting like-glyphs together
        return x

    sorted_choices = sorted(language_display_map, key=compare_choice)

    return current_language, sorted_choices, language_display_map
    def installButtonClicked(self):
        # if not root, start a new instance
        if os.getuid() != 0:
            if os.path.exists("gdebi-kde"):
                executable = os.path.curdir + "/gdebi-kde"
            else:
                executable = "/usr/bin/gdebi-kde"
            su_cmd = "/usr/bin/kdesudo"
            if not os.access(su_cmd, os.X_OK):
                su_cmd = "/usr/lib/kde4/libexec/kdesu"
            os.execl(su_cmd, os.path.basename(su_cmd), executable, "--", "-n",
                     self._deb.filename)
            self.kapp.exit()

        if not self.try_acquire_lock():
            KMessageBox.error(
                self, '<b>' + self.error_header + '</b><br>' + self.error_body,
                self.error_header)
            return False
        if not self.try_acquire_lock():
            KMessageBox.error(
                self, '<b>' + self.error_header + '</b><br>' + self.error_body,
                self.error_header)
            return False
        # set the window as disabled
        self.setDisabled(True)
        self.installDialog = GDebiKDEInstall(self)
        self.installDialog.show()

        # FIXME: use the new python-apt acquire interface here,
        # or rather use it in the apt module and raise exception
        # when stuff goes wrong!
        if len(self.install) > 0 or len(self.remove) > 0:
            #if not self.acquire_lock():
            if not self.acquire_lock():
                #self.show_alert(Gtk.MessageType.ERROR, self.error_header, self.error_body)
                KMessageBox.sorry(
                    self,
                    '<b>' + self.error_header + '</b><br>' + self.error_body,
                    self.error_header)
                return False
            fprogress = KDEFetchProgressAdapter(
                self.installDialog.installationProgress,
                self.installDialog.installingLabel, self.installDialog)
            iprogress = KDEInstallProgressAdapter(
                self.installDialog.installationProgress,
                self.installDialog.installingLabel, self.installDialog)
            self.installDialog.konsole.setInstallProgress(iprogress)
            #errMsg = None
            try:
                res = self._cache.commit(fprogress, iprogress)
            except IOError as msg:
                res = False
                #errMsg = "%s" % msg
                header = _("Could not download all required files")
                body = _("Please check your internet connection or "
                         "installation medium, or make sure your "
                         "APT cache is up-to-date.")
            except SystemError as msg:
                logging.warning("error: %s" % msg)
                res = False
                header = _("Could not install all dependencies")
                body = _("Usually this is related to an error of the "
                         "software distributor. See the terminal window for "
                         "more details.")
            if not res:
                #print "something bad happend"
                self.errorReport = KMessageBox.error(self,
                                                     header + "<br>" + body,
                                                     header)
                return

        # install the package itself
        #self.label_action.set_markup("<b><big>"+_("Installing package file")+"</big></b>")
        dprogress = KDEDpkgInstallProgress(
            self._deb.filename, self.installDialog.installingLabel,
            self.installDialog.installationProgress,
            self.installDialog.konsole, self.installDialog)
        dprogress.commit()
        #self.label_action.set_markup("<b><big>"+_("Package installed")+"</big></b>")
        # show the button
        #self.button_deb_install_close.set_sensitive(True)
        #self.button_deb_install_close.grab_default()
        self.installDialog.setWindowTitle(_("Installation finished"))
        if dprogress.exitstatus == 0:
            self.installDialog.installingLabel.setText(
                _("<b>" + "Package '%s' was installed" + "</b>") %
                self._deb.pkgname)
        else:
            self.installDialog.installingLabel.setText(
                "<b>" + _("Failed to install package '%s'") %
                os.path.basename(self._deb.filename) + "</b>")
            self.installDialog.konsoleFrame.show()
        #self.statusbar_main.push(self.context,_("Installation complete"))
        # FIXME: Doesn't stop notifying
        #self.window_main.set_property("urgency-hint", 1)

        # reopen the cache, reread the file, FIXME: add progress reporting
        #self._cache = Cache(self.cprogress)
        self._cache = Cache()
        if self._cache._depcache.broken_count > 0:
            header = _("Failed to completely install all dependencies")
            text = _("To fix this run 'sudo apt-get install -f' in a "
                     "terminal window.")
            self.errorReport = KMessageBox.error(self, header + text, header)
            sys.exit(1)