From e88780a5ddbba230b500052391c1ba64b67e6a22 Mon Sep 17 00:00:00 2001 From: "Daniel P. Berrange" Date: Tue, 19 Jun 2012 14:22:44 +0100 Subject: Adjust the libvirt config classes' API contract for parsing Don't not automatically invoke the 'parse_dom' method from the LibvirtConfigObject constructor, because this is too early in construction - no child class constructors have initialized yet. Instead require the 'parse_dom' method to be invoked after the bare object has been constructed. Also make the default impl of 'parse_dom' take an etree.Element instance and validate its root element name. Add a convenient 'parse_str' method for turning a XML string into an etree.Element instance & parsing it. Change-Id: I7eda2b59869f3b4ef9dce1602cbb05f7662f4528 Signed-off-by: Daniel P. Berrange --- nova/tests/test_libvirt_config.py | 5 +++++ nova/virt/libvirt/config.py | 14 +++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/nova/tests/test_libvirt_config.py b/nova/tests/test_libvirt_config.py index 1e0818bd7..4f9970e79 100644 --- a/nova/tests/test_libvirt_config.py +++ b/nova/tests/test_libvirt_config.py @@ -53,6 +53,11 @@ class LibvirtConfigTest(LibvirtConfigBaseTest): xml = etree.tostring(root) self.assertXmlEqual(xml, "bar") + def test_config_parse(self): + inxml = "" + obj = config.LibvirtConfigObject(root_name="demo") + obj.parse_str(inxml) + class LibvirtConfigGuestTimerTest(LibvirtConfigBaseTest): def test_config_platform(self): diff --git a/nova/virt/libvirt/config.py b/nova/virt/libvirt/config.py index 3ebdf21f0..c67f11550 100644 --- a/nova/virt/libvirt/config.py +++ b/nova/virt/libvirt/config.py @@ -21,6 +21,7 @@ Classes to represent the configuration of various libvirt objects and support conversion to/from XML """ +from nova import exception from nova import log as logging from lxml import etree @@ -38,9 +39,6 @@ class LibvirtConfigObject(object): self.ns_prefix = kwargs.get('ns_prefix') self.ns_uri = kwargs.get('ns_uri') - if "xml_str" in kwargs: - self.parse_dom(kwargs.get("xml_str")) - def _text_node(self, name, value): child = etree.Element(name) child.text = str(value) @@ -53,8 +51,14 @@ class LibvirtConfigObject(object): return etree.Element("{" + self.ns_uri + "}" + self.root_name, nsmap={self.ns_prefix: self.ns_uri}) - def parse_dom(xmldoc): - raise NotImplementedError() + def parse_str(self, xmlstr): + self.parse_dom(etree.fromstring(xmlstr)) + + def parse_dom(self, xmldoc): + if self.root_name != xmldoc.tag: + raise exception.InvalidInput( + "Root element name should be '%s' not '%s'" + % (self.root_name, xmldoc.tag)) def to_xml(self, pretty_print=True): root = self.format_dom() -- cgit