refactored
[sfa.git] / sfa / rspecs / pg_rspec_converter.py
1 #!/usr/bin/python 
2 from __future__ import with_statement
3 from lxml import etree
4 from xmlbuilder import XMLBuilder
5 from StringIO import StringIO
6 from sfa.util.xrn import *
7 from sfa.rspecs.pg_rspec import PGRSpec 
8
9 xslt='''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
10 <xsl:output method="xml" indent="no"/>
11
12 <xsl:template match="/|comment()|processing-instruction()">
13     <xsl:copy>
14       <xsl:apply-templates/>
15     </xsl:copy>
16 </xsl:template>
17
18 <xsl:template match="*">
19     <xsl:element name="{local-name()}">
20       <xsl:apply-templates select="@*|node()"/>
21     </xsl:element>
22 </xsl:template>
23
24 <xsl:template match="@*">
25     <xsl:attribute name="{local-name()}">
26       <xsl:value-of select="."/>
27     </xsl:attribute>
28 </xsl:template>
29 </xsl:stylesheet>
30 '''
31
32 xslt_doc=etree.parse(StringIO(xslt))
33 transform=etree.XSLT(xslt_doc)
34
35 class PGRSpecConverter:
36
37     @staticmethod
38     def to_sfa_node(site, node, i=0):
39         cm_urn = node.get('component_manager_uuid')
40         c_name = node.get('component_name')
41         c_urn = node.get('component_uuid')
42         c_hrn, _ = urn_to_hrn(c_urn)
43         node_tag = etree.SubElement(site, "node")
44         node_tag.set("component_manager_uuid", cm_urn)
45         node_tag.set("component_name", c_name)
46         node_tag.set("component_uuid", c_urn)
47         hostname_tag = etree.SubElement(node_tag, "hostname").text = c_hrn
48         urn_tag = etree.SubElement(node_tag, "urn").text = c_hrn
49         for child in node.getchildren():
50             node_tag.append(transform(child).getroot())      
51
52     @staticmethod
53     def to_sfa_network(pg_rspec, xml): 
54         network_urn = pg_rspec.get_network()
55         network,  _ = urn_to_hrn(network_urn)
56         nodes = pg_rspec.get_nodes()
57         network_tag = etree.SubElement(xml, "network")
58         network_tag.set("name", network)
59         network_tag.set("id", network)
60         site_tag = etree.SubElement(network_tag, "Site")
61         site_tag.set("id", network)
62         name = etree.SubElement(site_tag, "name").text = network
63         i = 0
64         for node in nodes:
65            PGRSpecConverter.to_sfa_node(site_tag, node, i)
66         
67     @staticmethod
68     def to_sfa_rspec(rspec):
69         pg_rspec = PGRSpec(rspec)
70         header = '<?xml version="1.0"?>\n'
71         xml = etree.Element("RSpec", type="SFA") 
72         PGRSpecConverter.to_sfa_network(pg_rspec, xml) 
73         return header + etree.tostring(xml, pretty_print=True)
74
75 if __name__ == '__main__':
76    rspec = 'protogeni.rspec' 
77    print PGRSpecConverter.to_sfa_rspec(rspec)