~rackspace-ozone/rackspace-nova/development

1098.421.6 by Dan Wendlandt
replace accidental deletion in nova-mange
1
#!/usr/bin/env python
1 by Jesse Andrews
initial commit
2
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
114 by Devin Carlen
Updated licenses
4
# Copyright 2010 United States Government as represented by the
3.1.9 by Vishvananda Ishaya
Removed trailing whitespace from header
5
# Administrator of the National Aeronautics and Space Administration.
114 by Devin Carlen
Updated licenses
6
# All Rights Reserved.
7
#
8
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
9
#    not use this file except in compliance with the License. You may obtain
10
#    a copy of the License at
11
#
12
#         http://www.apache.org/licenses/LICENSE-2.0
1 by Jesse Andrews
initial commit
13
#
14
#    Unless required by applicable law or agreed to in writing, software
114 by Devin Carlen
Updated licenses
15
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17
#    License for the specific language governing permissions and limitations
18
#    under the License.
19
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
20
# Interactive shell based on Django:
21
#
22
# Copyright (c) 2005, the Lawrence Journal-World
23
# All rights reserved.
24
#
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
25
# Redistribution and use in source and binary forms, with or without
26
# modification, are permitted provided that the following conditions are met:
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
27
#
28
#     1. Redistributions of source code must retain the above copyright notice,
29
#        this list of conditions and the following disclaimer.
30
#
31
#     2. Redistributions in binary form must reproduce the above copyright
32
#        notice, this list of conditions and the following disclaimer in the
33
#        documentation and/or other materials provided with the distribution.
34
#
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
35
#     3. Neither the name of Django nor the names of its contributors may be
36
#        used to endorse or promote products derived from this software without
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
37
#        specific prior written permission.
38
#
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
39
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
40
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
41
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
42
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
43
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
45
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
46
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
47
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
48
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
49
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
50
51
1 by Jesse Andrews
initial commit
52
"""
53
  CLI interface for nova management.
54
"""
55
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
56
import ast
454.2.2 by jaypipes at gmail
For some reason, I forgot to commit the other endpoints...
57
import gettext
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
58
import glob
59
import json
1098.262.2 by John Tran
added warning when size of subnet(s) being created are larger than FLAG.network_size in attempt to alleviate confusion. For example, currently when 'nova-manage network create foo 192.168.0.0/16', the result is that it creates a 192.168.0.0/24 instead without any indication to why.
60
import math
1098.84.1 by Chuck Short
Remove ipy from nova-manage and use netaddr
61
import netaddr
1098.421.1 by Dan Wendlandt
pulling all qmanager changes into a branch based on trunk, as they were previously stacked on top of melange
62
from optparse import OptionParser
265.1.1 by Soren Hansen
Make the scripts in bin/ detect if they're being run from a bzr checkout
63
import os
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
64
import StringIO
1 by Jesse Andrews
initial commit
65
import sys
139.2.2 by Jesse Andrews
reorder imports spacing
66
import time
1 by Jesse Andrews
initial commit
67
237.7.1 by Vishvananda Ishaya
floating ip commands
68
265.1.1 by Soren Hansen
Make the scripts in bin/ detect if they're being run from a bzr checkout
69
# If ../nova/__init__.py exists, add ../ to Python search path, so that
70
# it will override what happens to be installed in /usr/(local/)lib/python...
1005.1.1 by Josh Kearney
Pylinted nova-manage
71
POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
265.1.1 by Soren Hansen
Make the scripts in bin/ detect if they're being run from a bzr checkout
72
                                   os.pardir,
73
                                   os.pardir))
1005.1.1 by Josh Kearney
Pylinted nova-manage
74
if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'nova', '__init__.py')):
75
    sys.path.insert(0, POSSIBLE_TOPDIR)
265.1.1 by Soren Hansen
Make the scripts in bin/ detect if they're being run from a bzr checkout
76
454.2.2 by jaypipes at gmail
For some reason, I forgot to commit the other endpoints...
77
gettext.install('nova', unicode=1)
78
350.1.1 by Vishvananda Ishaya
add scrub command to clean up networks and sec groups
79
from nova import context
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
80
from nova import crypto
237.1.90 by Vishvananda Ishaya
removed model from nova-manage
81
from nova import db
237.10.13 by Vishvananda Ishaya
manage command for project quotas
82
from nova import exception
1 by Jesse Andrews
initial commit
83
from nova import flags
1084.2.33 by William Wolf
moved utils functions into nova/image/
84
from nova import image
706.2.15 by Vishvananda Ishaya
switch to explicit call to logging.setup()
85
from nova import log as logging
237.10.13 by Vishvananda Ishaya
manage command for project quotas
86
from nova import quota
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
87
from nova import rpc
1 by Jesse Andrews
initial commit
88
from nova import utils
1033.1.1 by Ken Pepple
added nova version output to usage printout for nova-manage
89
from nova import version
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
90
from nova import vsa
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
91
from nova.api.ec2 import ec2utils
145.2.1 by Vishvananda Ishaya
Massive refactor of users.py
92
from nova.auth import manager
27 by andy
re-added cloudpipe
93
from nova.cloudpipe import pipelib
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
94
from nova.compute import instance_types
556.5.1 by Andy Smith
add support for database migration
95
from nova.db import migration
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
96
from nova.volume import volume_types
573.1.1 by Andy Smith
revert live_migration branch
97
1 by Jesse Andrews
initial commit
98
FLAGS = flags.FLAGS
316.9.17 by Vishvananda Ishaya
get flags for nova-manage and fix a couple more deprecations
99
flags.DECLARE('fixed_range', 'nova.network.manager')
100
flags.DECLARE('num_networks', 'nova.network.manager')
101
flags.DECLARE('network_size', 'nova.network.manager')
102
flags.DECLARE('vlan_start', 'nova.network.manager')
103
flags.DECLARE('vpn_start', 'nova.network.manager')
462.1.1 by NTT PF Lab.
Support IPv6
104
flags.DECLARE('fixed_range_v6', 'nova.network.manager')
1098.39.1 by Josh Kearney
Add the option to specify a default IPv6 gateway.
105
flags.DECLARE('gateway_v6', 'nova.network.manager')
1027.1.7 by Brian Lamar
Updated the value of the nova-manager libvirt_type
106
flags.DECLARE('libvirt_type', 'nova.virt.libvirt.connection')
724.1.2 by termie
add help back to the scripts that don't use service.py
107
flags.DEFINE_flag(flags.HelpFlag())
108
flags.DEFINE_flag(flags.HelpshortFlag())
109
flags.DEFINE_flag(flags.HelpXMLFlag())
80 by Vishvananda Ishaya
Added admin command to restart networks
110
462.1.16 by Hisaharu Ishii
Fixed for pep8
111
1092.2.5 by Lvov Maxim
decorators for action methods added
112
# Decorators for actions
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
113
def args(*args, **kwargs):
1092.2.5 by Lvov Maxim
decorators for action methods added
114
    def _decorator(func):
115
        func.__dict__.setdefault('options', []).insert(0, (args, kwargs))
116
        return func
117
    return _decorator
118
1098.201.18 by Lvov Maxim
fix pep8
119
577.2.4 by Anthony Young
per vish's feedback, allow admin to specify volume id in any of the
120
def param2id(object_id):
121
    """Helper function to convert various id types to internal id.
122
    args: [object_id], e.g. 'vol-0000000a' or 'volume-0000000a' or '10'
123
    """
124
    if '-' in object_id:
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
125
        return ec2utils.ec2_id_to_id(object_id)
577.2.4 by Anthony Young
per vish's feedback, allow admin to specify volume id in any of the
126
    else:
127
        return int(object_id)
128
129
27 by andy
re-added cloudpipe
130
class VpnCommands(object):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
131
    """Class for managing VPNs."""
132
27 by andy
re-added cloudpipe
133
    def __init__(self):
145.2.1 by Vishvananda Ishaya
Massive refactor of users.py
134
        self.manager = manager.AuthManager()
246.8.1 by Eric Day
Various loose ends for endpoint and tornado removal cleanup, including cloudpipe API addition, rpc.call() cleanup by removing tornado ioloop, and fixing bin/* programs. Tornado still exists as part of some test cases and those should be reworked to not require it.
135
        self.pipe = pipelib.CloudPipe()
27 by andy
re-added cloudpipe
136
1098.201.18 by Lvov Maxim
fix pep8
137
    @args('--project', dest="project", metavar='<Project name>',
138
            help='Project name')
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
139
    def list(self, project=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
140
        """Print a listing of the VPN data for one or all projects."""
1098.364.2 by Vishvananda Ishaya
make admin context the default, clean up pipelib
141
        print "WARNING: This method only works with deprecated auth"
40 by Vishvananda Ishaya
change pipelib to work with projects
142
        print "%-12s\t" % 'project',
316.8.1 by Ewan Mellor
Bug #654025: nova-manage project zip and nova-manage vpn list broken by change in DB semantics when networks are missing
143
        print "%-20s\t" % 'ip:port',
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
144
        print "%-20s\t" % 'private_ip',
27 by andy
re-added cloudpipe
145
        print "%s" % 'state'
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
146
        if project:
147
            projects = [self.manager.get_project(project)]
148
        else:
149
            projects = self.manager.get_projects()
396.6.5 by Vishvananda Ishaya
add vpn ping and optimize vpn list
150
            # NOTE(vish): This hits the database a lot.  We could optimize
151
            #             by getting all networks in one query and all vpns
152
            #             in aother query, then doing lookups by project
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
153
        for project in projects:
40 by Vishvananda Ishaya
change pipelib to work with projects
154
            print "%-12s\t" % project.name,
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
155
            ipport = "%s:%s" % (project.vpn_ip, project.vpn_port)
156
            print "%-20s\t" % ipport,
396.6.5 by Vishvananda Ishaya
add vpn ping and optimize vpn list
157
            ctxt = context.get_admin_context()
158
            vpn = db.instance_get_project_vpn(ctxt, project.id)
27 by andy
re-added cloudpipe
159
            if vpn:
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
160
                address = None
396.6.5 by Vishvananda Ishaya
add vpn ping and optimize vpn list
161
                state = 'down'
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
162
                if vpn.get('fixed_ip', None):
163
                    address = vpn['fixed_ip']['address']
396.6.6 by Vishvananda Ishaya
don't error on edge case where vpn has been launched but fails to get a network
164
                if project.vpn_ip and utils.vpn_ping(project.vpn_ip,
165
                                                     project.vpn_port):
396.6.5 by Vishvananda Ishaya
add vpn ping and optimize vpn list
166
                    state = 'up'
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
167
                print address,
168
                print vpn['host'],
1007.2.1 by Vishvananda Ishaya
fix display of vpn instance id and add output rule so it can be tested from network host
169
                print ec2utils.id_to_ec2_id(vpn['id']),
1098.410.1 by Vishvananda Ishaya
remove extra references to state_description
170
                print vpn['vm_state'],
396.6.5 by Vishvananda Ishaya
add vpn ping and optimize vpn list
171
                print state
27 by andy
re-added cloudpipe
172
            else:
173
                print None
174
175
    def spawn(self):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
176
        """Run all VPNs."""
1098.364.2 by Vishvananda Ishaya
make admin context the default, clean up pipelib
177
        print "WARNING: This method only works with deprecated auth"
40 by Vishvananda Ishaya
change pipelib to work with projects
178
        for p in reversed(self.manager.get_projects()):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
179
            if not self._vpn_for(p.id):
180
                print 'spawning %s' % p.id
1098.364.2 by Vishvananda Ishaya
make admin context the default, clean up pipelib
181
                self.pipe.launch_vpn_instance(p.id, p.project_manager_id)
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
182
                time.sleep(10)
27 by andy
re-added cloudpipe
183
1098.201.18 by Lvov Maxim
fix pep8
184
    @args('--project', dest="project_id", metavar='<Project name>',
185
            help='Project name')
1098.364.2 by Vishvananda Ishaya
make admin context the default, clean up pipelib
186
    @args('--user', dest="user_id", metavar='<user name>', help='User name')
187
    def run(self, project_id, user_id):
188
        """Start the VPN for a given project and user."""
189
        if not user_id:
190
            print "WARNING: This method only works with deprecated auth"
191
            user_id = self.manager.get_project(project_id).project_manager_id
192
        self.pipe.launch_vpn_instance(project_id, user_id)
27 by andy
re-added cloudpipe
193
1098.201.18 by Lvov Maxim
fix pep8
194
    @args('--project', dest="project_id", metavar='<Project name>',
195
            help='Project name')
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
196
    @args('--ip', dest="ip", metavar='<IP Address>', help='IP Address')
197
    @args('--port', dest="port", metavar='<Port>', help='Port')
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
198
    def change(self, project_id, ip, port):
199
        """Change the ip and port for a vpn.
200
742.1.19 by Trey Morris
fixed_ip disassociate now also unsets mac_address_id
201
        this will update all networks associated with a project
202
        not sure if that's the desired behavior or not, patches accepted
203
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
204
        """
742.1.19 by Trey Morris
fixed_ip disassociate now also unsets mac_address_id
205
        # TODO(tr3buchet): perhaps this shouldn't update all networks
206
        # associated with a project in the future
207
        admin_context = context.get_admin_context()
208
        networks = db.project_get_networks(admin_context, project_id)
209
        for network in networks:
210
            db.network_update(admin_context,
211
                              network['id'],
212
                              {'vpn_public_address': ip,
213
                               'vpn_public_port': int(port)})
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
214
215
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
216
class ShellCommands(object):
270.1.3 by Vishvananda Ishaya
bpython is amazing
217
    def bpython(self):
218
        """Runs a bpython shell.
219
220
        Falls back to Ipython/python shell if unavailable"""
221
        self.run('bpython')
222
223
    def ipython(self):
224
        """Runs an Ipython shell.
225
226
        Falls back to Python shell if unavailable"""
227
        self.run('ipython')
228
229
    def python(self):
270.1.5 by Vishvananda Ishaya
typo s/an/a
230
        """Runs a python shell.
270.1.3 by Vishvananda Ishaya
bpython is amazing
231
232
        Falls back to Python shell if unavailable"""
233
        self.run('python')
234
1098.201.18 by Lvov Maxim
fix pep8
235
    @args('--shell', dest="shell", metavar='<bpython|ipython|python >',
236
            help='Python shell')
270.1.3 by Vishvananda Ishaya
bpython is amazing
237
    def run(self, shell=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
238
        """Runs a Python interactive interpreter."""
270.1.3 by Vishvananda Ishaya
bpython is amazing
239
        if not shell:
240
            shell = 'bpython'
241
242
        if shell == 'bpython':
243
            try:
244
                import bpython
245
                bpython.embed()
246
            except ImportError:
247
                shell = 'ipython'
248
        if shell == 'ipython':
249
            try:
250
                import IPython
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
251
                # Explicitly pass an empty list as arguments, because
252
                # otherwise IPython would use sys.argv from this script.
270.1.3 by Vishvananda Ishaya
bpython is amazing
253
                shell = IPython.Shell.IPShell(argv=[])
254
                shell.mainloop()
255
            except ImportError:
256
                shell = 'python'
257
258
        if shell == 'python':
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
259
            import code
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
260
            try:
261
                # Try activating rlcompleter, because it's handy.
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
262
                import readline
263
            except ImportError:
264
                pass
265
            else:
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
266
                # We don't have to wrap the following import in a 'try',
267
                # because we already know 'readline' was imported successfully.
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
268
                import rlcompleter
269
                readline.parse_and_bind("tab:complete")
270
            code.interact()
271
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
272
    @args('--path', dest='path', metavar='<path>', help='Script path')
270.1.2 by Jesse Andrews
now we can run files - thanks vish
273
    def script(self, path):
274
        """Runs the script from the specifed path with flags set properly.
275
        arguments: path"""
276
        exec(compile(open(path).read(), path, 'exec'), locals(), globals())
277
1098.487.3 by paul at openstack
fixed grant user, added stdout support
278
    @args('--filename', dest='filename', metavar='<path>', default=False,
279
          help='Export file path')
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
280
    def export(self, filename):
281
        """Export Nova users into a file that can be consumed by Keystone"""
1098.487.3 by paul at openstack
fixed grant user, added stdout support
282
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
283
        def create_file(filename):
1098.487.3 by paul at openstack
fixed grant user, added stdout support
284
            data = generate_data()
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
285
            with open(filename, 'w') as f:
286
                f.write(data.getvalue())
287
288
        def tenants(data, am):
289
            for project in am.get_projects():
290
                print >> data, ("tenant add '%s'" %
1098.487.2 by paul at openstack
minor changes to credentials for the correct format
291
                               (project.name))
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
292
                for u in project.member_ids:
293
                    user = am.get_user(u)
294
                    print >> data, ("user add '%s' '%s' '%s'" %
1098.487.2 by paul at openstack
minor changes to credentials for the correct format
295
                                   (user.name, user.access, project.name))
296
                    print >> data, ("credentials add 'EC2' '%s:%s' '%s' '%s'" %
297
                            (user.access, project.id, user.secret, project.id))
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
298
299
        def roles(data, am):
300
            for role in am.get_roles():
301
                print >> data, ("role add '%s'" % (role))
302
303
        def grant_roles(data, am):
304
            roles = am.get_roles()
305
            for project in am.get_projects():
306
                for u in project.member_ids:
307
                    user = am.get_user(u)
1098.487.3 by paul at openstack
fixed grant user, added stdout support
308
                    for role in db.user_get_roles_for_project(ctxt, u,
309
                                                              project.id):
310
                        print >> data, ("role grant '%s', '%s', '%s')," %
311
                                       (user.name, role, project.name))
312
            print >> data
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
313
1098.487.3 by paul at openstack
fixed grant user, added stdout support
314
        def generate_data():
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
315
            data = StringIO.StringIO()
316
            am = manager.AuthManager()
317
            tenants(data, am)
318
            roles(data, am)
1098.487.3 by paul at openstack
fixed grant user, added stdout support
319
            grant_roles(data, am)
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
320
            data.seek(0)
321
            return data
322
1098.487.3 by paul at openstack
fixed grant user, added stdout support
323
        ctxt = context.get_admin_context()
324
        if filename:
325
            create_file(filename)
326
        else:
327
            data = generate_data()
328
            print data.getvalue()
1098.487.1 by paul at openstack
exporting auth to keystone (users, projects/tenants, roles, credentials)
329
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
330
94 by andy
more commands in nova-manage for projects and roles
331
class RoleCommands(object):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
332
    """Class for managing roles."""
333
94 by andy
more commands in nova-manage for projects and roles
334
    def __init__(self):
145.2.1 by Vishvananda Ishaya
Massive refactor of users.py
335
        self.manager = manager.AuthManager()
94 by andy
more commands in nova-manage for projects and roles
336
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
337
    @args('--user', dest="user", metavar='<user name>', help='User name')
338
    @args('--role', dest="role", metavar='<user role>', help='User role')
1098.201.18 by Lvov Maxim
fix pep8
339
    @args('--project', dest="project", metavar='<Project name>',
340
            help='Project name')
94 by andy
more commands in nova-manage for projects and roles
341
    def add(self, user, role, project=None):
342
        """adds role to user
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
343
        if project is specified, adds project specific role"""
1098.80.1 by John Tran
nova-manage checks if user is member of proj, prior to adding role for that project
344
        if project:
345
            projobj = self.manager.get_project(project)
346
            if not projobj.has_member(user):
347
                print "%s not a member of %s" % (user, project)
348
                return
94 by andy
more commands in nova-manage for projects and roles
349
        self.manager.add_role(user, role, project)
350
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
351
    @args('--user', dest="user", metavar='<user name>', help='User name')
352
    @args('--role', dest="role", metavar='<user role>', help='User role')
1098.201.18 by Lvov Maxim
fix pep8
353
    @args('--project', dest="project", metavar='<Project name>',
354
            help='Project name')
94 by andy
more commands in nova-manage for projects and roles
355
    def has(self, user, role, project=None):
356
        """checks to see if user has role
357
        if project is specified, returns True if user has
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
358
        the global role and the project role"""
94 by andy
more commands in nova-manage for projects and roles
359
        print self.manager.has_role(user, role, project)
360
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
361
    @args('--user', dest="user", metavar='<user name>', help='User name')
362
    @args('--role', dest="role", metavar='<user role>', help='User role')
1098.201.18 by Lvov Maxim
fix pep8
363
    @args('--project', dest="project", metavar='<Project name>',
364
            help='Project name')
94 by andy
more commands in nova-manage for projects and roles
365
    def remove(self, user, role, project=None):
366
        """removes role from user
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
367
        if project is specified, removes project specific role"""
94 by andy
more commands in nova-manage for projects and roles
368
        self.manager.remove_role(user, role, project)
1 by Jesse Andrews
initial commit
369
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
370
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
371
def _db_error(caught_exception):
372
    print caught_exception
373
    print _("The above error may show that the database has not "
374
            "been created.\nPlease create a database using "
794.1.1 by Soren Hansen
Fix instructions for setting up the initial database.
375
            "'nova-manage db sync' before running this command.")
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
376
    exit(1)
377
583.4.8 by Vishvananda Ishaya
fix pep8 issue (and my commit hook that didn't catch it)
378
1 by Jesse Andrews
initial commit
379
class UserCommands(object):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
380
    """Class for managing users."""
381
237.10.13 by Vishvananda Ishaya
manage command for project quotas
382
    @staticmethod
383
    def _print_export(user):
384
        """Print export variables to use with API."""
385
        print 'export EC2_ACCESS_KEY=%s' % user.access
386
        print 'export EC2_SECRET_KEY=%s' % user.secret
387
1 by Jesse Andrews
initial commit
388
    def __init__(self):
145.2.1 by Vishvananda Ishaya
Massive refactor of users.py
389
        self.manager = manager.AuthManager()
1 by Jesse Andrews
initial commit
390
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
391
    @args('--name', dest="name", metavar='<admin name>', help='Admin name')
392
    @args('--access', dest="access", metavar='<access>', help='Access')
393
    @args('--secret', dest="secret", metavar='<secret>', help='Secret')
1 by Jesse Andrews
initial commit
394
    def admin(self, name, access=None, secret=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
395
        """creates a new admin and prints exports"""
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
396
        try:
397
            user = self.manager.create_user(name, access, secret, True)
583.4.5 by Vishvananda Ishaya
wrap sqlalchemy exceptions in a generic error
398
        except exception.DBError, e:
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
399
            _db_error(e)
237.10.13 by Vishvananda Ishaya
manage command for project quotas
400
        self._print_export(user)
1 by Jesse Andrews
initial commit
401
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
402
    @args('--name', dest="name", metavar='<name>', help='User name')
403
    @args('--access', dest="access", metavar='<access>', help='Access')
404
    @args('--secret', dest="secret", metavar='<secret>', help='Secret')
1 by Jesse Andrews
initial commit
405
    def create(self, name, access=None, secret=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
406
        """creates a new user and prints exports"""
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
407
        try:
408
            user = self.manager.create_user(name, access, secret, False)
583.4.5 by Vishvananda Ishaya
wrap sqlalchemy exceptions in a generic error
409
        except exception.DBError, e:
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
410
            _db_error(e)
237.10.13 by Vishvananda Ishaya
manage command for project quotas
411
        self._print_export(user)
1 by Jesse Andrews
initial commit
412
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
413
    @args('--name', dest="name", metavar='<name>', help='User name')
1 by Jesse Andrews
initial commit
414
    def delete(self, name):
415
        """deletes an existing user
416
        arguments: name"""
417
        self.manager.delete_user(name)
418
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
419
    @args('--name', dest="name", metavar='<admin name>', help='User name')
1 by Jesse Andrews
initial commit
420
    def exports(self, name):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
421
        """prints access and secrets for user in export format"""
1 by Jesse Andrews
initial commit
422
        user = self.manager.get_user(name)
423
        if user:
237.10.13 by Vishvananda Ishaya
manage command for project quotas
424
            self._print_export(user)
1 by Jesse Andrews
initial commit
425
        else:
426
            print "User %s doesn't exist" % name
427
428
    def list(self):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
429
        """lists all users"""
1 by Jesse Andrews
initial commit
430
        for user in self.manager.get_users():
431
            print user.name
432
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
433
    @args('--name', dest="name", metavar='<name>', help='User name')
1098.201.18 by Lvov Maxim
fix pep8
434
    @args('--access', dest="access_key", metavar='<access>',
435
            help='Access key')
436
    @args('--secret', dest="secret_key", metavar='<secret>',
437
            help='Secret key')
438
    @args('--is_admin', dest='is_admin', metavar="<'T'|'F'>",
439
            help='Is admin?')
292.6.3 by Todd Willey
Hook the AuthManger#modify_user method into nova-manage commands.
440
    def modify(self, name, access_key, secret_key, is_admin):
441
        """update a users keys & admin flag
442
        arguments: accesskey secretkey admin
443
        leave any field blank to ignore it, admin should be 'T', 'F', or blank
444
        """
445
        if not is_admin:
446
            is_admin = None
447
        elif is_admin.upper()[0] == 'T':
448
            is_admin = True
449
        else:
450
            is_admin = False
451
        self.manager.modify_user(name, access_key, secret_key, is_admin)
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
452
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
453
    @args('--name', dest="user_id", metavar='<name>', help='User name')
1098.201.18 by Lvov Maxim
fix pep8
454
    @args('--project', dest="project_id", metavar='<Project name>',
455
            help='Project name')
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
456
    def revoke(self, user_id, project_id=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
457
        """revoke certs for a user"""
396.6.1 by Vishvananda Ishaya
Per-project vpns, certificates, and revocation
458
        if project_id:
459
            crypto.revoke_certs_by_user_and_project(user_id, project_id)
460
        else:
461
            crypto.revoke_certs_by_user(user_id)
462
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
463
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
464
class ProjectCommands(object):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
465
    """Class for managing projects."""
466
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
467
    def __init__(self):
145.2.1 by Vishvananda Ishaya
Massive refactor of users.py
468
        self.manager = manager.AuthManager()
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
469
1098.201.18 by Lvov Maxim
fix pep8
470
    @args('--project', dest="project_id", metavar='<Project name>',
471
            help='Project name')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
472
    @args('--user', dest="user_id", metavar='<name>', help='User name')
350.1.2 by Vishvananda Ishaya
call stuff project_id instead of project
473
    def add(self, project_id, user_id):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
474
        """Adds user to project"""
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
475
        try:
476
            self.manager.add_to_project(user_id, project_id)
1072.3.3 by Eldar Nugaev
style fixing
477
        except exception.UserNotFound as ex:
478
            print ex
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
479
            raise
94 by andy
more commands in nova-manage for projects and roles
480
1098.201.18 by Lvov Maxim
fix pep8
481
    @args('--project', dest="name", metavar='<Project name>',
482
            help='Project name')
483
    @args('--user', dest="project_manager", metavar='<user>',
484
            help='Project manager')
485
    @args('--desc', dest="description", metavar='<description>',
486
            help='Description')
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
487
    def create(self, name, project_manager, description=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
488
        """Creates a new project"""
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
489
        try:
490
            self.manager.create_project(name, project_manager, description)
1072.3.3 by Eldar Nugaev
style fixing
491
        except exception.UserNotFound as ex:
492
            print ex
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
493
            raise
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
494
1098.201.18 by Lvov Maxim
fix pep8
495
    @args('--project', dest="name", metavar='<Project name>',
496
            help='Project name')
497
    @args('--user', dest="project_manager", metavar='<user>',
498
            help='Project manager')
499
    @args('--desc', dest="description", metavar='<description>',
500
            help='Description')
382.9.4 by rlane at wikimedia
Typo fix
501
    def modify(self, name, project_manager, description=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
502
        """Modifies a project"""
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
503
        try:
504
            self.manager.modify_project(name, project_manager, description)
1072.3.3 by Eldar Nugaev
style fixing
505
        except exception.UserNotFound as ex:
506
            print ex
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
507
            raise
1072.3.2 by Eldar Nugaev
Pep8 cleaning
508
1098.201.18 by Lvov Maxim
fix pep8
509
    @args('--project', dest="name", metavar='<Project name>',
510
            help='Project name')
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
511
    def delete(self, name):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
512
        """Deletes an existing project"""
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
513
        try:
514
            self.manager.delete_project(name)
1072.3.3 by Eldar Nugaev
style fixing
515
        except exception.ProjectNotFound as ex:
516
            print ex
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
517
            raise
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
518
1098.201.18 by Lvov Maxim
fix pep8
519
    @args('--project', dest="project_id", metavar='<Project name>',
520
            help='Project name')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
521
    @args('--user', dest="user_id", metavar='<name>', help='User name')
1098.201.18 by Lvov Maxim
fix pep8
522
    @args('--file', dest="filename", metavar='<filename>',
523
            help='File name(Default: novarc)')
198.4.19 by Vishvananda Ishaya
clean up nova-manage. If vpn data isn't set for user it skips it
524
    def environment(self, project_id, user_id, filename='novarc'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
525
        """Exports environment variables to an sourcable file"""
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
526
        try:
527
            rc = self.manager.get_environment_rc(user_id, project_id)
1072.3.3 by Eldar Nugaev
style fixing
528
        except (exception.UserNotFound, exception.ProjectNotFound) as ex:
529
            print ex
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
530
            raise
1098.147.1 by Scott Moser
support '-' to indicate stdout in nova-manage project 'environment' and 'zip'
531
        if filename == "-":
1098.147.2 by Scott Moser
use 'with' so that close is called on file handle
532
            sys.stdout.write(rc)
1098.147.1 by Scott Moser
support '-' to indicate stdout in nova-manage project 'environment' and 'zip'
533
        else:
1098.147.2 by Scott Moser
use 'with' so that close is called on file handle
534
            with open(filename, 'w') as f:
535
                f.write(rc)
198.4.19 by Vishvananda Ishaya
clean up nova-manage. If vpn data isn't set for user it skips it
536
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
537
    @args('--user', dest="username", metavar='<username>', help='User name')
1031.2.1 by Todd Willey
Let nova-mange limit project list by user.
538
    def list(self, username=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
539
        """Lists all projects"""
1031.2.1 by Todd Willey
Let nova-mange limit project list by user.
540
        for project in self.manager.get_projects(username):
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
541
            print project.name
542
1098.201.18 by Lvov Maxim
fix pep8
543
    @args('--project', dest="project_id", metavar='<Project name>',
544
            help='Project name')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
545
    @args('--key', dest="key", metavar='<key>', help='Key')
546
    @args('--value', dest="value", metavar='<value>', help='Value')
237.10.13 by Vishvananda Ishaya
manage command for project quotas
547
    def quota(self, project_id, key=None, value=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
548
        """Set or display quotas for project"""
316.9.12 by Vishvananda Ishaya
fix context in bin files
549
        ctxt = context.get_admin_context()
237.10.13 by Vishvananda Ishaya
manage command for project quotas
550
        if key:
1054.8.3 by Mark Washenberger
support unlimited quotas in nova-manage and flags
551
            if value.lower() == 'unlimited':
552
                value = None
237.10.13 by Vishvananda Ishaya
manage command for project quotas
553
            try:
1054.6.1 by Mark Washenberger
convert quota table to key-value
554
                db.quota_update(ctxt, project_id, key, value)
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
555
            except exception.ProjectQuotaNotFound:
1054.6.1 by Mark Washenberger
convert quota table to key-value
556
                db.quota_create(ctxt, project_id, key, value)
1054.6.21 by Mark Washenberger
waldon's naming feedback
557
        project_quota = quota.get_project_quotas(ctxt, project_id)
237.10.13 by Vishvananda Ishaya
manage command for project quotas
558
        for key, value in project_quota.iteritems():
1054.8.3 by Mark Washenberger
support unlimited quotas in nova-manage and flags
559
            if value is None:
560
                value = 'unlimited'
237.10.13 by Vishvananda Ishaya
manage command for project quotas
561
            print '%s: %s' % (key, value)
562
1098.201.18 by Lvov Maxim
fix pep8
563
    @args('--project', dest="project_id", metavar='<Project name>',
564
            help='Project name')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
565
    @args('--user', dest="user_id", metavar='<name>', help='User name')
350.1.2 by Vishvananda Ishaya
call stuff project_id instead of project
566
    def remove(self, project_id, user_id):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
567
        """Removes user from project"""
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
568
        try:
569
            self.manager.remove_from_project(user_id, project_id)
1072.3.3 by Eldar Nugaev
style fixing
570
        except (exception.UserNotFound, exception.ProjectNotFound) as ex:
571
            print ex
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
572
            raise
94 by andy
more commands in nova-manage for projects and roles
573
1098.201.18 by Lvov Maxim
fix pep8
574
    @args('--project', dest="project_id", metavar='<Project name>',
575
            help='Project name')
350.1.2 by Vishvananda Ishaya
call stuff project_id instead of project
576
    def scrub(self, project_id):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
577
        """Deletes data associated with project"""
742.1.19 by Trey Morris
fixed_ip disassociate now also unsets mac_address_id
578
        admin_context = context.get_admin_context()
579
        networks = db.project_get_networks(admin_context, project_id)
580
        for network in networks:
581
            db.network_disassociate(admin_context, network['id'])
582
        groups = db.security_group_get_by_project(admin_context, project_id)
350.1.1 by Vishvananda Ishaya
add scrub command to clean up networks and sec groups
583
        for group in groups:
742.1.19 by Trey Morris
fixed_ip disassociate now also unsets mac_address_id
584
            db.security_group_destroy(admin_context, group['id'])
350.1.1 by Vishvananda Ishaya
add scrub command to clean up networks and sec groups
585
1098.201.18 by Lvov Maxim
fix pep8
586
    @args('--project', dest="project_id", metavar='<Project name>',
587
            help='Project name')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
588
    @args('--user', dest="user_id", metavar='<name>', help='User name')
1098.201.18 by Lvov Maxim
fix pep8
589
    @args('--file', dest="filename", metavar='<filename>',
590
            help='File name(Default: nova.zip)')
220.1.1 by Vishvananda Ishaya
rename create_zip to zipfile so lazy match works
591
    def zipfile(self, project_id, user_id, filename='nova.zip'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
592
        """Exports credentials for project to a zip file"""
435.2.1 by Soren Hansen
Add a helpful error message to nova-manage in case of NoMoreNetworks.
593
        try:
594
            zip_file = self.manager.get_credentials(user_id, project_id)
1098.147.1 by Scott Moser
support '-' to indicate stdout in nova-manage project 'environment' and 'zip'
595
            if filename == "-":
1098.147.2 by Scott Moser
use 'with' so that close is called on file handle
596
                sys.stdout.write(zip_file)
1098.147.1 by Scott Moser
support '-' to indicate stdout in nova-manage project 'environment' and 'zip'
597
            else:
1098.147.2 by Scott Moser
use 'with' so that close is called on file handle
598
                with open(filename, 'w') as f:
599
                    f.write(zip_file)
1072.3.3 by Eldar Nugaev
style fixing
600
        except (exception.UserNotFound, exception.ProjectNotFound) as ex:
601
            print ex
1072.3.1 by Eldar Nugaev
Added response about error in nova-manage project operations
602
            raise
435.2.1 by Soren Hansen
Add a helpful error message to nova-manage in case of NoMoreNetworks.
603
        except db.api.NoMoreNetworks:
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
604
            print _('No more networks available. If this is a new '
605
                    'installation, you need\nto call something like this:\n\n'
1098.166.15 by Vishvananda Ishaya
fix issues that were breaking vlan mode
606
                    '  nova-manage network create pvt 10.0.0.0/8 10 64\n\n')
583.4.1 by Vishvananda Ishaya
add helpful error messages to nova-manage and update nova.sh
607
        except exception.ProcessExecutionError, e:
608
            print e
1098.201.18 by Lvov Maxim
fix pep8
609
            print _("The above error may show that the certificate db has "
610
                    "not been created.\nPlease create a database by running "
611
                    "a nova-api server on this host.")
1 by Jesse Andrews
initial commit
612
752.4.1 by Monsyne Dragon
Add in multi-tenant support in openstack api.
613
AccountCommands = ProjectCommands
614
237.10.13 by Vishvananda Ishaya
manage command for project quotas
615
687.1.1 by Christian Berendt
added new functionality to list all defined fixed ips
616
class FixedIpCommands(object):
617
    """Class for managing fixed ip."""
618
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
619
    @args('--host', dest="host", metavar='<host>', help='Host')
687.1.1 by Christian Berendt
added new functionality to list all defined fixed ips
620
    def list(self, host=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
621
        """Lists all fixed ips (optionally by host)"""
687.1.1 by Christian Berendt
added new functionality to list all defined fixed ips
622
        ctxt = context.get_admin_context()
700.7.1 by Christian Berendt
added functionality to list only fixed ip addresses of one node and added exception handling to list method
623
624
        try:
992.1.1 by Jason Koelker
Change '== None' to 'is None'
625
            if host is None:
700.7.1 by Christian Berendt
added functionality to list only fixed ip addresses of one node and added exception handling to list method
626
                fixed_ips = db.fixed_ip_get_all(ctxt)
627
            else:
1098.166.1 by Vishvananda Ishaya
First round of changes for ha-flatdhcp.
628
                fixed_ips = db.fixed_ip_get_all_by_instance_host(ctxt, host)
700.7.1 by Christian Berendt
added functionality to list only fixed ip addresses of one node and added exception handling to list method
629
        except exception.NotFound as ex:
630
            print "error: %s" % ex
631
            sys.exit(2)
687.1.1 by Christian Berendt
added new functionality to list all defined fixed ips
632
633
        print "%-18s\t%-15s\t%-17s\t%-15s\t%s" % (_('network'),
634
                                                  _('IP address'),
635
                                                  _('MAC address'),
636
                                                  _('hostname'),
637
                                                  _('host'))
638
        for fixed_ip in fixed_ips:
639
            hostname = None
640
            host = None
641
            mac_address = None
642
            if fixed_ip['instance']:
643
                instance = fixed_ip['instance']
644
                hostname = instance['hostname']
645
                host = instance['host']
1098.159.1 by Brian Waldon
fixing bad lookup
646
                mac_address = fixed_ip['virtual_interface']['address']
687.1.1 by Christian Berendt
added new functionality to list all defined fixed ips
647
            print "%-18s\t%-15s\t%-17s\t%-15s\t%s" % (
700.7.1 by Christian Berendt
added functionality to list only fixed ip addresses of one node and added exception handling to list method
648
                    fixed_ip['network']['cidr'],
649
                    fixed_ip['address'],
650
                    mac_address, hostname, host)
687.1.1 by Christian Berendt
added new functionality to list all defined fixed ips
651
1098.272.2 by Ilya Alekseyev
tests and merge with trunk
652
    @args('--address', dest="address", metavar='<ip address>',
653
          help='IP address')
1098.272.1 by Ilya Alekseyev
added commands
654
    def reserve(self, address):
655
        """Mark fixed ip as reserved
656
        arguments: address"""
657
        self._set_reserved(address, True)
658
1098.272.2 by Ilya Alekseyev
tests and merge with trunk
659
    @args('--address', dest="address", metavar='<ip address>',
660
          help='IP address')
1098.272.4 by Ilya Alekseyev
methods renamed
661
    def unreserve(self, address):
1098.272.1 by Ilya Alekseyev
added commands
662
        """Mark fixed ip as free to use
663
        arguments: address"""
664
        self._set_reserved(address, False)
665
666
    def _set_reserved(self, address, reserved):
667
        ctxt = context.get_admin_context()
668
669
        try:
670
            fixed_ip = db.fixed_ip_get_by_address(ctxt, address)
1098.358.2 by Alex Meade
Ensure that reserve and unreserve exit when an address is not found
671
            if fixed_ip is None:
672
                raise exception.NotFound('Could not find address')
1098.272.1 by Ilya Alekseyev
added commands
673
            db.fixed_ip_update(ctxt, fixed_ip['address'],
674
                                {'reserved': reserved})
675
        except exception.NotFound as ex:
676
            print "error: %s" % ex
677
            sys.exit(2)
678
687.1.1 by Christian Berendt
added new functionality to list all defined fixed ips
679
237.7.1 by Vishvananda Ishaya
floating ip commands
680
class FloatingIpCommands(object):
681
    """Class for managing floating ip."""
682
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
683
    @args('--ip_range', dest="range", metavar='<range>', help='IP range')
742.1.43 by Trey Morris
floating ips can now move around the network hosts
684
    def create(self, range):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
685
        """Creates floating ips for zone by range"""
1098.84.8 by Chuck Short
Use IPNetwork rather than IPRange
686
        for address in netaddr.IPNetwork(range):
316.9.12 by Vishvananda Ishaya
fix context in bin files
687
            db.floating_ip_create(context.get_admin_context(),
742.1.43 by Trey Morris
floating ips can now move around the network hosts
688
                                  {'address': str(address)})
237.7.1 by Vishvananda Ishaya
floating ip commands
689
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
690
    @args('--ip_range', dest="ip_range", metavar='<range>', help='IP range')
237.7.1 by Vishvananda Ishaya
floating ip commands
691
    def delete(self, ip_range):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
692
        """Deletes floating ips by range"""
1098.84.8 by Chuck Short
Use IPNetwork rather than IPRange
693
        for address in netaddr.IPNetwork(ip_range):
316.9.12 by Vishvananda Ishaya
fix context in bin files
694
            db.floating_ip_destroy(context.get_admin_context(),
695
                                   str(address))
237.7.1 by Vishvananda Ishaya
floating ip commands
696
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
697
    @args('--host', dest="host", metavar='<host>', help='Host')
237.7.1 by Vishvananda Ishaya
floating ip commands
698
    def list(self, host=None):
699
        """Lists all floating ips (optionally by host)
742.1.43 by Trey Morris
floating ips can now move around the network hosts
700
        Note: if host is given, only active floating IPs are returned"""
316.9.12 by Vishvananda Ishaya
fix context in bin files
701
        ctxt = context.get_admin_context()
992.1.1 by Jason Koelker
Change '== None' to 'is None'
702
        if host is None:
316.9.12 by Vishvananda Ishaya
fix context in bin files
703
            floating_ips = db.floating_ip_get_all(ctxt)
237.7.1 by Vishvananda Ishaya
floating ip commands
704
        else:
316.9.12 by Vishvananda Ishaya
fix context in bin files
705
            floating_ips = db.floating_ip_get_all_by_host(ctxt, host)
237.7.1 by Vishvananda Ishaya
floating ip commands
706
        for floating_ip in floating_ips:
237.7.4 by Vishvananda Ishaya
list command for floating ips
707
            instance = None
708
            if floating_ip['fixed_ip']:
1098.23.2 by John Tran
fixed as per peer review to make more consistent
709
                instance = floating_ip['fixed_ip']['instance']['hostname']
237.7.4 by Vishvananda Ishaya
list command for floating ips
710
            print "%s\t%s\t%s" % (floating_ip['host'],
711
                                  floating_ip['address'],
712
                                  instance)
1 by Jesse Andrews
initial commit
713
375.2.1 by Eric Day
PEP8 and pylint cleanup. There should be no functional changes here, just style changes to get violations down.
714
292.8.3 by Vishvananda Ishaya
get rid of network indexes and make networks into a pool
715
class NetworkCommands(object):
716
    """Class for managing networks."""
717
1098.201.18 by Lvov Maxim
fix pep8
718
    @args('--label', dest="label", metavar='<label>',
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
719
            help='Label for network (ex: public)')
1098.220.3 by Trey Morris
added ipv6 requirements to nova-manage network create. changed --network to --fixed_range_v4
720
    @args('--fixed_range_v4', dest="fixed_range_v4", metavar='<x.x.x.x/yy>',
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
721
            help='IPv4 subnet (ex: 10.0.0.0/8)')
1098.201.18 by Lvov Maxim
fix pep8
722
    @args('--num_networks', dest="num_networks", metavar='<number>',
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
723
            help='Number of networks to create')
1098.201.18 by Lvov Maxim
fix pep8
724
    @args('--network_size', dest="network_size", metavar='<number>',
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
725
            help='Number of IPs per network')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
726
    @args('--vlan', dest="vlan_start", metavar='<vlan id>', help='vlan id')
727
    @args('--vpn', dest="vpn_start", help='vpn start')
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
728
    @args('--fixed_range_v6', dest="fixed_range_v6",
729
          help='IPv6 subnet (ex: fe80::/64')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
730
    @args('--gateway_v6', dest="gateway_v6", help='ipv6 gateway')
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
731
    @args('--bridge', dest="bridge",
732
            metavar='<bridge>',
733
            help='VIFs on this network are connected to this bridge')
1098.201.18 by Lvov Maxim
fix pep8
734
    @args('--bridge_interface', dest="bridge_interface",
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
735
            metavar='<bridge interface>',
736
            help='the bridge is connected to this interface')
1098.201.18 by Lvov Maxim
fix pep8
737
    @args('--multi_host', dest="multi_host", metavar="<'T'|'F'>",
738
            help='Multi host')
1098.201.17 by Lvov Maxim
add decorator for 'dns' params
739
    @args('--dns1', dest="dns1", metavar="<DNS Address>", help='First DNS')
740
    @args('--dns2', dest="dns2", metavar="<DNS Address>", help='Second DNS')
1098.492.1 by bmcconne at rackspace
Fixed --uuid network command in nova-manage to desc to "uuid" instead of "net_uuid"
741
    @args('--uuid', dest="uuid", metavar="<network uuid>",
1098.421.9 by Dan Wendlandt
use 'uuid' field in networks table rather than 'bridge'. Specify project_id when creating instance in unit test
742
      help='Network UUID')
1098.421.1 by Dan Wendlandt
pulling all qmanager changes into a branch based on trunk, as they were previously stacked on top of melange
743
    @args('--project_id', dest="project_id", metavar="<project id>",
744
      help='Project id')
745
    @args('--priority', dest="priority", metavar="<number>",
746
      help='Network interface priority')
1098.240.4 by Jason Koelker
either v4 or v6 is required
747
    def create(self, label=None, fixed_range_v4=None, num_networks=None,
1098.166.6 by Vishvananda Ishaya
add ability to set multi_host in nova-manage and remove debugging issues
748
               network_size=None, multi_host=None, vlan_start=None,
742.1.35 by Trey Morris
merged trunk again
749
               vpn_start=None, fixed_range_v6=None, gateway_v6=None,
1098.421.1 by Dan Wendlandt
pulling all qmanager changes into a branch based on trunk, as they were previously stacked on top of melange
750
               bridge=None, bridge_interface=None, dns1=None, dns2=None,
1098.421.9 by Dan Wendlandt
use 'uuid' field in networks table rather than 'bridge'. Specify project_id when creating instance in unit test
751
               project_id=None, priority=None, uuid=None):
1098.201.13 by Lvov Maxim
merge with trunk, resolve conflicts
752
        """Creates fixed ips for host by range"""
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
753
754
        # check for certain required inputs
742.1.35 by Trey Morris
merged trunk again
755
        if not label:
1098.220.3 by Trey Morris
added ipv6 requirements to nova-manage network create. changed --network to --fixed_range_v4
756
            raise exception.NetworkNotCreated(req='--label')
1098.240.4 by Jason Koelker
either v4 or v6 is required
757
        if not (fixed_range_v4 or fixed_range_v6):
758
            req = '--fixed_range_v4 or --fixed_range_v6'
1098.240.1 by Jason Koelker
require either v4 or v6
759
            raise exception.NetworkNotCreated(req=req)
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
760
761
        bridge = bridge or FLAGS.flat_network_bridge
762
        if not bridge:
1098.220.2 by Trey Morris
updated the bridge arg requirements based on manager
763
            bridge_required = ['nova.network.manager.FlatManager',
764
                               'nova.network.manager.FlatDHCPManager']
765
            if FLAGS.network_manager in bridge_required:
1098.491.1 by Trey Morris
now raising instead of setting bridge to br100 and warning as was noted
766
                raise exception.NetworkNotCreated(req='--bridge')
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
767
768
        bridge_interface = bridge_interface or FLAGS.flat_interface or \
769
                           FLAGS.vlan_interface
770
        if not bridge_interface:
1098.441.1 by Mark McLoughlin
Do not require --bridge_interface for FlatDHCPManager
771
            interface_required = ['nova.network.manager.VlanManager']
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
772
            if FLAGS.network_manager in interface_required:
1098.220.3 by Trey Morris
added ipv6 requirements to nova-manage network create. changed --network to --fixed_range_v4
773
                raise exception.NetworkNotCreated(req='--bridge_interface')
774
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
775
        # sanitize other input using FLAGS if necessary
292.8.3 by Vishvananda Ishaya
get rid of network indexes and make networks into a pool
776
        if not num_networks:
777
            num_networks = FLAGS.num_networks
1098.328.3 by Jason Koelker
don't require ipv4
778
        if not network_size and fixed_range_v4:
1098.262.5 by John Tran
updated to work w/ changes after merged trunk fixing var renaming. the logic which forces default to FLAGS.network_size if requested cidr was larger, was also applying to requested cidrs smaller than FLAGS.network_size. Requested cidrs smaller than FLAGS.network_size should be ignored and not overriden.
779
            fixnet = netaddr.IPNetwork(fixed_range_v4)
1098.262.2 by John Tran
added warning when size of subnet(s) being created are larger than FLAG.network_size in attempt to alleviate confusion. For example, currently when 'nova-manage network create foo 192.168.0.0/16', the result is that it creates a 192.168.0.0/24 instead without any indication to why.
780
            each_subnet_size = fixnet.size / int(num_networks)
1098.262.5 by John Tran
updated to work w/ changes after merged trunk fixing var renaming. the logic which forces default to FLAGS.network_size if requested cidr was larger, was also applying to requested cidrs smaller than FLAGS.network_size. Requested cidrs smaller than FLAGS.network_size should be ignored and not overriden.
781
            if each_subnet_size > FLAGS.network_size:
782
                network_size = FLAGS.network_size
1098.262.2 by John Tran
added warning when size of subnet(s) being created are larger than FLAG.network_size in attempt to alleviate confusion. For example, currently when 'nova-manage network create foo 192.168.0.0/16', the result is that it creates a 192.168.0.0/24 instead without any indication to why.
783
                subnet = 32 - int(math.log(network_size, 2))
784
                oversize_msg = _('Subnet(s) too large, defaulting to /%s.'
1098.286.1 by Thierry Carrez
Fix remaining two pep8 violations
785
                         '  To override, specify network_size flag.') % subnet
1098.262.2 by John Tran
added warning when size of subnet(s) being created are larger than FLAG.network_size in attempt to alleviate confusion. For example, currently when 'nova-manage network create foo 192.168.0.0/16', the result is that it creates a 192.168.0.0/24 instead without any indication to why.
786
                print oversize_msg
1098.262.5 by John Tran
updated to work w/ changes after merged trunk fixing var renaming. the logic which forces default to FLAGS.network_size if requested cidr was larger, was also applying to requested cidrs smaller than FLAGS.network_size. Requested cidrs smaller than FLAGS.network_size should be ignored and not overriden.
787
            else:
788
                network_size = fixnet.size
1098.166.6 by Vishvananda Ishaya
add ability to set multi_host in nova-manage and remove debugging issues
789
        if not multi_host:
790
            multi_host = FLAGS.multi_host
791
        else:
792
            multi_host = multi_host == 'T'
292.8.3 by Vishvananda Ishaya
get rid of network indexes and make networks into a pool
793
        if not vlan_start:
794
            vlan_start = FLAGS.vlan_start
795
        if not vpn_start:
796
            vpn_start = FLAGS.vpn_start
1098.181.10 by Jason Koelker
default to None in the method signature
797
        if not dns1 and FLAGS.flat_network_dns:
798
            dns1 = FLAGS.flat_network_dns
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
799
1098.328.4 by Jason Koelker
make sure network_size gets set
800
        if not network_size:
801
            network_size = FLAGS.network_size
802
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
803
        # create the network
292.8.6 by Vishvananda Ishaya
Fixed flat network manager with network index gone.
804
        net_manager = utils.import_object(FLAGS.network_manager)
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
805
        net_manager.create_networks(context.get_admin_context(),
806
                                    label=label,
1098.220.3 by Trey Morris
added ipv6 requirements to nova-manage network create. changed --network to --fixed_range_v4
807
                                    cidr=fixed_range_v4,
1098.220.1 by Trey Morris
updated nova-manage create network. better help, handling of required args, and exceptions. Also updated FLAG flat_network_bridge to default to None
808
                                    multi_host=multi_host,
809
                                    num_networks=int(num_networks),
810
                                    network_size=int(network_size),
811
                                    vlan_start=int(vlan_start),
812
                                    vpn_start=int(vpn_start),
813
                                    cidr_v6=fixed_range_v6,
814
                                    gateway_v6=gateway_v6,
815
                                    bridge=bridge,
816
                                    bridge_interface=bridge_interface,
817
                                    dns1=dns1,
1098.421.1 by Dan Wendlandt
pulling all qmanager changes into a branch based on trunk, as they were previously stacked on top of melange
818
                                    dns2=dns2,
819
                                    project_id=project_id,
1098.421.9 by Dan Wendlandt
use 'uuid' field in networks table rather than 'bridge'. Specify project_id when creating instance in unit test
820
                                    priority=priority,
821
                                    uuid=uuid)
237.10.13 by Vishvananda Ishaya
manage command for project quotas
822
679.1.1 by Christian Berendt
added functionality to nova-manage to list created networks
823
    def list(self):
824
        """List all created networks"""
1098.421.37 by Dan Wendlandt
feedback from jk0's review, including removing a lot of spaces from docstrings
825
        _fmt = "%-5s\t%-18s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s"
1098.360.32 by Tushar Patil
Added uuid for networks and made changes to the Create server API format to accept network as uuid instead of id
826
        print _fmt % (_('id'),
827
                          _('IPv4'),
828
                          _('IPv6'),
829
                          _('start address'),
830
                          _('DNS1'),
831
                          _('DNS2'),
832
                          _('VlanID'),
833
                          _('project'),
1098.421.4 by Dan Wendlandt
fix for quantum api changes, change nova-mange to have quantum_list command
834
                          _("uuid"))
679.1.1 by Christian Berendt
added functionality to nova-manage to list created networks
835
        for network in db.network_get_all(context.get_admin_context()):
1098.360.32 by Tushar Patil
Added uuid for networks and made changes to the Create server API format to accept network as uuid instead of id
836
            print _fmt % (network.id,
837
                          network.cidr,
838
                          network.cidr_v6,
839
                          network.dhcp_start,
840
                          network.dns1,
841
                          network.dns2,
842
                          network.vlan,
843
                          network.project_id,
1098.421.4 by Dan Wendlandt
fix for quantum api changes, change nova-mange to have quantum_list command
844
                          network.uuid)
845
846
    def quantum_list(self):
847
        """List all created networks with Quantum-relevant fields"""
848
        _fmt = "%-32s\t%-10s\t%-10s\t%s , %s"
1098.424.1 by Brad Hall
Address code review feedback from Rick and Matt
849
        print _fmt % (_('uuid'),
850
                      _('project'),
851
                      _('priority'),
852
                      _('cidr_v4'),
853
                      _('cidr_v6'))
1098.421.4 by Dan Wendlandt
fix for quantum api changes, change nova-mange to have quantum_list command
854
        for network in db.network_get_all(context.get_admin_context()):
1098.421.9 by Dan Wendlandt
use 'uuid' field in networks table rather than 'bridge'. Specify project_id when creating instance in unit test
855
            print _fmt % (network.uuid,
1098.421.4 by Dan Wendlandt
fix for quantum api changes, change nova-mange to have quantum_list command
856
                          network.project_id,
1098.421.1 by Dan Wendlandt
pulling all qmanager changes into a branch based on trunk, as they were previously stacked on top of melange
857
                          network.priority,
1098.421.4 by Dan Wendlandt
fix for quantum api changes, change nova-mange to have quantum_list command
858
                          network.cidr,
859
                          network.cidr_v6)
679.1.1 by Christian Berendt
added functionality to nova-manage to list created networks
860
1098.201.18 by Lvov Maxim
fix pep8
861
    @args('--network', dest="fixed_range", metavar='<x.x.x.x/yy>',
862
            help='Network to delete')
758.1.1 by Ricardo Carrillo Cruz
Added initial support to delete networks nova-manage
863
    def delete(self, fixed_range):
864
        """Deletes a network"""
1098.421.1 by Dan Wendlandt
pulling all qmanager changes into a branch based on trunk, as they were previously stacked on top of melange
865
866
        # delete the network
867
        net_manager = utils.import_object(FLAGS.network_manager)
1098.421.20 by Dan Wendlandt
remove 'uuid' param for nova-manage network delete that I had add previously
868
        net_manager.delete_network(context.get_admin_context(), fixed_range)
1098.421.1 by Dan Wendlandt
pulling all qmanager changes into a branch based on trunk, as they were previously stacked on top of melange
869
1098.378.4 by Hisaharu Ishii
Add 'nova-manage network modify' command.
870
    @args('--network', dest="fixed_range", metavar='<x.x.x.x/yy>',
871
            help='Network to modify')
872
    @args('--project', dest="project", metavar='<project name>',
1098.378.8 by Hisaharu Ishii
Change parameters of 'nova-manage network modify'.
873
            help='Project name to associate')
1098.378.4 by Hisaharu Ishii
Add 'nova-manage network modify' command.
874
    @args('--host', dest="host", metavar='<host>',
1098.378.8 by Hisaharu Ishii
Change parameters of 'nova-manage network modify'.
875
            help='Host to associate')
876
    @args('--disassociate-project', action="store_true", dest='dis_project',
877
          default=False, help='Disassociate Network from Project')
878
    @args('--disassociate-host', action="store_true", dest='dis_host',
879
          default=False, help='Disassociate Host from Project')
880
    def modify(self, fixed_range, project=None, host=None,
881
               dis_project=None, dis_host=None):
882
        """Associate/Disassociate Network with Project and/or Host
1098.378.4 by Hisaharu Ishii
Add 'nova-manage network modify' command.
883
        arguments: network project host
884
        leave any field blank to ignore it
885
        """
886
        admin_context = context.get_admin_context()
887
        network = db.network_get_by_cidr(admin_context, fixed_range)
1098.378.10 by Hisaharu Ishii
Stub out the DB in unit test.
888
        net = {}
1098.378.20 by Hisaharu Ishii
Add comments for associate/dissociate logic
889
        #User can choose the following actions each for project and host.
890
        #1) Associate (set not None value given by project/host parameter)
891
        #2) Disassociate (set None by disassociate parameter)
892
        #3) Keep unchanged (project/host key is not added to 'net')
1098.378.8 by Hisaharu Ishii
Change parameters of 'nova-manage network modify'.
893
        if project:
1098.378.10 by Hisaharu Ishii
Stub out the DB in unit test.
894
            net['project_id'] = project
1098.378.8 by Hisaharu Ishii
Change parameters of 'nova-manage network modify'.
895
        elif dis_project:
1098.378.10 by Hisaharu Ishii
Stub out the DB in unit test.
896
            net['project_id'] = None
1098.378.8 by Hisaharu Ishii
Change parameters of 'nova-manage network modify'.
897
        if host:
1098.378.10 by Hisaharu Ishii
Stub out the DB in unit test.
898
            net['host'] = host
1098.378.8 by Hisaharu Ishii
Change parameters of 'nova-manage network modify'.
899
        elif dis_host:
1098.378.10 by Hisaharu Ishii
Stub out the DB in unit test.
900
            net['host'] = None
901
        db.network_update(admin_context, network['id'], net)
1098.378.4 by Hisaharu Ishii
Add 'nova-manage network modify' command.
902
758.1.7 by Ricardo Carrillo Cruz
Fixed pep8 issues
903
439.1.47 by Kei Masumoto
Merged to trunk rev 757. Main changes are below.
904
class VmCommands(object):
439.1.1 by masumotok
rev439ベースにライブマイグレーションの機能をマージ
905
    """Class for mangaging VM instances."""
906
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
907
    @args('--host', dest="host", metavar='<host>', help='Host')
950.2.2 by Ken Pepple
removed unused instance parameter from vm list ... as it is unused. added parameters to docstring for vm list.
908
    def list(self, host=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
909
        """Show a list of all instances"""
950.2.5 by Ken Pepple
pep8
910
1098.104.1 by Thierry Carrez
Fix nova-manage vm list
911
        print "%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" \
950.2.1 by Ken Pepple
moved -manage instance list command to -manage vm list to avoid lazy match conflict with instance_types
912
              "  %-10s %-10s %-10s %-5s" % (
913
            _('instance'),
914
            _('node'),
915
            _('type'),
916
            _('state'),
917
            _('launched'),
918
            _('image'),
919
            _('kernel'),
920
            _('ramdisk'),
921
            _('project'),
922
            _('user'),
923
            _('zone'),
924
            _('index'))
925
992.1.1 by Jason Koelker
Change '== None' to 'is None'
926
        if host is None:
950.2.1 by Ken Pepple
moved -manage instance list command to -manage vm list to avoid lazy match conflict with instance_types
927
            instances = db.instance_get_all(context.get_admin_context())
928
        else:
929
            instances = db.instance_get_all_by_host(
930
                           context.get_admin_context(), host)
931
932
        for instance in instances:
1098.104.1 by Thierry Carrez
Fix nova-manage vm list
933
            print "%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" \
950.2.1 by Ken Pepple
moved -manage instance list command to -manage vm list to avoid lazy match conflict with instance_types
934
                  "  %-10s %-10s %-10s %-5d" % (
935
                instance['hostname'],
936
                instance['host'],
1098.104.1 by Thierry Carrez
Fix nova-manage vm list
937
                instance['instance_type'].name,
1098.410.1 by Vishvananda Ishaya
remove extra references to state_description
938
                instance['vm_state'],
950.2.1 by Ken Pepple
moved -manage instance list command to -manage vm list to avoid lazy match conflict with instance_types
939
                instance['launched_at'],
1098.104.1 by Thierry Carrez
Fix nova-manage vm list
940
                instance['image_ref'],
950.2.1 by Ken Pepple
moved -manage instance list command to -manage vm list to avoid lazy match conflict with instance_types
941
                instance['kernel_id'],
942
                instance['ramdisk_id'],
943
                instance['project_id'],
944
                instance['user_id'],
945
                instance['availability_zone'],
946
                instance['launch_index'])
947
1098.321.1 by Kei Masumoto
block migration feature added
948
    def _migration(self, ec2_id, dest, block_migration=False):
439.1.37 by Kei Masumoto
Fixed based on reviewer's comment.
949
        """Migrates a running instance to a new machine.
1098.321.16 by Kei Masumoto
merged recent trunk
950
         :param ec2_id: instance id which comes from euca-describe-instance.
951
         :param dest: destination host name.
952
         :param block_migration: if True, do block_migration.
439.1.37 by Kei Masumoto
Fixed based on reviewer's comment.
953
954
        """
439.1.1 by masumotok
rev439ベースにライブマイグレーションの機能をマージ
955
439.1.19 by Kei Masumoto
merged to rev 561 and fixed based on reviewer's comment
956
        ctxt = context.get_admin_context()
799.3.1 by Ken Pepple
small typo in nova-manage vm live-migration
957
        instance_id = ec2utils.ec2_id_to_id(ec2_id)
439.1.19 by Kei Masumoto
merged to rev 561 and fixed based on reviewer's comment
958
807.3.1 by Soren Hansen
Fix a couple of things that assume that libvirt == kvm/qemu.
959
        if (FLAGS.connection_type != 'libvirt' or
960
           (FLAGS.connection_type == 'libvirt' and
961
            FLAGS.libvirt_type not in ['kvm', 'qemu'])):
807.3.2 by Soren Hansen
Make error message match the check.
962
            msg = _('Only KVM and QEmu are supported for now. Sorry!')
439.1.19 by Kei Masumoto
merged to rev 561 and fixed based on reviewer's comment
963
            raise exception.Error(msg)
439.3.2 by masumotok
Get reviewed and fixed based on comments.
964
439.1.34 by Kei Masumoto
Fixed based on reviewer's comment.
965
        if (FLAGS.volume_driver != 'nova.volume.driver.AOEDriver' and \
966
            FLAGS.volume_driver != 'nova.volume.driver.ISCSIDriver'):
439.1.31 by Kei Masumoto
Merge request candidate version.
967
            msg = _("Support only AOEDriver and ISCSIDriver. Sorry!")
439.1.52 by Kei Masumoto
fixed based on reviewer's comment.
968
            raise exception.Error(msg)
439.3.2 by masumotok
Get reviewed and fixed based on comments.
969
970
        rpc.call(ctxt,
971
                 FLAGS.scheduler_topic,
972
                 {"method": "live_migration",
973
                  "args": {"instance_id": instance_id,
974
                           "dest": dest,
1098.321.1 by Kei Masumoto
block migration feature added
975
                           "topic": FLAGS.compute_topic,
976
                           "block_migration": block_migration}})
439.3.2 by masumotok
Get reviewed and fixed based on comments.
977
439.1.37 by Kei Masumoto
Fixed based on reviewer's comment.
978
        print _('Migration of %s initiated.'
979
               'Check its progress using euca-describe-instances.') % ec2_id
439.1.1 by masumotok
rev439ベースにライブマイグレーションの機能をマージ
980
1098.321.16 by Kei Masumoto
merged recent trunk
981
    @args('--ec2_id', dest='ec2_id', metavar='<ec2 id>', help='EC2 ID')
982
    @args('--dest', dest='dest', metavar='<Destanation>',
983
            help='destanation node')
1098.321.1 by Kei Masumoto
block migration feature added
984
    def live_migration(self, ec2_id, dest):
1098.321.16 by Kei Masumoto
merged recent trunk
985
        """Migrates a running instance to a new machine."""
986
1098.321.1 by Kei Masumoto
block migration feature added
987
        self._migration(ec2_id, dest)
988
1098.321.16 by Kei Masumoto
merged recent trunk
989
    @args('--ec2_id', dest='ec2_id', metavar='<ec2 id>', help='EC2 ID')
990
    @args('--dest', dest='dest', metavar='<Destanation>',
991
            help='destanation node')
1098.321.1 by Kei Masumoto
block migration feature added
992
    def block_migration(self, ec2_id, dest):
1098.321.16 by Kei Masumoto
merged recent trunk
993
        """Migrates a running instance to a new machine with storage data."""
994
1098.321.1 by Kei Masumoto
block migration feature added
995
        self._migration(ec2_id, dest, True)
996
439.1.13 by masumotok
merge recent revision(version of 2010/12/28)
997
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
998
class ServiceCommands(object):
999
    """Enable and disable running services"""
1000
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1001
    @args('--host', dest='host', metavar='<host>', help='Host')
1098.201.18 by Lvov Maxim
fix pep8
1002
    @args('--service', dest='service', metavar='<service>',
1003
            help='Nova service')
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1004
    def list(self, host=None, service=None):
1098.201.18 by Lvov Maxim
fix pep8
1005
        """
1006
        Show a list of all running services. Filter by host & service name.
1007
        """
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1008
        ctxt = context.get_admin_context()
1098.26.1 by Vishvananda Ishaya
make all uses of utcnow use our testable utils.utcnow
1009
        now = utils.utcnow()
843.8.1 by Josh Kleinpeter
Changed default for disabled on service_get_all to None. Changed calls to service_get_all so that the results should still be as they previously were.
1010
        services = db.service_get_all(ctxt)
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1011
        if host:
1012
            services = [s for s in services if s['host'] == host]
1013
        if service:
1014
            services = [s for s in services if s['binary'] == service]
1098.311.1 by Tushar Patil
Added availability zone support to the Create Server API
1015
        print_format = "%-16s %-36s %-16s %-10s %-5s %-10s"
1016
        print print_format % (
1017
                    _('Binary'),
1018
                    _('Host'),
1019
                    _('Zone'),
1020
                    _('Status'),
1021
                    _('State'),
1022
                    _('Updated_At'))
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1023
        for svc in services:
1024
            delta = now - (svc['updated_at'] or svc['created_at'])
1025
            alive = (delta.seconds <= 15)
1026
            art = (alive and ":-)") or "XXX"
1027
            active = 'enabled'
1028
            if svc['disabled']:
1029
                active = 'disabled'
1098.311.1 by Tushar Patil
Added availability zone support to the Create Server API
1030
            print print_format % (svc['binary'], svc['host'],
1031
                                  svc['availability_zone'], active, art,
1032
                                  svc['updated_at'])
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1033
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1034
    @args('--host', dest='host', metavar='<host>', help='Host')
1098.201.18 by Lvov Maxim
fix pep8
1035
    @args('--service', dest='service', metavar='<service>',
1036
            help='Nova service')
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1037
    def enable(self, host, service):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1038
        """Enable scheduling for a service"""
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1039
        ctxt = context.get_admin_context()
1040
        svc = db.service_get_by_args(ctxt, host, service)
1041
        if not svc:
1042
            print "Unable to find service"
1043
            return
1044
        db.service_update(ctxt, svc['id'], {'disabled': False})
1045
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1046
    @args('--host', dest='host', metavar='<host>', help='Host')
1098.201.18 by Lvov Maxim
fix pep8
1047
    @args('--service', dest='service', metavar='<service>',
1048
            help='Nova service')
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1049
    def disable(self, host, service):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1050
        """Disable scheduling for a service"""
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1051
        ctxt = context.get_admin_context()
1052
        svc = db.service_get_by_args(ctxt, host, service)
1053
        if not svc:
1054
            print "Unable to find service"
1055
            return
1056
        db.service_update(ctxt, svc['id'], {'disabled': True})
1057
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1058
    @args('--host', dest='host', metavar='<host>', help='Host')
439.1.33 by Kei Masumoto
fixed based on reviewer's comment.
1059
    def describe_resource(self, host):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1060
        """Describes cpu/memory/hdd info for host."""
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1061
1062
        result = rpc.call(context.get_admin_context(),
1063
                     FLAGS.scheduler_topic,
439.1.37 by Kei Masumoto
Fixed based on reviewer's comment.
1064
                     {"method": "show_host_resources",
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1065
                      "args": {"host": host}})
1066
1067
        if type(result) != dict:
439.1.52 by Kei Masumoto
fixed based on reviewer's comment.
1068
            print _('An unexpected error has occurred.')
1069
            print _('[Result]'), result
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1070
        else:
439.1.34 by Kei Masumoto
Fixed based on reviewer's comment.
1071
            cpu = result['resource']['vcpus']
1072
            mem = result['resource']['memory_mb']
1073
            hdd = result['resource']['local_gb']
1074
            cpu_u = result['resource']['vcpus_used']
1075
            mem_u = result['resource']['memory_mb_used']
1076
            hdd_u = result['resource']['local_gb_used']
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1077
1098.321.1 by Kei Masumoto
block migration feature added
1078
            cpu_sum = 0
1079
            mem_sum = 0
1080
            hdd_sum = 0
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1081
            print 'HOST\t\t\tPROJECT\t\tcpu\tmem(mb)\tdisk(gb)'
1082
            print '%s(total)\t\t\t%s\t%s\t%s' % (host, cpu, mem, hdd)
1098.321.1 by Kei Masumoto
block migration feature added
1083
            print '%s(used_now)\t\t\t%s\t%s\t%s' % (host, cpu_u, mem_u, hdd_u)
1084
            for p_id, val in result['usage'].items():
1085
                cpu_sum += val['vcpus']
1086
                mem_sum += val['memory_mb']
1087
                hdd_sum += val['local_gb']
1088
            print '%s(used_max)\t\t\t%s\t%s\t%s' % (host, cpu_sum,
1089
                                                    mem_sum, hdd_sum)
1090
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1091
            for p_id, val in result['usage'].items():
1092
                print '%s\t\t%s\t\t%s\t%s\t%s' % (host,
1093
                                                  p_id,
1094
                                                  val['vcpus'],
1095
                                                  val['memory_mb'],
1096
                                                  val['local_gb'])
1097
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1098
    @args('--host', dest='host', metavar='<host>', help='Host')
439.1.33 by Kei Masumoto
fixed based on reviewer's comment.
1099
    def update_resource(self, host):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1100
        """Updates available vcpu/memory/disk info for host."""
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1101
1102
        ctxt = context.get_admin_context()
1103
        service_refs = db.service_get_all_by_host(ctxt, host)
1104
        if len(service_refs) <= 0:
439.1.52 by Kei Masumoto
fixed based on reviewer's comment.
1105
            raise exception.Invalid(_('%s does not exist.') % host)
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1106
439.1.31 by Kei Masumoto
Merge request candidate version.
1107
        service_refs = [s for s in service_refs if s['topic'] == 'compute']
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1108
        if len(service_refs) <= 0:
1109
            raise exception.Invalid(_('%s is not compute node.') % host)
439.1.31 by Kei Masumoto
Merge request candidate version.
1110
439.1.33 by Kei Masumoto
fixed based on reviewer's comment.
1111
        rpc.call(ctxt,
1112
                 db.queue_get_for(ctxt, FLAGS.compute_topic, host),
1113
                 {"method": "update_available_resource"})
439.1.29 by Kei Masumoto
1. Discard nova-manage host list
1114
472.2.1 by Todd Willey
Burnin support by specifying a specific host via availability_zone for running
1115
1098.146.2 by Mike Scherbakov
Renamed 'nova-manage server list' -> 'nova-manage host list' to differentiate physical hosts from VMs
1116
class HostCommands(object):
1117
    """List hosts"""
1098.146.1 by Mike Scherbakov
Improvements to nova-manage: network list now includes vlan and projectID, added servers list filtered by zone if needed
1118
1119
    def list(self, zone=None):
1098.146.2 by Mike Scherbakov
Renamed 'nova-manage server list' -> 'nova-manage host list' to differentiate physical hosts from VMs
1120
        """Show a list of all physical hosts. Filter by zone.
1098.146.1 by Mike Scherbakov
Improvements to nova-manage: network list now includes vlan and projectID, added servers list filtered by zone if needed
1121
        args: [zone]"""
1122
        print "%-25s\t%-15s" % (_('host'),
1123
                                _('zone'))
1124
        ctxt = context.get_admin_context()
1125
        now = utils.utcnow()
1126
        services = db.service_get_all(ctxt)
1127
        if zone:
1128
            services = [s for s in services if s['availability_zone'] == zone]
1098.146.2 by Mike Scherbakov
Renamed 'nova-manage server list' -> 'nova-manage host list' to differentiate physical hosts from VMs
1129
        hosts = []
1098.146.1 by Mike Scherbakov
Improvements to nova-manage: network list now includes vlan and projectID, added servers list filtered by zone if needed
1130
        for srv in services:
1098.146.2 by Mike Scherbakov
Renamed 'nova-manage server list' -> 'nova-manage host list' to differentiate physical hosts from VMs
1131
            if not [h for h in hosts if h['host'] == srv['host']]:
1132
                hosts.append(srv)
1098.146.1 by Mike Scherbakov
Improvements to nova-manage: network list now includes vlan and projectID, added servers list filtered by zone if needed
1133
1098.146.2 by Mike Scherbakov
Renamed 'nova-manage server list' -> 'nova-manage host list' to differentiate physical hosts from VMs
1134
        for h in hosts:
1135
            print "%-25s\t%-15s" % (h['host'], h['availability_zone'])
1098.146.1 by Mike Scherbakov
Improvements to nova-manage: network list now includes vlan and projectID, added servers list filtered by zone if needed
1136
1137
556.5.1 by Andy Smith
add support for database migration
1138
class DbCommands(object):
1139
    """Class for managing the database."""
1140
1141
    def __init__(self):
1142
        pass
1143
1098.201.18 by Lvov Maxim
fix pep8
1144
    @args('--version', dest='version', metavar='<version>',
1145
            help='Database version')
556.5.1 by Andy Smith
add support for database migration
1146
    def sync(self, version=None):
556.5.7 by Andy Smith
merge from upstream and fix small issues
1147
        """Sync the database up to the most recent version."""
556.5.1 by Andy Smith
add support for database migration
1148
        return migration.db_sync(version)
1149
1150
    def version(self):
556.5.7 by Andy Smith
merge from upstream and fix small issues
1151
        """Print the current database version."""
556.5.1 by Andy Smith
add support for database migration
1152
        print migration.db_version()
1153
1154
1033.1.2 by Ken Pepple
added version list command to nova-manage
1155
class VersionCommands(object):
1033.1.3 by Ken Pepple
fixed docstring per jsb
1156
    """Class for exposing the codebase version."""
1033.1.2 by Ken Pepple
added version list command to nova-manage
1157
1158
    def __init__(self):
1159
        pass
1160
1161
    def list(self):
1162
        print _("%s (%s)") %\
1163
                (version.version_string(), version.version_string_with_vcs())
1164
1098.201.8 by Yuriy Taraday
Add possibility to call commands without subcommands.
1165
    def __call__(self):
1166
        self.list()
1167
1033.1.4 by Ken Pepple
pep8
1168
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1169
class VsaCommands(object):
1170
    """Methods for dealing with VSAs"""
1171
1172
    def __init__(self, *args, **kwargs):
1173
        self.manager = manager.AuthManager()
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1174
        self.vsa_api = vsa.API()
1098.388.28 by vladimir.p
Merge with nova. Moved user+access to flags. changes for log access mode
1175
        self.context = context.get_admin_context()
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1176
1098.388.49 by vladimir.p
changed format string in nova-manage
1177
        self._format_str_vsa = "%(id)-5s %(vsa_id)-15s %(name)-25s "\
1178
                    "%(type)-10s %(vcs)-6s %(drives)-9s %(stat)-10s "\
1179
                    "%(az)-10s %(time)-10s"
1180
        self._format_str_volume = "\t%(id)-4s %(name)-15s %(size)-5s "\
1181
                    "%(stat)-10s %(att)-20s %(time)s"
1182
        self._format_str_drive = "\t%(id)-4s %(name)-15s %(size)-5s "\
1183
                    "%(stat)-10s %(host)-20s %(type)-4s %(tname)-10s %(time)s"
1184
        self._format_str_instance = "\t%(id)-4s %(name)-10s %(dname)-20s "\
1185
                    "%(image)-12s %(type)-10s %(fl_ip)-15s %(fx_ip)-15s "\
1186
                    "%(stat)-10s %(host)-15s %(time)s"
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1187
1188
    def _print_vsa_header(self):
1189
        print self._format_str_vsa %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1190
               dict(id=_('ID'),
1191
                    vsa_id=_('vsa_id'),
1192
                    name=_('displayName'),
1193
                    type=_('vc_type'),
1194
                    vcs=_('vc_cnt'),
1195
                    drives=_('drive_cnt'),
1196
                    stat=_('status'),
1197
                    az=_('AZ'),
1198
                    time=_('createTime'))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1199
1200
    def _print_vsa(self, vsa):
1201
        print self._format_str_vsa %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1202
                dict(id=vsa['id'],
1203
                     vsa_id=vsa['name'],
1204
                     name=vsa['display_name'],
1205
                     type=vsa['vsa_instance_type'].get('name', None),
1206
                     vcs=vsa['vc_count'],
1207
                     drives=vsa['vol_count'],
1208
                     stat=vsa['status'],
1209
                     az=vsa['availability_zone'],
1210
                     time=str(vsa['created_at']))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1211
1212
    def _print_volume_header(self):
1213
        print _('      === Volumes ===')
1214
        print self._format_str_volume %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1215
                dict(id=_('ID'),
1216
                     name=_('name'),
1217
                     size=_('size'),
1218
                     stat=_('status'),
1219
                     att=_('attachment'),
1220
                     time=_('createTime'))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1221
1222
    def _print_volume(self, vol):
1223
        print self._format_str_volume %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1224
                dict(id=vol['id'],
1225
                     name=vol['display_name'] or vol['name'],
1226
                     size=vol['size'],
1227
                     stat=vol['status'],
1228
                     att=vol['attach_status'],
1229
                     time=str(vol['created_at']))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1230
1231
    def _print_drive_header(self):
1232
        print _('      === Drives ===')
1233
        print self._format_str_drive %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1234
                dict(id=_('ID'),
1235
                    name=_('name'),
1236
                    size=_('size'),
1237
                    stat=_('status'),
1238
                    host=_('host'),
1239
                    type=_('type'),
1240
                    tname=_('typeName'),
1241
                    time=_('createTime'))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1242
1243
    def _print_drive(self, drive):
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1244
        if drive['volume_type_id'] is not None and drive.get('volume_type'):
1245
            drive_type_name = drive['volume_type'].get('name')
1246
        else:
1247
            drive_type_name = ''
1248
1249
        print self._format_str_drive %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1250
                dict(id=drive['id'],
1251
                    name=drive['display_name'],
1252
                    size=drive['size'],
1253
                    stat=drive['status'],
1254
                    host=drive['host'],
1255
                    type=drive['volume_type_id'],
1256
                    tname=drive_type_name,
1257
                    time=str(drive['created_at']))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1258
1259
    def _print_instance_header(self):
1260
        print _('      === Instances ===')
1261
        print self._format_str_instance %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1262
                dict(id=_('ID'),
1263
                    name=_('name'),
1264
                    dname=_('disp_name'),
1265
                    image=_('image'),
1266
                    type=_('type'),
1267
                    fl_ip=_('floating_IP'),
1268
                    fx_ip=_('fixed_IP'),
1269
                    stat=_('status'),
1270
                    host=_('host'),
1271
                    time=_('createTime'))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1272
1273
    def _print_instance(self, vc):
1274
1275
        fixed_addr = None
1276
        floating_addr = None
1277
        if vc['fixed_ips']:
1278
            fixed = vc['fixed_ips'][0]
1279
            fixed_addr = fixed['address']
1280
            if fixed['floating_ips']:
1281
                floating_addr = fixed['floating_ips'][0]['address']
1282
        floating_addr = floating_addr or fixed_addr
1283
1284
        print self._format_str_instance %\
1098.388.49 by vladimir.p
changed format string in nova-manage
1285
                dict(id=vc['id'],
1286
                    name=ec2utils.id_to_ec2_id(vc['id']),
1287
                    dname=vc['display_name'],
1288
                    image=('ami-%08x' % int(vc['image_ref'])),
1289
                    type=vc['instance_type']['name'],
1290
                    fl_ip=floating_addr,
1291
                    fx_ip=fixed_addr,
1098.410.1 by Vishvananda Ishaya
remove extra references to state_description
1292
                    stat=vc['vm_state'],
1098.388.49 by vladimir.p
changed format string in nova-manage
1293
                    host=vc['host'],
1294
                    time=str(vc['created_at']))
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1295
1296
    def _list(self, context, vsas, print_drives=False,
1297
                    print_volumes=False, print_instances=False):
1298
        if vsas:
1299
            self._print_vsa_header()
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1300
1301
        for vsa in vsas:
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1302
            self._print_vsa(vsa)
1303
            vsa_id = vsa.get('id')
1304
1305
            if print_instances:
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1306
                instances = self.vsa_api.get_all_vsa_instances(context, vsa_id)
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1307
                if instances:
1308
                    print
1309
                    self._print_instance_header()
1310
                    for instance in instances:
1311
                        self._print_instance(instance)
1312
                    print
1313
1314
            if print_drives:
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1315
                drives = self.vsa_api.get_all_vsa_drives(context, vsa_id)
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1316
                if drives:
1317
                    self._print_drive_header()
1318
                    for drive in drives:
1319
                        self._print_drive(drive)
1320
                    print
1321
1322
            if print_volumes:
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1323
                volumes = self.vsa_api.get_all_vsa_volumes(context, vsa_id)
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1324
                if volumes:
1325
                    self._print_volume_header()
1326
                    for volume in volumes:
1327
                        self._print_volume(volume)
1328
                    print
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1329
1098.388.22 by vladimir.p
merged with nova-1336
1330
    @args('--storage', dest='storage',
1331
        metavar="[{'drive_name': 'type', 'num_drives': N, 'size': M},..]",
1332
        help='Initial storage allocation for VSA')
1333
    @args('--name', dest='name', metavar="<name>", help='VSA name')
1334
    @args('--description', dest='description', metavar="<description>",
1335
        help='VSA description')
1336
    @args('--vc', dest='vc_count', metavar="<number>", help='Number of VCs')
1337
    @args('--instance_type', dest='instance_type_name', metavar="<name>",
1338
        help='Instance type name')
1339
    @args('--image', dest='image_name', metavar="<name>", help='Image name')
1098.388.25 by vladimir.p
returned vsa_manager, nova-manage arg and print changes
1340
    @args('--shared', dest='shared', action="store_true", default=False,
1341
        help='Use shared drives')
1098.388.22 by vladimir.p
merged with nova-1336
1342
    @args('--az', dest='az', metavar="<zone:host>", help='Availability zone')
1098.388.28 by vladimir.p
Merge with nova. Moved user+access to flags. changes for log access mode
1343
    @args('--user', dest="user_id", metavar='<User name>',
1344
            help='User name')
1345
    @args('--project', dest="project_id", metavar='<Project name>',
1346
            help='Project name')
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1347
    def create(self, storage='[]', name=None, description=None, vc_count=1,
1348
                     instance_type_name=None, image_name=None, shared=None,
1098.388.28 by vladimir.p
Merge with nova. Moved user+access to flags. changes for log access mode
1349
                     az=None, user_id=None, project_id=None):
1098.388.22 by vladimir.p
merged with nova-1336
1350
        """Create a VSA."""
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1351
1098.388.28 by vladimir.p
Merge with nova. Moved user+access to flags. changes for log access mode
1352
        if project_id is None:
1353
            try:
1354
                project_id = os.getenv("EC2_ACCESS_KEY").split(':')[1]
1355
            except Exception as exc:
1098.388.49 by vladimir.p
changed format string in nova-manage
1356
                print _("Failed to retrieve project id: %(exc)s") % exc
1098.388.28 by vladimir.p
Merge with nova. Moved user+access to flags. changes for log access mode
1357
                raise
1358
1359
        if user_id is None:
1360
            try:
1361
                project = self.manager.get_project(project_id)
1362
                user_id = project.project_manager_id
1363
            except Exception as exc:
1098.388.49 by vladimir.p
changed format string in nova-manage
1364
                print _("Failed to retrieve user info: %(exc)s") % exc
1098.388.28 by vladimir.p
Merge with nova. Moved user+access to flags. changes for log access mode
1365
                raise
1366
1367
        is_admin = self.manager.is_admin(user_id)
1368
        ctxt = context.RequestContext(user_id, project_id, is_admin)
1369
        if not is_admin and \
1370
           not self.manager.is_project_member(user_id, project_id):
1371
            msg = _("%(user_id)s must be an admin or a "
1372
                    "member of %(project_id)s")
1373
            LOG.warn(msg % locals())
1374
            raise ValueError(msg % locals())
1375
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1376
        # Sanity check for storage string
1377
        storage_list = []
1378
        if storage is not None:
1379
            try:
1380
                storage_list = ast.literal_eval(storage)
1381
            except:
1382
                print _("Invalid string format %s") % storage
1383
                raise
1384
1385
            for node in storage_list:
1386
                if ('drive_name' not in node) or ('num_drives' not in node):
1387
                    print (_("Invalid string format for element %s. " \
1388
                            "Expecting keys 'drive_name' & 'num_drives'"),
1389
                            str(node))
1390
                    raise KeyError
1391
1392
        if instance_type_name == '':
1393
            instance_type_name = None
1098.388.36 by vladimir.p
nova-manage: fixed instance type in vsa creation
1394
        instance_type = instance_types.get_instance_type_by_name(
1395
                                instance_type_name)
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1396
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1397
        if image_name == '':
1398
            image_name = None
1399
1098.388.25 by vladimir.p
returned vsa_manager, nova-manage arg and print changes
1400
        if shared in [None, False, "--full_drives"]:
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1401
            shared = False
1098.388.25 by vladimir.p
returned vsa_manager, nova-manage arg and print changes
1402
        elif shared in [True, "--shared"]:
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1403
            shared = True
1404
        else:
1405
            raise ValueError(_('Shared parameter should be set either to "\
1406
                "--shared or --full_drives'))
1407
1408
        values = {
1409
            'display_name': name,
1410
            'display_description': description,
1411
            'vc_count': int(vc_count),
1098.388.36 by vladimir.p
nova-manage: fixed instance type in vsa creation
1412
            'instance_type': instance_type,
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1413
            'image_name': image_name,
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1414
            'availability_zone': az,
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1415
            'storage': storage_list,
1416
            'shared': shared,
1417
            }
1418
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1419
        result = self.vsa_api.create(ctxt, **values)
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1420
        self._list(ctxt, [result])
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1421
1098.388.22 by vladimir.p
merged with nova-1336
1422
    @args('--id', dest='vsa_id', metavar="<vsa_id>", help='VSA ID')
1423
    @args('--name', dest='name', metavar="<name>", help='VSA name')
1424
    @args('--description', dest='description', metavar="<description>",
1425
        help='VSA description')
1426
    @args('--vc', dest='vc_count', metavar="<number>", help='Number of VCs')
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1427
    def update(self, vsa_id, name=None, description=None, vc_count=None):
1098.388.22 by vladimir.p
merged with nova-1336
1428
        """Updates name/description of vsa and number of VCs."""
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1429
1430
        values = {}
1431
        if name is not None:
1432
            values['display_name'] = name
1433
        if description is not None:
1434
            values['display_description'] = description
1435
        if vc_count is not None:
1436
            values['vc_count'] = int(vc_count)
1437
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1438
        vsa_id = ec2utils.ec2_id_to_id(vsa_id)
1439
        result = self.vsa_api.update(self.context, vsa_id=vsa_id, **values)
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1440
        self._list(self.context, [result])
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1441
1098.388.22 by vladimir.p
merged with nova-1336
1442
    @args('--id', dest='vsa_id', metavar="<vsa_id>", help='VSA ID')
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1443
    def delete(self, vsa_id):
1098.388.22 by vladimir.p
merged with nova-1336
1444
        """Delete a VSA."""
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1445
        vsa_id = ec2utils.ec2_id_to_id(vsa_id)
1446
        self.vsa_api.delete(self.context, vsa_id)
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1447
1098.388.22 by vladimir.p
merged with nova-1336
1448
    @args('--id', dest='vsa_id', metavar="<vsa_id>",
1449
        help='VSA ID (optional)')
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1450
    @args('--all', dest='all', action="store_true", default=False,
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1451
        help='Show all available details')
1452
    @args('--drives', dest='drives', action="store_true",
1453
        help='Include drive-level details')
1454
    @args('--volumes', dest='volumes', action="store_true",
1455
        help='Include volume-level details')
1456
    @args('--instances', dest='instances', action="store_true",
1457
        help='Include instance-level details')
1458
    def list(self, vsa_id=None, all=False,
1459
             drives=False, volumes=False, instances=False):
1098.388.22 by vladimir.p
merged with nova-1336
1460
        """Describe all available VSAs (or particular one)."""
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1461
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1462
        vsas = []
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1463
        if vsa_id is not None:
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1464
            internal_id = ec2utils.ec2_id_to_id(vsa_id)
1465
            vsa = self.vsa_api.get(self.context, internal_id)
1466
            vsas.append(vsa)
1467
        else:
1468
            vsas = self.vsa_api.get_all(self.context)
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1469
1098.388.37 by vladimir.p
nova-manage VSA print & forced update_cap changes; fixed bug with report capabilities; added IP address to VSA APIs; added instances to APIs
1470
        if all:
1471
            drives = volumes = instances = True
1472
1473
        self._list(self.context, vsas, drives, volumes, instances)
1474
1475
    def update_capabilities(self):
1476
        """Forces updates capabilities on all nova-volume nodes."""
1477
1478
        rpc.fanout_cast(context.get_admin_context(),
1479
                 FLAGS.volume_topic,
1480
                 {"method": "notification",
1481
                  "args": {"event": "startup"}})
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1482
1483
1484
class VsaDriveTypeCommands(object):
1485
    """Methods for dealing with VSA drive types"""
1486
1487
    def __init__(self, *args, **kwargs):
1488
        super(VsaDriveTypeCommands, self).__init__(*args, **kwargs)
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1489
        self.context = context.get_admin_context()
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1490
        self._drive_type_template = '%s_%sGB_%sRPM'
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1491
1492
    def _list(self, drives):
1493
        format_str = "%-5s %-30s %-10s %-10s %-10s %-20s %-10s %s"
1494
        if len(drives):
1495
            print format_str %\
1496
                   (_('ID'),
1497
                    _('name'),
1498
                    _('type'),
1499
                    _('size_gb'),
1500
                    _('rpm'),
1501
                    _('capabilities'),
1502
                    _('visible'),
1503
                    _('createTime'))
1504
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1505
        for name, vol_type in drives.iteritems():
1506
            drive = vol_type.get('extra_specs')
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1507
            print format_str %\
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1508
                (str(vol_type['id']),
1509
                drive['drive_name'],
1510
                drive['drive_type'],
1511
                drive['drive_size'],
1512
                drive['drive_rpm'],
1513
                drive.get('capabilities', ''),
1514
                str(drive.get('visible', '')),
1515
                str(vol_type['created_at']))
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1516
1098.388.22 by vladimir.p
merged with nova-1336
1517
    @args('--type', dest='type', metavar="<type>",
1518
        help='Drive type (SATA, SAS, SSD, etc.)')
1519
    @args('--size', dest='size_gb', metavar="<gb>", help='Drive size in GB')
1520
    @args('--rpm', dest='rpm', metavar="<rpm>", help='RPM')
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1521
    @args('--capabilities', dest='capabilities', default=None,
1522
        metavar="<string>", help='Different capabilities')
1523
    @args('--hide', dest='hide', action="store_true", default=False,
1098.388.22 by vladimir.p
merged with nova-1336
1524
        help='Show or hide drive')
1525
    @args('--name', dest='name', metavar="<name>", help='Drive name')
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1526
    def create(self, type, size_gb, rpm, capabilities=None,
1527
                     hide=False, name=None):
1098.388.22 by vladimir.p
merged with nova-1336
1528
        """Create drive type."""
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1529
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1530
        hide = True if hide in [True, "True", "--hide", "hide"] else False
1531
1532
        if name is None:
1533
            name = self._drive_type_template % (type, size_gb, rpm)
1534
1535
        extra_specs = {'type': 'vsa_drive',
1536
                       'drive_name': name,
1537
                       'drive_type': type,
1538
                       'drive_size': size_gb,
1539
                       'drive_rpm': rpm,
1540
                       'visible': True,
1541
                       }
1542
        if hide:
1543
            extra_specs['visible'] = False
1544
1545
        if capabilities is not None and capabilities != '':
1546
            extra_specs['capabilities'] = capabilities
1547
1548
        volume_types.create(self.context, name, extra_specs)
1549
        result = volume_types.get_volume_type_by_name(self.context, name)
1550
        self._list({name: result})
1551
1552
    @args('--name', dest='name', metavar="<name>", help='Drive name')
1553
    @args('--purge', action="store_true", dest='purge', default=False,
1554
            help='purge record from database')
1555
    def delete(self, name, purge):
1556
        """Marks instance types / flavors as deleted"""
1557
        try:
1558
            if purge:
1559
                volume_types.purge(self.context, name)
1560
                verb = "purged"
1561
            else:
1562
                volume_types.destroy(self.context, name)
1563
                verb = "deleted"
1564
        except exception.ApiError:
1565
            print "Valid volume type name is required"
1566
            sys.exit(1)
1567
        except exception.DBError, e:
1568
            print "DB Error: %s" % e
1569
            sys.exit(2)
1570
        except:
1571
            sys.exit(3)
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1572
        else:
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1573
            print "%s %s" % (name, verb)
1574
1575
    @args('--all', dest='all', action="store_true", default=False,
1576
        help='Show all drives (including invisible)')
1098.388.22 by vladimir.p
merged with nova-1336
1577
    @args('--name', dest='name', metavar="<name>",
1578
        help='Show only specified drive')
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1579
    def list(self, all=False, name=None):
1098.388.22 by vladimir.p
merged with nova-1336
1580
        """Describe all available VSA drive types (or particular one)."""
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1581
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1582
        all = False if all in ["--all", False, "False"] else True
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1583
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1584
        search_opts = {'extra_specs': {'type': 'vsa_drive'}}
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1585
        if name is not None:
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1586
            search_opts['extra_specs']['name'] = name
1587
1588
        if all == False:
1589
            search_opts['extra_specs']['visible'] = '1'
1590
1591
        drives = volume_types.get_all_types(self.context,
1592
                                            search_opts=search_opts)
1098.388.35 by vladimir.p
removed VSA/drive_type code from EC2 cloud. changed nova-manage not to use cloud APIs
1593
        self._list(drives)
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1594
1098.388.22 by vladimir.p
merged with nova-1336
1595
    @args('--name', dest='name', metavar="<name>", help='Drive name')
1596
    @args('--type', dest='type', metavar="<type>",
1597
        help='Drive type (SATA, SAS, SSD, etc.)')
1598
    @args('--size', dest='size_gb', metavar="<gb>", help='Drive size in GB')
1599
    @args('--rpm', dest='rpm', metavar="<rpm>", help='RPM')
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1600
    @args('--capabilities', dest='capabilities', default=None,
1601
        metavar="<string>", help='Different capabilities')
1602
    @args('--visible', dest='visible',
1603
        metavar="<show|hide>", help='Show or hide drive')
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1604
    def update(self, name, type=None, size_gb=None, rpm=None,
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1605
                     capabilities=None, visible=None):
1098.388.22 by vladimir.p
merged with nova-1336
1606
        """Update drive type."""
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1607
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1608
        volume_type = volume_types.get_volume_type_by_name(self.context, name)
1609
1610
        extra_specs = {'type': 'vsa_drive'}
1611
1612
        if type:
1613
            extra_specs['drive_type'] = type
1614
1615
        if size_gb:
1616
            extra_specs['drive_size'] = size_gb
1617
1618
        if rpm:
1619
            extra_specs['drive_rpm'] = rpm
1620
1621
        if capabilities:
1622
            extra_specs['capabilities'] = capabilities
1623
1624
        if visible is not None:
1625
            if visible in ["show", True, "True"]:
1626
                extra_specs['visible'] = True
1627
            elif visible in ["hide", False, "False"]:
1628
                extra_specs['visible'] = False
1098.388.25 by vladimir.p
returned vsa_manager, nova-manage arg and print changes
1629
            else:
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1630
                raise ValueError(_('visible parameter should be set to '\
1631
                                   'show or hide'))
1098.388.25 by vladimir.p
returned vsa_manager, nova-manage arg and print changes
1632
1098.388.42 by vladimir.p
VSA code redesign. Drive types completely replaced by Volume types
1633
        db.api.volume_type_extra_specs_update_or_create(self.context,
1634
                    volume_type['id'],
1635
                    extra_specs)
1636
        result = volume_types.get_volume_type_by_name(self.context, name)
1637
        self._list({name: result})
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
1638
1639
577.2.2 by Anthony Young
s/cleanup/volume. volume commands will need their own ns in the long run
1640
class VolumeCommands(object):
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1641
    """Methods for dealing with a cloud in an odd state"""
1642
1098.201.18 by Lvov Maxim
fix pep8
1643
    @args('--volume', dest='volume_id', metavar='<volume id>',
1644
            help='Volume ID')
577.2.2 by Anthony Young
s/cleanup/volume. volume commands will need their own ns in the long run
1645
    def delete(self, volume_id):
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1646
        """Delete a volume, bypassing the check that it
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1647
        must be available."""
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1648
        ctxt = context.get_admin_context()
577.2.4 by Anthony Young
per vish's feedback, allow admin to specify volume id in any of the
1649
        volume = db.volume_get(ctxt, param2id(volume_id))
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1650
        host = volume['host']
669.2.1 by Anthony Young
fix for bug #716847 - if a volume has not been assigned to a host, then delete from db and skip rpc
1651
1652
        if not host:
1653
            print "Volume not yet assigned to host."
1654
            print "Deleting volume from database and skipping rpc."
1655
            db.volume_destroy(ctxt, param2id(volume_id))
1656
            return
1657
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1658
        if volume['status'] == 'in-use':
1659
            print "Volume is in-use."
1660
            print "Detach volume from instance and then try again."
1661
            return
1662
1663
        rpc.cast(ctxt,
1664
                 db.queue_get_for(ctxt, FLAGS.volume_topic, host),
1665
                 {"method": "delete_volume",
1666
                  "args": {"volume_id": volume['id']}})
1667
1098.201.18 by Lvov Maxim
fix pep8
1668
    @args('--volume', dest='volume_id', metavar='<volume id>',
1669
            help='Volume ID')
577.2.2 by Anthony Young
s/cleanup/volume. volume commands will need their own ns in the long run
1670
    def reattach(self, volume_id):
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1671
        """Re-attach a volume that has previously been attached
1672
        to an instance.  Typically called after a compute host
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1673
        has been rebooted."""
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1674
        ctxt = context.get_admin_context()
577.2.4 by Anthony Young
per vish's feedback, allow admin to specify volume id in any of the
1675
        volume = db.volume_get(ctxt, param2id(volume_id))
577.2.1 by Anthony Young
fixes related to #701749. Also, added nova-manage commands to recover
1676
        if not volume['instance_id']:
1677
            print "volume is not attached to an instance"
1678
            return
1679
        instance = db.instance_get(ctxt, volume['instance_id'])
1680
        host = instance['host']
1681
        rpc.cast(ctxt,
1682
                 db.queue_get_for(ctxt, FLAGS.compute_topic, host),
1683
                 {"method": "attach_volume",
1684
                  "args": {"instance_id": instance['id'],
1685
                           "volume_id": volume['id'],
1686
                           "mountpoint": volume['mountpoint']}})
1687
577.3.1 by Vishvananda Ishaya
merged trunkand fixed conflicts and pep error
1688
624.2.14 by Ken Pepple
aliased flavor to instance_types in nova-manage. will probably need to make flavor a full fledged class as users will want to list flavors by flavor name
1689
class InstanceTypeCommands(object):
624.2.1 by Ken Pepple
initial support for dynamic instance_types: db migration and model, stub tests and stub methods.
1690
    """Class for managing instance types / flavors."""
1691
1005.1.1 by Josh Kearney
Pylinted nova-manage
1692
    def _print_instance_types(self, name, val):
624.2.53 by Ken Pepple
refactored nova-manage list (-all, <name>) and fixed docs
1693
        deleted = ('', ', inactive')[val["deleted"] == 1]
624.4.1 by Josh Kearney
Added more columns to instance_types tables
1694
        print ("%s: Memory: %sMB, VCPUS: %s, Storage: %sGB, FlavorID: %s, "
1098.496.1 by Vishvananda Ishaya
show swap in Mb in nova manage
1695
            "Swap: %sMB, RXTX Quota: %sGB, RXTX Cap: %sMB%s") % (
1005.1.1 by Josh Kearney
Pylinted nova-manage
1696
            name, val["memory_mb"], val["vcpus"], val["local_gb"],
624.2.62 by Ken Pepple
fixed coding style per devcamcar review notes
1697
            val["flavorid"], val["swap"], val["rxtx_quota"],
1698
            val["rxtx_cap"], deleted)
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
1699
1098.201.18 by Lvov Maxim
fix pep8
1700
    @args('--name', dest='name', metavar='<name>',
1701
            help='Name of instance type/flavor')
1702
    @args('--memory', dest='memory', metavar='<memory size>',
1703
            help='Memory size')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1704
    @args('--cpu', dest='vcpus', metavar='<num cores>', help='Number cpus')
1098.201.18 by Lvov Maxim
fix pep8
1705
    @args('--local_gb', dest='local_gb', metavar='<local_gb>',
1706
            help='local_gb')
1707
    @args('--flavor', dest='flavorid', metavar='<flavor  id>',
1708
            help='Flavor ID')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1709
    @args('--swap', dest='swap', metavar='<swap>', help='Swap')
1098.201.18 by Lvov Maxim
fix pep8
1710
    @args('--rxtx_quota', dest='rxtx_quota', metavar='<rxtx_quota>',
1711
            help='rxtx_quota')
1712
    @args('--rxtx_cap', dest='rxtx_cap', metavar='<rxtx_cap>',
1713
            help='rxtx_cap')
624.2.67 by Ken Pepple
pep8
1714
    def create(self, name, memory, vcpus, local_gb, flavorid,
624.2.62 by Ken Pepple
fixed coding style per devcamcar review notes
1715
               swap=0, rxtx_quota=0, rxtx_cap=0):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1716
        """Creates instance types / flavors"""
624.2.18 by Ken Pepple
additional error checking for nova-manage instance_type
1717
        try:
624.2.62 by Ken Pepple
fixed coding style per devcamcar review notes
1718
            instance_types.create(name, memory, vcpus, local_gb,
1719
                                  flavorid, swap, rxtx_quota, rxtx_cap)
1098.104.2 by Thierry Carrez
Fix 'undefined name 'e'' pylint error
1720
        except exception.InvalidInput, e:
917.1.1 by Ken Pepple
clarified nova-manage instance_type create error output on duplicate flavorid
1721
            print "Must supply valid parameters to create instance_type"
624.2.32 by Ken Pepple
updated tests and added more error checking
1722
            print e
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
1723
            sys.exit(1)
917.1.1 by Ken Pepple
clarified nova-manage instance_type create error output on duplicate flavorid
1724
        except exception.ApiError, e:
917.1.9 by Ken Pepple
pep8
1725
            print "\n\n"
917.1.10 by Ken Pepple
revamped spacing per Rick Harris suggestion. Added exact error to nova-manage output.
1726
            print "\n%s" % e
917.1.9 by Ken Pepple
pep8
1727
            print "Please ensure instance_type name and flavorid are unique."
917.1.4 by Ken Pepple
reminde admins of --purge option
1728
            print "To complete remove a instance_type, use the --purge flag:"
1729
            print "\n     # nova-manage instance_type delete <name> --purge\n"
1730
            print "Currently defined instance_type names and flavorids:"
917.1.1 by Ken Pepple
clarified nova-manage instance_type create error output on duplicate flavorid
1731
            self.list("--all")
624.2.32 by Ken Pepple
updated tests and added more error checking
1732
            sys.exit(2)
624.2.18 by Ken Pepple
additional error checking for nova-manage instance_type
1733
        except:
1734
            print "Unknown error"
624.2.32 by Ken Pepple
updated tests and added more error checking
1735
            sys.exit(3)
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
1736
        else:
1737
            print "%s created" % name
624.2.1 by Ken Pepple
initial support for dynamic instance_types: db migration and model, stub tests and stub methods.
1738
1098.201.18 by Lvov Maxim
fix pep8
1739
    @args('--name', dest='name', metavar='<name>',
1740
            help='Name of instance type/flavor')
1098.289.1 by Ken Pepple
added --purge optparse for flavor delete
1741
    @args('--purge', action="store_true", dest='purge', default=False,
1742
            help='purge record from database')
1743
    def delete(self, name, purge):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1744
        """Marks instance types / flavors as deleted"""
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
1745
        try:
1098.289.2 by Ken Pepple
fixed conditional because jk0 is very picky :)
1746
            if purge:
624.2.39 by Ken Pepple
completed doc and added --purge option to instance type delete
1747
                instance_types.purge(name)
624.2.46 by Ken Pepple
added purge option and tightened up testing
1748
                verb = "purged"
1749
            else:
1750
                instance_types.destroy(name)
624.2.39 by Ken Pepple
completed doc and added --purge option to instance type delete
1751
                verb = "deleted"
624.2.32 by Ken Pepple
updated tests and added more error checking
1752
        except exception.ApiError:
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
1753
            print "Valid instance type name is required"
1754
            sys.exit(1)
624.2.46 by Ken Pepple
added purge option and tightened up testing
1755
        except exception.DBError, e:
1756
            print "DB Error: %s" % e
1757
            sys.exit(2)
1758
        except:
1759
            sys.exit(3)
624.2.9 by Ken Pepple
rewrote nova-manage instance_type to use correct db.api returned objects and have more robust error handling
1760
        else:
624.2.39 by Ken Pepple
completed doc and added --purge option to instance type delete
1761
            print "%s %s" % (name, verb)
624.2.1 by Ken Pepple
initial support for dynamic instance_types: db migration and model, stub tests and stub methods.
1762
1098.201.18 by Lvov Maxim
fix pep8
1763
    @args('--name', dest='name', metavar='<name>',
1764
            help='Name of instance type/flavor')
624.2.9 by Ken Pepple
rewrote nova-manage instance_type to use correct db.api returned objects and have more robust error handling
1765
    def list(self, name=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1766
        """Lists all active or specific instance types / flavors"""
624.2.53 by Ken Pepple
refactored nova-manage list (-all, <name>) and fixed docs
1767
        try:
992.1.1 by Jason Koelker
Change '== None' to 'is None'
1768
            if name is None:
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
1769
                inst_types = instance_types.get_all_types()
624.2.53 by Ken Pepple
refactored nova-manage list (-all, <name>) and fixed docs
1770
            elif name == "--all":
828.3.5 by Ken Pepple
cleanup another inconsistent use of 1 for True in nova-manage
1771
                inst_types = instance_types.get_all_types(True)
624.2.21 by Ken Pepple
added testing for instance_types.py and refactored nova-manage to use instance_types.py instead of going directly to db.
1772
            else:
930.3.1 by Dan Prince
Refactor so that instances.instance_type is now instances.instance_type_id.
1773
                inst_types = instance_types.get_instance_type_by_name(name)
624.2.53 by Ken Pepple
refactored nova-manage list (-all, <name>) and fixed docs
1774
        except exception.DBError, e:
1775
            _db_error(e)
1776
        if isinstance(inst_types.values()[0], dict):
1777
            for k, v in inst_types.iteritems():
1778
                self._print_instance_types(k, v)
1779
        else:
1780
            self._print_instance_types(name, inst_types)
624.2.1 by Ken Pepple
initial support for dynamic instance_types: db migration and model, stub tests and stub methods.
1781
1782
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1783
class ImageCommands(object):
1784
    """Methods for dealing with a cloud in an odd state"""
1785
1786
    def __init__(self, *args, **kwargs):
1084.2.33 by William Wolf
moved utils functions into nova/image/
1787
        self.image_service = image.get_default_image_service()
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1788
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1789
    def _register(self, container_format, disk_format,
758.3.13 by Vishvananda Ishaya
update code to work with new container and disk formats from glance
1790
                  path, owner, name=None, is_public='T',
1791
                  architecture='x86_64', kernel_id=None, ramdisk_id=None):
922.2.6 by Vishvananda Ishaya
unite the filtering done by glance client and s3
1792
        meta = {'is_public': (is_public == 'T'),
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1793
                'name': name,
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1794
                'container_format': container_format,
758.3.13 by Vishvananda Ishaya
update code to work with new container and disk formats from glance
1795
                'disk_format': disk_format,
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1796
                'properties': {'image_state': 'available',
922.2.6 by Vishvananda Ishaya
unite the filtering done by glance client and s3
1797
                               'project_id': owner,
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1798
                               'architecture': architecture,
922.2.6 by Vishvananda Ishaya
unite the filtering done by glance client and s3
1799
                               'image_location': 'local'}}
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1800
        if kernel_id:
1801
            meta['properties']['kernel_id'] = int(kernel_id)
1802
        if ramdisk_id:
1803
            meta['properties']['ramdisk_id'] = int(ramdisk_id)
1804
        elevated = context.get_admin_context()
1805
        try:
1806
            with open(path) as ifile:
1807
                image = self.image_service.create(elevated, meta, ifile)
1808
            new = image['id']
1809
            print _("Image registered to %(new)s (%(new)08x).") % locals()
1810
            return new
1811
        except Exception as exc:
1812
            print _("Failed to register %(path)s: %(exc)s") % locals()
1813
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1814
    @args('--image', dest='image', metavar='<image>', help='Image')
1815
    @args('--kernel', dest='kernel', metavar='<kernel>', help='Kernel')
1816
    @args('--ram', dest='ramdisk', metavar='<ramdisk>', help='RAM disk')
1817
    @args('--owner', dest='owner', metavar='<owner>', help='Image owner')
1818
    @args('--name', dest='name', metavar='<name>', help='Image name')
1098.201.18 by Lvov Maxim
fix pep8
1819
    @args('--public', dest='is_public', metavar="<'T'|'F'>",
1820
            help='Image public or not')
1821
    @args('--arch', dest='architecture', metavar='<arch>',
1822
            help='Architecture')
758.3.9 by Vishvananda Ishaya
rework register commands based on review
1823
    def all_register(self, image, kernel, ramdisk, owner, name=None,
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1824
                 is_public='T', architecture='x86_64'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1825
        """Uploads an image, kernel, and ramdisk into the image_service"""
758.3.9 by Vishvananda Ishaya
rework register commands based on review
1826
        kernel_id = self.kernel_register(kernel, owner, None,
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1827
                                   is_public, architecture)
758.3.9 by Vishvananda Ishaya
rework register commands based on review
1828
        ramdisk_id = self.ramdisk_register(ramdisk, owner, None,
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1829
                                    is_public, architecture)
758.3.9 by Vishvananda Ishaya
rework register commands based on review
1830
        self.image_register(image, owner, name, is_public,
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1831
                            architecture, 'ami', 'ami',
1832
                            kernel_id, ramdisk_id)
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1833
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1834
    @args('--path', dest='path', metavar='<path>', help='Image path')
1835
    @args('--owner', dest='owner', metavar='<owner>', help='Image owner')
1836
    @args('--name', dest='name', metavar='<name>', help='Image name')
1098.201.18 by Lvov Maxim
fix pep8
1837
    @args('--public', dest='is_public', metavar="<'T'|'F'>",
1838
            help='Image public or not')
1839
    @args('--arch', dest='architecture', metavar='<arch>',
1840
            help='Architecture')
1841
    @args('--cont_format', dest='container_format',
1842
            metavar='<container format>',
1843
            help='Container format(default bare)')
1844
    @args('--disk_format', dest='disk_format', metavar='<disk format>',
1845
            help='Disk format(default: raw)')
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1846
    @args('--kernel', dest='kernel_id', metavar='<kernel>', help='Kernel')
1847
    @args('--ram', dest='ramdisk_id', metavar='<ramdisk>', help='RAM disk')
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1848
    def image_register(self, path, owner, name=None, is_public='T',
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1849
                       architecture='x86_64', container_format='bare',
1850
                       disk_format='raw', kernel_id=None, ramdisk_id=None):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1851
        """Uploads an image into the image_service"""
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1852
        return self._register(container_format, disk_format, path,
758.3.13 by Vishvananda Ishaya
update code to work with new container and disk formats from glance
1853
                              owner, name, is_public, architecture,
1854
                              kernel_id, ramdisk_id)
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1855
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1856
    @args('--path', dest='path', metavar='<path>', help='Image path')
1857
    @args('--owner', dest='owner', metavar='<owner>', help='Image owner')
1858
    @args('--name', dest='name', metavar='<name>', help='Image name')
1098.201.18 by Lvov Maxim
fix pep8
1859
    @args('--public', dest='is_public', metavar="<'T'|'F'>",
1860
            help='Image public or not')
1861
    @args('--arch', dest='architecture', metavar='<arch>',
1862
            help='Architecture')
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1863
    def kernel_register(self, path, owner, name=None, is_public='T',
1864
               architecture='x86_64'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1865
        """Uploads a kernel into the image_service"""
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1866
        return self._register('aki', 'aki', path, owner, name,
758.3.13 by Vishvananda Ishaya
update code to work with new container and disk formats from glance
1867
                              is_public, architecture)
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1868
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
1869
    @args('--path', dest='path', metavar='<path>', help='Image path')
1870
    @args('--owner', dest='owner', metavar='<owner>', help='Image owner')
1871
    @args('--name', dest='name', metavar='<name>', help='Image name')
1098.201.18 by Lvov Maxim
fix pep8
1872
    @args('--public', dest='is_public', metavar="<'T'|'F'>",
1873
            help='Image public or not')
1874
    @args('--arch', dest='architecture', metavar='<arch>',
1875
            help='Architecture')
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1876
    def ramdisk_register(self, path, owner, name=None, is_public='T',
1877
                architecture='x86_64'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1878
        """Uploads a ramdisk into the image_service"""
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1879
        return self._register('ari', 'ari', path, owner, name,
758.3.13 by Vishvananda Ishaya
update code to work with new container and disk formats from glance
1880
                              is_public, architecture)
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1881
1882
    def _lookup(self, old_image_id):
1098.271.1 by Vishvananda Ishaya
Pass a real context object into image service calls
1883
        elevated = context.get_admin_context()
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1884
        try:
1885
            internal_id = ec2utils.ec2_id_to_id(old_image_id)
1098.271.1 by Vishvananda Ishaya
Pass a real context object into image service calls
1886
            image = self.image_service.show(elevated, internal_id)
1063.1.1 by Vishvananda Ishaya
make sure proper exceptions are raised for ec2 id conversion and add tests
1887
        except (exception.InvalidEc2Id, exception.ImageNotFound):
1098.271.1 by Vishvananda Ishaya
Pass a real context object into image service calls
1888
            image = self.image_service.show_by_name(elevated, old_image_id)
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1889
        return image['id']
1890
1891
    def _old_to_new(self, old):
758.3.13 by Vishvananda Ishaya
update code to work with new container and disk formats from glance
1892
        mapping = {'machine': 'ami',
1893
                   'kernel': 'aki',
1894
                   'ramdisk': 'ari'}
1895
        container_format = mapping[old['type']]
1896
        disk_format = container_format
922.2.2 by Vishvananda Ishaya
remove all references to image_type and change nova-manage upload to set container format more intelligently
1897
        if container_format == 'ami' and not old.get('kernelId'):
1898
            container_format = 'bare'
1899
            disk_format = 'raw'
758.3.13 by Vishvananda Ishaya
update code to work with new container and disk formats from glance
1900
        new = {'disk_format': disk_format,
1901
               'container_format': container_format,
922.2.6 by Vishvananda Ishaya
unite the filtering done by glance client and s3
1902
               'is_public': old['isPublic'],
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1903
               'name': old['imageId'],
1904
               'properties': {'image_state': old['imageState'],
922.2.6 by Vishvananda Ishaya
unite the filtering done by glance client and s3
1905
                              'project_id': old['imageOwnerId'],
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1906
                              'architecture': old['architecture'],
922.2.6 by Vishvananda Ishaya
unite the filtering done by glance client and s3
1907
                              'image_location': old['imageLocation']}}
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1908
        if old.get('kernelId'):
1909
            new['properties']['kernel_id'] = self._lookup(old['kernelId'])
1910
        if old.get('ramdiskId'):
1911
            new['properties']['ramdisk_id'] = self._lookup(old['ramdiskId'])
1912
        return new
1913
1914
    def _convert_images(self, images):
1915
        elevated = context.get_admin_context()
1916
        for image_path, image_metadata in images.iteritems():
1917
            meta = self._old_to_new(image_metadata)
1918
            old = meta['name']
1919
            try:
1920
                with open(image_path) as ifile:
1921
                    image = self.image_service.create(elevated, meta, ifile)
1922
                new = image['id']
1923
                print _("Image %(old)s converted to " \
1924
                        "%(new)s (%(new)08x).") % locals()
1925
            except Exception as exc:
1926
                print _("Failed to convert %(old)s: %(exc)s") % locals()
1927
1098.201.18 by Lvov Maxim
fix pep8
1928
    @args('--dir', dest='directory', metavar='<path>',
1929
            help='Images directory')
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1930
    def convert(self, directory):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1931
        """Uploads old objectstore images in directory to new service"""
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1932
        machine_images = {}
1933
        other_images = {}
758.3.11 by Vishvananda Ishaya
move the images_dir out of the way when converting
1934
        directory = os.path.abspath(directory)
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1935
        for fn in glob.glob("%s/*/info.json" % directory):
1936
            try:
1937
                image_path = os.path.join(fn.rpartition('/')[0], 'image')
1938
                with open(fn) as metadata_file:
1939
                    image_metadata = json.load(metadata_file)
1940
                if image_metadata['type'] == 'machine':
1941
                    machine_images[image_path] = image_metadata
1942
                else:
1943
                    other_images[image_path] = image_metadata
1005.1.1 by Josh Kearney
Pylinted nova-manage
1944
            except Exception:
758.3.8 by Vishvananda Ishaya
make compute get the new images properly, fix a bunch of tests, and provide conversion commands
1945
                print _("Failed to load %(fn)s.") % locals()
1946
        # NOTE(vish): do kernels and ramdisks first so images
1947
        self._convert_images(other_images)
1948
        self._convert_images(machine_images)
1949
1950
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
1951
class AgentBuildCommands(object):
1952
    """Class for managing agent builds."""
1953
1098.75.8 by Johannes Erdfelt
PEP8 cleanups
1954
    def create(self, os, architecture, version, url, md5hash,
1955
                hypervisor='xen'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1956
        """Creates a new agent build."""
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
1957
        ctxt = context.get_admin_context()
1958
        agent_build = db.agent_build_create(ctxt,
1959
                                            {'hypervisor': hypervisor,
1960
                                             'os': os,
1961
                                             'architecture': architecture,
1962
                                             'version': version,
1963
                                             'url': url,
1964
                                             'md5hash': md5hash})
1965
1966
    def delete(self, os, architecture, hypervisor='xen'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
1967
        """Deletes an existing agent build."""
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
1968
        ctxt = context.get_admin_context()
1969
        agent_build_ref = db.agent_build_get_by_triple(ctxt,
1970
                                  hypervisor, os, architecture)
1971
        db.agent_build_destroy(ctxt, agent_build_ref['id'])
1972
1098.75.9 by Johannes Erdfelt
Print list of agent builds a bit prettier
1973
    def list(self, hypervisor=None):
1098.75.13 by Johannes Erdfelt
Clean up docstrings to match HACKING
1974
        """Lists all agent builds.
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
1975
        arguments: <none>"""
1098.75.9 by Johannes Erdfelt
Print list of agent builds a bit prettier
1976
        fmt = "%-10s  %-8s  %12s  %s"
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
1977
        ctxt = context.get_admin_context()
1098.75.9 by Johannes Erdfelt
Print list of agent builds a bit prettier
1978
        by_hypervisor = {}
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
1979
        for agent_build in db.agent_build_get_all(ctxt):
1098.75.9 by Johannes Erdfelt
Print list of agent builds a bit prettier
1980
            buildlist = by_hypervisor.get(agent_build.hypervisor)
1981
            if not buildlist:
1982
                buildlist = by_hypervisor[agent_build.hypervisor] = []
1983
1984
            buildlist.append(agent_build)
1985
1986
        for key, buildlist in by_hypervisor.iteritems():
1987
            if hypervisor and key != hypervisor:
1988
                continue
1989
1990
            print "Hypervisor: %s" % key
1991
            print fmt % ('-' * 10, '-' * 8, '-' * 12, '-' * 32)
1992
            for agent_build in buildlist:
1993
                print fmt % (agent_build.os, agent_build.architecture,
1994
                             agent_build.version, agent_build.md5hash)
1995
                print '    %s' % agent_build.url
1996
1997
            print
1998
1999
    def modify(self, os, architecture, version, url, md5hash,
2000
               hypervisor='xen'):
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
2001
        """Update an existing agent build."""
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
2002
        ctxt = context.get_admin_context()
2003
        agent_build_ref = db.agent_build_get_by_triple(ctxt,
2004
                                  hypervisor, os, architecture)
2005
        db.agent_build_update(ctxt, agent_build_ref['id'],
2006
                              {'version': version,
2007
                               'url': url,
2008
                               'md5hash': md5hash})
2009
2010
1098.31.1 by Justin Shepherd
added 'nova-manage config list' which will list out all of the flags and their values. I also alphabetized the list of available categories
2011
class ConfigCommands(object):
2012
    """Class for exposing the flags defined by flag_file(s)."""
2013
2014
    def __init__(self):
2015
        pass
2016
2017
    def list(self):
2018
        print FLAGS.FlagsIntoString()
2019
2020
247.1.1 by Eric Day
More bin/ pep8/pylint cleanup.
2021
CATEGORIES = [
752.4.1 by Monsyne Dragon
Add in multi-tenant support in openstack api.
2022
    ('account', AccountCommands),
1098.75.2 by Johannes Erdfelt
Record architecture of image for matching to agent build later.
2023
    ('agent', AgentBuildCommands),
1098.31.1 by Justin Shepherd
added 'nova-manage config list' which will list out all of the flags and their values. I also alphabetized the list of available categories
2024
    ('config', ConfigCommands),
2025
    ('db', DbCommands),
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
2026
    ('drive', VsaDriveTypeCommands),
1098.31.1 by Justin Shepherd
added 'nova-manage config list' which will list out all of the flags and their values. I also alphabetized the list of available categories
2027
    ('fixed', FixedIpCommands),
2028
    ('flavor', InstanceTypeCommands),
2029
    ('floating', FloatingIpCommands),
1098.146.2 by Mike Scherbakov
Renamed 'nova-manage server list' -> 'nova-manage host list' to differentiate physical hosts from VMs
2030
    ('host', HostCommands),
1098.31.1 by Justin Shepherd
added 'nova-manage config list' which will list out all of the flags and their values. I also alphabetized the list of available categories
2031
    ('instance_type', InstanceTypeCommands),
2032
    ('image', ImageCommands),
2033
    ('network', NetworkCommands),
3.2.2 by Vishvananda Ishaya
Add project methods to nova-manage
2034
    ('project', ProjectCommands),
94 by andy
more commands in nova-manage for projects and roles
2035
    ('role', RoleCommands),
1098.31.1 by Justin Shepherd
added 'nova-manage config list' which will list out all of the flags and their values. I also alphabetized the list of available categories
2036
    ('service', ServiceCommands),
270.1.1 by Jesse Andrews
add a shell to nova-manage, which respects flags (taken from django)
2037
    ('shell', ShellCommands),
1098.31.1 by Justin Shepherd
added 'nova-manage config list' which will list out all of the flags and their values. I also alphabetized the list of available categories
2038
    ('user', UserCommands),
2039
    ('version', VersionCommands),
439.1.47 by Kei Masumoto
Merged to trunk rev 757. Main changes are below.
2040
    ('vm', VmCommands),
700.7.3 by Christian Berendt
beautification...
2041
    ('volume', VolumeCommands),
1098.388.1 by vladimir.p
VSA: first cut. merged with 1279
2042
    ('vpn', VpnCommands),
2043
    ('vsa', VsaCommands)]
1 by Jesse Andrews
initial commit
2044
439.3.1 by Muneyuki Noguchi
Add support for EBS volumes to the live migration feature.
2045
1 by Jesse Andrews
initial commit
2046
def lazy_match(name, key_value_tuples):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
2047
    """Finds all objects that have a key that case insensitively contains
2048
    [name] key_value_tuples is a list of tuples of the form (key, value)
1 by Jesse Andrews
initial commit
2049
    returns a list of tuples of the form (key, value)"""
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
2050
    result = []
2051
    for (k, v) in key_value_tuples:
2052
        if k.lower().find(name.lower()) == 0:
2053
            result.append((k, v))
2054
    if len(result) == 0:
2055
        print "%s does not match any options:" % name
2056
        for k, _v in key_value_tuples:
2057
            print "\t%s" % k
2058
        sys.exit(2)
2059
    if len(result) > 1:
2060
        print "%s matched multiple options:" % name
2061
        for k, _v in result:
2062
            print "\t%s" % k
2063
        sys.exit(2)
2064
    return result
1 by Jesse Andrews
initial commit
2065
2066
2067
def methods_of(obj):
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
2068
    """Get all callable methods of an object that don't start with underscore
1 by Jesse Andrews
initial commit
2069
    returns a list of tuples of the form (method_name, method)"""
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
2070
    result = []
2071
    for i in dir(obj):
2072
        if callable(getattr(obj, i)) and not i.startswith('_'):
2073
            result.append((i, getattr(obj, i)))
2074
    return result
2075
2076
2077
def main():
2078
    """Parse options and call the appropriate class/method."""
411.2.1 by Soren Hansen
Unify the location of the default flagfile.
2079
    utils.default_flagfile()
1 by Jesse Andrews
initial commit
2080
    argv = FLAGS(sys.argv)
706.2.15 by Vishvananda Ishaya
switch to explicit call to logging.setup()
2081
    logging.setup()
316.3.1 by Ewan Mellor
Bug #654034: nova-manage doesn't honour --verbose flag
2082
1 by Jesse Andrews
initial commit
2083
    script_name = argv.pop(0)
2084
    if len(argv) < 1:
1033.1.1 by Ken Pepple
added nova version output to usage printout for nova-manage
2085
        print _("\nOpenStack Nova version: %s (%s)\n") %\
2086
                (version.version_string(), version.version_string_with_vcs())
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
2087
        print script_name + " category action [<args>]"
904.1.1 by Vishvananda Ishaya
displays an error message if a command fails, so that the user knows something went wrong
2088
        print _("Available categories:")
2089
        for k, _v in CATEGORIES:
1 by Jesse Andrews
initial commit
2090
            print "\t%s" % k
2091
        sys.exit(2)
2092
    category = argv.pop(0)
247.1.1 by Eric Day
More bin/ pep8/pylint cleanup.
2093
    matches = lazy_match(category, CATEGORIES)
1 by Jesse Andrews
initial commit
2094
    # instantiate the command group object
2095
    category, fn = matches[0]
2096
    command_object = fn()
2097
    actions = methods_of(command_object)
2098
    if len(argv) < 1:
1098.201.8 by Yuriy Taraday
Add possibility to call commands without subcommands.
2099
        if hasattr(command_object, '__call__'):
1098.201.15 by Lvov Maxim
fix 'version' command
2100
            action = ''
1098.201.8 by Yuriy Taraday
Add possibility to call commands without subcommands.
2101
            fn = command_object.__call__
2102
        else:
2103
            print script_name + " category action [<args>]"
2104
            print _("Available actions for %s category:") % category
2105
            for k, _v in actions:
2106
                print "\t%s" % k
2107
            sys.exit(2)
2108
    else:
2109
        action = argv.pop(0)
2110
        matches = lazy_match(action, actions)
2111
        action, fn = matches[0]
1092.2.2 by Lvov Maxim
add support for keyword arguments
2112
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
2113
    # For not decorated methods
1098.201.9 by Lvov Maxim
remove argument help from docstrings + minor fix
2114
    options = getattr(fn, 'options', [])
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
2115
1098.201.15 by Lvov Maxim
fix 'version' command
2116
    usage = "%%prog %s %s <args> [options]" % (category, action)
1092.2.5 by Lvov Maxim
decorators for action methods added
2117
    parser = OptionParser(usage=usage)
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
2118
    for ar, kw in options:
1092.2.5 by Lvov Maxim
decorators for action methods added
2119
        parser.add_option(*ar, **kw)
1092.2.4 by Lvov Maxim
parse options with optparse, options prepended '--'
2120
    (opts, fn_args) = parser.parse_args(argv)
2121
    fn_kwargs = vars(opts)
1092.2.5 by Lvov Maxim
decorators for action methods added
2122
1092.2.4 by Lvov Maxim
parse options with optparse, options prepended '--'
2123
    for k, v in fn_kwargs.items():
2124
        if v is None:
2125
            del fn_kwargs[k]
1092.2.5 by Lvov Maxim
decorators for action methods added
2126
1 by Jesse Andrews
initial commit
2127
    # call the action with the remaining arguments
2128
    try:
1092.2.2 by Lvov Maxim
add support for keyword arguments
2129
        fn(*fn_args, **fn_kwargs)
97 by Vishvananda Ishaya
add exit status to nova-manage
2130
        sys.exit(0)
1 by Jesse Andrews
initial commit
2131
    except TypeError:
904.1.1 by Vishvananda Ishaya
displays an error message if a command fails, so that the user knows something went wrong
2132
        print _("Possible wrong number of arguments supplied")
1098.201.2 by Lvov Maxim
removed posargs decorator, all methods decorated
2133
        print fn.__doc__
2134
        parser.print_help()
292.8.3 by Vishvananda Ishaya
get rid of network indexes and make networks into a pool
2135
        raise
904.1.2 by Vishvananda Ishaya
don't print the error message on sys.exit(0)
2136
    except Exception:
904.1.1 by Vishvananda Ishaya
displays an error message if a command fails, so that the user knows something went wrong
2137
        print _("Command failed, please check log for more info")
2138
        raise
1 by Jesse Andrews
initial commit
2139
206.3.3 by Eric Day
Cleaned up pep8/pylint for bin/* files. I did not fix rsapi since this is already cleaned up in another branch.
2140
if __name__ == '__main__':
2141
    main()