[libvirt] [sandbox PATCH 03/11] Image: Add Hooking Mechanism

Eren Yagdiran erenyagdiran at gmail.com
Thu Jul 23 15:57:29 UTC 2015


Any custom source provider can be added to virt-sandbox-image as a source
---
 virt-sandbox-image/sources/Source.py     |  8 ++++++++
 virt-sandbox-image/virt-sandbox-image.py | 30 +++++++++++++++++++++++++++++-
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 virt-sandbox-image/sources/Source.py

diff --git a/virt-sandbox-image/sources/Source.py b/virt-sandbox-image/sources/Source.py
new file mode 100644
index 0000000..cfc75d3
--- /dev/null
+++ b/virt-sandbox-image/sources/Source.py
@@ -0,0 +1,8 @@
+#!/usr/bin/python
+
+from abc import ABCMeta, abstractmethod
+
+class Source():
+    __metaclass__ = ABCMeta
+    def __init__(self):
+        pass
diff --git a/virt-sandbox-image/virt-sandbox-image.py b/virt-sandbox-image/virt-sandbox-image.py
index 324e568..99ed46e 100644
--- a/virt-sandbox-image/virt-sandbox-image.py
+++ b/virt-sandbox-image/virt-sandbox-image.py
@@ -1,5 +1,5 @@
 #!/usr/bin/python -Es
-#
+# -*- coding: utf-8 -*-
 # Authors: Daniel P. Berrange <berrange at redhat.com>
 #          Eren Yagdiran <erenyagdiran at gmail.com>
 #
@@ -38,6 +38,34 @@ default_template_dir = "/var/lib/libvirt/templates"
 debug = True
 verbose = True
 
+sys.dont_write_bytecode = True
+
+
+##Hook mechanism starts##
+import __builtin__
+from sources.Source import Source
+__builtin__.hookHolder = {}
+def add_hook(driverName,clazz):
+    holder = __builtin__.hookHolder
+    if not issubclass(clazz,Source):
+        raise Exception("Loading %s failed. Make sure it is a subclass Of %s" %(clazz,Source))
+    holder[driverName] = clazz
+
+def init_from_name(name):
+    holder = __builtin__.hookHolder
+    return holder.get(name,None)
+
+__builtin__.add_hook = add_hook
+__builtin__.init_from_name = init_from_name
+from sources import *
+
+def dynamic_source_loader(name):
+    obj = init_from_name(name)
+    if obj == None:
+        raise IOError
+    return obj()
+##Hook mechanism ends
+
 gettext.bindtextdomain("libvirt-sandbox", "/usr/share/locale")
 gettext.textdomain("libvirt-sandbox")
 try:
-- 
2.1.0




More information about the libvir-list mailing list