forked from softlayer/softlayer-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCCI.py
More file actions
297 lines (237 loc) · 10 KB
/
CCI.py
File metadata and controls
297 lines (237 loc) · 10 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
"""
SoftLayer.CCI
~~~~~~~~~~~~~
CCI Manager/helpers
:copyright: (c) 2013, SoftLayer Technologies, Inc. All rights reserved.
:license: BSD, see LICENSE for more details.
"""
import socket
from SoftLayer.exceptions import SoftLayerError
from SoftLayer.utils import NestedDict, query_filter, IdentifierMixin
from time import sleep
from itertools import repeat
class CCICreateMissingRequired(SoftLayerError):
def __init__(self):
self.message = "cpu, memory, hostname, and domain are required"
class CCICreateMutuallyExclusive(SoftLayerError):
def __init__(self, *args):
self.message = "Can only specify one of:", ','.join(args)
class CCIManager(IdentifierMixin, object):
""" Manage CCIs """
def __init__(self, client):
self.client = client
self.account = client['Account']
self.guest = client['Virtual_Guest']
self.resolvers = [self._get_ids_from_ip, self._get_ids_from_hostname]
def list_instances(self, hourly=True, monthly=True, tags=None, cpus=None,
memory=None, hostname=None, domain=None,
local_disk=None, datacenter=None, nic_speed=None,
public_ip=None, private_ip=None, **kwargs):
""" Retrieve a list of all CCIs on the account.
:param boolean hourly: include hourly instances
:param boolean monthly: include monthly instances
:param list tags: filter based on 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 domain: filter based on domain
:param string local_disk: filter based on local_disk
:param string datacenter: filter based on datacenter
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \*\*kwargs: response-level arguments (limit, offset, etc.)
"""
if 'mask' not in kwargs:
items = set([
'id',
'globalIdentifier',
'fullyQualifiedDomainName',
'primaryBackendIpAddress',
'primaryIpAddress',
'lastKnownPowerState.name',
'powerState.name',
'maxCpu',
'maxMemory',
'datacenter.name',
'activeTransaction.transactionStatus[friendlyName,name]',
'status.name',
'tagReferences[id,tag[name,id]]',
])
kwargs['mask'] = "mask[%s]" % ','.join(items)
call = 'getVirtualGuests'
if not all([hourly, monthly]):
if hourly:
call = 'getHourlyVirtualGuests'
elif monthly:
call = 'getMonthlyVirtualGuests'
_filter = NestedDict(kwargs.get('filter') or {})
if tags:
_filter['virtualGuests']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if cpus:
_filter['virtualGuests']['maxCpu'] = query_filter(cpus)
if memory:
_filter['virtualGuests']['maxMemory'] = query_filter(memory)
if hostname:
_filter['virtualGuests']['hostname'] = query_filter(hostname)
if domain:
_filter['virtualGuests']['domain'] = query_filter(domain)
if local_disk is not None:
_filter['virtualGuests']['localDiskFlag'] = \
query_filter(bool(local_disk))
if datacenter:
_filter['virtualGuests']['datacenter']['name'] = \
query_filter(datacenter)
if nic_speed:
_filter['virtualGuests']['networkComponents']['maxSpeed'] = \
query_filter(nic_speed)
if public_ip:
_filter['virtualGuests']['primaryIpAddress'] = \
query_filter(public_ip)
if private_ip:
_filter['virtualGuests']['primaryBackendIpAddress'] = \
query_filter(private_ip)
kwargs['filter'] = _filter.to_dict()
func = getattr(self.account, call)
return func(**kwargs)
def get_instance(self, id, **kwargs):
""" Get details about a CCI instance
:param integer id: the instance ID
"""
if 'mask' not in kwargs:
items = set([
'id',
'globalIdentifier',
'fullyQualifiedDomainName',
'hostname',
'domain',
'createDate',
'modifyDate',
'provisionDate',
'notes',
'dedicatedAccountHostOnlyFlag',
'privateNetworkOnlyFlag',
'primaryBackendIpAddress',
'primaryIpAddress',
'lastKnownPowerState.name',
'powerState.name',
'maxCpu',
'maxMemory',
'datacenter.name',
'activeTransaction.id',
'blockDeviceTemplateGroup[id, name]',
'status.name',
'operatingSystem.softwareLicense.'
'softwareDescription[manufacturer,name,version,referenceCode]',
'operatingSystem.passwords[username,password]',
'billingItem.recurringFee',
'tagReferences[id,tag[name,id]]',
])
kwargs['mask'] = "mask[%s]" % ','.join(items)
return self.guest.getObject(id=id, **kwargs)
def get_create_options(self):
return self.guest.getCreateObjectOptions()
def cancel_instance(self, id):
""" Cancel an instance immediately, deleting all its data.
:param integer id: the instance ID to cancel
"""
return self.guest.deleteObject(id=id)
def reload_instance(self, id):
""" Perform an OS reload of an instance with its current configuration.
:param integer id: the instance ID to reload
"""
return self.guest.reloadCurrentOperatingSystemConfiguration(id=id)
def _generate_create_dict(
self, cpus=None, memory=None, hourly=True,
hostname=None, domain=None, local_disk=True,
datacenter=None, os_code=None, image_id=None,
private=False, public_vlan=None, private_vlan=None,
userdata=None, nic_speed=None, disks=None):
required = [cpus, memory, hostname, domain]
mutually_exclusive = [
{'os_code': os_code, "image_id": image_id},
]
if not all(required):
raise CCICreateMissingRequired()
for me in mutually_exclusive:
if all(me.values()):
raise CCICreateMutuallyExclusive(*me.keys())
data = {
"startCpus": int(cpus),
"maxMemory": int(memory),
"hostname": hostname,
"domain": domain,
"localDiskFlag": local_disk,
}
data["hourlyBillingFlag"] = hourly
if private:
data["dedicatedAccountHostOnlyFlag"] = private
if image_id:
data["blockDeviceTemplateGroup"] = {"globalIdentifier": image_id}
elif os_code:
data["operatingSystemReferenceCode"] = os_code
if datacenter:
data["datacenter"] = {"name": datacenter}
if public_vlan:
data.update({
'primaryNetworkComponent': {
"networkVlan": {"id": int(public_vlan)}}})
if private_vlan:
data.update({
"primaryBackendNetworkComponent": {
"networkVlan": {"id": int(private_vlan)}}})
if userdata:
data['userData'] = [{'value': userdata}, ]
if nic_speed:
data['networkComponents'] = [{'maxSpeed': nic_speed}]
if isinstance(disks, list):
data['blockDevices'] = [
{"device": "0", "diskImage": {"capacity": disks[0]}}
]
# disk 1 is reservered for swap
# XXX: enumerate(iterator, start=0) was added in 2.6. work around
# for 2.5 by adding 2 to the enumerated value
for dev_id, disk in enumerate(disks[1:]):
data['blockDevices'].append(
{
"device": str(dev_id + 2),
"diskImage": {"capacity": disk}
}
)
return data
def wait_for_transaction(self, id, limit, delay=1):
for count, new_instance in enumerate(repeat(id)):
instance = self.get_instance(new_instance)
if not instance.get('activeTransaction', {}).get('id') and \
instance.get('provisionDate'):
return True
if count >= limit:
return False
sleep(delay)
def verify_create_instance(self, **kwargs):
""" see _generate_create_dict """ # TODO: document this
create_options = self._generate_create_dict(**kwargs)
return self.guest.generateOrderTemplate(create_options)
def create_instance(self, **kwargs):
""" see _generate_create_dict """ # TODO: document this
create_options = self._generate_create_dict(**kwargs)
return self.guest.createObject(create_options)
def _get_ids_from_hostname(self, hostname):
results = self.list_instances(hostname=hostname, mask="id")
return [result['id'] for result in results]
def _get_ids_from_ip(self, ip):
try:
# Does it look like an ip address?
socket.inet_aton(ip)
except socket.error:
return []
# Find the CCI via ip address. First try public ip, then private
results = self.list_instances(public_ip=ip, mask="id")
if results:
return [result['id'] for result in results]
results = self.list_instances(private_ip=ip, mask="id")
if results:
return [result['id'] for result in results]