summaryrefslogtreecommitdiff
path: root/pygerrit/stream.py
blob: c786ad0c9961b22bea003e838a5976da2d4a156e (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
""" Gerrit event stream interface.

Class to listen to the Gerrit event stream and dispatch events.

"""

import json
from select import poll, POLLIN
from threading import Thread, Event

from pygerrit.ssh import GerritSSHClient
from pygerrit.error import GerritError
from pygerrit.events import GerritEvent, GerritEventFactory


@GerritEventFactory.register("gerrit-stream-error")
class GerritStreamErrorEvent(GerritEvent):

    """ Represents an error when handling the gerrit event stream """

    def __init__(self, json_data):
        super(GerritStreamErrorEvent, self).__init__()
        self.error = json_data["error"]


class GerritStream(Thread):

    """ Gerrit events stream handler. """

    def __init__(self, gerrit, host):
        Thread.__init__(self)
        self.daemon = True
        self._gerrit = gerrit
        self._host = host
        self._stop = Event()

    def stop(self):
        """ Stop the thread. """
        self._stop.set()

    def run(self):
        """ Listen to the stream and send events to the client. """
        try:
            client = GerritSSHClient(self._host)
            _stdin, stdout, _stderr = client.run_gerrit_command("stream-events")
            p = poll()
            p.register(stdout.channel)
            while not self._stop.is_set():
                data = p.poll()
                for (fd, event) in data:
                    if fd == stdout.channel.fileno():
                        if event == POLLIN:
                            line = stdout.readline()
                            json_data = json.loads(line)
                            self._gerrit.put_event(json_data)
        except GerritError, e:
            error = json.loads('{"type":"gerrit-stream-error",'
                               '"error":"%s"}' % str(e))
            self._gerrit.put_event(error)