~laney/ubuntu-archive-tools/cm-show-fix-released

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
#!/usr/bin/python
# Manage the Launchpad build farm.
#
# Copyright 2012-2014 Canonical Ltd.
# Author: William Grant <wgrant@ubuntu.com>
#
# 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 of the License.
#
# 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, see <http://www.gnu.org/licenses/>.

from __future__ import print_function

from datetime import (
    datetime,
    timedelta,
    )
from itertools import groupby
from optparse import OptionParser
import re
from textwrap import dedent

from launchpadlib.launchpad import Launchpad
import pytz


def format_timedelta(delta):
    value = None
    hours = delta.seconds // 3600
    minutes = (delta.seconds - (hours * 3600)) // 60
    if delta.days > 0:
        value = delta.days
        unit = 'day'
    elif hours > 0:
        value = hours
        unit = 'hour'
    elif minutes > 0:
        value = minutes
        unit = 'minute'
    if value is not None:
        return 'for %d %s%s' % (value, unit, 's' if value > 1 else '')
    return ''


parser = OptionParser(description=dedent("""\
    List and manage Launchpad builders.

    If no changes are specified (--auto, --manual, --enable, --disable,
    --set-failnotes, --set-virtual, --set-non-virtual, or --set-vm-host), a
    detailed listing of matching builders will be shown.
    """))
parser.add_option(
    "-l", "--lp-instance", dest="lp_instance", default="production",
    help="use the specified Launchpad instance (default: production)")

parser.add_option(
    "-q", "--quiet", dest="quiet", action="store_true", default=None,
    help="only display errors")
parser.add_option(
    "-v", "--verbose", dest="verbose", action="store_true", default=None,
    help="display more detail")

parser.add_option(
    "-a", "--arch", dest="arch", default=None,
    help="update only builders of this architecture (eg. i386)")
parser.add_option(
    "-b", "--builder", dest="builders", action="append", metavar="BUILDER",
    help="update only this builder (may be given multiple times)")
parser.add_option(
    "--failnotes", dest="failnotes", default=None,
    help="update only builders with failnotes matching this regexp")
parser.add_option(
    "-e", "--enabled", action="store_const", dest="ok_filter", const=True,
    help="update only enabled builders")
parser.add_option(
    "-d", "--disabled", action="store_const", dest="ok_filter", const=False,
    help="update only disabled builders")
parser.add_option(
    "--virtual", action="store_const", dest="virtual_filter", const=True,
    help="update only virtual builders")
parser.add_option(
    "--non-virtual", action="store_const", dest="virtual_filter", const=False,
    help="update only non-virtual builders")
parser.add_option(
    "--builder-version", dest="builder_version", default=None,
    help="update only builders running this launchpad-buildd version")

parser.add_option(
    "--auto", dest="auto", action="store_true", default=None,
    help="enable automatic dispatching")
parser.add_option(
    "--manual", dest="manual", action="store_true", default=None,
    help="disable automatic dispatching")
parser.add_option(
    "--enable", dest="enable", action="store_true", default=None,
    help="mark the builder as OK")
parser.add_option(
    "--disable", dest="disable", action="store_true", default=None,
    help="mark the builder as not OK")
parser.add_option(
    "--set-failnotes", dest="set_failnotes", default=None,
    help="set the builder's failnotes")
parser.add_option(
    "--set-virtual", dest="set_virtual", action="store_true", default=None,
    help="mark the builder as virtual")
parser.add_option(
    "--set-non-virtual", dest="set_non_virtual",
    action="store_true", default=None,
    help="mark the builder as non-virtual")
parser.add_option(
    "--set-vm-host", dest="set_vm_host", default=None,
    help="set the builder's VM host")

(options, args) = parser.parse_args()

if args:
    parser.error(
        "manage-builders does not take positional arguments.  Did you mean to "
        "use -b?")
if options.manual and options.auto:
    parser.error("--manual and --auto are mutually exclusive")
if options.enable and options.disable:
    parser.error("--enable and --disable are mutually exclusive")
if options.set_virtual and options.set_non_virtual:
    parser.error("--set-virtual and --set-non-virtual are mutually exclusive")

changes = {}
if options.manual:
    changes['manual'] = True
if options.auto:
    changes['manual'] = False
if options.enable:
    changes['builderok'] = True
if options.disable:
    changes['builderok'] = False
if options.set_failnotes is not None:
    changes['failnotes'] = options.set_failnotes or None
if options.set_virtual:
    changes['virtualized'] = True
if options.set_non_virtual:
    changes['virtualized'] = False
if options.set_vm_host is not None:
    changes['vm_host'] = options.set_vm_host or None

lp = Launchpad.login_with(
    'manage-builders', options.lp_instance, version='devel')

processor_names = {p.self_link: p.name for p in lp.processors}

def get_processor_name(processor_link):
    if processor_link not in processor_names:
        processor_names[processor_link] = lp.load(processor_link).name
    return processor_names[processor_link]

candidates = []
for builder in lp.builders:
    if not builder.active:
        continue
    if (options.ok_filter is not None
            and builder.builderok != options.ok_filter):
        continue
    if (options.virtual_filter is not None
            and builder.virtualized != options.virtual_filter):
        continue
    if options.builders and builder.name not in options.builders:
        continue
    if (options.arch
        and not any(get_processor_name(p) == options.arch
                    for p in builder.processors)):
        continue
    if (options.failnotes and (
            not builder.failnotes
            or not re.search(options.failnotes, builder.failnotes))):
        continue
    if (options.builder_version is not None and
            options.builder_version != builder.version):
        continue
    candidates.append(builder)

def builder_sort_key(builder):
    return (
        builder.virtualized,
        # https://launchpad.net/builders sorts by Processor.id, but that
        # isn't accessible on the webservice.  This produces vaguely similar
        # results in practice and looks reasonable.
        sorted(builder.processors),
        builder.vm_host,
        builder.vm_reset_protocol if builder.virtualized else '',
        builder.name)

candidates.sort(key=builder_sort_key)

count_changed = count_unchanged = 0

if changes and not options.quiet:
    print('Updating %d builders.' % len(candidates))

if options.verbose:
    clump_sort_key = lambda b: builder_sort_key(b)[:4]
else:
    clump_sort_key = lambda b: builder_sort_key(b)[:2]
builder_clumps = [
    list(group) for _, group in groupby(candidates, clump_sort_key)]

for clump in builder_clumps:
    if not changes and not options.quiet:
        if clump != builder_clumps[0]:
            print()
        exemplar = clump[0]
        archs = ' '.join(get_processor_name(p) for p in exemplar.processors)
        if options.verbose:
            if exemplar.virtualized:
                virt_desc = '(v %s)' % exemplar.vm_reset_protocol
            else:
                virt_desc = '(nv)'
            print(
                '%s %s%s' % (
                    virt_desc, archs,
                    (' [%s]' % exemplar.vm_host) if exemplar.vm_host else ''))
        else:
            print(
                '%-4s %s' % ('(v)' if exemplar.virtualized else '(nv)', archs))

    for candidate in clump:
        changed = False
        for change, value in changes.items():
            if getattr(candidate, change) != value:
                setattr(candidate, change, value)
                changed = True
        if changed:
            count_changed += 1
            candidate.lp_save()
            if not options.quiet:
                print('* %s' % candidate.name)
        elif changes:
            if not options.quiet:
                print('  %s' % candidate.name)
            count_unchanged += 1
        else:
            duration = (
                datetime.now(pytz.UTC) - candidate.date_clean_status_changed)
            if not candidate.builderok:
                # Disabled builders always need explanation.
                if candidate.failnotes:
                    failnote = candidate.failnotes.strip().splitlines()[0]
                else:
                    failnote = 'no failnotes'
                status = 'DISABLED: %s' % failnote
            elif (candidate.current_build_link is None
                  and candidate.clean_status in ('Dirty', 'Cleaning')
                  and duration > timedelta(minutes=10)):
                # Idle builders that have been dirty or cleaning for more
                # than ten minutes are a little suspicious.
                status = '%s %s' % (
                    candidate.clean_status, format_timedelta(duration))
            elif (candidate.current_build_link is not None
                  and duration > timedelta(days=1)):
                # Something building for more than a day deserves
                # investigation.
                status = 'Building %s' % format_timedelta(duration)
            else:
                status = ''
            if options.verbose:
                if candidate.current_build_link is not None:
                    dirty_flag = 'B'
                elif candidate.clean_status == 'Dirty':
                    dirty_flag = 'D'
                elif candidate.clean_status == 'Cleaning':
                    dirty_flag = 'C'
                else:
                    dirty_flag = ' '
                print(
                    '  %-18s %-8s %s%s%s  %s' % (
                        candidate.name, candidate.version,
                        dirty_flag, 'M' if candidate.manual else ' ',
                        'X' if not candidate.builderok else ' ',
                        status))
            elif not options.quiet:
                print('  %-20s %s' % (candidate.name, status))

if changes and not options.quiet:
    print("Changed: %d. Unchanged: %d." % (count_changed, count_unchanged))