summaryrefslogtreecommitdiff
path: root/ick2lib/apiservice.py
blob: e4cfe8adaa39c6e1105e7f662e9fbad529cde5b5 (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
# Copyright 2017  Lars Wirzenius
#
# This program 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-3+ =*=


import logging
import time


import bottle


import ick2lib


class ApiService(object):

    def __init__(self):
        self._projects = {}
        self._app = self._create_bottle_app()

    def _create_bottle_app(self):
        app = bottle.Bottle()

        routes = [
            {
                'method': 'GET',
                'path': '/',
                'callback': lambda: None,
            },
            {
                'method': 'GET',
                'path': '/version',
                'callback': lambda: { 'version': '1.0' },
            },
            {
                'method': 'GET',
                'path': '/projects',
                'callback': self._projects_cb,
            },
            {
                'method': 'GET',
                'path': '/projects/<project>/logs/current',
                'callback': self._current_log_cb,
            },
            {
                'method': 'GET',
                'path': '/projects/<project>/logs/previous',
                'callback': self._previous_log_cb,
            },
            {
                'method': 'GET',
                'path': '/projects/<project>/+trigger',
                'callback': self._trigger_cb,
            },
            {
                'method': 'GET',
                'path': '/worker/<worker>',
                'callback': self._work_cb,
            },
            {
                'method': 'POST',
                'path': '/worker/<worker>/snippet',
                'callback': self._snippet_cb,
            },
        ]

        for route in routes:
            app.route(**route)

        app.install(LoggingPlugin())
        return app

    def _projects_cb(self):
        return {
            'projects': list(sorted(self._projects.keys())),
        }

    def _current_log_cb(self, project):
        return self._projects[project].get_current_log()

    def _previous_log_cb(self, project):
        return self._projects[project].get_previous_log()

    def _trigger_cb(self, project):
        return self._projects[project].trigger_build()

    def _work_cb(self, worker):
        for p in self._projects.values():
            step = p.get_current_build_step()
            if step is not None:
                return {
                    'project': p.name,
                    'shell': step,
                }
        return None

    def _snippet_cb(self, worker):
        obj = bottle.request.json
        p = self._projects[obj['project']]
        logging.debug('stdout: %r', obj['stdout'])
        logging.debug('stderr: %r', obj['stderr'])
        p.append_to_current_log(obj['stdout'] + obj['stderr'])
        logging.debug('log is now: %r', p.get_current_log())
        if obj['exit-code'] is not None:
            p.finish_current_log()
            p.finish_current_build_step()

    def set_projects(self, projects):
        self._projects = projects

    def get_uwsgi_app(self):
        return self._app

    def run_debug(self, port):
        self._app.run(port=port, quiet=True)



class LoggingPlugin(object):

    def apply(self, callback, route):

        def wrapper(*args, **kwargs):
            # Do the thing and catch any exceptions.
            try:
                self.log_request()
                data = callback(*args, **kwargs)
                self.add_response_headers()
                self.log_response()
                return data
            except SystemExit:
                raise
            except BaseException as e:
                logging.error(str(e), exc_info=True)
                raise bottle.HTTPError(status=500, body=str(e))

        return wrapper

    def add_response_headers(self):
        rfc822 = time.strftime('%a, %d %b %Y %H:%M:%S %z')
        bottle.response.set_header('Date', rfc822)

    def log_request(self):
        r = bottle.request
        logging.info('Request: %s %s', r.method, r.path)

    def log_response(self):
        logging.info('Response: %s', bottle.response.status_code)