blob: 267b4d85d8dc1d9a3dba7c825515b5bc769a0eed [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
Maxf7255fa2018-11-28 11:25:15 +010025__version__ = "0.7.2" # bump this on every non-trivial change
Maxe732c2c2017-11-23 16:42:59 +010026
Max25a82972018-11-28 11:55:19 +010027import argparse, os, logging
28from functools import partial
29from distutils.version import StrictVersion as V # FIXME: use NormalizedVersion from PEP-386 when available
Maxe732c2c2017-11-23 16:42:59 +010030from twisted.internet import defer, reactor
Max25a82972018-11-28 11:55:19 +010031from suds.client import Client
32from treq import post, collect
33from osmopy.trap_helper import debug_init, get_type, get_r, p_h, make_params, comm_proc
Pau Espin Pedrol8739f9c2018-07-11 14:03:32 +020034from osmopy.twisted_ipa import CTRL, IPAFactory, __version__ as twisted_ipa_version
Maxe732c2c2017-11-23 16:42:59 +010035from osmopy.osmo_ipa import Ctrl
Maxe732c2c2017-11-23 16:42:59 +010036
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 """
Maxf7255fa2018-11-28 11:25:15 +010043 Reply handler: takes function p to process raw SOAP server reply r, function f to run for each command
Maxe732c2c2017-11-23 16:42:59 +010044 """
45 repl = p(r) # result is expected to have both commands[] array and error string (could be None)
Maxf7255fa2018-11-28 11:25:15 +010046 bsc_id = comm_proc(repl.commands, f, log)
Maxe732c2c2017-11-23 16:42:59 +010047 log.info("Received SOAP response for BSC %s with %d commands, error status: %s" % (bsc_id, len(repl.commands), repl.error))
Maxe732c2c2017-11-23 16:42:59 +010048
49
Maxa07e5532018-11-27 17:42:07 +010050class Trap(CTRL):
51 """
52 TRAP handler (agnostic to factory's client object)
53 """
54 def ctrl_TRAP(self, data, op_id, v):
55 """
56 Parse CTRL TRAP and dispatch to appropriate handler after normalization
57 """
58 self.factory.log.debug('TRAP %s' % v)
59 t_type = get_type(v)
60 p = p_h(v)
61 method = getattr(self, 'handle_' + t_type.replace('-', ''), lambda *_: "Unhandled %s trap" % t_type)
62 method(p(1), p(3), p(5), p(7), get_r(v))
63
64 def ctrl_SET_REPLY(self, data, _, v):
65 """
66 Debug log for replies to our commands
67 """
68 self.factory.log.debug('SET REPLY %s' % v)
69
70 def ctrl_ERROR(self, data, op_id, v):
71 """
72 We want to know if smth went wrong
73 """
74 self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v))
75
76 def connectionMade(self):
77 """
78 Logging wrapper, calling super() is necessary not to break reconnection logic
79 """
80 self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.host, self.factory.port))
81 super(CTRL, self).connectionMade()
82
83 @defer.inlineCallbacks
84 def handle_locationstate(self, net, bsc, bts, trx, data):
85 """
86 Handle location-state TRAP: parse trap content, build SOAP context and use treq's routines to post it while setting up async handlers
87 """
88 params = make_params(bsc, data)
89 self.factory.log.debug('location-state@%s.%s.%s.%s (%s) => %s' % (net, bsc, bts, trx, params['time_stamp'], data))
90 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'])
91 d = post(self.factory.location, ctx.envelope)
92 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
93 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
94 # Ensure that we run only limited number of requests in parallel:
95 yield self.factory.semaphore.acquire()
96 yield d # we end up here only if semaphore is available which means it's ok to fire the request without exceeding the limit
97 self.factory.semaphore.release()
98
99 def handle_notificationrejectionv1(self, net, bsc, bts, trx, data):
100 """
101 Handle notification-rejection-v1 TRAP: just an example to show how more message types can be handled
102 """
103 self.factory.log.debug('notification-rejection-v1@bsc-id %s => %s' % (bsc, data))
104
105
Maxe732c2c2017-11-23 16:42:59 +0100106class TrapFactory(IPAFactory):
107 """
108 Store SOAP client object so TRAP handler can use it for requests
109 """
110 location = None
111 log = None
112 semaphore = None
113 client = None
114 host = None
115 port = None
116 def __init__(self, host, port, proto, semaphore, log, wsdl=None, location=None):
117 self.host = host # for logging only,
118 self.port = port # seems to be no way to get it from ReconnectingClientFactory
119 self.log = log
120 self.semaphore = semaphore
121 soap = Client(wsdl, location=location, nosend=True) # make async SOAP client
122 self.location = location.encode() if location else soap.wsdl.services[0].ports[0].location # necessary for dispatching HTTP POST via treq
123 self.client = soap.service
124 level = self.log.getEffectiveLevel()
125 self.log.setLevel(logging.WARNING) # we do not need excessive debug from lower levels
126 super(TrapFactory, self).__init__(proto, self.log)
127 self.log.setLevel(level)
128 self.log.debug("Using IPA %s, SUDS client: %s" % (Ctrl.version, soap))
129
Maxe732c2c2017-11-23 16:42:59 +0100130
131if __name__ == '__main__':
132 p = argparse.ArgumentParser(description='Proxy between given SOAP service and Osmocom CTRL protocol.')
133 p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__))
134 p.add_argument('-p', '--port', type=int, default=4250, help="Port to use for CTRL interface, defaults to 4250")
135 p.add_argument('-c', '--ctrl', default='localhost', help="Adress to use for CTRL interface, defaults to localhost")
136 p.add_argument('-w', '--wsdl', required=True, help="WSDL URL for SOAP")
137 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 +0100138 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 +0100139 p.add_argument('-o', '--output', action='store_true', help="Log to STDOUT in addition to SYSLOG")
140 p.add_argument('-l', '--location', help="Override location found in WSDL file (don't use unless you know what you're doing)")
141 args = p.parse_args()
142
Max5baba8c2018-11-26 16:42:59 +0100143 log = debug_init('CTRL2SOAP', args.debug, args.output)
Maxe732c2c2017-11-23 16:42:59 +0100144
145 log.info("SOAP proxy %s starting with PID %d ..." % (__version__, os.getpid()))
146 reactor.connectTCP(args.ctrl, args.port, TrapFactory(args.ctrl, args.port, Trap, defer.DeferredSemaphore(args.num), log, args.wsdl, args.location))
147 reactor.run()