~zulcss/ubuntu/precise/quantum/trunk

« back to all changes in this revision

Viewing changes to quantum/plugins/cisco/client/cli.py

  • Committer: Chuck Short
  • Date: 2012-11-26 19:51:11 UTC
  • mfrom: (26.1.1 raring-proposed)
  • Revision ID: zulcss@ubuntu.com-20121126195111-jnz2cr4xi6whemw2
* New upstream release for the Ubuntu Cloud Archive.
* debian/patches/*: Refreshed for opening of Grizzly.
* New upstream release.
* debian/rules: FTFBS if there is missing binaries.
* debian/quantum-server.install: Add quantum-debug.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
 
#
3
 
# Copyright 2011 Cisco Systems, Inc.  All rights reserved.
4
 
#
5
 
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
6
 
#    not use this file except in compliance with the License. You may obtain
7
 
#    a copy of the License at
8
 
#
9
 
#         http://www.apache.org/licenses/LICENSE-2.0
10
 
#
11
 
#    Unless required by applicable law or agreed to in writing, software
12
 
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
 
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
 
#    License for the specific language governing permissions and limitations
15
 
#    under the License.
16
 
#
17
 
# Initial structure and framework of this CLI has been borrowed from Quantum,
18
 
# written by the following authors
19
 
# @author: Somik Behera, Nicira Networks, Inc.
20
 
# @author: Brad Hall, Nicira Networks, Inc.
21
 
# @author: Salvatore Orlando, Citrix
22
 
#
23
 
# Cisco adaptation for extensions
24
 
# @author: Sumit Naiksatam, Cisco Systems, Inc.
25
 
# @author: Ying Liu, Cisco Systems, Inc.
26
 
 
27
 
import logging
28
 
import logging.handlers
29
 
from optparse import OptionParser
30
 
import os
31
 
import sys
32
 
 
33
 
import quantumclient.cli as qcli
34
 
from quantumclient import Client
35
 
 
36
 
 
37
 
LOG = logging.getLogger('quantum')
38
 
 
39
 
 
40
 
FORMAT = 'json'
41
 
#ACTION_PREFIX_EXT = '/v1.0'
42
 
#ACTION_PREFIX_CSCO = ACTION_PREFIX_EXT + \
43
 
#        '/extensions/csco/tenants/{tenant_id}'
44
 
VERSION = '1.0'
45
 
URI_PREFIX_EXT = ''
46
 
URI_PREFIX_CSCO = '/extensions/csco/tenants/{tenant_id}'
47
 
TENANT_ID = 'nova'
48
 
CSCO_EXT_NAME = 'Cisco Nova Tenant'
49
 
DEFAULT_QUANTUM_VERSION = '1.1'
50
 
 
51
 
 
52
 
def help():
53
 
    """Help for CLI"""
54
 
    print "\nCisco Extension Commands:"
55
 
    for key in COMMANDS.keys():
56
 
        print "    %s %s" % (
57
 
            key, " ".join(["<%s>" % y for y in COMMANDS[key]["args"]]))
58
 
 
59
 
 
60
 
def build_args(cmd, cmdargs, arglist):
61
 
    """Building the list of args for a particular CLI"""
62
 
    args = []
63
 
    orig_arglist = arglist[:]
64
 
    try:
65
 
        for cmdarg in cmdargs:
66
 
            args.append(arglist[0])
67
 
            del arglist[0]
68
 
    except:
69
 
        LOG.error("Not enough arguments for \"%s\" (expected: %d, got: %d)" % (
70
 
            cmd, len(cmdargs), len(orig_arglist)))
71
 
        print "Usage:\n    %s %s" % (
72
 
            cmd, " ".join(["<%s>" % y for y in COMMANDS[cmd]["args"]]))
73
 
        sys.exit()
74
 
    if len(arglist) > 0:
75
 
        LOG.error("Too many arguments for \"%s\" (expected: %d, got: %d)" % (
76
 
            cmd, len(cmdargs), len(orig_arglist)))
77
 
        print "Usage:\n    %s %s" % (
78
 
            cmd, " ".join(["<%s>" % y for y in COMMANDS[cmd]["args"]]))
79
 
        sys.exit()
80
 
    return args
81
 
 
82
 
 
83
 
def list_extensions(*args):
84
 
    """Invoking the action to get the supported extensions"""
85
 
    request_url = "/extensions"
86
 
    client = Client(HOST, PORT, USE_SSL, format='json',
87
 
                    version=VERSION, uri_prefix=URI_PREFIX_EXT, tenant="dummy")
88
 
    data = client.do_request('GET', request_url)
89
 
    print("Obtained supported extensions from Quantum: %s" % data)
90
 
 
91
 
 
92
 
def schedule_host(tenant_id, instance_id, user_id=None):
93
 
    """Gets the host name from the Quantum service"""
94
 
    project_id = tenant_id
95
 
 
96
 
    instance_data_dict = {
97
 
        'novatenant': {
98
 
            'instance_id': instance_id,
99
 
            'instance_desc': {
100
 
                'user_id': user_id,
101
 
                'project_id': project_id,
102
 
            },
103
 
        },
104
 
    }
105
 
 
106
 
    request_url = "/novatenants/" + project_id + "/schedule_host"
107
 
    client = Client(HOST, PORT, USE_SSL, format='json', tenant=TENANT_ID,
108
 
                    version=VERSION, uri_prefix=URI_PREFIX_CSCO)
109
 
    data = client.do_request('PUT', request_url, body=instance_data_dict)
110
 
 
111
 
    hostname = data["host_list"]["host_1"]
112
 
    if not hostname:
113
 
        print("Scheduler was unable to locate a host"
114
 
              " for this request. Is the appropriate"
115
 
              " service running?")
116
 
 
117
 
    print("Quantum service returned host: %s" % hostname)
118
 
 
119
 
 
120
 
def create_multiport(tenant_id, net_id_list, *args):
121
 
    """Creates ports on a single host"""
122
 
    net_list = net_id_list.split(",")
123
 
    ports_info = {'multiport':
124
 
                  {'status': 'ACTIVE',
125
 
                   'net_id_list': net_list,
126
 
                   'ports_desc': {'key': 'value'}}}
127
 
 
128
 
    request_url = "/multiport"
129
 
    client = Client(HOST, PORT, USE_SSL, format='json', tenant=tenant_id,
130
 
                    version=VERSION, uri_prefix=URI_PREFIX_CSCO)
131
 
    data = client.do_request('POST', request_url, body=ports_info)
132
 
 
133
 
    print("Created ports: %s" % data)
134
 
 
135
 
 
136
 
COMMANDS = {
137
 
    "create_multiport": {
138
 
        "func": create_multiport,
139
 
        "args": ["tenant-id",
140
 
                 "net-id-list (comma separated list of netword IDs)"],
141
 
    },
142
 
    "list_extensions": {
143
 
        "func": list_extensions,
144
 
        "args": [],
145
 
    },
146
 
    "schedule_host": {
147
 
        "func": schedule_host,
148
 
        "args": ["tenant-id", "instance-id"],
149
 
    },
150
 
}
151
 
 
152
 
 
153
 
def main():
154
 
    import cli
155
 
    usagestr = "Usage: %prog [OPTIONS] <command> [args]"
156
 
    PARSER = OptionParser(usage=usagestr)
157
 
    PARSER.add_option("-H", "--host", dest="host",
158
 
                      type="string", default="127.0.0.1",
159
 
                      help="ip address of api host")
160
 
    PARSER.add_option("-p", "--port", dest="port",
161
 
                      type="int", default=9696, help="api poort")
162
 
    PARSER.add_option("-s", "--ssl", dest="ssl",
163
 
                      action="store_true", default=False, help="use ssl")
164
 
    PARSER.add_option("-v", "--verbose", dest="verbose",
165
 
                      action="store_true", default=False,
166
 
                      help="turn on verbose logging")
167
 
    PARSER.add_option("-f", "--logfile", dest="logfile",
168
 
                      type="string", default="syslog", help="log file path")
169
 
    PARSER.add_option(
170
 
        '--version', default=DEFAULT_QUANTUM_VERSION,
171
 
        help='Accepts 1.1 and 1.0, defaults to env[QUANTUM_VERSION].')
172
 
    options, args = PARSER.parse_args()
173
 
 
174
 
    if options.verbose:
175
 
        LOG.setLevel(logging.DEBUG)
176
 
    else:
177
 
        LOG.setLevel(logging.WARN)
178
 
 
179
 
    if options.logfile == "syslog":
180
 
        LOG.addHandler(logging.handlers.SysLogHandler(address='/dev/log'))
181
 
    else:
182
 
        LOG.addHandler(logging.handlers.WatchedFileHandler(options.logfile))
183
 
        os.chmod(options.logfile, 0644)
184
 
 
185
 
    version = options.version
186
 
    if len(args) < 1:
187
 
        PARSER.print_help()
188
 
        qcli.help(version)
189
 
        help()
190
 
        sys.exit(1)
191
 
 
192
 
    CMD = args[0]
193
 
    if CMD in qcli.commands['1.1'].keys():
194
 
        qcli.main()
195
 
        sys.exit(1)
196
 
    if CMD not in COMMANDS.keys():
197
 
        LOG.error("Unknown command: %s" % CMD)
198
 
        qcli.help(version)
199
 
        help()
200
 
        sys.exit(1)
201
 
 
202
 
    args = build_args(CMD, COMMANDS[CMD]["args"], args[1:])
203
 
 
204
 
    LOG.info("Executing command \"%s\" with args: %s" % (CMD, args))
205
 
 
206
 
    HOST = options.host
207
 
    PORT = options.port
208
 
    USE_SSL = options.ssl
209
 
    COMMANDS[CMD]["func"](*args)
210
 
 
211
 
    LOG.info("Command execution completed")
212
 
    sys.exit(0)
213
 
 
214
 
 
215
 
if __name__ == "__main__":
216
 
    main()