diff options
Diffstat (limited to 'main/models.py')
-rw-r--r-- | main/models.py | 328 |
1 files changed, 150 insertions, 178 deletions
diff --git a/main/models.py b/main/models.py index c532ed56..2f4d3520 100644 --- a/main/models.py +++ b/main/models.py @@ -4,17 +4,16 @@ from itertools import groupby from pgpdump import BinaryData from django.db import models +from django.db.models import Q from django.contrib.auth.models import User from django.contrib.sites.models import Site from .fields import PositiveBigIntegerField -from .utils import cache_function, set_created_field, utc_now +from .utils import set_created_field +from devel.models import DeveloperKey +from packages.alpm import AlpmAPI -class TodolistManager(models.Manager): - def incomplete(self): - return self.filter(todolistpkg__complete=False).distinct() - class PackageManager(models.Manager): def flagged(self): """Used by dev dashboard.""" @@ -23,6 +22,13 @@ class PackageManager(models.Manager): def normal(self): return self.select_related('arch', 'repo') + def restricted(self, user=None): + qs = self.normal() + if user is not None and user.is_authenticated: + return qs + return qs.filter(repo__staging=False) + + class Donor(models.Model): name = models.CharField(max_length=255, unique=True) visible = models.BooleanField(default=True, @@ -35,7 +41,8 @@ class Donor(models.Model): class Meta: db_table = 'donors' ordering = ('name',) - get_latest_by = 'when' + get_latest_by = 'created' + class Arch(models.Model): name = models.CharField(max_length=255, unique=True) @@ -50,9 +57,10 @@ class Arch(models.Model): class Meta: db_table = 'arches' - ordering = ['name'] + ordering = ('name',) verbose_name_plural = 'arches' + class Repo(models.Model): name = models.CharField(max_length=255, unique=True) testing = models.BooleanField(default=False, @@ -74,8 +82,8 @@ class Repo(models.Model): class Meta: db_table = 'repos' - ordering = ['name'] - verbose_name_plural = 'repos' + ordering = ('name',) + class Package(models.Model): repo = models.ForeignKey(Repo, related_name="packages", @@ -95,11 +103,12 @@ class Package(models.Model): build_date = models.DateTimeField(null=True) last_update = models.DateTimeField(db_index=True) files_last_update = models.DateTimeField(null=True, blank=True) + created = models.DateTimeField() packager_str = models.CharField(max_length=255) - packager = models.ForeignKey(User, null=True, + packager = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) pgp_signature = models.TextField(null=True, blank=True) - flag_date = models.DateTimeField(null=True) + flag_date = models.DateTimeField(null=True, blank=True) objects = PackageManager() @@ -128,25 +137,26 @@ class Package(models.Model): return '%s://%s%s' % (proto, domain, self.get_absolute_url()) @property - @cache_function(15) def signature(self): try: - data = b64decode(self.pgp_signature) + data = b64decode(self.pgp_signature.encode('utf-8')) except TypeError: return None + if not data: + return None data = BinaryData(data) packets = list(data.packets()) return packets[0] @property - @cache_function(15) def signer(self): sig = self.signature if sig and sig.key_id: try: - user = User.objects.get( - userprofile__pgp_key__endswith=sig.key_id) - except User.DoesNotExist: + matching_key = DeveloperKey.objects.select_related( + 'owner').get(key=sig.key_id, owner_id__isnull=False) + user = matching_key.owner + except DeveloperKey.DoesNotExist: user = None return user return None @@ -166,47 +176,89 @@ class Package(models.Model): def maintainers(self, maintainers): self._maintainers = maintainers - @cache_function(1800) + _applicable_arches = None + def applicable_arches(self): '''The list of (this arch) + (available agnostic arches).''' - arches = set(Arch.objects.filter(agnostic=True)) - arches.add(self.arch) - return list(arches) + if self._applicable_arches is None: + arches = set(Arch.objects.filter(agnostic=True)) + arches.add(self.arch) + self._applicable_arches = list(arches) + return self._applicable_arches - @cache_function(119) def get_requiredby(self): """ Returns a list of package objects. An attempt will be made to keep this list slim by including the corresponding package in the same testing category as this package if that check makes sense. """ - provides = set(self.provides.values_list('name', flat=True)) - provides.add(self.pkgname) - requiredby = PackageDepend.objects.select_related('pkg', - 'pkg__arch', 'pkg__repo').filter( - depname__in=provides).order_by( - 'pkg__pkgname', 'pkg__arch__name', 'pkg__repo__name') + from packages.models import Depend + sorttype = '''(CASE deptype + WHEN 'D' THEN 0 + WHEN 'O' THEN 1 + WHEN 'M' THEN 2 + WHEN 'C' THEN 3 + ELSE 1000 END)''' + name_clause = '''packages_depend.name IN ( + SELECT %s UNION ALL + SELECT z.name FROM packages_provision z WHERE z.pkg_id = %s + )''' + requiredby = Depend.objects.select_related('pkg', + 'pkg__arch', 'pkg__repo').extra( + select={'sorttype': sorttype}, + where=[name_clause], params=[self.pkgname, self.id]).order_by( + 'sorttype', 'pkg__pkgname', + 'pkg__arch__name', 'pkg__repo__name') if not self.arch.agnostic: # make sure we match architectures if possible requiredby = requiredby.filter( pkg__arch__in=self.applicable_arches()) + + # if we can use ALPM, ensure our returned Depend objects abide by the + # version comparison operators they may specify + alpm = AlpmAPI() + if alpm.available: + provides = self.provides.all() + new_rqd = [] + for dep in requiredby: + if not dep.comparison or not dep.version: + # no comparisson/version, so always let it through + new_rqd.append(dep) + elif self.pkgname == dep.name: + # depends on this package, so check it directly + if alpm.compare_versions(self.full_version, + dep.comparison, dep.version): + new_rqd.append(dep) + else: + # it must be a provision of ours at this point + for provide in (p for p in provides if p.name == dep.name): + if alpm.compare_versions(provide.version, + dep.comparison, dep.version): + new_rqd.append(dep) + break + requiredby = new_rqd + # sort out duplicate packages; this happens if something has a double - # versioned dep such as a kernel module + # versioned depend such as a kernel module requiredby = [list(vals)[0] for _, vals in groupby(requiredby, lambda x: x.pkg.id)] + if len(requiredby) == 0: + return requiredby - # find another package by this name in the opposite testing setup - # TODO: figure out staging exclusions too - if not Package.objects.filter(pkgname=self.pkgname, - arch=self.arch).exclude(id=self.id).exclude( - repo__testing=self.repo.testing).exists(): + # find another package by this name in a different testing or staging + # repo; if we can't, we can short-circuit some checks + repo_q = (Q(repo__testing=(not self.repo.testing)) | + Q(repo__staging=(not self.repo.staging))) + if not Package.objects.filter( + repo_q, pkgname=self.pkgname, arch=self.arch + ).exclude(id=self.id).exists(): # there isn't one? short circuit, all required by entries are fine return requiredby trimmed = [] # for each unique package name, try to screen our package list down to - # those packages in the same testing category (yes or no) iff there is - # a package in the same testing category. + # those packages in the same testing and staging category (yes or no) + # iff there is a package in the same testing and staging category. for _, dep_pkgs in groupby(requiredby, lambda x: x.pkg.pkgname): dep_pkgs = list(dep_pkgs) dep = dep_pkgs[0] @@ -219,7 +271,6 @@ class Package(models.Model): trimmed.append(dep) return trimmed - @cache_function(121) def get_depends(self): """ Returns a list of dicts. Each dict contains ('dep', 'pkg', and @@ -230,21 +281,49 @@ class Package(models.Model): Packages will match the testing status of this package if possible. """ deps = [] - arches = None - if not self.arch.agnostic: - arches = self.applicable_arches() - # TODO: we can use list comprehension and an 'in' query to make this more effective - for dep in self.depends.order_by('optional', 'depname'): - pkg = dep.get_best_satisfier(arches, testing=self.repo.testing, - staging=self.repo.staging) + # TODO: we can use list comprehension and an 'in' query to make this + # more effective + for dep in self.depends.all(): + pkg = dep.get_best_satisfier() providers = None if not pkg: - providers = dep.get_providers(arches, - testing=self.repo.testing, staging=self.repo.staging) + providers = dep.get_providers() deps.append({'dep': dep, 'pkg': pkg, 'providers': providers}) - return deps + # sort the list; deptype sorting makes this tricker than expected + sort_order = {'D': 0, 'O': 1, 'M': 2, 'C': 3} + + def sort_key(val): + dep = val['dep'] + return (sort_order.get(dep.deptype, 1000), dep.name) + return sorted(deps, key=sort_key) + + def reverse_conflicts(self): + """ + Returns a list of packages with conflicts against this package. + """ + pkgs = Package.objects.normal().filter(conflicts__name=self.pkgname) + if not self.arch.agnostic: + # make sure we match architectures if possible + pkgs = pkgs.filter(arch__in=self.applicable_arches()) + + alpm = AlpmAPI() + if not alpm.available: + return pkgs + + # If we can use ALPM, we can filter out items that don't actually + # conflict due to the version specification. + pkgs = pkgs.prefetch_related('conflicts') + new_pkgs = [] + for package in pkgs: + for conflict in package.conflicts.all(): + if conflict.name != self.pkgname: + continue + if not conflict.comparison or not conflict.version \ + or alpm.compare_versions(self.full_version, + conflict.comparison, conflict.version): + new_pkgs.append(package) + return new_pkgs - @cache_function(125) def base_package(self): """ Locate the base package for this package. It may be this very package, @@ -256,7 +335,7 @@ class Package(models.Model): return Package.objects.normal().get(arch=self.arch, repo=self.repo, pkgname=self.pkgbase) except Package.DoesNotExist: - # this package might be split across repos? just find one + # this package might be split across repos? find one # that matches the correct [testing] repo flag pkglist = Package.objects.normal().filter(arch=self.arch, repo__testing=self.repo.testing, @@ -273,17 +352,23 @@ class Package(models.Model): repo.testing and repo.staging flags. For any non-split packages, the return value will be an empty list. """ - return Package.objects.normal().filter(arch__in=self.applicable_arches(), - repo__testing=self.repo.testing, repo__staging=self.repo.staging, + return Package.objects.normal().filter( + arch__in=self.applicable_arches(), + repo__testing=self.repo.testing, + repo__staging=self.repo.staging, pkgbase=self.pkgbase).exclude(id=self.id) def flag_request(self): - if not self.flag_date: + if self.flag_date is None: return None from packages.models import FlagRequest try: + # Note that we don't match on pkgrel here; this is because a pkgrel + # bump does not unflag a package so we can still show the same flag + # request from a different pkgrel. request = FlagRequest.objects.filter(pkgbase=self.pkgbase, - repo=self.repo).latest() + repo=self.repo, pkgver=self.pkgver, + epoch=self.epoch, is_spam=False).latest() return request except FlagRequest.DoesNotExist: return None @@ -320,10 +405,19 @@ class Package(models.Model): def elsewhere(self): '''attempt to locate this package anywhere else, regardless of architecture or repository. Excludes this package from the list.''' + names = [self.pkgname] + if self.pkgname.startswith(u'lib32-'): + names.append(self.pkgname[6:]) + elif self.pkgname.endswith(u'-multilib'): + names.append(self.pkgname[:-9]) + else: + names.append(u'lib32-' + self.pkgname) + names.append(self.pkgname + u'-multilib') return Package.objects.normal().filter( - pkgname=self.pkgname).exclude(id=self.id).order_by( + pkgname__in=names).exclude(id=self.id).order_by( 'arch__name', 'repo__name') + class PackageFile(models.Model): pkg = models.ForeignKey(Package) is_directory = models.BooleanField(default=False) @@ -336,128 +430,6 @@ class PackageFile(models.Model): class Meta: db_table = 'package_files' -class PackageDepend(models.Model): - pkg = models.ForeignKey(Package, related_name='depends') - depname = models.CharField(max_length=255, db_index=True) - depvcmp = models.CharField(max_length=255, default='') - optional = models.BooleanField(default=False) - description = models.TextField(null=True, blank=True) - - def get_best_satisfier(self, arches=None, testing=None, staging=None): - '''Find a satisfier for this dependency that best matches the given - criteria. It will not search provisions, but will find packages named - and matching repo characteristics if possible.''' - pkgs = Package.objects.normal().filter(pkgname=self.depname) - if arches is not None: - # make sure we match architectures if possible - pkgs = pkgs.filter(arch__in=arches) - if len(pkgs) == 0: - # couldn't find a package in the DB - # it should be a virtual depend (or a removed package) - return None - if len(pkgs) == 1: - return pkgs[0] - # more than one package, see if we can't shrink it down - # grab the first though in case we fail - pkg = pkgs[0] - # prevents yet more DB queries, these lists should be short; - # after each grab the best available in case we remove all entries - if staging is not None: - pkgs = [p for p in pkgs if p.repo.staging == staging] - if len(pkgs) > 0: - pkg = pkgs[0] - - if testing is not None: - pkgs = [p for p in pkgs if p.repo.testing == testing] - if len(pkgs) > 0: - pkg = pkgs[0] - - return pkg - - def get_providers(self, arches=None, testing=None, staging=None): - '''Return providers of this dep. Does *not* include exact matches as it - checks the Provision names only, use get_best_satisfier() instead.''' - pkgs = Package.objects.normal().filter( - provides__name=self.depname).distinct() - if arches is not None: - pkgs = pkgs.filter(arch__in=arches) - - # Logic here is to filter out packages that are in multiple repos if - # they are not requested. For example, if testing is False, only show a - # testing package if it doesn't exist in a non-testing repo. - if staging is not None: - filtered = {} - for p in pkgs: - if p.pkgname not in filtered or p.repo.staging == staging: - filtered[p.pkgname] = p - pkgs = filtered.values() - - if testing is not None: - filtered = {} - for p in pkgs: - if p.pkgname not in filtered or p.repo.testing == testing: - filtered[p.pkgname] = p - pkgs = filtered.values() - - return pkgs - - def __unicode__(self): - return "%s%s" % (self.depname, self.depvcmp) - - class Meta: - db_table = 'package_depends' - -class Todolist(models.Model): - creator = models.ForeignKey(User, on_delete=models.PROTECT) - name = models.CharField(max_length=255) - description = models.TextField() - date_added = models.DateTimeField(db_index=True) - objects = TodolistManager() - - def __unicode__(self): - return self.name - - _packages = None - - @property - def packages(self): - if not self._packages: - # select_related() does not use LEFT OUTER JOIN for nullable - # ForeignKey fields. That is why we need to explicitly list the - # ones we want. - self._packages = TodolistPkg.objects.select_related( - 'pkg__repo', 'pkg__arch').filter(list=self).order_by('pkg') - return self._packages - - @property - def package_names(self): - # depends on packages property returning a queryset - return self.packages.values_list('pkg__pkgname', flat=True).distinct() - - class Meta: - db_table = 'todolists' - - def get_absolute_url(self): - return '/todo/%i/' % self.id - - def get_full_url(self, proto='https'): - '''get a URL suitable for things like email including the domain''' - domain = Site.objects.get_current().domain - return '%s://%s%s' % (proto, domain, self.get_absolute_url()) - -class TodolistPkg(models.Model): - list = models.ForeignKey(Todolist) - pkg = models.ForeignKey(Package) - complete = models.BooleanField(default=False) - - class Meta: - db_table = 'todolist_pkgs' - unique_together = (('list','pkg'),) - -def set_todolist_fields(sender, **kwargs): - todolist = kwargs['instance'] - if not todolist.date_added: - todolist.date_added = utc_now() # connect signals needed to keep cache in line with reality from main.utils import refresh_latest @@ -465,8 +437,8 @@ from django.db.models.signals import pre_save, post_save post_save.connect(refresh_latest, sender=Package, dispatch_uid="main.models") -pre_save.connect(set_todolist_fields, sender=Todolist, - dispatch_uid="main.models") +# note: reporead sets the 'created' field on Package objects, so no signal +# listener is set up here to do so pre_save.connect(set_created_field, sender=Donor, dispatch_uid="main.models") |