better handling for existing files checks
[tools/mic.git] / plugins / imager / raw_plugin.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright (c) 2011 Intel, Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 # for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18 import os
19 import shutil
20 import re
21 import tempfile
22
23 from mic import configmgr, pluginmgr, chroot, msger
24 from mic.utils import misc, fs_related, errors, runner
25 from mic.utils.partitionedfs import PartitionedMount
26
27 import mic.imager.raw as raw
28
29 from mic.pluginbase import ImagerPlugin
30 class RawPlugin(ImagerPlugin):
31     name = 'raw'
32
33     @classmethod
34     def do_create(self, subcmd, opts, *args):
35         """${cmd_name}: create raw image
36
37         ${cmd_usage}
38         ${cmd_option_list}
39         """
40
41         if not args:
42             raise errors.Usage("More arguments needed")
43
44         if len(args) != 1:
45             raise errors.Usage("Extra arguments given")
46
47         cfgmgr = configmgr.getConfigMgr()
48         creatoropts = cfgmgr.create
49         ksconf = args[0]
50
51         if not os.path.exists(ksconf):
52             raise errors.CreatorError("Can't find the file: %s" % ksconf)
53
54         recording_pkgs = []
55         if len(creatoropts['record_pkgs']) > 0:
56             recording_pkgs = creatoropts['record_pkgs']
57         if creatoropts['release'] is not None:
58             if 'name' not in recording_pkgs:
59                 recording_pkgs.append('name')
60             ksconf = misc.save_ksconf_file(ksconf, creatoropts['release'])
61             name = os.path.splitext(os.path.basename(ksconf))[0]
62             creatoropts['outdir'] = "%s/%s/images/%s/" % (creatoropts['outdir'], creatoropts['release'], name)
63         cfgmgr._ksconf = ksconf
64
65         # try to find the pkgmgr
66         pkgmgr = None
67         for (key, pcls) in pluginmgr.PluginMgr().get_plugins('backend').iteritems():
68             if key == creatoropts['pkgmgr']:
69                 pkgmgr = pcls
70                 break
71
72         if not pkgmgr:
73             pkgmgrs = pluginmgr.PluginMgr().get_plugins('backend').keys()
74             raise errors.CreatorError("Can't find package manager: %s (availables: %s)" % (creatoropts['pkgmgr'], ', '.join(pkgmgrs)))
75
76         creator = raw.RawImageCreator(creatoropts, pkgmgr)
77
78         if len(recording_pkgs) > 0:
79             creator._recording_pkgs = recording_pkgs
80
81         if creatoropts['release'] is None:
82             imagefile = "%s-sda.raw" % os.path.join(creator.destdir, creator.name)
83             if os.path.exists(imagefile):
84                 if msger.ask('The target image: %s already exists, cleanup and continue?' % imagefile):
85                     os.unlink(imagefile)
86                 else:
87                     raise errors.Abort('Canceled')
88
89         try:
90             creator.check_depend_tools()
91             creator.mount(None, creatoropts["cachedir"])
92             creator.install()
93             creator.configure(creatoropts["repomd"])
94             creator.unmount()
95             creator.package(creatoropts["outdir"])
96             if creatoropts['release'] is not None:
97                 creator.release_output(ksconf, creatoropts['outdir'], creatoropts['release'])
98             creator.print_outimage_info()
99
100         except errors.CreatorError:
101             raise
102         finally:
103             creator.cleanup()
104
105         msger.info("Finished.")
106         return 0
107
108     @classmethod
109     def do_chroot(cls, target):
110         img = target
111         imgsize = misc.get_file_size(img) * 1024L * 1024L
112         partedcmd = fs_related.find_binary_path("parted")
113         disk = fs_related.SparseLoopbackDisk(img, imgsize)
114         imgmnt = misc.mkdtemp()
115         imgloop = PartitionedMount({'/dev/sdb':disk}, imgmnt, skipformat = True)
116         img_fstype = "ext3"
117
118         # Check the partitions from raw disk.
119         root_mounted = False
120         partition_mounts = 0
121         for line in runner.outs([partedcmd,"-s",img,"unit","B","print"]).splitlines():
122             line = line.strip()
123
124             # Lines that start with number are the partitions,
125             # because parted can be translated we can't refer to any text lines.
126             if not line or not line[0].isdigit():
127                 continue
128
129             # Some vars have extra , as list seperator.
130             line = line.replace(",","")
131
132             # Example of parted output lines that are handled:
133             # Number  Start        End          Size         Type     File system     Flags
134             #  1      512B         3400000511B  3400000000B  primary
135             #  2      3400531968B  3656384511B  255852544B   primary  linux-swap(v1)
136             #  3      3656384512B  3720347647B  63963136B    primary  fat16           boot, lba
137
138             partition_info = re.split("\s+",line)
139
140             size = partition_info[3].split("B")[0]
141
142             if len(partition_info) < 6 or partition_info[5] in ["boot"]:
143                 # No filesystem can be found from partition line. Assuming
144                 # btrfs, because that is the only MeeGo fs that parted does
145                 # not recognize properly.
146                 # TODO: Can we make better assumption?
147                 fstype = "btrfs"
148             elif partition_info[5] in ["ext2","ext3","ext4","btrfs"]:
149                 fstype = partition_info[5]
150             elif partition_info[5] in ["fat16","fat32"]:
151                 fstype = "vfat"
152             elif "swap" in partition_info[5]:
153                 fstype = "swap"
154             else:
155                 raise errors.CreatorError("Could not recognize partition fs type '%s'." % partition_info[5])
156
157             if not root_mounted and fstype in ["ext2","ext3","ext4","btrfs"]:
158                 # TODO: Check that this is actually the valid root partition from /etc/fstab
159                 mountpoint = "/"
160                 root_mounted = True
161             elif fstype == "swap":
162                 mountpoint = "swap"
163             else:
164                 # TODO: Assing better mount points for the rest of the partitions.
165                 partition_mounts += 1
166                 mountpoint = "/media/partition_%d" % partition_mounts
167
168             if "boot" in partition_info:
169                 boot = True
170             else:
171                 boot = False
172
173             msger.verbose("Size: %s Bytes, fstype: %s, mountpoint: %s, boot: %s" % (size, fstype, mountpoint, boot))
174             # TODO: add_partition should take bytes as size parameter.
175             imgloop.add_partition((int)(size)/1024/1024, "/dev/sdb", mountpoint, fstype = fstype, boot = boot)
176
177         try:
178             imgloop.mount()
179
180         except errors.MountError:
181             imgloop.cleanup()
182             raise
183
184         try:
185             chroot.chroot(imgmnt, None,  "/bin/env HOME=/root /bin/bash")
186         except:
187             raise errors.CreatorError("Failed to chroot to %s." %img)
188         finally:
189             chroot.cleanup_after_chroot("img", imgloop, None, imgmnt)
190
191     @classmethod
192     def do_unpack(cls, srcimg):
193         srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
194         srcmnt = misc.mkdtemp("srcmnt")
195         disk = fs_related.SparseLoopbackDisk(srcimg, srcimgsize)
196         srcloop = PartitionedMount({'/dev/sdb':disk}, srcmnt, skipformat = True)
197
198         srcloop.add_partition(srcimgsize/1024/1024, "/dev/sdb", "/", "ext3", boot=False)
199         try:
200             srcloop.mount()
201
202         except errors.MountError:
203             srcloop.cleanup()
204             raise
205
206         image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "target.img")
207         args = ['dd', "if=%s" % srcloop.partitions[0]['device'], "of=%s" % image]
208
209         msger.info("`dd` image ...")
210         rc = runner.show(args)
211         srcloop.cleanup()
212         shutil.rmtree(os.path.dirname(srcmnt), ignore_errors = True)
213
214         if rc != 0:
215             raise errors.CreatorError("Failed to dd")
216         else:
217             return image