blob: 843aeb95fa1ab484582b5ca69c220f319f6a3aaf [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
Maxa07e5532018-11-27 17:42:07 +010025__version__ = "0.0.2" # 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 +020043@defer.inlineCallbacks
44def handle_reply(f, log, resp):
45 """
46 Reply handler: process raw CGI server response, function f to run for each command
47 """
48 #log.debug('HANDLE_REPLY: code=%r' % (resp.code))
49 #for key,val in resp.headers.getAllRawHeaders():
50 # log.debug('HANDLE_REPLY: key=%r val=%r' % (key, val))
51 if resp.code != 200:
52 resp_body = yield resp.text()
53 log.critical('Received HTTP response %d: %s' % (resp.code, resp_body))
54 return
55
56 parsed = yield resp.json()
57 #log.debug("RESPONSE: %r" % (parsed))
58 bsc_id = parsed.get('commands')[0].split()[0].split('.')[3] # we expect 1st command to have net.0.bsc.666.bts.2.trx.1 location prefix format
59 log.info("Received CGI response for BSC %s with %d commands, error status: %s" % (bsc_id, len(parsed.get('commands')), parsed.get('error')))
60 log.debug("BSC %s commands: %r" % (bsc_id, parsed.get('commands')))
61 for t in parsed.get('commands'): # Process commands format
62 (_, m) = Ctrl().cmd(*t.split())
63 f(m)
64
65def gen_hash(params, skey):
66 input = ''
67 for key in ['time_stamp','position_validity','admin_status','policy_status']:
68 input += str(params.get(key))
69 input += skey
70 for key in ['bsc_id','lat','lon','position_validity']:
71 input += str(params.get(key))
72 m = hashlib.md5()
73 m.update(input.encode('utf-8'))
74 res = m.hexdigest()
75 #print('HASH: \nparams="%r"\ninput="%s" \nres="%s"' %(params, input, res))
76 return res
77
Maxa07e5532018-11-27 17:42:07 +010078class Trap(CTRL):
79 """
80 TRAP handler (agnostic to factory's client object)
81 """
82 def ctrl_TRAP(self, data, op_id, v):
83 """
84 Parse CTRL TRAP and dispatch to appropriate handler after normalization
85 """
86 self.factory.log.debug('TRAP %s' % v)
87 t_type = get_type(v)
88 p = p_h(v)
89 method = getattr(self, 'handle_' + t_type.replace('-', ''), lambda *_: "Unhandled %s trap" % t_type)
90 method(p(1), p(3), p(5), p(7), get_r(v))
91
92 def ctrl_SET_REPLY(self, data, _, v):
93 """
94 Debug log for replies to our commands
95 """
96 self.factory.log.debug('SET REPLY %s' % v)
97
98 def ctrl_ERROR(self, data, op_id, v):
99 """
100 We want to know if smth went wrong
101 """
102 self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v))
103
104 def connectionMade(self):
105 """
106 Logging wrapper, calling super() is necessary not to break reconnection logic
107 """
108 self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.host, self.factory.port))
109 super(CTRL, self).connectionMade()
110
111 @defer.inlineCallbacks
112 def handle_locationstate(self, net, bsc, bts, trx, data):
113 """
114 Handle location-state TRAP: parse trap content, build CGI Request and use treq's routines to post it while setting up async handlers
115 """
116 params = make_params(bsc, data)
117 self.factory.log.debug('location-state@%s.%s.%s.%s (%s) => %s' % (net, bsc, bts, trx, params['time_stamp'], data))
118 params['h'] = gen_hash(params, self.factory.secret_key)
119 d = post(self.factory.location, None, params=params)
120 d.addCallback(partial(handle_reply, self.transport.write, self.factory.log)) # treq's collect helper is handy to get all reply content at once using closure on ctx
121 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
122 # Ensure that we run only limited number of requests in parallel:
123 yield self.factory.semaphore.acquire()
124 yield d # we end up here only if semaphore is available which means it's ok to fire the request without exceeding the limit
125 self.factory.semaphore.release()
126
127 def handle_notificationrejectionv1(self, net, bsc, bts, trx, data):
128 """
129 Handle notification-rejection-v1 TRAP: just an example to show how more message types can be handled
130 """
131 self.factory.log.debug('notification-rejection-v1@bsc-id %s => %s' % (bsc, data))
132
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200133
134class TrapFactory(IPAFactory):
135 """
136 Store CGI information so TRAP handler can use it for requests
137 """
138 location = None
139 log = None
140 semaphore = None
141 client = None
142 host = None
143 port = None
144 secret_key = None
145 def __init__(self, host, port, proto, semaphore, log, location, secret_key):
146 self.host = host # for logging only,
147 self.port = port # seems to be no way to get it from ReconnectingClientFactory
148 self.log = log
149 self.semaphore = semaphore
150 self.location = location
151 self.secret_key = secret_key
152 level = self.log.getEffectiveLevel()
153 self.log.setLevel(logging.WARNING) # we do not need excessive debug from lower levels
154 super(TrapFactory, self).__init__(proto, self.log)
155 self.log.setLevel(level)
156 self.log.debug("Using IPA %s, CGI server: %s" % (Ctrl.version, self.location))
157
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200158
159if __name__ == '__main__':
160 p = argparse.ArgumentParser(description='Proxy between given GCI service and Osmocom CTRL protocol.')
161 p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__))
162 p.add_argument('-a', '--addr-ctrl', default='localhost', help="Adress to use for CTRL interface, defaults to localhost")
163 p.add_argument('-p', '--port-ctrl', type=int, default=4250, help="Port to use for CTRL interface, defaults to 4250")
164 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 +0100165 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 +0200166 p.add_argument('-o', '--output', action='store_true', help="Log to STDOUT in addition to SYSLOG")
167 p.add_argument('-l', '--location', help="Location URL of the CGI server")
168 p.add_argument('-s', '--secret-key', help="Secret key used to generate verification token")
169 p.add_argument('-c', '--config-file', help="Path Config file. Cmd line args override values in config file")
170 args = p.parse_args()
171
Max5baba8c2018-11-26 16:42:59 +0100172 log = debug_init('CTRL2CGI', args.debug, args.output)
Pau Espin Pedrol10fbb402018-07-11 14:05:13 +0200173
174 location_cfgfile = None
175 secret_key_cfgfile = None
176 port_ctrl_cfgfile = None
177 addr_ctrl_cfgfile = None
178 num_max_conn_cfgfile = None
179 if args.config_file:
180 config = configparser.ConfigParser()
181 config.read(args.config_file)
182 if 'main' in config:
183 location_cfgfile = config['main'].get('location', None)
184 secret_key_cfgfile = config['main'].get('secret_key', None)
185 addr_ctrl_cfgfile = config['main'].get('addr_ctrl', None)
186 port_ctrl_cfgfile = config['main'].get('port_ctrl', None)
187 num_max_conn_cfgfile = config['main'].get('num_max_conn', None)
188 location = args.location if args.location is not None else location_cfgfile
189 secret_key = args.secret_key if args.secret_key is not None else secret_key_cfgfile
190 addr_ctrl = args.addr_ctrl if args.addr_ctrl is not None else addr_ctrl_cfgfile
191 port_ctrl = args.port_ctrl if args.port_ctrl is not None else port_ctrl_cfgfile
192 num_max_conn = args.num_max_conn if args.num_max_conn is not None else num_max_conn_cfgfile
193
194 log.info("CGI proxy %s starting with PID %d ..." % (__version__, os.getpid()))
195 reactor.connectTCP(addr_ctrl, port_ctrl, TrapFactory(addr_ctrl, port_ctrl, Trap, defer.DeferredSemaphore(num_max_conn), log, location, secret_key))
196 reactor.run()