def upgrade_and_install(): global args, log if args.skip_update or args.local: log.info('Skipping upgrade/install') return else: import apt cache = apt.Cache() try: # repos from softwareproperties.SoftwareProperties import SoftwareProperties sp = SoftwareProperties() for repo in repositories: if sp.add_source_from_line(repo): log.info('Adding repository: %s' % repo) else: log.error('Error adding repository: %s' % repo) sp.sourceslist.save() # packages log.info('Updating package info...') cache.update() cache.open(None) cache.upgrade() log.info('Marking packages for install: %s' % ' '.join(install_packages)) for pkg in install_packages: try: cache[pkg].mark_install() except KeyError: log.error('Could not mark package for install: %s' % pkg) log.info('Committing package changes') cache.commit() except apt.cache.LockFailedException: if not args.vmesh_trying_for_sudo: log.info("Need super-user rights to upgrade and install, restarting (with sudo)") restart(with_sudo=True, add_args=['--vmesh-trying-for-sudo']) else: log.error('Could not acquire apt cache lock (someone else is installing stuff, or this user is not a sudoer)') raise log.info("Upgrade/install complete, restarting (no sudo)") restart(with_sudo=False, add_args=['--skip-update'], remove_args=['--vmesh-trying-for-sudo'])
def on_install_button_active(button, model, itemSelectCount): global pulseTimer global installStatus global cache global view global p1 # set busy flag installStatus = 'busy' # Remove CANCEL button Gtk.Container.remove(grid, cancelButton) # Count items itemCount = len(model) # Add PPA's # Set progress progressBar.set_fraction(0.1) label.set_text("Installing new software sources...") appendToLog("Installing new software sources...") # Use APT module and SoftwareProperties to add-apt sp = SoftwareProperties() for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: if ppaList[listItem] != '': progressBar.set_text("Adding PPA for " + model[listItem][1]) # add-apt the python way ! taken from add-apt code try: sp.add_source_from_line(ppaList[listItem]) debugPrint("Added PPA - %s" % ppaList[listItem]) appendToLog("Added PPA - %s" % ppaList[listItem]) except: debugPrint("[Error] Could not add PPA - %s" % ppaList[listItem]) appendToLog("[Error] Could not add PPA - %s" % ppaList[listItem]) # Save new apt list sp.sourceslist.save() progressBar.set_fraction(0.2) # Add Keys for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: if getAptKeyList[listItem] != '': debugPrint("Name : %s" % model[listItem][1]) debugPrint("Keys : %s" % getAptKeyList[listItem]) progressBar.set_text("Adding software key for " + model[listItem][1]) # Add key the bash way TODO do this differently to handle errors/timeout # First check type of key wget or apt-key adv if "recv-keys" in getAptKeyList[listItem]: keyType = 'apt-key' else: keyType = 'wget' try: if keyType == 'wget': # Just read Key URL and do the rest p1 = subprocess.Popen( ['wget', '-O', '-', getAptKeyList[listItem]], stdout=subprocess.PIPE) p2 = subprocess.Popen( ['apt-key', 'add', '--yes', '--quiet', '-'], stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.close( ) # Allow p1 to receive a SIGPIPE if p2 exits. if keyType == 'apt-key': # Run command as is p6 = subprocess.Popen([getAptKeyList[listItem]], shell=True, stdout=subprocess.PIPE) debugPrint("Key added for : %s" % model[listItem][1]) appendToLog("Key added for : %s" % model[listItem][1]) debugPrint("Key status: %s" % output) appendToLog("Key status: %s" % output) except: debugPrint("[Error] Could not add key from - %s" % getAptKeyList[listItem]) appendToLog("[Error] Could not add key from - %s" % getAptKeyList[listItem]) progressBar.set_fraction(0.3) # Manually write to file to add APT for DEB repos for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: if aptListEntryList[listItem] != '': debugPrint("Name : %s" % model[listItem][1]) debugPrint("APT : %s" % aptListEntryList[listItem]) installTitles = installTitleList[listItem].split(' ') progressBar.set_text("Adding APT Repository for " + model[listItem][1]) # write sources to file try: writeToFile( os.path.join(aptListPath, installTitles[0] + '.list'), 'deb ' + aptListEntryList[listItem] + '\n', 'w') #writeToFile(os.path.join(aptListPath, installTitles[0]+'.list'), 'deb-src '+aptListEntryList[listItem]+'\n', 'a') writeToFile( os.path.join(aptListPath, installTitles[0] + '.list.save'), 'deb ' + aptListEntryList[listItem] + '\w', 'w') #writeToFile(os.path.join(aptListPath, installTitles[0]+'.list.save'), 'deb-src '+aptListEntryList[listItem]+'\n', 'a') debugPrint("Added APT - %s" % aptListEntryList[listItem]) appendToLog("Added APT - %s" % aptListEntryList[listItem]) except: debugPrint("[Error] Could not add APT - %s" % aptListEntryList[listItem]) appendToLog("[Error] Could not add APT - %s" % aptListEntryList[listItem]) onInstallError() # Save new apt list sp.sourceslist.save() # We need to open the cache again before updating progressBar.set_fraction(0.4) progressBar.set_text('Reading Software List...') debugPrint("[Progress] Open Cache...") appendToLog("[Progress] Open Cache...") cache.open() # Now, lets update the package list progressBar.set_fraction(0.5) progressBar.set_text('Updating Software Center...') debugPrint("[Progress] Cache update...") appendToLog("[Progress] Cache update...") pulseTimer = GLib.timeout_add(100, pulse) try: cache.update() except: appendToLog("[Warning] Cache update warnings. Not fatal - continue...") debugPrint("[Warning] Cache update warnings. Not fatal - continue...") GLib.source_remove(pulseTimer) # Now we can do the same as 'apt-get upgrade' does progressBar.set_fraction(0.7) #progressBar.set_text('Updating Software ...') #print "[progress] Updating Software ..." #cache.upgrade() # or we can play 'apt-get dist-upgrade' #cache.upgrade(True) # Q: Why does nothing happen? # A: You forgot to call commit()! debugPrint("[Progress] Commit Cache...") appendToLog("[Progress] Commit Cache...") progressBar.set_fraction(0.8) progressBar.set_text('Updating Software Center...') try: #cache.commit() cache.commit(aptAcquireProgress, aptInstallProgress) except: debugPrint("[Error] apt-get update failed") # Software sources added Done progressBar.set_fraction(1) progressBar.set_text('') label.set_text('Software sources added successfully') appendToLog('Software sources added successfully') # START installing apps one by one # using itemSelectCount to do progress increments progInc = float(100 / itemSelectCount) / 100 itemIncCount = 0 progressBar.set_fraction(0.02) for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: # With selected items ... label.set_text('Installing Software ' + str(itemIncCount + 1) + ' of ' + str(itemSelectCount) + ' ...') appendToLog('[Notice] Installing Software ' + str(itemIncCount + 1) + ' of ' + str(itemSelectCount) + ' ...') # Un Install first if RE-install is selected if installStateList[listItem] == 'installed': progressBar.set_text("Removing " + model[listItem][1]) # Set focus view.set_cursor(listItem) # open cache again for each install to update new packages list cache.open() # Get package list into array installTitles = installTitleList[listItem].split(' ') # mark packages for Remove for itemToRemove in installTitles: try: cache[itemToRemove].mark_delete() debugPrint("[Remove] Marked for Removal %s" % itemToRemove) appendToLog("[Remove] Marked for Removal %s" % itemToRemove) except: debugPrint("[Error] Packages not found for %s" % model[listItem][1]) appendToLog("[Error] Packages not found for %s" % model[listItem][1]) # TODO show install failed not done installError = "[Error] Packages not found for " + model[ listItem][1] # Commit new cache and remove each set of packages try: aptAcquireProgress.start() progressTimer = GLib.timeout_add(200, renderCellProgress, model, listItem, 'remove') cache.commit(aptAcquireProgress, aptInstallProgress) aptAcquireProgress.stop() GLib.source_remove(progressTimer) # Update icon after removal model[listItem][4] = GdkPixbuf.Pixbuf.new_from_file( iconPathBlank) debugPrint("Un-Install complete for %s" % model[listItem][1]) appendToLog("Un-Install complete for %s" % model[listItem][1]) except: debugPrint("[Error] Un-Install failed for %s" % model[listItem][1]) appendToLog("[Error] Un-Install failed for %s" % model[listItem][1]) installError = "[Error] Un-Install failed for " + model[ listItem][1] # Run Pre-install commands # if item has pre-install run that now if preInstallList[listItem] != '': progressBar.set_text("Running pre-install for " + model[listItem][1]) # Run pre install commands the bash way TODO do this differently to handle errors/timeout try: p1 = subprocess.Popen([preInstallList[listItem]], shell=True, stdout=subprocess.PIPE) output = p1.communicate()[0] debugPrint("Running Pre install script for : %s" % model[listItem][1]) debugPrint("Pre install script output: %s" % output) appendToLog("Running Pre install script for : %s" % model[listItem][1]) appendToLog("Pre install script output: %s" % output) except: debugPrint("[Error] Pre install script error : %s" % model[listItem][1]) appendToLog("[Error] Pre install script error : %s" % model[listItem][1]) # Install software item FINALLY installError = '' # Initial cell progressbar value model[listItem][3] = 0 progressBar.set_text("Installing " + model[listItem][1]) debugPrint("Installing %s" % model[listItem][1]) appendToLog("Installing %s" % model[listItem][1]) # Set focus view.set_cursor(listItem) # open cache again for each install to update new packages list cache.open() # Get package list into array installTitles = installTitleList[listItem].split(' ') # mark packages for install for itemToInstall in installTitles: try: cache[itemToInstall].mark_install() debugPrint("[Install] Marked for install %s" % itemToInstall) appendToLog("[Install] Marked for install %s" % itemToInstall) except: debugPrint("[Error] Packages not found for %s" % model[listItem][1]) appendToLog("[Error] Packages not found for %s" % model[listItem][1]) # TODO show install failed not done installError = "[Error] Packages not found for " + model[ listItem][1] # Commit new cache and install each set of packages try: #cache.upgrade() aptAcquireProgress.start() progressTimer = GLib.timeout_add(200, renderCellProgress, model, listItem, 'install') cache.commit(aptAcquireProgress, aptInstallProgress) #cache.commit() debugPrint("Install complete for %s" % model[listItem][1]) appendToLog("Install complete for %s" % model[listItem][1]) except: debugPrint("[Error] Installation failed for %s" % model[listItem][1]) # TODO show install failed not done installError = "[Error] Installation failed for " + model[ listItem][1] # END of Install # Run POST-install commands # if item has post-install run that now if postInstallList[listItem] != '': progressBar.set_text("Running post-install for " + model[listItem][1]) # Run post install commands the bash way TODO do this differently to handle errors/timeout try: p1 = subprocess.Popen([postInstallList[listItem]], shell=True, stdout=subprocess.PIPE) output = p1.communicate()[0] debugPrint("Running Post install script for : %s" % model[listItem][1]) debugPrint("Post install script output: %s" % output) appendToLog("Running Post install script for : %s" % model[listItem][1]) appendToLog("Post install script output: %s" % output) except: debugPrint("[Error] Post install script error : %s" % model[listItem][1]) appendToLog("[Error] Post install script error : %s" % model[listItem][1]) # Set Cell Progress bar and deselect when done model[listItem][3] = 100 model[listItem][0] = False GLib.source_remove(progressTimer) aptAcquireProgress.stop() time.sleep(0.1) refreshGui() time.sleep(0.1) # Check if install ok and set icon if installError == '': iconPathMod = iconPathOk installStateList[listItem] = 'installed' else: iconPathMod = iconPathError installStateList[listItem] = 'error' # Set icon model[listItem][4] = GdkPixbuf.Pixbuf.new_from_file(iconPathMod) # If selected Inc for each item as we know not how many here # Move progress incrementally depending on number of install items itemIncCount = itemIncCount + 1 displayInc = progInc * itemIncCount # Update main progress bar at the end of each item install progressBar.set_fraction(displayInc) # All Done - The End - # Remove Timers GLib.source_remove(progressTimer) progressBar.set_fraction(1) progressBar.set_text('') # Stop Spinner spinner.stop() os.system("python notify.py") label.set_text('Installation Complete') debugPrint('[END] Installation Complete') appendToLog('[END] Installation Complete') # Set focus view.set_cursor(0) # Reset installstatus installStatus = 'complete' # Remove Cancel Button and spinner #Gtk.Container.remove(grid, cancelButton) Gtk.Container.remove(grid, spinner) # Activate Install Now/Done button button.set_sensitive(True)
def on_install_button_active(button, model, itemSelectCount): global pulseTimer global installStatus global cache global view global p1 # set busy flag installStatus = 'busy' # Remove CANCEL button Gtk.Container.remove(grid, cancelButton) # Count items itemCount = len(model) # Add PPA's # Set progress progressBar.set_fraction(0.1) label.set_text("Installing new software sources...") appendToLog("Installing new software sources...") # Use APT module and SoftwareProperties to add-apt sp = SoftwareProperties() for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: if ppaList[listItem] != '' : progressBar.set_text("Adding PPA for "+model[listItem][1]) # add-apt the python way ! taken from add-apt code try: sp.add_source_from_line(ppaList[listItem]) debugPrint("Added PPA - %s" % ppaList[listItem]) appendToLog("Added PPA - %s" % ppaList[listItem]) except: debugPrint("[Error] Could not add PPA - %s" % ppaList[listItem]) appendToLog("[Error] Could not add PPA - %s" % ppaList[listItem]) # Save new apt list sp.sourceslist.save() progressBar.set_fraction(0.2) # Add Keys for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: if getAptKeyList[listItem] != '' : debugPrint("Name : %s" % model[listItem][1]) debugPrint("Keys : %s" % getAptKeyList[listItem]) progressBar.set_text("Adding software key for "+model[listItem][1]) # Add key the bash way TODO do this differently to handle errors/timeout # First check type of key wget or apt-key adv if "recv-keys" in getAptKeyList[listItem] : keyType='apt-key' else: keyType='wget' try: if keyType == 'wget': # Just read Key URL and do the rest p1 = subprocess.Popen(['wget', '-O', '-', getAptKeyList[listItem]], stdout=subprocess.PIPE) p2 = subprocess.Popen(['apt-key', 'add', '--yes', '--quiet', '-'], stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. if keyType == 'apt-key': # Run command as is p6 = subprocess.Popen([getAptKeyList[listItem]], shell=True, stdout=subprocess.PIPE) debugPrint("Key added for : %s" % model[listItem][1]) appendToLog("Key added for : %s" % model[listItem][1]) debugPrint("Key status: %s" % output) appendToLog("Key status: %s" % output) except: debugPrint("[Error] Could not add key from - %s" % getAptKeyList[listItem]) appendToLog("[Error] Could not add key from - %s" % getAptKeyList[listItem]) progressBar.set_fraction(0.3) # Manually write to file to add APT for DEB repos for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: if aptListEntryList[listItem] != '' : debugPrint("Name : %s" % model[listItem][1]) debugPrint("APT : %s" % aptListEntryList[listItem]) installTitles = installTitleList[listItem].split(' ') progressBar.set_text("Adding APT Repository for "+model[listItem][1]) # write sources to file try: writeToFile(os.path.join(aptListPath, installTitles[0]+'.list'), 'deb '+aptListEntryList[listItem]+'\n', 'w') #writeToFile(os.path.join(aptListPath, installTitles[0]+'.list'), 'deb-src '+aptListEntryList[listItem]+'\n', 'a') writeToFile(os.path.join(aptListPath, installTitles[0]+'.list.save'), 'deb '+aptListEntryList[listItem]+'\w', 'w') #writeToFile(os.path.join(aptListPath, installTitles[0]+'.list.save'), 'deb-src '+aptListEntryList[listItem]+'\n', 'a') debugPrint("Added APT - %s" % aptListEntryList[listItem]) appendToLog("Added APT - %s" % aptListEntryList[listItem]) except: debugPrint("[Error] Could not add APT - %s" % aptListEntryList[listItem]) appendToLog("[Error] Could not add APT - %s" % aptListEntryList[listItem]) onInstallError() # Save new apt list sp.sourceslist.save() # We need to open the cache again before updating progressBar.set_fraction(0.4) progressBar.set_text('Reading Software List...') debugPrint("[Progress] Open Cache...") appendToLog("[Progress] Open Cache...") cache.open() # Now, lets update the package list progressBar.set_fraction(0.5) progressBar.set_text('Updating Software Center...') debugPrint("[Progress] Cache update...") appendToLog("[Progress] Cache update...") pulseTimer = GLib.timeout_add(100, pulse) try: cache.update() except: appendToLog("[Warning] Cache update warnings. Not fatal - continue...") debugPrint("[Warning] Cache update warnings. Not fatal - continue...") GLib.source_remove(pulseTimer) # Now we can do the same as 'apt-get upgrade' does progressBar.set_fraction(0.7) #progressBar.set_text('Updating Software ...') #print "[progress] Updating Software ..." #cache.upgrade() # or we can play 'apt-get dist-upgrade' #cache.upgrade(True) # Q: Why does nothing happen? # A: You forgot to call commit()! debugPrint("[Progress] Commit Cache...") appendToLog("[Progress] Commit Cache...") progressBar.set_fraction(0.8) progressBar.set_text('Updating Software Center...') try: #cache.commit() cache.commit(aptAcquireProgress, aptInstallProgress) except: debugPrint("[Error] apt-get update failed") # Software sources added Done progressBar.set_fraction(1) progressBar.set_text('') label.set_text('Software sources added successfully') appendToLog('Software sources added successfully') # START installing apps one by one # using itemSelectCount to do progress increments progInc = float(100 / itemSelectCount) / 100 itemIncCount = 0 progressBar.set_fraction(0.02) for listItem in range(itemCount): # Check which items are selected True in list column 0 itemSelected = model[listItem][0] if itemSelected: # With selected items ... label.set_text('Installing Software '+str(itemIncCount+1)+' of '+str(itemSelectCount)+' ...') appendToLog('[Notice] Installing Software '+str(itemIncCount+1)+' of '+str(itemSelectCount)+' ...') # Un Install first if RE-install is selected if installStateList[listItem] == 'installed': progressBar.set_text("Removing "+model[listItem][1]) # Set focus view.set_cursor(listItem) # open cache again for each install to update new packages list cache.open() # Get package list into array installTitles = installTitleList[listItem].split(' ') # mark packages for Remove for itemToRemove in installTitles: try: cache[itemToRemove].mark_delete() debugPrint("[Remove] Marked for Removal %s" % itemToRemove ) appendToLog("[Remove] Marked for Removal %s" % itemToRemove ) except: debugPrint("[Error] Packages not found for %s" % model[listItem][1] ) appendToLog("[Error] Packages not found for %s" % model[listItem][1] ) # TODO show install failed not done installError = "[Error] Packages not found for " + model[listItem][1] # Commit new cache and remove each set of packages try: aptAcquireProgress.start() progressTimer = GLib.timeout_add(200, renderCellProgress, model, listItem, 'remove') cache.commit(aptAcquireProgress, aptInstallProgress) aptAcquireProgress.stop() GLib.source_remove(progressTimer) # Update icon after removal model[listItem][4] = GdkPixbuf.Pixbuf.new_from_file(iconPathBlank) debugPrint("Un-Install complete for %s" % model[listItem][1] ) appendToLog("Un-Install complete for %s" % model[listItem][1] ) except: debugPrint("[Error] Un-Install failed for %s" % model[listItem][1] ) appendToLog("[Error] Un-Install failed for %s" % model[listItem][1] ) installError = "[Error] Un-Install failed for " + model[listItem][1] # Run Pre-install commands # if item has pre-install run that now if preInstallList[listItem] != '' : progressBar.set_text("Running pre-install for "+model[listItem][1]) # Run pre install commands the bash way TODO do this differently to handle errors/timeout try: p1 = subprocess.Popen([preInstallList[listItem]], shell=True, stdout=subprocess.PIPE) output = p1.communicate()[0] debugPrint("Running Pre install script for : %s" % model[listItem][1]) debugPrint("Pre install script output: %s" % output) appendToLog("Running Pre install script for : %s" % model[listItem][1]) appendToLog("Pre install script output: %s" % output) except: debugPrint("[Error] Pre install script error : %s" % model[listItem][1]) appendToLog("[Error] Pre install script error : %s" % model[listItem][1]) # Install software item FINALLY installError = '' # Initial cell progressbar value model[listItem][3] = 0 progressBar.set_text("Installing "+model[listItem][1]) debugPrint("Installing %s" % model[listItem][1]) appendToLog("Installing %s" % model[listItem][1]) # Set focus view.set_cursor(listItem) # open cache again for each install to update new packages list cache.open() # Get package list into array installTitles = installTitleList[listItem].split(' ') # mark packages for install for itemToInstall in installTitles: try: cache[itemToInstall].mark_install() debugPrint("[Install] Marked for install %s" % itemToInstall ) appendToLog("[Install] Marked for install %s" % itemToInstall ) except: debugPrint("[Error] Packages not found for %s" % model[listItem][1] ) appendToLog("[Error] Packages not found for %s" % model[listItem][1] ) # TODO show install failed not done installError = "[Error] Packages not found for " + model[listItem][1] # Commit new cache and install each set of packages try: #cache.upgrade() aptAcquireProgress.start() progressTimer = GLib.timeout_add(200, renderCellProgress, model, listItem, 'install') cache.commit(aptAcquireProgress, aptInstallProgress) #cache.commit() debugPrint("Install complete for %s" % model[listItem][1] ) appendToLog("Install complete for %s" % model[listItem][1] ) except: debugPrint("[Error] Installation failed for %s" % model[listItem][1] ) # TODO show install failed not done installError = "[Error] Installation failed for " + model[listItem][1] # END of Install # Run POST-install commands # if item has post-install run that now if postInstallList[listItem] != '' : progressBar.set_text("Running post-install for "+model[listItem][1]) # Run post install commands the bash way TODO do this differently to handle errors/timeout try: p1 = subprocess.Popen([postInstallList[listItem]], shell=True, stdout=subprocess.PIPE) output = p1.communicate()[0] debugPrint("Running Post install script for : %s" % model[listItem][1]) debugPrint("Post install script output: %s" % output) appendToLog("Running Post install script for : %s" % model[listItem][1]) appendToLog("Post install script output: %s" % output) except: debugPrint("[Error] Post install script error : %s" % model[listItem][1]) appendToLog("[Error] Post install script error : %s" % model[listItem][1]) # Set Cell Progress bar and deselect when done model[listItem][3] = 100 model[listItem][0] = False GLib.source_remove(progressTimer) aptAcquireProgress.stop() time.sleep(0.1) refreshGui() time.sleep(0.1) # Check if install ok and set icon if installError == '': iconPathMod = iconPathOk installStateList[listItem]='installed' else: iconPathMod = iconPathError installStateList[listItem]='error' # Set icon model[listItem][4] = GdkPixbuf.Pixbuf.new_from_file(iconPathMod) # If selected Inc for each item as we know not how many here # Move progress incrementally depending on number of install items itemIncCount = itemIncCount + 1 displayInc = progInc * itemIncCount # Update main progress bar at the end of each item install progressBar.set_fraction(displayInc) # All Done - The End - # Remove Timers GLib.source_remove(progressTimer) progressBar.set_fraction(1) progressBar.set_text('') # Stop Spinner spinner.stop() os.system("python notify.py") label.set_text('Installation Complete') debugPrint('[END] Installation Complete') appendToLog('[END] Installation Complete') # Set focus view.set_cursor(0) # Reset installstatus installStatus = 'complete' # Remove Cancel Button and spinner #Gtk.Container.remove(grid, cancelButton) Gtk.Container.remove(grid, spinner) # Activate Install Now/Done button button.set_sensitive(True)
# Import softwareproperties try: from softwareproperties.SoftwareProperties import SoftwareProperties except ImportError: pkg = apt_cache['python-software-properties'] if pkg.is_installed: logger.error('Package: python-software-propertiesis already installed but python cannot import library.') else: pkg.mark_install() try: apt_cache.commit() from softwareproperties.SoftwareProperties import SoftwareProperties except Exception, err: logger.error('Package installation has failed: %s', str(err)) sys.exit(1) # Add ppa logger.debug('Add Openvswitch PPA') sp = SoftwareProperties() sp.add_source_from_line('ppa:sgran/openvswitch-precise') sp.sourceslist.save() logger.debug(subprocess.check_output('apt-get update',shell=True)) new_apt_cache = apt.cache.Cache() apt_cache = new_apt_cache main(args) logger.info('Finished!') sys.exit(0)
class PPA(dbus.service.Object): def __init__(self, conn=None, object_path=None, bus_name=None): dbus.service.Object.__init__(self, conn, object_path, bus_name) # These are used by PolKit to check privileges self.dbus_info = None self.polkit = None self.enforce_polkit = True try: self.system_repo = repolib.SystemSource() except: self.system_repo = None self.sp = SoftwareProperties() self.cache = apt.Cache() @dbus.service.method( "org.pop_os.repoman.Interface", in_signature='', out_signature='', sender_keyword='sender', connection_keyword='conn' ) def exit(self, sender=None, conn=None): mainloop.quit() @dbus.service.method( "org.pop_os.repoman.Interface", in_signature='b', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def set_system_source_code_enabled(self, enabled, sender=None, conn=None): """ Enable or disable source code in the system source. Arguments: enabled (bool): The new state to set, True = Enabled. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) if self.system_repo: self.system_repo.load_from_file() new_types = [repolib.util.AptSourceType.BINARY] if enabled: new_types.append(repolib.util.AptSourceType.SOURCE) self.system_repo.types = new_types self.system_repo.save_to_disk() return enabled return False @dbus.service.method( "org.pop_os.repoman.Interface", in_signature='sb', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def set_system_comp_enabled(self, comp, enable, sender=None, conn=None): """ Enable or disable a component in the system source. Arguments: comp (str): the component to set enable (bool): The new state to set, True = Enabled. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) if self.system_repo: self.system_repo.load_from_file() self.system_repo.set_component_enabled(component=comp, enabled=enable) self.system_repo.save_to_disk() return True return False @dbus.service.method( "org.pop_os.repoman.Interface", in_signature='sb', out_signature='b', sender_keyword='sender', connection_keyword='conn' ) def set_system_suite_enabled(self, suite, enable, sender=None, conn=None): """ Enable or disable a suite in the system source. Arguments: suite (str): the suite to set enable (bool): The new state to set, True = Enabled. """ self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) if self.system_repo: self.system_repo.load_from_file() self.system_repo.set_suite_enabled(suite=suite, enabled=enable) self.system_repo.save_to_disk() return True return False ## TODO: These are old SoftwareProperties Methods, and need to be replaced. @dbus.service.method( 'org.pop_os.repoman.Interface', in_signature='s', out_signature='bs', sender_keyword='sender', connection_keyword='conn' ) def add_repo(self, line, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) try: self.sp.add_source_from_line(line) self.sp.sourceslist.save() self.cache.open() self.cache.update() self.cache.open(None) self.sp.reload_sourceslist() return [True, ''] except Exception as e: print(str(e)) return [False, str(e)] @dbus.service.method( 'org.pop_os.repoman.Interface', in_signature='s', out_signature='bs', sender_keyword='sender', connection_keyword='conn' ) def delete_repo(self, repo, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) try: self.sp.remove_source(repo, remove_source_code=True) self.sp.sourceslist.save() self.cache.open() self.cache.update() self.cache.open(None) self.sp.reload_sourceslist() return [True, ''] except Exception as e: print(str(e)) return [False, str(e)] @dbus.service.method( 'org.pop_os.repoman.Interface', in_signature='ss', out_signature='bs', sender_keyword='sender', connection_keyword='conn' ) def modify_repo(self, old_repo, new_repo, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) try: old_source = self._find_source_from_string(old_repo) index = self.sp.sourceslist.list.index(old_source) file = self.sp.sourceslist.list[index].file new_source_entry = SourceEntry(new_repo, file) self.sp.sourceslist.list[index] = new_source_entry self.sp.sourceslist.save() self.cache.open() self.cache.update() self.cache.open(None) self.sp.reload_sourceslist() return [True, ''] except Exception as e: print(str(e)) return [False, str(e)] @dbus.service.method( 'org.pop_os.repoman.Interface', in_signature='b', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def set_source_code_enabled(self, enabled, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) if enabled: self.sp.enable_source_code_sources() else: self.sp.disable_source_code_sources() return 0 @dbus.service.method( 'org.pop_os.repoman.Interface', in_signature='sb', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def set_child_enabled(self, child, enabled, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) if enabled: self.sp.enable_child_source(child) else: self.sp.disable_child_source(child) return 0 @dbus.service.method( 'org.pop_os.repoman.Interface', in_signature='sb', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def set_comp_enabled(self, comp, enabled, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'org.pop_os.repoman.modifysources' ) if enabled: self.sp.enable_component(comp) else: self.sp.disable_component(comp) return 0 def _find_source_from_string(self, line): # ensure that we have a current list, it might have been changed underneath # us self.sp.reload_sourceslist() for source in self.sp.sourceslist.list: if str(source) == line: return source return None @classmethod def _log_in_file(klass, filename, string): date = time.asctime(time.localtime()) ff = open(filename, "a") ff.write("%s : %s\n" %(date,str(string))) ff.close() @classmethod def _strip_source_line(self, source): source = source.replace("#", "# ") source = source.replace("[", "") source = source.replace("]", "") source = source.replace("'", "") source = source.replace(" ", " ") return source def _check_polkit_privilege(self, sender, conn, privilege): # from jockey '''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: # that happens for testing purposes when running on the session # bus, and it does not make sense to restrict operations here return # get peer PID 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) # query PolicyKit 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: # we don't need is_challenge return here, since we call with AllowUserInteraction (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: PPA._log_in_file('/tmp/repoman.log','_check_polkit_privilege: sender %s on connection %s pid %i is not authorized for %s: %s' % (sender, conn, pid, privilege, str(details))) raise PermissionDeniedByPolicy(privilege)
class PPAObject(dbus.service.Object): cache = apt.Cache() def __init__(self, conn=None, object_path=None, bus_name=None): dbus.service.Object.__init__(self, conn, object_path, bus_name) # The following variables are used bu _check_polkit_privilege self.dbus_info = None self.polkit = None self.enforce_polkit = True self.sp = SoftwareProperties() @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='s', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def DelPPA(self, ppa, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'ro.santopiet.repoman.delppa' ) # PPA Remove code here try: self.sp.reload_sourceslist() self.sp.remove_source(ppa, remove_source_code=True) self.sp.sourceslist.save() self.sp.reload_sourceslist() return 0 except: raise AptException("Could not remove the APT Source") @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='s', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def AddPPA(self, ppa, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'ro.santopiet.repoman.addppa' ) # PPA Add code here try: self.sp.reload_sourceslist() self.sp.add_source_from_line(ppa) self.sp.sourceslist.save() self.sp.reload_sourceslist() return 0 except: raise AptException("Could not remove the APT Source") @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='ss', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def ModifyPPA(self, old_source, new_source, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'ro.santopiet.repoman.modppa' ) # PPA Modify code here try: self.sp.reload_sourceslist() old_source = self._strip_source_line(old_source) isvs = self.sp.get_isv_sources() for i in isvs: if str(i) == old_source: source = i index = self.sp.sourceslist.list.index(source) file = self.sp.sourceslist.list[index].file new_source_entry = SourceEntry(new_source,file) self.sp.sourceslist.list[index] = new_source_entry self.sp.sourceslist.save() self.cache.open() self.cache.update() self.cache.open(None) self.cache.close() self.sp.reload_sourceslist() return 0 except: raise AptException("Could not modify the APT Source") @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='sb', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def SetCompEnabled(self, comp_name, is_enabled, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'ro.santopiet.repoman.modppa' ) # PPA Modify code here if is_enabled: self.sp.enable_component(comp_name) else: self.sp.disable_component(comp_name) return 0 @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='sb', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def SetChildEnabled(self, child_name, is_enabled, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'ro.santopiet.repoman.modppa' ) # PPA Modify code here repos = self.sp.distro.source_template.children for repo in repos: if repo.name == child_name: child = repo if is_enabled: self.sp.enable_child_source(child) else: self.sp.disable_child_source(child) return 0 @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='b', out_signature='i', sender_keyword='sender', connection_keyword='conn' ) def SetSourceCodeEnabled(self, is_enabled, sender=None, conn=None): self._check_polkit_privilege( sender, conn, 'ro.santopiet.repoman.modppa' ) # PPA Modify code here if is_enabled: self.sp.enable_source_code_sources() else: self.sp.disable_source_code_sources() return 0 @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='', out_signature='', sender_keyword='sender', connection_keyword='conn' ) def RaiseException(self, sender=None, conn=None): raise RepomanException('Error managing software sources!') @dbus.service.method( "ro.santopiet.repoman.Interface", in_signature='', out_signature='', sender_keyword='sender', connection_keyword='conn' ) def Exit(self, sender=None, conn=None): mainloop.quit() @classmethod def _log_in_file(klass, filename, string): date = time.asctime(time.localtime()) ff = open(filename, "a") ff.write("%s : %s\n" %(date,str(string))) ff.close() @classmethod def _strip_source_line(self, source): source = source.replace("#", "# ") source = source.replace("[", "") source = source.replace("]", "") source = source.replace("'", "") source = source.replace(" ", " ") return source def _check_polkit_privilege(self, sender, conn, privilege): # from jockey '''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: # that happens for testing purposes when running on the session # bus, and it does not make sense to restrict operations here return # get peer PID 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) # query PolicyKit 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: # we don't need is_challenge return here, since we call with AllowUserInteraction (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: PPAObject._log_in_file('/tmp/repoman.log','_check_polkit_privilege: sender %s on connection %s pid %i is not authorized for %s: %s' % (sender, conn, pid, privilege, str(details))) raise PermissionDeniedByPolicy(privilege)
################################ PPA_LIST = open(PSTACK[0]+"ppa.lst").read().rstrip("\n") if len( PPA_LIST ) == 0: print "###################################################" print "# NO REPOSITORIES ARE MISSING #" print "###################################################" print "" else: PPA_LIST = PPA_LIST.split("\n") print "###################################################" print "# ADDING %i MISSING REPOSITORIES #" % (len(PPA_LIST)) print "###################################################" for PPA in PPA_LIST: if PPA != None and PPA != "": sp = SoftwareProperties() sp.add_source_from_line( PPA ) sp.sourceslist.save() print "" print "" ################################ ## INSTALL MISSING PROGRAMS ## ################################ APT_LIST = open("apt.lst").read().rstrip("\n") if len(APT_LIST) == 0: print "###################################################" print "# NO SOFTWARE TO INSTALLING #" print "###################################################" print elif "A" == "B":