aboutsummaryrefslogtreecommitdiffstats
path: root/tools/python/xen/util/bugtool.py
blob: e8d96b884af37e78d715324f97e57126f6fcb30e (plain)
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
#!/usr/bin/env python

# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) 2005, XenSource Ltd.


import errno
import getpass
import httplib
import re
import os
import os.path
import StringIO
import sys
import tarfile
import tempfile
import time
import urllib

import xen.lowlevel.xc

from xen.xend import encode


SERVER = 'bugzilla.xensource.com'
SHOW_BUG_PATTERN = 'http://%s/bugzilla/show_bug.cgi?id=%%d' % SERVER
ATTACH_PATTERN = \
 'http://%s/bugzilla/attachment.cgi?bugid=%%d&action=enter' % SERVER

TITLE_RE = re.compile(r'<title>(.*)</title>')

FILES_TO_SEND = [ '/var/log/' + x for x in 
                  [ 'syslog', 'messages', 'debug',
                    'xen/xend-debug.log', 'xen/xenstored-trace.log',
                    'xen/xen-hotplug.log', 'xen/xend.log' ] +
                  [ 'xen/xend.log.%d' % z for z in range(1,6) ] ]
#FILES_TO_SEND = [  ]


def main(argv = None):
    if argv is None:
        argv = sys.argv

    print '''
This application will collate the Xen dmesg output, details of the hardware
configuration of your machine, information about the build of Xen that you are
using, plus, if you allow it, various logs.

The information collated can either be posted to a Xen Bugzilla bug (this bug
must already exist in the system, and you must be a registered user there), or
it can be saved as a .tar.bz2 for sending or archiving.

The collated logs may contain private information, and if you are at all
worried about that, you should exit now, or you should explicitly exclude
those logs from the archive.

'''
    
    bugball = []

    xc = xen.lowlevel.xc.xc()

    def do(n, f):
        try:
            s = f()
        except Exception, exn:
            s = str(exn)
        bugball.append(string_iterator(n, s))

    do('xen-dmesg', lambda: xc.readconsolering())
    do('physinfo',  lambda: prettyDict(xc.physinfo()))
    do('xeninfo',   lambda: prettyDict(xc.xeninfo()))

    for filename in FILES_TO_SEND:
        if not os.path.exists(filename):
            continue

        if yes('Include %s? [Y/n] ' % filename):
            bugball.append(file(filename))

    maybeAttach(bugball)

    if (yes('''
Do you wish to save these details as a tarball (.tar.bz2)? [Y/n] ''')):
        tar(bugball)

    return 0


def maybeAttach(bugball):
    if not yes('''
Do you wish to attach these details to a Bugzilla bug? [Y/n] '''):
        return

    bug = int(raw_input('Bug number? '))

    bug_title = getBugTitle(bug)

    if bug_title == 'Search by bug number' or bug_title == 'Invalid Bug ID':
        print >>sys.stderr, 'Bug %d does not exist!' % bug
        maybeAttach(bugball)
    elif yes('Are you sure that you want to attach to %s? [Y/n] ' %
             bug_title):
        attach(bug, bugball)
    else:
        maybeAttach(bugball)


def attach(bug, bugball):
    username = raw_input('Bugzilla username: ')
    password = getpass.getpass('Bugzilla password: ')

    conn = httplib.HTTPConnection(SERVER)
    try:
        for f in bugball:
            send(bug, conn, f, f.name, username, password)
    finally:
        conn.close()


def getBugTitle(bug):
    f = urllib.urlopen(SHOW_BUG_PATTERN % bug)

    try:
        for line in f:
            m = TITLE_RE.search(line)
            if m:
                return m.group(1)
    finally:
        f.close()

    raise ValueError("Could not find title of bug %d!" % bug)


def send(bug, conn, fd, filename, username, password):

    print "Attaching %s to bug %d." % (filename, bug)
    
    headers, data = encode.encode_data(
        { 'bugid'                : str(bug),
          'action'               : 'insert',
          'data'                 : fd,
          'description'          : '%s from %s' % (filename, username),
          'contenttypeselection' : 'text/plain',
          'contenttypemethod'    : 'list',
          'ispatch'              : '0',
          'GoAheadAndLogIn'      : '1',
          'Bugzilla_login'       : username,
          'Bugzilla_password'    : password,
          })
    
    conn.request('POST',ATTACH_PATTERN % bug, data, headers)
    response = conn.getresponse()
    try:
        body = response.read()
        m = TITLE_RE.search(body)

        if response.status != 200:
            print >>sys.stderr, (
                'Attach failed: %s %s.' % (response.status, response.reason))
        elif not m or m.group(1) != 'Changes Submitted':
            print >>sys.stderr, (
                'Attach failed: got a page titled %s.' % m.group(1))
        else:
            print "Attaching %s to bug %d succeeded." % (filename, bug)
    finally:
        response.close()


def tar(bugball):
    filename = raw_input('Tarball destination filename? ')

    now = time.time()

    tf = tarfile.open(filename, 'w:bz2')

    try:
        for f in bugball:
            ti = tarfile.TarInfo(f.name.split('/')[-1])
            if hasattr(f, 'size'):
                ti.size = f.size()
            else:
                ti.size = os.stat(f.name).st_size

            ti.mtime = now
            ti.type = tarfile.REGTYPE
            ti.uid = 0
            ti.gid = 0
            ti.uname = 'root'
            ti.gname = 'root'

            f.seek(0) # If we've added this file to a bug, it will have been
                      # read once already, so reset it.
            tf.addfile(ti, f)
    finally:
        tf.close()

    print 'Writing tarball %s successful.' % filename


def prettyDict(d):
    format = '%%-%ds: %%s' % max(map(len, [k for k, _ in d.items()]))
    return '\n'.join([format % i for i in d.items()]) + '\n'


class string_iterator(StringIO.StringIO):
    def __init__(self, name, val):
        StringIO.StringIO.__init__(self, val)
        self.name = name

    def size(self):
        return len(self.getvalue())


def yes(prompt):
    yn = raw_input(prompt)

    return len(yn) == 0 or yn.lower()[0] == 'y'


if __name__ == "__main__":
    sys.exit(main())