Source

hydra / hydra / daemons.py

  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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Alexander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#

"""Mini Flask-like framework to build CouchDB External and OSDaemon processes
with CouchDB-hosted configuration::

    from time import time
    from hydra.apps import External

    app = External(__name__)

    @app.route('/', method='GET')
    def dump_req(req):
        return req

    if __name__ == '__main__':
        app.run()

"""

import argparse
import os
import logging
import logging.config
import sys
from couchdb import ResourceNotFound
from ConfigParser import SafeConfigParser
from getpass import getpass
from itertools import izip_longest
from . import json
from .lib.mime import best_match
from .client import Server, Document
from .version import __version__


DEFAULT_CONFIG = {
    'app': {},
    'couchdb': {
        'main': {
            'dbs': {},
            'password': None,
            'url': 'http://localhost:5984',
            'username': None
        }
    },
    'logging': {
        'formatters': {
            'debug': {
                'format': '''
--------------------------------------------------------------------------------
[%(asctime)s] [%(name)s] [%(processName)s::%(threadName)s] [%(levelname)s]
Module: %(module)s (at %(path)s)
Function: %(funcName)s (at %(lineno)s)

%(message)s'''.strip()
            },
            'default': {
                'format': '''
--------------------------------------------------------------------------------
[%(asctime)s] [%(name)s] [%(processName)s::%(threadName)s] [%(levelname)s]
%(message)s
'''.strip()
            }
        },
        'handlers': {
            'console': {
                'active': False,
                'class': 'logging.StreamHandler',
                'formatter': 'default'
            },
            'email': {
                'active': False,
                'class': 'logging.handlers.SMTPHandler',
                'fromaddr': None,
                'level': 'ERROR',
                'mailhost': 'localhost',
                'subject': 'Daemon reports about error',
                'toaddrs': None
            },
            'file': {
                'active': False,
                'class': 'logging.handlers.TimedRotatingFileHandler',
                'backupCount': 7,
                'filename': '',
                'formatter': 'default',
                'when': 'midnight'
            }
        },
        'loggers': {
            '__self__': {
                'handlers': [],
                'level': 'DEBUG'}
        },
        'root': {
            'handlers': [],
            'level': 'DEBUG'
        },
        'version': 1
    }
}


class CouchConfig(Document):

    def bind(self, db, docid):
        self._db = db
        self._docid = docid

    def reload(self, db=None, docid=None):
        if db is None:
            db = self._db
        if docid is None:
            docid = self._docid

        try:
            status, headers, data = db.resource.head(docid)
        except ResourceNotFound:
            self.update(DEFAULT_CONFIG)
            self['_id'] = docid
            self.store(db)
            return True

        if not self or '_rev' not in self:
            self.update(**db[docid])
            return True
        elif self['_rev'] != headers['etag'].strip('"'):
            data = db[docid]
            self.clear()
            self.update(**data)
            return True
        return False

    def store(self, db=None):
        if db is None:
            db = self._db
        db.save(self)


class CouchDBConfigLoader(object):

    connection_params = {
        'server': 'http://localhost:5984',
        'dbname': 'apps',
        'username': None,
        'password': None,
        'docid': None
    }

    def __init__(self, config_cls):
        self.config_cls = config_cls

    def load(self, server, dbname, username, password, docid, defaults=None):
        if defaults is None:
            defaults = {}
        srv = Server(server)
        if all((username, password)):
            srv.resource.credentials = (username, password)
        db = srv[dbname]
        config = self.config_cls(**defaults)
        config.bind(db, docid)
        config.reload()
        return config

    def load_from_cfg(self, path, section, common='common', defaults=None):
        data = self.connection_params
        cfg = SafeConfigParser(self.connection_params)
        cfg.read(path)
        for name in filter(None, [common, section]):
            if cfg.has_section(name):
                data.update(cfg.items(name))
        if not data['docid']:
            data['docid'] = section
        data['defaults'] = defaults
        return self.load(**data)


class Process(object):

    config_loader = CouchDBConfigLoader(CouchConfig)
    main_func = None
    version = __version__

    def __init__(self, name):
        self.realname = os.path.basename(sys.argv[0])
        self.name = self.realname.split('.')[0] if name == '__main__' else name

        self.config = {}
        self.args = None

        self.log = logging.getLogger(self.name)
        self.log.addHandler(logging.NullHandler())

        self.argparser = argparse.ArgumentParser(self.realname)
        self.subargparser = self.argparser.add_subparsers(
            title='commands',
            dest='command')
        self.prepare()

    def prepare(self):
        self.prepare_argparser()

    def prepare_argparser(self):
        self.argparser.add_argument(
            '--version',
            action='version',
            version='%(prog)s ' + __version__)
        parser = self.subargparser.add_parser('run', help='Runs process')
        parser.add_argument(
            '-c',
            dest='config',
            default=os.path.join(os.path.dirname(sys.argv[0]), 'config.ini'),
            help='Define config file with CouchDB credentials.')

    def setup_config(self):
        if self.args and 'config' in self.args:
            self.config = self.config_loader.load_from_cfg(
                self.args.config, self.name, defaults=self.config)

    def setup(self):
        if not sys.argv[1:]:
            sys.argv[1:] = ['run', '-c',
                            os.path.join(os.path.dirname(sys.argv[0]),
                                         'config.ini')]
        if sys.argv[1].startswith('-') and sys.argv[1] != '--help':
            sys.argv.insert(1, 'run')
        self.args, unknown = self.argparser.parse_known_args()
        self.setup_config()
        self.setup_logging()

    def setup_logging(self):
        if 'logging' not in self.config:
            return
        config = self.config['logging']
        if '__self__' in config['loggers']:
            config['loggers'][self.name] = config['loggers'].pop('__self__')
        for name, conf in list(config['handlers'].items()):
            active = conf.pop('active', False)
            if not active:
                config['handlers'].pop(name)
        logging.config.dictConfig(config)

    def main(self, func):
        self.main_func = func

    def run(self):
        self.setup()
        self.start()

    def start(self):
        self.main_func()


class RuleMatchException(Exception):
    pass


class MethodNotAllowed(RuleMatchException):
    pass


class PathNotFound(RuleMatchException):
    pass


class NotAcceptable(RuleMatchException):
    pass


class Rule(object):

    def __init__(self, endpoint, methods, path, accepts):
        self.endpoint = endpoint
        self.methods = map(lambda i: i.upper(), methods)
        self.path = path
        self.accepts = accepts

    def match_content_type(self, req):
        ctype = req['headers'].get('Content-Type', 'application/json')
        match = best_match(self.accepts, ctype) is not None
        if not match:
            raise NotAcceptable('Not acceptable content type %s, '
                                'expected one of: %s' %
                                (ctype, ', '.join(self.accepts)))

    def match_method(self, req):
        if self.methods and req['method'] not in self.methods:
            raise MethodNotAllowed('Only %s allowed' % ', '.join(self.methods))

    def match_path(self, req):
        kwargs = {}
        path = self.path.strip('/').split('/')
        for rsection, msection in izip_longest(req['requested_path'], path):
            if msection is None:
                raise PathNotFound('missed')
            if msection.startswith(':'):
                kwargs[msection[1:]] = rsection
            elif rsection != msection:
                raise PathNotFound('missed')
        return kwargs

    def match(self, req):
        self.match_method(req)
        kwargs = self.match_path(req)
        if kwargs is None:
            return self
        kwargs = {'req': req}
        target_path = self.path.strip('/').split('/')
        for rpath, mpath in izip_longest(req['requested_path'], target_path):
            if mpath is None:
                return
            if mpath.startswith(':'):
                kwargs[mpath[1:]] = rpath
            elif rpath != mpath:
                return
        return self.endpoint, kwargs


class CouchdbProcess(Process):

    def __init__(self, *args, **kwargs):
        super(CouchdbProcess, self).__init__(*args, **kwargs)

    def get_registration_params(self):
        raise NotImplementedError('should return dict with three keys: '
                                  'section, key, value')

    def prepare_argparser(self):
        super(CouchdbProcess, self).prepare_argparser()
        parser = self.subargparser.add_parser(
            'register', help='Registers process in CouchDB')
        parser.add_argument(
            '-s', '--server',
            dest='server',
            default='http://localhost:5984',
            help='CouchDB server url.')
        parser.add_argument(
            '-u', '--username',
            dest='username',
            default=None,
            help='CouchDB username with administrator permissions.')

    def register(self, server=None, username=None, password=None):
        if server is None:
            server = self.args.server
        if username is None and self.args.username:
            username = self.args.username
        server = _get_server_instance(server, username, password)
        params = self.get_registration_params()
        for section, key, value in params:
            resource = server.resource('_config', section, key)
            resource.put_json(body=json.encode(value))

    def receive(self):
        line = sys.stdin.readline()
        while line:
            yield json.decode(line)
            line = sys.stdin.readline()

    def response(self, obj):
        if obj is None:
            return
        obj = json.encode(obj) + '\n'
        if isinstance(obj, unicode):
            obj = obj.encode('utf-8')
        sys.stdout.write(obj)
        sys.stdout.flush()

    def start(self):
        if self.args.command == 'register':
            self.register()
        else:
            super(CouchdbProcess, self).start()


class OSDaemon(CouchdbProcess):

    def get_registration_params(self):
        return [['os_daemons', self.name, 'python %s' % sys.argv[0]]]


class External(CouchdbProcess):

    def __init__(self, *args, **kwargs):
        super(External, self).__init__(*args, **kwargs)
        self.rules = []
        self.mount_point = '/:dbname/_%s' % self.name

    def get_registration_params(self):
        name = self.name
        cmd = '%s %s' % (sys.executable, os.path.abspath(sys.argv[0]))
        return [
            ['external', name, cmd],
            ['httpd_db_handlers',
             '_%s' % name,
             '{couch_httpd_external, handle_external_req, <<"%s">>}' % name]
        ]

    def route(self, path, method=None, accept=None):
        def wrapper(func):
            self.add_route_rule(func, method, path, accept)
            return func
        return wrapper

    def main_func(self):
        for req in self.receive():
            if self.config.reload():
                self.setup()
            try:
                self.response(self.dispatch(req))
            except Exception as err:
                self.response(
                    self.make_error(500, type(err).__name__, str(err), {}))

    def add_route_rule(self, endpoint, method, path, accept):
        if method is None:
            method = []
        elif isinstance(method, basestring):
            method = [method]
        if accept is None:
            accept = []
        elif isinstance(accept, basestring):
            accept = [accept]
        rule = Rule(endpoint, method, self.mount_point + path, accept)
        self.rules.append(rule)

    def dispatch(self, req):
        errors = []
        for rule in self.rules:
            try:
                m = rule.match(req)
            except RuleMatchException as err:
                if isinstance(err, MethodNotAllowed):
                    code, name = 405, 'method_not_allowed'
                elif isinstance(err, PathNotFound):
                    code, name = 404, 'not_found'
                elif isinstance(err, NotAcceptable):
                    code, name = 406, 'not_acceptable'
                errors.append(self.make_error(code, name, str(err), {}))
                continue
            if m is not None:
                func, kwargs = m
                accepted_kwargs = dict(
                    (key, value)
                    for key, value in kwargs.items()
                    if key in func.func_code.co_varnames
                )
                return func(**accepted_kwargs)
        if errors:
            errors = sorted(errors, key=lambda e: e['code'])
            return errors[-1]
        else:
            return self.make_error(404, 'not_found', 'missed', {})

    def make_response(self, code, data, headers=None):
        headers = headers or {}
        if isinstance(data, basestring):
            return {'code': code, 'body': data, 'headers': headers}
        else:
            return {'code': code, 'json': data, 'headers': headers}

    def make_perm_redirect(self, location, reason, headers=None):
        headers = headers or {}
        headers['Location'] = location
        return self.make_response(301, reason, headers)

    def make_temp_redirect(self, location, reason, headers=None):
        headers = headers or {}
        headers['Location'] = location
        return self.make_response(307, reason, headers)

    def make_error(self, code, error, reason, headers=None):
        if code < 400:
            code = 500
        data = {'error': error, 'reason': reason}
        return self.make_response(code, data, headers)


def _get_server_instance(server, username=None, password=None):
    if isinstance(server, basestring):
        server = Server(server)
    if username is not None:
        if password is None:
            password = getpass('Enter password for %s: ' % username)
        credentials = (username, password)
    else:
        credentials = None
    if credentials:
        server.resource.credentials = credentials
    return server
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.