1 # Copyright 2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
11 # 2. Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following
13 # disclaimer in the documentation and/or other materials
14 # provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
34 from image_creator.util import get_command
35 from image_creator.util import try_fail_repeat
36 from image_creator.util import free_space
37 from image_creator.util import FatalError
38 from image_creator.bundle_volume import BundleVolume
39 from image_creator.image import Image
47 dd = get_command('dd')
48 dmsetup = get_command('dmsetup')
49 losetup = get_command('losetup')
50 blockdev = get_command('blockdev')
53 TMP_CANDIDATES = ['/var/tmp', os.path.expanduser('~'), '/mnt']
57 """This class represents a hard disk hosting an Operating System
59 A Disk instance never alters the source media it is created from.
60 Any change is done on a snapshot created by the device-mapper of
64 def __init__(self, source, output, tmp=None):
65 """Create a new Disk instance out of a source media. The source
66 media can be an image file, a block device or a directory.
68 self._cleanup_jobs = []
73 self.tmp = tempfile.mkdtemp(prefix='.snf_image_creator.',
74 dir=self._get_tmp_dir(tmp))
76 self._add_cleanup(shutil.rmtree, self.tmp)
78 def _get_tmp_dir(self, default=None):
79 if default is not None:
82 space = map(free_space, TMP_CANDIDATES)
86 for i, val in zip(range(len(space)), space):
91 # Return the candidate path with more available space
92 return TMP_CANDIDATES[max_idx]
94 def _add_cleanup(self, job, *args):
95 self._cleanup_jobs.append((job, args))
97 def _losetup(self, fname):
98 loop = losetup('-f', '--show', fname)
99 loop = loop.strip() # remove the new-line char
100 self._add_cleanup(try_fail_repeat, losetup, '-d', loop)
103 def _dir_to_disk(self):
104 if self.source == '/':
105 bundle = BundleVolume(self.out, self.meta)
106 image = '%s/%s.diskdump' % (self.tmp, uuid.uuid4().hex)
108 def check_unlink(path):
109 if os.path.exists(path):
112 self._add_cleanup(check_unlink, image)
113 bundle.create_image(image)
114 return self._losetup(image)
115 raise FatalError("Using a directory as media source is supported")
118 """Cleanup internal data. This needs to be called before the
122 while len(self._images):
123 image = self._images.pop()
126 # Make sure those are executed even if one of the device.destroy
127 # methods throws exeptions.
128 while len(self._cleanup_jobs):
129 job, args = self._cleanup_jobs.pop()
133 """Creates a snapshot of the original source media of the Disk
137 self.out.output("Examining source media `%s' ..." % self.source, False)
138 sourcedev = self.source
139 mode = os.stat(self.source).st_mode
140 if stat.S_ISDIR(mode):
141 self.out.success('looks like a directory')
142 return self._dir_to_disk()
143 elif stat.S_ISREG(mode):
144 self.out.success('looks like an image file')
145 sourcedev = self._losetup(self.source)
146 elif not stat.S_ISBLK(mode):
147 raise ValueError("Invalid media source. Only block devices, "
148 "regular files and directories are supported.")
150 self.out.success('looks like a block device')
152 # Take a snapshot and return it to the user
153 self.out.output("Snapshotting media source...", False)
154 size = blockdev('--getsz', sourcedev)
155 cowfd, cow = tempfile.mkstemp(dir=self.tmp)
157 self._add_cleanup(os.unlink, cow)
158 # Create cow sparse file
159 dd('if=/dev/null', 'of=%s' % cow, 'bs=512', 'seek=%d' % int(size))
160 cowdev = self._losetup(cow)
162 snapshot = uuid.uuid4().hex
163 tablefd, table = tempfile.mkstemp()
165 os.write(tablefd, "0 %d snapshot %s %s n 8" %
166 (int(size), sourcedev, cowdev))
167 dmsetup('create', snapshot, table)
168 self._add_cleanup(try_fail_repeat, dmsetup, 'remove', snapshot)
172 self.out.success('done')
173 return "/dev/mapper/%s" % snapshot
175 def get_image(self, media):
176 """Returns a newly created ImageCreator instance."""
178 image = Image(media, self.out)
179 self._images.append(image)
183 def destroy_image(self, image):
184 """Destroys an ImageCreator instance previously created by
185 get_image_creator method.
187 self._images.remove(image)
190 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :