forked from softlayer/softlayer-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdedicated_host.py
More file actions
367 lines (300 loc) · 12.5 KB
/
dedicated_host.py
File metadata and controls
367 lines (300 loc) · 12.5 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
"""
SoftLayer.dedicatedhost
~~~~~~~~~~~~~~~~~~~~~~~
DH Manager/helpers
:license: MIT, see License for more details.
"""
import logging
import SoftLayer
from SoftLayer.managers import ordering
from SoftLayer import utils
# Invalid names are ignored due to long method names and short argument names
# pylint: disable=invalid-name, no-self-use
LOGGER = logging.getLogger(__name__)
class DedicatedHostManager(utils.IdentifierMixin, object):
"""Manages SoftLayer Dedicated Hosts.
See product information here https://www.ibm.com/cloud/dedicated
:param SoftLayer.API.BaseClient client: the client instance
:param SoftLayer.managers.OrderingManager ordering_manager: an optional manager to handle ordering.
If none is provided, one will be auto initialized.
"""
def __init__(self, client, ordering_manager=None):
self.client = client
self.account = client['Account']
self.host = client['Virtual_DedicatedHost']
if ordering_manager is None:
self.ordering_manager = ordering.OrderingManager(client)
def list_instances(self, tags=None, cpus=None, memory=None, hostname=None,
disk=None, datacenter=None, **kwargs):
"""Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string disk: filter based on disk
:param string datacenter: filter based on datacenter
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching dedicated host.
"""
if 'mask' not in kwargs:
items = [
'id',
'name',
'cpuCount',
'diskCapacity',
'memoryCapacity',
'datacenter',
'guestCount',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['dedicatedHosts']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if hostname:
_filter['dedicatedHosts']['name'] = (
utils.query_filter(hostname)
)
if cpus:
_filter['dedicatedHosts']['cpuCount'] = utils.query_filter(cpus)
if disk:
_filter['dedicatedHosts']['diskCapacity'] = (
utils.query_filter(disk))
if memory:
_filter['dedicatedHosts']['memoryCapacity'] = (
utils.query_filter(memory))
if datacenter:
_filter['dedicatedHosts']['datacenter']['name'] = (
utils.query_filter(datacenter))
kwargs['filter'] = _filter.to_dict()
return self.account.getDedicatedHosts(**kwargs)
def get_host(self, host_id, **kwargs):
"""Get details about a dedicated host.
:param integer : the host ID
:returns: A dictionary containing host information.
Example::
# Print out host ID 12345.
dh = mgr.get_host(12345)
print dh
# Print out only name and backendRouter for instance 12345
object_mask = "mask[name,backendRouter[id]]"
dh = mgr.get_host(12345, mask=mask)
print dh
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('''
id,
name,
cpuCount,
memoryCapacity,
diskCapacity,
createDate,
modifyDate,
backendRouter[
id,
hostname,
domain
],
billingItem[
id,
nextInvoiceTotalRecurringAmount,
children[
categoryCode,
nextInvoiceTotalRecurringAmount
],
orderItem[
id,
order.userRecord[
username
]
]
],
datacenter[
id,
name,
longName
],
guests[
id,
hostname,
domain,
uuid
],
guestCount
''')
return self.host.getObject(id=host_id, **kwargs)
def place_order(self, hostname, domain, location, flavor, hourly, router=None):
"""Places an order for a dedicated host.
See get_create_options() for valid arguments.
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param int router: an optional value for selecting a backend router
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].placeOrder(create_options)
def verify_order(self, hostname, domain, location, hourly, flavor, router=None):
"""Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options.
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].verifyOrder(create_options)
def _generate_create_dict(self,
hostname=None,
domain=None,
flavor=None,
router=None,
datacenter=None,
hourly=True):
"""Translates args into a dictionary for creating a dedicated host."""
package = self._get_package()
item = self._get_item(package, flavor)
location = self._get_location(package['regions'], datacenter)
price = self._get_price(item)
routers = self._get_backend_router(
location['location']['locationPackageDetails'], item)
router = self._get_default_router(routers, router)
hardware = {
'hostname': hostname,
'domain': domain,
'primaryBackendNetworkComponent': {
'router': {
'id': router
}
}
}
complex_type = "SoftLayer_Container_Product_Order_Virtual_DedicatedHost"
order = {
"complexType": complex_type,
"quantity": 1,
'location': location['keyname'],
'packageId': package['id'],
'prices': [{'id': price}],
'hardware': [hardware],
'useHourlyPricing': hourly,
}
return order
def _get_package(self):
"""Get the package related to simple dedicated host ordering."""
mask = '''
items[
id,
description,
prices,
capacity,
keyName,
itemCategory[categoryCode],
bundleItems[capacity, categories[categoryCode]]
],
regions[location[location[priceGroups]]]
'''
package_keyname = 'DEDICATED_HOST'
package = self.ordering_manager.get_package_by_key(package_keyname,
mask=mask)
if package is None:
raise SoftLayer.SoftLayerError("Ordering package not found")
return package
def _get_location(self, regions, datacenter):
"""Get the longer key with a short location(datacenter) name."""
for region in regions:
# list of locations
if region['location']['location']['name'] == datacenter:
return region
raise SoftLayer.SoftLayerError("Could not find valid location for: '%s'"
% datacenter)
def get_create_options(self):
"""Returns valid options for ordering a dedicated host."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# flavors
dedicated_host = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == \
'dedicated_virtual_hosts':
dedicated_host.append({
'name': item['description'],
'key': item['keyName'],
})
return {
'locations': locations,
'dedicated_host': dedicated_host,
}
def _get_price(self, package):
"""Returns valid price for ordering a dedicated host."""
for price in package['prices']:
if not price.get('locationGroupId'):
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price")
def _get_item(self, package, flavor):
"""Returns the item for ordering a dedicated host."""
for item in package['items']:
if item['keyName'] == flavor:
return item
raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'"
% flavor)
def _get_backend_router(self, locations, item):
"""Returns valid router options for ordering a dedicated host."""
mask = '''
id,
hostname
'''
cpu_count = item['capacity']
for capacity in item['bundleItems']:
for category in capacity['categories']:
if category['categoryCode'] == 'dedicated_host_ram':
mem_capacity = capacity['capacity']
if category['categoryCode'] == 'dedicated_host_disk':
disk_capacity = capacity['capacity']
if locations is not None:
for location in locations:
if location['locationId'] is not None:
loc_id = location['locationId']
host = {
'cpuCount': cpu_count,
'memoryCapacity': mem_capacity,
'diskCapacity': disk_capacity,
'datacenter': {
'id': loc_id
}
}
routers = self.host.getAvailableRouters(host, mask=mask)
return routers
raise SoftLayer.SoftLayerError("Could not find available routers")
def _get_default_router(self, routers, router_name=None):
"""Returns the default router for ordering a dedicated host."""
if router_name is None:
for router in routers:
if router['id'] is not None:
return router['id']
else:
for router in routers:
if router['hostname'] == router_name:
return router['id']
raise SoftLayer.SoftLayerError("Could not find valid default router")
def get_router_options(self, datacenter=None, flavor=None):
"""Returns available backend routers for the dedicated host."""
package = self._get_package()
location = self._get_location(package['regions'], datacenter)
item = self._get_item(package, flavor)
return self._get_backend_router(location['location']['locationPackageDetails'], item)