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