more cleanup
[tools/mic.git] / plugins / imager / raw_plugin.py
1 #!/usr/bin/python -tt
2
3 import os, sys
4 import subprocess
5 import shutil
6 import re
7 import tempfile
8
9 from mic.pluginbase.imager_plugin import ImagerPlugin
10 import mic.utils.misc as misc
11 import mic.utils.fs_related as fs_related
12 import mic.utils.cmdln as cmdln
13 from mic.utils.errors import *
14 from mic.utils.partitionedfs import PartitionedMount
15 import mic.configmgr as configmgr
16 import mic.pluginmgr as pluginmgr
17 import mic.imager.raw as raw
18 import mic.chroot as chroot
19
20 class RawPlugin(ImagerPlugin):
21
22     @classmethod
23     def do_create(self, subcmd, opts, *args):
24         """${cmd_name}: create raw image
25
26         ${cmd_usage}
27         ${cmd_option_list}
28         """
29         if len(args) == 0:
30             return
31         if len(args) == 1:
32             ksconf = args[0]
33         else:
34             raise errors.Usage("Extra arguments given")
35
36         cfgmgr = configmgr.getConfigMgr()
37         creatoropts = cfgmgr.create
38         cfgmgr.setProperty("ksconf", ksconf)
39         plgmgr = pluginmgr.PluginMgr()
40         plgmgr.loadPlugins()
41
42         for (key, pcls) in plgmgr.getBackendPlugins():
43             if key == creatoropts['pkgmgr']:
44                 pkgmgr = pcls
45
46         if not pkgmgr:
47             raise CreatorError("Can't find backend %s" % pkgmgr)
48
49         creator = raw.RawImageCreator(creatoropts, pkgmgr)
50         try:
51             creator.check_depend_tools()
52             creator.mount(None, creatoropts["cachedir"])
53             creator.install()
54             creator.configure(creatoropts["repomd"])
55             creator.unmount()
56             creator.package(creatoropts["outdir"])
57             outimage = creator.outimage
58             creator.print_outimage_info()
59             outimage = creator.outimage
60         except CreatorError, e:
61             raise CreatorError("failed to create image : %s" % e)
62         finally:
63             creator.cleanup()
64             print "Finished."
65         return 0
66
67     @classmethod
68     def do_chroot(cls, target):
69         img = target
70         imgsize = misc.get_file_size(img) * 1024L * 1024L
71         partedcmd = fs_related.find_binary_path("parted")
72         disk = fs_related.SparseLoopbackDisk(img, imgsize)
73         imgmnt = misc.mkdtemp()
74         imgloop = PartitionedMount({'/dev/sdb':disk}, imgmnt, skipformat = True)
75         img_fstype = "ext3"
76
77         # Check the partitions from raw disk.
78         p1 = subprocess.Popen([partedcmd,"-s",img,"unit","B","print"],
79                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
80         out,err = p1.communicate()
81         lines = out.strip().split("\n")
82
83         root_mounted = False
84         partition_mounts = 0
85
86         for line in lines:
87             line = line.strip()
88             # Lines that start with number are the partitions,
89             # because parted can be translated we can't refer to any text lines.
90             if not line or not line[0].isdigit():
91                 continue
92
93             # Some vars have extra , as list seperator.
94             line = line.replace(",","")
95
96             # Example of parted output lines that are handled:
97             # Number  Start        End          Size         Type     File system     Flags
98             #  1      512B         3400000511B  3400000000B  primary
99             #  2      3400531968B  3656384511B  255852544B   primary  linux-swap(v1)
100             #  3      3656384512B  3720347647B  63963136B    primary  fat16           boot, lba
101
102             partition_info = re.split("\s+",line)
103
104             size = partition_info[3].split("B")[0]
105
106             if len(partition_info) < 6 or partition_info[5] in ["boot"]:
107                 # No filesystem can be found from partition line. Assuming
108                 # btrfs, because that is the only MeeGo fs that parted does
109                 # not recognize properly.
110                 # TODO: Can we make better assumption?
111                 fstype = "btrfs"
112             elif partition_info[5] in ["ext2","ext3","ext4","btrfs"]:
113                 fstype = partition_info[5]
114             elif partition_info[5] in ["fat16","fat32"]:
115                 fstype = "vfat"
116             elif "swap" in partition_info[5]:
117                 fstype = "swap"
118             else:
119                 raise CreatorError("Could not recognize partition fs type '%s'." % partition_info[5])
120
121             if not root_mounted and fstype in ["ext2","ext3","ext4","btrfs"]:
122                 # TODO: Check that this is actually the valid root partition from /etc/fstab
123                 mountpoint = "/"
124                 root_mounted = True
125             elif fstype == "swap":
126                 mountpoint = "swap"
127             else:
128                 # TODO: Assing better mount points for the rest of the partitions.
129                 partition_mounts += 1
130                 mountpoint = "/media/partition_%d" % partition_mounts
131
132             if "boot" in partition_info:
133                 boot = True
134             else:
135                 boot = False
136
137             print "Size: %s Bytes, fstype: %s, mountpoint: %s, boot: %s" % ( size, fstype, mountpoint, boot )
138             # TODO: add_partition should take bytes as size parameter.
139             imgloop.add_partition((int)(size)/1024/1024, "/dev/sdb", mountpoint, fstype = fstype, boot = boot)
140
141         try:
142             imgloop.mount()
143         except MountError, e:
144             imgloop.cleanup()
145             raise CreatorError("Failed to loopback mount '%s' : %s" %
146                                (img, e))
147
148         try:
149             chroot.chroot(imgmnt, None,  "/bin/env HOME=/root /bin/bash")
150         except:
151             raise CreatorError("Failed to chroot to %s." %img)
152         finally:
153             chroot.cleanup_after_chroot("img", imgloop, None, imgmnt)
154
155     @classmethod
156     def do_unpack(cls, srcimg):
157         srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
158         srcmnt = misc.mkdtemp("srcmnt")
159         disk = fs_related.SparseLoopbackDisk(srcimg, srcimgsize)
160         srcloop = PartitionedMount({'/dev/sdb':disk}, srcmnt, skipformat = True)
161
162         srcloop.add_partition(srcimgsize/1024/1024, "/dev/sdb", "/", "ext3", boot=False)
163         try:
164             srcloop.mount()
165         except MountError, e:
166             srcloop.cleanup()
167             raise CreatorError("Failed to loopback mount '%s' : %s" %
168                                (srcimg, e))
169
170         image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "target.img")
171         ddcmd = misc.find_binary_path("dd")
172         args = [ ddcmd, "if=%s" % srcloop.partitions[0]['device'], "of=%s" % image ]
173         print "dd image..."
174         rc = subprocess.call(args)
175         if rc != 0:
176             raise CreatorError("Failed to dd")
177         srcloop.cleanup()
178         shutil.rmtree(srcmnt, ignore_errors = True)
179         return image
180
181 mic_plugin = ["raw", RawPlugin]
182