/
_compute.py
1784 lines (1489 loc) · 70.4 KB
/
_compute.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
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# import types so that we can reference ListType in sphinx param declarations.
# We can't just use list, because sphinx gets confused by
# openstack.resource.Resource.list and openstack.resource2.Resource.list
import base64
import datetime
import functools
import operator
import threading
import time
import types # noqa
import iso8601
from openstack.cloud import _normalize
from openstack.cloud import _utils
from openstack.cloud import exc
from openstack.cloud import meta
from openstack import exceptions
from openstack import proxy
from openstack import utils
class ComputeCloudMixin(_normalize.Normalizer):
def __init__(self):
self._servers = None
self._servers_time = 0
self._servers_lock = threading.Lock()
@property
def _compute_region(self):
# This is only used in exception messages. Can we get rid of it?
return self.config.get_region_name('compute')
def get_flavor_name(self, flavor_id):
flavor = self.get_flavor(flavor_id, get_extra=False)
if flavor:
return flavor['name']
return None
def get_flavor_by_ram(self, ram, include=None, get_extra=True):
"""Get a flavor based on amount of RAM available.
Finds the flavor with the least amount of RAM that is at least
as much as the specified amount. If `include` is given, further
filter based on matching flavor name.
:param int ram: Minimum amount of RAM.
:param string include: If given, will return a flavor whose name
contains this string as a substring.
"""
flavors = self.list_flavors(get_extra=get_extra)
for flavor in sorted(flavors, key=operator.itemgetter('ram')):
if (flavor['ram'] >= ram
and (not include or include in flavor['name'])):
return flavor
raise exc.OpenStackCloudException(
"Could not find a flavor with {ram} and '{include}'".format(
ram=ram, include=include))
@_utils.cache_on_arguments()
def _nova_extensions(self):
extensions = set()
data = proxy._json_response(
self.compute.get('/extensions'),
error_message="Error fetching extension list for nova")
for extension in self._get_and_munchify('extensions', data):
extensions.add(extension['alias'])
return extensions
def _has_nova_extension(self, extension_name):
return extension_name in self._nova_extensions()
def search_keypairs(self, name_or_id=None, filters=None):
keypairs = self.list_keypairs(
filters=filters if isinstance(filters, dict) else None
)
return _utils._filter_list(keypairs, name_or_id, filters)
def search_flavors(self, name_or_id=None, filters=None, get_extra=True):
flavors = self.list_flavors(get_extra=get_extra)
return _utils._filter_list(flavors, name_or_id, filters)
def search_servers(
self, name_or_id=None, filters=None, detailed=False,
all_projects=False, bare=False):
servers = self.list_servers(
detailed=detailed, all_projects=all_projects, bare=bare)
return _utils._filter_list(servers, name_or_id, filters)
def search_server_groups(self, name_or_id=None, filters=None):
"""Seach server groups.
:param name: server group name or ID.
:param filters: a dict containing additional filters to use.
:returns: a list of dicts containing the server groups
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
server_groups = self.list_server_groups()
return _utils._filter_list(server_groups, name_or_id, filters)
def list_keypairs(self, filters=None):
"""List all available keypairs.
:returns: A list of ``munch.Munch`` containing keypair info.
"""
if not filters:
filters = {}
return list(self.compute.keypairs(allow_unknown_params=True,
**filters))
@_utils.cache_on_arguments()
def list_availability_zone_names(self, unavailable=False):
"""List names of availability zones.
:param bool unavailable: Whether or not to include unavailable zones
in the output. Defaults to False.
:returns: A list of availability zone names, or an empty list if the
list could not be fetched.
"""
try:
zones = self.compute.availability_zones()
ret = []
for zone in zones:
if zone.state['available'] or unavailable:
ret.append(zone.name)
return ret
except exceptions.SDKException:
self.log.debug(
"Availability zone list could not be fetched",
exc_info=True)
return []
@_utils.cache_on_arguments()
def list_flavors(self, get_extra=False):
"""List all available flavors.
:param get_extra: Whether or not to fetch extra specs for each flavor.
Defaults to True. Default behavior value can be
overridden in clouds.yaml by setting
openstack.cloud.get_extra_specs to False.
:returns: A list of flavor ``munch.Munch``.
"""
data = self.compute.flavors(details=True)
flavors = []
for flavor in data:
if not flavor.extra_specs and get_extra:
flavor.fetch_extra_specs(self.compute)
flavors.append(flavor._to_munch(original_names=False))
return flavors
def list_server_security_groups(self, server):
"""List all security groups associated with the given server.
:returns: A list of security group ``munch.Munch``.
"""
# Don't even try if we're a cloud that doesn't have them
if not self._has_secgroups():
return []
server = self.compute.get_server(server)
server.fetch_security_groups(self.compute)
return self._normalize_secgroups(server.security_groups)
def _get_server_security_groups(self, server, security_groups):
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
if not isinstance(server, dict):
server = self.get_server(server, bare=True)
if server is None:
self.log.debug('Server %s not found', server)
return None, None
if not isinstance(security_groups, (list, tuple)):
security_groups = [security_groups]
sec_group_objs = []
for sg in security_groups:
if not isinstance(sg, dict):
sg = self.get_security_group(sg)
if sg is None:
self.log.debug('Security group %s not found for adding',
sg)
return None, None
sec_group_objs.append(sg)
return server, sec_group_objs
def add_server_security_groups(self, server, security_groups):
"""Add security groups to a server.
Add existing security groups to an existing server. If the security
groups are already present on the server this will continue unaffected.
:returns: False if server or security groups are undefined, True
otherwise.
:raises: ``OpenStackCloudException``, on operation error.
"""
server, security_groups = self._get_server_security_groups(
server, security_groups)
if not (server and security_groups):
return False
for sg in security_groups:
self.compute.add_security_group_to_server(server, sg)
return True
def remove_server_security_groups(self, server, security_groups):
"""Remove security groups from a server
Remove existing security groups from an existing server. If the
security groups are not present on the server this will continue
unaffected.
:returns: False if server or security groups are undefined, True
otherwise.
:raises: ``OpenStackCloudException``, on operation error.
"""
server, security_groups = self._get_server_security_groups(
server, security_groups)
if not (server and security_groups):
return False
ret = True
for sg in security_groups:
try:
self.compute.remove_security_group_from_server(server, sg)
except exceptions.ResourceNotFound:
# NOTE(jamielennox): Is this ok? If we remove something that
# isn't present should we just conclude job done or is that an
# error? Nova returns ok if you try to add a group twice.
self.log.debug(
"The security group %s was not present on server %s so "
"no action was performed", sg.name, server.name)
ret = False
return ret
def list_servers(self, detailed=False, all_projects=False, bare=False,
filters=None):
"""List all available servers.
:param detailed: Whether or not to add detailed additional information.
Defaults to False.
:param all_projects: Whether to list servers from all projects or just
the current auth scoped project.
:param bare: Whether to skip adding any additional information to the
server record. Defaults to False, meaning the addresses
dict will be populated as needed from neutron. Setting
to True implies detailed = False.
:param filters: Additional query parameters passed to the API server.
:returns: A list of server ``munch.Munch``.
"""
# If pushdown filters are specified and we do not have batched caching
# enabled, bypass local caching and push down the filters.
if filters and self._SERVER_AGE == 0:
return self._list_servers(
detailed=detailed,
all_projects=all_projects,
bare=bare,
filters=filters,
)
if (time.time() - self._servers_time) >= self._SERVER_AGE:
# Since we're using cached data anyway, we don't need to
# have more than one thread actually submit the list
# servers task. Let the first one submit it while holding
# a lock, and the non-blocking acquire method will cause
# subsequent threads to just skip this and use the old
# data until it succeeds.
# Initially when we never got data, block to retrieve some data.
first_run = self._servers is None
if self._servers_lock.acquire(first_run):
try:
if not (first_run and self._servers is not None):
self._servers = self._list_servers(
detailed=detailed,
all_projects=all_projects,
bare=bare)
self._servers_time = time.time()
finally:
self._servers_lock.release()
# Wrap the return with filter_list so that if filters were passed
# but we were batching/caching and thus always fetching the whole
# list from the cloud, we still return a filtered list.
return _utils._filter_list(self._servers, None, filters)
def _list_servers(self, detailed=False, all_projects=False, bare=False,
filters=None):
filters = filters or {}
servers = [
# TODO(mordred) Add original_names=False here and update the
# normalize file for server. Then, just remove the normalize call
# and the to_munch call.
self._normalize_server(server._to_munch())
for server in self.compute.servers(
all_projects=all_projects, allow_unknown_params=True,
**filters)]
return [
self._expand_server(server, detailed, bare)
for server in servers
]
def list_server_groups(self):
"""List all available server groups.
:returns: A list of server group dicts.
"""
return list(self.compute.server_groups())
def get_compute_limits(self, name_or_id=None):
""" Get compute limits for a project
:param name_or_id: (optional) project name or ID to get limits for
if different from the current project
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the limits
"""
params = {}
project_id = None
error_msg = "Failed to get limits"
if name_or_id:
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
project_id = proj.id
params['tenant_id'] = project_id
error_msg = "{msg} for the project: {project} ".format(
msg=error_msg, project=name_or_id)
data = proxy._json_response(
self.compute.get('/limits', params=params))
limits = self._get_and_munchify('limits', data)
return self._normalize_compute_limits(limits, project_id=project_id)
def get_keypair(self, name_or_id, filters=None):
"""Get a keypair by name or ID.
:param name_or_id: Name or ID of the keypair.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A keypair ``munch.Munch`` or None if no matching keypair is
found.
"""
return _utils._get_entity(self, 'keypair', name_or_id, filters)
def get_flavor(self, name_or_id, filters=None, get_extra=True):
"""Get a flavor by name or ID.
:param name_or_id: Name or ID of the flavor.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param get_extra:
Whether or not the list_flavors call should get the extra flavor
specs.
:returns: A flavor ``munch.Munch`` or None if no matching flavor is
found.
"""
if not filters:
filters = {}
flavor = self.compute.find_flavor(
name_or_id, get_extra_specs=get_extra, **filters)
if flavor:
return flavor._to_munch(original_names=False)
def get_flavor_by_id(self, id, get_extra=False):
""" Get a flavor by ID
:param id: ID of the flavor.
:param get_extra:
Whether or not the list_flavors call should get the extra flavor
specs.
:returns: A flavor ``munch.Munch``.
"""
flavor = self.compute.get_flavor(id, get_extra_specs=get_extra)
return flavor._to_munch(original_names=False)
def get_server_console(self, server, length=None):
"""Get the console log for a server.
:param server: The server to fetch the console log for. Can be either
a server dict or the Name or ID of the server.
:param int length: The number of lines you would like to retrieve from
the end of the log. (optional, defaults to all)
:returns: A string containing the text of the console log or an
empty string if the cloud does not support console logs.
:raises: OpenStackCloudException if an invalid server argument is given
or if something else unforseen happens
"""
if not isinstance(server, dict):
server = self.get_server(server, bare=True)
if not server:
raise exc.OpenStackCloudException(
"Console log requested for invalid server")
try:
return self._get_server_console_output(server['id'], length)
except exc.OpenStackCloudBadRequest:
return ""
def _get_server_console_output(self, server_id, length=None):
output = self.compute.get_server_console_output(
server=server_id,
length=length
)
if 'output' in output:
return output['output']
def get_server(
self, name_or_id=None, filters=None, detailed=False, bare=False,
all_projects=False):
"""Get a server by name or ID.
:param name_or_id: Name or ID of the server.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param detailed: Whether or not to add detailed additional information.
Defaults to False.
:param bare: Whether to skip adding any additional information to the
server record. Defaults to False, meaning the addresses
dict will be populated as needed from neutron. Setting
to True implies detailed = False.
:param all_projects: Whether to get server from all projects or just
the current auth scoped project.
:returns: A server ``munch.Munch`` or None if no matching server is
found.
"""
searchfunc = functools.partial(self.search_servers,
detailed=detailed, bare=True,
all_projects=all_projects)
server = _utils._get_entity(self, searchfunc, name_or_id, filters)
return self._expand_server(server, detailed, bare)
def _expand_server(self, server, detailed, bare):
if bare or not server:
return server
elif detailed:
return meta.get_hostvars_from_server(self, server)
else:
return meta.add_server_interfaces(self, server)
def get_server_by_id(self, id):
"""Get a server by ID.
:param id: ID of the server.
:returns: A server dict or None if no matching server is found.
"""
try:
data = proxy._json_response(
self.compute.get('/servers/{id}'.format(id=id)))
server = self._get_and_munchify('server', data)
return meta.add_server_interfaces(
self, self._normalize_server(server))
except exceptions.ResourceNotFound:
return None
def get_server_group(self, name_or_id=None, filters=None):
"""Get a server group by name or ID.
:param name_or_id: Name or ID of the server group.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'policy': 'affinity',
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A server groups dict or None if no matching server group
is found.
"""
return _utils._get_entity(self, 'server_group', name_or_id,
filters)
def create_keypair(self, name, public_key=None):
"""Create a new keypair.
:param name: Name of the keypair being created.
:param public_key: Public key for the new keypair.
:raises: OpenStackCloudException on operation error.
"""
keypair = {
'name': name,
}
if public_key:
keypair['public_key'] = public_key
return self.compute.create_keypair(**keypair)
def delete_keypair(self, name):
"""Delete a keypair.
:param name: Name of the keypair to delete.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
try:
self.compute.delete_keypair(name, ignore_missing=False)
except exceptions.ResourceNotFound:
self.log.debug("Keypair %s not found for deleting", name)
return False
return True
def create_image_snapshot(
self, name, server, wait=False, timeout=3600, **metadata):
"""Create an image by snapshotting an existing server.
..note::
On most clouds this is a cold snapshot - meaning that the server
in question will be shutdown before taking the snapshot. It is
possible that it's a live snapshot - but there is no way to know
as a user, so caveat emptor.
:param name: Name of the image to be created
:param server: Server name or ID or dict representing the server
to be snapshotted
:param wait: If true, waits for image to be created.
:param timeout: Seconds to wait for image creation. None is forever.
:param metadata: Metadata to give newly-created image entity
:returns: A ``munch.Munch`` of the Image object
:raises: OpenStackCloudException if there are problems uploading
"""
if not isinstance(server, dict):
server_obj = self.get_server(server, bare=True)
if not server_obj:
raise exc.OpenStackCloudException(
"Server {server} could not be found and therefore"
" could not be snapshotted.".format(server=server))
server = server_obj
image = self.compute.create_server_image(
server, name=name, metadata=metadata, wait=wait, timeout=timeout)
return image
def get_server_id(self, name_or_id):
server = self.get_server(name_or_id, bare=True)
if server:
return server['id']
return None
def get_server_private_ip(self, server):
return meta.get_server_private_ip(server, self)
def get_server_public_ip(self, server):
return meta.get_server_external_ipv4(self, server)
def get_server_meta(self, server):
# TODO(mordred) remove once ansible has moved to Inventory interface
server_vars = meta.get_hostvars_from_server(self, server)
groups = meta.get_groups_from_server(self, server, server_vars)
return dict(server_vars=server_vars, groups=groups)
@_utils.valid_kwargs(
'meta', 'files', 'userdata',
'reservation_id', 'return_raw', 'min_count',
'max_count', 'security_groups', 'key_name',
'availability_zone', 'block_device_mapping',
'block_device_mapping_v2', 'nics', 'scheduler_hints',
'config_drive', 'admin_pass', 'disk_config')
def create_server(
self, name, image=None, flavor=None,
auto_ip=True, ips=None, ip_pool=None,
root_volume=None, terminate_volume=False,
wait=False, timeout=180, reuse_ips=True,
network=None, boot_from_volume=False, volume_size='50',
boot_volume=None, volumes=None, nat_destination=None,
group=None,
**kwargs):
"""Create a virtual server instance.
:param name: Something to name the server.
:param image: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
:param flavor: Flavor dict, name or ID to boot onto.
:param auto_ip: Whether to take actions to find a routable IP for
the server. (defaults to True)
:param ips: List of IPs to attach to the server (defaults to None)
:param ip_pool: Name of the network or floating IP pool to get an
address from. (defaults to None)
:param root_volume: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
:param boot_volume: Name or ID of a volume to boot from
(defaults to None)
:param terminate_volume: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
:param volumes: (optional) A list of volumes to attach to the server
:param meta: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
:param files: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
:param reservation_id: a UUID for the set of servers being requested.
:param min_count: (optional extension) The minimum number of
servers to launch.
:param max_count: (optional extension) The maximum number of
servers to launch.
:param security_groups: A list of security group names
:param userdata: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
:param key_name: (optional extension) name of previously created
keypair to inject into the instance.
:param availability_zone: Name of the availability zone for instance
placement.
:param block_device_mapping: (optional) A dict of block
device mappings for this server.
:param block_device_mapping_v2: (optional) A dict of block
device mappings for this server.
:param nics: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
:param scheduler_hints: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
:param config_drive: (optional extension) value for config drive
either boolean, or volume-id
:param disk_config: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
:param admin_pass: (optional extension) add a user supplied admin
password.
:param wait: (optional) Wait for the address to appear as assigned
to the server. Defaults to False.
:param timeout: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
:param reuse_ips: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
:param network: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be a list of network names or IDs or
network dicts.
:param boot_from_volume: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
:param volume_size: When booting an image from volume, how big should
the created volume be? Defaults to 50.
:param nat_destination: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
:param group: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
:returns: A ``munch.Munch`` representing the created server.
:raises: OpenStackCloudException on operation error.
"""
# TODO(shade) Image is optional but flavor is not - yet flavor comes
# after image in the argument list. Doh.
if not flavor:
raise TypeError(
"create_server() missing 1 required argument: 'flavor'")
if not image and not boot_volume:
raise TypeError(
"create_server() requires either 'image' or 'boot_volume'")
microversion = None
server_json = {'server': kwargs}
# TODO(mordred) Add support for description starting in 2.19
security_groups = kwargs.get('security_groups', [])
if security_groups and not isinstance(kwargs['security_groups'], list):
security_groups = [security_groups]
if security_groups:
kwargs['security_groups'] = []
for sec_group in security_groups:
kwargs['security_groups'].append(dict(name=sec_group))
if 'userdata' in kwargs:
user_data = kwargs.pop('userdata')
if user_data:
kwargs['user_data'] = self._encode_server_userdata(user_data)
for (desired, given) in (
('OS-DCF:diskConfig', 'disk_config'),
('config_drive', 'config_drive'),
('key_name', 'key_name'),
('metadata', 'meta'),
('adminPass', 'admin_pass')):
value = kwargs.pop(given, None)
if value:
kwargs[desired] = value
hints = kwargs.pop('scheduler_hints', {})
if group:
group_obj = self.get_server_group(group)
if not group_obj:
raise exc.OpenStackCloudException(
"Server Group {group} was requested but was not found"
" on the cloud".format(group=group))
hints['group'] = group_obj['id']
if hints:
server_json['os:scheduler_hints'] = hints
kwargs.setdefault('max_count', kwargs.get('max_count', 1))
kwargs.setdefault('min_count', kwargs.get('min_count', 1))
if 'nics' in kwargs and not isinstance(kwargs['nics'], list):
if isinstance(kwargs['nics'], dict):
# Be nice and help the user out
kwargs['nics'] = [kwargs['nics']]
else:
raise exc.OpenStackCloudException(
'nics parameter to create_server takes a list of dicts.'
' Got: {nics}'.format(nics=kwargs['nics']))
if network and ('nics' not in kwargs or not kwargs['nics']):
nics = []
if not isinstance(network, list):
network = [network]
for net_name in network:
if isinstance(net_name, dict) and 'id' in net_name:
network_obj = net_name
else:
network_obj = self.get_network(name_or_id=net_name)
if not network_obj:
raise exc.OpenStackCloudException(
'Network {network} is not a valid network in'
' {cloud}:{region}'.format(
network=network,
cloud=self.name, region=self._compute_region))
nics.append({'net-id': network_obj['id']})
kwargs['nics'] = nics
if not network and ('nics' not in kwargs or not kwargs['nics']):
default_network = self.get_default_network()
if default_network:
kwargs['nics'] = [{'net-id': default_network['id']}]
networks = []
for nic in kwargs.pop('nics', []):
net = {}
if 'net-id' in nic:
# TODO(mordred) Make sure this is in uuid format
net['uuid'] = nic.pop('net-id')
# If there's a net-id, ignore net-name
nic.pop('net-name', None)
elif 'net-name' in nic:
net_name = nic.pop('net-name')
nic_net = self.get_network(net_name)
if not nic_net:
raise exc.OpenStackCloudException(
"Requested network {net} could not be found.".format(
net=net_name))
net['uuid'] = nic_net['id']
for ip_key in ('v4-fixed-ip', 'v6-fixed-ip', 'fixed_ip'):
fixed_ip = nic.pop(ip_key, None)
if fixed_ip and net.get('fixed_ip'):
raise exc.OpenStackCloudException(
"Only one of v4-fixed-ip, v6-fixed-ip or fixed_ip"
" may be given")
if fixed_ip:
net['fixed_ip'] = fixed_ip
for key in ('port', 'port-id'):
if key in nic:
net['port'] = nic.pop(key)
# A tag supported only in server microversion 2.32-2.36 or >= 2.42
# Bumping the version to 2.42 to support the 'tag' implementation
if 'tag' in nic:
microversion = utils.pick_microversion(self.compute, '2.42')
net['tag'] = nic.pop('tag')
if nic:
raise exc.OpenStackCloudException(
"Additional unsupported keys given for server network"
" creation: {keys}".format(keys=nic.keys()))
networks.append(net)
if networks:
kwargs['networks'] = networks
if image:
if isinstance(image, dict):
kwargs['imageRef'] = image['id']
else:
kwargs['imageRef'] = self.get_image(image).id
if isinstance(flavor, dict):
kwargs['flavorRef'] = flavor['id']
else:
kwargs['flavorRef'] = self.get_flavor(flavor, get_extra=False).id
if volumes is None:
volumes = []
# nova cli calls this boot_volume. Let's be the same
if root_volume and not boot_volume:
boot_volume = root_volume
kwargs = self._get_boot_from_volume_kwargs(
image=image, boot_from_volume=boot_from_volume,
boot_volume=boot_volume, volume_size=str(volume_size),
terminate_volume=terminate_volume,
volumes=volumes, kwargs=kwargs)
kwargs['name'] = name
endpoint = '/servers'
# TODO(mordred) We're only testing this in functional tests. We need
# to add unit tests for this too.
if 'block_device_mapping_v2' in kwargs:
endpoint = '/os-volumes_boot'
with _utils.shade_exceptions("Error in creating instance"):
data = proxy._json_response(
self.compute.post(endpoint, json=server_json,
microversion=microversion))
server = self._get_and_munchify('server', data)
admin_pass = server.get('adminPass') or kwargs.get('admin_pass')
if not wait:
# This is a direct get call to skip the list_servers
# cache which has absolutely no chance of containing the
# new server.
# Only do this if we're not going to wait for the server
# to complete booting, because the only reason we do it
# is to get a server record that is the return value from
# get/list rather than the return value of create. If we're
# going to do the wait loop below, this is a waste of a call
server = self.get_server_by_id(server.id)
if server.status == 'ERROR':
raise exc.OpenStackCloudCreateException(
resource='server', resource_id=server.id)
if wait:
server = self.wait_for_server(
server,
auto_ip=auto_ip, ips=ips, ip_pool=ip_pool,
reuse=reuse_ips, timeout=timeout,
nat_destination=nat_destination,
)
server.adminPass = admin_pass
return server
def _get_boot_from_volume_kwargs(
self, image, boot_from_volume, boot_volume, volume_size,
terminate_volume, volumes, kwargs):
"""Return block device mappings
:param image: Image dict, name or id to boot with.
"""
# TODO(mordred) We're only testing this in functional tests. We need
# to add unit tests for this too.
if boot_volume or boot_from_volume or volumes:
kwargs.setdefault('block_device_mapping_v2', [])
else:
return kwargs
# If we have boot_from_volume but no root volume, then we're
# booting an image from volume
if boot_volume:
volume = self.get_volume(boot_volume)
if not volume:
raise exc.OpenStackCloudException(
'Volume {boot_volume} is not a valid volume'
' in {cloud}:{region}'.format(
boot_volume=boot_volume,
cloud=self.name, region=self._compute_region))
block_mapping = {
'boot_index': '0',
'delete_on_termination': terminate_volume,
'destination_type': 'volume',
'uuid': volume['id'],
'source_type': 'volume',
}
kwargs['block_device_mapping_v2'].append(block_mapping)
kwargs['imageRef'] = ''
elif boot_from_volume:
if isinstance(image, dict):
image_obj = image
else:
image_obj = self.get_image(image)
if not image_obj:
raise exc.OpenStackCloudException(
'Image {image} is not a valid image in'
' {cloud}:{region}'.format(
image=image,
cloud=self.name, region=self._compute_region))
block_mapping = {
'boot_index': '0',
'delete_on_termination': terminate_volume,
'destination_type': 'volume',
'uuid': image_obj['id'],
'source_type': 'image',
'volume_size': volume_size,
}
kwargs['imageRef'] = ''
kwargs['block_device_mapping_v2'].append(block_mapping)
if volumes and kwargs['imageRef']:
# If we're attaching volumes on boot but booting from an image,
# we need to specify that in the BDM.
block_mapping = {
u'boot_index': 0,
u'delete_on_termination': True,
u'destination_type': u'local',
u'source_type': u'image',
u'uuid': kwargs['imageRef'],
}
kwargs['block_device_mapping_v2'].append(block_mapping)
for volume in volumes:
volume_obj = self.get_volume(volume)
if not volume_obj:
raise exc.OpenStackCloudException(