Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | # -*- mode: python-mode; py-indent-tabs-mode: nil -*- |
| 3 | """ |
| 4 | /* |
| 5 | * Copyright (C) 2018 sysmocom s.f.m.c. GmbH |
| 6 | * |
| 7 | * All Rights Reserved |
| 8 | * |
| 9 | * This program is free software; you can redistribute it and/or modify |
| 10 | * it under the terms of the GNU General Public License as published by |
| 11 | * the Free Software Foundation; either version 3 of the License, or |
| 12 | * (at your option) any later version. |
| 13 | * |
| 14 | * This program is distributed in the hope that it will be useful, |
| 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 | * GNU General Public License for more details. |
| 18 | * |
| 19 | * You should have received a copy of the GNU General Public License along |
| 20 | * with this program; if not, write to the Free Software Foundation, Inc., |
| 21 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 22 | */ |
| 23 | """ |
| 24 | |
Max | 5530d7c | 2018-12-21 17:48:20 +0100 | [diff] [blame^] | 25 | __version__ = "0.1.0" # bump this on every non-trivial change |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 26 | |
Max | 4e95b8f | 2018-12-05 17:58:40 +0100 | [diff] [blame] | 27 | import argparse, os, logging, logging.handlers, datetime |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 28 | import hashlib |
| 29 | import json |
| 30 | import configparser |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 31 | from functools import partial |
Max | 66441e7 | 2018-12-21 18:42:30 +0100 | [diff] [blame] | 32 | from distutils.version import StrictVersion as V |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 33 | from twisted.internet import defer, reactor |
| 34 | from treq import post, collect |
| 35 | from osmopy.trap_helper import debug_init, get_type, get_r, p_h, make_params, comm_proc |
| 36 | from osmopy.twisted_ipa import CTRL, IPAFactory, __version__ as twisted_ipa_version |
| 37 | from osmopy.osmo_ipa import Ctrl |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 38 | |
| 39 | # we don't support older versions of TwistedIPA module |
| 40 | assert V(twisted_ipa_version) > V('0.4') |
| 41 | |
Max | c450237 | 2018-12-21 13:36:36 +0100 | [diff] [blame] | 42 | def log_duration(log, bid, ts, ts_http): |
| 43 | """ |
| 44 | Log human-readable duration from timestamps |
| 45 | """ |
| 46 | base = datetime.datetime.now() |
| 47 | delta_t = datetime.timedelta(seconds = (base - ts).total_seconds()) |
| 48 | delta_h = datetime.timedelta(seconds = (base - ts_http).total_seconds()) |
| 49 | delta_w = delta_t - delta_h |
| 50 | log.debug('Request for BSC %s took %s total (%s wait, %s http)' % (bid, delta_t, delta_w, delta_h)) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 51 | |
Max | c450237 | 2018-12-21 13:36:36 +0100 | [diff] [blame] | 52 | def handle_reply(ts, ts_http, bid, f, log, resp): |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 53 | """ |
| 54 | Reply handler: process raw CGI server response, function f to run for each command |
| 55 | """ |
Max | ec3944e | 2018-11-27 17:43:45 +0100 | [diff] [blame] | 56 | decoded = json.loads(resp.decode('utf-8')) |
Max | c450237 | 2018-12-21 13:36:36 +0100 | [diff] [blame] | 57 | log_duration(log, bid, ts, ts_http) |
Max | 7f0f786 | 2018-12-05 17:49:36 +0100 | [diff] [blame] | 58 | comm_proc(decoded.get('commands'), bid, f, log) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 59 | |
| 60 | def gen_hash(params, skey): |
Max | 66441e7 | 2018-12-21 18:42:30 +0100 | [diff] [blame] | 61 | """ |
| 62 | Make mandatory parameter for http request |
| 63 | """ |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 64 | inp = '' |
| 65 | for key in ['time_stamp', 'position_validity', 'admin_status', 'policy_status']: |
| 66 | inp += str(params.get(key)) |
| 67 | inp += skey |
| 68 | for key in ['bsc_id', 'lat', 'lon', 'position_validity']: |
| 69 | inp += str(params.get(key)) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 70 | m = hashlib.md5() |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 71 | m.update(inp.encode('utf-8')) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 72 | res = m.hexdigest() |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 73 | return res |
| 74 | |
Max | 0028ce1 | 2018-12-05 18:07:04 +0100 | [diff] [blame] | 75 | def make_async_req(ts, dst, par, f_write, f_log, tout): |
Max | 66441e7 | 2018-12-21 18:42:30 +0100 | [diff] [blame] | 76 | """ |
| 77 | Assemble deferred request parameters and partially instantiate response handler |
| 78 | """ |
Max | 0028ce1 | 2018-12-05 18:07:04 +0100 | [diff] [blame] | 79 | d = post(dst, par, timeout=tout) |
Max | c450237 | 2018-12-21 13:36:36 +0100 | [diff] [blame] | 80 | d.addCallback(collect, partial(handle_reply, ts, datetime.datetime.now(), par['bsc_id'], f_write, f_log)) |
Max | ee3a70e | 2018-12-05 18:18:38 +0100 | [diff] [blame] | 81 | d.addErrback(lambda e: f_log.critical("HTTP POST error %s while trying to register BSC %s on %s (timeout %d)" % (repr(e), par['bsc_id'], dst, tout))) # handle HTTP errors |
Max | 8f8d914 | 2018-12-05 16:03:57 +0100 | [diff] [blame] | 82 | return d |
| 83 | |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 84 | class Trap(CTRL): |
| 85 | """ |
| 86 | TRAP handler (agnostic to factory's client object) |
| 87 | """ |
| 88 | def ctrl_TRAP(self, data, op_id, v): |
| 89 | """ |
| 90 | Parse CTRL TRAP and dispatch to appropriate handler after normalization |
| 91 | """ |
Max | 5530d7c | 2018-12-21 17:48:20 +0100 | [diff] [blame^] | 92 | if get_type(v) == 'location-state': |
| 93 | p = p_h(v) |
| 94 | self.handle_locationstate(p(1), p(3), p(5), p(7), get_r(v)) |
| 95 | else: |
| 96 | self.factory.log.debug('Ignoring TRAP %s' % (v.split()[0])) |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 97 | |
| 98 | def ctrl_SET_REPLY(self, data, _, v): |
| 99 | """ |
| 100 | Debug log for replies to our commands |
| 101 | """ |
| 102 | self.factory.log.debug('SET REPLY %s' % v) |
| 103 | |
| 104 | def ctrl_ERROR(self, data, op_id, v): |
| 105 | """ |
| 106 | We want to know if smth went wrong |
| 107 | """ |
| 108 | self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v)) |
| 109 | |
| 110 | def connectionMade(self): |
| 111 | """ |
| 112 | Logging wrapper, calling super() is necessary not to break reconnection logic |
| 113 | """ |
Max | fa80a22 | 2018-12-05 16:00:29 +0100 | [diff] [blame] | 114 | self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.addr_ctrl, self.factory.port_ctrl)) |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 115 | super(CTRL, self).connectionMade() |
| 116 | |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 117 | def handle_locationstate(self, net, bsc, bts, trx, data): |
| 118 | """ |
| 119 | Handle location-state TRAP: parse trap content, build CGI Request and use treq's routines to post it while setting up async handlers |
| 120 | """ |
| 121 | params = make_params(bsc, data) |
Max | 40a3752 | 2018-12-05 17:55:58 +0100 | [diff] [blame] | 122 | self.factory.log.info('location-state@%s.%s.%s.%s (%s) => %s' % (net, bsc, bts, trx, params['time_stamp'], data)) |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 123 | params['h'] = gen_hash(params, self.factory.secret_key) |
Max | 4e95b8f | 2018-12-05 17:58:40 +0100 | [diff] [blame] | 124 | t = datetime.datetime.now() |
| 125 | self.factory.log.debug('Preparing request for BSC %s @ %s...' % (params['bsc_id'], t)) |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 126 | # Ensure that we run only limited number of requests in parallel: |
Max | 0028ce1 | 2018-12-05 18:07:04 +0100 | [diff] [blame] | 127 | self.factory.semaphore.run(make_async_req, t, self.factory.location, params, self.transport.write, self.factory.log, self.factory.timeout) |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 128 | |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 129 | |
| 130 | class TrapFactory(IPAFactory): |
| 131 | """ |
| 132 | Store CGI information so TRAP handler can use it for requests |
| 133 | """ |
Max | fa80a22 | 2018-12-05 16:00:29 +0100 | [diff] [blame] | 134 | def __init__(self, proto, log): |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 135 | self.log = log |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 136 | level = self.log.getEffectiveLevel() |
| 137 | self.log.setLevel(logging.WARNING) # we do not need excessive debug from lower levels |
| 138 | super(TrapFactory, self).__init__(proto, self.log) |
| 139 | self.log.setLevel(level) |
Max | fa80a22 | 2018-12-05 16:00:29 +0100 | [diff] [blame] | 140 | self.log.debug("Using Osmocom IPA library v%s" % Ctrl.version) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 141 | |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 142 | |
| 143 | if __name__ == '__main__': |
| 144 | p = argparse.ArgumentParser(description='Proxy between given GCI service and Osmocom CTRL protocol.') |
| 145 | p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__)) |
Max | 5baba8c | 2018-11-26 16:42:59 +0100 | [diff] [blame] | 146 | p.add_argument('-d', '--debug', action='store_true', help="Enable debug log") # keep in sync with debug_init call below |
Max | fa80a22 | 2018-12-05 16:00:29 +0100 | [diff] [blame] | 147 | p.add_argument('-c', '--config-file', required=True, help="Path to mandatory config file (in INI format).") |
| 148 | args = p.parse_args(namespace=TrapFactory) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 149 | |
Max | f0f8a35 | 2018-12-05 13:49:13 +0100 | [diff] [blame] | 150 | log = debug_init('CTRL2CGI', args.debug) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 151 | |
Max | fa80a22 | 2018-12-05 16:00:29 +0100 | [diff] [blame] | 152 | T = TrapFactory(Trap, log) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 153 | |
Max | fa80a22 | 2018-12-05 16:00:29 +0100 | [diff] [blame] | 154 | config = configparser.ConfigParser(interpolation=None) |
| 155 | config.read(args.config_file) |
| 156 | |
| 157 | T.addr_ctrl = config['main'].get('addr_ctrl', 'localhost') |
| 158 | T.port_ctrl = config['main'].getint('port_ctrl', 4250) |
Max | 0028ce1 | 2018-12-05 18:07:04 +0100 | [diff] [blame] | 159 | T.timeout = config['main'].getint('timeout', 30) |
Max | fa80a22 | 2018-12-05 16:00:29 +0100 | [diff] [blame] | 160 | T.semaphore = defer.DeferredSemaphore(config['main'].getint('num_max_conn', 5)) |
| 161 | T.location = config['main'].get('location') |
| 162 | T.secret_key = config['main'].get('secret_key') |
| 163 | |
| 164 | log.info("CGI proxy v%s starting with PID %d:" % (__version__, os.getpid())) |
| 165 | log.info("destination %s (concurrency %d)" % (T.location, T.semaphore.limit)) |
| 166 | log.info("connecting to %s:%d..." % (T.addr_ctrl, T.port_ctrl)) |
| 167 | reactor.connectTCP(T.addr_ctrl, T.port_ctrl, T) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 168 | reactor.run() |