forked from softlayer/softlayer-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathordering.py
More file actions
478 lines (369 loc) · 19.6 KB
/
ordering.py
File metadata and controls
478 lines (369 loc) · 19.6 KB
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
"""
SoftLayer.ordering
~~~~~~~~~~~~~~~~~~
Ordering Manager
:license: MIT, see LICENSE for more details.
"""
# pylint: disable=no-self-use
from SoftLayer import exceptions
CATEGORY_MASK = '''id,
isRequired,
itemCategory[id, name, categoryCode]
'''
ITEM_MASK = '''id, keyName, description'''
PACKAGE_MASK = '''id, name, keyName, isActive'''
PRESET_MASK = '''id, name, keyName, description'''
class OrderingManager(object):
"""Manager to help ordering via the SoftLayer API.
:param SoftLayer.API.BaseClient client: the client instance
"""
def __init__(self, client):
self.client = client
self.package_svc = client['Product_Package']
self.order_svc = client['Product_Order']
self.billing_svc = client['Billing_Order']
def get_packages_of_type(self, package_types, mask=None):
"""Get packages that match a certain type.
Each ordering package has a type, so return all packages that match
the types we are looking for
:param list package_types: List of strings representing the package
type keynames we are interested in.
:param string mask: Mask to specify the properties we want to retrieve
"""
_filter = {
'type': {
'keyName': {
'operation': 'in',
'options': [
{'name': 'data',
'value': package_types}
],
},
},
}
packages = self.package_svc.getAllObjects(mask=mask, filter=_filter)
packages = self.filter_outlet_packages(packages)
return packages
@staticmethod
def filter_outlet_packages(packages):
"""Remove packages designated as OUTLET.
Those type of packages must be handled in a different way,
and they are not supported at the moment.
:param packages: Dictionary of packages. Name and description keys
must be present in each of them.
"""
non_outlet_packages = []
for package in packages:
if all(['OUTLET' not in package.get('description', '').upper(),
'OUTLET' not in package.get('name', '').upper()]):
non_outlet_packages.append(package)
return non_outlet_packages
@staticmethod
def get_only_active_packages(packages):
"""Return only active packages.
If a package is active, it is eligible for ordering
This will inspect the 'isActive' property on the provided packages
:param packages: Dictionary of packages, isActive key must be present
"""
active_packages = []
for package in packages:
if package['isActive']:
active_packages.append(package)
return active_packages
def get_package_by_type(self, package_type, mask=None):
"""Get a single package of a given type.
Syntactic sugar to retrieve a single package of a given type.
If multiple packages share the given type, this will return the first
one returned by the API.
If no packages are found, returns None
:param string package_type: representing the package type key name we are interested in
"""
packages = self.get_packages_of_type([package_type], mask)
if len(packages) == 0:
return None
else:
return packages.pop()
def get_package_id_by_type(self, package_type):
"""Return the package ID of a Product Package with a given type.
:param string package_type: representing the package type key name we are interested in
:raises ValueError: when no package of the given type is found
"""
mask = "mask[id, name, description, isActive, type[keyName]]"
package = self.get_package_by_type(package_type, mask)
if package:
return package['id']
else:
raise ValueError("No package found for type: " + package_type)
def get_quotes(self):
"""Retrieve a list of quotes.
:returns: a list of SoftLayer_Billing_Order_Quote
"""
quotes = self.client['Account'].getActiveQuotes()
return quotes
def get_quote_details(self, quote_id):
"""Retrieve quote details.
:param quote_id: ID number of target quote
"""
quote = self.client['Billing_Order_Quote'].getObject(id=quote_id)
return quote
def get_order_container(self, quote_id):
"""Generate an order container from a quote object.
:param quote_id: ID number of target quote
"""
quote = self.client['Billing_Order_Quote']
container = quote.getRecalculatedOrderContainer(id=quote_id)
return container['orderContainers'][0]
def generate_order_template(self, quote_id, extra, quantity=1):
"""Generate a complete order template.
:param int quote_id: ID of target quote
:param list extra: List of dictionaries that have extra details about
the order such as hostname or domain names for
virtual servers or hardware nodes
:param int quantity: Number of ~things~ to order
"""
container = self.get_order_container(quote_id)
container['quantity'] = quantity
# NOTE(kmcdonald): This will only work with virtualGuests and hardware.
# There has to be a better way, since this is based on
# an existing quote that supposedly knows about this
# detail
if container['packageId'] == 46:
product_type = 'virtualGuests'
else:
product_type = 'hardware'
if len(extra) != quantity:
raise ValueError("You must specify extra for each server in the quote")
container[product_type] = []
for extra_details in extra:
container[product_type].append(extra_details)
container['presetId'] = None
return container
def verify_quote(self, quote_id, extra, quantity=1):
"""Verifies that a quote order is valid.
:param int quote_id: ID for the target quote
:param list hostnames: hostnames of the servers
:param string domain: domain of the new servers
:param int quantity: Quantity to override default
"""
container = self.generate_order_template(quote_id, extra,
quantity=quantity)
return self.order_svc.verifyOrder(container)
def order_quote(self, quote_id, extra, quantity=1):
"""Places an order using a quote
:param int quote_id: ID for the target quote
:param list hostnames: hostnames of the servers
:param string domain: domain of the new server
:param int quantity: Quantity to override default
"""
container = self.generate_order_template(quote_id, extra,
quantity=quantity)
return self.order_svc.placeOrder(container)
def get_package_by_key(self, package_keyname, mask=None):
"""Get a single package with a given key.
If no packages are found, returns None
:param package_keyname: string representing the package key name we are interested in.
:param string mask: Mask to specify the properties we want to retrieve
"""
_filter = {
'keyName': {
'operation': package_keyname,
},
}
packages = self.package_svc.getAllObjects(mask=mask, filter=_filter)
if len(packages) == 0:
return None
else:
return packages.pop()
def list_categories(self, package_keyname, **kwargs):
"""List the categories for the given package.
:param str package_keyname: The package for which to get the categories.
:returns: List of categories associated with the package
"""
get_kwargs = {}
get_kwargs['mask'] = kwargs.get('mask', CATEGORY_MASK)
if 'filter' in kwargs:
get_kwargs['filter'] = kwargs['filter']
package = self.get_package_by_key(package_keyname, mask='id')
if not package:
raise exceptions.SoftLayerError("Package {} does not exist".format(package_keyname))
categories = self.package_svc.getConfiguration(id=package['id'], **get_kwargs)
return categories
def list_items(self, package_keyname, **kwargs):
"""List the items for the given package.
:param str package_keyname: The package for which to get the items.
:returns: List of items in the package
"""
get_kwargs = {}
get_kwargs['mask'] = kwargs.get('mask', ITEM_MASK)
if 'filter' in kwargs:
get_kwargs['filter'] = kwargs['filter']
package = self.get_package_by_key(package_keyname, mask='id')
if not package:
raise exceptions.SoftLayerError("Package {} does not exist".format(package_keyname))
items = self.package_svc.getItems(id=package['id'], **get_kwargs)
return items
def list_packages(self, **kwargs):
"""List active packages.
:returns: List of active packages.
"""
get_kwargs = {}
get_kwargs['mask'] = kwargs.get('mask', PACKAGE_MASK)
if 'filter' in kwargs:
get_kwargs['filter'] = kwargs['filter']
packages = self.package_svc.getAllObjects(**get_kwargs)
return [package for package in packages if package['isActive']]
def list_presets(self, package_keyname, **kwargs):
"""Gets active presets for the given package.
:param str package_keyname: The package for which to get presets
:returns: A list of package presets that can be used for ordering
"""
get_kwargs = {}
get_kwargs['mask'] = kwargs.get('mask', PRESET_MASK)
if 'filter' in kwargs:
get_kwargs['filter'] = kwargs['filter']
package = self.get_package_by_key(package_keyname, mask='id')
if not package:
raise exceptions.SoftLayerError("Package {} does not exist".format(package_keyname))
acc_presets = self.package_svc.getAccountRestrictedActivePresets(
id=package['id'], **get_kwargs)
active_presets = self.package_svc.getActivePresets(id=package['id'], **get_kwargs)
return active_presets + acc_presets
def get_preset_by_key(self, package_keyname, preset_keyname, mask=None):
"""Gets a single preset with the given key."""
preset_operation = '_= %s' % preset_keyname
_filter = {'activePresets': {'keyName': {'operation': preset_operation}}}
presets = self.list_presets(package_keyname, mask=mask, filter=_filter)
if len(presets) == 0:
raise exceptions.SoftLayerError(
"Preset {} does not exist in package {}".format(preset_keyname,
package_keyname))
return presets[0]
def get_price_id_list(self, package_keyname, item_keynames):
"""Converts a list of item keynames to a list of price IDs.
This function is used to convert a list of item keynames into
a list of price IDs that are used in the Product_Order verifyOrder()
and placeOrder() functions.
:param str package_keyname: The package associated with the prices
:param list item_keynames: A list of item keyname strings
:returns: A list of price IDs associated with the given item
keynames in the given package
"""
mask = 'id, keyName, prices'
items = self.list_items(package_keyname, mask=mask)
prices = []
for item_keyname in item_keynames:
try:
# Need to find the item in the package that has a matching
# keyName with the current item we are searching for
matching_item = [i for i in items
if i['keyName'] == item_keyname][0]
except IndexError:
raise exceptions.SoftLayerError(
"Item {} does not exist for package {}".format(item_keyname,
package_keyname))
# we want to get the price ID that has no location attached to it,
# because that is the most generic price. verifyOrder/placeOrder
# can take that ID and create the proper price for us in the location
# in which the order is made
price_id = [p['id'] for p in matching_item['prices']
if p['locationGroupId'] == ''][0]
prices.append(price_id)
return prices
def verify_order(self, package_keyname, location, item_keynames, complex_type=None,
hourly=True, preset_keyname=None, extras=None, quantity=1):
"""Verifies an order with the given package and prices.
This function takes in parameters needed for an order and verifies the order
to ensure the given items are compatible with the given package.
:param str package_keyname: The keyname for the package being ordered
:param str location: The datacenter location string for ordering (Ex: DALLAS13)
:param list item_keynames: The list of item keyname strings to order. To see list of
possible keynames for a package, use list_items()
(or `slcli order item-list`)
:param str complex_type: The complex type to send with the order. Typically begins
with `SoftLayer_Container_Product_Order_`.
:param bool hourly: If true, uses hourly billing, otherwise uses monthly billing
:param string preset_keyname: If needed, specifies a preset to use for that package.
To see a list of possible keynames for a package, use
list_preset() (or `slcli order preset-list`)
:param dict extras: The extra data for the order in dictionary format.
Example: A VSI order requires hostname and domain to be set, so
extras will look like the following:
'virtualGuests': [{'hostname': 'test', 'domain': 'softlayer.com'}]}
:param int quantity: The number of resources to order
"""
order = self.generate_order(package_keyname, location, item_keynames,
complex_type=complex_type, hourly=hourly,
preset_keyname=preset_keyname,
extras=extras, quantity=quantity)
return self.order_svc.verifyOrder(order)
def place_order(self, package_keyname, location, item_keynames, complex_type=None,
hourly=True, preset_keyname=None, extras=None, quantity=1):
"""Places an order with the given package and prices.
This function takes in parameters needed for an order and places the order.
:param str package_keyname: The keyname for the package being ordered
:param str location: The datacenter location string for ordering (Ex: DALLAS13)
:param list item_keynames: The list of item keyname strings to order. To see list of
possible keynames for a package, use list_items()
(or `slcli order item-list`)
:param str complex_type: The complex type to send with the order. Typically begins
with `SoftLayer_Container_Product_Order_`.
:param bool hourly: If true, uses hourly billing, otherwise uses monthly billing
:param string preset_keyname: If needed, specifies a preset to use for that package.
To see a list of possible keynames for a package, use
list_preset() (or `slcli order preset-list`)
:param dict extras: The extra data for the order in dictionary format.
Example: A VSI order requires hostname and domain to be set, so
extras will look like the following:
{'virtualGuests': [{'hostname': 'test', domain': 'softlayer.com'}]}
:param int quantity: The number of resources to order
"""
order = self.generate_order(package_keyname, location, item_keynames,
complex_type=complex_type, hourly=hourly,
preset_keyname=preset_keyname,
extras=extras, quantity=quantity)
return self.order_svc.placeOrder(order)
def generate_order(self, package_keyname, location, item_keynames, complex_type=None,
hourly=True, preset_keyname=None, extras=None, quantity=1):
"""Generates an order with the given package and prices.
This function takes in parameters needed for an order and generates an order
dictionary. This dictionary can then be used in either verify or placeOrder().
:param str package_keyname: The keyname for the package being ordered
:param str location: The datacenter location string for ordering (Ex: DALLAS13)
:param list item_keynames: The list of item keyname strings to order. To see list of
possible keynames for a package, use list_items()
(or `slcli order item-list`)
:param str complex_type: The complex type to send with the order. Typically begins
with `SoftLayer_Container_Product_Order_`.
:param bool hourly: If true, uses hourly billing, otherwise uses monthly billing
:param string preset_keyname: If needed, specifies a preset to use for that package.
To see a list of possible keynames for a package, use
list_preset() (or `slcli order preset-list`)
:param dict extras: The extra data for the order in dictionary format.
Example: A VSI order requires hostname and domain to be set, so
extras will look like the following:
{'virtualGuests': [{'hostname': 'test', 'domain': 'softlayer.com'}]}
:param int quantity: The number of resources to order
"""
order = {}
extras = extras or {}
package = self.get_package_by_key(package_keyname, mask='id')
if not package:
raise exceptions.SoftLayerError("Package {} does not exist".format(package_keyname))
# if there was extra data given for the order, add it to the order
# example: VSIs require hostname and domain set on the order, so
# extras will be {'virtualGuests': [{'hostname': 'test',
# 'domain': 'softlayer.com'}]}
order.update(extras)
order['packageId'] = package['id']
order['location'] = location
order['quantity'] = quantity
order['useHourlyPricing'] = hourly
if preset_keyname:
preset_id = self.get_preset_by_key(package_keyname, preset_keyname)['id']
order['presetId'] = preset_id
if not complex_type:
raise exceptions.SoftLayerError("A complex type must be specified with the order")
order['complexType'] = complex_type
price_ids = self.get_price_id_list(package_keyname, item_keynames)
order['prices'] = [{'id': price_id} for price_id in price_ids]
return order