forked from saltstack/salt
/
__init__.py
2370 lines (2093 loc) · 86.4 KB
/
__init__.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
'''
The top level interface used to translate configuration data back to the
correct cloud modules
'''
# Import python libs
from __future__ import absolute_import, print_function, generators
import os
import copy
import glob
import time
import signal
import logging
import traceback
import multiprocessing
import sys
from itertools import groupby
# Import salt.cloud libs
from salt.exceptions import (
SaltCloudNotFound,
SaltCloudException,
SaltCloudSystemExit,
SaltCloudConfigError
)
# Import salt libs
import salt.config
import salt.client
import salt.loader
import salt.utils
import salt.utils.cloud
import salt.syspaths
from salt.utils import reinit_crypto
from salt.utils import context
from salt.ext.six import string_types
from salt.template import compile_template
# Import third party libs
try:
import Crypto.Random
except ImportError:
pass # pycrypto < 2.1
import yaml
import salt.ext.six as six
from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin
# Get logging started
log = logging.getLogger(__name__)
def communicator(func):
'''Warning, this is a picklable decorator !'''
def _call(queue, args, kwargs):
'''called with [queue, args, kwargs] as first optional arg'''
kwargs['queue'] = queue
ret = None
try:
ret = func(*args, **kwargs)
queue.put('END')
except KeyboardInterrupt as ex:
trace = traceback.format_exc()
queue.put('KEYBOARDINT')
queue.put('Keyboard interrupt')
queue.put('{0}\n{1}\n'.format(ex, trace))
except Exception as ex:
trace = traceback.format_exc()
queue.put('ERROR')
queue.put('Exception')
queue.put('{0}\n{1}\n'.format(ex, trace))
return ret
return _call
def enter_mainloop(target,
mapped_args=None,
args=None,
kwargs=None,
pool=None,
pool_size=None,
callback=None,
queue=None):
'''
Manage a multiprocessing pool
- If the queue does not output anything, the pool runs indefinitely
- If the queue returns KEYBOARDINT or ERROR, this will kill the pool
totally calling terminate & join and ands with a SaltCloudSystemExit
exception notifying callers from the abnormal termination
- If the queue returns END or callback is defined and returns True,
it just join the process and return the data.
target
the function you want to execute in multiproccessing
pool
pool object can be None if you want a default pool, but you ll
have then to define pool_size instead
pool_size
pool size if you did not provide yourself a pool
callback
a boolean taking a string in argument which returns True to
signal that 'target' is finished and we need to join
the pool
queue
A custom multiproccessing queue in case you want to do
extra stuff and need it later in your program
args
positional arguments to call the function with
if you don't want to use pool.map
mapped_args
a list of one or more arguments combinations to call the function with
e.g. (foo, [[1], [2]]) will call::
foo([1])
foo([2])
kwargs
kwargs to give to the function in case of process
Attention, the function must have the following signature:
target(queue, *args, **kw)
You may use the 'communicator' decorator to generate such a function
(see end of this file)
'''
if not kwargs:
kwargs = {}
if not pool_size:
pool_size = 1
if not pool:
pool = multiprocessing.Pool(pool_size)
if not queue:
manager = multiprocessing.Manager()
queue = manager.Queue()
if mapped_args is not None and not mapped_args:
msg = (
six.u('We are called to asynchronously execute {0} '
'but we do no have anything to execute, weird, '
'we bail out').format(target))
log.error(msg)
raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg))
elif mapped_args is not None:
iterable = [[queue, [arg], kwargs] for arg in mapped_args]
ret = pool.map(func=target, iterable=iterable)
else:
ret = pool.apply(target, [queue, args, kwargs])
while True:
test = queue.get()
if test in ['ERROR', 'KEYBOARDINT']:
type_ = queue.get()
trace = queue.get()
msg = six.u('Caught {0}, terminating workers\n'
'TRACE: {1}\n').format(
type_,
trace
)
log.error(msg)
pool.terminate()
pool.join()
raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg))
elif test in ['END'] or (callback and callback(test)):
pool.close()
pool.join()
break
else:
time.sleep(0.125)
return ret
class CloudClient(object):
'''
The client class to wrap cloud interactions
'''
def __init__(self, path=None, opts=None, config_dir=None, pillars=None):
if opts:
self.opts = opts
else:
self.opts = salt.config.cloud_config(path)
if pillars:
for name, provider in six.iteritems(pillars.pop('providers', {})):
# Since using "provider: <provider-engine>" is deprecated, alias provider
# to use driver: "driver: <provider-engine>"
if 'provider' in provider:
driver = provider.pop('provider')
else:
driver = provider['driver']
provider['profiles'] = {}
self.opts['providers'].update({name: {driver: provider}})
for name, profile in six.iteritems(pillars.pop('profiles', {})):
provider = profile['provider'].split(':')[0]
driver = next(six.iterkeys(self.opts['providers'][provider]))
profile['provider'] = '{0}:{1}'.format(provider, driver)
profile['profile'] = name
self.opts['profiles'].update({name: profile})
self.opts['providers'][provider][driver]['profiles'].update({name: profile})
self.opts.update(pillars)
def _opts_defaults(self, **kwargs):
'''
Set the opts dict to defaults and allow for opts to be overridden in
the kwargs
'''
# Let's start with the default salt cloud configuration
opts = salt.config.CLOUD_CONFIG_DEFAULTS.copy()
# Update it with the loaded configuration
opts.update(self.opts.copy())
# Reset some of the settings to sane values
opts['parallel'] = False
opts['keep_tmp'] = False
opts['deploy'] = True
opts['update_bootstrap'] = False
opts['show_deploy_args'] = False
opts['script_args'] = ''
# Update it with the passed kwargs
if 'kwargs' in kwargs:
opts.update(kwargs['kwargs'])
opts.update(kwargs)
profile = opts.get('profile', None)
# filter other profiles if one is specified
if profile:
for _profile in [a for a in opts.get('profiles', {})]:
if not _profile == profile:
opts['profiles'].pop(_profile)
# if profile is specified and we have enough info about providers
# also filter them to speedup methods like
# __filter_non_working_providers
providers = [a.get('provider', '').split(':')[0]
for a in six.itervalues(opts['profiles'])
if a.get('provider', '')]
if providers:
_providers = opts.get('providers', {})
for provider in _providers.keys():
if provider not in providers:
_providers.pop(provider)
return opts
def low(self, fun, low):
'''
Pass the cloud function and low data structure to run
'''
l_fun = getattr(self, fun)
f_call = salt.utils.format_call(l_fun, low)
return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
def list_sizes(self, provider=None):
'''
List all available sizes in configured cloud systems
'''
mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.cloud.simple_types_filter(
mapper.size_list(provider)
)
def list_images(self, provider=None):
'''
List all available images in configured cloud systems
'''
mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.cloud.simple_types_filter(
mapper.image_list(provider)
)
def list_locations(self, provider=None):
'''
List all available locations in configured cloud systems
'''
mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.cloud.simple_types_filter(
mapper.location_list(provider)
)
def query(self, query_type='list_nodes'):
'''
Query basic instance information
'''
mapper = salt.cloud.Map(self._opts_defaults())
return mapper.map_providers_parallel(query_type)
def full_query(self, query_type='list_nodes_full'):
'''
Query all instance information
'''
mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts['selected_query_option'] = 'list_nodes_full'
return mapper.map_providers_parallel(query_type)
def select_query(self, query_type='list_nodes_select'):
'''
Query select instance information
'''
mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts['selected_query_option'] = 'list_nodes_select'
return mapper.map_providers_parallel(query_type)
def min_query(self, query_type='list_nodes_min'):
'''
Query select instance information
'''
mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts['selected_query_option'] = 'list_nodes_min'
return mapper.map_providers_parallel(query_type)
def profile(self, profile, names, vm_overrides=None, **kwargs):
'''
Pass in a profile to create, names is a list of vm names to allocate
vm_overrides is a special dict that will be per node options
overrides
Example:
.. code-block:: python
>>> client= salt.cloud.CloudClient(path='/etc/salt/cloud')
>>> client.profile('do_512_git', names=['minion01',])
{'minion01': {u'backups_active': 'False',
u'created_at': '2014-09-04T18:10:15Z',
u'droplet': {u'event_id': 31000502,
u'id': 2530006,
u'image_id': 5140006,
u'name': u'minion01',
u'size_id': 66},
u'id': '2530006',
u'image_id': '5140006',
u'ip_address': '107.XXX.XXX.XXX',
u'locked': 'True',
u'name': 'minion01',
u'private_ip_address': None,
u'region_id': '4',
u'size_id': '66',
u'status': 'new'}}
'''
if not vm_overrides:
vm_overrides = {}
kwargs['profile'] = profile
mapper = salt.cloud.Map(self._opts_defaults(**kwargs))
if isinstance(names, str):
names = names.split(',')
return salt.utils.cloud.simple_types_filter(
mapper.run_profile(profile, names, vm_overrides=vm_overrides)
)
def map_run(self, path, **kwargs):
'''
Pass in a location for a map to execute
'''
kwarg = {'map': path}
kwarg.update(kwargs)
mapper = salt.cloud.Map(self._opts_defaults(**kwarg))
dmap = mapper.map_data()
return salt.utils.cloud.simple_types_filter(
mapper.run_map(dmap)
)
def destroy(self, names):
'''
Destroy the named VMs
'''
mapper = salt.cloud.Map(self._opts_defaults(destroy=True))
if isinstance(names, str):
names = names.split(',')
return salt.utils.cloud.simple_types_filter(
mapper.destroy(names)
)
def create(self, provider, names, **kwargs):
'''
Create the named VMs, without using a profile
Example:
.. code-block:: python
client.create(names=['myinstance'], provider='my-ec2-config',
kwargs={'image': 'ami-1624987f', 'size': 't1.micro',
'ssh_username': 'ec2-user', 'securitygroup': 'default',
'delvol_on_destroy': True})
'''
mapper = salt.cloud.Map(self._opts_defaults())
providers = self.opts['providers']
if provider in providers:
provider += ':{0}'.format(next(six.iterkeys(providers[provider])))
else:
return False
if isinstance(names, str):
names = names.split(',')
ret = {}
for name in names:
vm_ = kwargs.copy()
# Since using "provider: <provider-engine>" is deprecated, alias provider
# to use driver: "driver: <provider-engine>"
if 'provider' in vm_:
vm_['driver'] = vm_.pop('provider')
vm_['name'] = name
vm_['driver'] = provider
vm_['profile'] = None
ret[name] = salt.utils.cloud.simple_types_filter(
mapper.create(vm_))
return ret
def extra_action(self, names, provider, action, **kwargs):
'''
Perform actions with block storage devices
Example:
.. code-block:: python
client.extra_action(names=['myblock'], action='volume_create',
provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}
)
client.extra_action(names=['salt-net'], action='network_create',
provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}
)
'''
mapper = salt.cloud.Map(self._opts_defaults())
providers = mapper.map_providers_parallel()
if provider in providers:
provider += ':{0}'.format(next(six.iterkeys(providers[provider])))
else:
return False
if isinstance(names, str):
names = names.split(',')
ret = {}
for name in names:
extra_ = kwargs.copy()
extra_['name'] = name
extra_['provider'] = provider
extra_['profile'] = None
extra_['action'] = action
ret[name] = salt.utils.cloud.simple_types_filter(
mapper.extras(extra_)
)
return ret
def action(
self,
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
kwargs=None
):
'''
Execute a single action via the cloud plugin backend
Examples:
.. code-block:: python
client.action(fun='show_instance', names=['myinstance'])
client.action(fun='show_image', provider='my-ec2-config',
kwargs={'image': 'ami-10314d79'}
)
'''
mapper = salt.cloud.Map(self._opts_defaults(action=fun, names=names))
if instance:
if names:
raise SaltCloudConfigError(
'Please specify either a list of \'names\' or a single '
'\'instance\', but not both.'
)
names = [instance]
if names and not provider:
self.opts['action'] = fun
return mapper.do_action(names, kwargs)
if provider and not names:
return mapper.do_function(provider, fun, kwargs)
else:
# This should not be called without either an instance or a
# provider. If both an instance/list of names and a provider
# are given, then we also need to exit. We can only have one
# or the other.
raise SaltCloudConfigError(
'Either an instance (or list of names) or a provider must be '
'specified, but not both.'
)
class Cloud(object):
'''
An object for the creation of new VMs
'''
def __init__(self, opts):
self.opts = opts
self.clouds = salt.loader.clouds(self.opts)
self.__filter_non_working_providers()
self.__cached_provider_queries = {}
def get_configured_providers(self):
'''
Return the configured providers
'''
providers = set()
for alias, drivers in six.iteritems(self.opts['providers']):
if len(drivers) > 1:
for driver in drivers:
providers.add('{0}:{1}'.format(alias, driver))
continue
providers.add(alias)
return providers
def lookup_providers(self, lookup):
'''
Get a dict describing the configured providers
'''
if lookup is None:
lookup = 'all'
if lookup == 'all':
providers = set()
for alias, drivers in six.iteritems(self.opts['providers']):
for driver in drivers:
providers.add((alias, driver))
if not providers:
raise SaltCloudSystemExit(
'There are no cloud providers configured.'
)
return providers
if ':' in lookup:
alias, driver = lookup.split(':')
if alias not in self.opts['providers'] or \
driver not in self.opts['providers'][alias]:
raise SaltCloudSystemExit(
'No cloud providers matched {0!r}. Available: {1}'.format(
lookup, ', '.join(self.get_configured_providers())
)
)
providers = set()
for alias, drivers in six.iteritems(self.opts['providers']):
for driver in drivers:
if lookup in (alias, driver):
providers.add((alias, driver))
if not providers:
raise SaltCloudSystemExit(
'No cloud providers matched {0!r}. '
'Available selections: {1}'.format(
lookup, ', '.join(self.get_configured_providers())
)
)
return providers
def lookup_profiles(self, provider, lookup):
'''
Return a dictionary describing the configured profiles
'''
if provider is None:
provider = 'all'
if lookup is None:
lookup = 'all'
if lookup == 'all':
profiles = set()
provider_profiles = set()
for alias, info in six.iteritems(self.opts['profiles']):
providers = info.get('provider')
if providers:
given_prov_name = providers.split(':')[0]
salt_prov_name = providers.split(':')[1]
if given_prov_name == provider:
provider_profiles.add((alias, given_prov_name))
elif salt_prov_name == provider:
provider_profiles.add((alias, salt_prov_name))
profiles.add((alias, given_prov_name))
if not profiles:
raise SaltCloudSystemExit(
'There are no cloud profiles configured.'
)
if provider != 'all':
return provider_profiles
return profiles
def map_providers(self, query='list_nodes', cached=False):
'''
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
'''
if cached is True and query in self.__cached_provider_queries:
return self.__cached_provider_queries[query]
pmap = {}
for alias, drivers in six.iteritems(self.opts['providers']):
for driver, details in six.iteritems(drivers):
fun = '{0}.{1}'.format(driver, query)
if fun not in self.clouds:
log.error(
six.u('Public cloud provider {0} is not available').format(
driver
)
)
continue
if alias not in pmap:
pmap[alias] = {}
try:
with context.func_globals_inject(
self.clouds[fun],
__active_provider_name__=':'.join([alias, driver])
):
pmap[alias][driver] = self.clouds[fun]()
except Exception as err:
log.debug(six.u(
'Failed to execute \'{0}()\' while querying for '
'running nodes: {1}').format(fun, err),
# Show the traceback if the debug logging level is
# enabled
exc_info_on_loglevel=logging.DEBUG
)
# Failed to communicate with the provider, don't list any
# nodes
pmap[alias][driver] = []
self.__cached_provider_queries[query] = pmap
return pmap
def map_providers_parallel(self, query='list_nodes', cached=False):
'''
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
Same as map_providers but query in parallel.
'''
if cached is True and query in self.__cached_provider_queries:
return self.__cached_provider_queries[query]
opts = self.opts.copy()
multiprocessing_data = []
# Optimize Providers
opts['providers'] = self._optimize_providers(opts['providers'])
for alias, drivers in six.iteritems(opts['providers']):
# Make temp query for this driver to avoid overwrite next
this_query = query
for driver, details in six.iteritems(drivers):
# If driver has function list_nodes_min, just replace it
# with query param to check existing vms on this driver
# for minimum information, Otherwise still use query param.
if 'selected_query_option' not in opts and '{0}.list_nodes_min'.format(driver) in self.clouds:
this_query = 'list_nodes_min'
fun = '{0}.{1}'.format(driver, this_query)
if fun not in self.clouds:
log.error(
six.u('Public cloud provider {0} is not available').format(
driver
)
)
continue
multiprocessing_data.append({
'fun': fun,
'opts': opts,
'query': this_query,
'alias': alias,
'driver': driver
})
output = {}
if not multiprocessing_data:
return output
data_count = len(multiprocessing_data)
pool = multiprocessing.Pool(data_count < 10 and data_count or 10,
init_pool_worker)
parallel_pmap = enter_mainloop(_run_parallel_map_providers_query,
multiprocessing_data,
pool=pool)
for alias, driver, details in parallel_pmap:
if not details:
# There's no providers details?! Skip it!
continue
if alias not in output:
output[alias] = {}
output[alias][driver] = details
self.__cached_provider_queries[query] = output
return output
def get_running_by_names(self, names, query='list_nodes', cached=False,
profile=None):
if isinstance(names, string_types):
names = [names]
matches = {}
handled_drivers = {}
mapped_providers = self.map_providers_parallel(query, cached=cached)
for alias, drivers in six.iteritems(mapped_providers):
for driver, vms in six.iteritems(drivers):
if driver not in handled_drivers:
handled_drivers[driver] = alias
# When a profile is specified, only return an instance
# that matches the provider specified in the profile.
# This solves the issues when many providers return the
# same instance. For example there may be one provider for
# each availability zone in amazon in the same region, but
# the search returns the same instance for each provider
# because amazon returns all instances in a region, not
# availability zone.
if profile and alias not in self.opts['profiles'][profile]['provider'].split(':')[0]:
continue
for vm_name, details in six.iteritems(vms):
# XXX: The logic below can be removed once the aws driver
# is removed
if vm_name not in names:
continue
elif driver == 'ec2' and 'aws' in handled_drivers and \
'aws' in matches[handled_drivers['aws']] and \
vm_name in matches[handled_drivers['aws']]['aws']:
continue
elif driver == 'aws' and 'ec2' in handled_drivers and \
'ec2' in matches[handled_drivers['ec2']] and \
vm_name in matches[handled_drivers['ec2']]['ec2']:
continue
if alias not in matches:
matches[alias] = {}
if driver not in matches[alias]:
matches[alias][driver] = {}
matches[alias][driver][vm_name] = details
return matches
def _optimize_providers(self, providers):
'''
Return an optimized mapping of available providers
'''
new_providers = {}
provider_by_driver = {}
for alias, driver in six.iteritems(providers):
for name, data in six.iteritems(driver):
if name not in provider_by_driver:
provider_by_driver[name] = {}
provider_by_driver[name][alias] = data
for driver, providers_data in six.iteritems(provider_by_driver):
fun = '{0}.optimize_providers'.format(driver)
if fun not in self.clouds:
log.debug(
six.u('The {0!r} cloud driver is unable to be optimized.').format(
driver
)
)
for name, prov_data in six.iteritems(providers_data):
if name not in new_providers:
new_providers[name] = {}
new_providers[name][driver] = prov_data
continue
new_data = self.clouds[fun](providers_data)
if new_data:
for name, prov_data in six.iteritems(new_data):
if name not in new_providers:
new_providers[name] = {}
new_providers[name][driver] = prov_data
return new_providers
def location_list(self, lookup='all'):
'''
Return a mapping of all location data for available providers
'''
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
fun = '{0}.avail_locations'.format(driver)
if fun not in self.clouds:
# The capability to gather locations is not supported by this
# cloud module
log.debug(
six.u('The {0!r} cloud driver defined under {1!r} provider '
'alias is unable to get the locations information').format(
driver, alias
)
)
continue
if alias not in data:
data[alias] = {}
try:
with context.func_globals_inject(
self.clouds[fun],
__active_provider_name__=':'.join([alias, driver])
):
data[alias][driver] = self.clouds[fun]()
except Exception as err:
log.error(
six.u('Failed to get the output of \'{0}()\': {1}').format(
fun, err
),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return data
def image_list(self, lookup='all'):
'''
Return a mapping of all image data for available providers
'''
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
fun = '{0}.avail_images'.format(driver)
if fun not in self.clouds:
# The capability to gather images is not supported by this
# cloud module
log.debug(
six.u('The {0!r} cloud driver defined under {1!r} provider '
'alias is unable to get the images information').format(
driver,
alias
)
)
continue
if alias not in data:
data[alias] = {}
try:
with context.func_globals_inject(
self.clouds[fun],
__active_provider_name__=':'.join([alias, driver])
):
data[alias][driver] = self.clouds[fun]()
except Exception as err:
log.error(
six.u('Failed to get the output of \'{0}()\': {1}').format(
fun, err
),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return data
def size_list(self, lookup='all'):
'''
Return a mapping of all image data for available providers
'''
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
fun = '{0}.avail_sizes'.format(driver)
if fun not in self.clouds:
# The capability to gather sizes is not supported by this
# cloud module
log.debug(
six.u('The {0!r} cloud driver defined under {1!r} provider '
'alias is unable to get the sizes information').format(
driver,
alias
)
)
continue
if alias not in data:
data[alias] = {}
try:
with context.func_globals_inject(
self.clouds[fun],
__active_provider_name__=':'.join([alias, driver])
):
data[alias][driver] = self.clouds[fun]()
except Exception as err:
log.error(
six.u('Failed to get the output of \'{0}()\': {1}').format(
fun, err
),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return data
def provider_list(self, lookup='all'):
'''
Return a mapping of all image data for available providers
'''
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
if alias not in data:
data[alias] = {}
if driver not in data[alias]:
data[alias][driver] = {}
return data
def profile_list(self, provider, lookup='all'):
'''
Return a mapping of all configured profiles
'''
data = {}
lookups = self.lookup_profiles(provider, lookup)
if not lookups:
return data
for alias, driver in lookups:
if alias not in data:
data[alias] = {}
if driver not in data[alias]:
data[alias][driver] = {}
return data
def create_all(self):
'''
Create/Verify the VMs in the VM data
'''
ret = []
for vm_name, vm_details in six.iteritems(self.opts['profiles']):
ret.append(
{vm_name: self.create(vm_details)}
)
return ret
def destroy(self, names, cached=False):
'''
Destroy the named VMs
'''
processed = {}
names = set(names)
matching = self.get_running_by_names(names, cached=cached)
vms_to_destroy = set()
parallel_data = []
for alias, drivers in six.iteritems(matching):
for driver, vms in six.iteritems(drivers):
for name in vms:
if name in names:
vms_to_destroy.add((alias, driver, name))
if self.opts['parallel']:
parallel_data.append({
'opts': self.opts,
'name': name,
'alias': alias,
'driver': driver,
})
# destroying in parallel
if self.opts['parallel'] and len(parallel_data) > 0:
# set the pool size based on configuration or default to
# the number of machines we're destroying
if 'pool_size' in self.opts:
pool_size = self.opts['pool_size']
else:
pool_size = len(parallel_data)
log.info(
six.u('Destroying in parallel mode; '
'Cloud pool size: {0}').format(pool_size)
)
# kick off the parallel destroy
output_multip = enter_mainloop(
_destroy_multiprocessing, parallel_data, pool_size=pool_size)
# massage the multiprocessing output a bit
ret_multip = {}