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