summaryrefslogtreecommitdiff
path: root/bin/heat-jeos
blob: d8f2d2b6fb800f1933de7607ec10668cfb551af0 (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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Tools to generate JEOS TDLs, build the images and register them in Glance.
"""

import ConfigParser
import gettext
from glob import glob
import logging
import optparse
import os
import os.path
import sys
import time
import traceback

from prettytable import PrettyTable


possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                   os.pardir,
                                   os.pardir))

if os.path.exists(os.path.join(possible_topdir, 'heat_jeos')):
    sys.path.insert(0, possible_topdir)

try:
    from heat_jeos import glance_clients as glance
except ImportError:
    glance = None
from heat_jeos.utils import *


def command_list(options, arguments):
    """
    List all available templates.
    """
    templates = sorted(glob('%s/*.tdl' % options.jeos_dir))
    table = PrettyTable(['Name', 'OS', 'Version', 'Architecture'])
    try:  # prettytable version 0.5 -- on Fedora 16 and 17
        table.set_field_align('Name', 'l')
    except AttributeError:  # prettytable version 0.6  -- on Ubuntu 12.04
        table.align['Name'] = 'l'
    for template_path in templates:
        table.add_row(template_metadata(template_path))
    print table


register_with_glance_message = """
Now register with Glance using:

glance add name=%s is_public=true disk_format=qcow2 container_format=bare < %s
"""


def command_create(options, arguments):
    """
    Create a new JEOS (Just Enough Operating System) image and (optionally)
    register it.

    Usage:
    heat-jeos create (<name> | --template-file=FILE) <options>

    Arguments:
    name                    Template name from `heat-jeos list`
    --template-file=FILE    Path to the template file to use
    --iso=FILE              Path to the ISO file to use as the base OS image
    --register-with-glance  Register the image with Glance after it's built

    The command must be run as root in order for libvirt to have permissions
    to create virtual machines and read the raw DVDs.

    The image ISO must be specified in the Template file under the
    `/template/os/install/iso` section or passed using the `--iso` argument.
    """
    tdl_path = None
    if len(arguments) == 0:
        tdl_path = options.template_file
    elif len(arguments) == 1:
        tdl_path = find_template_by_name(options.jeos_dir, arguments[0])

    if not tdl_path:
        logging.info('You must specify a correct template name or path.')
        sys.exit(1)

    if os.geteuid() != 0:
        logging.error("This command must be run as root")
        sys.exit(1)

    if options.register_with_glance:
        if not glance:
            logging.error("The Python Glance client is not installed. Please "
                "install python-glance for Essex or python-glanceclient for "
                "Folsom.")
            sys.exit(1)
        try:
            client = glance.client(options)
            glance.get_image(client, 'test')
        except glance.NotFoundError:
            pass
        except glance.ConnectionError:
            logging.error("Cannot connect to Glance. Please verify that it's "
                  "running.")
            sys.exit(1)
        except glance.AuthError:
            logging.error("Cannot authenticate to Keystone, please check your "
                  "credentials.")
            sys.exit(1)

    with open(tdl_path, 'r') as f:
        tdl_xml = f.read()
    oz_guest = get_oz_guest(tdl_xml)
    dsk_path, qcow2_path, image_name = target_image_paths(oz_guest)

    should_build_jeos = True
    if os.access(qcow2_path, os.R_OK):
        should_build_jeos = options.yes or prompt_bool('An existing JEOS was '
            'found on disk. Do you want to build a fresh JEOS? (y/n) ')

    if should_build_jeos:
        final_tdl = create_tdl(tdl_xml, options.iso, options.cfn_dir)

        logging.info('Creating JEOS image (%s) - '
                     'this takes approximately 10 minutes.' % image_name)
        build_jeos(get_oz_guest(final_tdl))
        print('\nGenerated image: %s' % qcow2_path)

        if not options.register_with_glance:
            print(register_with_glance_message % (image_name, qcow2_path))
            return

    if not options.register_with_glance:
        return

    logging.info('Registering JEOS image (%s) with OpenStack Glance.' %
                 image_name)
    if not os.access(qcow2_path, os.R_OK):
        logging.error('Cannot find image %s.' % qcow2_path)
        sys.exit(1)

    try:
        client = glance.client(options)
        image = glance.find_image_by_name(client, image_name)
        if image:
            delete_image = options.yes or prompt_bool('Do you want to '
                    'delete the existing JEOS in glance? (y/n) ')
            if delete_image:
                glance.delete_image(client, image)
            else:
                logging.info('No action taken')
                sys.exit(0)
        image_id = glance.register_image(client, qcow2_path, image_name,
                                  options.username, image)
        print('\nImage %s was registered with ID %s' % (image_name, image_id))
    except glance.ConnectionError, e:
        logging.error('Failed to connect to the Glance API server.')
        sys.exit(1)
    except Exception, e:
        logging.error(" Failed to add image. Got error:")
        traceback.print_exc()
        logging.warning("Note: Your image metadata may still be in the "
               "registry, but the image's status will likely be 'killed'.")
        sys.exit(1)


def prompt_bool(question):
    """
    Ask the user a yes/no question and return the answer as a bool.
    """
    while True:
        answer = raw_input(question).lower()
        if answer in ('y', 'yes'):
            return True
        if answer in ('n', 'no'):
            return False


def create_options(parser):
    """
    Sets up the CLI and config-file options that may be
    parsed and program commands.

    :param parser: The option parser
    """
    parser.add_option('-t', '--template-file',
                      default=None,
                      help="Path to the template file to build image from")
    parser.add_option('-j', '--jeos-dir',
                      default=DEFAULT_JEOS_DIR,
                      help="Path to the JEOS templates directory")
    parser.add_option('-c', '--cfn-dir',
                      default=DEFAULT_CFNTOOLS_DIR,
                      help="Path to cfntools directory")
    parser.add_option('-v', '--verbose', default=False, action="store_true",
                      help="Print more verbose output")
    parser.add_option('-d', '--debug', default=False, action="store_true",
                      help="Print more verbose output")
    parser.add_option('-s', '--iso', default=None,
                      help="Path to the ISO file to use as the base OS image")
    parser.add_option('-G', '--register-with-glance', default=False,
                      action='store_true', help="Register the image with Glance")
    parser.add_option('-y', '--yes', default=False, action="store_true",
                      help="Don't prompt for user input; assume the answer to "
                           "every question is 'yes'.")
    parser.add_option('-H', '--glance-host',
                      default=None,
                      help="Glance hostname")
    parser.add_option('-P', '--glance-port',
                      default=None,
                      help="Glance port number")
    parser.add_option('-A', '--auth_token', dest="auth_token",
                      metavar="TOKEN", default=None,
                      help="Authentication token to use to identify the "
                           "client to the heat server")
    parser.add_option('-I', '--username', dest="username",
                      metavar="USER", default=None,
                      help="User name used to acquire an authentication token")
    parser.add_option('-K', '--password', dest="password",
                      metavar="PASSWORD", default=None,
                      help="Password used to acquire an authentication token")
    parser.add_option('-T', '--tenant', dest="tenant",
                      metavar="TENANT", default=None,
                      help="Tenant name used for Keystone authentication")
    parser.add_option('-R', '--region', dest="region",
                      metavar="REGION", default=None,
                      help="Region name. When using keystone authentication "
                      "version 2.0 or later this identifies the region "
                      "name to use when selecting the service endpoint. A "
                      "region name must be provided if more than one "
                      "region endpoint is available")
    parser.add_option('-N', '--auth_url', dest="auth_url",
                      metavar="AUTH_URL", default=None,
                      help="Authentication URL")
    parser.add_option('-S', '--auth_strategy', dest="auth_strategy",
                      metavar="STRATEGY", default=None,
                      help="Authentication strategy (keystone or noauth)")


def credentials_from_env():
    return dict(username=os.getenv('OS_USERNAME'),
                password=os.getenv('OS_PASSWORD'),
                tenant=os.getenv('OS_TENANT_NAME'),
                auth_url=os.getenv('OS_AUTH_URL'),
                auth_strategy=os.getenv('OS_AUTH_STRATEGY'))


def parse_options(parser, cli_args):
    """
    Returns the parsed CLI options, command to run and its arguments, merged
    with any same-named options found in a configuration file

    :param parser: The option parser
    """
    if not cli_args:
        cli_args.append('-h')  # Show options in usage output...

    (options, args) = parser.parse_args(cli_args)
    env_opts = credentials_from_env()
    for option, env_val in env_opts.items():
        if not getattr(options, option):
            setattr(options, option, env_val)

    if not options.auth_strategy:
        options.auth_strategy = 'noauth'

    # HACK(sirp): Make the parser available to the print_help method
    # print_help is a command, so it only accepts (options, args); we could
    # one-off have it take (parser, options, args), however, for now, I think
    # this little hack will suffice
    options.__parser = parser

    if not args:
        parser.print_usage()
        sys.exit(0)

    command_name = args.pop(0)
    command = lookup_command(parser, command_name)

    if options.debug:
        logging.basicConfig(format='%(levelname)s:%(message)s',\
            level=logging.DEBUG)
        logging.debug("Debug level logging enabled")
    elif options.verbose:
        logging.basicConfig(format='%(levelname)s:%(message)s',\
            level=logging.INFO)
    else:
        logging.basicConfig(format='%(levelname)s:%(message)s',\
            level=logging.WARNING)

    options.jeos_dir = os.path.join(os.getcwd(), options.jeos_dir)
    options.cfn_dir = os.path.join(os.getcwd(), options.cfn_dir)

    return (options, command, args)


def print_help(options, args):
    """
    Print help specific to a command
    """
    parser = options.__parser

    if not args:
        parser.print_usage()

    subst = {'prog': os.path.basename(sys.argv[0])}
    docs = [lookup_command(parser, cmd).__doc__ % subst for cmd in args]
    print '\n\n'.join(docs)


def lookup_command(parser, command_name):
    commands = {
        'list': command_list,
        'create': command_create,
        'help': print_help,
    }

    try:
        command = commands[command_name]
    except KeyError:
        parser.print_usage()
        sys.exit("Unknown command: %s" % command_name)
    return command


def main():
    '''
    '''
    usage = """
%prog <command> [options] [args]

Commands:

    list            Prepare a template ready for Oz

    create          Create a JEOS image from a template

    help <command>  Output help for one of the commands below

"""

    oparser = optparse.OptionParser(version='%%prog %s'
                                    % '0.0.1',
                                    usage=usage.strip())
    create_options(oparser)
    (opts, cmd, args) = parse_options(oparser, sys.argv[1:])

    try:
        start_time = time.time()
        result = cmd(opts, args)
        end_time = time.time()
        logging.debug("Completed in %-0.4f sec." % (end_time - start_time))
        sys.exit(result)
    except (RuntimeError,
            NotImplementedError), ex:
        oparser.print_usage()
        logging.error("ERROR: %s" % ex)
        sys.exit(1)


if __name__ == '__main__':
    main()