/
inventory.py
318 lines (253 loc) · 10.3 KB
/
inventory.py
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
# 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.
from collections import defaultdict
from osc_lib.command import command
from osc_lib import utils
from osc_placement import version
BASE_URL = '/resource_providers/{uuid}/inventories'
PER_CLASS_URL = BASE_URL + '/{resource_class}'
RP_BASE_URL = '/resource_providers'
INVENTORY_FIELDS = {
'allocation_ratio': {
'type': float,
'required': False,
'help': ('It is used in determining whether consumption '
'of the resource of the provider can exceed '
'physical constraints. For example, for a vCPU resource '
'with: allocation_ratio = 16.0, total = 8. '
'Overall capacity is equal to 128 vCPUs.')
},
'min_unit': {
'type': int,
'required': False,
'help': ('A minimum amount any single allocation against '
'an inventory can have.')
},
'max_unit': {
'type': int,
'required': False,
'help': ('A maximum amount any single allocation against '
'an inventory can have.')
},
'reserved': {
'type': int,
'required': False,
'help': ('The amount of the resource a provider has reserved '
'for its own use.')
},
'step_size': {
'type': int,
'required': False,
'help': ('A representation of the divisible amount of the resource '
'that may be requested. For example, step_size = 5 means '
'that only values divisible by 5 (5, 10, 15, etc.) '
'can be requested.')
},
'total': {
'type': int,
'required': True,
'help': ('The actual amount of the resource that the provider '
'can accommodate.')
}
}
FIELDS = tuple(INVENTORY_FIELDS.keys())
RC_HELP = ('<resource_class> is an entity that indicates standard or '
'deployer-specific resources that can be provided by a resource '
'provider. For example, VCPU, MEMORY_MB, DISK_GB.')
def parse_resource_argument(resource):
parts = resource.split('=')
if len(parts) != 2:
raise ValueError(
'Resource argument must have "name=value" format')
name, value = parts
parts = name.split(':')
if len(parts) == 2:
name, field = parts
elif len(parts) == 1:
name = parts[0]
field = 'total'
else:
raise ValueError('Resource argument can contain only one colon')
if not all([name, field, value]):
raise ValueError('Name, field and value must be not empty')
if field not in INVENTORY_FIELDS:
raise ValueError('Unknown inventory field %s' % field)
value = INVENTORY_FIELDS[field]['type'](value)
return name, field, value
class SetInventory(command.Lister):
"""Replaces the set of inventory records for the resource provider.
Note that this is a full replacement of the existing inventory. If you
want to retain the existing inventory and add a new resource class
inventory, you must specify all resource class inventory, old and new.
If a specific inventory field is not specified for a given resource class,
it is assumed to be the total, i.e. --resource VCPU=16 is equivalent to
--resource VCPU:total=16.
Example: openstack resource provider inventory set <uuid> \
--resource VCPU=16 \
--resource MEMORY_MB=2048 \
--resource MEMORY_MB:step_size=128
"""
def get_parser(self, prog_name):
parser = super(SetInventory, self).get_parser(prog_name)
parser.add_argument(
'uuid',
metavar='<uuid>',
help='UUID of the resource provider'
)
fields_help = '\n'.join(
'{} - {}'.format(f, INVENTORY_FIELDS[f]['help'].lower())
for f in INVENTORY_FIELDS)
parser.add_argument(
'--resource',
metavar='<resource_class>:<inventory_field>=<value>',
help='String describing resource.\n' + RC_HELP + '\n'
'<inventory_field> (optional) can be:\n' + fields_help,
default=[],
action='append'
)
return parser
def take_action(self, parsed_args):
inventories = defaultdict(dict)
for r in parsed_args.resource:
name, field, value = parse_resource_argument(r)
inventories[name][field] = value
http = self.app.client_manager.placement
url = RP_BASE_URL + '/' + parsed_args.uuid
rp = http.request('GET', url).json()
payload = {'inventories': inventories,
'resource_provider_generation': rp['generation']}
url = BASE_URL.format(uuid=parsed_args.uuid)
resources = http.request('PUT', url, json=payload).json()
inventories = [
dict(resource_class=k, **v)
for k, v in resources['inventories'].items()
]
fields = ('resource_class', ) + FIELDS
rows = (utils.get_dict_properties(i, fields) for i in inventories)
return fields, rows
class SetClassInventory(command.ShowOne):
"""Replace the inventory record of the class for the resource provider.
Example: openstack resource provider inventory class set <uuid> VCPU \
--total 16 \
--max_unit 4 \
--reserved 1
"""
def get_parser(self, prog_name):
parser = super(SetClassInventory, self).get_parser(prog_name)
parser.add_argument(
'uuid',
metavar='<uuid>',
help='UUID of the resource provider'
)
parser.add_argument(
'resource_class',
metavar='<class>',
help=RC_HELP
)
for name, props in INVENTORY_FIELDS.items():
parser.add_argument(
'--' + name,
metavar='<{}>'.format(name),
required=props['required'],
type=props['type'],
help=props['help'])
return parser
def take_action(self, parsed_args):
http = self.app.client_manager.placement
url = RP_BASE_URL + '/' + parsed_args.uuid
rp = http.request('GET', url).json()
payload = {'resource_provider_generation': rp['generation']}
for field in FIELDS:
value = getattr(parsed_args, field, None)
if value is not None:
payload[field] = value
url = PER_CLASS_URL.format(uuid=parsed_args.uuid,
resource_class=parsed_args.resource_class)
resource = http.request('PUT', url, json=payload).json()
return FIELDS, utils.get_dict_properties(resource, FIELDS)
class DeleteInventory(command.Command, version.CheckerMixin):
"""Delete the inventory.
Depending on the resource class argument presence, it can
delete all inventory for a given resource provider or for a resource
provider/class pair.
Delete all inventories for given resource provider
requires at least ``--os-placement-api-version 1.5``.
"""
def get_parser(self, prog_name):
parser = super(DeleteInventory, self).get_parser(prog_name)
parser.add_argument(
'uuid',
metavar='<uuid>',
help='UUID of the resource provider'
)
parser.add_argument(
'--resource-class',
metavar='<resource_class>',
required=self.compare_version(version.lt('1.5')),
help=(RC_HELP +
'\nThis argument can be omitted starting with '
'``--os-placement-api-version 1.5``. If it is omitted all '
'inventories of the specified resource provider '
'will be deleted.')
)
return parser
def take_action(self, parsed_args):
http = self.app.client_manager.placement
url = BASE_URL
params = {'uuid': parsed_args.uuid}
if parsed_args.resource_class is not None:
url = PER_CLASS_URL
params = {'uuid': parsed_args.uuid,
'resource_class': parsed_args.resource_class}
http.request('DELETE', url.format(**params))
class ShowInventory(command.ShowOne):
"""Show the inventory for a given resource provider/class pair."""
def get_parser(self, prog_name):
parser = super(ShowInventory, self).get_parser(prog_name)
parser.add_argument(
'uuid',
metavar='<uuid>',
help='UUID of the resource provider'
)
parser.add_argument(
'resource_class',
metavar='<resource_class>',
help=RC_HELP
)
return parser
def take_action(self, parsed_args):
http = self.app.client_manager.placement
url = PER_CLASS_URL.format(uuid=parsed_args.uuid,
resource_class=parsed_args.resource_class)
resource = http.request('GET', url).json()
return FIELDS, utils.get_dict_properties(resource, FIELDS)
class ListInventory(command.Lister):
"""List inventories for a given resource provider."""
def get_parser(self, prog_name):
parser = super(ListInventory, self).get_parser(prog_name)
parser.add_argument(
'uuid',
metavar='<uuid>',
help='UUID of the resource provider'
)
return parser
def take_action(self, parsed_args):
http = self.app.client_manager.placement
url = BASE_URL.format(uuid=parsed_args.uuid)
resources = http.request('GET', url).json()
inventories = [
dict(resource_class=k, **v)
for k, v in resources['inventories'].items()
]
fields = ('resource_class', ) + FIELDS
rows = (utils.get_dict_properties(i, fields) for i in inventories)
return fields, rows