~vcs-imports/bts-lin/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
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
#! /usr/bin/env python
# vim:set encoding=utf-8:
###############################################################################
# Copyright:
#   © 2006 Pierre Habouzit <madcoder@debian.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. The names of its contributors may not be used to endorse or promote
#    products derived from this software without specific prior written
#    permission.
#
# THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
# EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################

"""
Usage: %s [-nvs] nnn [, nnn2]

    -n  --dry-run
               dry run : won't send any mail

    -v  --verbose
               be verbose

    -s  --short
               short run, don't deal with 'Done' bugs.

    -k  --skip-summary
               don't generate a summary file (used for testing)

    nnn        the debian bug number

"""

from __future__ import with_statement

import sys, os, getopt, threading, time, signal
import bts, utils
from remote import RemoteBts
from utils import BTSLConfig as Cnf
# for summary
from datetime import datetime, date
# to know the machine
import platform
import re

def warn(s):
    print >> sys.stderr, s

def die(s):
    print >> sys.stderr, s
    os.kill(os.getpid(), signal.SIGKILL)
    sys.exit(1)

def usage(exitCode = 1):
    die(__doc__.lstrip() % (sys.argv[0].split('/')[-1]))



class Task(threading.Thread):
    def __init__(self, rbts, res, summary):
        self.rbts = rbts
        self.res  = res
        self.summary = summary
        threading.Thread.__init__(self)

    def run(self):
        tmp_res, tmp_summ = self.rbts.processQueue()
        self.res += tmp_res
        for k in tmp_summ.keys():
            self.summary[k] += tmp_summ[k]
        return

# Program starts here

if __name__ == "__main__":
    debug = False
    short = False
    verbose = False
    dosummary = True

    # differentiate local runs from those on Debian BTS node
    if platform.node() == 'sonntag':
        logdir = Cnf.get('btsnode', 'logdir')
    else:
        logdir = Cnf.get('local', 'logdir')

    today = date.today().isoformat()
    summaryfile = logdir + '/' + 'summary_' + today

    # summary dictionaries:
    # description of tags
    # WARNING: keep it in sync with rrd graph generator
    summary_desc = {
        'A': 'actions to perform',
        'C': 'checks successfully done',
        'D': 'bugs done',
        'E': 'errors',
        'I': 'no status',
        'N': 'not a bts/ignored',
        'M': 'mails sent',
        'S': 'SMTP errors (sending mails)',
        'T': 'total bugs count',
        'U': 'unmatched/unconfigured bts',
        'X': 'bugs not existing',
    }
    # tags count (init to 0)
    summary = dict()
    for k in summary_desc.keys():
        summary[k] = 0

    summary_start = datetime.now()

    opts, args = getopt.getopt(sys.argv[1:], 'nsvk', ['dry-run', 'short', 'verbose', 'skip-summary'])
    if len(args) < 1: usage(1)
    for o, v in opts:
        if o in ('-n', '--dry-run'):
            debug = True
        if o in ('-s', '--short'):
            short = True
        if o in ('-v', '--verbose'):
            verbose = True
        if o in ('-k', '--skip-summary'):
            dosummary = False

    RemoteBts.setup(Cnf.resources())
    btsi = bts.BtsInterface(Cnf)

    summary['T'] = len(args)

    # add all bugs in their respective bugtracker's queue
    for id in args:
        btsbug = btsi.getReport(id)

        if btsbug is None:
            warn("X: #%s does not exist or error reading summary file" % (id))
            summary['X'] += 1
            continue

        if short and btsbug.done:
            summary['D'] += 1
            continue

        if not btsbug.forward:
            if verbose:
                if not btsbug.fwdTo:
                    warn("E: pkg=%s, bug=%s, msg=this bug has no forwards" % (btsbug.srcpackage, btsbug.id))
                if len(btsbug.fwdTo) is not 1:
                    warn("E: pkg=%s, bug=%s, msg=this bug has more than one forward" % (btsbug.srcpackage, btsbug.id))
            summary['E'] += 1
            continue

        if any(re.search(pattern, btsbug.forward) for pattern in Cnf.get('general', 'notbtsregexs')):
            warn("N: pkg=%s, bug=%s, msg=not a bts or ignored bts: [%s]" % (btsbug.srcpackage, btsbug.id, btsbug.forward))
            summary['N'] += 1
            continue

        rbts = RemoteBts.find(btsbug.forward)
        if not rbts:
            if verbose:
                warn("U: pkg=%s, bug=%s, msg=unmatched/unconfigured remote bts: [%s]" % (btsbug.srcpackage, btsbug.id, btsbug.forward))
            summary['U'] += 1
            continue
        # add the bug to it's bugtracker's queue
        rbts.enqueue(btsbug)

    # Now start processing the bugtracker's queues in independant threads
    try:
        res = []
        for _, v in RemoteBts.resources.iteritems():
            # start processing the bugtracker's queue
            Task(v['bts'], res, summary).start()

        while threading.activeCount() > 1:
            time.sleep(1)

    except KeyboardInterrupt:
        die("*** ^C...")

    # Now we have processed all actions (Task.run()) and all results are in res

    # direct commands to the source packages
    per_src = {}
    for btsbug, cmds in res:
        if btsbug.srcpackage in per_src:
            per_src[btsbug.srcpackage] += cmds
        else:
            per_src[btsbug.srcpackage] = cmds

    # can now send emails to debbugs
    mailer = bts.BtsMailer(debug)

    for spkg, cmds in per_src.iteritems():
        precmds = []
        precmds.append("#")
        precmds.append("# bts-link upstream status pull for source package %s" % (spkg))
        precmds.append("# see http://lists.debian.org/debian-devel-announce/2006/05/msg00001.html")
        precmds.append("#     https://bts-link-team.pages.debian.net/bts-link/")
        precmds.append("#")
        precmds.append("")
        precmds.append("user %s" % (Cnf.get('general', 'user')))
        precmds.append("")

        cmds.append('thanks')

        # if there is pkg1,pkg2 it will split them and create a correct CC field
        # if there is only one pkg, it does the right thing since the join does nothing in this case
        spkg_cc = '@packages.debian.org, '.join(spkg.split(','))+'@packages.debian.org'

        msg = None

        try:
            msg = mailer.BtsMail('\n'.join([x.decode('ascii', 'ignore') for x in precmds + cmds]))
            msg['From']       = Cnf.sender()
            msg['To']         = 'control@bugs.debian.org'
            msg['Cc']         = "%s, %s" % (Cnf.sender(), spkg_cc)
            msg['Subject']    = '[bts-link] source package %s' % (spkg)
            msg['X-BTS-Link'] = spkg
            if Cnf.replyTo(): msg['Reply-To'] = Cnf.replyTo()

            mailer.sendmail(msg['From'], [msg['To'], msg['From'], spkg_cc], msg)
            summary['M'] += 1
        except Exception, e:
            if msg:
                warn("S: error sending mail (%s); from=%s, to=%s, cc=%s %s, body=%s" % (' '.join([e.message, e.reason]), msg['From'], msg['To'], msg['From'], spkg_cc, msg))
            else:
                warn("S: error sending mail for package %s, no msg generated? (%s) commands=%s" % (spkg, ' '.join([e.message, e.reason]), '\n'.join([x.decode('utf-8').encode('utf-8') for x in cmds])))
            summary['S'] += 1

    mailer.unlink()

    summary_end = datetime.now()

    if dosummary:
        with open(summaryfile, 'w') as f:
            f.write("Execution beginning: %s\n" % summary_start)
            f.write("Execution complete:  %s\n" % summary_end)
            f.write("Elapsed time:        %s\n\n" % (summary_end - summary_start).seconds)

            f.write("Tags summary:\n")
            for key in sorted(summary.keys()):
                f.write("  %s: %d\n" % (key, summary[key]))

# vim:set foldmethod=indent foldnestmax=1: