summaryrefslogtreecommitdiff
path: root/lorry-controller-webapp
blob: 6a3b0e25e39388a6aac8dac737ddca907ae4e653 (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
#!/usr/bin/env python
#
# Copyright (C) 2014  Codethink Limited
#
# 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; version 2 of the License.
#
# 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.


import errno
import logging
import json
import os
import sqlite3
import time
import wsgiref.simple_server

import bottle
import cliapp
from flup.server.fcgi import WSGIServer


STATUS_HTML_TEMPLATE = '''
<!DOCTYPE HTML>
<html>
 <head>
  <title>Lorry Controller status</title>
 </head>
 <body>
    <blockquote>{quote}</blockquote>

    <h1>Status of Lorry Controller</h1>

    <p>Running queue: {running-queue}.</p>
    <p>Free disk space: {disk-free-gib} GiB.</p>

    <hr>

    <p>Updated: {timestamp}</p>
 </body>
</html>
'''


class StateDB(object):

    '''A wrapper around raw Sqlite for STATEDB.'''

    def __init__(self, filename):
        self._filename = filename
        self._conn = None

    def _open(self):
        if self._conn is None:
            self._conn = sqlite3.connect(self._filename)
            self._initialise_tables()

    def _initialise_tables(self):
        c = self._conn.cursor()
        c.execute('BEGIN TRANSACTION')

        c.execute('CREATE TABLE IF NOT EXISTS running_queue (running INT)')
        c.execute('INSERT INTO running_queue VALUES (0)')

        c.execute('CREATE TABLE IF NOT EXISTS lorries (path TEXT, text TEXT, generated INT)')

        self._conn.commit()

    def get_running_queue(self):
        self._open()
        c = self._conn.cursor()
        for (running,) in c.execute('SELECT running FROM running_queue'):
            return bool(running)

    def set_running_queue(self, new_status):
        if new_status:
            new_value = 1
        else:
            new_value = 0
        self._open()
        c = self._conn.cursor()
        c.execute('UPDATE running_queue SET running = ?', str(new_value))
        self._conn.commit()

    def get_lorries(self):
        self._open()
        c = self._conn.cursor()
        return c.execute('SELECT * FROM lorries')


class LorryControllerRoute(object):

    '''Base class for Lorry Controller HTTP API routes.

    A route is an HTTP request that the Bottle web application
    recognises as satisfied by a particular callback. To make it
    easier to implement them and get them added automagically to a
    Bottle instance, we define the callbacks as subclasses of this
    base class.

    Subclasses MUST define the attributes ``http_method`` and
    ``path``, which are given the bottle.Bottle.route method as the
    arguments ``method`` and ``path``, respectively.

    '''

    def __init__(self, app_settings, statedb):
        self.app_settings = app_settings
        self.statedb = statedb

    def run(self, **kwargs):
        raise NotImplementedError()


class StatusRenderer(object):

    '''Helper class for rendering service status as JSON/HTML'''

    def get_status_as_dict(self, statedb, work_directory):
        quotes = [
            "Never get drunk unless you're willing to pay for it - "
            "the next day.",
            "I'm giving her all she's got, Captain!",
            ]
        import random
        status = {
            'quote': '%s' % random.choice(quotes),
            'running-queue': statedb.get_running_queue(),
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
            }
        status.update(self.get_free_disk_space(work_directory))
        return status

    def render_status_as_html(self, status):
        return STATUS_HTML_TEMPLATE.format(**status)

    def write_status_as_html(self, status, filename):
        html = self.render_status_as_html(status)
        with open(filename, 'w') as f:
            f.write(html)

    def get_free_disk_space(self, dirname):
        result = os.statvfs(dirname)
        free_bytes = result.f_bavail * result.f_bsize
        return {
            'disk-free': free_bytes,
            'disk-free-mib': free_bytes / 1024**2,
            'disk-free-gib': free_bytes / 1024**2,
            }


class Status(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/status'

    def run(self, **kwargs):
        renderer = StatusRenderer()
        status = renderer.get_status_as_dict(self.statedb, self.app_settings['statedb'])
        renderer.write_status_as_html(status, self.app_settings['status-html'])
        return status


class StatusHTML(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/status-html'

    def run(self, **kwargs):
        renderer = StatusRenderer()
        status = renderer.get_status_as_dict(self.statedb, self.app_settings['statedb'])
        renderer.write_status_as_html(status, self.app_settings['status-html'])
        return renderer.render_status_as_html(status)


class ReadConfiguration(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/read-configuration'

    def run(self, **kwargs):
        # FIXME: This doesn't update the git repo from upstream, yet.

        conf_obj = self.read_config_file()
        troves = [x for x in conf_obj if x['type'] == 'trove']
        lorries = [x for x in conf_obj if x['type'] == 'lorries']

        # FIXME: put the troves and the lorries into STATEDB, but
        # don't generate lorries from troves, yet. Don't, in fact,
        # scan for local lorries either, yet. Just make sure STATEDB
        # has the right tables and columns so that /1.0/list-queue
        # will return something reasonable-looking.
        return { 'troves': troves, 'lorries': lorries }

    def read_config_file(self):
        '''Read the configuration file, return as Python object.'''

        filename = os.path.join(
            self.app_settings['configuration-directory'],
            'lorry-controller.conf')
        try:
            with open(filename) as f:
                return json.load(f)
        except IOError as e:
            if e.errno == errno.ENOENT:
                # File doesn't exist. Return an empty configuration.
                return []
            bottle.abort(500, 'Error reading %s: %s' % (filename, e))


class ListQueue(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/list-queue'

    def run(self, **kwargs):
        return {
            'queue': [row.path for row in self.statedb.get_lorries()],
            }


class StartQueue(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/start-queue'

    def run(self, **kwargs):
        self.statedb.set_running_queue(1)
        return 'Queue set to run'


class StopQueue(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/stop-queue'

    def run(self, **kwargs):
        self.statedb.set_running_queue(0)
        return 'Queue set to not run'


class WEBAPP(cliapp.Application):

    def add_settings(self):
        self.settings.string(
            ['statedb'],
            'use FILE as the state database',
            metavar='FILE')

        self.settings.string(
            ['configuration-directory'],
            'use DIR as the configuration directory',
            metavar='DIR',
            default='.')

        self.settings.string(
            ['status-html'],
            'write a static HTML page to FILE to describe overall status',
            metavar='FILE',
            default='/dev/null')

        self.settings.boolean(
            ['wsgi'],
            'run in wsgi mode (default is debug mode, for development)')

        self.settings.integer(
            ['debug-port'],
            'use PORT in debugging mode '
            '(i.e., when not running under WSGI); '
            'note that using this to non-zero disables --debug-port-file',
            metavar='PORT',
            default=0)

        self.settings.string(
            ['debug-port-file'],
            'write listening port to FILE when in debug mode '
            '(i.e., not running under WSGI)',
            metavar='FILE',
            default='webapp.port')

        self.settings.string(
            ['debug-host'],
            'listen on HOST when in debug mode (i.e., not running under WSGI)',
            metavar='HOST',
            default='0.0.0.0')

    def find_routes(self):
        '''Return all classes that are API routes.

        This is a generator.

        '''

        # This is a bit tricky and magic. globals() returns a dict
        # that contains all objects in the global namespace. We
        # iterate over the objects and pick the ones that are
        # subclasses of our superclass (no duck typing here), but ARE
        # NOT the superclass itself.

        for x in globals().values():
            is_route = (
                type(x) == type and # it must be class, for issubclass
                issubclass(x, LorryControllerRoute) and
                x != LorryControllerRoute)
            if is_route:
                yield x

    def process_args(self, args):
        self.settings.require('statedb')
        statedb = StateDB(self.settings['statedb'])

        webapp = bottle.Bottle()

        for route_class in self.find_routes():
            route = route_class(self.settings, statedb)
            webapp.route(
                path=route.path,
                method=route.http_method,
                callback=route.run)

        logging.info('Starting server')
        if self.settings['wsgi']:
            self.run_wsgi_server(webapp)
        else:
            self.run_debug_server(webapp)

    def run_wsgi_server(self, webapp):
        WSGIServer(webapp).run()

    def run_debug_server(self, webapp):
        if self.settings['debug-port']:
            self.run_debug_server_on_given_port(webapp)
        else:
            self.run_debug_server_on_random_port(webapp)

    def run_debug_server_on_given_port(self, webapp):
        bottle.run(
            webapp,
            host=self.settings['debug-host'],
            port=self.settings['debug-port'],
            quiet=True,
            debug=True)

    def run_debug_server_on_random_port(self, webapp):
        server_port_file = self.settings['debug-port-file']

        class DebugServer(wsgiref.simple_server.WSGIServer):
            '''WSGI-like server that uses an ephemeral port.
            
            Rather than use a specified port, or default, the
            DebugServer connects to an ephemeral port and writes
            its number to debug-port-file, so a non-racy temporary
            port can be used.
            
            '''
            
            def __init__(self, (host, port), *args, **kwargs):
                wsgiref.simple_server.WSGIServer.__init__(
                    self, (host, 0), *args, **kwargs)
                with open(server_port_file, 'w') as f:
                    f.write(str(self.server_port) + '\n')

        bottle.run(
            webapp,
            host=self.settings['debug-host'],
            server_class=DebugServer,
            quiet=True,
            debug=True)

WEBAPP().run()