1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nicira Networks, Inc.
# Copyright 2011 Citrix Systems
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# @author: Somik Behera, Nicira Networks, Inc.
# @author: Brad Hall, Nicira Networks, Inc.
# @author: Salvatore Orlando, Citrix
""" Functions providing implementation for CLI commands. """
import logging
import traceback
LOG = logging.getLogger('quantumclient.cli_lib')
FORMAT = "json"
class OutputTemplate(object):
""" A class for generating simple templated output.
Based on Python templating mechanism.
Templates can also express attributes on objects, such as network.id;
templates can also be nested, thus allowing for iteration on inner
templates.
Examples:
1) template with class attributes
Name: %(person.name)s \n
Surname: %(person.surname)s \n
2) template with iteration
Telephone numbers: \n
%(phone_numbers|Telephone number:%(number)s)
3) template with iteration and class attributes
Addresses: \n
%(Addresses|Street:%(address.street)s\nNumber%(address.number))
Instances of this class are initialized with a template string and
the dictionary for performing substitution. The class implements the
__str__ method, so it can be directly printed.
"""
def __init__(self, template, data):
self._template = template
self.data = data
def __str__(self):
return self._template % self
def __getitem__(self, key):
items = key.split("|")
# Note(madhav-puri): for now the logic supports only 0 or 1 list
# indicators (|) in a template.
if len(items) > 2:
raise Exception("Found more than one list indicator (|).")
if len(items) == 1:
return self._make_attribute(key)
else:
# Note(salvatore-orlando): items[0] must be subscriptable
return self._make_list(self._make_attribute(items[0]), items[1])
def _make_attribute(self, item):
""" Renders an entity attribute key in the template.
e.g.: entity.attribute
"""
items = item.split('.')
attr = self.data[items[0]]
for _item in items[1:]:
attr = attr[_item]
return attr
def _make_list(self, items, inner_template):
""" Renders a list key in the template.
e.g.: %(list|item data:%(item))
"""
#make sure list is subscriptable
if not hasattr(items, '__getitem__'):
raise Exception("Element is not iterable")
return "\n".join([str(OutputTemplate(inner_template, item))
for item in items])
class CmdOutputTemplate(OutputTemplate):
""" This class provides templated output for CLI commands.
Extends OutputTemplate loading a different template for each command.
"""
_templates_v10 = dict(
list_nets="""
Virtual Networks for Tenant %(tenant_id)s
%(networks|\tNetwork ID: %(id)s)s
""".strip(),
list_nets_detail="""
Virtual Networks for Tenant %(tenant_id)s
%(networks|\tNetwork %(name)s with ID: %(id)s)s
""".strip(),
show_net="""
Network ID: %(network.id)s
Network Name: %(network.name)s
""".strip(),
show_net_detail="""
Network ID: %(network.id)s
Network Name: %(network.name)s
Ports: %(network.ports|\tID: %(id)s
\t\tadministrative state: %(state)s
\t\tinterface: %(attachment.id)s)s
""".strip(),
create_net="""
Created a new Virtual Network with ID: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
update_net="""
Updated Virtual Network with ID: %(network.id)s
for Tenant: %(tenant_id)s
""".strip(),
delete_net="""
Deleted Virtual Network with ID: %(network_id)s
for Tenant %(tenant_id)s
""".strip(),
list_ports="""
Ports on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
%(ports|\tLogical Port: %(id)s)s
""".strip(),
list_ports_detail="""
Ports on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
%(ports|\tLogical Port: %(id)s
\t\tadministrative State: %(state)s)s
""".strip(),
create_port="""
Created new Logical Port with ID: %(port_id)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
show_port="""
Logical Port ID: %(port.id)s
administrative State: %(port.state)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
show_port_detail="""
Logical Port ID: %(port.id)s
administrative State: %(port.state)s
interface: %(port.attachment.id)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
update_port="""
Updated Logical Port with ID: %(port.id)s
on Virtual Network: %(network_id)s
for tenant: %(tenant_id)s
""".strip(),
delete_port="""
Deleted Logical Port with ID: %(port_id)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
plug_iface="""
Plugged interface %(attachment)s
into Logical Port: %(port_id)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
unplug_iface="""
Unplugged interface from Logical Port: %(port_id)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
show_iface="""
interface: %(iface.id)s
plugged in Logical Port ID: %(port_id)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(), )
_templates_v11 = _templates_v10.copy()
_templates_v11.update(dict(
show_net="""
Network ID: %(network.id)s
network Name: %(network.name)s
operational Status: %(network.op-status)s
""".strip(),
show_net_detail="""
Network ID: %(network.id)s
Network Name: %(network.name)s
operational Status: %(network.op-status)s
Ports: %(network.ports|\tID: %(id)s
\t\tadministrative state: %(state)s
\t\tinterface: %(attachment.id)s)s
""".strip(),
show_port="""
Logical Port ID: %(port.id)s
administrative state: %(port.state)s
operational status: %(port.op-status)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(),
show_port_detail="""
Logical Port ID: %(port.id)s
administrative State: %(port.state)s
operational status: %(port.op-status)s
interface: %(port.attachment.id)s
on Virtual Network: %(network_id)s
for Tenant: %(tenant_id)s
""".strip(), ))
_templates = {
'1.0': _templates_v10,
'1.1': _templates_v11, }
def __init__(self, cmd, data, version):
super(CmdOutputTemplate, self).__init__(
self._templates[version][cmd], data)
def _handle_exception(ex):
status_code = None
message = None
# Retrieve dict at 1st element of tuple at last argument
if ex.args and isinstance(ex.args[-1][0], dict):
status_code = ex.args[-1][0].get('status_code', None)
message = ex.args[-1][0].get('message', None)
msg_1 = ("Command failed with error code: %s" %
(status_code or '<missing>'))
msg_2 = "Error message:%s" % (message or '<missing>')
print msg_1
print msg_2
else:
traceback.print_exc()
def prepare_output(cmd, tenant_id, response, version):
LOG.debug("Preparing output for response:%s, version:%s" %
(response, version))
response['tenant_id'] = tenant_id
output = str(CmdOutputTemplate(cmd, response, version))
LOG.debug("Finished preparing output for command:%s", cmd)
return output
def list_nets(client, *args):
tenant_id, version = args
try:
res = client.list_networks()
LOG.debug("Operation 'list_networks' executed.")
output = prepare_output("list_nets", tenant_id, res, version)
print output
except Exception as ex:
_handle_exception(ex)
def list_nets_v11(client, *args):
filters = {}
tenant_id, version = args[:2]
if len(args) > 2:
filters = args[2]
try:
res = client.list_networks(**filters)
LOG.debug("Operation 'list_networks' executed.")
output = prepare_output("list_nets", tenant_id, res, version)
print output
except Exception as ex:
_handle_exception(ex)
def list_nets_detail(client, *args):
tenant_id, version = args
try:
res = client.list_networks_details()
LOG.debug("Operation 'list_networks_details' executed.")
output = prepare_output("list_nets_detail", tenant_id, res, version)
print output
except Exception as ex:
_handle_exception(ex)
def list_nets_detail_v11(client, *args):
filters = {}
tenant_id, version = args[:2]
if len(args) > 2:
filters = args[2]
try:
res = client.list_networks_details(**filters)
LOG.debug("Operation 'list_networks_details' executed.")
output = prepare_output("list_nets_detail", tenant_id, res, version)
print output
except Exception as ex:
_handle_exception(ex)
def create_net(client, *args):
tenant_id, name, version = args
data = {'network': {'name': name}}
new_net_id = None
try:
res = client.create_network(data)
new_net_id = res["network"]["id"]
LOG.debug("Operation 'create_network' executed.")
output = prepare_output("create_net",
tenant_id,
dict(network_id=new_net_id),
version)
print output
except Exception as ex:
_handle_exception(ex)
def delete_net(client, *args):
tenant_id, network_id, version = args
try:
client.delete_network(network_id)
LOG.debug("Operation 'delete_network' executed.")
output = prepare_output("delete_net",
tenant_id,
dict(network_id=network_id),
version)
print output
except Exception as ex:
_handle_exception(ex)
def show_net(client, *args):
tenant_id, network_id, version = args
try:
res = client.show_network(network_id)["network"]
LOG.debug("Operation 'show_network' executed.")
output = prepare_output("show_net", tenant_id,
dict(network=res),
version)
print output
except Exception as ex:
_handle_exception(ex)
def show_net_detail(client, *args):
tenant_id, network_id, version = args
try:
res = client.show_network_details(network_id)["network"]
LOG.debug("Operation 'show_network_details' executed.")
if not len(res["ports"]):
res["ports"] = [{"id": "<none>",
"state": "<none>",
"attachment": {"id": "<none>"}}]
else:
for port in res["ports"]:
if "attachment" not in port:
port["attachment"] = {"id": "<none>"}
output = prepare_output("show_net_detail",
tenant_id,
dict(network=res),
version)
print output
except Exception as ex:
_handle_exception(ex)
def update_net(client, *args):
tenant_id, network_id, param_data, version = args
data = {'network': {}}
for kv in param_data.split(","):
k, v = kv.split("=")
data['network'][k] = v
data['network']['id'] = network_id
try:
client.update_network(network_id, data)
LOG.debug("Operation 'update_network' executed.")
# Response has no body. Use data for populating output
output = prepare_output("update_net", tenant_id, data, version)
print output
except Exception as ex:
_handle_exception(ex)
def list_ports(client, *args):
tenant_id, network_id, version = args
try:
ports = client.list_ports(network_id)
LOG.debug("Operation 'list_ports' executed.")
data = ports
data['network_id'] = network_id
output = prepare_output("list_ports", tenant_id, data, version)
print output
except Exception as ex:
_handle_exception(ex)
def list_ports_v11(client, *args):
filters = {}
tenant_id, network_id, version = args[:3]
if len(args) > 3:
filters = args[3]
try:
ports = client.list_ports(network_id, **filters)
LOG.debug("Operation 'list_ports' executed.")
data = ports
data['network_id'] = network_id
output = prepare_output("list_ports", tenant_id, data, version)
print output
except Exception as ex:
_handle_exception(ex)
def list_ports_detail(client, *args):
tenant_id, network_id, version = args
try:
ports = client.list_ports_details(network_id)
LOG.debug("Operation 'list_ports_details' executed.")
data = ports
data['network_id'] = network_id
output = prepare_output("list_ports_detail", tenant_id, data, version)
print output
except Exception as ex:
_handle_exception(ex)
def list_ports_detail_v11(client, *args):
filters = {}
tenant_id, network_id, version = args[:3]
if len(args) > 3:
filters = args[3]
try:
ports = client.list_ports_details(network_id, **filters)
LOG.debug("Operation 'list_ports' executed.")
data = ports
data['network_id'] = network_id
output = prepare_output("list_ports_detail", tenant_id, data, version)
print output
except Exception as ex:
_handle_exception(ex)
def create_port(client, *args):
tenant_id, network_id, version = args
try:
res = client.create_port(network_id)
LOG.debug("Operation 'create_port' executed.")
new_port_id = res["port"]["id"]
output = prepare_output("create_port",
tenant_id,
dict(network_id=network_id,
port_id=new_port_id),
version)
print output
except Exception as ex:
_handle_exception(ex)
def delete_port(client, *args):
tenant_id, network_id, port_id, version = args
try:
client.delete_port(network_id, port_id)
LOG.debug("Operation 'delete_port' executed.")
output = prepare_output("delete_port",
tenant_id,
dict(network_id=network_id,
port_id=port_id),
version)
print output
except Exception as ex:
_handle_exception(ex)
return
def show_port(client, *args):
tenant_id, network_id, port_id, version = args
try:
port = client.show_port(network_id, port_id)["port"]
LOG.debug("Operation 'show_port' executed.")
output = prepare_output("show_port", tenant_id,
dict(network_id=network_id,
port=port),
version)
print output
except Exception as ex:
_handle_exception(ex)
def show_port_detail(client, *args):
tenant_id, network_id, port_id, version = args
try:
port = client.show_port_details(network_id, port_id)["port"]
LOG.debug("Operation 'show_port_details' executed.")
if 'attachment' not in port:
port['attachment'] = {'id': '<none>'}
output = prepare_output("show_port_detail", tenant_id,
dict(network_id=network_id,
port=port),
version)
print output
except Exception as ex:
_handle_exception(ex)
def update_port(client, *args):
tenant_id, network_id, port_id, param_data, version = args
data = {'port': {}}
for kv in param_data.split(","):
k, v = kv.split("=")
data['port'][k] = v
data['network_id'] = network_id
data['port']['id'] = port_id
try:
client.update_port(network_id, port_id, data)
LOG.debug("Operation 'udpate_port' executed.")
# Response has no body. Use data for populating output
output = prepare_output("update_port", tenant_id, data, version)
print output
except Exception as ex:
_handle_exception(ex)
def plug_iface(client, *args):
tenant_id, network_id, port_id, attachment, version = args
try:
data = {'attachment': {'id': '%s' % attachment}}
client.attach_resource(network_id, port_id, data)
LOG.debug("Operation 'attach_resource' executed.")
output = prepare_output("plug_iface", tenant_id,
dict(network_id=network_id,
port_id=port_id,
attachment=attachment),
version)
print output
except Exception as ex:
_handle_exception(ex)
def unplug_iface(client, *args):
tenant_id, network_id, port_id, version = args
try:
client.detach_resource(network_id, port_id)
LOG.debug("Operation 'detach_resource' executed.")
output = prepare_output("unplug_iface",
tenant_id,
dict(network_id=network_id,
port_id=port_id),
version)
print output
except Exception as ex:
_handle_exception(ex)
def show_iface(client, *args):
tenant_id, network_id, port_id, version = args
try:
iface = client.show_port_attachment(network_id, port_id)['attachment']
if 'id' not in iface:
iface['id'] = '<none>'
LOG.debug("Operation 'show_port_attachment' executed.")
output = prepare_output("show_iface", tenant_id,
dict(network_id=network_id,
port_id=port_id,
iface=iface),
version)
print output
except Exception as ex:
_handle_exception(ex)
|