aboutsummaryrefslogtreecommitdiff
path: root/stream-lava-log.py
blob: f3e6e4ef901b6df6698feb41ddf91652ef0b01f9 (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
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
#!/usr/bin/env python
#
# This file is part of lava-hacks.  lava-hacks is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program 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
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Tyler Baker 2015

import os
import sys
import argparse
import urlparse
import datetime
import time
import xmlrpclib
import ConfigParser
import curses
import re

from text_output import TextBlock


class FileOutputHandler(object):
    def __init__(self, file_obj, outputter):
        self.file_obj = file_obj
        self.outputter = outputter

        self.full_output = ""
        self.printed_output = ""


    def run(self):
        while True:
            self._update_output()
            self._print_output()

            if not self.outputter.is_running(): break

            time.sleep(2)

        self.file_obj.write("Job has finished.")


    def _update_output(self):
        self.full_output = self.outputter.get_output()


    def _print_output(self):
        if not self.full_output:
            self.file_obj.write("No job output...\n")

        new_output = self.full_output[len(self.printed_output):]

        self.file_obj.write(new_output)
        self.file_obj.flush()
        self.printed_output = self.full_output


class CursesOutput(object):
    def __init__(self, outputter, follow=True):
        self.outputter = outputter
        self.textblock = TextBlock()
        self.follow = follow

        self.win_height = 0
        self.win_width = 0
        self.win_changed = False
        self.cur_line = 0
        self.status_win = None
        self.state_win_height = 2
        self.output = ""
        self.text_changed = False


    def run(self):
        curses.wrapper(self._run)


    def _run(self, stdscr):
        self.stdscr = stdscr
        self._setup_win()

        while True:
            self._update_win()
            self._poll_state()

            self._redraw_output()
            self._redraw_status()

            self._refresh()
            time.sleep(0.1)


    def _setup_win(self):
        self.win_height, self.win_width = self.stdscr.getmaxyx()
        self.status_win = curses.newwin(self.state_win_height, self.win_width, self.win_height-self.state_win_height, 0)
        self.status_win.bkgdset(' ', curses.A_REVERSE)
        self.textblock.set_width(self.win_width, reflow=False)
        self.win_changed = True


    def _update_win(self):
        if curses.is_term_resized(self.win_height, self.win_width):
            self.win_height, self.win_width = self.stdscr.getmaxyx()
            curses.resizeterm(self.win_height, self.win_width)

            self.status_win.resize(self.state_win_height, self.win_width)
            self.status_win.mvwin(self.win_height-self.state_win_height, 0)

            self.textblock.set_width(self.win_width, reflow=False)

            self.win_changed = True


    def _poll_state(self):
        old_output_len = len(self.output)

        self.output = self.outputter.get_output()

        if len(self.output) != old_output_len:
            self.textblock.set_text(self.output, reflow=False)
            self.text_changed = True


    def _redraw_output(self):
        if self.text_changed or self.win_changed:
            output_lines = None

            self.textblock.reflow()
            if self.follow:
                output_lines = self.textblock.get_block(-1, self.win_height-self.state_win_height)
            else:
                output_lines = self.textblock.get_block(self.cur_line, self.win_height-self.state_win_height)

            self.stdscr.clear()
            self._draw_text(output_lines)

            self.win_changed = False
            self.text_changed = False


    def _redraw_status(self):
        details = "description: %s" % self.outputter.get_description()
        details += "   device_type: %s" % self.outputter.get_device_type_id()
        details += "   hostname: %s" % self.outputter.get_hostname()
        self.status_win.addstr(0, 0, details[:self.win_width-1])

        status = "active: %s" % self.outputter.is_running()
        status += "   action: %s" % self.outputter.last_action()
        self.status_win.addstr(1, 0, status[:self.win_width-1])


    def _draw_text(self, lines):
        for index, line in enumerate(lines):
            self.stdscr.addstr(index, 0, line)


    def _refresh(self):
        self.stdscr.refresh()
        self.status_win.refresh()


class Config(object):
    def __init__(self, config_sources=None):
        self.config_sources = config_sources or list()


    def add_config_override(self, config_source):
        self.config_sources.insert(0, config_source)


    def has_enough_config(self):
        return (self.get_config_variable('username') and
                self.get_config_variable('token') and
                self.get_config_variable('server'))


    def construct_url(self):
        if not self.has_enough_config():
            raise Exception("Not enough configuration to construct the URL")

        url = urlparse.urlparse(self.get_config_variable('server'))

        if not url.path.endswith(('/RPC2', '/RPC2/')):
            print "LAVA Server URL must end with /RPC2 or /RPC2/"
            exit(1)

        return (url.scheme + '://' +
                self.get_config_variable('username') + ':' +
                self.get_config_variable('token') +
                '@' + url.netloc + url.path)


    def get_config_variable(self, variable_name):
        for config_source in self.config_sources:
            method_name = 'get_%s' % variable_name
            if hasattr(config_source, method_name):
                variable = getattr(config_source, method_name)()
                if variable:
                    return variable


class FileConfigParser(object):
    def __init__(self, filename=None, section=None):
        self.section = section or "default"
        self.filename = filename or os.path.expanduser('~/.lavarc')

        self.config_parser = ConfigParser.ConfigParser()

        if os.path.isfile(self.filename):
            self.config_parser.readfp(open(self.filename))

        self.username = None
        self.token = None
        self.server = None


    def get_username(self):
        if self.username: return self.username

        if self.config_parser:
            self.username = self.config_parser.get(self.section, 'username')
        return self.username


    def get_token(self):
        if self.token: return self.token

        if self.config_parser:
            self.token = self.config_parser.get(self.section, 'token')
        return self.token


    def get_server(self):
        if self.server: return self.server

        if self.config_parser:
            self.server = self.config_parser.get(self.section, 'server')
        return self.server


class ArgumentParser(object):
    def __init__(self, args):
        self.username = args.get('username')
        self.token = args.get('token')
        self.server = args.get('server')
        self.job = args.get('job')


    def get_username(self):
        return self.username


    def get_token(self):
        return self.token


    def get_server(self):
        return self.server


    def get_job(self):
        return self.job


def handle_connection(func):
    def inner(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except xmlrpclib.ProtocolError as e:
            if e.errcode == 502:
                print "Protocol Error: 502 Bad Gateway, retrying..."
            elif e.errcode == 401:
                print "Server authentication error."
                print e
                exit(1)
            else:
                print "Unknown XMLRPC error."
                print e
                exit(1)
        except xmlrpclib.Fault as e:
            if e.faultCode == 404 and e.faultString == \
                    "Job output not found.":
                pass
        except (IOError, Exception) as e:
            print "Function %s raised an exception, exiting..." % func.__name__
            print e
            exit(1)
    return inner


class LavaConnection(object):
    def __init__(self, configuration):
        self.configuration = configuration
        self.connection = None


    @handle_connection
    def connect(self):
        url = self.configuration.construct_url()
        print "Connecting to Server..."
        self.connection = xmlrpclib.ServerProxy(url)
        # Here we make a call to ensure the connection has been made.
        self.connection.system.listMethods()
        print "Connection Successful."


    @handle_connection
    def get_job_status(self, job_id):
        return self.connection.scheduler.job_status(job_id)


    @handle_connection
    def get_job_details(self, job_id):
        return self.connection.scheduler.job_details(job_id)


    @handle_connection
    def get_job_output(self, job_id):
        return self.connection.scheduler.job_output(job_id)


class LavaRunJob(object):
    def __init__(self, connection, job_id, poll_interval):
        self.END_STATES = ['Complete', 'Incomplete', 'Canceled']
        self.job_id = job_id
        self.connection = connection
        self.poll_interval = poll_interval or 2
        self.output = ""
        self.state = dict()
        self.details = dict()
        self.raw_details = dict()
        self.actions = list()
        self.last_poll_time = None
        self.next_poll_time = datetime.datetime.now()
        self._is_running = True


    def get_description(self):
        self._get_state()
        return self.details.get('description', '')


    def get_hostname(self):
        self._get_state()
        return self.details.get('hostname', '')


    def get_device_type_id(self):
        self._get_state()
        return self.details.get('device_type_id', '')


    def get_output(self):
        self._get_state()
        return self.output


    def is_running(self):
        self._get_state()
        return self._is_running


    def last_action(self):
        if not self.actions:
            return "-"
        return self.actions[-1]


    def all_actions(self):
        return self.actions


    def connect(self):
        self.connection.connect()


    def _get_state(self):
        if self._is_running and datetime.datetime.now() > self.next_poll_time:
            self.state = self.connection.get_job_status(self.job_id)
            self.raw_details = self.connection.get_job_details(self.job_id)
            self.output = self.connection.get_job_output(self.job_id)

            self.last_poll_time = self.next_poll_time
            self.next_poll_time = self.last_poll_time + datetime.timedelta(seconds=self.poll_interval)

            if not self.output:
                self.output = ""
            else:
                self.output = str(self.output)

            self._parse_output()
            self._parse_details()

            self._is_running = self.state['job_status'] not in self.END_STATES


    def _parse_details(self):
        description = self.raw_details.get('description', None)
        if description:
            self.details['description'] = description

        device_cache = self.raw_details.get('_actual_device_cache', None)
        if device_cache:
            hostname = device_cache.get('hostname', None)
            if hostname:
                self.details['hostname'] = hostname

            device_type_id = device_cache.get('device_type_id', None)
            if device_type_id:
                self.details['device_type_id'] = device_type_id


    def _parse_output(self):
        del self.actions[:]
        for line in self.output.splitlines():
            if 'ACTION-B' in line:
                self.actions.append(self._parse_actions(line))


    def _parse_actions(self, line):
        substr = line[line.find('ACTION-B')+len('ACTION-B')+2:]
        if substr.startswith('deploy_linaro_'):
            deployment_elems = list()
            re_elems = re.compile('u\'[a-z]+\'')
            for elem in re_elems.findall(substr):
                deployment_elems.append(elem[2:-1])
            return "deploy " + ','.join(deployment_elems)
        elif substr.startswith('lava_test_shell'):
            substr = substr[substr.find('testdef\': u')+len('testdef\': u')+1:]
            substr = substr[:substr.find('.yaml')]
            return "test_shell " + substr

        return "unknown (%s)" % substr[:substr.find(' ')]


def get_config(args):
    config = Config()
    config.add_config_override(FileConfigParser(filename=args.get('config', None), section=args.get('section', None)))
    config.add_config_override(ArgumentParser(args))
    return config

def main(args):
    config = get_config(args)
    lava_connection = LavaConnection(config)

    lava_job = LavaRunJob(lava_connection,
                          config.get_config_variable('job'),
                          2)
    lava_job.connect()

    if args["curses"]:
        output_handler = CursesOutput(lava_job)
    else:
        output_handler = FileOutputHandler(sys.stdout, lava_job)

    output_handler.run()

    exit(0)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration for the LAVA server")
    parser.add_argument("--section", help="section in the LAVA config file")
    parser.add_argument("--username", help="username for the LAVA server")
    parser.add_argument("--token", help="token for LAVA server api")
    parser.add_argument("--server", help="server url for LAVA server")
    parser.add_argument("--job", help="job to fetch console log from")
    parser.add_argument("--curses", help="use curses for output", action="store_true")
    args = vars(parser.parse_args())
    main(args)

# vim: set sw=4 sts=4 et fileencoding=utf-8 :