summaryrefslogtreecommitdiff
path: root/lorry-controller-webapp
blob: 27c637575860bb361abda2683e4b0ebcfb96136f (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
#!/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 logging
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>

    <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)')
        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()


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 Status(LorryControllerRoute):

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

    def run(self, **kwargs):
        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': self.statedb.get_running_queue(),
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
            }
        self.write_static_status_page(status)
        return status

    def write_static_status_page(self, status):
        with open(self.app_settings['status-html'], 'w') as f:
            f.write(STATUS_HTML_TEMPLATE.format(**status))


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(
            ['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.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']:
            WSGIServer(webapp).run()
        else:
            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()