-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
libcloudfuncs.py
502 lines (415 loc) · 13.8 KB
/
libcloudfuncs.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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# -*- coding: utf-8 -*-
'''
The generic libcloud template used to create the connections and deploy the
cloud virtual machines
'''
from __future__ import absolute_import
# Import python libs
import os
import logging
from salt.ext.six import string_types
import salt.ext.six as six
from salt.ext.six.moves import zip
# pylint: disable=W0611
# Import libcloud
try:
import libcloud
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.compute.deployment import (
MultiStepDeployment,
ScriptDeployment
)
HAS_LIBCLOUD = True
LIBCLOUD_VERSION_INFO = tuple([
int(part) for part in libcloud.__version__.replace('-', '.').split('.')[:3]
])
except ImportError:
HAS_LIBCLOUD = False
LIBCLOUD_VERSION_INFO = (1000,)
# pylint: enable=W0611
# Import salt libs
import salt.utils.event
import salt.client
# Import salt cloud libs
import salt.utils
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudNotFound, SaltCloudSystemExit
# Get logging started
log = logging.getLogger(__name__)
LIBCLOUD_MINIMAL_VERSION = (0, 14, 0)
def node_state(id_):
'''
Libcloud supported node states
'''
states = {0: 'RUNNING',
1: 'REBOOTING',
2: 'TERMINATED',
3: 'PENDING',
4: 'UNKNOWN',
5: 'STOPPED',
6: 'SUSPENDED',
7: 'ERROR',
8: 'PAUSED'}
return states[id_]
def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None):
'''
Compare different libcloud versions
'''
if not HAS_LIBCLOUD:
return False
if not isinstance(reqver, (list, tuple)):
raise RuntimeError(
'\'reqver\' needs to passed as a tuple or list, i.e., (0, 14, 0)'
)
try:
import libcloud # pylint: disable=redefined-outer-name
except ImportError:
raise ImportError(
'salt-cloud requires >= libcloud {0} which is not installed'.format(
'.'.join([str(num) for num in reqver])
)
)
if LIBCLOUD_VERSION_INFO >= reqver:
return libcloud.__version__
errormsg = 'Your version of libcloud is {0}. '.format(libcloud.__version__)
errormsg += 'salt-cloud requires >= libcloud {0}'.format(
'.'.join([str(num) for num in reqver])
)
if why:
errormsg += ' for {0}'.format(why)
errormsg += '. Please upgrade.'
raise ImportError(errormsg)
def get_node(conn, name):
'''
Return a libcloud node for the named VM
'''
nodes = conn.list_nodes()
for node in nodes:
if node.name == name:
salt.utils.cloud.cache_node(salt.utils.cloud.simple_types_filter(node.__dict__), __active_provider_name__, __opts__)
return node
def avail_locations(conn=None, call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn() # pylint: disable=E0602
locations = conn.list_locations()
ret = {}
for img in locations:
if isinstance(img.name, string_types):
img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
else:
img_name = str(img.name)
ret[img_name] = {}
for attr in dir(img):
if attr.startswith('_'):
continue
attr_value = getattr(img, attr)
if isinstance(attr_value, string_types):
attr_value = attr_value.encode(
'ascii', 'salt-cloud-force-ascii'
)
ret[img_name][attr] = attr_value
return ret
def avail_images(conn=None, call=None):
'''
Return a dict of all available VM images on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn() # pylint: disable=E0602
images = conn.list_images()
ret = {}
for img in images:
if isinstance(img.name, string_types):
img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
else:
img_name = str(img.name)
ret[img_name] = {}
for attr in dir(img):
if attr.startswith('_'):
continue
attr_value = getattr(img, attr)
if isinstance(attr_value, string_types):
attr_value = attr_value.encode(
'ascii', 'salt-cloud-force-ascii'
)
ret[img_name][attr] = attr_value
return ret
def avail_sizes(conn=None, call=None):
'''
Return a dict of all available VM images on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if not conn:
conn = get_conn() # pylint: disable=E0602
sizes = conn.list_sizes()
ret = {}
for size in sizes:
if isinstance(size.name, string_types):
size_name = size.name.encode('ascii', 'salt-cloud-force-ascii')
else:
size_name = str(size.name)
ret[size_name] = {}
for attr in dir(size):
if attr.startswith('_'):
continue
try:
attr_value = getattr(size, attr)
except Exception:
pass
if isinstance(attr_value, string_types):
attr_value = attr_value.encode(
'ascii', 'salt-cloud-force-ascii'
)
ret[size_name][attr] = attr_value
return ret
def get_location(conn, vm_):
'''
Return the location object to use
'''
locations = conn.list_locations()
vm_location = config.get_cloud_config_value('location', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
for img in locations:
if isinstance(img.id, string_types):
img_id = img.id.encode('ascii', 'salt-cloud-force-ascii')
else:
img_id = str(img.id)
if isinstance(img.name, string_types):
img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
else:
img_name = str(img.name)
if vm_location and vm_location in (img_id, img_name):
return img
raise SaltCloudNotFound(
'The specified location, {0!r}, could not be found.'.format(
vm_location
)
)
def get_image(conn, vm_):
'''
Return the image object to use
'''
images = conn.list_images()
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
for img in images:
if isinstance(img.id, string_types):
img_id = img.id.encode('ascii', 'salt-cloud-force-ascii')
else:
img_id = str(img.id)
if isinstance(img.name, string_types):
img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
else:
img_name = str(img.name)
if vm_image and vm_image in (img_id, img_name):
return img
raise SaltCloudNotFound(
'The specified image, {0!r}, could not be found.'.format(vm_image)
)
def get_size(conn, vm_):
'''
Return the VM's size object
'''
sizes = conn.list_sizes()
vm_size = config.get_cloud_config_value('size', vm_, __opts__)
if not vm_size:
return sizes[0]
for size in sizes:
if vm_size and str(vm_size) in (str(size.id), str(size.name)):
return size
raise SaltCloudNotFound(
'The specified size, {0!r}, could not be found.'.format(vm_size)
)
def script(vm_):
'''
Return the script deployment object
'''
return ScriptDeployment(
salt.utils.cloud.os_script(
config.get_cloud_config_value('os', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
)
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
salt.utils.cloud.fire_event(
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
{'name': name},
transport=__opts__['transport']
)
if not conn:
conn = get_conn() # pylint: disable=E0602
node = get_node(conn, name)
profiles = get_configured_provider()['profiles'] # pylint: disable=E0602
if node is None:
log.error('Unable to find the VM {0}'.format(name))
profile = None
if 'metadata' in node.extra and 'profile' in node.extra['metadata']:
profile = node.extra['metadata']['profile']
flush_mine_on_destroy = False
if profile is not None and profile in profiles:
if 'flush_mine_on_destroy' in profiles[profile]:
flush_mine_on_destroy = profiles[profile]['flush_mine_on_destroy']
if flush_mine_on_destroy:
log.info('Clearing Salt Mine: {0}'.format(name))
mopts_ = salt.config.DEFAULT_MINION_OPTS
conf_path = '/'.join(__opts__['conf_file'].split('/')[:-1])
mopts_.update(
salt.config.minion_config(os.path.join(conf_path, 'minion'))
)
client = salt.client.get_local_client(mopts_)
minions = client.cmd(name, 'mine.flush')
log.info('Clearing Salt Mine: {0}, {1}'.format(name, flush_mine_on_destroy))
log.info('Destroying VM: {0}'.format(name))
ret = conn.destroy_node(node)
if ret:
log.info('Destroyed VM: {0}'.format(name))
# Fire destroy action
salt.utils.cloud.fire_event(
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
{'name': name},
transport=__opts__['transport']
)
if __opts__['delete_sshkeys'] is True:
salt.utils.cloud.remove_sshkey(getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
salt.utils.cloud.delete_minion_cachedir(name, __active_provider_name__.split(':')[0], __opts__)
return True
log.error('Failed to Destroy VM: {0}'.format(name))
return False
def reboot(name, conn=None):
'''
Reboot a single VM
'''
if not conn:
conn = get_conn() # pylint: disable=E0602
node = get_node(conn, name)
if node is None:
log.error('Unable to find the VM {0}'.format(name))
log.info('Rebooting VM: {0}'.format(name))
ret = conn.reboot_node(node)
if ret:
log.info('Rebooted VM: {0}'.format(name))
# Fire reboot action
salt.utils.cloud.fire_event(
'event',
'{0} has been rebooted'.format(name), 'salt-cloud'
'salt/cloud/{0}/rebooting'.format(name),
{'name': name},
transport=__opts__['transport']
)
return True
log.error('Failed to reboot VM: {0}'.format(name))
return False
def list_nodes(conn=None, call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn() # pylint: disable=E0602
nodes = conn.list_nodes()
ret = {}
for node in nodes:
ret[node.name] = {
'id': node.id,
'image': node.image,
'private_ips': node.private_ips,
'public_ips': node.public_ips,
'size': node.size,
'state': node_state(node.state)
}
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn() # pylint: disable=E0602
nodes = conn.list_nodes()
ret = {}
for node in nodes:
pairs = {}
for key, value in zip(node.__dict__, six.itervalues(node.__dict__)):
pairs[key] = value
ret[node.name] = pairs
del ret[node.name]['driver']
salt.utils.cloud.cache_node_list(ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn() # pylint: disable=E0602
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
salt.utils.cloud.cache_node(nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def conn_has_method(conn, method_name):
'''
Find if the provided connection object has a specific method
'''
if method_name in dir(conn):
return True
log.error(
'Method {0!r} not yet supported!'.format(
method_name
)
)
return False