2 # Geniwrapper XML-RPC and SOAP interfaces
11 from geni.util.auth import Auth
12 from geni.util.config import *
13 from geni.util.faults import *
14 from geni.util.debug import *
16 # See "2.2 Characters" in the XML specification:
18 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
20 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
22 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
23 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
25 def xmlrpclib_escape(s, replace = string.replace):
27 xmlrpclib does not handle invalid 7-bit control characters. This
28 function augments xmlrpclib.escape, which by default only replaces
29 '&', '<', and '>' with entities.
32 # This is the standard xmlrpclib.escape function
33 s = replace(s, "&", "&")
34 s = replace(s, "<", "<")
35 s = replace(s, ">", ">",)
37 # Replace invalid 7-bit control characters with '?'
38 return s.translate(xml_escape_table)
40 def xmlrpclib_dump(self, value, write):
42 xmlrpclib cannot marshal instances of subclasses of built-in
43 types. This function overrides xmlrpclib.Marshaller.__dump so that
44 any value that is an instance of one of its acceptable types is
45 marshalled as that type.
47 xmlrpclib also cannot handle invalid 7-bit control characters. See
51 # Use our escape function
52 args = [self, value, write]
53 if isinstance(value, (str, unicode)):
54 args.append(xmlrpclib_escape)
57 # Try for an exact match first
58 f = self.dispatch[type(value)]
61 # Try for an isinstance() match
62 for Type, f in self.dispatch.iteritems():
63 if isinstance(value, Type):
66 raise TypeError, "cannot marshal %s objects" % type(value)
70 # You can't hide from me!
71 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
73 # SOAP support is optional
76 from SOAPpy.Parser import parseSOAPRPC
77 from SOAPpy.Types import faultType
78 from SOAPpy.NS import NS
79 from SOAPpy.SOAPBuilder import buildSOAP
85 def import_deep(name):
86 mod = __import__(name)
87 components = name.split('.')
88 for comp in components[1:]:
89 mod = getattr(mod, comp)
94 # flat list of method names
95 methods = geni.methods.methods
97 def __init__(self, config = "/usr/share/geniwrapper/geni/util/geni_config", encoding = "utf-8", peer_cert = None, interface = None):
98 self.encoding = encoding
100 # Better just be documenting the API
105 self.config = Config(config)
106 self.auth = Auth(peer_cert)
107 self.interface = interface
108 self.plshell = self.getPLCShell()
109 self.basedir = self.config.GENI_BASE_DIR + os.sep
110 self.server_basedir = self.basedir + os.sep + "geni" + os.sep
111 self.hrn = self.config.GENI_INTERFACE_HRN
114 def getPLCShell(self):
115 self.plauth = {'Username': self.config.GENI_PLC_USER,
116 'AuthMethod': 'password',
117 'AuthString': self.config.GENI_PLC_PASSWORD}
120 shell = PLC.Shell.Shell(globals = globals())
121 shell.AuthCheck(self.plauth)
125 plc_host = self.config.GENI_PLC_HOST
126 plc_port = self.config.GENI_PLC_PORT
127 plc_api_path = self.config.GENI_PLC_API_PATH
128 url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % \
131 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
132 shell.AuthCheck(self.plauth)
135 def fill_record_pl_info(self, record):
137 Fill in the planetlab specific fields of a Geni record. This
138 involves calling the appropraite PLC method to retrie the
139 dtabase record for the object.
141 PLC data is filled into the pl_fino field of the record.
143 @param record record to fill in field (in/out param)
145 type = record.get_type()
146 pointer = record.get_pointer()
148 # records with pointer==-1 do not have plc info associated with them.
149 # for example, the top level authority records which are
150 # authorities, but not PL "sites"
152 record.set_pl_info({})
155 if (type == "sa") or (type == "ma"):
156 pl_res = self.plshell.GetSites(self.plauth, [pointer])
157 elif (type == "slice"):
158 pl_res = self.plshell.GetSlices(self.plauth, [pointer])
159 elif (type == "user"):
160 pl_res = self.plshell.GetPersons(self.plauth, [pointer])
161 key_ids = pl_res[0]['key_ids']
162 keys = self.plshell.GetKeys(self.plauth, key_ids)
165 pubkeys = [key['key'] for key in keys]
166 pl_res[0]['keys'] = pubkeys
167 elif (type == "node"):
168 pl_res = self.plshell.GetNodes(self.plauth, [pointer])
170 raise UnknownGeniType(type)
173 # the planetlab record no longer exists
174 # TODO: delete the geni record ?
175 raise PlanetLabRecordDoesNotExist(record.get_name())
177 record.set_pl_info(pl_res[0])
180 def lookup_users(self, auth_table, user_id_list, role="*"):
182 for person_id in user_id_list:
183 user_records = auth_table.find("user", person_id, "pointer")
184 for user_record in user_records:
185 self.fill_record_info(user_record)
187 user_roles = user_record.get_pl_info().get("roles")
188 if (role=="*") or (role in user_roles):
189 record_list.append(user_record.get_name())
192 def fill_record_geni_info(self, record):
194 type = record.get_type()
196 if (type == "slice"):
197 auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
198 person_ids = record.pl_info.get("person_ids", [])
199 researchers = self.lookup_users(auth_table, person_ids)
200 geni_info['researcher'] = researchers
203 auth_table = self.auth.get_auth_table(record.get_name())
204 person_ids = record.pl_info.get("person_ids", [])
205 pis = self.lookup_users(auth_table, person_ids, "pi")
206 geni_info['pi'] = pis
207 # TODO: OrganizationName
210 auth_table = self.auth.get_auth_table(record.get_name())
211 person_ids = record.pl_info.get("person_ids", [])
212 operators = self.lookup_users(auth_table, person_ids, "tech")
213 geni_info['operator'] = operators
214 # TODO: OrganizationName
216 auth_table = self.auth.get_auth_table(record.get_name())
217 person_ids = record.pl_info.get("person_ids", [])
218 owners = self.lookup_users(auth_table, person_ids, "admin")
219 geni_info['owner'] = owners
221 elif (type == "node"):
222 geni_info['dns'] = record.pl_info.get("hostname", "")
223 # TODO: URI, LatLong, IP, DNS
225 elif (type == "user"):
226 geni_info['email'] = record.pl_info.get("email", "")
227 # TODO: PostalAddress, Phone
229 record.set_geni_info(geni_info)
231 def fill_record_info(self, record):
233 Given a geni record, fill in the PLC specific and Geni specific
234 fields in the record.
236 self.fill_record_pl_info(record)
237 self.fill_record_geni_info(record)
239 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
240 # get a list of the HRNs tht are members of the old and new records^M
242 if oldRecord.pl_info == None:
243 oldRecord.pl_info = {}
244 oldList = oldRecord.get_geni_info().get(listName, [])
247 newList = record.get_geni_info().get(listName, [])
249 # if the lists are the same, then we don't have to update anything
250 if (oldList == newList):
253 # build a list of the new person ids, by looking up each person to get
257 userRecord = self.resolve_raw("user", hrn)[0]
258 newIdList.append(userRecord.get_pointer())
260 # build a list of the old person ids from the person_ids field of the
263 oldIdList = oldRecord.plinfo.get("person_ids", [])
264 containerId = oldRecord.get_pointer()
266 # if oldRecord==None, then we are doing a Register, instead of an
269 containerId = record.get_pointer()
271 # add people who are in the new list, but not the oldList
272 for personId in newIdList:
273 if not (personId in oldIdList):
274 print "adding id", personId, "to", record.get_name()
275 addFunc(self.plauth, personId, containerId)
277 # remove people who are in the old list, but not the new list
278 for personId in oldIdList:
279 if not (personId in newIdList):
280 print "removing id", personId, "from", record.get_name()
281 delFunc(self.plauth, personId, containerId)
283 def update_membership(self, oldRecord, record):
284 if record.type == "slice":
285 self.update_membership_list(oldRecord, record, 'researcher',
286 self.plshell.AddPersonToSlice,
287 self.plshell.DeletePersonFromSlice)
288 elif record.type == "sa":
291 elif record.type == "ma":
296 def callable(self, method):
298 Return a new instance of the specified method.
301 if method not in self.methods:
302 raise GeniInvalidAPIMethod, method
304 # Get new instance of method
306 classname = method.split(".")[-1]
307 module = __import__("geni.methods." + method, globals(), locals(), [classname])
308 callablemethod = getattr(module, classname)(self)
309 return getattr(module, classname)(self)
310 except ImportError, AttributeError:
311 raise GeniInvalidAPIMethod, method
313 def call(self, source, method, *args):
315 Call the named method from the specified source with the
318 function = self.callable(method)
319 function.source = source
320 return function(*args)
322 def handle(self, source, data):
324 Handle an XML-RPC or SOAP request from the specified source.
327 # Parse request into method name and arguments
329 interface = xmlrpclib
330 (args, method) = xmlrpclib.loads(data)
331 methodresponse = True
333 if SOAPpy is not None:
335 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
338 # XXX Support named arguments
343 result = self.call(source, method, *args)
344 except Exception, fault:
345 traceback.print_exc(file = log)
346 # Handle expected faults
347 if interface == xmlrpclib:
349 methodresponse = None
350 elif interface == SOAPpy:
351 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
352 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
355 if interface == xmlrpclib:
356 if not isinstance(result, GeniFault):
359 data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
360 elif interface == SOAPpy:
361 data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)