blob: 28a7c3b26a72fc7d04779b67013cfa0ca6c5b5c6 [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
Max0028ce12018-12-05 18:07:04 +010025__version__ = "0.0.8" # 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
32from distutils.version import StrictVersion as V # FIXME: use NormalizedVersion from PEP-386 when available
33from 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
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020042
Max4e95b8f2018-12-05 17:58:40 +010043def handle_reply(ts, bid, f, log, resp):
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020044 """
45 Reply handler: process raw CGI server response, function f to run for each command
46 """
Maxec3944e2018-11-27 17:43:45 +010047 decoded = json.loads(resp.decode('utf-8'))
Max4e95b8f2018-12-05 17:58:40 +010048 log.debug('request for BSC %s took %d seconds' % (bid, (datetime.datetime.now() - ts).total_seconds()))
Max7f0f7862018-12-05 17:49:36 +010049 comm_proc(decoded.get('commands'), bid, f, log)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020050
51def gen_hash(params, skey):
Max25a82972018-11-28 11:55:19 +010052 inp = ''
53 for key in ['time_stamp', 'position_validity', 'admin_status', 'policy_status']:
54 inp += str(params.get(key))
55 inp += skey
56 for key in ['bsc_id', 'lat', 'lon', 'position_validity']:
57 inp += str(params.get(key))
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020058 m = hashlib.md5()
Max25a82972018-11-28 11:55:19 +010059 m.update(inp.encode('utf-8'))
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020060 res = m.hexdigest()
61 #print('HASH: \nparams="%r"\ninput="%s" \nres="%s"' %(params, input, res))
62 return res
63
Max0028ce12018-12-05 18:07:04 +010064def make_async_req(ts, dst, par, f_write, f_log, tout):
65 d = post(dst, par, timeout=tout)
Max4e95b8f2018-12-05 17:58:40 +010066 d.addCallback(collect, partial(handle_reply, ts, par['bsc_id'], f_write, f_log)) # treq's collect helper is handy to get all reply content at once
Maxee3a70e2018-12-05 18:18:38 +010067 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 +010068 return d
69
Maxa07e5532018-11-27 17:42:07 +010070class Trap(CTRL):
71 """
72 TRAP handler (agnostic to factory's client object)
73 """
74 def ctrl_TRAP(self, data, op_id, v):
75 """
76 Parse CTRL TRAP and dispatch to appropriate handler after normalization
77 """
78 self.factory.log.debug('TRAP %s' % v)
79 t_type = get_type(v)
80 p = p_h(v)
81 method = getattr(self, 'handle_' + t_type.replace('-', ''), lambda *_: "Unhandled %s trap" % t_type)
82 method(p(1), p(3), p(5), p(7), get_r(v))
83
84 def ctrl_SET_REPLY(self, data, _, v):
85 """
86 Debug log for replies to our commands
87 """
88 self.factory.log.debug('SET REPLY %s' % v)
89
90 def ctrl_ERROR(self, data, op_id, v):
91 """
92 We want to know if smth went wrong
93 """
94 self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v))
95
96 def connectionMade(self):
97 """
98 Logging wrapper, calling super() is necessary not to break reconnection logic
99 """
Maxfa80a222018-12-05 16:00:29 +0100100 self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.addr_ctrl, self.factory.port_ctrl))
Maxa07e5532018-11-27 17:42:07 +0100101 super(CTRL, self).connectionMade()
102
Maxa07e5532018-11-27 17:42:07 +0100103 def handle_locationstate(self, net, bsc, bts, trx, data):
104 """
105 Handle location-state TRAP: parse trap content, build CGI Request and use treq's routines to post it while setting up async handlers
106 """
107 params = make_params(bsc, data)
Max40a37522018-12-05 17:55:58 +0100108 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 +0100109 params['h'] = gen_hash(params, self.factory.secret_key)
Max4e95b8f2018-12-05 17:58:40 +0100110 t = datetime.datetime.now()
111 self.factory.log.debug('Preparing request for BSC %s @ %s...' % (params['bsc_id'], t))
Maxa07e5532018-11-27 17:42:07 +0100112 # Ensure that we run only limited number of requests in parallel:
Max0028ce12018-12-05 18:07:04 +0100113 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 +0100114
115 def handle_notificationrejectionv1(self, net, bsc, bts, trx, data):
116 """
117 Handle notification-rejection-v1 TRAP: just an example to show how more message types can be handled
118 """
119 self.factory.log.debug('notification-rejection-v1@bsc-id %s => %s' % (bsc, data))
120
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200121
122class TrapFactory(IPAFactory):
123 """
124 Store CGI information so TRAP handler can use it for requests
125 """
Maxfa80a222018-12-05 16:00:29 +0100126 def __init__(self, proto, log):
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200127 self.log = log
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200128 level = self.log.getEffectiveLevel()
129 self.log.setLevel(logging.WARNING) # we do not need excessive debug from lower levels
130 super(TrapFactory, self).__init__(proto, self.log)
131 self.log.setLevel(level)
Maxfa80a222018-12-05 16:00:29 +0100132 self.log.debug("Using Osmocom IPA library v%s" % Ctrl.version)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200133
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200134
135if __name__ == '__main__':
136 p = argparse.ArgumentParser(description='Proxy between given GCI service and Osmocom CTRL protocol.')
137 p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__))
Max5baba8c2018-11-26 16:42:59 +0100138 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 +0100139 p.add_argument('-c', '--config-file', required=True, help="Path to mandatory config file (in INI format).")
140 args = p.parse_args(namespace=TrapFactory)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200141
Maxf0f8a352018-12-05 13:49:13 +0100142 log = debug_init('CTRL2CGI', args.debug)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200143
Maxfa80a222018-12-05 16:00:29 +0100144 T = TrapFactory(Trap, log)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200145
Maxfa80a222018-12-05 16:00:29 +0100146 config = configparser.ConfigParser(interpolation=None)
147 config.read(args.config_file)
148
149 T.addr_ctrl = config['main'].get('addr_ctrl', 'localhost')
150 T.port_ctrl = config['main'].getint('port_ctrl', 4250)
Max0028ce12018-12-05 18:07:04 +0100151 T.timeout = config['main'].getint('timeout', 30)
Maxfa80a222018-12-05 16:00:29 +0100152 T.semaphore = defer.DeferredSemaphore(config['main'].getint('num_max_conn', 5))
153 T.location = config['main'].get('location')
154 T.secret_key = config['main'].get('secret_key')
155
156 log.info("CGI proxy v%s starting with PID %d:" % (__version__, os.getpid()))
157 log.info("destination %s (concurrency %d)" % (T.location, T.semaphore.limit))
158 log.info("connecting to %s:%d..." % (T.addr_ctrl, T.port_ctrl))
159 reactor.connectTCP(T.addr_ctrl, T.port_ctrl, T)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200160 reactor.run()