[sandbox PATCH v2 05/19] Image: Refactor create function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Move the docker-related code to the DockerSource and use
the Source mechanism
---
 virt-sandbox-image/sources/DockerSource.py | 100 +++++++++++++++++++++++++++++
 virt-sandbox-image/sources/Source.py       |   4 ++
 virt-sandbox-image/virt-sandbox-image.py   |  70 ++++----------------
 3 files changed, 118 insertions(+), 56 deletions(-)

diff --git a/virt-sandbox-image/sources/DockerSource.py b/virt-sandbox-image/sources/DockerSource.py
index cf81ffe..9cd0080 100644
--- a/virt-sandbox-image/sources/DockerSource.py
+++ b/virt-sandbox-image/sources/DockerSource.py
@@ -223,5 +223,105 @@ class DockerSource(Source):
             debug("FAIL %s\n" % str(e))
             raise
 
+    def create_template(self,**args):
+        name = args['name']
+        connect = args['connect']
+        path = args['imagepath']
+        path = path if path is not None else self.default_image_path
+        format = args['format']
+        format = format if format is not None else self.default_disk_format
+
+        self._create_template(name,
+                               connect,
+                               path,
+                               format,
+                               path)
+
+    def _create_template(self,name,connect,image_path,format,destdir):
+        self._check_disk_format(format)
+        imagelist = self._get_image_list(name,destdir)
+        imagelist.reverse()
+
+        parentImage = None
+        for imagetagid in imagelist:
+            templateImage = destdir + "/" + imagetagid + "/template." + format
+            cmd = ["qemu-img","create","-f","qcow2"]
+            if parentImage is not None:
+                cmd.append("-o")
+                cmd.append("backing_fmt=qcow2,backing_file=%s" % parentImage)
+            cmd.append(templateImage)
+            if parentImage is None:
+                cmd.append("10G")
+            subprocess.call(cmd)
+
+            if parentImage is None:
+                self._format_disk(templateImage,format,connect)
+
+            self._extract_tarballs(destdir + "/" + imagetagid + "/template.",format,connect)
+            parentImage = templateImage
+
+
+    def _check_disk_format(self,format):
+        supportedFormats = ['qcow2']
+        if not format in supportedFormats:
+            raise ValueError(["Unsupported image format %s" % format])
+
+    def _get_image_list(self,name,destdir):
+        imageparent = {}
+        imagenames = {}
+        imagedirs = os.listdir(destdir)
+        for imagetagid in imagedirs:
+            indexfile = destdir + "/" + imagetagid + "/index.json"
+            if os.path.exists(indexfile):
+                with open(indexfile,"r") as f:
+                    index = json.load(f)
+                imagenames[index["name"]] = imagetagid
+            jsonfile = destdir + "/" + imagetagid + "/template.json"
+            if os.path.exists(jsonfile):
+                with open(jsonfile,"r") as f:
+                    template = json.load(f)
+                parent = template.get("parent",None)
+                if parent:
+                    imageparent[imagetagid] = parent
+        if not name in imagenames:
+            raise ValueError(["Image %s does not exist locally" %name])
+        imagetagid = imagenames[name]
+        imagelist = []
+        while imagetagid != None:
+            imagelist.append(imagetagid)
+            parent = imageparent.get(imagetagid,None)
+            imagetagid = parent
+        return imagelist
+
+    def _format_disk(self,disk,format,connect):
+        cmd = ['virt-sandbox']
+        if connect is not None:
+            cmd.append("-c")
+            cmd.append(connect)
+        params = ['--disk=file:disk_image=%s,format=%s' %(disk,format),
+                  '/sbin/mkfs.ext3',
+                  '/dev/disk/by-tag/disk_image']
+        cmd = cmd + params
+        subprocess.call(cmd)
+
+    def _extract_tarballs(self,directory,format,connect):
+        tempdir = "/mnt"
+        tarfile = directory + "tar.gz"
+        diskfile = directory + "qcow2"
+        cmd = ['virt-sandbox']
+        if connect is not None:
+            cmd.append("-c")
+            cmd.append(connect)
+        params = ['-m',
+                  'host-image:/mnt=%s,format=%s' %(diskfile,format),
+                  '--',
+                  '/bin/tar',
+                  'zxvf',
+                  '%s' %tarfile,
+                  '-C',
+                  '/mnt']
+        cmd = cmd + params
+        subprocess.call(cmd)
+
 def debug(msg):
     sys.stderr.write(msg)
diff --git a/virt-sandbox-image/sources/Source.py b/virt-sandbox-image/sources/Source.py
index 08bf335..1a63428 100644
--- a/virt-sandbox-image/sources/Source.py
+++ b/virt-sandbox-image/sources/Source.py
@@ -33,3 +33,7 @@ class Source():
     @abstractmethod
     def download_template(self,**args):
         pass
+
+    @abstractmethod
+    def create_template(self,**args):
+      pass
diff --git a/virt-sandbox-image/virt-sandbox-image.py b/virt-sandbox-image/virt-sandbox-image.py
index 2573c29..6f65445 100755
--- a/virt-sandbox-image/virt-sandbox-image.py
+++ b/virt-sandbox-image/virt-sandbox-image.py
@@ -116,59 +116,6 @@ def delete_template(name, destdir):
                 parent = None
         imagetagid = parent
 
-
-def get_image_list(name, destdir):
-    imageparent = {}
-    imagenames = {}
-    imagedirs = os.listdir(destdir)
-    for imagetagid in imagedirs:
-        indexfile = destdir + "/" + imagetagid + "/index.json"
-        if os.path.exists(indexfile):
-            with open(indexfile, "r") as f:
-                index = json.load(f)
-            imagenames[index["name"]] = imagetagid
-        jsonfile = destdir + "/" + imagetagid + "/template.json"
-        if os.path.exists(jsonfile):
-            with open(jsonfile, "r") as f:
-                template = json.load(f)
-
-            parent = template.get("parent", None)
-            if parent:
-                imageparent[imagetagid] = parent
-
-    if not name in imagenames:
-        raise ValueError(["Image %s does not exist locally" % name])
-
-    imagetagid = imagenames[name]
-    imagelist = []
-    while imagetagid != None:
-        imagelist.append(imagetagid)
-        parent = imageparent.get(imagetagid, None)
-        imagetagid = parent
-
-    return imagelist
-
-def create_template(name, imagepath, format, destdir):
-    if not format in ["qcow2"]:
-        raise ValueError(["Unsupported image format %s" % format])
-
-    imagelist = get_image_list(name, destdir)
-    imagelist.reverse()
-
-    parentImage = None
-    for imagetagid in imagelist:
-        templateImage = destdir + "/" + imagetagid + "/template." + format
-        cmd = ["qemu-img", "create", "-f", "qcow2"]
-        if parentImage is not None:
-            cmd.append("-o")
-            cmd.append("backing_fmt=qcow2,backing_file=%s" % parentImage)
-        cmd.append(templateImage)
-        if parentImage is None:
-            cmd.append("10G")
-        debug("Run %s\n" % " ".join(cmd))
-        subprocess.call(cmd)
-        parentImage = templateImage
-
 def download(args):
     try:
         dynamic_source_loader(args.source).download_template(name=args.name,
@@ -186,8 +133,13 @@ def delete(args):
     delete_template(args.name, default_template_dir)
 
 def create(args):
-    info("Creating %s from %s in format %s\n" % (args.imagepath, args.name, args.format))
-    create_template(args.name, args.imagepath, args.format, default_template_dir)
+    try:
+        dynamic_source_loader(args.source).create_template(name=args.name,
+                                                           connect=args.connect,
+                                                           imagepath=args.imagepath,
+                                                           format=args.format)
+    except Exception,e:
+        print "Create Error %s" % str(e)
 
 def requires_name(parser):
     parser.add_argument("name",
@@ -198,6 +150,10 @@ def requires_source(parser):
                         default="docker",
                         help=_("name of the template"))
 
+def requires_connect(parser):
+    parser.add_argument("-c","--connect",
+                        help=_("Connect string for libvirt"))
+
 def requires_auth_conn(parser):
     parser.add_argument("-r","--registry",
                         help=_("Url of the custom registry"))
@@ -226,10 +182,12 @@ def gen_create_args(subparser):
     parser = subparser.add_parser("create",
                                    help=_("Create image from template data"))
     requires_name(parser)
+    requires_source(parser)
+    requires_connect(parser)
     parser.add_argument("imagepath",
                         help=_("path for image"))
     parser.add_argument("format",
-                        help=_("format"))
+                        help=_("format format for image"))
     parser.set_defaults(func=create)
 
 if __name__ == '__main__':
-- 
2.1.0

--
libvir-list mailing list
libvir-list@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/libvir-list



[Index of Archives]     [Virt Tools]     [Libvirt Users]     [Lib OS Info]     [Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [KDE Users]     [Fedora Tools]