Source

vpackager / src / vpackager / bot.old.py

  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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#!/usr/bin/env python

#    This file is part of vpackager.
#
#    vpackager is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License v2 as published by
#    the Free Software Foundation.
#
#    vpackager 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 vpackager.  If not, see <http://www.gnu.org/licenses/>.

import gtk
import guitools
import dbutils
import buildutils
import jobmanage
import historymanager
import threading
import time
import os
import sqlite3
import urllib2
import urllib
import shutil
import glib

__author__ = 'M0E-lnx'
__author_email__ = 'moc.liamg@xnl.E0M'[::-1]
__version__ = '0.1'

class Dispatcher(threading.Thread):
    """ Dispatcher thread used for dispatching jobs from the queue"""
    def __init__(self, parent=None, dbase=None):
        threading.Thread.__init__(self)
        self.name = 'job-dispatcher'
        self.parent = parent

        if dbase:
            self.dbase = dbase
        else:
            self.dbase = dbutils.dbase()

    def _get_next_job(self):
        ''' Get the next job in line from the database '''
        print self.parent
        return self.parent._get_next_job_()
        #return self.dbase.GetNextJob()

    def _log_job_start(self, _id):
        ''' Log the job start to the database history'''
        return self.dbase.LogJobStart(_id)

    def _log_job_end(self, _id, stdoutpath, result):
        ''' Log the job end to the database history'''
        return self.dbase.LogJobEnd(_id, stdoutpath, result)

    def _refresh_views(self):
        ''' Refresh the screens that show the database status '''
        self.parent.historyman._refresh_history_display()
        self.parent.queueman._update_queue()

    def _download_file(self, url):
        '''download a remote file to the local directory'''
        urllib.urlretrieve(url)

    def run(self):
        while self.parent._bot_run:
            time.sleep(0.25)
            njob = self._get_next_job()
            if njob is None:
                # NO new job in queue
                self.parent._bot_run = False
                print "Stopping bot because there is nothing to do"
                return
            # clear the textview
            buf = self.parent.outputplayer.get_buffer()
            buf.delete(buf.get_bounds()[0], buf.get_bounds()[1])
            _id = njob[0]
            info = self.dbase.GetJobDetails(_id)
            pkg = info['app']
            ver = info['ver']
            src = info['srcURI']
            desc = info['descURI']
            rel = info['release']
            _type = info['type']
            patches = info['patches']
            toinstall = info['install']
            patchlist = []
            if patches:
                patchlist = patches.split(',')
            # Log the build start time
            self._log_job_start(_id)
            # Update GUI displays for queue and history
            self._refresh_views()
            self.parent.job_indicator.set_markup('<b>%s-%s</b>'%(pkg,ver))
            if src.startswith('/'):
                srcob = buildutils.Source(src)
            else:
                srcob = buildutils.SourceURL(app = pkg, version=ver,
                        srctype=_type, link=src)
            sbpath = srcob.makeSlackBuild(buildno = rel)
            # cd to the right place
            os.chdir(os.path.dirname(sbpath))
            if desc:
                if desc.startswith('/'):
                    shutil.copy2(desc, 'slack-desc')
                else:
                    self.parent._play_output('Downloading description from %s \n'% desc)
                    u = urllib2.urlopen(desc)
                    f = open('slack-desc', 'w')
                    f.write(u.read())
                    f.close()
                    u.close()
            if patchlist:
                os.chdir(os.path.join(
                    os.path.dirname(sbpath), 'patches'))
                for patch in patchlist:
                    if patch.startswith('/'):
                        self.parent._play_output('\
                                Adding patch %s to source tree \n'% patch)
                        shutil.copy2(patch, os.path.join(
                                    os.path.dirname(sbpath), 'patches',patch))
                    else:
                        self.parent._play_output('\
                                Downloading patch %s \n'% patch)
                        self._download_file(patch)
            os.chdir(os.path.dirname(sbpath))
            job = srcob.buildSlackBuild()
            job.observer.add_callback(self.parent._play_output)
            job.run()
            while job._popen_running:
                time.sleep(1)
            retval = job.popen.returncode
            if retval > 0:
                result = 'Fail'
            else:
                result = 'Success'

            # Save the output to a log file
            buf = self.parent.outputplayer.get_buffer()
            #logpath = sbpath.replace('.SlackBuild', '.build_log')
            logpath = os.path.join(os.path.dirname(srcob.srclocation),
                    '%s.build_log'% srcob.app)
            output = buf.get_text(buf.get_bounds()[0], buf.get_bounds()[1])
            f = open(logpath, 'w')
            f.write(output)
            f.close()
            # Log the build result to the database
            self._log_job_end(_id, logpath, result)
            # Refresh the GUI display of the history and queue
            self._refresh_views()
            if result == "Success" and toinstall == "1":
                # install the package
                self.parent._play_output(
                        '\nInstalling package \n')
                try:
                    proc = srcob.install_pkg()
                    proc.observer.add_callback(self.parent._play_output)
                    proc.run()
                    while proc._popen_running:
                        time.sleep(1)
                    retval = proc.popen.returncode
                except:
                    print 'Error while installing package'
                    pass
        #self.dbase.close()

class Tab(gtk.VBox):
    ''' Generic tab for use in the tabstrip '''
    def __init__(self, label='', stock=None, parent=None, dbase = None ):
        gtk.VBox.__init__(self)
        if dbase is None:
            self.dbase = dbutils.dbase()
        else:
            self.dbase = dbase
        ibox = gtk.VBox()
        img = gtk.Image()
        img.set_from_stock(stock, gtk.ICON_SIZE_BUTTON)
        ibox.pack_start(img, False, False, 2)
        lbl = gtk.Label()
        lbl.set_use_markup(True)
        lbl.set_markup(label)
        ibox.pack_start(lbl, False, False, 2)
        self.label = ibox
        self.label.show_all()
        self._parent = parent

class TabStatus(Tab):
    ''' Bot control and status tab '''
    def __init__(self, *args, **kwargs):
        Tab.__init__(self, label='Bot Status', 
                stock=gtk.STOCK_PREFERENCES, **kwargs)
        #Tab.__init__(self, label='Bot Status',
        #        stock=gtk.STOCK_PREFERENCES)

        topbox = gtk.HBox()
        flt = gtk.Frame('Bot Status')
        lvbox = gtk.VBox()
        flt.add(lvbox)
        ltbox = gtk.HBox()
        lbbox = gtk.HBox()
        lvbox.pack_start(ltbox, False , True, 2)
        lvbox.pack_start(lbbox, False, True, 2)
        lb0 = gtk.Label()
        lb1 = gtk.Label()
        lb0.set_use_markup(True)
        lb1.set_use_markup(True)
        lb0.set_markup('Current Status:')
        lb1.set_markup('Current Job:')
        self.label_bot_status = gtk.Label()
        self.label_bot_status.set_use_markup(True)
        self.label_current_job = gtk.Label()
        self.label_current_job.set_use_markup(True)
        ltbox.pack_start(lb0, False, False, 2)
        ltbox.pack_start(self.label_bot_status, False, True, 2)
        lbbox.pack_start(lb1, False, False, 2)
        lbbox.pack_start(self.label_current_job, False, True, 2)
        self._parent.bot_indicator = self.label_bot_status
        self._parent.job_indicator = self.label_current_job

        self._parent.bot_indicator.set_markup('<b>Stopped</b>')
        self._parent.job_indicator.set_markup('<b>None</b>')

        frt = gtk.Frame('Bot Control')
        rvbox = gtk.VBox()
        frt.add(rvbox)
        rtbox = gtk.HBox()
        rbbox = gtk.HBox()

        btStopBot = guitools.vButton(label='Stop', stock=gtk.STOCK_NO)
        btStartBot = guitools.vButton(label='Start', stock=gtk.STOCK_YES)
        self.btStopBot = btStopBot
        self.btStartBot = btStartBot
        btStartBot.connect('clicked', self._start_bot)
        btStopBot.connect('clicked', self._stop_bot)

        rtbox.pack_start(btStartBot, False, False, 2)
        rtbox.pack_start(btStopBot, False, False, 2)

        rvbox.pack_start(rtbox, False, True, 2)
        rvbox.pack_start(rbbox, False, True, 2)

        topbox.pack_start(flt, True, True, 2)
        topbox.pack_start(frt, False, False, 2)
        self.pack_start(topbox, False, True, 4)

        # add a textview inside a scrolled window for output monitoring.
        self.scroll = gtk.ScrolledWindow()
        self.scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.stdoutmon = gtk.TextView()
        self.stdoutmon.set_property('editable', False)
        for edge in (gtk.TEXT_WINDOW_LEFT, gtk.TEXT_WINDOW_RIGHT,
                gtk.TEXT_WINDOW_TOP, gtk.TEXT_WINDOW_BOTTOM):
            self.stdoutmon.set_border_window_size(edge, 4)
        self.scroll.add(self.stdoutmon)

        frmoutput = gtk.Frame('Build Output')
        frmoutput.add(self.scroll)
        self._parent.outputplayer = self.stdoutmon
        self._parent.scrollarea = self.scroll

        self.pack_start(frmoutput, True, True, 4)
        self.mon_thread = threading.Thread(target=self.__bot_monitor,
                name='vpackager-bot-monitor', args=())
        self.mon_thread.start()
        self.jobDispatcher = Dispatcher(parent = self._parent, 
                dbase = self.dbase)

    def __bot_monitor(self):
        while self._parent._bot_run:
            gtk.gdk.threads_enter()
            self.btStartBot.set_property('sensitive', False)
            self.btStopBot.set_property('sensitive', True)
            self._parent.bot_indicator.set_markup('<b>Running</b>')
            gtk.gdk.threads_leave()
            time.sleep(0.25)
        gtk.gdk.threads_enter()
        self.btStartBot.set_property('sensitive', True)
        self.btStopBot.set_property('sensitive', False)
        self._parent.bot_indicator.set_markup('<b>Stopped</b>')
        self._parent.job_indicator.set_markup('<b>None</b>')
        gtk.gdk.threads_leave()

    def __log_line(self, line):
        buf = self.stdoutmon.get_buffer()
        buf.insert(buf.get_end_iter(), line + '\n')

    def _stop_bot(self, widget=None):
        self._parent._bot_run = False
        return

    def _dispatch_job(self):
        _id = 0
        while self.dbase.GetQueue():
            jobs = self.dbase.GetQueue()
            job = jobs[_id]
            yield job
            _id += 1
            jobs = self.dbase.GetNextJob()


    def _start_bot(self, widget=None):
        self._parent._bot_run = True
        # ^^ Sends the signal to update the UI
        if not self.mon_thread.isAlive():
            del self.mon_thread
            self.mon_thread = threading.Thread(target=self.__bot_monitor,
                    name='vpackager-bot-monitor', args=())
            self.mon_thread.start()
        # Use a generator to dispatch jobs.
        for job in self.dbase.GetQueue():
            #print job[0]
            self._do_build_job(job[0])

    def _do_build_job(self, _id):
        """ Perform the build job """
        info = self.dbase.GetJobDetails(_id)
        pkg = info['app']
        ver = info['ver']
        src = info['srcURI']
        desc = info['descURI']
        rel = info['release']
        _type = info['type']
        toinstall = info['install']
        patches = info['patches']
        patchlist = []
        if patches:
            patchlist = patches.split(',')

        # Log the timestamp at the job start.
        self.dbase.LogJobStart(_id)
        # update the views that display the queue and history
        self._parent.historyman._refresh_history_display()
        self._parent.queueman._update_queue()
        # clear the text view
        buf = self._parent.outputplayer.get_buffer()
        start, end = buf.get_bounds()
        buf.delete(start, end)
        # create the source object to begin work
        if src.startswith('/'):
            srcob = buildutils.Source(src)
        else:
            srcob = buildutils.SourceURL(app = pkg, 
                    version = ver, srctype = _type,
                    link = src)
        # get the path to the slackbuild
        sbpath = srcob.makeSlackBuild(buildno = rel)
        # cd to the right place
        os.chdir(os.path.dirname(sbpath))

        # Create the job
        job_ = srcob.buildSlackBuild()
        job_.observer.add_callback(self._parent._play_output)
        # hand the build process off to another thread
        t = threading.Thread(target=job_.run, args=())
        t.start()
        time.sleep(1)
        #job_.run()
        while job_.popen.running:
            time.sleep(1)
        retval = job_.popen.returncode
        if retval > 0:
            result = 'Fail'
        else:
            result = 'Success'

        # Save the output to a log file
        start, end = buf.get_bounds()
        logpath = os.path.join(os.path.dirname(srcob.srclocation),
                '%s.build_log'% srcob.app)
        output = buf.get_text(start, end)
        f = open(logpath, 'w')
        f.write(output)
        f.close()

        # Log the job end timestamp
        self.dbase.LogJobEnd(_id, logpath, result)

        # Update the view
        self._parent.queueman._update_queue()
        self._parent.historyman._refresh_history_display()



        #if not self.jobDispatcher.isAlive():
        #    del self.jobDispatcher
        #    self.jobDispatcher = Dispatcher(parent=self._parent,
        #            dbase=self.dbase)
        #    self.jobDispatcher.start()
        #return

class TabQueue(Tab):
    """ Job queue tab. Used to manage build jobs."""
    def __init__(self, dbase=None, *args, **kwargs):
        Tab.__init__(self, label = 'Job Queue',
                stock = gtk.STOCK_INDEX, **kwargs)
        if not self.dbase:
            if dbase is None:
                self.dbase = dbutils.dbase()
            else:
                self.dbase = dbase
        cont = jobmanage.Main()
        self.pack_start(cont, True, True, 2)
        self._parent.queueman = cont

    def _refresh_ui(self):
        return self._parent.queueman._update_queue()

class TabHistory(Tab):
    """ Tab displaying the job build history"""
    def __init__(self, dbase = None, *args, **kwargs):
        Tab.__init__(self, label = 'Job History',
                stock=gtk.STOCK_JUSTIFY_FILL, **kwargs)
        if not self.dbase:
            if not dbase:
                self.dbase = dbutils.dbase()
            else:
                self.dbase = dbase
        cont = historymanager.Main()
        self.pack_start(cont, True, True, 2)
        self._parent.historyman = cont

    def _refresh_ui(self):
        return self._parent.historyman._refresh_history_display()

class TabStrip(gtk.Notebook):
    """ Tabstrip used to display the main content of the application"""
    def __init__(self):
        gtk.Notebook.__init__(self)
        self.set_property('tab-pos', gtk.POS_LEFT)
        self.connect('switch-page', self._switch_page_event)

    def _switch_page_event(self, widget=None, page=None, page_num=0):
        if page_num in (1,2):
            return self.get_nth_page(page_num)._refresh_ui()
        #print page_num
        #return

        child = self.get_nth_page(page_num)
        #return child.

class App(gtk.Window):
    """ Main app GUI """
    def __init__(self):
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
        # Load the database
        self.dbase = dbutils.dbase()
        self.set_title('vpackager')
        self.connect('destroy', self._exit)
        datadir = os.path.dirname(os.path.abspath(__file__))
        datadir = os.path.join(datadir, 'data')
        self.set_icon_from_file(os.path.join(datadir, 'vpackager.png'))
        self.set_size_request(950, 500)
        self.body = gtk.VBox()
        # make sure the db is ok
        self._check_db_sanity()
        self.outputplayer = None
        self.historyman = None
        self.queueman = None
        self._bot_run = False
        self.body.pack_start(self._get_menubar(), False, True, 4)
        self.body.pack_start(self._get_notebook(), True, True, 4)

        self.add(self.body)

    def _get_next_job_(self):
        return self.dbase.GetNextJob()

    def _get_menubar(self):
        mb = gtk.MenuBar()
        filemenu = gtk.Menu()
        filem = gtk.MenuItem("File")
        filem.set_submenu(filemenu)

        exit = gtk.MenuItem("Exit")
        exit.connect("activate", self._exit)
        filemenu.append(exit)

        mb.append(filem)

        helpm = gtk.MenuItem("Help")
        helpmenu = gtk.Menu()
        helpm.set_submenu(helpmenu)

        about = gtk.MenuItem("About")
        about.connect("activate", self._show_about)
        helpmenu.append(about)
        mb.append(helpm)
        return mb

    def _show_about(self, widget=None):
        """Display the about window"""
        dia = guitools.About()
        if dia.run():
            dia.destroy()


    def _play_output(self, line=None):
        gtk.gdk.threads_enter()
        buf = self.outputplayer.get_buffer()
        buf.insert(buf.get_end_iter(), line)
        #gtk.gdk.threads_enter()
        vad = self.scrollarea.get_vadjustment()
        newpos = vad.get_upper() - vad.get_page_size()
        vad.set_value(newpos)
        self.scrollarea.set_vadjustment(vad)
        gtk.gdk.threads_leave()


    def _get_notebook(self):
        """ Main content notebook"""
        strip = TabStrip()
        stats = TabStatus(parent=self, dbase = self.dbase)
        strip.append_page(stats, stats.label)

        queuet = TabQueue(parent=self, dbase = self.dbase)
        strip.append_page(queuet, queuet.label)

        history = TabHistory(parent=self, dbase = self.dbase)
        strip.append_page(history, history.label)


        return strip

    def _get_bottombar(self):
        return gtk.Label('Bottom bar')

    def _exit(self, widget=None):
        self._stop_bot = True
        time.sleep(0.25)
        self.dbase.close()
        return gtk.main_quit()

    def _check_db_sanity(self):
        if self.dbase.verify_tables():
            self.dbase.CreateTables()

if __name__ == '__main__':
    gtk.gdk.threads_init()
    w = App()
    w.show_all()
    gtk.gdk.threads_enter()
    gtk.main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.