~stefanor/+junk/ubuntu-seeded-packages

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
#!/usr/bin/python
#
# Copyright (C) 2011-2017, Stefano Rivera <stefanor@ubuntu.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import collections
import gzip
import json
import logging
import optparse
import os
import re
import urllib2
import time
import sys

from distro_info import UbuntuDistroInfo

log = logging.getLogger(os.path.basename(sys.argv[0]))

# TODO: Find a way to determine these at runtime
# Used for parsing germinate-output
FLAVORS = [
    'kubuntu',
    'lubuntu',
    'ubuntu',
    'ubuntu-budgie',
    'ubuntu-core',
    'ubuntu-mate',
    'ubuntukylin',
    'ubuntustudio',
    'xubuntu',
]
RELEASE = UbuntuDistroInfo().devel()
GERMINATE_URL = 'http://people.canonical.com/~ubuntu-archive/germinate-output/'


class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj)


def parse_manifest(fn):
    packages = set()
    with open(fn, 'r') as f:
        for lineno, line in enumerate(f):
            if '\t' not in line:
                log.warning('Unparseable line: %s:%i', fn, lineno)
                continue
            package, version = line.split('\t')
            package = package.split(':')[0]
            packages.add(package)
    return packages


def parse_list(fn):
    packages = set()
    pkg_re = re.compile(r'^/pool/[^/]+/[^/]+/[^/]+/([a-z0-9+.-]+)'
                        r'_[a-z0-9.+:~-]+_[a-z0-9-]+\.deb$')
    with open(fn, 'r') as f:
        for lineno, line in enumerate(f):
            m = pkg_re.match(line)
            if m is not None:
                packages.add(m.group(1))
    return packages


def read_manifests(seeded):
    """Read all the .list and .manifest files"""
    pending = None
    for root, dirs, files in os.walk('manifests'):
        parts = root.split('/')
        if 'pending' in dirs:
            pending = os.readlink(os.path.join(root, 'pending'))
            continue
        elif parts[-1] != pending:
            continue
        elif parts[-2] == 'source':
            continue
        elif parts[1] == 'ubuntu-core':
            continue  # It works differently
        elif parts[2] == 'ubuntu-rtm':
            continue  # Not the development release
        elif parts[2] == 'vivid':
            continue  # Also not the dev release. Used for phones and things

        version = parts[-1]
        type_ = parts[-2]
        if len(parts) == 4 and ('untu' in parts[-3]
                                or parts[-3] == 'livecd-base'):
            flavor = parts[-3]
        elif len(parts) == 3:
            flavor = 'ubuntu'
        else:
            log.warning("Unexpected path: %s", root)

        for fn in files:
            log.debug("Parsing %s %s %s %s", flavor, type_, version, fn)
            fullname = os.path.join(root, fn)
            if fn.endswith('.manifest'):
                packages = parse_manifest(fullname)
            elif fn.endswith('.list'):
                packages = parse_list(fullname)
            else:
                log.warning("Unknown file: %s", fullname)
                continue
            for pkg in packages:
                seeded[pkg].add((flavor, type_))


def read_supported_seeds(seeded):
    '''Parse germinate output to determine the contents of the supported seed
    '''
    flavors = FLAVORS
    retried = set()

    for flavor in flavors:
        if flavor == 'ubuntu-core':  # No seed structure
            continue

        if flavor in retried:
            log.debug("Retrying %s in 10s", flavor)
            time.sleep(10)

        url_base = os.path.join(GERMINATE_URL, flavor + '.' + RELEASE)
        try:
            f = urllib2.urlopen(os.path.join(url_base, 'structure'))
            data = f.readlines()
            f.close()
        except urllib2.URLError:
            if flavor not in retried:
                retried.add(flavor)
                flavors.append(flavor)
                log.debug("Missing %s seed structure, scheduling retry",
                          flavor)
            else:
                log.exception("Missing %s seed structure", flavor)
            continue

        for line in data:
            if line.split(':')[0].strip() == 'supported':
                break
        else:
            log.debug("No supported seed: %s", flavor)
            continue

        try:
            f = urllib2.urlopen(os.path.join(url_base, 'supported'))
            data = f.readlines()
            f.close()
        except urllib2.URLError:
            log.exception("Missing %s supported seed", flavor)
            continue

        if (not data[0].startswith("Package")
                or not data[1].startswith("---")
                or not data[-1].startswith("   ")
                or not data[-2].startswith("---")):
            log.warning("Unexpected format of %s supported seed", flavor)
            continue

        data = data[2:-2]

        for line in data:
            package = line.split('|', 1)[0].strip()
            seeded[package].add((flavor, 'supported'))


def main():
    parser = optparse.OptionParser()
    parser.add_option("-v", "--verbose", action="store_true", default=False,
                      help="Increase verbosity")
    options, args = parser.parse_args()

    logging.basicConfig(stream=sys.stderr,
                        level=(logging.DEBUG if options.verbose
                               else logging.WARNING))

    seeded = collections.defaultdict(set)
    read_manifests(seeded)
    read_supported_seeds(seeded)

    # gzip doesn't support with statemnts on 2.6
    f = gzip.open('seeded.json.gz.new', 'w')
    json.dump(seeded, f, cls=SetEncoder)
    f.close()
    os.rename('seeded.json.gz.new', 'seeded.json.gz')


if __name__ == '__main__':
    main()