summaryrefslogtreecommitdiff
path: root/lorry-controller-webapp
blob: 468f941a2341b478cbdbc6062a97beea537446de (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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
#!/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 contextlib
import errno
import glob
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>

        <style>
table {
    border: 1px solid black;
}

th, td {
    padding-right: 2em;
}

th {
    font-weight: bold;
    text-align: left;
}

td {
    font-family: monospace;
    border-top: 1px solid black;
    text-align: left;
}
        </style>

    </head>
    <body>
        % import json

        <h1>Status of Lorry Controller</h1>

        <p>Running jobs from run-queue: {{"yes" if running_queue else "no"}}.</p>

        <p>Free disk space: {{disk_free_gib}} GiB.</p>

        <h2>Currently running jobs</h2>

<table>
<tr>
<th>Job ID</th>
<th>path</th>
</tr>
% for spec in run_queue:
%    if spec['running_job'] is not None:
<tr>
<td>{{spec['running_job']}}</td>
<td>{{spec['path']}}</td>
</tr>
%    end
% end
</table>

        <h2>Run-queue</h2>

<table>
<tr>
<th>Pos</th>
<th>Path</th>
<th>URL</th>
<th>Interval</th>
<th>Due</th>
<th>Job</th>
</tr>
% for i, spec in enumerate(run_queue):
%   obj = json.loads(spec['text'])
%   name = obj.keys()[0]
%   fields = obj[name]
<tr>
<td>{{i+1}}</td>
<td>{{spec['path']}}</td>
<td>{{fields['url']}}</td>
<td>{{spec['interval']}}</td>
<td>{{spec['due_nice']}}</td>
<td>{{spec['running_job']}}</td>
</tr>
% end
</table>

        <hr />

        <p>Scotty says: {{quote}}</p>

        <p>Updated: {{timestamp}}</p>

    </body>
</html>
'''


class LorryNotFoundError(Exception):

    def __init__(self, path):
        Exception.__init__(
            self, 'Lorry with path %r not found in STATEDB' % path)


class WrongNumberLorriesRunningJob(Exception):

    def __init__(self, job_id, row_count):
        Exception.__init__(
            self, 'STATEDB has %d Lorry specs running jobs %r, should be 1' %
            (row_count, job_id))


class StateDB(object):

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

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

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

    def _initialise_tables(self):
        logging.debug('Initialising tables (if necessary) in database')
        c = self._conn.cursor()
        c.execute('BEGIN TRANSACTION')

        # Table for holding the "are we scheduling jobs" value.
        c.execute('CREATE TABLE IF NOT EXISTS running_queue (running INT)')
        c.execute('INSERT INTO running_queue VALUES (0)')

        # Table for all the known lorries (the "run queue").

        self.lorries_fields = [
            ('path', 'TEXT PRIMARY KEY'),
            ('text', 'TEXT'),
            ('generated', 'INT'),
            ('running_job', 'INT'),
            ('kill_job', 'INT'),
            ('due', 'INT'),
            ('interval', 'INT'),
            ]
        self.lorries_booleans = [
            'kill_job',
            ]

        fields_sql = ', '.join(
            '%s %s' % (name, info) for name, info in self.lorries_fields
            )

        c.execute(
            'CREATE TABLE IF NOT EXISTS lorries (%s)' % fields_sql)

        # Table for the next available job id.
        c.execute('CREATE TABLE IF NOT EXISTS next_job_id (job_id INT)')
        c.execute('INSERT INTO next_job_id VALUES (1)')

        # Done.
        self._conn.commit()

    @property
    def in_transaction(self):
        return self._transaction_cursor is not None

    @contextlib.contextmanager
    def transaction(self):
        assert not self.in_transaction
        self._open()
        self._transaction_cursor = self._conn.cursor()
        self._transaction_cursor.execute('BEGIN TRANSACTION')
        yield
        self._conn.commit()
        self._transaction_cursor = None

    def get_cursor(self):
        '''Return transaction cursor, or a new one.'''
        if self._transaction_cursor is None:
            self._open()
            return self._conn.cursor()
        else:
            return self._transaction_cursor

    def get_running_queue(self):
        logging.debug('StateDB.get_running_queue called')
        c = self.get_cursor()
        for (running,) in c.execute('SELECT running FROM running_queue'):
            return bool(running)

    def set_running_queue(self, new_status):
        logging.debug('StateDB.set_running_queue(%r) called', new_status)
        assert self.in_transaction
        if new_status:
            new_value = 1
        else:
            new_value = 0
        self.get_cursor().execute(
            'UPDATE running_queue SET running = ?', str(new_value))

    def make_lorry_info_from_row(self, row):
        result = dict((t[0], row[i]) for i, t in enumerate(self.lorries_fields))
        for field in self.lorries_booleans:
            result[field] = bool(result[field])
        return result

    def get_lorry_info(self, path):
        logging.debug('StateDB.get_lorry_info(path=%r) called', path)
        c = self.get_cursor()
        c.execute('SELECT * FROM lorries WHERE path IS ?', (path,))
        row = c.fetchone()
        if row is None:
            raise LorryNotFoundError(path)
        return self.make_lorry_info_from_row(row)

    def get_all_lorries_info(self):
        logging.debug('StateDB.get_all_lorries_info called')
        c = self.get_cursor()
        c.execute('SELECT * FROM lorries ORDER BY due')
        return [self.make_lorry_info_from_row(row) for row in c.fetchall()]

    def get_lorries_paths(self):
        logging.debug('StateDB.get_lorries_paths called')
        c = self.get_cursor()
        return [
            row[0]
            for row in c.execute('SELECT path FROM lorries ORDER BY due')]

    def add_to_lorries(self, path=None, text=None, generated=None, due=None,
                       interval=None):
        logging.debug(
            'StateDB.add_to_lorries('
            'path=%r, text=%r, generated=%r, due=%r, interval=%s called',
            path,
            text,
            generated,
            due,
            interval)

        assert path is not None
        assert text is not None
        assert generated is not None
        assert due is not None
        assert interval is not None
        assert self.in_transaction

        c = self.get_cursor()
        c.execute(
            'INSERT OR REPLACE INTO lorries '
            '(path, text, generated, due, interval, running_job, kilL_job) '
            'VALUES (?, ?, ?, ?, ?, ?, ?)',
            (path, text, generated, due, interval, None, 0))

    def remove_lorry(self, path):
        logging.debug('StateDB.remove_lorry(%r) called', path)
        assert self.in_transaction
        c = self.get_cursor()
        c.execute('DELETE FROM lorries WHERE path IS ?', (path,))

    def set_running_job(self, path, job_id):
        logging.debug(
            'StateDB.set_running_job(%r, %r) called', path, job_id)
        assert self.in_transaction
        c = self.get_cursor()
        c.execute(
            'UPDATE lorries SET running_job=? WHERE path=?',
            (job_id, path))

    def find_lorry_running_job(self, job_id):
        logging.debug('StateDB.find_path_running_job(%r) called', job_id)
        c = self.get_cursor()
        c.execute(
            'SELECT path FROM lorries WHERE running_job IS ?',
            (job_id,))
        rows = c.fetchall()
        if len(rows) != 1:
            raise WrongNumberLorriesRunningJob(job_id, len(rows))
        return rows[0][0]

    def get_running_jobs(self):
        logging.debug('StateDB.get_running_jobs() called')
        c = self.get_cursor()
        c.execute(
            'SELECT running_job FROM lorries WHERE running_job IS NOT NULL')
        return [row[0] for row in c.fetchall()]

    def set_kill_job(self, path, value):
        logging.debug('StateDB.set_kill_job(%r, %r) called', path, value)
        assert self.in_transaction
        if value:
            value = 1
        else:
            value = 0
        c = self.get_cursor()
        c.execute(
            'UPDATE lorries SET kill_job=? WHERE path=?',
            (value, path))

    def get_next_job_id(self):
        logging.debug('StateDB.get_next_job_id called')
        assert self.in_transaction
        c = self.get_cursor()
        c.execute('SELECT job_id FROM next_job_id')
        row = c.fetchone()
        job_id = row[0]
        c.execute('UPDATE next_job_id SET job_id=?', (job_id + 1,))
        return job_id


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 UTC', time.gmtime()),
            'run_queue': self.get_run_queue(statedb),
            }
        status.update(self.get_free_disk_space(work_directory))
        return status

    def render_status_as_html(self, status):
        return bottle.template(STATUS_HTML_TEMPLATE, **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**3,
            }

    def get_run_queue(self, statedb):
        lorries = statedb.get_all_lorries_info()
        now = time.time()
        for lorry in lorries:
            exact = time.strftime(
                '%Y-%m-%d %H:%M:%S UTC',
                time.gmtime(lorry['due']))
            nice = self.format_secs_nicely(lorry['due'] - now)
            lorry['due_nice'] = '%s (%s)' % (exact, nice)
        return lorries

    def format_secs_nicely(self, secs):
        if secs <= 0:
            return 'now'

        result = []

        hours = secs / 3600
        if hours > 0:
            result.append('%d hours' % hours)
            secs %= 3600
            
        mins = secs / 60
        if mins > 0 or hours > 0:
            result.append('%d mins' % mins)
            secs %= 60
                
        result.append('%d secs' % secs)

        return ' '.join(result)


class Status(LorryControllerRoute):

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

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)
        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):
        logging.debug('%s %s called', self.http_method, self.path)
        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):
        logging.debug('%s %s called', self.http_method, self.path)

        # FIXME: This doesn't update the git repo from upstream, yet.

        conf_obj = self.read_config_file()

        with self.statedb.transaction():
            existing = set(self.statedb.get_lorries_paths())
            logging.debug('existing at beginning: %r', existing)

            for section in conf_obj:
                if section['type'] == 'lorries':
                    added = self.add_matching_lorries_to_statedb(section)
                    logging.debug('added: %r', added)
                    existing = existing.difference(added)

            logging.debug('existing at end: %r', existing)
            for path in existing:
                self.statedb.remove_lorry(path)

            return 'Configuration has been updated.'

    @property
    def config_file_name(self):
        return os.path.join(
            self.app_settings['configuration-directory'],
            'lorry-controller.conf')

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

        filename = self.config_file_name
        logging.debug(
            '%s %s: reading config file %s',
            self.http_method, self.path, filename)

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

    def add_matching_lorries_to_statedb(self, section):
        added_paths = set()

        filenames = self.find_lorry_files_for_section(section)
        for filename in filenames:
            for lorry_spec in self.get_lorry_specs(filename):
                path = self.deduce_repo_path(section, lorry_spec)
                text = self.serialise_lorry_spec(lorry_spec)
                due = 0
                interval = section['interval']
                logging.debug(
                    '%s %s: adding lorry spec %r: %r',
                    self.http_method, self.path, path, text)
                self.statedb.add_to_lorries(
                    path=path, text=text, generated=0, 
                    due=due, interval=interval)
                added_paths.add(path)

        return added_paths

    def find_lorry_files_for_section(self, section):
        result = []
        dirname = os.path.dirname(self.config_file_name)
        for base_pattern in section['globs']:
            pattern = os.path.join(dirname, base_pattern)
            result.extend(glob.glob(pattern))
        return result
    
    def get_lorry_specs(self, filename):
        logging.debug(
            '%s %s: reading Lorry specs from %s',
            self.http_method, self.path, filename)

        with open(filename) as f:
            obj = json.load(f)
        return obj.items()

    def deduce_repo_path(self, section, lorry_spec):
        base_path, details = lorry_spec
        return '%s/%s' % (section['prefix'], base_path)

    def serialise_lorry_spec(self, lorry_spec):
        key, details = lorry_spec
        obj = { key: details }
        return json.dumps(obj)


class ListQueue(LorryControllerRoute):

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

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)
        return {
            'queue':
                [spec['path'] for spec in self.statedb.get_all_lorries_info()],
            }


class ShowLorry(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/lorry/<path:path>'

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)
        try:
            return self.statedb.get_lorry_info(kwargs['path'])
        except LorryNotFoundError as e:
            bottle.abort(404, str(e))


class StartQueue(LorryControllerRoute):

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

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)
        with self.statedb.transaction():
            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):
        logging.debug('%s %s called', self.http_method, self.path)
        with self.statedb.transaction():
            self.statedb.set_running_queue(0)
        return 'Queue set to not run'


class GiveMeJob(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/give-me-job'

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)
        with self.statedb.transaction():
            lorry_infos = self.statedb.get_all_lorries_info()
            for lorry_info in lorry_infos:
                if lorry_info['running_job'] is None:
                    path = lorry_info['path']
                    running_job = self.statedb.get_next_job_id()
                    self.statedb.set_running_job(path, running_job)
                    return {
                        'job_id':  running_job,
                        'path': path,
                        }
        return { 'job_id': None }


class JobUpdate(LorryControllerRoute):

    http_method = 'POST'
    path = '/1.0/job-update'

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)

        job_id = bottle.request.forms.job_id
        exit = bottle.request.forms.exit

        logging.debug('form job_id: %r', job_id)
        logging.debug('form exit: %r', exit)

        if exit is not None and exit != 'no':
            with self.statedb.transaction():
                path = self.statedb.find_lorry_running_job(job_id)
                self.statedb.set_running_job(path, None)
                return self.statedb.get_lorry_info(path)
        else:
            path = self.statedb.find_lorry_running_job(job_id)
            return self.statedb.get_lorry_info(path)


class ListRunningJobs(LorryControllerRoute):

    http_method = 'GET'
    path = '/1.0/list-running-jobs'

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)

        job_ids = self.statedb.get_running_jobs()
        return {
            'running_jobs': job_ids,
            }


class StopJob(LorryControllerRoute):

    http_method = 'POST'
    path = '/1.0/stop-job'

    def run(self, **kwargs):
        logging.debug('%s %s called', self.http_method, self.path)
        with self.statedb.transaction():
            job_id = bottle.request.forms.job_id
            path = self.statedb.find_lorry_running_job(job_id)
            self.statedb.set_kill_job(path, True)
        return self.statedb.get_lorry_info(path)


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