Statistics
| Branch: | Tag: | Revision:

root / image_creator / main.py @ b5430a9f

History | View | Annotate | Download (6.7 kB)

1
#!/usr/bin/env python
2

    
3
# Copyright 2011 GRNET S.A. All rights reserved.
4
#
5
# Redistribution and use in source and binary forms, with or
6
# without modification, are permitted provided that the following
7
# conditions are met:
8
#
9
#   1. Redistributions of source code must retain the above
10
#      copyright notice, this list of conditions and the following
11
#      disclaimer.
12
#
13
#   2. Redistributions in binary form must reproduce the above
14
#      copyright notice, this list of conditions and the following
15
#      disclaimer in the documentation and/or other materials
16
#      provided with the distribution.
17
#
18
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
# POSSIBILITY OF SUCH DAMAGE.
30
#
31
# The views and conclusions contained in the software and
32
# documentation are those of the authors and should not be
33
# interpreted as representing official policies, either expressed
34
# or implied, of GRNET S.A.
35

    
36
from image_creator import get_os_class
37
from image_creator import __version__ as version
38
from image_creator.disk import Disk
39
from image_creator.util import get_command, error, success, output, FatalError
40
from image_creator import util
41
import sys
42
import os
43
import optparse
44

    
45
dd = get_command('dd')
46

    
47

    
48
def check_writable_dir(option, opt_str, value, parser):
49
    dirname = os.path.dirname(value)
50
    name = os.path.basename(value)
51
    if dirname and not os.path.isdir(dirname):
52
        raise FatalError("`%s' is not an existing directory" % dirname)
53

    
54
    if not name:
55
        raise FatalError("`%s' is not a valid file name" % dirname)
56

    
57
    setattr(parser.values, option.dest, value)
58

    
59

    
60
def parse_options(input_args):
61
    usage = "Usage: %prog [options] <input_media>"
62
    parser = optparse.OptionParser(version=version, usage=usage)
63

    
64
    parser.add_option("-f", "--force", dest="force", default=False,
65
        action="store_true", help="overwrite output files if they exist")
66

    
67
    parser.add_option("--no-sysprep", dest="sysprep", default=True,
68
        help="don't perform system preperation", action="store_false")
69

    
70
    parser.add_option("--no-shrink", dest="shrink", default=True,
71
        help="don't shrink any partition", action="store_false")
72

    
73
    parser.add_option("-o", "--outfile", type="string", dest="outfile",
74
        default=None, action="callback", callback=check_writable_dir,
75
        help="dump image to FILE", metavar="FILE")
76

    
77
    parser.add_option("--enable-sysprep", dest="enabled_syspreps", default=[],
78
        help="run SYSPREP operation on the input media",
79
        action="append", metavar="SYSPREP")
80

    
81
    parser.add_option("--disable-sysprep", dest="disabled_syspreps",
82
        help="prevent SYSPREP operation from running on the input media",
83
        default=[], action="append", metavar="SYSPREP")
84

    
85
    parser.add_option("--print-sysprep", dest="print_sysprep", default=False,
86
        help="print the enabled and disabled sysprep operations for this "
87
        "input media", action="store_true")
88

    
89
    parser.add_option("-s", "--silent", dest="silent", default=False,
90
        help="silent mode, only output errors", action="store_true")
91

    
92
    parser.add_option("-u", "--upload", dest="upload", type="string",
93
        default=False, help="upload the image to pithos with name FILENAME",
94
        metavar="FILENAME")
95

    
96
    parser.add_option("-r", "--register", dest="register", type="string",
97
        default=False, help="register the image to ~okeanos as IMAGENAME",
98
        metavar="IMAGENAME")
99

    
100
    options, args = parser.parse_args(input_args)
101

    
102
    if len(args) != 1:
103
        parser.error('Wrong number of arguments')
104
    options.source = args[0]
105
    if not os.path.exists(options.source):
106
        raise FatalError("Input media `%s' is not accessible" % options.source)
107

    
108
    if options.register and options.upload == False: 
109
        raise FatalError("You also need to set -u when -r option is set")
110

    
111
    return options
112

    
113

    
114
def image_creator():
115
    options = parse_options(sys.argv[1:])
116

    
117
    if options.silent:
118
        util.silent = True
119

    
120
    if options.outfile is None and not options.upload \
121
                                            and not options.print_sysprep:
122
        raise FatalError("At least one of `-o', `-u' or" \
123
                            "`--print-sysprep' must be set")
124

    
125
    output('snf-image-creator %s\n' % version)
126

    
127
    if os.geteuid() != 0:
128
        raise FatalError("You must run %s as root" \
129
                        % os.path.basename(sys.argv[0]))
130

    
131
    if not options.force and options.outfile is not None:
132
        for extension in ('', '.meta'):
133
            filename = "%s%s" % (options.outfile, extension)
134
            if os.path.exists(filename):
135
                raise FatalError("Output file %s exists "
136
                    "(use --force to overwrite it)." % filename)
137

    
138
    disk = Disk(options.source)
139
    try:
140
        dev = disk.get_device()
141
        dev.mount()
142

    
143
        osclass = get_os_class(dev.distro, dev.ostype)
144
        image_os = osclass(dev.root, dev.g)
145
        metadata = image_os.get_metadata()
146

    
147
        output()
148

    
149
        for sysprep in options.disabled_syspreps:
150
            image_os.disable_sysprep(sysprep)
151

    
152
        for sysprep in options.enabled_syspreps:
153
            image_os.enable_sysprep(sysprep)
154

    
155
        if options.print_sysprep:
156
            image_os.print_syspreps()
157
            output()
158

    
159
        if options.outfile is None and not options.upload:
160
            return 0
161

    
162
        if options.sysprep:
163
            image_os.do_sysprep()
164

    
165
        dev.umount()
166

    
167
        size = options.shrink and dev.shrink() or dev.size()
168
        metadata['SIZE'] = str(size // 2 ** 20)
169

    
170
        if options.outfile is not None:
171
            f = open('%s.%s' % (options.outfile, 'meta'), 'w')
172
            try:
173
                for key in metadata.keys():
174
                    f.write("%s=%s\n" % (key, metadata[key]))
175
            finally:
176
                f.close()
177

    
178
            dev.dump(options.outfile)
179
    finally:
180
        output('cleaning up...')
181
        disk.cleanup()
182

    
183
    return 0
184

    
185

    
186
def main():
187
    try:
188
        ret = image_creator()
189
        sys.exit(ret)
190
    except FatalError as e:
191
        error(e)
192
        sys.exit(1)
193

    
194

    
195
if __name__ == '__main__':
196
    main()
197

    
198
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :