blob: 95ff7884360cc0a72a0ff0de710185ec2eaaae79 [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
Max19b77a42019-01-07 15:53:35 +010025__version__ = "0.1.1" # 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
Max19b77a42019-01-07 15:53:35 +010035from osmopy.trap_helper import debug_init, get_type, get_r, p_h, gen_hash, make_params, comm_proc
Max25a82972018-11-28 11:55:19 +010036from 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
Max0028ce12018-12-05 18:07:04 +010060def make_async_req(ts, dst, par, f_write, f_log, tout):
Max66441e72018-12-21 18:42:30 +010061 """
62 Assemble deferred request parameters and partially instantiate response handler
63 """
Max0028ce12018-12-05 18:07:04 +010064 d = post(dst, par, timeout=tout)
Maxc4502372018-12-21 13:36:36 +010065 d.addCallback(collect, partial(handle_reply, ts, datetime.datetime.now(), par['bsc_id'], f_write, f_log))
Maxee3a70e2018-12-05 18:18:38 +010066 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 +010067 return d
68
Maxa07e5532018-11-27 17:42:07 +010069class Trap(CTRL):
70 """
71 TRAP handler (agnostic to factory's client object)
72 """
73 def ctrl_TRAP(self, data, op_id, v):
74 """
75 Parse CTRL TRAP and dispatch to appropriate handler after normalization
76 """
Max5530d7c2018-12-21 17:48:20 +010077 if get_type(v) == 'location-state':
78 p = p_h(v)
79 self.handle_locationstate(p(1), p(3), p(5), p(7), get_r(v))
80 else:
81 self.factory.log.debug('Ignoring TRAP %s' % (v.split()[0]))
Maxa07e5532018-11-27 17:42:07 +010082
83 def ctrl_SET_REPLY(self, data, _, v):
84 """
85 Debug log for replies to our commands
86 """
87 self.factory.log.debug('SET REPLY %s' % v)
88
89 def ctrl_ERROR(self, data, op_id, v):
90 """
91 We want to know if smth went wrong
92 """
93 self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v))
94
95 def connectionMade(self):
96 """
97 Logging wrapper, calling super() is necessary not to break reconnection logic
98 """
Maxfa80a222018-12-05 16:00:29 +010099 self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.addr_ctrl, self.factory.port_ctrl))
Maxa07e5532018-11-27 17:42:07 +0100100 super(CTRL, self).connectionMade()
101
Maxa07e5532018-11-27 17:42:07 +0100102 def handle_locationstate(self, net, bsc, bts, trx, data):
103 """
104 Handle location-state TRAP: parse trap content, build CGI Request and use treq's routines to post it while setting up async handlers
105 """
106 params = make_params(bsc, data)
Max40a37522018-12-05 17:55:58 +0100107 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 +0100108 params['h'] = gen_hash(params, self.factory.secret_key)
Max4e95b8f2018-12-05 17:58:40 +0100109 t = datetime.datetime.now()
110 self.factory.log.debug('Preparing request for BSC %s @ %s...' % (params['bsc_id'], t))
Maxa07e5532018-11-27 17:42:07 +0100111 # Ensure that we run only limited number of requests in parallel:
Max0028ce12018-12-05 18:07:04 +0100112 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 +0100113
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200114
115class TrapFactory(IPAFactory):
116 """
117 Store CGI information so TRAP handler can use it for requests
118 """
Maxfa80a222018-12-05 16:00:29 +0100119 def __init__(self, proto, log):
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200120 self.log = log
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200121 level = self.log.getEffectiveLevel()
122 self.log.setLevel(logging.WARNING) # we do not need excessive debug from lower levels
123 super(TrapFactory, self).__init__(proto, self.log)
124 self.log.setLevel(level)
Maxfa80a222018-12-05 16:00:29 +0100125 self.log.debug("Using Osmocom IPA library v%s" % Ctrl.version)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200126
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200127
128if __name__ == '__main__':
129 p = argparse.ArgumentParser(description='Proxy between given GCI service and Osmocom CTRL protocol.')
130 p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__))
Max5baba8c2018-11-26 16:42:59 +0100131 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 +0100132 p.add_argument('-c', '--config-file', required=True, help="Path to mandatory config file (in INI format).")
133 args = p.parse_args(namespace=TrapFactory)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200134
Maxf0f8a352018-12-05 13:49:13 +0100135 log = debug_init('CTRL2CGI', args.debug)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200136
Maxfa80a222018-12-05 16:00:29 +0100137 T = TrapFactory(Trap, log)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200138
Maxfa80a222018-12-05 16:00:29 +0100139 config = configparser.ConfigParser(interpolation=None)
140 config.read(args.config_file)
141
142 T.addr_ctrl = config['main'].get('addr_ctrl', 'localhost')
143 T.port_ctrl = config['main'].getint('port_ctrl', 4250)
Max0028ce12018-12-05 18:07:04 +0100144 T.timeout = config['main'].getint('timeout', 30)
Maxfa80a222018-12-05 16:00:29 +0100145 T.semaphore = defer.DeferredSemaphore(config['main'].getint('num_max_conn', 5))
146 T.location = config['main'].get('location')
147 T.secret_key = config['main'].get('secret_key')
148
149 log.info("CGI proxy v%s starting with PID %d:" % (__version__, os.getpid()))
150 log.info("destination %s (concurrency %d)" % (T.location, T.semaphore.limit))
151 log.info("connecting to %s:%d..." % (T.addr_ctrl, T.port_ctrl))
152 reactor.connectTCP(T.addr_ctrl, T.port_ctrl, T)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200153 reactor.run()