~cupstream2distro-maintainers/cupstream2distro/trunk

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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 Canonical
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""CI Train Copy 2 Distro Script

This script runs on snakefruit and effects the actual copying from the PPAs
to the distro archive.

Any output generated by this script should be discoverable at:

http://people.canonical.com/~ubuntu-archive/cicopy.log
"""

from __future__ import absolute_import, division, unicode_literals

import logging
import time

from os.path import isdir
from os import makedirs, rename

from lazr.restfulclient.errors import NotFound

from glob import glob
from operator import attrgetter
from subprocess import Popen, PIPE

from launchpadlib.launchpad import Launchpad


OLD_STACK_DIR = 'old'
PREFIX = 'packagelist_rsync_'
DOMAIN = 'rsync.bileto.ubuntu.com'
RSYNC_PATTERN = 'rsync://{}/publish/{}*'.format(DOMAIN, PREFIX)


logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')


class lp(object):
    """Trigger connections to launchpadlib only when needed."""
    _instance = None

    @property
    def _launchpad(self):
        """Connect to launchpad if we haven't already."""
        if not self._instance:
            self._instance = Launchpad.login_with(
                application_name='cupstream2distro',
                service_root='production',
                allow_access_levels=['WRITE_PRIVATE'],
                version='devel',  # Need devel for copyPackage
            )
        return self._instance

    def __getattr__(self, attr):
        """Wrap launchpadlib so tightly you can't tell the difference."""
        return getattr(self._launchpad, attr)

    def get_ppa(self, ppa_name):
        """Return a launchpad ppa."""
        parts = ppa_name.split('/')
        parts[0] = parts[0].rpartition('ppa:')[-1]
        distro = self.distributions[parts[1] if len(parts) >= 3 else 'ubuntu']
        return self.people[parts[0]].getPPAByName(
            name=parts[-1], distribution=distro)
lp = lp()


def sort_by_date(archive, **kwargs):
    """Fetch a list of source package objects sorted newest first."""
    kwargs.update(exact_match=True)
    sources = archive.getPublishedSources(**kwargs)
    return sorted(sources, key=attrgetter('date_created'), reverse=True)


def newest(archive, **kwargs):
    """Fetch the newest source package object from a destination archive."""
    try:
        return sort_by_date(archive, **kwargs)[0]
    except IndexError:
        pass


def get_archive_version(name, archive=None, series=None):
    """Get current version for a package name in that series."""
    assert hasattr(series, 'previous_series_link')
    source = newest(archive, source_name=name, distro_series=series)
    if getattr(source, 'status', None) in ('Pending', 'Published'):
        return source.source_package_version


def _rsync_stack_files():
    """RSync all stack files"""
    cmd = ["rsync", '--remove-source-files', '--timeout=60', RSYNC_PATTERN, '.']
    instance = Popen(cmd, stdout=PIPE, stderr=PIPE)
    (stdout, stderr) = instance.communicate()
    if instance.returncode not in (0, 23):
        raise Exception(stderr.decode("utf-8").strip())


def main():
    dest_archive = None
    distro = None

    _rsync_stack_files()
    for fname in glob('./{}*'.format(PREFIX)):
        logging.info("Found {}".format(fname))
        with open(fname) as f:
            for line in f.readlines():
                values = line.strip().split("\t")
                (ppa, src_pocket, from_series, dest_pocket, to_series,
                    source, version, distro_version_at_prepare_time,
                    sponsored_name) = values[:9]
                if len(values) > 9:
                    distro = values[9]
                else:
                    distro = "ubuntu"
                    ppa_split = ppa.split("/")
                    ppa = "{}/ubuntu/{}".format(ppa_split[0], ppa_split[1])
                dest_archive = lp.distributions[distro].main_archive

                logging.info(
                    'Received copy request for {} ({}), from {} ({}, {}), '
                    'to {} ({}, {}) by {}'.format(
                        source, version, ppa, from_series, src_pocket, distro,
                        to_series, dest_pocket, sponsored_name))

                try:
                    sponsored = lp.people[sponsored_name]
                except KeyError:
                    logging.error(
                        "{} isn't a valid launchpad user name.".format(
                            sponsored_name))
                    continue

                series_obj = lp.load('{}/{}'.format(distro, to_series))
                distro_version = get_archive_version(
                    source, dest_archive, series_obj) or '0'
                if distro_version != distro_version_at_prepare_time:
                    message = (
                        'Manual upload of {} {} is newer than {}. '
                        'Not uploading {}.'.format(
                            source, distro_version,
                            distro_version_at_prepare_time, version))
                    logging.error(message)
                    continue

                try:
                    src_ppa = lp.get_ppa(ppa)
                except NotFound:
                    logging.error('Source PPA has been deleted, skipping!')
                    continue

                dest_archive.copyPackage(
                    from_archive=src_ppa,
                    from_pocket=src_pocket,
                    from_series=from_series,
                    include_binaries=True,
                    to_pocket=dest_pocket,
                    to_series=to_series,
                    source_name=source,
                    version=version,
                    sponsored=sponsored)
            if not isdir("../" + OLD_STACK_DIR):
                makedirs("../" + OLD_STACK_DIR)
            rename(
                fname,
                "../{}/{}_{}".format(
                    OLD_STACK_DIR, fname, time.strftime('%Y%m%d-%H%M%S')))
    logging.info('All done.')
    return 0


if __name__ == '__main__':
    import sys
    sys.exit(main())