summaryrefslogtreecommitdiff
path: root/tools/mic
blob: 9dcc5bf4083b9b9df2632e2980d62d976a69759b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/usr/bin/env python

#Copyright (c) 2011 Intel, Inc.
#
#This program is free software; you can redistribute it and/or modify it
#under the terms of the GNU General Public License as published by the Free
#Software Foundation; version 2 of the License
#
#This program is distributed in the hope that it will be useful, but
#WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# pylint: disable-msg=E0611, E1101, R0201
# E0611: no name in module, some attributes are set during running, so ignore it
# E1101: %s %r has no %r member, some attributes are set during running,
#        so ignore it
# R0201: Method could be a function

"""
 This mudule is entry for mic.
 It defines a class named MicCmd inheriting Cmdln, and supplies interfaces like
 'create, chroot, convert' and also some parameters for command 'mic'.
"""
import os
import sys
import errno

from mic import msger, creator, __version__ as VERSION
from mic.utils import cmdln, misc, errors
from mic.conf import configmgr
from mic.plugin import pluginmgr


def optparser_setup(func):
    """Setup optparser for a function"""
    if not hasattr(func, "optparser"):
        func.optparser = cmdln.SubCmdOptionParser()
        func.optparser.disable_interspersed_args()
    return func


class MicCmd(cmdln.Cmdln):
    """
    Usage: mic SUBCOMMAND [OPTS] [ARGS...]

    mic Means the Image Creation tool
    Try 'mic help SUBCOMMAND' for help on a specific subcommand.

    ${command_list}
    global ${option_list}
    ${help_list}
    """
    name = 'mic'
    version = VERSION

    def print_version(self):
        """log name, verion, hostname"""

        msger.raw("%s %s (%s)" % (self.name,
                                  self.version,
                                  misc.get_hostname_distro_str()))

    def get_optparser(self):
        optparser = cmdln.CmdlnOptionParser(self, version=self.version)
        # hook optparse print_version here
        optparser.print_version = self.print_version
        optparser.add_option('-d', '--debug', action='store_true',
                             dest='debug',
                             help='print debug message')
        optparser.add_option('-v', '--verbose', action='store_true',
                             dest='verbose',
                             help='verbose information')
        optparser.add_option('-i', '--interactive', action='store_true',
                             dest='interactive', default='True',
                             help='interactive output')
        optparser.add_option('--non-interactive', action='store_false',
                             dest='interactive', default='True',
                             help='non-interactive output')
        return optparser

    def postoptparse(self):
        if self.options.interactive:
            msger.enable_interactive()
        else:
            msger.disable_interactive()

        if self.options.verbose:
            msger.set_loglevel('VERBOSE')

        if self.options.debug:
            try:
                import rpm
                rpm.setVerbosity(rpm.RPMLOG_NOTICE)
            except ImportError:
                pass

            msger.set_loglevel('DEBUG')

        self.print_version()

    def help_create(self):
        """Get help info from doc string.
           Fill symbols with real parameters
        """
        crobj = creator.Creator()
        crobj.optparser = crobj.get_optparser()
        doc = crobj.__doc__
        doc = crobj.help_reindent(doc)
        doc = crobj.help_preprocess(doc, None)
        doc = doc.replace(crobj.name, "${cmd_name}", 1)
        doc = doc.rstrip() + '\n'
        return doc

    @cmdln.alias("cr")
    def do_create(self, argv):
        """Main for creating image"""
        crobj = creator.Creator()
        crobj.main(argv[1:])

    def _root_confirm(self):
        """Make sure command is called by root
        There are a lot of commands needed to be run during creating images,
        some of them must be run with root privilege like mount, kpartx"""
        if os.geteuid() != 0:
            msger.error('Root permission is required to continue, abort')

    @cmdln.alias("cv")
    @cmdln.option("-S", "--shell",
                  action="store_true", dest="shell", default=False,
                  help="Launch shell before packaging the converted image")
    def do_convert(self, _subcmd, opts, *args):
        """${cmd_name}: convert image format
 
        Usage:
            mic convert <imagefile> <destformat>

        ${cmd_option_list}
        """
        if not args or len(args) != 2:
            # print help
            handler = self._get_cmd_handler('convert')
            if hasattr(handler, "optparser"):
                handler.optparser.print_help()
            raise errors.Usage("2 arguments and only 2 are required")

        (srcimg, destformat) = args

        if not os.path.exists(srcimg):
            raise errors.CreatorError("Cannot find the image: %s" % srcimg)

        self._root_confirm()

        configmgr.convert['shell'] = opts.shell

        srcformat = misc.get_image_type(srcimg)
        if srcformat == "ext3fsimg":
            srcformat = "loop"

        srcimager = None
        destimager = None
        for iname, icls in pluginmgr.get_plugins('imager').iteritems():
            if iname == srcformat and hasattr(icls, "do_unpack"):
                srcimager = icls
            if iname == destformat and hasattr(icls, "do_pack"):
                destimager = icls

        if (srcimager and destimager) is None:
            raise errors.CreatorError("Can't convert from %s to %s" \
                                  % (srcformat, destformat))
        maptab = {
                    "livecd": "iso",
                    "loop": "img",
                 }
        if destformat in maptab:
            imgname = os.path.splitext(os.path.basename(srcimg))[0]
            dstname = "{0}.{1}".format(imgname, maptab[destformat])
            if os.path.exists(dstname):
                if msger.ask("Converted image %s seems existed, "
                             "remove and continue?" % dstname):
                    os.unlink(dstname)
                else:
                    raise errors.Abort("Canceled")

        destimager.do_pack(srcimager.do_unpack(srcimg))

    @cmdln.alias("ch")
    @cmdln.option('-s', '--saveto',
                  action = 'store', dest = 'saveto', default = None,
                  help = "Save the unpacked image to specified dir")
    @optparser_setup
    def do_chroot(self, _subcmd, opts, *args):
        """${cmd_name}: chroot into an image

        Usage:
            mic chroot [options] <imagefile> [command [arg]...]

        ${cmd_option_list}
        """
        if not args:
            # print help
            handler = self._get_cmd_handler('chroot')
            if hasattr(handler, "optparser"):
                handler.optparser.print_help()
            return 1

        targetimage = args[0]
        if not os.path.exists(targetimage):
            raise errors.CreatorError("Cannot find the image: %s"
                                      % targetimage)

        self._root_confirm()

        configmgr.chroot['saveto'] = opts.saveto

        imagetype = misc.get_image_type(targetimage)
        if imagetype in ("ext3fsimg", "ext4fsimg", "btrfsimg"):
            imagetype = "loop"

        chrootclass = None
        for pname, pcls in pluginmgr.get_plugins('imager').iteritems():
            if pname == imagetype and hasattr(pcls, "do_chroot"):
                chrootclass = pcls
                break

        if not chrootclass:
            raise errors.CreatorError("Cannot support image type: %s" \
                                      % imagetype)

        chrootclass.do_chroot(targetimage, args[1:])


if __name__ == "__main__":
    try:
        MIC = MicCmd()
        sys.exit(MIC.main())
    except KeyboardInterrupt:
        msger.error('\n^C catched, program aborted.')
    except IOError as ioerr:
        # catch 'no space left' exception, etc
        if ioerr.errno == errno.ENOSPC:
            msger.error('\nNo space left on device')
        raise
    except errors.Usage as usage:
        msger.error(str(usage))
    except errors.Abort as  msg:
        msger.info(str(msg))
    except errors.CreatorError as err:
        if msger.get_loglevel() == 'DEBUG':
            import traceback
            msger.error(traceback.format_exc())
        else:
            msger.error(str(err))