[sandbox PATCH v3 08/22] 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   |  76 +++++-----------------
 3 files changed, 121 insertions(+), 59 deletions(-)

diff --git a/virt-sandbox-image/sources/DockerSource.py b/virt-sandbox-image/sources/DockerSource.py
index f3cf5f3..09eea85 100644
--- a/virt-sandbox-image/sources/DockerSource.py
+++ b/virt-sandbox-image/sources/DockerSource.py
@@ -210,5 +210,105 @@ class DockerSource(Source):
             debug("FAIL %s\n" % str(e))
             raise
 
+    def create_template(self,**args):
+        name = args['name']
+        connect = args['connect']
+        templatedir = args['templatedir']
+        format = args['format']
+        format = format if format is not None else self.default_disk_format
+
+        self._create_template(name,
+                               connect,
+                               templatedir,
+                               format)
+
+    def _create_template(self,name,connect,templatedir,format):
+        self._check_disk_format(format)
+        imagelist = self._get_image_list(name,templatedir)
+        imagelist.reverse()
+
+        parentImage = None
+        for imagetagid in imagelist:
+            templateImage = templatedir + "/" + 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(templatedir + "/" + 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)
+        cmd.append("-p")
+        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)
+        cmd.append("-p")
+        params = ['-m',
+                  'host-image:/mnt=%s,format=%s' %(diskfile,format),
+                  '--',
+                  '/bin/tar',
+                  'zxf',
+                  '%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 8751689..6ac08dc 100644
--- a/virt-sandbox-image/sources/Source.py
+++ b/virt-sandbox-image/sources/Source.py
@@ -29,3 +29,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 4f371d7..745401c 100755
--- a/virt-sandbox-image/virt-sandbox-image.py
+++ b/virt-sandbox-image/virt-sandbox-image.py
@@ -143,59 +143,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,
@@ -213,8 +160,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,
+                                                           templatedir=args.template_dir,
+                                                           format=args.format)
+    except Exception,e:
+        print "Create Error %s" % str(e)
 
 def requires_name(parser):
     parser.add_argument("name",
@@ -225,6 +177,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"))
@@ -258,10 +214,12 @@ def gen_create_args(subparser):
     parser = subparser.add_parser("create",
                                    help=_("Create image from template data"))
     requires_name(parser)
-    parser.add_argument("imagepath",
-                        help=_("path for image"))
-    parser.add_argument("format",
-                        help=_("format"))
+    requires_source(parser)
+    requires_connect(parser)
+    requires_template_dir(parser)
+    parser.add_argument("-f","--format",
+                        default="qcow2",
+                        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]