~mars/launchpad/test-ghost-update

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

# pylint: disable-msg=E0211,E0213

"""Interfaces including and related to IDistribution."""

__metaclass__ = type

__all__ = [
    'IBaseDistribution',
    'IDerivativeDistribution',
    'IDistribution',
    'IDistributionDriverRestricted',
    'IDistributionEditRestricted',
    'IDistributionMirrorMenuMarker',
    'IDistributionPublic',
    'IDistributionSet',
    'NoPartnerArchive',
    'NoSuchDistribution',
    ]

from lazr.lifecycle.snapshot import doNotSnapshot
from lazr.restful.declarations import (
    collection_default_content,
    export_as_webservice_collection,
    export_as_webservice_entry,
    export_operation_as,
    export_read_operation,
    exported,
    operation_parameters,
    operation_returns_collection_of,
    operation_returns_entry,
    rename_parameters_as,
    )
from lazr.restful.fields import (
    CollectionField,
    Reference,
    )
from lazr.restful.interface import copy_field
from zope.interface import (
    Attribute,
    Interface,
    )
from zope.schema import (
    Bool,
    Choice,
    Datetime,
    List,
    Object,
    Text,
    TextLine,
    )

from canonical.launchpad import _
from canonical.launchpad.interfaces.launchpad import (
    IHasAppointedDriver,
    IHasDrivers,
    )
from canonical.launchpad.validators.name import name_validator
from lp.app.errors import NameLookupFailed
from lp.app.interfaces.headings import IRootContext
from lp.app.interfaces.launchpad import (
    ILaunchpadUsage,
    IServiceUsage,
    )
from lp.blueprints.interfaces.specificationtarget import ISpecificationTarget
from lp.blueprints.interfaces.sprint import IHasSprints
from lp.bugs.interfaces.bugsupervisor import IHasBugSupervisor
from lp.bugs.interfaces.bugtarget import (
    IBugTarget,
    IOfficialBugTagTargetPublic,
    IOfficialBugTagTargetRestricted,
    )
from lp.bugs.interfaces.securitycontact import IHasSecurityContact
from lp.registry.interfaces.announcement import IMakesAnnouncements
from lp.registry.interfaces.distributionmirror import IDistributionMirror
from lp.registry.interfaces.karma import IKarmaContext
from lp.registry.interfaces.mentoringoffer import IHasMentoringOffers
from lp.registry.interfaces.milestone import (
    ICanGetMilestonesDirectly,
    IHasMilestones,
    )
from lp.registry.interfaces.pillar import IPillar
from lp.registry.interfaces.role import IHasOwner
from lp.registry.interfaces.structuralsubscription import (
    IStructuralSubscriptionTarget,
    )
from lp.services.fields import (
    Description,
    IconImageUpload,
    LogoImageUpload,
    MugshotImageUpload,
    PillarNameField,
    PublicPersonChoice,
    Summary,
    Title,
    )
from lp.soyuz.interfaces.buildrecords import IHasBuildRecords
from lp.translations.interfaces.translationgroup import ITranslationPolicy


class IDistributionMirrorMenuMarker(Interface):
    """Marker interface for Mirror navigation."""


class DistributionNameField(PillarNameField):
    """The pillar for a distribution."""

    @property
    def _content_iface(self):
        """Return the interface of this pillar object."""
        return IDistribution


class IDistributionEditRestricted(IOfficialBugTagTargetRestricted):
    """IDistribution properties requiring launchpad.Edit permission."""


class IDistributionDriverRestricted(Interface):
    """IDistribution properties requiring launchpad.Driver permission."""

    def newSeries(name, displayname, title, summary, description,
                  version, parent_series, owner):
        """Creates a new distroseries."""


class IDistributionPublic(
    IBugTarget, ICanGetMilestonesDirectly, IHasAppointedDriver,
    IHasBuildRecords, IHasDrivers, IHasMentoringOffers, IHasMilestones,
    IHasOwner, IHasSecurityContact, IHasSprints, ITranslationPolicy,
    IKarmaContext, ILaunchpadUsage, IMakesAnnouncements,
    IOfficialBugTagTargetPublic, IPillar, IServiceUsage,
    ISpecificationTarget):
    """Public IDistribution properties."""

    id = Attribute("The distro's unique number.")
    name = exported(
        DistributionNameField(
            title=_("Name"),
            constraint=name_validator,
            description=_("The distro's name."), required=True))
    displayname = exported(
        TextLine(
            title=_("Display Name"),
            description=_("The displayable name of the distribution."),
            required=True),
        exported_as='display_name')
    title = exported(
        Title(
            title=_("Title"),
            description=_("The distro's title."), required=True))
    summary = exported(
        Summary(
            title=_("Summary"),
            description=_(
                "A short paragraph to introduce the the goals and highlights "
                "of the distribution."),
            required=True))
    homepage_content = exported(
        Text(
            title=_("Homepage Content"), required=False,
            description=_(
                "The content of this distribution's home page. Edit this and "
                "it will be displayed for all the world to see. It is NOT a "
                "wiki so you cannot undo changes.")))
    icon = exported(
        IconImageUpload(
            title=_("Icon"), required=False,
            default_image_resource='/@@/distribution',
            description=_(
                "A small image of exactly 14x14 pixels and at most 5kb in "
                "size, that can be used to identify this distribution. The "
                "icon will be displayed everywhere we list the distribution "
                "and link to it.")))
    logo = exported(
        LogoImageUpload(
            title=_("Logo"), required=False,
            default_image_resource='/@@/distribution-logo',
            description=_(
                "An image of exactly 64x64 pixels that will be displayed in "
                "the heading of all pages related to this distribution. It "
                "should be no bigger than 50kb in size.")))
    mugshot = exported(
        MugshotImageUpload(
            title=_("Brand"), required=False,
            default_image_resource='/@@/distribution-mugshot',
            description=_(
                "A large image of exactly 192x192 pixels, that will be "
                "displayed on this distribution's home page in Launchpad. "
                "It should be no bigger than 100kb in size. ")))
    description = exported(
        Description(
            title=_("Description"),
            description=_(
                "Details about the distributions's work, highlights, goals, "
                "and how to contribute. Use plain text, paragraphs are "
                "preserved and URLs are linked in pages. Don't repeat the "
                "Summary."),
            required=True))
    domainname = exported(
        TextLine(
            title=_("Domain name"),
            description=_("The distro's domain name."), required=True),
        exported_as='domain_name')
    owner = exported(
        PublicPersonChoice(
            title=_("Owner"), vocabulary='ValidOwner',
            description=_("The distro's owner."), required=True))
    date_created = exported(
        Datetime(title=_('Date created'),
                 description=_("The date this distribution was registered.")))
    driver = exported(
        PublicPersonChoice(
            title=_("Driver"),
            description=_(
                "The person or team responsible for decisions about features "
                "and bugs that will be targeted for any series in this "
                "distribution. Note that you can also specify a driver "
                "on each series whose permissions will be limited to that "
                "specific series."),
            required=False, vocabulary='ValidPersonOrTeam'))
    drivers = Attribute(
        "Presents the distro driver as a list for consistency with "
        "IProduct.drivers where the list might include a project driver.")
    members = PublicPersonChoice(
        title=_("Members"),
        description=_("The distro's members team."), required=True,
        vocabulary='ValidPersonOrTeam')
    mirror_admin = exported(PublicPersonChoice(
        title=_("Mirror Administrator"),
        description=_("The person or team that has the rights to review and "
                      "mark this distribution's mirrors as official."),
        required=True, vocabulary='ValidPersonOrTeam'))
    lucilleconfig = TextLine(
        title=_("Lucille Config"),
        description=_("The Lucille Config."), required=False)
    archive_mirrors = exported(doNotSnapshot(
        CollectionField(
            description=_("All enabled and official ARCHIVE mirrors "
                          "of this Distribution."),
            readonly=True, value_type=Object(schema=IDistributionMirror))))
    cdimage_mirrors = exported(doNotSnapshot(
        CollectionField(
            description=_("All enabled and official RELEASE mirrors "
                          "of this Distribution."),
            readonly=True, value_type=Object(schema=IDistributionMirror))))
    disabled_mirrors = Attribute(
        "All disabled and official mirrors of this Distribution.")
    unofficial_mirrors = Attribute(
        "All unofficial mirrors of this Distribution.")
    pending_review_mirrors = Attribute(
        "All mirrors of this Distribution that haven't been reviewed yet.")
    series = exported(doNotSnapshot(
        CollectionField(
            title=_("DistroSeries inside this Distribution"),
            # Really IDistroSeries, see _schema_circular_imports.py.
            value_type=Reference(schema=Interface))))
    architectures = List(
        title=_("DistroArchSeries inside this Distribution"))
    uploaders = Attribute(_(
        "ArchivePermission records for uploaders with rights to upload to "
        "this distribution."))

    # properties
    currentseries = exported(
        Reference(
            # Really IDistroSeries, see _schema_circular_imports.py.
            Interface,
            title=_("Current series"),
            description=_(
                "The current development series of this distribution. "
                "Note that all maintainerships refer to the current "
                "series. When people ask about the state of packages "
                "in the distribution, we should interpret that query "
                "in the context of the currentseries.")),
        exported_as="current_series")

    full_functionality = Attribute(
        "Whether or not we enable the full functionality of Launchpad for "
        "this distribution. Currently only Ubuntu and some derivatives "
        "get the full functionality of LP")

    translation_focus = Choice(
        title=_("Translation Focus"),
        description=_(
            "The DistroSeries that should get the translation effort focus."),
        required=False,
        vocabulary='FilteredDistroSeries')

    language_pack_admin = Choice(
        title=_("Language Pack Administrator"),
        description=_("The distribution language pack administrator."),
        required=False, vocabulary='ValidPersonOrTeam')

    main_archive = exported(
        Reference(
            title=_('Distribution Main Archive.'), readonly=True,
            # Really IArchive, see _schema_circular_imports.py.
            schema=Interface))

    all_distro_archives = exported(doNotSnapshot(
        CollectionField(
            title=_("A sequence of the distribution's non-PPA Archives."),
            readonly=True, required=False,
            value_type=Reference(schema=Interface))),
                # Really IArchive, see _schema_circular_imports.py.
        exported_as='archives')

    all_distro_archive_ids = Attribute(
        "A list containing the IDs of all the non-PPA archives.")

    upstream_report_excluded_packages = Attribute(
        "A list of the source packages that should not be shown on the "
        "upstream bug report for this Distribution.")

    has_published_binaries = Bool(
        title=_("Has Published Binaries"),
        description=_("True if this distribution has binaries published "
                      "on disk."),
        readonly=True, required=False)

    def getArchiveIDList(archive=None):
        """Return a list of archive IDs suitable for sqlvalues() or quote().

        If the archive param is supplied, just its ID will be returned in
        a list of one item.  If it is not supplied, return a list of
        all the IDs for all the archives for the distribution.
        """

    def __getitem__(name):
        """Returns a DistroSeries that matches name, or raises and
        exception if none exists."""

    def __iter__():
        """Iterate over the series for this distribution."""

    @operation_parameters(
        name=TextLine(title=_("Archive name"), required=True))
    @operation_returns_entry(Interface)
    @export_read_operation()
    def getArchive(name):
        """Return the distribution archive with the given name.

        Only distribution archives are considered -- PPAs will not be found.

        :param name: The name of the archive, e.g. 'partner'
        """

    # Really IDistroSeries, see _schema_circular_imports.py.
    @operation_returns_collection_of(Interface)
    @export_operation_as(name="getDevelopmentSeries")
    @export_read_operation()
    def getDevelopmentSeries():
        """Return the DistroSeries which are marked as in development."""

    @operation_parameters(
        name_or_version=TextLine(title=_("Name or version"), required=True))
    # Really IDistroSeries, see _schema_circular_imports.py.
    @operation_returns_entry(Interface)
    @export_read_operation()
    def getSeries(name_or_version):
        """Return the series with the name or version given.

        :param name_or_version: The `IDistroSeries.name` or
            `IDistroSeries.version`.
        """

    @operation_parameters(
        name=TextLine(title=_("Name"), required=True))
    @operation_returns_entry(IDistributionMirror)
    @export_read_operation()
    def getMirrorByName(name):
        """Return the mirror with the given name for this distribution or None
        if it's not found.
        """

    @operation_parameters(
        country=copy_field(IDistributionMirror['country'], required=True),
        mirror_type=copy_field(IDistributionMirror['content'], required=True))
    @operation_returns_entry(IDistributionMirror)
    @export_read_operation()
    def getCountryMirror(country, mirror_type):
        """Return the country DNS mirror for a country and content type."""

    def newMirror(owner, speed, country, content, displayname=None,
                  description=None, http_base_url=None,
                  ftp_base_url=None, rsync_base_url=None, enabled=False,
                  official_candidate=False, whiteboard=None):
        """Create a new DistributionMirror for this distribution.

        At least one of http_base_url or ftp_base_url must be provided in
        order to create a mirror.
        """

    @operation_parameters(
        name=TextLine(title=_("Package name"), required=True))
    # Really returns IDistributionSourcePackage, see
    # _schema_circular_imports.py.
    @operation_returns_entry(Interface)
    @export_read_operation()
    def getSourcePackage(name):
        """Return a DistributionSourcePackage with the given name for this
        distribution, or None.
        """

    def getSourcePackageRelease(sourcepackagerelease):
        """Returns an IDistributionSourcePackageRelease

        Receives a sourcepackagerelease.
        """

    def getCurrentSourceReleases(source_package_names):
        """Get the current release of a list of source packages.

        :param source_package_names: a list of `ISourcePackageName`
            instances.

        :return: a dict where the key is a `IDistributionSourcePackage`
            and the value is a `IDistributionSourcePackageRelease`.
        """

    def getDistroSeriesAndPocket(distroseriesname):
        """Return a (distroseries,pocket) tuple which is the given textual
        distroseriesname in this distribution."""

    def getSeriesByStatus(status):
        """Query context distribution for distroseries with a given status.

        :param status: Series status to look for
        :return: list of `IDistroSeries`
        """

    def getSourcePackageCaches(archive=None):
        """The set of all source package info caches for this distribution.

        If 'archive' is not given it will return all caches stored for the
        distribution main archives (PRIMARY and PARTNER).
        """

    def removeOldCacheItems(archive, log):
        """Delete any cache records for removed packages.

        Also purges all existing cache records for disabled archives.

        :param archive: target `IArchive`.
        :param log: the context logger object able to print DEBUG level
            messages.
        """

    def updateCompleteSourcePackageCache(archive, log, ztm, commit_chunk=500):
        """Update the source package cache.

        Consider every non-REMOVED sourcepackage and entirely skips updates
        for disabled archives.

        :param archive: target `IArchive`;
        :param log: logger object for printing debug level information;
        :param ztm:  transaction used for partial commits, every chunk of
            'commit_chunk' updates is committed;
        :param commit_chunk: number of updates before commit, defaults to 500.

        :return the number packages updated done
        """

    def updateSourcePackageCache(sourcepackagename, archive, log):
        """Update cached source package details.

        Update cache details for a given ISourcePackageName, including
        generated binarypackage names, summary and description fti.
        'log' is required and only prints debug level information.
        """

    @rename_parameters_as(text="source_match")
    @operation_parameters(
        text=TextLine(title=_("Source package name substring match"),
                      required=True))
    # Really returns IDistributionSourcePackage, see
    # _schema_circular_imports.py.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def searchSourcePackages(
        text, has_packaging=None, publishing_distroseries=None):
        """Search for source packages that correspond to the given text.

        This method just decorates the result of searchSourcePackageCaches()
        to return DistributionSourcePackages.
        """

    def searchSourcePackageCaches(
        text, has_packaging=None, publishing_distroseries=None):
        """Search for source packages that correspond to the given text.

        :param text: The text that will be matched.
        :param has_packaging: If True, it will filter out
            packages with no packaging (i.e. no link to the upstream
            project). False will do the reverse filtering, and None
            will do no filtering on this field.
        :param publishing_distroseries: If it is not None, then
            it will filter out source packages that do not have a
            publishing history for the given distroseries.
        :return: A result set containing
            (DistributionSourcePackageCache, SourcePackageName, rank) tuples
            ordered by rank.
        """

    def searchBinaryPackages(package_name, exact_match=False):
        """Search for binary packages in this distribution.

        :param package_name: The binary package name to match.
        :param exact_match: If False, substring matches are done on the
            binary package names; if True only a full string match is
            returned.
        :return: A result set containing appropriate DistributionSourcePackage
            objects for the matching source.

        The returned results will consist of source packages that match
        (a substring of) their binary package names.
        """

    def searchBinaryPackagesFTI(package_name):
        """Do an FTI search on binary packages.

        :param package_name: The binary package name to search for.
        :return: A result set containing DistributionSourcePackageCache
            objects for the matching binaries found via an FTI search on
            DistroSeriesPackageCache.
        """

    def getFileByName(filename, archive=None, source=True, binary=True):
        """Find and return a LibraryFileAlias for the filename supplied.

        The file returned will be one of those published in the distribution.

        If searching both source and binary, and the file is found in the
        binary packages it'll return that over a file for a source package.

        If 'archive' is not passed the distribution.main_archive is assumed.

        At least one of source and binary must be true.

        Raises NotFoundError if it fails to find the named file.
        """

    def guessPackageNames(pkgname):
        """Try and locate source and binary package name objects that
        are related to the provided name --  which could be either a
        source or a binary package name. Returns a tuple of
        (sourcepackagename, binarypackagename) based on the current
        publishing status of these binary / source packages. Raises
        NotFoundError if it fails to find any package published with
        that name in the distribution.
        """

    def getAllPPAs():
        """Return all PPAs for this distribution."""

    # Really returns IArchive, see
    # _schema_circular_imports.py.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getCommercialPPAs():
        """Return all commercial PPAs.

        Commercial PPAs are private, but explicitly flagged up as commercial
        so that they are discoverable by people who wish to buy items
        from them.
        """

    def searchPPAs(text=None, show_inactive=False):
        """Return all PPAs matching the given text in this distribution.

        'text', when passed, will restrict results to Archives with matching
        description (using substring) or matching Archive.owner (using
        available person fti/ftq).

        'show_inactive', when False, will restrict results to Archive with
        at least one source publication in PENDING or PUBLISHED status.
        """

    def getPendingAcceptancePPAs():
        """Return only pending acceptance PPAs in this distribution."""

    def getPendingPublicationPPAs():
        """Return all PPAs in this distribution that are pending publication.

        A PPA is said to be pending publication if it has publishing records
        in the pending state or if it had packages deleted from it.
        """

    def getArchiveByComponent(component_name):
        """Return the archive most appropriate for the component name.

        Where different components may imply a different archive (e.g.
        partner), this method will return the archive for that component.

        If the component_name supplied is unknown, None is returned.
        """

    def getPackagesAndPublicUpstreamBugCounts(limit=50,
                                              exclude_packages=None):
        """Return list of tuples of packages, upstreams and public bug counts.

        :param limit: The maximum number of rows to return.
        :param exclude_packages: A list of source packages to exclude.
            These should be specified as strings which correspond with
            SourcePackageName.name.
        :returns: [(IDistroSourcePackage, IProduct, int, int, int, int), ...]

        This API is quite specialized; it returns a list of up to limit
        tuples containing IProducts and three different bug counts:
            - open bugs
            - triaged bugs
            - open bugs with an upstream task
            - open bugs with upstream tasks that are either linked to
              bug watches or to products that use_malone.
        """

    def userCanEdit(user):
        """Can the user edit this distribution?"""


class IDistribution(
    IDistributionEditRestricted, IDistributionPublic, IHasBugSupervisor,
    IRootContext, IStructuralSubscriptionTarget):
    """An operating system distribution."""
    export_as_webservice_entry()


class IBaseDistribution(IDistribution):
    """A Distribution that is the base for other Distributions."""


class IDerivativeDistribution(IDistribution):
    """A Distribution that derives from another Distribution."""


class IDistributionSet(Interface):
    """Interface for DistrosSet"""
    export_as_webservice_collection(IDistribution)

    title = Attribute('Title')

    def __iter__():
        """Iterate over all distributions.

        Ubuntu and its flavours will always be at the top of the list, with
        the other ones sorted alphabetically after them.
        """

    def __getitem__(name):
        """Retrieve a distribution by name"""

    @collection_default_content()
    def getDistros():
        """Return all distributions.

        Ubuntu and its flavours will always be at the top of the list, with
        the other ones sorted alphabetically after them.
        """

    def count():
        """Return the number of distributions in the system."""

    def get(distributionid):
        """Return the IDistribution with the given distributionid."""

    def getByName(distroname):
        """Return the IDistribution with the given name or None."""

    def new(name, displayname, title, description, summary, domainname,
            members, owner, mugshot=None, logo=None, icon=None):
        """Create a new distribution."""


class NoSuchDistribution(NameLookupFailed):
    """Raised when we try to find a distribution that doesn't exist."""

    _message_prefix = "No such distribution"


class NoPartnerArchive(Exception):
    """Raised when a partner archive is needed, but none exists."""

    def __init__(self, distribution):
        Exception.__init__(
            self, "Partner archive for distro '%s' not found"
            % (distribution.name, ))