aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/share/python/asterisk/asterisk-opensim.py
diff options
context:
space:
mode:
authorSean Dague2008-04-15 14:24:15 +0000
committerSean Dague2008-04-15 14:24:15 +0000
commit6f8ff326307ae1522e2f3163596b0bf1cdd2157f (patch)
tree4517fcd0560e9cf05ad170c0032fc9a60e7a01e4 /share/python/asterisk/asterisk-opensim.py
parentFrom: dirk husemann <hud@zurich.ibm.com> (diff)
downloadopensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.zip
opensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.tar.gz
opensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.tar.bz2
opensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.tar.xz
From: Dr Scofield <hud@zurich.ibm.com>
ansgar and i have been working on an asterisk voice module that will allow us to couple opensim with an asterisk VoIP gateway. the patch below consists of * AsteriskVoiceModule region module: alternative to the plain-vanilla VoiceModule, will make XmlRpc calls out to an asterisk-opensim frontend * asterisk-opensim.py frontend, living in share/python/asterisk, takes XmlRpc calls from the AsteriskVoiceModule * account_update: to update/create a new SIP account (on ProvisionVoiceAccountRequest) * region_update: to update/create a new "region" conference call (on ParcelVoiceInfo) * a asterisk-opensim test client, living in share/python/asterisk, to exercise astersik-opensim.py this still does not give us voice in OpenSim, but it's another step on this path...
Diffstat (limited to 'share/python/asterisk/asterisk-opensim.py')
-rw-r--r--share/python/asterisk/asterisk-opensim.py231
1 files changed, 231 insertions, 0 deletions
diff --git a/share/python/asterisk/asterisk-opensim.py b/share/python/asterisk/asterisk-opensim.py
new file mode 100644
index 0000000..aad72eb
--- /dev/null
+++ b/share/python/asterisk/asterisk-opensim.py
@@ -0,0 +1,231 @@
1#!/usr/bin/python
2# -*- encoding: utf-8 -*-
3
4from __future__ import with_statement
5
6import base64
7import ConfigParser
8import optparse
9import MySQLdb
10import re
11import SimpleXMLRPCServer
12import socket
13import sys
14import uuid
15
16class AsteriskOpenSimServerException(Exception):
17 pass
18
19class AsteriskOpenSimServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
20 '''Subclassed SimpleXMLRPCServer to be able to muck around with the socket options.
21 '''
22
23 def __init__(self, config):
24 baseURL = config.get('xmlrpc', 'baseurl')
25 match = reURLParser.match(baseURL)
26 if not match:
27 raise AsteriskOpenSimServerException('baseURL "%s" is not a well-formed URL' % (baseURL))
28
29 host = 'localhost'
30 port = 80
31 path = None
32 if match.group('host'):
33 host = match.group('host')
34 port = int(match.group('port'))
35 else:
36 host = match.group('hostonly')
37
38 self.__host = host
39 self.__port = port
40
41 SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self,(host, port))
42
43 def host(self):
44 return self.__host
45
46 def port(self):
47 return self.__port
48
49 def server_bind(self):
50 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
51 SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self)
52
53
54class AsteriskFrontend(object):
55 '''AsteriskFrontend serves as an XmlRpc function dispatcher.
56 '''
57
58 def __init__(self, config, db):
59 '''Constructor to take note of the AsteriskDB object.
60 '''
61 self.__db = db
62 try:
63 self.__debug = config.getboolean('dispatcher', 'debug')
64 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
65 self.__debug = False
66
67 def account_update(self, request):
68 '''update (or create) the SIP account data in the Asterisk RealTime DB.
69
70 OpenSim's AsteriskVoiceModule will call this method each
71 time it receives a ProvisionVoiceAccount request.
72 '''
73 print '[asterisk-opensim] account_update: new request'
74
75 for p in ['admin_password', 'username', 'password']:
76 if p not in request:
77 print '[asterisk-opensim] account_update: failed: missing password'
78 return { 'success': 'false', 'error': 'missing parameter "%s"' % (p)}
79
80 # turn base64 binary UUID into proper UUID
81 user = request['username'].partition('@')[0]
82 user = user.lstrip('x').replace('-','+').replace('_','/')
83 user = uuid.UUID(bytes = base64.standard_b64decode(user))
84
85 if self.__debug: print '[asterisk-opensim]: account_update: user %s' % user
86
87 error = self.__db.AccountUpdate(user = user, password = request['password'])
88 if error:
89 print '[asterisk-opensim]: DB.AccountUpdate failed'
90 return { 'success': 'false', 'error': error}
91
92 print '[asterisk-opensim] account_update: done'
93 return { 'success': 'true'}
94
95
96 def region_update(self, request):
97 '''update (or create) a VoIP conference call for a region.
98
99 OpenSim's AsteriskVoiceModule will call this method each time it
100 receives a ParcelVoiceInfo request.
101 '''
102 print '[asterisk-opensim] region_update: new request'
103
104 for p in ['admin_password', 'region']:
105 if p not in request:
106 print '[asterisk-opensim] region_update: failed: missing password'
107 return { 'success': 'false', 'error': 'missing parameter "%s"' % (p)}
108
109 region = request['region'].partition('@')[0]
110 if self.__debug: print '[asterisk-opensim]: region_update: region %s' % user
111
112 error = self.__db.RegionUpdate(region = region)
113 if error:
114 print '[asterisk-opensim]: DB.RegionUpdate failed'
115 return { 'success': 'false', 'error': error}
116
117 print '[asterisk-opensim] region_update: done'
118 return { 'success': 'true' }
119
120class AsteriskDBException(Exception):
121 pass
122
123class AsteriskDB(object):
124 '''AsteriskDB maintains the connection to Asterisk's MySQL database.
125 '''
126 def __init__(self, config):
127 # configure from config object
128 self.__server = config.get('mysql', 'server')
129 self.__database = config.get('mysql', 'database')
130 self.__user = config.get('mysql', 'user')
131 self.__password = config.get('mysql', 'password')
132
133 try:
134 self.__debug = config.getboolean('mysql', 'debug')
135 self.__debug_t = config.getboolean('mysql-templates', 'debug')
136 except ConfigParser.NoOptionError:
137 self.__debug = False
138
139 self.__tablesTemplate = self.__loadTemplate(config, 'tables')
140 self.__userTemplate = self.__loadTemplate(config, 'user')
141 self.__regionTemplate = self.__loadTemplate(config, 'region')
142
143 self.__mysql = MySQLdb.connect(host = self.__server, db = self.__database,
144 user = self.__user, passwd = self.__password)
145 if self.__assertDBExists():
146 raise AsteriskDBException('could not initialize DB')
147
148 def __loadTemplate(self, config, templateName):
149 template = config.get('mysql-templates', templateName)
150 t = ''
151 with open(template, 'r') as templateFile:
152 for line in templateFile:
153 line = line.rstrip('\n')
154 t += line
155 return t.split(';')
156
157
158 def __assertDBExists(self):
159 '''Assert that DB tables exist.
160 '''
161 try:
162 cursor = self.__mysql.cursor()
163 for sql in self.__tablesTemplate[:]:
164 if not sql: continue
165 sql = sql % { 'database': self.__database }
166 if self.__debug: print 'AsteriskDB.__assertDBExists: %s' % sql
167 cursor.execute(sql)
168 cursor.fetchall()
169 cursor.close()
170 except MySQLdb.Error, e:
171 if self.__debug: print 'AsteriskDB.__assertDBExists: Error %d: %s' % (e.args[0], e.args[1])
172 return e.args[1]
173 return None
174
175 def AccountUpdate(self, user, password):
176 print 'AsteriskDB.AccountUpdate: user %s' % (user)
177 try:
178 cursor = self.__mysql.cursor()
179 for sql in self.__userTemplate[:]:
180 if not sql: continue
181 sql = sql % { 'database': self.__database, 'username': user, 'password': password }
182 if self.__debug_t: print 'AsteriskDB.AccountUpdate: sql: %s' % sql
183 cursor.execute(sql)
184 cursor.fetchall()
185 cursor.close()
186 except MySQLdb.Error, e:
187 if self.__debug: print 'AsteriskDB.RegionUpdate: Error %d: %s' % (e.args[0], e.args[1])
188 return e.args[1]
189 return None
190
191 def RegionUpdate(self, region):
192 print 'AsteriskDB.RegionUpdate: region %s' % (region)
193 try:
194 cursor = self.__mysql.cursor()
195 for sql in self.__regionTemplate[:]:
196 if not sql: continue
197 sql = sql % { 'database': self.__database, 'regionname': region }
198 if self.__debug_t: print 'AsteriskDB.RegionUpdate: sql: %s' % sql
199 cursor.execute(sql)
200 res = cursor.fetchall()
201 except MySQLdb.Error, e:
202 if self.__debug: print 'AsteriskDB.RegionUpdate: Error %d: %s' % (e.args[0], e.args[1])
203 return e.args[1]
204 return None
205
206
207reURLParser = re.compile(r'^http://((?P<host>[^/]+):(?P<port>\d+)|(?P<hostonly>[^/]+))/', re.IGNORECASE)
208
209# main
210if __name__ == '__main__':
211
212 parser = optparse.OptionParser()
213 parser.add_option('-c', '--config', dest = 'config', help = 'config file', metavar = 'CONFIG')
214 (options, args) = parser.parse_args()
215
216 if not options.config:
217 parser.error('missing option config')
218 sys.exit(1)
219
220 config = ConfigParser.ConfigParser()
221 config.readfp(open(options.config))
222
223 server = AsteriskOpenSimServer(config)
224 server.register_introspection_functions()
225 server.register_instance(AsteriskFrontend(config, AsteriskDB(config)))
226
227 # get cracking
228 print '[asterisk-opensim] server ready on %s:%d' % (server.host(), server.port())
229 server.serve_forever()
230
231 sys.exit(0)