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()
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()
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()
def do_update(mark_only): _, progress = query_verbosity() log.info("Getting list of eligible packages...") cache = Cache(progress) f_cache = FilteredCache(cache) f_cache.set_filter(NvidiaFilter()) names = f_cache.keys() with unhold(names, cache): # mark_only means we just want the side-effects of exiting the # unhold() context manager. if mark_only: return False log.info("Updating package list...") try: cache.update() except FetchFailedException, err: log.warn(err) cache.open(progress) # Refresh package list old_versions = {name: cache[name].installed for name in names} log.info("Updating all packages...") for name in names: if cache[name].is_upgradable: cache[name].mark_upgrade() cache.commit(None, None) log.info("Refreshing package cache...") cache.open(progress) new_versions = {name: cache[name].installed for name in names} log.info("Checking whether packages were upgraded...") for name in old_versions: if old_versions[name] != new_versions[name]: log.info("Kernel module changed") return True return False
class GDebiCli(object): 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 open(self, file): try: if (file.endswith(".deb") or "Debian binary package" in Popen(["file", file], stdout=PIPE, universal_newlines=True).communicate()[0]): self._deb = DebPackage(file, self._cache) elif (file.endswith(".dsc") or os.path.basename(file) == "control"): self._deb = DscSrcPackage(file, self._cache) else: sys.stderr.write(_("Unknown package type '%s', exiting\n") % file) sys.exit(1) except (IOError,SystemError,ValueError) as e: logging.debug("error opening: %s" % e) sys.stderr.write(_("Failed to open the software package\n")) sys.stderr.write(_("The package might be corrupted or you are not " "allowed to open the file. Check the permissions " "of the file.\n")) sys.exit(1) # check the deps if not self._deb.check(): sys.stderr.write(_("This package is uninstallable\n")) sys.stderr.write(self._deb._failure_string + "\n") return False return True def show_description(self): try: print(self._deb["Description"]) except KeyError: print(_("No description is available")) def show_dependencies(self): print(self.get_dependencies_info()) def get_dependencies_info(self): s = "" # show what changes (install, remove, unauthenticated) = self._deb.required_changes if len(unauthenticated) > 0: s += _("The following packages are UNAUTHENTICATED: ") for pkgname in unauthenticated: s += pkgname + " " if len(remove) > 0: s += _("Requires the REMOVAL of the following packages: ") for pkgname in remove: s += pkgname + " " s += "\n" if len(install) > 0: s += _("Requires the installation of the following packages: ") for pkgname in install: s += pkgname + " " s += "\n" return s def install(self): # install the dependecnies (install,remove,unauthenticated) = self._deb.required_changes if len(install) > 0 or len(remove) > 0: fprogress = apt.progress.text.AcquireProgress() iprogress = apt.progress.base.InstallProgress() try: self._cache.commit(fprogress,iprogress) except(apt.cache.FetchFailedException, SystemError) as e: sys.stderr.write(_("Error during install: '%s'") % e) return 1 # install the package itself if self._deb.filename.endswith(".dsc"): # FIXME: add option to only install build-dependencies # (or build+install the deb) and then enable # this code #dir = self._deb.pkgname + "-" + apt_pkg.UpstreamVersion(self._deb["Version"]) #os.system("dpkg-source -x %s" % self._deb.filename) #os.system("cd %s && dpkg-buildpackage -b -uc" % dir) #for i in self._deb.binaries: # os.system("gdebi %s_%s_*.deb" % (i,self._deb["Version"])) return 0 else: return call(["dpkg","--auto-deconfigure", "-i",self._deb.filename])
class GDebiCli(object): 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 open(self, file): try: if (file.endswith(".deb") or "Debian binary package" in Popen( ["file", file], stdout=PIPE, universal_newlines=True).communicate()[0]): self._deb = DebPackage(file, self._cache) elif (file.endswith(".dsc") or os.path.basename(file) == "control"): self._deb = DscSrcPackage(file, self._cache) else: sys.stderr.write( _("Unknown package type '%s', exiting\n") % file) sys.exit(1) except (IOError, SystemError, ValueError) as e: logging.debug("error opening: %s" % e) sys.stderr.write(_("Failed to open the software package\n")) sys.stderr.write( _("The package might be corrupted or you are not " "allowed to open the file. Check the permissions " "of the file.\n")) sys.exit(1) # check the deps if not self._deb.check(): sys.stderr.write(_("This package is uninstallable\n")) sys.stderr.write(self._deb._failure_string + "\n") return False return True def show_description(self): try: print(self._deb["Description"]) except KeyError: print(_("No description is available")) def show_dependencies(self): print(self.get_dependencies_info()) def get_dependencies_info(self): s = "" # show what changes (install, remove, unauthenticated) = self._deb.required_changes if len(unauthenticated) > 0: s += _("The following packages are UNAUTHENTICATED: ") for pkgname in unauthenticated: s += pkgname + " " if len(remove) > 0: s += _("Requires the REMOVAL of the following packages: ") for pkgname in remove: s += pkgname + " " s += "\n" if len(install) > 0: s += _("Requires the installation of the following packages: ") for pkgname in install: s += pkgname + " " s += "\n" return s def install(self): # install the dependecnies (install, remove, unauthenticated) = self._deb.required_changes if len(install) > 0 or len(remove) > 0: fprogress = apt.progress.text.AcquireProgress() iprogress = apt.progress.base.InstallProgress() try: self._cache.commit(fprogress, iprogress) except (apt.cache.FetchFailedException, SystemError) as e: sys.stderr.write(_("Error during install: '%s'") % e) return 1 # install the package itself if self._deb.filename.endswith(".dsc"): # FIXME: add option to only install build-dependencies # (or build+install the deb) and then enable # this code #dir = self._deb.pkgname + "-" + apt_pkg.UpstreamVersion(self._deb["Version"]) #os.system("dpkg-source -x %s" % self._deb.filename) #os.system("cd %s && dpkg-buildpackage -b -uc" % dir) #for i in self._deb.binaries: # os.system("gdebi %s_%s_*.deb" % (i,self._deb["Version"])) return 0 else: return call( ["dpkg", "--auto-deconfigure", "-i", self._deb.filename])
class Transition(dbus.service.Object): 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 @dbus.service.method( 'org.pop_os.transition_system.Interface', in_signature='', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def obtain_lock(self, sender=None, conn=None): """ Lock the package system. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.transition_system.removedebs' ) print('Obtaining Package manager lock') try: self.lock = apt_pkg.get_lock('/var/lib/dpkg/lock-frontend', True) self.apt_lock = apt_pkg.get_lock('/var/lib/apt/lists/lock', True) print('Lock obtained') return True except apt_pkg.Error: print('Could not obtain lock') self.lock = None self.apt_lock = None return False @dbus.service.method( 'org.pop_os.transition_system.Interface', in_signature='', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def release_lock(self, sender=None, conn=None): """ Unlock the package system. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.transition_system.removedebs' ) print('Releasing package manager lock') try: os.close(self.lock) os.close(self.apt_lock) self.lock = None self.apt_lock = None print('Lock released') return True except: print('Could not release lock') return False @dbus.service.method( 'org.pop_os.transition_system.Interface', in_signature='', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def open_cache(self, sender=None, conn=None): """ Open the package cache. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.transition_system.removedebs' ) if self.lock and self.apt_lock: print('Opening package cache') self.cache.update() self.cache.open() print('Cache open') return True print('No lock, cannot open cache') return False @dbus.service.method( 'org.pop_os.transition_system.Interface', in_signature='', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def commit_changes(self, sender=None, conn=None): """ Commit changes to the cache. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.transition_system.removedebs' ) if self.lock and self.apt_lock: self.cache.commit() print('Committed changes to cache') return True print('No lock, Cannot commit changes') return False @dbus.service.method( 'org.pop_os.transition_system.Interface', in_signature='', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def close_cache(self, sender=None, conn=None): """ Close the package cache. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.transition_system.removedebs' ) if self.lock and self.apt_lock: self.cache.close() print('Package cache closed') return True print('No lock, cannot close cache') return False @dbus.service.method( 'org.pop_os.transition_system.Interface', in_signature='s', out_signature='s', sender_keyword='sender', connection_keyword='conn' ) def remove_package(self, package, sender=None, conn=None): """ Mark a package for removal.""" self._check_polkit_privilege( sender, conn, 'org.pop_os.transition_system.removedebs' ) if self.lock and self.apt_lock: print(f'Marking {package} for removal') try: pkg = self.cache[package] pkg.mark_delete() return pkg.name except: print(f'Could not mark {package} for removal') return '' print('No lock, cannot mark packages') return '' @dbus.service.method( 'org.pop_os.transition_system.Interface', in_signature='', out_signature='', sender_keyword='sender', connection_keyword='conn' ) def exit(self, sender=None, conn=None): if self.lock and self.apt_lock: self.close_cache() self.release_lock() mainloop.quit() def _check_polkit_privilege(self, sender, conn, privilege): '''Verify that sender has a given PolicyKit privilege. sender is the sender's (private) D-BUS name, such as ":1:42" (sender_keyword in @dbus.service.methods). conn is the dbus.Connection object (connection_keyword in @dbus.service.methods). privilege is the PolicyKit privilege string. This method returns if the caller is privileged, and otherwise throws a PermissionDeniedByPolicy exception. ''' if sender is None and conn is None: # Called locally, not through D-Bus return if not self.enforce_polkit: # For testing return if self.dbus_info is None: self.dbus_info = dbus.Interface(conn.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus/Bus', False), 'org.freedesktop.DBus') pid = self.dbus_info.GetConnectionUnixProcessID(sender) if self.polkit is None: self.polkit = dbus.Interface(dbus.SystemBus().get_object( 'org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority', False), 'org.freedesktop.PolicyKit1.Authority' ) try: (is_auth, _, details) = self.polkit.CheckAuthorization( ('unix-process', {'pid': dbus.UInt32(pid, variant_level=1), 'start-time': dbus.UInt64(0, variant_level=1)}), privilege, {'': ''}, dbus.UInt32(1), '', timeout=600 ) except dbus.DBusException as e: if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown': # polkitd timed out, connect again self.polkit = None return self._check_polkit_privilege(sender, conn, privilege) else: raise if not is_auth: raise PermissionDeniedByPolicy(privilege)
# self.apt_status = os.WEXITSTATUS(status) # self.finished = True # # def error(self, pkg, errormsg): # """Called when an error happens. # # Emits: status_error() # """ # self.emit(QtCore.SIGNAL("status_error()")) # def conffile(self, current, new): # """Called during conffile. # # Emits: status-conffile() # """ # self.emit("status-conffile") # # def start_update(self): # """Called when the update starts. # # Emits: status-started() # """ # self.emit("status-started") if __name__ =='__main__': from apt.cache import Cache import apt c = Cache(QOpProgress()) c.update(QAcquireProgress()) c.commit(QAcquireProgress(), QInstallProgress())
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') cache = 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 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 cache.commit(fetchprogress, installprogress): fetchprogress.stop() installprogress.finishUpdate() 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.finishUpdate() self.db.progress('STOP') self.nested_progress_end() return except SystemError, 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()