76e20a2facfb7a3086bea8c4f78faf04f712248b
[sfa.git] / wsdl / gw2wsdl.py
1 #!/usr/bin/python
2 #
3 # Sapan Bhatia <sapanb@cs.princeton.edu>
4 #
5 # Generates a WSDL for geniwrapper
6
7
8 import os, sys
9 import time
10 import pdb
11 import xml.dom.minidom
12 import xml.dom.ext
13 import apistub
14 import inspect
15
16 from types import *
17 from optparse import OptionParser
18
19 from sfa.trust.auth import Auth
20 from sfa.util.parameter import Parameter,Mixed
21
22 import globals
23
24 complex_types = {}
25 services = {}
26
27 num_types = 0
28
29 class SoapError(Exception):
30      def __init__(self, value):
31          self.value = value
32      def __str__(self):
33          return repr(self.value)
34 try:
35     set
36 except NameError:
37     from sets import Set
38     set = Set
39
40 def filter_argname(argname):
41     global interface_options
42     if (not interface_options.lite or (argname!="cred")):
43         if (argname.find('(') != -1):
44             # The name has documentation in it :-/
45             brackright = argname.split('(')[1]
46             if (brackright.find(')') == -1):
47                     raise Exception("Please fix the argument %s to be well-formed.\n"%argname)
48             inbrack = brackright.split(')')[0]
49             argname = inbrack
50     return argname
51
52 def fold_complex_type_names(acc, arg):
53     name = arg.doc
54     if (type(acc)==list):
55         acc.append(name)
56     else:
57         p_i_b = acc.doc
58         acc = [p_i_b,name]
59     return acc
60
61 def fold_complex_type(acc, arg):
62     global complex_types
63     name = name_complex_type(arg)
64     complex_types[arg]=name
65     if (type(acc)==list):
66         acc.append(name)
67     else:
68         p_i_b = name_complex_type(acc)
69         acc = [p_i_b,name]
70     return acc
71
72 def name_complex_type(arg):
73     global num_types
74     global types
75
76     types_section = types.getElementsByTagName("xsd:schema")[0]
77
78     #pdb.set_trace()
79     if (isinstance(arg, Mixed)):
80         inner_types = reduce(fold_complex_type, arg)
81         inner_names = reduce(fold_complex_type_names, arg)
82         if (inner_types[-1]=="none"):
83             inner_types=inner_types[:-1]
84             min_args = 0
85         else:
86             min_args = 1
87     
88         num_types=num_types+1
89         type_name = "Type%d"%num_types
90         complex_type = types_section.appendChild(types.createElement("xsd:complexType"))
91         complex_type.setAttribute("name", type_name)
92
93         choice = complex_type.appendChild(types.createElement("xsd:choice"))
94         for n,t in zip(inner_names,inner_types):
95             element = choice.appendChild(types.createElement("element"))
96             n = filter_argname(n)
97             element.setAttribute("name", n)
98             element.setAttribute("type", "%s"%t)
99             element.setAttribute("minOccurs","%d"%min_args)
100         return "xsdl:%s"%type_name
101     elif (isinstance(arg, Parameter)):
102         return (name_simple_type(arg.type))
103     elif type(arg) == ListType or type(arg) == TupleType:
104         inner_type = name_complex_type(arg[0]) 
105         num_types=num_types+1
106         type_name = "Type%d"%num_types
107         complex_type = types_section.appendChild(types.createElement("xsd:simpleType"))
108         type_name = filter_argname(type_name)
109         complex_type.setAttribute("name", type_name)
110         complex_content = complex_type.appendChild(types.createElement("xsd:list"))
111         complex_content.setAttribute("itemType",inner_type)
112         return "xsdl:%s"%type_name
113     elif type(arg) == DictType or arg == DictType or (inspect.isclass(arg) and issubclass(arg, dict)):
114         num_types=num_types+1
115         type_name = "Type%d"%num_types
116         complex_type = types_section.appendChild(types.createElement("xsd:complexType"))
117         type_name = filter_argname(type_name)
118         complex_type.setAttribute("name", type_name)
119         complex_content = complex_type.appendChild(types.createElement("xsd:sequence"))
120  
121         for k in arg.fields:
122             inner_type = name_complex_type(arg.fields[k]) 
123             element=complex_content.appendChild(types.createElement("xsd:element"))
124             element.setAttribute("name",k)
125             element.setAttribute("type",inner_type)
126
127         return "xsdl:%s"%type_name 
128     else:
129         return (name_simple_type(arg))
130
131 def name_simple_type(arg_type):
132     # A Parameter is reported as an instance, even though it is serialized as a type <>
133     if type(arg_type) == InstanceType:
134         return (name_simple_type(arg_type.type))
135     if arg_type == None:
136         return "none"
137     if arg_type == DictType:
138         return "xsd:anyType"
139     elif arg_type == IntType or arg_type == LongType:
140         return "xsd:int"
141     elif arg_type == bool:
142         return "xsd:boolean"
143     elif arg_type == FloatType:
144         return "xsd:double"
145     elif arg_type in StringTypes:
146         return "xsd:string"
147     else:
148        pdb.set_trace()
149        raise SoapError, "Cannot handle %s objects" % arg_type
150
151 def param_type(arg):
152     return (name_complex_type(arg))
153
154 def add_wsdl_ports_and_bindings (wsdl):
155     for method in apistub.methods:
156
157         # Skip system. methods
158         if "system." in method:
159             continue
160
161         function = apistub.callable(method) # Commented documentation
162         #lines = ["// " + line.strip() for line in function.__doc__.strip().split("\n")]
163         #print "\n".join(lines)
164         #print
165
166         
167         in_el = wsdl.firstChild.appendChild(wsdl.createElement("message"))
168         in_el.setAttribute("name", method + "_in")
169
170         for service_name in function.interfaces:
171             if (services.has_key(service_name)):
172                 if (not method in services[service_name]):
173                     services[service_name].append(method)
174             else:
175                 services[service_name]=[method]
176
177         # Arguments
178
179         if (function.accepts):
180             (min_args, max_args, defaults) = function.args()
181             for (argname,argtype) in zip(max_args,function.accepts):
182                 argname = filter_argname(argname)
183                 arg_part = in_el.appendChild(wsdl.createElement("part"))
184                 arg_part.setAttribute("name", argname)
185                 arg_part.setAttribute("type", param_type(argtype))
186                 
187         # Return type            
188         return_type = function.returns
189         out_el = wsdl.firstChild.appendChild(wsdl.createElement("message"))
190         out_el.setAttribute("name", method + "_out")
191         ret_part = out_el.appendChild(wsdl.createElement("part"))
192         ret_part.setAttribute("name", "Result")
193         ret_part.setAttribute("type", param_type(return_type))
194
195         # Port connecting arguments with return type
196
197         port_el = wsdl.firstChild.appendChild(wsdl.createElement("portType"))
198         port_el.setAttribute("name", method + "_port")
199         
200         op_el = port_el.appendChild(wsdl.createElement("operation"))
201         op_el.setAttribute("name", method)
202         inp_el=wsdl.createElement("input")
203         inp_el.setAttribute("message","tns:" + method + "_in")
204         inp_el.setAttribute("name",method+"_request")
205         op_el.appendChild(inp_el)
206         out_el = wsdl.createElement("output")
207         out_el.setAttribute("message","tns:" + method + "_out")
208         out_el.setAttribute("name",method+"_response")
209         op_el.appendChild(out_el)
210
211         # Bindings
212
213         bind_el = wsdl.firstChild.appendChild(wsdl.createElement("binding"))
214         bind_el.setAttribute("name", method + "_binding")
215         bind_el.setAttribute("type", "tns:" + method + "_port")
216         
217         soap_bind = bind_el.appendChild(wsdl.createElement("soap:binding"))
218         soap_bind.setAttribute("style", "rpc")
219         soap_bind.setAttribute("transport","http://schemas.xmlsoap.org/soap/http")
220
221         
222         wsdl_op = bind_el.appendChild(wsdl.createElement("operation"))
223         wsdl_op.setAttribute("name", method)
224         wsdl_op.appendChild(wsdl.createElement("soap:operation")).setAttribute("soapAction",
225                 "urn:" + method)
226
227         
228         wsdl_input = wsdl_op.appendChild(wsdl.createElement("input"))
229         input_soap_body = wsdl_input.appendChild(wsdl.createElement("soap:body"))
230         input_soap_body.setAttribute("use", "encoded")
231         input_soap_body.setAttribute("namespace", "urn:" + method)
232         input_soap_body.setAttribute("encodingStyle","http://schemas.xmlsoap.org/soap/encoding/")
233
234         
235         wsdl_output = wsdl_op.appendChild(wsdl.createElement("output"))
236         output_soap_body = wsdl_output.appendChild(wsdl.createElement("soap:body"))
237         output_soap_body.setAttribute("use", "encoded")
238         output_soap_body.setAttribute("namespace", "urn:" + method)
239         output_soap_body.setAttribute("encodingStyle","http://schemas.xmlsoap.org/soap/encoding/")
240         
241
242 def add_wsdl_service(wsdl):
243     for service in services.keys():
244         global interface_options
245         if (getattr(interface_options,service)):
246             service_el = wsdl.firstChild.appendChild(wsdl.createElement("service"))
247             service_el.setAttribute("name", service)
248
249             for method in services[service]:
250                     name=method
251                     servport_el = service_el.appendChild(wsdl.createElement("port"))
252                     servport_el.setAttribute("name", name + "_port")
253                     servport_el.setAttribute("binding", "tns:" + name + "_binding")
254
255                     soapaddress = servport_el.appendChild(wsdl.createElement("soap:address"))
256                     soapaddress.setAttribute("location", "%s/%s" % (globals.plc_ns,service))
257
258
259 def get_wsdl_definitions():
260     wsdl_text_header = """
261         <wsdl:definitions
262         name="geniwrapper_autogenerated"
263         targetNamespace="%s/2009/07/sfa.wsdl"
264         xmlns="http://schemas.xmlsoap.org/wsdl/"
265         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
266         xmlns:xsdl="%s/2009/07/schema"
267         xmlns:tns="%s/2009/07/sfa.wsdl"
268         xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
269         xmlns:soapenc="http://schemas.xmlsoap.org/wsdl/soap/encoding"
270         xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"/>
271         """ % (globals.plc_ns,globals.plc_ns,globals.plc_ns)
272         
273     wsdl = xml.dom.minidom.parseString(wsdl_text_header)
274     
275     return wsdl
276
277 def get_wsdl_definitions_and_types():
278     wsdl_text_header = """
279     <wsdl:definitions
280         name="geniwrapper_autogenerated"
281         targetNamespace="%s/2009/07/sfa.wsdl"
282         xmlns="http://schemas.xmlsoap.org/wsdl/"
283         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
284         xmlns:xsdl="%s/2009/07/schema"
285         xmlns:tns="%s/2009/07/sfa.wsdl"
286         xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
287         xmlns:soapenc="http://schemas.xmlsoap.org/wsdl/soap/encoding"
288         xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
289         <types>
290             <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="%s/2009/07/schema"/>
291         </types>
292     </wsdl:definitions> """ % (globals.plc_ns, globals.plc_ns, globals.plc_ns, globals.plc_ns)
293     wsdl = xml.dom.minidom.parseString(wsdl_text_header)
294     return wsdl
295
296 def main():
297     global types
298     global interface_options
299
300     parser = OptionParser()
301     parser.add_option("-r", "--registry", dest="registry", action="store_true", 
302                               help="Generate registry.wsdl", metavar="FILE")
303     parser.add_option("-s", "--slice-manager",
304                               action="store_true", dest="slicemgr", 
305                               help="Generate sm.wsdl")
306     parser.add_option("-a", "--aggregate", action="store_true", dest="aggregate",
307                               help="Generate am.wsdl")
308     parser.add_option("-l", "--lite", action="store_true", dest="lite",
309                               help="Generate LITE version of the interface, in which calls exclude credentials")
310     (interface_options, args) = parser.parse_args()
311
312     types = get_wsdl_definitions_and_types()
313     wsdl = get_wsdl_definitions()
314     add_wsdl_ports_and_bindings(wsdl)
315     wsdl_types = wsdl.importNode(types.getElementsByTagName("types")[0], True)
316     wsdl.firstChild.appendChild(wsdl_types)
317     add_wsdl_service(wsdl)
318
319     xml.dom.ext.PrettyPrint(wsdl)
320
321 if __name__ == "__main__":
322         main()