blob: 75acd89c196619eee747b4f046ac0ccad8f4c11b [file] [log] [blame]
Maxe732c2c2017-11-23 16:42:59 +01001#!/usr/bin/python3
2# -*- mode: python-mode; py-indent-tabs-mode: nil -*-
3"""
4/*
5 * Copyright (C) 2016 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
25__version__ = "0.7.1" # bump this on every non-trivial change
26
27from twisted.internet import defer, reactor
Pau Espin Pedrol8739f9c2018-07-11 14:03:32 +020028from osmopy.twisted_ipa import CTRL, IPAFactory, __version__ as twisted_ipa_version
Maxe732c2c2017-11-23 16:42:59 +010029from osmopy.osmo_ipa import Ctrl
30from treq import post, collect
31from suds.client import Client
32from functools import partial
Maxa07e5532018-11-27 17:42:07 +010033from osmopy.trap_helper import reloader, debug_init, get_type, get_r, p_h, make_params
Maxe732c2c2017-11-23 16:42:59 +010034from distutils.version import StrictVersion as V # FIXME: use NormalizedVersion from PEP-386 when available
35import argparse, datetime, signal, sys, os, logging, logging.handlers
36
37# we don't support older versions of TwistedIPA module
38assert V(twisted_ipa_version) > V('0.4')
39
Maxe732c2c2017-11-23 16:42:59 +010040
41def handle_reply(p, f, log, r):
42 """
43 Reply handler: takes function p to process raw SOAP server reply r, function f to run for each command and verbosity flag v
44 """
45 repl = p(r) # result is expected to have both commands[] array and error string (could be None)
46 bsc_id = repl.commands[0].split()[0].split('.')[3] # we expect 1st command to have net.0.bsc.666.bts.2.trx.1 location prefix format
47 log.info("Received SOAP response for BSC %s with %d commands, error status: %s" % (bsc_id, len(repl.commands), repl.error))
48 log.debug("BSC %s commands: %s" % (bsc_id, repl.commands))
49 for t in repl.commands: # Process OpenBscCommands format from .wsdl
50 (_, m) = Ctrl().cmd(*t.split())
51 f(m)
52
53
Maxa07e5532018-11-27 17:42:07 +010054class Trap(CTRL):
55 """
56 TRAP handler (agnostic to factory's client object)
57 """
58 def ctrl_TRAP(self, data, op_id, v):
59 """
60 Parse CTRL TRAP and dispatch to appropriate handler after normalization
61 """
62 self.factory.log.debug('TRAP %s' % v)
63 t_type = get_type(v)
64 p = p_h(v)
65 method = getattr(self, 'handle_' + t_type.replace('-', ''), lambda *_: "Unhandled %s trap" % t_type)
66 method(p(1), p(3), p(5), p(7), get_r(v))
67
68 def ctrl_SET_REPLY(self, data, _, v):
69 """
70 Debug log for replies to our commands
71 """
72 self.factory.log.debug('SET REPLY %s' % v)
73
74 def ctrl_ERROR(self, data, op_id, v):
75 """
76 We want to know if smth went wrong
77 """
78 self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v))
79
80 def connectionMade(self):
81 """
82 Logging wrapper, calling super() is necessary not to break reconnection logic
83 """
84 self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.host, self.factory.port))
85 super(CTRL, self).connectionMade()
86
87 @defer.inlineCallbacks
88 def handle_locationstate(self, net, bsc, bts, trx, data):
89 """
90 Handle location-state TRAP: parse trap content, build SOAP context and use treq's routines to post it while setting up async handlers
91 """
92 params = make_params(bsc, data)
93 self.factory.log.debug('location-state@%s.%s.%s.%s (%s) => %s' % (net, bsc, bts, trx, params['time_stamp'], data))
94 ctx = self.factory.client.registerSiteLocation(bsc, float(params['lon']), float(params['lat']), params['position_validity'], params['time_stamp'], params['oper_status'], params['admin_status'], params['policy_status'])
95 d = post(self.factory.location, ctx.envelope)
96 d.addCallback(collect, partial(handle_reply, ctx.process_reply, self.transport.write, self.factory.log)) # treq's collect helper is handy to get all reply content at once using closure on ctx
97 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
98 # Ensure that we run only limited number of requests in parallel:
99 yield self.factory.semaphore.acquire()
100 yield d # we end up here only if semaphore is available which means it's ok to fire the request without exceeding the limit
101 self.factory.semaphore.release()
102
103 def handle_notificationrejectionv1(self, net, bsc, bts, trx, data):
104 """
105 Handle notification-rejection-v1 TRAP: just an example to show how more message types can be handled
106 """
107 self.factory.log.debug('notification-rejection-v1@bsc-id %s => %s' % (bsc, data))
108
109
Maxe732c2c2017-11-23 16:42:59 +0100110class TrapFactory(IPAFactory):
111 """
112 Store SOAP client object so TRAP handler can use it for requests
113 """
114 location = None
115 log = None
116 semaphore = None
117 client = None
118 host = None
119 port = None
120 def __init__(self, host, port, proto, semaphore, log, wsdl=None, location=None):
121 self.host = host # for logging only,
122 self.port = port # seems to be no way to get it from ReconnectingClientFactory
123 self.log = log
124 self.semaphore = semaphore
125 soap = Client(wsdl, location=location, nosend=True) # make async SOAP client
126 self.location = location.encode() if location else soap.wsdl.services[0].ports[0].location # necessary for dispatching HTTP POST via treq
127 self.client = soap.service
128 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)
132 self.log.debug("Using IPA %s, SUDS client: %s" % (Ctrl.version, soap))
133
Maxe732c2c2017-11-23 16:42:59 +0100134
135if __name__ == '__main__':
136 p = argparse.ArgumentParser(description='Proxy between given SOAP service and Osmocom CTRL protocol.')
137 p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__))
138 p.add_argument('-p', '--port', type=int, default=4250, help="Port to use for CTRL interface, defaults to 4250")
139 p.add_argument('-c', '--ctrl', default='localhost', help="Adress to use for CTRL interface, defaults to localhost")
140 p.add_argument('-w', '--wsdl', required=True, help="WSDL URL for SOAP")
141 p.add_argument('-n', '--num', type=int, default=5, help="Max number of concurrent HTTP requests to SOAP server")
Max5baba8c2018-11-26 16:42:59 +0100142 p.add_argument('-d', '--debug', action='store_true', help="Enable debug log") # keep in sync with debug_init call below
Maxe732c2c2017-11-23 16:42:59 +0100143 p.add_argument('-o', '--output', action='store_true', help="Log to STDOUT in addition to SYSLOG")
144 p.add_argument('-l', '--location', help="Override location found in WSDL file (don't use unless you know what you're doing)")
145 args = p.parse_args()
146
Max5baba8c2018-11-26 16:42:59 +0100147 log = debug_init('CTRL2SOAP', args.debug, args.output)
Maxe732c2c2017-11-23 16:42:59 +0100148
149 log.info("SOAP proxy %s starting with PID %d ..." % (__version__, os.getpid()))
150 reactor.connectTCP(args.ctrl, args.port, TrapFactory(args.ctrl, args.port, Trap, defer.DeferredSemaphore(args.num), log, args.wsdl, args.location))
151 reactor.run()