Beispiel #1
0
def _apply_update(fname, status):

    try:
        xml = etree(fname)
    except:
        return "read %s failed" % fname

    fpl = xml.node("fullpkgs")

    sources = apt_pkg.SourceList()
    sources.read_main_list()

    status.log("initialize apt")
    apt_pkg.init()
    cache = apt_pkg.Cache(progress=ElbeOpProgress(cb=status.log))

    status.set_progress(1)
    status.log("updating package cache")
    cache.update(ElbeAcquireProgress(cb=status.log), sources)
    # quote from python-apt api doc: "A call to this method does not affect the
    # current Cache object, instead a new one should be created in order to use
    # the changed index files."
    cache = apt_pkg.Cache(progress=ElbeOpProgress(cb=status.log))
    depcache = apt_pkg.DepCache(cache)
    hl_cache = apt.cache.Cache(progress=ElbeOpProgress(cb=status.log))
    hl_cache.update(fetch_progress=ElbeAcquireProgress(cb=status.log))

    # go through package cache, if a package is in the fullpkg list of the XML
    #  mark the package for installation (with the specified version)
    #  if it is not mentioned in the fullpkg list purge the package out of the
    #  system.
    status.set_progress(2)
    status.log("calculating packages to install/remove")
    count = len(hl_cache)
    step = count / 10
    i = 0
    percent = 0
    for p in hl_cache:
        i = i + 1
        if not (i % step):
            percent = percent + 10
            status.log(str(percent) + "% - " + str(i) + "/" + str(count))
            status.set_progress(2, str(percent) + "%")

        pkg = cache[p.name]
        marked = False
        for fpi in fpl:
            if pkg.name == fpi.et.text:
                mark_install(depcache, pkg, fpi.et.get('version'),
                             fpi.et.get('auto'), status)
                marked = True

        if not marked:
            depcache.mark_delete(pkg, True)

    status.set_progress(3)
    status.log("applying snapshot")
    depcache.commit(ElbeAcquireProgress(cb=status.log),
                    ElbeInstallProgress(cb=status.log))
    del depcache
    del hl_cache
    del cache
    del sources

    version_file = open("/etc/updated_version", "w")
    version_file.write(xml.text("/project/version"))
    version_file.close()
Beispiel #2
0
    def __init__(self):

        self.selected_language = None
        self.selected_language_packs = None

        self.language_packs = []
        with codecs.open("/usr/share/linuxmint/mintlocale/language_packs",
                         'r',
                         encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                columns = line.split(":")
                if len(columns) == 4:
                    (category, language, dependency, package) = columns
                    if package.endswith("-"):
                        self.language_packs.append(
                            LanguagePack(category, language, dependency,
                                         "%sLANG" % package))
                        self.language_packs.append(
                            LanguagePack(category, language, dependency,
                                         "%sLANG-COUNTRY" % package))
                    else:
                        self.language_packs.append(
                            LanguagePack(category, language, dependency,
                                         package))

        apt_pkg.init()
        self.cache = apt_pkg.Cache(None)
        self.cache_updated = False

        self.builder = Gtk.Builder()
        self.builder.set_translation_domain("mintlocale")
        self.builder.add_from_file(
            '/usr/share/linuxmint/mintlocale/install_remove.ui')
        self.window = self.builder.get_object("main_window")
        self.window.set_icon_name("preferences-desktop-locale")
        self.builder.get_object("main_window").connect("destroy",
                                                       Gtk.main_quit)

        self.treeview = self.builder.get_object("treeview_language_list")

        self.builder.get_object("main_window").set_title(
            _("Install / Remove Languages"))
        self.builder.get_object("main_window").set_icon_name(
            "preferences-desktop-locale")
        self.builder.get_object("main_window").connect("destroy",
                                                       Gtk.main_quit)
        self.builder.get_object("button_close").connect(
            "clicked", Gtk.main_quit)
        self.builder.get_object("button_install").connect(
            "clicked", self.button_install_clicked)
        self.builder.get_object("button_add").connect("clicked",
                                                      self.button_add_clicked)
        self.builder.get_object("button_remove").connect(
            "clicked", self.button_remove_clicked)

        ren = Gtk.CellRendererPixbuf()
        column = Gtk.TreeViewColumn("Flags", ren)
        column.add_attribute(ren, "pixbuf", 2)
        ren.set_property('ypad', 5)
        ren.set_property('xpad', 10)
        self.treeview.append_column(column)

        ren = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Languages", ren)
        column.add_attribute(ren, "markup", 0)
        self.treeview.append_column(column)

        ren = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Packs", ren)
        column.add_attribute(ren, "markup", 3)
        ren.set_property('xpad', 10)
        self.treeview.append_column(column)

        self.build_lang_list()

        self.apt = mintcommon.aptdaemon.APT(self.window)
Beispiel #3
0
def scan_and_store_packages(cursor,
                            sysname,
                            fake_null=False,
                            architecture=None):
    '''updates the system <sysname> with the current package state
	if <fake_null> is True put '' instead of None in the vername field'''
    delete_packages = '''
	DELETE FROM packages_on_systems
           WHERE sysname = %(sysname)s
	'''  # noqa: E101
    insert_statement = '''
	INSERT INTO packages_on_systems (scandate,
                                     sysname,
                                     currentstate,
                                     inststate,
                                     inststatus,
                                     pkgname,
                                     selectedstate,
                                     vername)
           VALUES
	'''  # noqa: E101
    insert_value = '''(
	CURRENT_TIMESTAMP,
	%(sysname)s,
	%(currentstate)s,
	%(inststate)s,
	%(inststatus)s,
	%(pkgname)s,
	%(selectedstate)s,
	%(vername)s)
	'''
    if scan_and_store_packages.cache is None:
        apt_pkg.init()
        scan_and_store_packages.cache = apt_pkg.Cache()
    cursor.execute(delete_packages, {
        'sysname': sysname,
    })
    insert_values = []
    for package in scan_and_store_packages.cache.packages:
        if not package.has_versions:
            continue
        if architecture is not None and architecture != package.architecture:
            continue
        parameters = {
            'sysname': sysname,
            'currentstate': package.current_state,
            'inststate': package.inst_state,
            'inststatus': 'n',
            'pkgname': package.name,
            'selectedstate': package.selected_state,
            'vername': None,
        }
        if fake_null:
            parameters['vername'] = ''
        if package.current_ver:
            parameters['inststatus'] = 'i'
            parameters['vername'] = package.current_ver.ver_str
        insert_values.append(cursor._quoteparams(insert_value, parameters))
    if insert_values:
        insert_statement += ','.join(insert_values)
        cursor.execute(insert_statement)
#!/usr/bin/python

import apt_pkg

apt_pkg.init()

sources = apt_pkg.SourceList()
sources.read_main_list()

cache = apt_pkg.Cache()
depcache = apt_pkg.DepCache(cache)
pkg = cache["libimlib2"]
cand = depcache.get_candidate_ver(pkg)
for (f, i) in cand.file_list:
    index = sources.find_index(f)
    print index
    if index:
        print index.size
        print index.is_trusted
        print index.exists
        print index.Haspackages
        print index.archive_uri("some/path")
Beispiel #5
0
 def setUp(self):
     apt_pkg.init()
     self.cache = apt_pkg.Cache(progress=None)
Beispiel #6
0
def run_command(argv):

    # pylint: disable=too-many-locals
    # pylint: disable=too-many-branches

    oparser = OptionParser(
        usage="usage: %prog pkgdiff [options] <rfs1> <rfs2>")
    oparser.add_option("--noauto",
                       action="store_true",
                       dest="noauto",
                       default=False,
                       help="Dont compare automatically installed Packages")
    (opt, args) = oparser.parse_args(argv)

    if len(args) != 2:
        print("Wrong number of arguments")
        oparser.print_help()
        sys.exit(20)

    gen_rfs = args[0]
    fix_rfs = args[1]

    x = os.path.join(gen_rfs, 'etc/elbe_base.xml')
    xml = ElbeXML(x,
                  skip_validate=True,
                  url_validation=ValidationMode.NO_CHECK)
    arch = xml.text('project/arch', key='arch')

    apt_pkg.init_config()
    apt_pkg.config.set('RootDir', gen_rfs)
    apt_pkg.config.set('APT::Architecture', arch)
    apt_pkg.init_system()
    gen_cache = apt_pkg.Cache(apt.progress.base.OpProgress())
    gc = apt.Cache()

    gen_pkgs = {}
    # pylint: disable=E1133
    for p in gen_cache.packages:
        if opt.noauto:
            if p.current_ver and not \
               gc[p.name].is_auto_installed and not \
               p.essential:
                gen_pkgs[p.name] = p.current_ver
        else:
            if p.current_ver and not p.essential:
                gen_pkgs[p.name] = p.current_ver

    apt_pkg.init_config()
    apt_pkg.config.set('RootDir', fix_rfs)
    apt_pkg.config.set('APT::Architecture', arch)
    apt_pkg.init_system()
    fix_cache = apt_pkg.Cache(apt.progress.base.OpProgress())
    fc = apt.Cache()

    fix_pkgs = {}
    # pylint: disable=E1133
    for p in fix_cache.packages:
        if opt.noauto:
            if p.current_ver and not \
               fc[p.name].is_auto_installed and not \
               p.essential:
                fix_pkgs[p.name] = p.current_ver
        else:
            if p.current_ver and not p.essential:
                fix_pkgs[p.name] = p.current_ver

    for p in fix_pkgs:
        if p not in gen_pkgs:
            print("+<pkg>%s</pkg>" % p)

    for p in gen_pkgs:
        if p not in fix_pkgs.keys():
            print("-<pkg>%s</pkg>" % p)

    for p in fix_pkgs:
        if p in gen_pkgs.keys() and fix_pkgs[p] != gen_pkgs[p]:
            print("%s: Version mismatch %s != %s" %
                  (p, fix_pkgs[p], gen_pkgs[p]))
    def listUpdates(self):
        SYNAPTIC_PINFILE = "/var/lib/synaptic/preferences"
        DISTRO = 'bionic'

        def clean(cache, depcache):
            """ unmark (clean) all changes from the given depcache """
            # mvo: looping is too inefficient with the new auto-mark code
            # for pkg in cache.Packages:
            #    depcache.MarkKeep(pkg)
            depcache.init()

        def saveDistUpgrade(cache, depcache):
            """ this functions mimics a upgrade but will never remove anything """
            depcache.upgrade(True)
            if depcache.del_count > 0:
                clean(cache, depcache)
            depcache.upgrade()

        def isSecurityUpgrade(pkg, depcache):
            def isSecurityUpgrade_helper(ver):
                """ check if the given version is a security update (or masks one) """
                security_pockets = [("Ubuntu", "%s-security" % DISTRO),
                                    ("gNewSense", "%s-security" % DISTRO),
                                    ("Debian", "%s-updates" % DISTRO)]

                for (file, index) in ver.file_list:
                    for origin, archive in security_pockets:
                        if (
                                file.archive == archive and file.origin == origin):
                            return True
                return False

            inst_ver = pkg.current_ver
            cand_ver = depcache.get_candidate_ver(pkg)

            if isSecurityUpgrade_helper(cand_ver):
                return True

            # now check for security updates that are masked by a
            # canidate version from another repo (-proposed or -updates)
            for ver in pkg.version_list:
                if (inst_ver and
                        apt_pkg.version_compare(ver.ver_str,
                                                inst_ver.ver_str) <= 0):
                    # print "skipping '%s' " % ver.VerStr
                    continue
                if isSecurityUpgrade_helper(ver):
                    return True

            return False

        """
        Return a list of dict about package updates
        """
        appstream_cpts = []
        app_updates = []
        system_updates = []
        security_updates = []

        for i in self.pool.get_components():
            appstream_cpts.append(self.appSummery(i.props.id))

        apt_pkg.init()
        # force apt to build its caches in memory for now to make sure
        # that there is no race when the pkgcache file gets re-generated
        apt_pkg.config.set("Dir::Cache::pkgcache", "")

        try:
            cache = apt_pkg.Cache(apt.progress.base.OpProgress())
        except SystemError as e:
            sys.stderr.write("Error: Opening the cache (%s)" % e)
            sys.exit(-1)

        depcache = apt_pkg.DepCache(cache)
        # read the pin files
        depcache.read_pinfile()
        # read the synaptic pins too
        if os.path.exists(SYNAPTIC_PINFILE):
            depcache.read_pinfile(SYNAPTIC_PINFILE)
        # init the depcache
        depcache.init()

        try:
            saveDistUpgrade(cache, depcache)
        except SystemError as e:
            sys.stderr.write("Error: Marking the upgrade (%s)" % e)
            sys.exit(-1)

        # use assignment here since apt.Cache() doesn't provide a __exit__ method
        # on Ubuntu 12.04 it looks like
        # aptcache = apt.Cache()
        for pkg in cache.packages:
            if not (depcache.marked_install(
                    pkg) or depcache.marked_upgrade(pkg)):
                continue
            inst_ver = pkg.current_ver
            cand_ver = depcache.get_candidate_ver(pkg)
            if cand_ver == inst_ver:
                continue
            if isSecurityUpgrade(pkg, depcache):
                security_updates.append(pkg.name)
            else:
                system_updates.append(pkg.name)

        appstream_pkgs = []
        for i in appstream_cpts:
            try:
                as_pkg = i['pkg'][0]
            except IndexError:
                pass

            for package in system_updates + security_updates:
                if package == as_pkg:
                    app_updates.append(i)

            appstream_pkgs.append(as_pkg)

        for i in list(set(appstream_pkgs).intersection(system_updates)):
            system_updates.remove(i)

        for i in list(set(appstream_pkgs).intersection(security_updates)):
            security_updates.remove(i)

        app_updates = sorted(app_updates, key=itemgetter('name'))
        system_updates = sorted(system_updates)
        security_updates = sorted(security_updates)
        return app_updates, system_updates, security_updates
Beispiel #8
0
 def setUp(self):
     testcommon.TestCase.setUp(self)
     self.cache = apt_pkg.Cache(progress=None)
Beispiel #9
0
 def update(self):
     self.cache = apt_pkg.Cache(None)
     self.depcache = apt_pkg.DepCache(self.cache)
Beispiel #10
0
def init():
    "Initialize apt and prepare it for dependency solving."

    global cache

    if cache:
        raise RuntimeError, "apt is already initialized"

    global_conf = picax.config.get_config()
    base_dir = global_conf["temp_dir"] + "/apt-info"
    path = global_conf["base_path"]

    distro_hash = {}
    for (distro, comp) in global_conf["repository_list"]:
        if not distro_hash.has_key(distro):
            distro_hash[distro] = []
        distro_hash[distro].append(comp)
    distro_list = [(x, distro_hash[x]) for x in distro_hash.keys()]

    subdirs = ("state", "state/lists", "state/lists/partial", "cache",
               "cache/archives", "cache/archives/partial")

    if os.path.exists(base_dir):
        shutil.rmtree(base_dir)
    os.mkdir(base_dir)

    for subdir in subdirs:
        os.mkdir(base_dir + "/" + subdir)

    status = open("%s/state/status" % (base_dir, ), "w")
    status.close()

    conf = open("%s/apt.conf" % (base_dir, ), "w")
    conf.write("""
APT
{
  Architecture "%s";
};
Dir "%s/"
{
  State "state/" {
    status "status";
  };
  Cache "cache/";
  Etc "%s/";
};
""" % (global_conf['arch'], base_dir, base_dir))
    conf.close()

    slist = open("%s/sources.list" % (base_dir, ), "w")
    for (distro, components) in distro_list:
        for component in components:
            slist.write("deb file://%s %s %s\n" % (path, distro, component))
    if global_conf.has_key("correction_apt_repo"):
        slist.write(global_conf["correction_apt_repo"] + "\n")
    slist.close()

    os.system("apt-get --config-file %s/apt.conf update" % (base_dir, ))

    # Add base media to apt's cache.

    for base_media_dir in global_conf["base_media"]:
        os.system("apt-cdrom --config-file %s/apt.conf -d %s -m add" %
                  (base_dir, base_media_dir))

    # Initialize the python-apt bindings.

    apt_pkg.init_config()
    apt_pkg.read_config_file(apt_pkg.config, "%s/apt.conf" % (base_dir, ))
    apt_pkg.init_system()

    cache = apt_pkg.Cache()
    global_conf["apt_path"] = base_dir
    def __init__(self):

        # create bus, call super

        icontheme = gtk.icon_theme_get_default()
        pixbuf = icontheme.load_icon("screenlets", 24, 0)
        pixbuf_tray = icontheme.load_icon("screenlets-tray", 24, 0)

        session_bus = dbus.SessionBus()
        bus_name = dbus.service.BusName(SLD_BUS, bus=session_bus)
        dbus.service.Object.__init__(self, bus_name, SLD_PATH)
        # init properties
        self.running_screenlets = []
        self.menu = None
        # get list of currently open screenlets from system
        running = utils.list_running_screenlets()
        if running:
            self.running_screenlets = running
        try:
            ini = utils.IniReader()
            if ini.load(os.path.join(screenlets.DIR_CONFIG, 'config.ini')):
                self.show_in_tray = ini.get_option('show_in_tray',
                                                   section='Options')
        except:
            self.show_in_tray = 'True'
        if self.show_in_tray == 'True':

            self.init_menu()

            has_app_indicator = False
            try:
                import appindicator
                import apt_pkg

                apt_pkg.init()
                cache = apt_pkg.Cache()

                if apt_pkg.version_compare(
                        cache['python-appindicator'].current_ver.ver_str,
                        '0.3.0') >= 0:
                    #print "INDICATOR"
                    has_app_indicator = True
            except Exception:
                pass

            if has_app_indicator:

                self.app_indicator = appindicator.Indicator(
                    "screenlets", "screenlets-tray",
                    appindicator.CATEGORY_OTHER)
                self.app_indicator.set_status(appindicator.STATUS_ACTIVE)
                self.app_indicator.set_attention_icon("screenlets-tray")

                # appindicator
                while gtk.events_pending():
                    gtk.main_iteration(False)

                gobject.idle_add(self.app_indicator.set_menu, self.menu)
                gobject.idle_add(self.refresh_menu)

            else:

                tray = gtk.StatusIcon()
                tray.set_from_pixbuf(pixbuf_tray)
                tray.connect("activate", self.openit)
                tray.connect("popup-menu", self.show_menu)
                tray.set_tooltip(_("Screenlets daemon"))
                tray.set_visible(True)

            gtk.main()
Beispiel #12
0
    def build_lang_list(self):
        self.cache = apt_pkg.Cache(None)

        self.builder.get_object('button_install').set_sensitive(False)
        self.builder.get_object('button_remove').set_sensitive(False)

        model = Gtk.ListStore(
            str, str, GdkPixbuf.Pixbuf, str, bool, object
        )  # label, locale, flag, packs_label, packs_installed, list_of_missing_packs
        model.set_sort_column_id(0, Gtk.SortType.ASCENDING)

        #Load countries into memory
        self.countries = {}
        file = open('/usr/lib/linuxmint/mintLocale/countries', "r")
        for line in file:
            line = line.strip()
            split = line.split("=")
            if len(split) == 2:
                self.countries[split[0]] = split[1]
        file.close()

        #Load languages into memory
        self.languages = {}
        file = open('/usr/lib/linuxmint/mintLocale/languages', "r")
        for line in file:
            line = line.strip()
            split = line.split("=")
            if len(split) == 2:
                self.languages[split[0]] = split[1]
        file.close()

        locales = commands.getoutput("localedef --list-archive")
        for line in locales.split("\n"):
            line = line.replace("utf8", "UTF-8")
            locale_code = line.split(".")[0].strip()
            charmap = None
            if len(line.split(".")) > 1:
                charmap = line.split(".")[1].strip()

            if "_" in locale_code:
                split = locale_code.split("_")
                if len(split) == 2:
                    language_code = split[0]
                    if language_code in self.languages:
                        language = self.languages[language_code]
                    else:
                        language = language_code

                    country_code = split[1].lower().split('@')[0].strip()
                    if country_code in self.countries:
                        country = self.countries[country_code]
                    else:
                        country = country_code

                    if '@' in split[1]:
                        language_label = "%s (@%s), %s" % (
                            language, split[1].split('@')[1].strip(), country)
                    else:
                        language_label = "%s, %s" % (language, country)

                    flag_path = '/usr/share/linuxmint/mintLocale/flags/16/' + country_code + '.png'
            else:
                if locale_code in self.languages:
                    language_label = self.languages[locale_code]
                else:
                    language_label = locale_code
                flag_path = '/usr/share/linuxmint/mintLocale/flags/16/languages/%s.png' % locale_code
                language_code = locale_code

            if charmap is not None:
                language_label = "%s <small><span foreground='#3c3c3c'>%s</span></small>" % (
                    language_label, charmap)

            # Check if the language packs are installed
            missing_packs = []
            for pkgname in self.pack_prefixes:
                pkgname = "%s%s" % (pkgname, language_code)
                if pkgname in self.cache:
                    pkg = self.cache[pkgname]
                    if (pkg.has_versions and
                            pkg.current_state != apt_pkg.CURSTATE_INSTALLED):
                        missing_packs.append(pkg)

            iter = model.append()
            model.set_value(iter, 0, language_label)
            model.set_value(iter, 1, line)
            if len(missing_packs) > 0:
                model.set_value(
                    iter, 3,
                    "<small><span fgcolor='#a04848'>%s</span></small>" %
                    _("Some language packs are missing"))
                model.set_value(iter, 4, False)
                model.set_value(iter, 5, missing_packs)
            else:
                model.set_value(
                    iter, 3,
                    "<small><span fgcolor='#4ba048'>%s</span></small>" %
                    _("Fully installed"))
                model.set_value(iter, 4, True)
            if os.path.exists(flag_path):
                model.set_value(iter, 2,
                                GdkPixbuf.Pixbuf.new_from_file(flag_path))
            else:
                model.set_value(
                    iter, 2,
                    GdkPixbuf.Pixbuf.new_from_file(
                        '/usr/share/linuxmint/mintLocale/flags/16/generic.png')
                )

        treeview = self.builder.get_object("treeview_language_list")
        treeview.set_model(model)
        treeview.set_search_column(0)
        self.treeview.connect("cursor-changed", self.select_language)
Beispiel #13
0
def run():
    apt_pkg.init()
    cache = apt_pkg.Cache(Progress())
    #
    for pf in cache.file_list:
        log.debug("{0}".format(pf.filename))
Beispiel #14
0
    def _load(self):
        """Regenerates the fake configuration and loads the packages caches."""
        if self.loaded: return True

        # Modify the default configuration to create the fake one.
        apt_pkg.init_system()
        self.cache_dir.preauthChild(
            self.apt_config['Dir::State']).preauthChild(
                self.apt_config['Dir::State::Lists']).remove()
        self.cache_dir.preauthChild(
            self.apt_config['Dir::State']).preauthChild(
                self.apt_config['Dir::State::Lists']).child(
                    'partial').makedirs()
        sources_file = self.cache_dir.preauthChild(
            self.apt_config['Dir::Etc']).preauthChild(
                self.apt_config['Dir::Etc::sourcelist'])
        sources = sources_file.open('w')
        sources_count = 0
        deb_src_added = False
        self.packages.check_files()
        self.indexrecords = {}

        # Create an entry in sources.list for each needed index file
        for f in self.packages:
            # we should probably clear old entries from self.packages and
            # take into account the recorded mtime as optimization
            file = self.packages[f]
            if f.split('/')[-1] == "Release":
                self.addRelease(f, file)
            fake_uri = 'http://apt-p2p' + f
            fake_dirname = '/'.join(fake_uri.split('/')[:-1])
            if f.endswith('Sources'):
                deb_src_added = True
                source_line = 'deb-src ' + fake_dirname + '/ /'
            else:
                source_line = 'deb ' + fake_dirname + '/ /'
            listpath = self.cache_dir.preauthChild(
                self.apt_config['Dir::State']).preauthChild(
                    self.apt_config['Dir::State::Lists']).child(
                        apt_pkg.uri_to_filename(fake_uri))
            sources.write(source_line + '\n')
            log.msg("Sources line: " + source_line)
            sources_count = sources_count + 1

            if listpath.exists():
                #we should empty the directory instead
                listpath.remove()
            os.symlink(file.path, listpath.path)
        sources.close()

        if sources_count == 0:
            log.msg("No Packages files available for %s backend" %
                    (self.cache_dir.path))
            return False

        log.msg("Loading Packages database for " + self.cache_dir.path)
        for key, value in self.apt_config.items():
            apt_pkg.config[key] = value

        self.cache = apt_pkg.Cache(OpProgress())
        self.records = apt_pkg.PackageRecords(self.cache)
        if deb_src_added:
            self.srcrecords = apt_pkg.SourceRecords()
        else:
            self.srcrecords = None

        self.loaded = True
        return True
Beispiel #15
0
    if args.fromaddr and not args.toaddr:
        parser.error("Can't specify from without to")
    if args.toaddr and not args.fromaddr:
        parser.error("Can't specify to without from")

    status = StringIO()

    apt_pkg.init()

	# Turn off cache to avoid concurrency issues
    apt_pkg.config.set("Dir::Cache::pkgcache","")

    # "apt-get update"
    sl = apt_pkg.SourceList()
    sl.read_main_list()
    tmpcache = apt_pkg.Cache(_DevNullProgress())
    tmpcache.update(_DevNullProgress(), sl)

    # Now do the actual check
    cache = apt_pkg.Cache(_DevNullProgress())
    depcache = apt_pkg.DepCache(cache)
    depcache.read_pinfile()
    depcache.init()

    if depcache.broken_count > 0:
        status.write("Depcache broken count is {0}\n\n".format(depcache.broken_count))

    depcache.upgrade(True)

    if depcache.del_count > 0:
        status.write("Dist-upgrade generated {0} pending package removals!\n\n".format(depcache.del_count))
Beispiel #16
0
        for origin, archive in security_pockets:
            if (file.archive == archive and file.origin == origin):
                return True
    return False


output = []

SYNAPTIC_PINFILE = "/var/lib/synaptic/preferences"
DISTRO = subprocess.Popen(['lsb_release', '-c', '-s'],
                          stdout=subprocess.PIPE).communicate()[0]

apt_pkg.init()

try:
    cache = apt_pkg.Cache(apt.progress.base.OpProgress())
except SystemError as e:
    sys.stderr.write("E: " + _("Error: Opening the cache (%s)") % e)
    sys.exit(-1)

depcache = apt_pkg.DepCache(cache)

if os.path.exists(SYNAPTIC_PINFILE):
    depcache.read_pinfile(SYNAPTIC_PINFILE)
    depcache.init()

try:
    saveDistUpgrade(cache, depcache)
except SystemError as e:
    sys.stderr.write("E: " + _("Error: Marking the upgrade (%s)") % e)
    sys.exit(-1)
Beispiel #17
0
    def __init__(self, xml):

        self.xml = xml

        arch = xml.text("project/buildimage/arch", key="arch")
        suite = xml.text("project/suite")

        self.basefs = TmpdirFilesystem()
        self.initialize_dirs()

        create_apt_prefs(self.xml, self.basefs)

        mirror = self.xml.create_apt_sources_list(build_sources=True,
                                                  initvm=False)
        self.basefs.write_file("etc/apt/sources.list", 0o644, mirror)

        self.setup_gpg()
        self.import_keys()

        apt_pkg.config.set("APT::Architecture", arch)
        apt_pkg.config.set("APT::Architectures", arch)
        apt_pkg.config.set("Acquire::http::Proxy::127.0.0.1", "DIRECT")
        apt_pkg.config.set("APT::Install-Recommends", "0")
        apt_pkg.config.set("Dir::Etc", self.basefs.fname('/'))
        apt_pkg.config.set("Dir::Etc::Trusted",
                           self.basefs.fname('/etc/apt/trusted.gpg'))
        apt_pkg.config.set("Dir::Etc::TrustedParts",
                           self.basefs.fname('/etc/apt/trusted.gpg.d'))
        apt_pkg.config.set("APT::Cache-Limit", "0")
        apt_pkg.config.set("APT::Cache-Start", "32505856")
        apt_pkg.config.set("APT::Cache-Grow", "2097152")
        apt_pkg.config.set("Dir::State", self.basefs.fname("state"))
        apt_pkg.config.set("Dir::State::status",
                           self.basefs.fname("state/status"))
        apt_pkg.config.set("Dir::Cache", self.basefs.fname("cache"))
        apt_pkg.config.set("Dir::Cache::archives",
                           self.basefs.fname("cache/archives"))
        apt_pkg.config.set("Dir::Etc", self.basefs.fname("etc/apt"))
        apt_pkg.config.set("Dir::Log", self.basefs.fname("log"))
        if self.xml.has('project/noauth'):
            apt_pkg.config.set("APT::Get::AllowUnauthenticated", "1")
            apt_pkg.config.set("Acquire::AllowInsecureRepositories", "1")
        else:
            apt_pkg.config.set("APT::Get::AllowUnauthenticated", "0")
            apt_pkg.config.set("Acquire::AllowInsecureRepositories", "0")

        apt_pkg.init_system()

        self.source = apt_pkg.SourceList()
        self.source.read_main_list()
        self.cache = apt_pkg.Cache()
        try:
            self.cache.update(self, self.source)
        except BaseException as e:
            print(e)

        apt_pkg.config.set("APT::Default-Release", suite)

        self.cache = apt_pkg.Cache()
        try:
            self.cache.update(self, self.source)
        except BaseException as e:
            print(e)

        try:
            self.depcache = apt_pkg.DepCache(self.cache)
            prefs_name = self.basefs.fname("/etc/apt/preferences")
            self.depcache.read_pinfile(prefs_name)
        except BaseException as e:
            print(e)

        self.downloads = {}
        self.acquire = apt_pkg.Acquire(self)
Beispiel #18
0
 def test_proper_invocation(self):
     """cache_invocation: Test correct invocation."""
     apt_cache = apt_pkg.Cache(apt.progress.base.OpProgress())
     apt_depcache = apt_pkg.DepCache(apt_cache)
Beispiel #19
0
#!/usr/bin/python3
# example how to deal with the depcache

import apt_pkg
from progress import TextProgress

# init
apt_pkg.init()

progress = TextProgress()
cache = apt_pkg.Cache(progress)
print("Available packages: %s " % cache.package_count)

iter = cache["base-config"]
print("example package iter: %s" % iter)

# get depcache
print("\n\n depcache")
depcache = apt_pkg.DepCache(cache)
depcache.read_pinfile()
# init is needed after the creation/pin file reading
depcache.init(progress)
print("got a depcache: %s " % depcache)
print("Marked for install: %s " % depcache.inst_count)

print("\n\n Reinit")
depcache.init(progress)

#sys.exit()

# get a canidate version
Beispiel #20
0
def run(options=None):

    # we are run in "are security updates installed automatically?"
    # question mode
    if options.security_updates_unattended:
        res = apt_pkg.config.find_i("APT::Periodic::Unattended-Upgrade", 0)
        #print(res)
        sys.exit(res)

    # get caches
    try:
        cache = apt_pkg.Cache(apt.progress.base.OpProgress())
    except SystemError as e:
        sys.stderr.write("E: "+ _("Error: Opening the cache (%s)") % e)
        sys.exit(-1)
    depcache = apt_pkg.DepCache(cache)

    # read the synaptic pins too
    if os.path.exists(SYNAPTIC_PINFILE):
        depcache.read_pinfile(SYNAPTIC_PINFILE)
        depcache.init()

    if depcache.broken_count > 0:
        sys.stderr.write("E: "+ _("Error: BrokenCount > 0"))
        sys.exit(-1)

    # do the upgrade (not dist-upgrade!)
    try:
        saveDistUpgrade(cache,depcache)
    except SystemError as e:
        sys.stderr.write("E: "+ _("Error: Marking the upgrade (%s)") % e)
        sys.exit(-1)

    # analyze the ugprade
    upgrades = 0
    security_updates = 0

    # we need another cache that has more pkg details
    with apt.Cache() as aptcache:
        for pkg in cache.packages:
            # skip packages that are not marked upgraded/installed
            if not (depcache.marked_install(pkg) or depcache.marked_upgrade(pkg)):
                continue
            # check if this is really a upgrade or a false positive
            # (workaround for ubuntu #7907)
            inst_ver = pkg.current_ver
            cand_ver = depcache.get_candidate_ver(pkg)
            if cand_ver == inst_ver:
                continue
            # check for security upgrades
            if isSecurityUpgrade(cand_ver):
                upgrades += 1
                security_updates += 1
                continue

            # check to see if the update is a phased one
            try:
                from UpdateManager.Core.UpdateList import UpdateList
                ul = UpdateList(None)
                ignored = ul._is_ignored_phased_update(aptcache[pkg.name])
                if ignored:
                    depcache.mark_keep(pkg)
                    continue
            except ImportError:
                pass

            upgrades = upgrades + 1	

            # now check for security updates that are masked by a 
            # canidate version from another repo (-proposed or -updates)
            for ver in pkg.version_list:
                if (inst_ver and apt_pkg.version_compare(ver.ver_str, inst_ver.ver_str) <= 0):
                    #print("skipping '%s' " % ver.VerStr)
                    continue
                if isSecurityUpgrade(ver):
                    security_updates += 1
                    break

    # print the number of upgrades
    if options and options.show_package_names:
        write_package_names(sys.stderr, cache, depcache)
    elif options and options.readable_output:
        write_human_readable_summary(sys.stdout, upgrades, security_updates)
    else:
        # print the number of regular upgrades and the number of 
        # security upgrades
        sys.stderr.write("%s;%s" % (upgrades,security_updates))

    # return the number of upgrades (if its used as a module)
    return(upgrades,security_updates)
Beispiel #21
0
#!/usr/bin/env python3
import apt_pkg
import sys

from apt_pkg import CURSTATE_INSTALLED, version_compare
from operator import lt, le, eq, ge, gt

# Function mappings for relationship operators.
relation_operators = {"<<": lt, "<=": le, "=": eq, ">=": ge, ">>": gt}

# Set up APT cache.
apt_pkg.init()
cache = apt_pkg.Cache(None)

missing_packages = []

for i in sys.argv[1:]:
    # Build the package relationship string for use by 'apt-get satisfy'.
    relationship_operator = None

    for j in ["<=", ">=", "<", ">", "="]:
        if j in i:
            relationship_operator = j
            break

    if relationship_operator is not None:
        if relationship_operator in ["<", ">"]:
            relationship_operator_formatted = j + j
        else:
            relationship_operator_formatted = j
Beispiel #22
0
    def build_lang_list(self):
        self.cache = apt_pkg.Cache(None)

        self.builder.get_object('button_install').set_sensitive(False)
        self.builder.get_object('button_remove').set_sensitive(False)

        model = Gtk.ListStore(
            str, str, GdkPixbuf.Pixbuf, str, bool, object
        )  # label, locale, flag, packs_label, packs_installed, list_of_missing_packs
        model.set_sort_column_id(0, Gtk.SortType.ASCENDING)

        # Load countries into memory
        self.countries = {}
        with codecs.open('/usr/share/linuxmint/mintlocale/countries',
                         "r",
                         encoding="utf-8") as file:
            for line in file:
                line = line.strip()
                split = line.split("=")
                if len(split) == 2:
                    self.countries[split[0]] = split[1]

        # Load languages into memory
        self.languages = {}
        with codecs.open('/usr/share/linuxmint/mintlocale/languages',
                         "r",
                         encoding='utf-8') as file:
            for line in file:
                line = line.strip()
                split = line.split("=")
                if len(split) == 2:
                    self.languages[split[0]] = split[1]

        locales = subprocess.check_output("localedef --list-archive",
                                          shell=True)
        locales = locales.decode('utf-8').strip()
        for line in locales.split("\n"):
            line = line.replace("utf8", "UTF-8").strip()

            locale_code = line.split(".")[0].strip()
            charmap = None
            if len(line.split(".")) > 1:
                charmap = line.split(".")[1].strip()

            language_code, country_code, language_label = self.split_locale(
                locale_code)
            if country_code == "":
                flag_path = FLAG_PATH % locale_code
            else:
                flag_path = FLAG_PATH % country_code

            # Check for minority languages. Get tje language code from the locale_code.
            # For example, Basque's locale code can be eu or eu_es or eu_fr, Welsh's cy or cy_gb...
            if language_code == 'ca':
                flag_path = FLAG_PATH % '_catalonia'
            elif language_code == 'cy':
                flag_path = FLAG_PATH % '_wales'
            elif language_code == 'eu':
                flag_path = FLAG_PATH % '_basque'
            elif language_code == 'gl':
                flag_path = FLAG_PATH % '_galicia'

            if charmap is not None:
                language_label = "%s <small><span foreground='#3c3c3c'>%s</span></small>" % (
                    language_label, charmap)

            # Check if the language packs are installed
            missing_packs = []
            missing_pack_names = []
            for language_pack in self.language_packs:
                if language_pack.language == "" or language_pack.language == language_code:
                    pkgname = language_pack.package.replace(
                        "LANG", language_code).replace("COUNTRY", country_code)
                    depname = language_pack.dependency
                    if pkgname in self.cache:
                        pkg = self.cache[pkgname]
                        if (pkg.has_versions and pkg.current_state !=
                                apt_pkg.CURSTATE_INSTALLED):
                            if depname != "":
                                if depname in self.cache and self.cache[
                                        depname].current_state == apt_pkg.CURSTATE_INSTALLED:
                                    if pkgname not in missing_pack_names:
                                        missing_packs.append(pkg)
                                        missing_pack_names.append(pkgname)
                            else:
                                if pkgname not in missing_pack_names:
                                    missing_packs.append(pkg)
                                    missing_pack_names.append(pkgname)

            iter = model.append()
            model.set_value(iter, 0, language_label)
            model.set_value(iter, 1, line)
            if len(missing_pack_names) > 0:
                model.set_value(
                    iter, 3,
                    "<small><span fgcolor='#a04848'>%s</span></small>" %
                    _("Some language packs are missing"))
                model.set_value(iter, 4, False)
                model.set_value(iter, 5, missing_pack_names)
            else:
                model.set_value(
                    iter, 3,
                    "<small><span fgcolor='#4ba048'>%s</span></small>" %
                    _("Fully installed"))
                model.set_value(iter, 4, True)
            if os.path.exists(flag_path):
                model.set_value(
                    iter, 2,
                    GdkPixbuf.Pixbuf.new_from_file_at_size(
                        flag_path, -1, FLAG_SIZE))
            else:
                model.set_value(
                    iter, 2,
                    GdkPixbuf.Pixbuf.new_from_file_at_size(
                        FLAG_PATH % '_generic', -1, FLAG_SIZE))

        treeview = self.builder.get_object("treeview_language_list")
        treeview.set_model(model)
        treeview.set_search_column(0)
        self.treeview.connect("cursor-changed", self.select_language)
 def test_proper_invocation(self):
     """cache_invocation: Test correct invocation."""
     apt_cache = apt_pkg.Cache(progress=None)
     apt_depcache = apt_pkg.DepCache(apt_cache)
     self.assertNotEqual(apt_depcache, None)
Beispiel #24
0
    security_package_sources = [("Ubuntu", "%s-security" % DISTRO),
                                ("Debian", "%s-security" % DISTRO)]

    for (file, index) in pkg.file_list:
        for origin, archive in security_package_sources:
            if (file.archive == archive and file.origin == origin):
                return True
    return False


# init apt and config
apt_pkg.init()

# open the apt cache
try:
    cache = apt_pkg.Cache(OpNullProgress())
except SystemError, e:
    sys.stderr.write("Error: Opening the cache (%s)" % e)
    sys.exit(-1)

# setup a DepCache instance to interact with the repo
depcache = apt_pkg.DepCache(cache)

# take into account apt policies
depcache.read_pinfile()

# initialise it
depcache.init()

# give up if packages are broken
if depcache.broken_count > 0: