blob: c566a7c35689453bc8ab37523a6d5ee8e3539d66 [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
Maxec3944e2018-11-27 17:43:45 +010025__version__ = "0.0.3" # bump this on every non-trivial change
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020026
27from twisted.internet import defer, reactor
28from osmopy.twisted_ipa import CTRL, IPAFactory, __version__ as twisted_ipa_version
29from osmopy.osmo_ipa import Ctrl
30from treq import post, collect
31from functools import partial
Maxa07e5532018-11-27 17:42:07 +010032from osmopy.trap_helper import reloader, debug_init, get_type, get_r, p_h, make_params
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020033from distutils.version import StrictVersion as V # FIXME: use NormalizedVersion from PEP-386 when available
34import argparse, datetime, signal, sys, os, logging, logging.handlers
35import hashlib
36import json
37import configparser
38
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
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020043def handle_reply(f, log, resp):
44 """
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'))
48 bsc_id = decoded.get('commands')[0].split()[0].split('.')[3] # we expect 1st command to have net.0.bsc.666.bts.2.trx.1 location prefix format
49 log.debug("BSC %s commands: %r" % (bsc_id, decoded.get('commands')))
50 for t in decoded.get('commands'): # Process commands format
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +020051 (_, m) = Ctrl().cmd(*t.split())
52 f(m)
53
54def gen_hash(params, skey):
55 input = ''
56 for key in ['time_stamp','position_validity','admin_status','policy_status']:
57 input += str(params.get(key))
58 input += skey
59 for key in ['bsc_id','lat','lon','position_validity']:
60 input += str(params.get(key))
61 m = hashlib.md5()
62 m.update(input.encode('utf-8'))
63 res = m.hexdigest()
64 #print('HASH: \nparams="%r"\ninput="%s" \nres="%s"' %(params, input, res))
65 return res
66
Maxa07e5532018-11-27 17:42:07 +010067class Trap(CTRL):
68 """
69 TRAP handler (agnostic to factory's client object)
70 """
71 def ctrl_TRAP(self, data, op_id, v):
72 """
73 Parse CTRL TRAP and dispatch to appropriate handler after normalization
74 """
75 self.factory.log.debug('TRAP %s' % v)
76 t_type = get_type(v)
77 p = p_h(v)
78 method = getattr(self, 'handle_' + t_type.replace('-', ''), lambda *_: "Unhandled %s trap" % t_type)
79 method(p(1), p(3), p(5), p(7), get_r(v))
80
81 def ctrl_SET_REPLY(self, data, _, v):
82 """
83 Debug log for replies to our commands
84 """
85 self.factory.log.debug('SET REPLY %s' % v)
86
87 def ctrl_ERROR(self, data, op_id, v):
88 """
89 We want to know if smth went wrong
90 """
91 self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v))
92
93 def connectionMade(self):
94 """
95 Logging wrapper, calling super() is necessary not to break reconnection logic
96 """
97 self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.host, self.factory.port))
98 super(CTRL, self).connectionMade()
99
100 @defer.inlineCallbacks
101 def handle_locationstate(self, net, bsc, bts, trx, data):
102 """
103 Handle location-state TRAP: parse trap content, build CGI Request and use treq's routines to post it while setting up async handlers
104 """
105 params = make_params(bsc, data)
106 self.factory.log.debug('location-state@%s.%s.%s.%s (%s) => %s' % (net, bsc, bts, trx, params['time_stamp'], data))
107 params['h'] = gen_hash(params, self.factory.secret_key)
Maxec3944e2018-11-27 17:43:45 +0100108 d = post(self.factory.location, params)
109 d.addCallback(collect, partial(handle_reply, self.transport.write, self.factory.log)) # treq's collect helper is handy to get all reply content at once
Maxa07e5532018-11-27 17:42:07 +0100110 d.addErrback(lambda e, bsc: self.factory.log.critical("HTTP POST error %s while trying to register BSC %s on %s" % (e, bsc, self.factory.location)), bsc) # handle HTTP errors
111 # Ensure that we run only limited number of requests in parallel:
112 yield self.factory.semaphore.acquire()
113 yield d # we end up here only if semaphore is available which means it's ok to fire the request without exceeding the limit
114 self.factory.semaphore.release()
115
116 def handle_notificationrejectionv1(self, net, bsc, bts, trx, data):
117 """
118 Handle notification-rejection-v1 TRAP: just an example to show how more message types can be handled
119 """
120 self.factory.log.debug('notification-rejection-v1@bsc-id %s => %s' % (bsc, data))
121
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200122
123class TrapFactory(IPAFactory):
124 """
125 Store CGI information so TRAP handler can use it for requests
126 """
127 location = None
128 log = None
129 semaphore = None
130 client = None
131 host = None
132 port = None
133 secret_key = None
134 def __init__(self, host, port, proto, semaphore, log, location, secret_key):
135 self.host = host # for logging only,
136 self.port = port # seems to be no way to get it from ReconnectingClientFactory
137 self.log = log
138 self.semaphore = semaphore
139 self.location = location
140 self.secret_key = secret_key
141 level = self.log.getEffectiveLevel()
142 self.log.setLevel(logging.WARNING) # we do not need excessive debug from lower levels
143 super(TrapFactory, self).__init__(proto, self.log)
144 self.log.setLevel(level)
145 self.log.debug("Using IPA %s, CGI server: %s" % (Ctrl.version, self.location))
146
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200147
148if __name__ == '__main__':
149 p = argparse.ArgumentParser(description='Proxy between given GCI service and Osmocom CTRL protocol.')
150 p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__))
151 p.add_argument('-a', '--addr-ctrl', default='localhost', help="Adress to use for CTRL interface, defaults to localhost")
152 p.add_argument('-p', '--port-ctrl', type=int, default=4250, help="Port to use for CTRL interface, defaults to 4250")
153 p.add_argument('-n', '--num-max-conn', type=int, default=5, help="Max number of concurrent HTTP requests to CGI server")
Max5baba8c2018-11-26 16:42:59 +0100154 p.add_argument('-d', '--debug', action='store_true', help="Enable debug log") # keep in sync with debug_init call below
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200155 p.add_argument('-o', '--output', action='store_true', help="Log to STDOUT in addition to SYSLOG")
156 p.add_argument('-l', '--location', help="Location URL of the CGI server")
157 p.add_argument('-s', '--secret-key', help="Secret key used to generate verification token")
158 p.add_argument('-c', '--config-file', help="Path Config file. Cmd line args override values in config file")
159 args = p.parse_args()
160
Max5baba8c2018-11-26 16:42:59 +0100161 log = debug_init('CTRL2CGI', args.debug, args.output)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200162
163 location_cfgfile = None
164 secret_key_cfgfile = None
165 port_ctrl_cfgfile = None
166 addr_ctrl_cfgfile = None
167 num_max_conn_cfgfile = None
168 if args.config_file:
169 config = configparser.ConfigParser()
170 config.read(args.config_file)
171 if 'main' in config:
172 location_cfgfile = config['main'].get('location', None)
173 secret_key_cfgfile = config['main'].get('secret_key', None)
174 addr_ctrl_cfgfile = config['main'].get('addr_ctrl', None)
175 port_ctrl_cfgfile = config['main'].get('port_ctrl', None)
176 num_max_conn_cfgfile = config['main'].get('num_max_conn', None)
177 location = args.location if args.location is not None else location_cfgfile
178 secret_key = args.secret_key if args.secret_key is not None else secret_key_cfgfile
179 addr_ctrl = args.addr_ctrl if args.addr_ctrl is not None else addr_ctrl_cfgfile
180 port_ctrl = args.port_ctrl if args.port_ctrl is not None else port_ctrl_cfgfile
181 num_max_conn = args.num_max_conn if args.num_max_conn is not None else num_max_conn_cfgfile
182
183 log.info("CGI proxy %s starting with PID %d ..." % (__version__, os.getpid()))
184 reactor.connectTCP(addr_ctrl, port_ctrl, TrapFactory(addr_ctrl, port_ctrl, Trap, defer.DeferredSemaphore(num_max_conn), log, location, secret_key))
185 reactor.run()