Skip to content
This repository was archived by the owner on Nov 29, 2023. It is now read-only.

Commit defb548

Browse files
author
Yong Sheng Gong
committed
Add name or id to quantum cli commands.
Bug #1030180 We first lookup the resource id via id if it looks like an id. If we cannot find it via id, we will look it up via name. All of the update/show/delete support reference resource via name or id. To create port/subnet, we can refercen network via network's name. Also in port creation, we support reference subnet in fixed_ip via its name. quantum_test.sh is added to test the command lines after running 'python setup.py install' Change-Id: I54b6912e2c4044ba70aaf604cd79520022de262f
1 parent d16e00a commit defb548

9 files changed

Lines changed: 303 additions & 134 deletions

File tree

‎quantum_test.sh‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/bin/bash
2+
set -x
3+
function die() {
4+
local exitcode=$?
5+
set +o xtrace
6+
echo $@
7+
exit $exitcode
8+
}
9+
10+
11+
# test the CRUD of network
12+
network=mynet1
13+
quantum net-create $network || die "fail to create network $network"
14+
temp=`quantum net-list -- --name $network --fields id | wc -l`
15+
echo $temp
16+
if [ $temp -ne 5 ]; then
17+
die "networks with name $network is not unique or found"
18+
fi
19+
network_id=`quantum net-list -- --name $network --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
20+
echo "ID of network with name $network is $network_id"
21+
22+
quantum net-show $network || die "fail to show network $network"
23+
quantum net-show $network_id || die "fail to show network $network_id"
24+
25+
quantum net-update $network --admin_state_up False || die "fail to update network $network"
26+
quantum net-update $network_id --admin_state_up True || die "fail to update network $network_id"
27+
28+
# test the CRUD of subnet
29+
subnet=mysubnet1
30+
cidr=10.0.1.3/24
31+
quantum subnet-create $network $cidr --name $subnet || die "fail to create subnet $subnet"
32+
tempsubnet=`quantum subnet-list -- --name $subnet --fields id | wc -l`
33+
echo $tempsubnet
34+
if [ $tempsubnet -ne 5 ]; then
35+
die "subnets with name $subnet is not unique or found"
36+
fi
37+
subnet_id=`quantum subnet-list -- --name $subnet --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
38+
echo "ID of subnet with name $subnet is $subnet_id"
39+
quantum subnet-show $subnet || die "fail to show subnet $subnet"
40+
quantum subnet-show $subnet_id || die "fail to show subnet $subnet_id"
41+
42+
quantum subnet-update $subnet --dns_namesevers host1 || die "fail to update subnet $subnet"
43+
quantum subnet-update $subnet_id --dns_namesevers host2 || die "fail to update subnet $subnet_id"
44+
45+
# test the crud of ports
46+
port=myport1
47+
quantum port-create $network --name $port || die "fail to create port $port"
48+
tempport=`quantum port-list -- --name $port --fields id | wc -l`
49+
echo $tempport
50+
if [ $tempport -ne 5 ]; then
51+
die "ports with name $port is not unique or found"
52+
fi
53+
port_id=`quantum port-list -- --name $port --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
54+
echo "ID of port with name $port is $port_id"
55+
quantum port-show $port || die "fail to show port $port"
56+
quantum port-show $port_id || die "fail to show port $port_id"
57+
58+
quantum port-update $port --device_id deviceid1 || die "fail to update port $port"
59+
quantum port-update $port_id --device_id deviceid2 || die "fail to update port $port_id"

‎quantumclient/quantum/v2_0/__init__.py‎

Lines changed: 56 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,44 @@
2626
from quantumclient.common import exceptions
2727
from quantumclient.common import utils
2828

29+
HEX_ELEM = '[0-9A-Fa-f]'
30+
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
31+
HEX_ELEM + '{4}', HEX_ELEM + '{4}',
32+
HEX_ELEM + '{12}'])
33+
34+
35+
def find_resourceid_by_name_or_id(client, resource, name_or_id):
36+
obj_lister = getattr(client, "list_%ss" % resource)
37+
# perform search by id only if we are passing a valid UUID
38+
match = re.match(UUID_PATTERN, name_or_id)
39+
collection = resource + "s"
40+
if match:
41+
data = obj_lister(id=name_or_id, fields='id')
42+
if data and data[collection]:
43+
return data[collection][0]['id']
44+
return _find_resourceid_by_name(client, resource, name_or_id)
45+
46+
47+
def _find_resourceid_by_name(client, resource, name):
48+
obj_lister = getattr(client, "list_%ss" % resource)
49+
data = obj_lister(name=name, fields='id')
50+
collection = resource + "s"
51+
info = data[collection]
52+
if len(info) > 1:
53+
msg = (_("Multiple %(resource)s matches found for '%(name)s',"
54+
" use an ID to be more specific.") %
55+
{'resource': resource, 'name': name})
56+
raise exceptions.QuantumClientException(
57+
message=msg)
58+
elif len(info) == 0:
59+
not_found_message = (_("Unable to find %(resource)s with '%(name)s'") %
60+
{'resource': resource, 'name': name})
61+
# 404 is used to simulate server side behavior
62+
raise exceptions.QuantumClientException(
63+
message=not_found_message, status_code=404)
64+
else:
65+
return info[0]['id']
66+
2967

3068
def add_show_list_common_argument(parser):
3169
parser.add_argument(
@@ -222,8 +260,8 @@ class UpdateCommand(QuantumCommand):
222260
def get_parser(self, prog_name):
223261
parser = super(UpdateCommand, self).get_parser(prog_name)
224262
parser.add_argument(
225-
'id', metavar='%s_id' % self.resource,
226-
help='ID of %s to update' % self.resource)
263+
'id', metavar=self.resource,
264+
help='ID or name of %s to update' % self.resource)
227265
add_extra_argument(parser, 'value_specs',
228266
'new values for the %s' % self.resource)
229267
return parser
@@ -237,9 +275,12 @@ def run(self, parsed_args):
237275
raise exceptions.CommandError(
238276
"Must specify new values to update %s" % self.resource)
239277
data = {self.resource: parse_args_to_dict(value_specs)}
278+
_id = find_resourceid_by_name_or_id(quantum_client,
279+
self.resource,
280+
parsed_args.id)
240281
obj_updator = getattr(quantum_client,
241282
"update_%s" % self.resource)
242-
obj_updator(parsed_args.id, data)
283+
obj_updator(_id, data)
243284
print >>self.app.stdout, (
244285
_('Updated %(resource)s: %(id)s') %
245286
{'id': parsed_args.id, 'resource': self.resource})
@@ -258,8 +299,8 @@ class DeleteCommand(QuantumCommand):
258299
def get_parser(self, prog_name):
259300
parser = super(DeleteCommand, self).get_parser(prog_name)
260301
parser.add_argument(
261-
'id', metavar='%s_id' % self.resource,
262-
help='ID of %s to delete' % self.resource)
302+
'id', metavar=self.resource,
303+
help='ID or name of %s to delete' % self.resource)
263304
return parser
264305

265306
def run(self, parsed_args):
@@ -268,7 +309,10 @@ def run(self, parsed_args):
268309
quantum_client.format = parsed_args.request_format
269310
obj_deleter = getattr(quantum_client,
270311
"delete_%s" % self.resource)
271-
obj_deleter(parsed_args.id)
312+
_id = find_resourceid_by_name_or_id(quantum_client,
313+
self.resource,
314+
parsed_args.id)
315+
obj_deleter(_id)
272316
print >>self.app.stdout, (_('Deleted %(resource)s: %(id)s')
273317
% {'id': parsed_args.id,
274318
'resource': self.resource})
@@ -327,10 +371,7 @@ class ShowCommand(QuantumCommand, show.ShowOne):
327371
"""Show information of a given resource
328372
329373
"""
330-
HEX_ELEM = '[0-9A-Fa-f]'
331-
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
332-
HEX_ELEM + '{4}', HEX_ELEM + '{4}',
333-
HEX_ELEM + '{12}'])
374+
334375
api = 'network'
335376
resource = None
336377
log = None
@@ -339,7 +380,7 @@ def get_parser(self, prog_name):
339380
parser = super(ShowCommand, self).get_parser(prog_name)
340381
add_show_list_common_argument(parser)
341382
parser.add_argument(
342-
'id', metavar='%s_id' % self.resource,
383+
'id', metavar=self.resource,
343384
help='ID or name of %s to look up' % self.resource)
344385
return parser
345386

@@ -353,57 +394,10 @@ def get_data(self, parsed_args):
353394
params = {'verbose': 'True'}
354395
if parsed_args.fields:
355396
params = {'fields': parsed_args.fields}
356-
357-
data = None
358-
# Error message to be used in case both search by id and name are
359-
# unsuccessful (if list by name fails it does not return an error)
360-
not_found_message = "Unable to find resource:%s" % parsed_args.id
361-
362-
# perform search by id only if we are passing a valid UUID
363-
match = re.match(self.UUID_PATTERN, parsed_args.id)
364-
if match:
365-
try:
366-
obj_shower = getattr(quantum_client,
367-
"show_%s" % self.resource)
368-
data = obj_shower(parsed_args.id, **params)
369-
except exceptions.QuantumClientException as ex:
370-
logging.debug("Show operation failed with code:%s",
371-
ex.status_code)
372-
not_found_message = ex.message
373-
if ex.status_code != 404:
374-
logging.exception("Unable to perform show operation")
375-
raise
376-
377-
# If data is empty, then we got a 404. Try to interpret Id as a name
378-
if not data:
379-
logging.debug("Trying to interpret %s as a %s name",
380-
parsed_args.id,
381-
self.resource)
382-
# build search_opts for the name
383-
search_opts = parse_args_to_dict(["--name=%s" % parsed_args.id])
384-
search_opts.update(params)
385-
obj_lister = getattr(quantum_client,
386-
"list_%ss" % self.resource)
387-
data = obj_lister(**search_opts)
388-
info = []
389-
collection = self.resource + "s"
390-
if collection in data:
391-
info = data[collection]
392-
if len(info) > 1:
393-
logging.info("Multiple occurrences found for: %s",
394-
parsed_args.id)
395-
_columns = ['id']
396-
# put all ids in a single string as formatter for show
397-
# command will print on record only
398-
id_string = "\n".join(utils.get_item_properties(
399-
s, _columns)[0] for s in info)
400-
return (_columns, (id_string, ), )
401-
elif len(info) == 0:
402-
#Nothing was found
403-
raise exceptions.QuantumClientException(
404-
message=not_found_message)
405-
else:
406-
data = {self.resource: info[0]}
397+
_id = find_resourceid_by_name_or_id(quantum_client, self.resource,
398+
parsed_args.id)
399+
obj_shower = getattr(quantum_client, "show_%s" % self.resource)
400+
data = obj_shower(_id, **params)
407401
if self.resource in data:
408402
for k, v in data[self.resource].iteritems():
409403
if isinstance(v, list):

‎quantumclient/quantum/v2_0/port.py‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import logging
1919

2020
from quantumclient.common import utils
21+
from quantumclient.quantum import v2_0 as quantumv20
2122
from quantumclient.quantum.v2_0 import CreateCommand
2223
from quantumclient.quantum.v2_0 import DeleteCommand
2324
from quantumclient.quantum.v2_0 import ListCommand
@@ -54,39 +55,52 @@ class CreatePort(CreateCommand):
5455
log = logging.getLogger(__name__ + '.CreatePort')
5556

5657
def add_known_arguments(self, parser):
58+
parser.add_argument(
59+
'--name',
60+
help='name of this port')
5761
parser.add_argument(
5862
'--admin_state_down',
5963
default=True, action='store_false',
6064
help='set admin state up to false')
6165
parser.add_argument(
6266
'--mac_address',
63-
help='mac address of port')
67+
help='mac address of this port')
6468
parser.add_argument(
6569
'--device_id',
6670
help='device id of this port')
6771
parser.add_argument(
6872
'--fixed_ip',
6973
action='append',
70-
help='desired Ip for this port: '
71-
'subnet_id=<id>,ip_address=<ip>, '
74+
help='desired IP for this port: '
75+
'subnet_id=<name_or_id>,ip_address=<ip>, '
7276
'can be repeated')
7377
parser.add_argument(
74-
'network_id',
75-
help='Network id this port belongs to')
78+
'network_id', metavar='network',
79+
help='Network id or name this port belongs to')
7680

7781
def args2body(self, parsed_args):
82+
_network_id = quantumv20.find_resourceid_by_name_or_id(
83+
self.get_client(), 'network', parsed_args.network_id)
7884
body = {'port': {'admin_state_up': parsed_args.admin_state_down,
79-
'network_id': parsed_args.network_id, }, }
85+
'network_id': _network_id, }, }
8086
if parsed_args.mac_address:
8187
body['port'].update({'mac_address': parsed_args.mac_address})
8288
if parsed_args.device_id:
8389
body['port'].update({'device_id': parsed_args.device_id})
8490
if parsed_args.tenant_id:
8591
body['port'].update({'tenant_id': parsed_args.tenant_id})
92+
if parsed_args.name:
93+
body['port'].update({'name': parsed_args.name})
8694
ips = []
8795
if parsed_args.fixed_ip:
8896
for ip_spec in parsed_args.fixed_ip:
89-
ips.append(utils.str2dict(ip_spec))
97+
ip_dict = utils.str2dict(ip_spec)
98+
if 'subnet_id' in ip_dict:
99+
subnet_name_id = ip_dict['subnet_id']
100+
_subnet_id = quantumv20.find_resourceid_by_name_or_id(
101+
self.get_client(), 'subnet', subnet_name_id)
102+
ip_dict['subnet_id'] = _subnet_id
103+
ips.append(ip_dict)
90104
if ips:
91105
body['port'].update({'fixed_ips': ips})
92106
return body

‎quantumclient/quantum/v2_0/subnet.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import logging
1919

2020
from quantumclient.common import utils
21+
from quantumclient.quantum import v2_0 as quantumv20
2122
from quantumclient.quantum.v2_0 import CreateCommand
2223
from quantumclient.quantum.v2_0 import DeleteCommand
2324
from quantumclient.quantum.v2_0 import ListCommand
@@ -55,6 +56,9 @@ class CreateSubnet(CreateCommand):
5556
log = logging.getLogger(__name__ + '.CreateSubnet')
5657

5758
def add_known_arguments(self, parser):
59+
parser.add_argument(
60+
'--name',
61+
help='name of this subnet')
5862
parser.add_argument('--ip_version', type=int,
5963
default=4, choices=[4, 6],
6064
help='IP version with default 4')
@@ -68,20 +72,24 @@ def add_known_arguments(self, parser):
6872
'start=<ip_address>,end=<ip_address> '
6973
'can be repeated')
7074
parser.add_argument(
71-
'network_id',
72-
help='Network id this subnet belongs to')
75+
'network_id', metavar='network',
76+
help='Network id or name this subnet belongs to')
7377
parser.add_argument(
7478
'cidr', metavar='cidr',
7579
help='cidr of subnet to create')
7680

7781
def args2body(self, parsed_args):
82+
_network_id = quantumv20.find_resourceid_by_name_or_id(
83+
self.get_client(), 'network', parsed_args.network_id)
7884
body = {'subnet': {'cidr': parsed_args.cidr,
79-
'network_id': parsed_args.network_id,
85+
'network_id': _network_id,
8086
'ip_version': parsed_args.ip_version, }, }
8187
if parsed_args.gateway:
8288
body['subnet'].update({'gateway_ip': parsed_args.gateway})
8389
if parsed_args.tenant_id:
8490
body['subnet'].update({'tenant_id': parsed_args.tenant_id})
91+
if parsed_args.name:
92+
body['subnet'].update({'name': parsed_args.name})
8593
ips = []
8694
if parsed_args.allocation_pool:
8795
for ip_spec in parsed_args.allocation_pool:

0 commit comments

Comments
 (0)