vpackager / src / vpackager / bot.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
#!/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 dbutils
import dbviews
import guitools
import viewcontrollers
import threading
import buildutils
import os
import shutil
import urllib
import time
import preferences
import psutil

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


class Dispatcher(threading.Thread):
    """ Threaded Build process"""
    def __init__(self, model, view):
        threading.Thread.__init__(self)
        self.view = view
        self.model = model

    def get_builder(self, srcuri, _id):
        """ Returns the correct source object based on the source URI"""
        if srcuri.startswith('/'):
            srcob = buildutils.Source(srcuri)
        else:
            # we need to get the details about this job
            details = self.model.GetJobDetails(_id)
            srcob = buildutils.SourceURL(
                app = details['app'], version = details['ver'],
                srctype = details['type'], link=srcuri)
        return srcob

    def process_source(self, srcuri, workdir):
        """ Copy the source to the right location """
        if srcuri.startswith('/'):
            return shutil.copy2(srcuri, workdir)
        return

    def process_doinst(self, doinstURI, workdir):
        if doinstURI in ("", None):
            return
        if doinstURI.startswith('/'):
            return shutil.copy2(doinstURI,
                                os.path.join(workdir, 'doinst.sh'))
        else:
            self.print_to_log(
                "\n +++ Downloading post-install script %s\n"% doinstURI)
            os.chdir(workdir)
            return urllib.urlretrieve(doinstURI, 'doinst.sh')

    def process_description(self, descuri, workdir):
        """ Copy or download the package description to the right place"""
        if not descuri:
            return
        if descuri is None:
            return
        if descuri.startswith('/'):
            self.print_to_log(
                "\n +++ Copying package description from %s\n"% descuri)
            return shutil.copy2(descuri, workdir)
        else:
            self.print_to_log(
                "\n +++ Downloading package description from %s\n"% descuri)
            _prevdir = os.getcwd()
            os.chdir(workdir)
            urllib.urlretrieve(descuri, 'slack-desc')
            return os.chdir(_prevdir)
        return

    def process_patches(self, patchlist, workdir):
        """ copy or download any patches into the source tree"""
        if patchlist in (None,"","None"):
            return
        _prevdir = os.getcwd()
        patchesdir = os.path.join(workdir, 'patches')
        try:
            os.makedirs(patchesdir)
        except:
            pass
        for patch in patchlist.split(','):
            if patch.startswith('/'):
                shutil.copy2(patch, patchesdir)
            else:
                os.chdir(patchesdir)
                # I need to determine the filename so we can save it.
                self.print_to_log('\n   +++ Downloading patch: %s\n'% patch)
                pname = patch.rsplit('/',1)[1]
                urllib.urlretrieve(patch, pname)
        return os.chdir(_prevdir)

    def clear_textview(self):
        buf = self.view.textview.get_buffer()
        start, end = buf.get_bounds()
        return buf.delete(start, end)

    def log_output_to_file(self, logfile_abspath):
        buf = self.view.textview.get_buffer()
        start, end = buf.get_bounds()
        f = open(logfile_abspath, 'w')
        f.write(buf.get_text(start, end))
        f.close()
        return

    def print_to_log(self, data):
        return self.view.PlayOutput(data)

    def run(self):
        """ Actual build sequence"""
        while self.view._parentView.RUN_BOT:
            time.sleep(1)
            job_id = self.model.GetNextJob()
            if job_id is None:
                self.print_to_log(
                    "\n   *** No more jobs in queue. Stopping bot ***")
                return self.view.StopBot()
            #clear the textview()
            self.clear_textview()
            job_info = self.model.GetJobDetails(job_id)
            # Create the appropriate build object
            srcob = self.get_builder(job_info['srcURI'], job_info['id'])
            # Show the progress on the GUI
            self.view.IndicateBotRunning(app = job_info['app'],
                                         ver = job_info['ver'])
            # Log the job start
            self.model.LogJobStart(job_id)

            # Create the build script
            sbpath = srcob.makeSlackBuild(
                buildno = job_info['release'])
            workdir = os.path.dirname(sbpath)
            # cd to the right place to perform operations
            os.chdir(os.path.dirname(sbpath))
            # Process the source code
            self.process_source(job_info['srcURI'], workdir)
            # Process the package description
            self.process_description(job_info['descURI'], workdir)
            # Process the specified post-install script
            self.process_doinst(job_info['doinstURI'], workdir)
            # Process any patches added to the build
            self.process_patches(job_info['patches'], workdir)
            # cd back to the original workdir (just in case)
            os.chdir(os.path.dirname(sbpath))
            # Create build job object
            #job = srcob.buildSlackBuild()
            job = srcob.buildSlackBuild(config=job_info['config'])
            # Connect the observer so we can watch the matrix.
            job.observer.add_callback(self.view.PlayOutput)
            # start the job
            job.run()
            while job._popen_running:
                time.sleep(1)
            retval = job.popen.returncode
            if retval > 0:
                result = 'Fail'
            else:
                result = 'Success'

            # Install the package if it was requested
            if result == 'Success' and job_info['install'] == "1":
                self.print_to_log(
                    "\n   + Installing package per user request +")
                proc = srcob.install_pkg()
                # again, play the output on the GUI
                proc.observer.add_callback(self.view.PlayOutput)
                proc.run()
                while proc._popen_running:
                    time.sleep(1)
                retval = proc.popen.returncode

            # Log the output to a file
            logpath = os.path.join(os.path.dirname(srcob.srclocation),
                                   '%s.build_log'% job_info['app'])
            self.log_output_to_file(logpath)

            # Log the end of the job on the database:
            self.model.LogJobEnd(job_id, logpath, result)
        return

class StatusTab(gtk.VBox):
    """ Content of the status tab packed in a vbox that can be
    appended as a page to the tabstrip"""

    def __init__(self, model, _parentView=None):
        gtk.VBox.__init__(self)
        self.model = model
        self._parentView = _parentView
        self.pack_start(self._get_output_display(), True, True, 4)

    def IndicateBotRunning(self, app, ver):
        """ Indicate in the GUI that the bot is running. This just
        returns a method from the parent window"""
        return self._parentView.IndicateBotRunning(app, ver)

    def IndicateBotStopped(self):
        """ Indicate in the gui that the bot is stopped.  Just returns
        a method from the parent window"""
        return self._parentView.IndicateBotStopped()

    def StopBot(self, widget=None):
        """ Stop the bot"""
        return self._parentView.StopBot()

    def StartBot(self, widget=None):
        """ Start the bot"""
        return self._parentView.StartBot()

    def PlayOutput(self, data):
        gtk.gdk.threads_enter()
        try:
            buf = self.textview.get_buffer()
            buf.insert(buf.get_end_iter(), data)
            # scroll the lines if necessary
            vad = self.scrl.get_vadjustment()
            newpos = vad.get_upper() - vad.get_page_size()
            vad.set_value(newpos)
            self.scrl.set_vadjustment(vad)
        except:
            pass
        gtk.gdk.threads_leave()

    def _get_output_display(self):
        self.scrl = gtk.ScrolledWindow()
        self.scrl.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.textview = gtk.TextView()
        self.textview.set_editable(False)
        for edge in (gtk.TEXT_WINDOW_LEFT, gtk.TEXT_WINDOW_RIGHT,
                     gtk.TEXT_WINDOW_TOP, gtk.TEXT_WINDOW_BOTTOM):
            self.textview.set_border_window_size(edge, 4)
        self.scrl.add(self.textview)

        return self.scrl


class Gui(gtk.Window):
    """ Main window for vpackager"""
    def __init__(self, dbase_model):
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
        self.dbase_model = dbase_model
        self.RUN_BOT = False
        self.body = gtk.VBox()
        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_title('vpackager')
        self.set_position(gtk.WIN_POS_CENTER)
        self.body.pack_start(self._get_menubar(), False, True, 2)
        self.tabstrip = guitools.TabStrip()
        self.bot_tab = StatusTab(_parentView = self,
                                 model = self.dbase_model)
        #self.bot_tab = StatusTab(model = self.dbase_model, )

        # Bot control and status bar.
        bot_controlbar = gtk.HBox()
        btStatuslb = gtk.Label()
        btStatuslb.set_property('use-markup', True)
        btStatuslb.set_markup('<b>Bot Status: </b>')
        bot_controlbar.pack_start(btStatuslb, False, False, 2)
        self.bot_state_label = gtk.Label()
        self.bot_state_label.set_property('use-markup', True)
        self.bot_state_label.set_property('xalign', 0.0)
        bot_controlbar.pack_start(self.bot_state_label, True, True, 2)
        self.bt_bot_start = guitools.vButton(stock=gtk.STOCK_YES,
                                             label = 'Start')
        self.bt_bot_stop = guitools.vButton(stock=gtk.STOCK_NO,
                                            label = 'Stop')
        bot_controlbar.pack_start(self.bt_bot_start, False, False, 2)
        bot_controlbar.pack_start(self.bt_bot_stop, False, False, 2)

        self.body.pack_start(bot_controlbar, False, True, 4)

        #self.bot_tab = StatusTab()
        self.queue_view = dbviews.QueueView()
        self.history_view = dbviews.HistoryView()
        queue_controller = viewcontrollers.QueueController(
            model = self.dbase_model, view = self.queue_view)
        history_controller = viewcontrollers.HistoryController(
            model = self.dbase_model, view = self.history_view)

        self.tabstrip.append_page(self.queue_view,
                                  guitools.TabIcon(
                                    label = 'Job Queue',
                                    stock=gtk.STOCK_INDEX))
        self.tabstrip.append_page(self.history_view,
                                  guitools.TabIcon(
                                    label = 'Job History',
                                    stock=gtk.STOCK_JUSTIFY_FILL))
        self.tabstrip.append_page(self.bot_tab,
                                  guitools.TabIcon(
                                    label='Terminal\nOutput',
                                    stock=gtk.STOCK_EXECUTE))



        self.body.pack_start(self.tabstrip, True, True, 2)
        self.add(self.body)
        self.show_all()
        #self.connect('destroy', self._exit)
        self.connect('delete-event', self._exit)
        self.set_size_request(700,400)

        # Connect the start/stop buttons
        self.bt_bot_start.connect('clicked', self.StartBot)
        self.bt_bot_stop.connect('clicked', self.StopBot)

        # Initialize the dispatcher
        self.dispatcher = Dispatcher(model = self.dbase_model,
                                     view = self.bot_tab)

        self.CheckDatabase()

        # Force initial display of the queue and history
        self.dbase_model.RefreshQueue()
        self.dbase_model.RefreshHistory()
        self.StopBot(self.bt_bot_stop)

    def StartBot(self, widget=None):
        """ Start the bot"""
        self.RUN_BOT = True
        #self.bt_bot_start.set_sensitive(False)
        #self.bt_bot_stop.set_sensitive(True)

        try:
            self.dispatcher.start()
        except:
            del self.dispatcher
            self.dispatcher = Dispatcher(model = self.dbase_model,
                                         view = self.bot_tab)
            self.dispatcher.start()

    def StopBot(self, widget=None):
        self.RUN_BOT = False
        return self.IndicateBotStopped()

    def IndicateBotStopped(self):
        """ Update the GUI to indicate the bot is not running"""
        self.bot_state_label.set_text('Stopped')
        self.bt_bot_start.set_sensitive(True)
        self.bt_bot_stop.set_sensitive(False)

    def IndicateBotRunning(self, app, ver):
        """ UPdate the GUI to indicate the bot is running and
        show the current job being built"""
        self.bot_state_label.set_text(
            "Building %s-%s"%(app, ver))
        self.bt_bot_start.set_sensitive(False)
        self.bt_bot_stop.set_sensitive(True)

    def CheckDatabase(self):
        """ Run a sanity check and make sure the databse tables exist"""
        self.dbase_model._cleanup_history()
        if self.dbase_model.verify_tables() is True:
            return self.dbase_model.CreateTables()

    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)

        editm = gtk.MenuItem("Edit")
        editmenu = gtk.Menu()
        editm.set_submenu(editmenu)
        mb.append(editm)
        editprefs = gtk.MenuItem("Preferences")
        editmenu.append(editprefs)
        editprefs.connect('activate', self.ShowPrefsWindow)

        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 ShowPrefsWindow(self, widget=None):
        """ Show the preferences window and update the settings
        accordingly"""
        dia = guitools.PrefsDialog(parent = self)
        res = dia.run()
        dia.hide()
        if res == gtk.RESPONSE_OK:
            conf = preferences.VPConf()
            conf.SetSetting('packager_name', dia.PACKAGER_NAME)
            conf.SetSetting('sources_home', dia.DEFAULT_SOURCES_PATH)
            conf.SetSetting('database_home', dia.DATABASE_HOME)

        return dia.destroy()

    def _force_exit(self):
        """ Force close the application """
        parent = psutil.Process(os.getpid())
        for child in parent.get_children():
            child.kill()
        parent.kill()
        self.dbase_model.close()
        return gtk.main_quit()

    def _exit(self, widget=None, event=None):
        if self.RUN_BOT:
            # Warn the user about running tasks
            msg = "The build bot is currently running. Are you sure you "\
                  "want to quit anyway?"
            dia = guitools.message.Question(text=msg, parent=self)
            res = dia.run()
            dia.hide()
            if res == gtk.RESPONSE_YES:
                # Force quit
                return self._force_exit()
            else:
                return True
        else:
            self.RUN_BOT = False
            time.sleep(0.25)
            self.dbase_model.close()
            return gtk.main_quit()

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



if __name__ == '__main__':
    model = dbutils.dbase()
    w = Gui(dbase_model = model)
    w.show_all()
    gtk.gdk.threads_init()
    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.