~bughelper-dev/bughelper/main

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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""TODO:
    * changing values in TOOL e.g. './bughelper' into 'bughelper'
    * remove logging.debug statements
    * push changes before finish
    * using bzr API (?)
"""


import threading
import time
import Queue
import subprocess
import tempfile
import glob
import ConfigParser
import os
import shutil
import logging
import optparse
import libxml2
from bugHelper.commandLine import commandLine
import bugHelper.bzrutils as bzrutils
from bugHelper.config import Config

ERROR_LOG =  {}
all_taskfiles = {}
removedfiles = set()
settings = {}
index = None

TOOLS = {"bughelper": "./bughelper", "bugnumbers": "./bugnumbers"}
FORMAT_FILEEXTENSION = {"plain": "txt", "wiki": "txt", "html": "html"}

class IndexFile(object):
    style_row = [""," bgcolor='gainsboro'"]
    
    def __init__(self, f):
        self.__items = {"bughelper-server": [], "bughelper-cron": []}
        self.__old = {"bughelper-server": {}, "bughelper-cron": {}}
        try:
            old = libxml2.htmlParseFile("%s/index.html" %settings["result-path"], None)
            x = old.xpathEval("//tr[@id]")
            for i in x:
                content = {}
                id = i.prop("id")
                y = i.xpathEval("td[1]/a")
                filename = y[0].prop("href")
                description = y[0].content
                y = i.xpathEval("td[2]/small")
                commandline = y[0].content.split()
                self.__old[id.split("_")[0]][id] = {"cline": commandline, "resultfile": filename,
                                "description": description}
        except:
            pass
        self.fileobj = file(f, "w+")
        self._header()
        self.__start = time.time()
       
    def additem(self, content, type="bughelper-server"):
        h = "%s_%s" %(type, hash(" ".join(content["cline"])))
        try:
            del self.__old[type][h]
        except: pass
        self.__items[type].append(content)
        
    def _add(self, content, type):
        h = "%s_%s" %(type, hash(" ".join(content["cline"])))
        self._write("""
            <tr%s id="%s">
                <td><a href='%s'>%s</a></td>
                <td><small>%s</small></td>
            <tr>
""" %(IndexFile.style_row[self.__rowcount], h, content["resultfile"],
                content["description"], " ".join(content["cline"])))
        self.__rowcount = not(self.__rowcount)
        
    def _write(self, text):
        self.fileobj.write(text)
        
    def _header(self):
        self._write("""<html>
    <title>bughelper-server index</title>
    <body>""")
    
    def _footer(self):
        now = time.time()
        diff = now - self.__start
        self._write("""<small>This output was generated on %s in %.2d:%.2d:%.2d</small>
    </body>
</html>""" %(time.strftime("%a, %d %b %Y %H:%M %Z"), int(diff)//3600, (int(diff)%3600)//60, (int(diff)%3600)%60))

    def _table_header(self, description):
        self.__rowcount = 0
        self._write("""<h3>%s</h3><br>
        <table>
            <thead>
                <tr>
                    <th>file</th>
                    <th>commandline</th>
                </tr>
            </thead>""" %description)
            
    def _table_footer(self):
        self._write("""</table>""")
        
    def close(self):
        if self.__items["bughelper-server"] or self.__old["bughelper-server"]:
            self._table_header("output of bughelper-server")
            for i in self.__items["bughelper-server"]:
                self._add(i, "bughelper-server")
            for v in self.__old["bughelper-server"].itervalues():
                if os.path.exists(os.path.join(settings["result-path"], v["resultfile"])):
                    self._add(v, "bughelper-server")
            self._table_footer()
        if self.__items["bughelper-cron"] or self.__old["bughelper-cron"]:
            self._table_header("output of bughelper-cron")
            for i in self.__items["bughelper-cron"]:
                self._add(i, "bughelper-cron")
            for v in self.__old["bughelper-cron"].itervalues():
                if os.path.exists(os.path.join(settings["result-path"], v["resultfile"])):
                    self._add(v, "bughelper-cron")
            self._table_footer()
        self._footer()
        self.fileobj.close()

def _get_settings():
    s = ConfigParser.ConfigParser()
    s.readfp(open('bughelper-server-config'))
    s.read([os.path.expanduser('~/.bughelper/bughelper-server-config')])
    return dict([(x[0],os.path.expanduser(x[1])) for x in s.items("config")])

def _is_like_true(value):
    if str(value).lower() in ["1", "true", "yes", "on"]:
        return True
    else:
        return False
        
def _add_counter(d, k):
    if k in d:
        d[k] += 1
    else:
        d[k] = 1
    return d
    
def lazy_makedir(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)
       
def _move_done_taskfile(file):
    assert file in all_taskfiles, "This should not happen, wrong name? '%s', %s" %(file, all_taskfiles)
    if all_taskfiles[file] > 1:
        all_taskfiles[file] -= 1
    else:
        f = os.path.split(file)
        new_file = os.path.join(settings["done-path"], f[1])
        shutil.move(file, new_file)
        removedfiles.add(f[1])
        del all_taskfiles[file]
        return 0
        
def showResults():
    while True:
        try:
            id, result = resultsQueue.get_nowait()
        except Queue.Empty:
                return
        if "sourcefile" in workRequests[id]:
            f = workRequests[id]["sourcefile"]
            _move_done_taskfile(workRequests[id]["sourcefile"])
            type = "bughelper-server"
        elif "cluefile" in workRequests[id]:
            f = workRequests[id]["cluefile"]
            type = "bughelper-cron"
        else:
            f = "<unknown source>, (description: %s)" %workRequests[id]["description"]
            type = "bughelper-cron"
        
        ERROR_LOG[id].flush()
        ERROR_LOG[id].seek(0)
        if result:
            logging.warning("failed to process '%s'\nCommandline: %s\n%s" %(f, workRequests[id]["cline"], ERROR_LOG[id].read()))
        else:
            logging.info("successfully proceed '%s'; output in '%s'" %(f, workRequests[id]["resultfile"]))
            x = ERROR_LOG[id].read()
            if x:
                logging.debug("Messages while proceeding '%s':\n%s" %(f, x))
            index.additem(workRequests[id], type)
        del workRequests[id]
        ERROR_LOG[id].close()
            
       
def bughelper_subprocess(args, filename, id=None):
    assert id in ERROR_LOG, "Missing Log-object"
    return subprocess.Popen(args, stdout=open(os.path.join(tmpdir, filename), "w"), stderr=ERROR_LOG[id]).wait() #, stderr=tempfile.TemporaryFile()
        
class Worker(threading.Thread):
    requestID = 0
    def __init__(self, requestQueue, resultQueue, **kwds):
        threading.Thread.__init__(self, **kwds)
        self.setDaemon(1)
        self.workRequestQueue = requestQueue
        self.resultQueue = resultQueue
        self.start()
    def performWork(self, args, filename):
        Worker.requestID += 1
        ERROR_LOG[Worker.requestID] = tempfile.TemporaryFile()
        self.workRequestQueue.put((Worker.requestID, args, filename))
        return Worker.requestID
    def run(self):
        while True:
            requestID, args, filename = self.workRequestQueue.get()
            self.resultQueue.put((requestID, bughelper_subprocess(args, filename, requestID)))
      
if __name__ == "__main__":
    p = optparse.OptionParser()
    p.add_option("--exclude-no-package", dest="exclude_no_package", action="store_true", default=False)
    p.add_option("--exclude-clues", dest="exclude_clues", action="store_true", default=False)
    p.add_option("--exclude-tasks", dest="exclude_tasks", action="store_true", default=False)
    p.add_option("--debug", dest="debug", action="store_true", default=False)
    options, arguments = p.parse_args()
    
    bughelper_config = Config("~/.bughelper/config")
    settings = _get_settings()
    lazy_makedir(settings["result-path"])
    lazy_makedir(settings["log-path"])
    logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)8s %(message)s',
                    filename=os.path.join(settings["log-path"], 'bughelper-server.log'),
                    filemode='a')
    tmpdir = tempfile.mkdtemp()
    logging.debug("created tmpdir: %s" %tmpdir)
                    
    index = IndexFile("%s/index.html" %tmpdir)
    logging.debug("start server")
    tool = None
    # Create queue
    requestsQueue = Queue.Queue()
    resultsQueue = Queue.Queue()
    for i in range(5):
        worker = Worker(requestsQueue, resultsQueue, name='worker %i' % (i+1))
    
    workRequests = {}
    if not options.exclude_tasks:
        try:
            bzrutils.update_branch(settings["task-path"], None, settings["branch"])
        except bzrutils.BzrError, e:
            logging.warning("failt to pull changes:\n%s" %e)
        lazy_makedir(settings["done-path"])
        logging.debug("parse cl-options")
        c = commandLine(prog="bughelper")
        default_format = c.parser.defaults["format"]
        long_store = set([i._long_opts[0] for i in c.parser._get_all_options() if i._long_opts and i.action == "store"])
        long_store -= set(["--file", "--debug"])
        long_bool = set([i._long_opts[0] for i in c.parser._get_all_options() if i._long_opts and i.action == "store_true"])
        
        logging.debug("parse task files")
        tasks = {}
        for f in glob.glob("%s/*.task" %settings["task-path"]):
            config = ConfigParser.ConfigParser()
            config.readfp(open(f))
            tasks[f] = {}
            for s in config.sections():
                opt = []
                if not config.has_option(s, "tool"):
                    config.set(s, "tool", "bughelper")
                for i in config.items(s):
                    o = "--%s" %i[0].lower()
                    if o in long_store:
                        opt.extend((o, i[1]))
                    elif o in long_bool and _is_like_true(i[1]):
                        opt.append(o)
                    elif i[0] == "tool":
                        if i[1] not in TOOLS:
                            logging.warning("invalid value %s ('%s.tool' in %s)" %(i[1], s, f))
                            break #do not continue parsing of this section
                        config.set(s, "tool", TOOLS[i[1]])
                    else:
                        logging.warning("invalid option '%s.%s' in %s" %(s, i[0], f))
                        break #do not continue parsing of this section
                else: #only continue if parsing of options in section is successfull
                    if config.has_option(s, "format"):
                        x = config.get(s, "format")
                        if x not in FORMAT_FILEEXTENSION:
                            logging.warning("unknown value %s ('%s.format' in %s)" %(x, s, f))
                            continue #only continue if format is valid
                        ext = FORMAT_FILEEXTENSION[x]
                    else:
                        ext = FORMAT_FILEEXTENSION[default_format]
                    if not config.has_option(s, "description"):
                        config.set(s, "description", s)
                    if opt:
                        opt.insert(0, config.get(s, "tool"))
                        if options.debug:
                            opt.append("--debug")
                        tasks[f][s] = {"cmd": opt, "extension": ext, "description": config.get(s, "description")}
                all_taskfiles = _add_counter(all_taskfiles, f)
            if not tasks[f]:
                del tasks[f]
                del all_taskfiles[f]
                
        logging.debug("create worker for task files")
        for file, task in tasks.iteritems():
            f = os.path.splitext(os.path.split(file)[1])[0]
            for key, value in task.items():
                id = worker.performWork(value["cmd"], "%s.%s.%s" %(f, key, value["extension"]))
                workRequests[id] = {"cline": value["cmd"],
                    "resultfile": "%s.%s.%s" %(f, key, value["extension"]),
                    "sourcefile": file, "description": value["description"]}
                showResults()
          
    if not options.exclude_clues:
        logging.debug("create worker for clue files")
        for cluefile in glob.glob("%s/*.info" % bughelper_config.packages_dir):
            packagename = os.path.basename(cluefile).split(".info")[0]
            cmdline = [TOOLS["bughelper"], "--package", packagename, "-AU", "--verbose", "2", "--format", "html"]
            if options.debug:
                cmdline.append("--debug")
            id = worker.performWork(cmdline, "%s.bughelper-cron.html" %packagename)
            workRequests[id] = {"cline": cmdline,
                "resultfile": "%s.bughelper-cron.html" %packagename,
                "cluefile": cluefile, "description": "bugs in %s" %packagename}
            showResults()
    
    if not options.exclude_no_package:
        logging.debug("create worker for non-package query")
        cmdline = [TOOLS["bughelper"], "--url", "https://bugs.launchpad.net/ubuntu/+bugs?field.has_no_package=on", "-AH", "--verbose", "2", "--format", "html"]
        if options.debug:
            cmdline.append("--debug")
        id = worker.performWork(cmdline, "ubuntu_no_package.bughelper-cron.html")
        workRequests[id] = {"cline": cmdline,
            "resultfile": "ubuntu_no_package.bughelper-cron.html",
            "description": "bugs in ubuntu with no package"}

    while workRequests:
        showResults()
        
    index.close()
    
    logging.debug("(re)move tmp-files")
    for f in glob.glob("%s/*" %tmpdir):
        shutil.move(f, settings["result-path"])
    shutil.rmtree(tmpdir)

    if removedfiles:
        logging.debug("commit changes")
        description = ""
        for i in removedfiles:
            description = "%s * removed %s\n" %(description, i)
        id = Worker.requestID + 1
        ERROR_LOG[id] = tempfile.TemporaryFile()
        p = subprocess.Popen(["bzr","commit", "-m", description], cwd=settings["task-path"], stderr=subprocess.STDOUT, stdout=ERROR_LOG[id]).wait()
        if p:
            ERROR_LOG[id].flush()
            ERROR_LOG[id].seek(0)
            logging.warning("failed to commit changes to %s\n%s" %(settings["task-path"], ERROR_LOG[id].read()))
        else:
            logging.info("successfully committed changes to %s" %settings["task-path"])
        ERROR_LOG[id].close()
    logging.debug("finish server")