-
Notifications
You must be signed in to change notification settings - Fork 12
/
Rtp_cluster_config.py
294 lines (247 loc) · 11.7 KB
/
Rtp_cluster_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# Copyright (c) 2009-2014 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from os.path import dirname
from xml.sax import make_parser
from xml.sax.handler import feature_namespaces, feature_validation
from xml.sax.handler import ContentHandler
from xml.sax.saxutils import escape
RTP_CLUSTER_CONFIG_DTD = "Rtp_cluster_config.dtd"
class DisconnectNotify(object):
section_name = None
in_address = None
dest_sprefix = None
def __init__(self, section_name = 'disconnect_notify'):
self.section_name = section_name
def set_in_address(self, in_address_str):
in_address = in_address_str.split(':', 1)
self.in_address = (in_address[0], int(in_address[1]))
def __str__(self, ident = '', idlevel = 1):
return ('%s<%s>\n%s<inbound_address>%s:%d</inbound_address>\n' \
'%s<dest_socket_prefix>%s</dest_socket_prefix>\n%s</%s>' % \
(ident * idlevel, self.section_name, ident * (idlevel + 1), \
self.in_address[0], self.in_address[1], ident * (idlevel + 1), \
self.dest_sprefix, ident * idlevel, self.section_name))
class ValidateHandler(ContentHandler):
def __init__(self, config):
self.config = config
self.element = None
self.warnings = []
self.errors = []
self.rtp_cluster = None
self.rtpproxy = None
self.dnconfig = None
self.ctx = []
def startElement(self, name, attrs):
self.element = name
if self.element == 'rtp_cluster_config':
self.ctx.append('rtp_cluster_config')
elif self.element == 'rtp_cluster':
self.rtp_cluster = {'rtpproxies': []}
self.config.append(self.rtp_cluster)
self.ctx.append('rtp_cluster')
elif self.element == 'rtpproxy':
self.rtpproxy = {}
self.rtp_cluster['rtpproxies'].append(self.rtpproxy)
self.ctx.append('rtpproxy')
elif self.element == 'disconnect_notify':
self.dnconfig = DisconnectNotify(self.element)
self.rtp_cluster['dnconfig'] = self.dnconfig
self.ctx.append('dnconfig')
elif self.element == 'capacity_limit' and self.ctx[-1] == 'rtp_cluster':
cl_type = attrs.getValue('type')
if cl_type == 'soft':
self.rtp_cluster['capacity_limit_soft'] = True
else:
self.rtp_cluster['capacity_limit_soft'] = False
def characters(self, content):
if self.ctx[-1] == 'rtp_cluster':
if self.element == 'name':
for c in self.config:
if 'name' in c:
if c['name'] == content:
raise Exception('rtp_cluster name should be unique: %s' % (content))
self.rtp_cluster['name'] = content
elif self.element == 'protocol':
self.rtp_cluster['protocol'] = content.lower()
if self.rtp_cluster['protocol'] not in ('udp', 'unix', 'udp6'):
raise Exception("rtp_cluster protocol should be one of 'udp', 'udp6' or 'unix'")
elif self.element == 'address':
if self.rtp_cluster['protocol'] in ('udp', 'udp6'):
content = content.rsplit(':', 1)
if len(content) == 1:
self.rtp_cluster['address'] = (content[0], 22222)
else:
self.rtp_cluster['address'] = (content[0], int(content[1]))
else:
self.rtp_cluster['address'] = content
elif self.ctx[-1] == 'rtpproxy':
if self.element == 'name':
for c in self.rtp_cluster['rtpproxies']:
if 'name' in c:
if c['name'] == content:
raise Exception('rtpproxy name should be unique within rtp_cluster: %s' % (content))
self.rtpproxy['name'] = content
elif self.element == 'protocol':
self.rtpproxy['protocol'] = content.lower()
if self.rtpproxy['protocol'] not in ('udp', 'unix', 'udp6'):
raise Exception("rtpproxy protocol should be one of 'udp', 'udp6' or 'unix'")
elif self.element == 'address':
self.rtpproxy['address'] = content
elif self.element == 'wan_address':
self.rtpproxy['wan_address'] = content
elif self.element == 'lan_address':
self.rtpproxy['lan_address'] = content
elif self.element == 'cmd_out_address':
self.rtpproxy['cmd_out_address'] = content
elif self.element == 'weight':
try:
self.rtpproxy['weight'] = int(content)
except Exception:
raise Exception("wrong rtpproxy weight value, an integer is expected: %s" % (content))
if self.rtpproxy['weight'] <= 0:
raise Exception("rtpproxy weight should > 0: %s" % (content))
elif self.element == 'capacity':
try:
self.rtpproxy['capacity'] = int(content)
except Exception:
raise Exception("wrong rtpproxy capacity value, an integer is expected: %s" % (content))
if self.rtpproxy['capacity'] <= 0:
raise Exception("rtpproxy capacity should > 0: %s" % (content))
elif self.element == 'status':
self.rtpproxy['status'] = content.upper()
if self.rtpproxy['status'] != 'SUSPENDED' and self.rtpproxy['status'] != 'ACTIVE':
raise Exception("rtpproxy status should be either 'SUSPENDED' or 'ACTIVE'")
if self.ctx[-1] == 'dnconfig':
if self.element == 'inbound_address':
self.dnconfig.set_in_address(content)
elif self.element == 'dest_socket_prefix':
self.dnconfig.dest_sprefix = content
def endElement(self, name):
if name == 'rtp_cluster':
self.rtp_cluster = None
self.ctx.pop()
elif name == 'rtpproxy':
self.rtpproxy = None
self.ctx.pop()
elif name == 'disconnect_notify':
self.dnconfig = None
self.ctx.pop()
elif name == self.element:
self.element = None
def warning(self, exception):
self.warnings.append(exception)
def error(self, exception):
self.errors.append(exception)
def fatalError(self, exception):
self.errors.append(exception)
def read_cluster_config(global_config, config, debug = False):
parsed_config = []
parser = make_parser(['xml.sax.drivers2.drv_xmlproc',])
parser.setFeature(feature_namespaces, False)
try:
parser.setFeature(feature_validation, True)
validation_supported = True
except:
validation_supported = False
h = ValidateHandler(parsed_config)
parser.setContentHandler(h)
parser.setErrorHandler(h)
if validation_supported:
try:
dir_name = dirname(__file__)
if dir_name == '':
dtd = RTP_CLUSTER_CONFIG_DTD
else:
dtd = dir_name + '/' + RTP_CLUSTER_CONFIG_DTD
f = open(dtd)
dtd = f.read()
parser.feed(dtd)
except Exception as detail:
raise Exception('validation failed: %s' % (detail))
parser.feed(config)
parser.close()
if h.warnings:
for warning in h.warnings:
if debug:
global_config['_sip_logger'].write('read_cluster_config:warning: %s' % str(warning))
if h.errors:
for error in h.errors:
global_config['_sip_logger'].write('read_cluster_config:error: %s' % str(error))
raise Exception('validation failed')
if debug:
global_config['_sip_logger'].write('Parsed:\n%s' % parsed_config[0]['rtpproxies'][0])
return parsed_config
def gen_cluster_config(config):
xml = '<rtp_cluster_config>\n\n'
for cluster in config:
xml += ' <rtp_cluster>\n'
xml += ' <name>%s</name>\n' % escape(cluster['name'])
xml += ' <protocol>%s</protocol>\n' % escape(cluster['protocol'])
address = cluster['address']
if cluster['protocol'] in ('udp', 'udp6'):
xml += ' <address>%s:%d</address>\n\n' % (escape(address[0]), address[1])
else:
xml += ' <address>%s</address>\n\n' % escape(address)
dnconfig = cluster.get('dnconfig', None)
if dnconfig != None:
xml += dnconfig.__str__(' ', 2) + '\n\n'
cl_type = cluster.get('capacity_limit_soft', True)
if cl_type:
cl_type = 'soft'
else:
cl_type = 'hard'
xml += ' <capacity_limit type="%s" />\n\n' % escape(cl_type)
for proxy in cluster['rtpproxies']:
xml += ' <rtpproxy>\n'
xml += ' <name>%s</name>\n' % escape(proxy['name'])
xml += ' <protocol>%s</protocol>\n' % escape(proxy['protocol'])
xml += ' <address>%s</address>\n' % escape(proxy['address'])
xml += ' <weight>%s</weight>\n' % escape(str(proxy['weight']))
xml += ' <capacity>%s</capacity>\n' % escape(str(proxy['capacity']))
xml += ' <status>%s</status>\n' % escape(proxy['status'])
for key_name in ('wan_address', 'lan_address', 'cmd_out_address'):
if key_name in proxy:
xml += ' <%s>%s</%s>\n' % (key_name, escape(proxy[key_name]), key_name)
xml += ' </rtpproxy>\n'
xml += ' </rtp_cluster>\n\n'
xml += '</rtp_cluster_config>\n'
return xml
if __name__ == '__main__':
import sys, traceback
sys.path.append('sippy')
from sippy_lite.sippy.SipLogger import SipLogger
global_config = {}
global_config['_sip_logger'] = SipLogger('Rtp_cluster_config::selftest')
try:
global_config['_sip_logger'].write('Reading config...')
f = open('rtp_cluster.xml')
config = read_cluster_config(global_config, f.read(), True)
global_config['_sip_logger'].write('Generating config...')
config = gen_cluster_config(config)
global_config['_sip_logger'].write('Reading generated config...')
config = read_cluster_config(global_config, config, True)
except Exception as detail:
global_config['_sip_logger'].write('error: %s' % detail)
traceback.print_exc(file = sys.stderr)