blob: bb5c93e4d394ca0bea39c3ca157047f783fb1c74 [file] [log] [blame]
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +02001#!/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
Max5530d7c2018-12-21 17:48:20 +010025__version__ = "0.1.0" # bump this on every non-trivial change
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020026
Max4e95b8f2018-12-05 17:58:40 +010027import argparse, os, logging, logging.handlers, datetime
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020028import hashlib
29import json
30import configparser
Max25a82972018-11-28 11:55:19 +010031from functools import partial
Max66441e72018-12-21 18:42:30 +010032from distutils.version import StrictVersion as V
Max25a82972018-11-28 11:55:19 +010033from twisted.internet import defer, reactor
34from treq import post, collect
35from osmopy.trap_helper import debug_init, get_type, get_r, p_h, make_params, comm_proc
36from osmopy.twisted_ipa import CTRL, IPAFactory, __version__ as twisted_ipa_version
37from osmopy.osmo_ipa import Ctrl
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020038
39# we don't support older versions of TwistedIPA module
40assert V(twisted_ipa_version) > V('0.4')
41
Maxc4502372018-12-21 13:36:36 +010042def 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 Pedrol10fbb402018-07-11 14:05:13 +020051
Maxc4502372018-12-21 13:36:36 +010052def handle_reply(ts, ts_http, bid, f, log, resp):
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020053 """
54 Reply handler: process raw CGI server response, function f to run for each command
55 """
Maxec3944e2018-11-27 17:43:45 +010056 decoded = json.loads(resp.decode('utf-8'))
Maxc4502372018-12-21 13:36:36 +010057 log_duration(log, bid, ts, ts_http)
Max7f0f7862018-12-05 17:49:36 +010058 comm_proc(decoded.get('commands'), bid, f, log)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020059
60def gen_hash(params, skey):
Max66441e72018-12-21 18:42:30 +010061 """
62 Make mandatory parameter for http request
63 """
Max25a82972018-11-28 11:55:19 +010064 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 Pedrol10fbb402018-07-11 14:05:13 +020070 m = hashlib.md5()
Max25a82972018-11-28 11:55:19 +010071 m.update(inp.encode('utf-8'))
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020072 res = m.hexdigest()
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020073 return res
74
Max0028ce12018-12-05 18:07:04 +010075def make_async_req(ts, dst, par, f_write, f_log, tout):
Max66441e72018-12-21 18:42:30 +010076 """
77 Assemble deferred request parameters and partially instantiate response handler
78 """
Max0028ce12018-12-05 18:07:04 +010079 d = post(dst, par, timeout=tout)
Maxc4502372018-12-21 13:36:36 +010080 d.addCallback(collect, partial(handle_reply, ts, datetime.datetime.now(), par['bsc_id'], f_write, f_log))
Maxee3a70e2018-12-05 18:18:38 +010081 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
Max8f8d9142018-12-05 16:03:57 +010082 return d
83
Maxa07e5532018-11-27 17:42:07 +010084class 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 """
Max5530d7c2018-12-21 17:48:20 +010092 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]))
Maxa07e5532018-11-27 17:42:07 +010097
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 """
Maxfa80a222018-12-05 16:00:29 +0100114 self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.addr_ctrl, self.factory.port_ctrl))
Maxa07e5532018-11-27 17:42:07 +0100115 super(CTRL, self).connectionMade()
116
Maxa07e5532018-11-27 17:42:07 +0100117 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)
Max40a37522018-12-05 17:55:58 +0100122 self.factory.log.info('location-state@%s.%s.%s.%s (%s) => %s' % (net, bsc, bts, trx, params['time_stamp'], data))
Maxa07e5532018-11-27 17:42:07 +0100123 params['h'] = gen_hash(params, self.factory.secret_key)
Max4e95b8f2018-12-05 17:58:40 +0100124 t = datetime.datetime.now()
125 self.factory.log.debug('Preparing request for BSC %s @ %s...' % (params['bsc_id'], t))
Maxa07e5532018-11-27 17:42:07 +0100126 # Ensure that we run only limited number of requests in parallel:
Max0028ce12018-12-05 18:07:04 +0100127 self.factory.semaphore.run(make_async_req, t, self.factory.location, params, self.transport.write, self.factory.log, self.factory.timeout)
Maxa07e5532018-11-27 17:42:07 +0100128
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200129
130class TrapFactory(IPAFactory):
131 """
132 Store CGI information so TRAP handler can use it for requests
133 """
Maxfa80a222018-12-05 16:00:29 +0100134 def __init__(self, proto, log):
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200135 self.log = log
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200136 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)
Maxfa80a222018-12-05 16:00:29 +0100140 self.log.debug("Using Osmocom IPA library v%s" % Ctrl.version)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200141
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200142
143if __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__))
Max5baba8c2018-11-26 16:42:59 +0100146 p.add_argument('-d', '--debug', action='store_true', help="Enable debug log") # keep in sync with debug_init call below
Maxfa80a222018-12-05 16:00:29 +0100147 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 Pedrol10fbb402018-07-11 14:05:13 +0200149
Maxf0f8a352018-12-05 13:49:13 +0100150 log = debug_init('CTRL2CGI', args.debug)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200151
Maxfa80a222018-12-05 16:00:29 +0100152 T = TrapFactory(Trap, log)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200153
Maxfa80a222018-12-05 16:00:29 +0100154 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)
Max0028ce12018-12-05 18:07:04 +0100159 T.timeout = config['main'].getint('timeout', 30)
Maxfa80a222018-12-05 16:00:29 +0100160 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 Pedrol10fbb402018-07-11 14:05:13 +0200168 reactor.run()