Add progress bar for the guestfs launch method
[snf-image-creator] / image_creator / main.py
1 # Copyright 2011 GRNET S.A. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6 #
7 #   1. Redistributions of source code must retain the above
8 #      copyright notice, this list of conditions and the following
9 #      disclaimer.
10 #
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.
15 #
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.
28 #
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.
33
34 from image_creator import get_os_class
35 from image_creator import __version__ as version
36 from image_creator.disk import Disk
37 import sys
38 import os
39 import optparse
40 from pbs import dd
41
42
43 class FatalError(Exception):
44     pass
45
46
47 def check_writable_dir(option, opt_str, value, parser):
48     if not os.path.isdir(value):
49         raise OptionValueError("%s is not a valid directory name" % value)
50     setattr(parser.values, option.dest, value)
51
52
53 def parse_options(input_args):
54     usage = "Usage: %prog [options] <input_media> <name>"
55     parser = optparse.OptionParser(version=version, usage=usage)
56
57     parser.add_option("-o", "--outdir", type="string", dest="outdir",
58         default=".", action="callback", callback=check_writable_dir,
59         help="Output files to DIR [default: working dir]",
60         metavar="DIR")
61
62     parser.add_option("-f", "--force", dest="force", default=False,
63         action="store_true", help="Overwrite output files if they exist")
64
65     parser.add_option("--no-shrink", dest="shrink", default=True,
66         help="Don't shrink any partition before extracting the image",
67         action="store_false")
68
69     parser.add_option("--no-cleanup", dest="cleanup", default=True,
70         help="Don't cleanup sensitive data before extracting the image",
71         action="store_false")
72
73     parser.add_option("-u", "--upload", dest="upload", default=False,
74         help="Upload image to a pithos repository using kamaki",
75         action="store_true")
76
77     parser.add_option("-r", "--register", dest="register", default=False,
78         help="Register image to okeanos using kamaki", action="store_true")
79
80     options, args = parser.parse_args(input_args)
81
82     if len(args) != 2:
83         parser.error('input media or name are missing')
84     options.source = args[0]
85     options.name = args[1]
86
87     if not os.path.exists(options.source):
88         parser.error('Input media is not accessible')
89
90     if options.register:
91         options.upload = True
92
93     return options
94
95
96 def main():
97
98     options = parse_options(sys.argv[1:])
99
100     if os.geteuid() != 0:
101         raise FatalError("You must run %s as root" \
102                         % os.path.basename(sys.argv[0]))
103
104     if not options.force:
105         for extension in ('diskdump', 'meta'):
106             filename = "%s/%s.%s" % (options.outdir, options.name, extension)
107             if os.path.exists(filename):
108                 raise FatalError("Output file %s exists "
109                     "(use --force to overwrite it)." % filename)
110
111     disk = Disk(options.source)
112     try:
113         dev = disk.get_device()
114         dev.mount()
115         osclass = get_os_class(dev.distro, dev.ostype)
116         image_os = osclass(dev.root, dev.g)
117         metadata = image_os.get_metadata()
118         
119         if options.cleanup:
120             image_os.data_cleanup()
121
122         dev.umount()
123
124         size = options.shrink and dev.shrink() or dev.size()
125         metadata['size'] = str(size // 2 ** 20)
126
127         dd('if=%s' % dev.device,
128             'of=%s/%s.%s' % (options.outdir, options.name, 'diskdump'),
129             'bs=4M', 'count=%d' % ((size + 1) // 2 ** 22))
130
131         f = open('%s/%s.%s' % (options.outdir, options.name, 'meta'), 'w')
132         for key in metadata.keys():
133             f.write("%s=%s\n" % (key, metadata[key]))
134         f.close()
135     finally:
136         disk.cleanup()
137
138     #The image is ready, lets call kamaki if necessary
139     if options.upload:
140        pass 
141
142     return 0
143
144 COLOR_BLACK = "\033[00m"
145 COLOR_RED = "\033[1;31m"
146
147 if __name__ == '__main__':
148     try:
149         ret = main()
150         sys.exit(ret)
151     except FatalError as e:
152         print >> sys.stderr, "\n%sError: %s%s\n" % (COLOR_RED, e, COLOR_BLACK)
153         sys.exit(1)
154
155 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :