/
api.py
1836 lines (1544 loc) · 76.3 KB
/
api.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
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Piston Cloud Computing, Inc.
# All Rights Reserved.
#
# 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.
"""Handles all requests relating to compute resources (e.g. guest vms,
networking and storage of vms, and compute hosts on which they run)."""
import functools
import re
import time
import novaclient
import webob.exc
from nova import block_device
from nova.compute import aggregate_states
from nova.compute import instance_types
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import vm_states
from nova.db import base
from nova import exception
from nova import flags
import nova.image
from nova import log as logging
from nova import network
from nova.openstack.common import cfg
import nova.policy
from nova import quota
from nova import rpc
from nova.scheduler import api as scheduler_api
from nova import utils
from nova import volume
LOG = logging.getLogger(__name__)
find_host_timeout_opt = cfg.StrOpt('find_host_timeout',
default=30,
help='Timeout after NN seconds when looking for a host.')
FLAGS = flags.FLAGS
FLAGS.register_opt(find_host_timeout_opt)
flags.DECLARE('consoleauth_topic', 'nova.consoleauth')
def check_instance_state(vm_state=None, task_state=None):
"""Decorator to check VM and/or task state before entry to API functions.
If the instance is in the wrong state, the wrapper will raise an exception.
"""
if vm_state is not None and not isinstance(vm_state, set):
vm_state = set(vm_state)
if task_state is not None and not isinstance(task_state, set):
task_state = set(task_state)
def outer(f):
@functools.wraps(f)
def inner(self, context, instance, *args, **kw):
if vm_state is not None and instance['vm_state'] not in vm_state:
raise exception.InstanceInvalidState(
attr='vm_state',
instance_uuid=instance['uuid'],
state=instance['vm_state'],
method=f.__name__)
if (task_state is not None and
instance['task_state'] not in task_state):
raise exception.InstanceInvalidState(
attr='task_state',
instance_uuid=instance['uuid'],
state=instance['task_state'],
method=f.__name__)
return f(self, context, instance, *args, **kw)
return inner
return outer
def wrap_check_policy(func):
"""Check corresponding policy prior of wrapped method to execution"""
@functools.wraps(func)
def wrapped(self, context, target, *args, **kwargs):
check_policy(context, func.__name__, target)
return func(self, context, target, *args, **kwargs)
return wrapped
def check_policy(context, action, target):
_action = 'compute:%s' % action
nova.policy.enforce(context, _action, target)
class API(base.Base):
"""API for interacting with the compute manager."""
def __init__(self, image_service=None, network_api=None, volume_api=None,
**kwargs):
self.image_service = (image_service or
nova.image.get_default_image_service())
self.network_api = network_api or network.API()
self.volume_api = volume_api or volume.API()
super(API, self).__init__(**kwargs)
def _cast_or_call_compute_message(self, rpc_method, compute_method,
context, instance=None, host=None, params=None):
"""Generic handler for RPC casts and calls to compute.
:param rpc_method: RPC method to use (rpc.call or rpc.cast)
:param compute_method: Compute manager method to call
:param context: RequestContext of caller
:param instance: The instance object to use to find host to send to
Can be None to not include instance_uuid in args
:param host: Optional host to send to instead of instance['host']
Must be specified if 'instance' is None
:param params: Optional dictionary of arguments to be passed to the
compute worker
:returns: None
"""
if not params:
params = {}
if not host:
if not instance:
raise exception.Error(_("No compute host specified"))
host = instance['host']
if not host:
raise exception.Error(_("Unable to find host for "
"Instance %s") % instance['uuid'])
queue = self.db.queue_get_for(context, FLAGS.compute_topic, host)
if instance:
params['instance_uuid'] = instance['uuid']
kwargs = {'method': compute_method, 'args': params}
return rpc_method(context, queue, kwargs)
def _cast_compute_message(self, *args, **kwargs):
"""Generic handler for RPC casts to compute."""
self._cast_or_call_compute_message(rpc.cast, *args, **kwargs)
def _call_compute_message(self, *args, **kwargs):
"""Generic handler for RPC calls to compute."""
return self._cast_or_call_compute_message(rpc.call, *args, **kwargs)
def _cast_scheduler_message(self, context, args):
"""Generic handler for RPC calls to the scheduler."""
rpc.cast(context, FLAGS.scheduler_topic, args)
def _check_injected_file_quota(self, context, injected_files):
"""Enforce quota limits on injected files.
Raises a QuotaError if any limit is exceeded.
"""
if injected_files is None:
return
limit = quota.allowed_injected_files(context, len(injected_files))
if len(injected_files) > limit:
raise exception.QuotaError(code="OnsetFileLimitExceeded")
path_limit = quota.allowed_injected_file_path_bytes(context)
for path, content in injected_files:
if len(path) > path_limit:
raise exception.QuotaError(code="OnsetFilePathLimitExceeded")
content_limit = quota.allowed_injected_file_content_bytes(
context, len(content))
if len(content) > content_limit:
code = "OnsetFileContentLimitExceeded"
raise exception.QuotaError(code=code)
def _check_metadata_properties_quota(self, context, metadata=None):
"""Enforce quota limits on metadata properties."""
if not metadata:
metadata = {}
num_metadata = len(metadata)
quota_metadata = quota.allowed_metadata_items(context, num_metadata)
if quota_metadata < num_metadata:
pid = context.project_id
msg = _("Quota exceeded for %(pid)s, tried to set "
"%(num_metadata)s metadata properties") % locals()
LOG.warn(msg)
raise exception.QuotaError(code="MetadataLimitExceeded")
# Because metadata is stored in the DB, we hard-code the size limits
# In future, we may support more variable length strings, so we act
# as if this is quota-controlled for forwards compatibility
for k, v in metadata.iteritems():
if len(k) > 255 or len(v) > 255:
pid = context.project_id
msg = _("Quota exceeded for %(pid)s, metadata property "
"key or value too long") % locals()
LOG.warn(msg)
raise exception.QuotaError(code="MetadataLimitExceeded")
def _check_requested_networks(self, context, requested_networks):
""" Check if the networks requested belongs to the project
and the fixed IP address for each network provided is within
same the network block
"""
if requested_networks is None:
return
self.network_api.validate_networks(context, requested_networks)
def _create_instance(self, context, instance_type,
image_href, kernel_id, ramdisk_id,
min_count, max_count,
display_name, display_description,
key_name, key_data, security_group,
availability_zone, user_data, metadata,
injected_files, admin_password,
access_ip_v4, access_ip_v6,
requested_networks, config_drive,
block_device_mapping, auto_disk_config,
reservation_id=None, create_instance_here=False,
scheduler_hints=None):
"""Verify all the input parameters regardless of the provisioning
strategy being performed and schedule the instance(s) for
creation."""
if not metadata:
metadata = {}
if not display_description:
display_description = ''
if not security_group:
security_group = 'default'
if not instance_type:
instance_type = instance_types.get_default_instance_type()
if not min_count:
min_count = 1
if not max_count:
max_count = min_count
if not metadata:
metadata = {}
block_device_mapping = block_device_mapping or []
num_instances = quota.allowed_instances(context, max_count,
instance_type)
if num_instances < min_count:
pid = context.project_id
if num_instances <= 0:
msg = _("Cannot run any more instances of this type.")
else:
msg = (_("Can only run %s more instances of this type.") %
num_instances)
LOG.warn(_("Quota exceeded for %(pid)s,"
" tried to run %(min_count)s instances. " + msg) % locals())
raise exception.QuotaError(code="InstanceLimitExceeded")
self._check_metadata_properties_quota(context, metadata)
self._check_injected_file_quota(context, injected_files)
self._check_requested_networks(context, requested_networks)
(image_service, image_id) = nova.image.get_image_service(context,
image_href)
image = image_service.show(context, image_id)
if instance_type['memory_mb'] < int(image.get('min_ram') or 0):
raise exception.InstanceTypeMemoryTooSmall()
if instance_type['root_gb'] < int(image.get('min_disk') or 0):
raise exception.InstanceTypeDiskTooSmall()
config_drive_id = None
if config_drive and config_drive is not True:
# config_drive is volume id
config_drive, config_drive_id = None, config_drive
os_type = None
if 'properties' in image and 'os_type' in image['properties']:
os_type = image['properties']['os_type']
architecture = None
if 'properties' in image and 'arch' in image['properties']:
architecture = image['properties']['arch']
vm_mode = None
if 'properties' in image and 'vm_mode' in image['properties']:
vm_mode = image['properties']['vm_mode']
# If instance doesn't have auto_disk_config overridden by request, use
# whatever the image indicates
if auto_disk_config is None:
if ('properties' in image and
'auto_disk_config' in image['properties']):
auto_disk_config = utils.bool_from_str(
image['properties']['auto_disk_config'])
if kernel_id is None:
kernel_id = image['properties'].get('kernel_id', None)
if ramdisk_id is None:
ramdisk_id = image['properties'].get('ramdisk_id', None)
# FIXME(sirp): is there a way we can remove null_kernel?
# No kernel and ramdisk for raw images
if kernel_id == str(FLAGS.null_kernel):
kernel_id = None
ramdisk_id = None
LOG.debug(_("Creating a raw instance"))
# Make sure we have access to kernel and ramdisk (if not raw)
LOG.debug(_("Using Kernel=%(kernel_id)s, Ramdisk=%(ramdisk_id)s")
% locals())
if kernel_id:
image_service.show(context, kernel_id)
if ramdisk_id:
image_service.show(context, ramdisk_id)
if config_drive_id:
image_service.show(context, config_drive_id)
self.ensure_default_security_group(context)
if key_data is None and key_name:
key_pair = self.db.key_pair_get(context, context.user_id, key_name)
key_data = key_pair['public_key']
if reservation_id is None:
reservation_id = utils.generate_uid('r')
root_device_name = block_device.properties_root_device_name(
image['properties'])
# NOTE(vish): We have a legacy hack to allow admins to specify hosts
# via az using az:host. It might be nice to expose an
# api to specify specific hosts to force onto, but for
# now it just supports this legacy hack.
host = None
if availability_zone:
availability_zone, _x, host = availability_zone.partition(':')
if not availability_zone:
availability_zone = FLAGS.default_schedule_zone
if context.is_admin and host:
filter_properties = {'force_hosts': [host]}
else:
filter_properties = {}
filter_properties['scheduler_hints'] = scheduler_hints
base_options = {
'reservation_id': reservation_id,
'image_ref': image_href,
'kernel_id': kernel_id or '',
'ramdisk_id': ramdisk_id or '',
'power_state': power_state.NOSTATE,
'vm_state': vm_states.BUILDING,
'config_drive_id': config_drive_id or '',
'config_drive': config_drive or '',
'user_id': context.user_id,
'project_id': context.project_id,
'launch_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
'instance_type_id': instance_type['id'],
'memory_mb': instance_type['memory_mb'],
'vcpus': instance_type['vcpus'],
'root_gb': instance_type['root_gb'],
'ephemeral_gb': instance_type['ephemeral_gb'],
'display_name': display_name,
'display_description': display_description,
'user_data': user_data or '',
'key_name': key_name,
'key_data': key_data,
'locked': False,
'metadata': metadata,
'access_ip_v4': access_ip_v4,
'access_ip_v6': access_ip_v6,
'availability_zone': availability_zone,
'os_type': os_type,
'architecture': architecture,
'vm_mode': vm_mode,
'root_device_name': root_device_name,
'progress': 0,
'auto_disk_config': auto_disk_config}
LOG.debug(_("Going to run %s instances...") % num_instances)
if create_instance_here:
instance = self.create_db_entry_for_new_instance(
context, instance_type, image, base_options,
security_group, block_device_mapping)
# Tells scheduler we created the instance already.
base_options['uuid'] = instance['uuid']
rpc_method = rpc.cast
else:
# We need to wait for the scheduler to create the instance
# DB entries, because the instance *could* be # created in
# a child zone.
rpc_method = rpc.call
# TODO(comstud): We should use rpc.multicall when we can
# retrieve the full instance dictionary from the scheduler.
# Otherwise, we could exceed the AMQP max message size limit.
# This would require the schedulers' schedule_run_instances
# methods to return an iterator vs a list.
instances = self._schedule_run_instance(
rpc_method,
context, base_options,
instance_type,
availability_zone, injected_files,
admin_password, image,
num_instances, requested_networks,
block_device_mapping, security_group,
filter_properties)
if create_instance_here:
return ([instance], reservation_id)
return (instances, reservation_id)
@staticmethod
def _volume_size(instance_type, virtual_name):
size = 0
if virtual_name == 'swap':
size = instance_type.get('swap', 0)
elif block_device.is_ephemeral(virtual_name):
num = block_device.ephemeral_num(virtual_name)
# TODO(yamahata): ephemeralN where N > 0
# Only ephemeral0 is allowed for now because InstanceTypes
# table only allows single local disk, ephemeral_gb.
# In order to enhance it, we need to add a new columns to
# instance_types table.
if num > 0:
return 0
size = instance_type.get('ephemeral_gb')
return size
def _update_image_block_device_mapping(self, elevated_context,
instance_type, instance_id,
mappings):
"""tell vm driver to create ephemeral/swap device at boot time by
updating BlockDeviceMapping
"""
instance_type = (instance_type or
instance_types.get_default_instance_type())
for bdm in block_device.mappings_prepend_dev(mappings):
LOG.debug(_("bdm %s"), bdm)
virtual_name = bdm['virtual']
if virtual_name == 'ami' or virtual_name == 'root':
continue
if not block_device.is_swap_or_ephemeral(virtual_name):
continue
size = self._volume_size(instance_type, virtual_name)
if size == 0:
continue
values = {
'instance_id': instance_id,
'device_name': bdm['device'],
'virtual_name': virtual_name,
'volume_size': size}
self.db.block_device_mapping_update_or_create(elevated_context,
values)
def _update_block_device_mapping(self, elevated_context,
instance_type, instance_id,
block_device_mapping):
"""tell vm driver to attach volume at boot time by updating
BlockDeviceMapping
"""
LOG.debug(_("block_device_mapping %s"), block_device_mapping)
for bdm in block_device_mapping:
assert 'device_name' in bdm
values = {'instance_id': instance_id}
for key in ('device_name', 'delete_on_termination', 'virtual_name',
'snapshot_id', 'volume_id', 'volume_size',
'no_device'):
values[key] = bdm.get(key)
virtual_name = bdm.get('virtual_name')
if (virtual_name is not None and
block_device.is_swap_or_ephemeral(virtual_name)):
size = self._volume_size(instance_type, virtual_name)
if size == 0:
continue
values['volume_size'] = size
# NOTE(yamahata): NoDevice eliminates devices defined in image
# files by command line option.
# (--block-device-mapping)
if virtual_name == 'NoDevice':
values['no_device'] = True
for k in ('delete_on_termination', 'volume_id',
'snapshot_id', 'volume_id', 'volume_size',
'virtual_name'):
values[k] = None
self.db.block_device_mapping_update_or_create(elevated_context,
values)
#NOTE(bcwaldon): No policy check since this is only used by scheduler and
# the compute api. That should probably be cleaned up, though.
def create_db_entry_for_new_instance(self, context, instance_type, image,
base_options, security_group, block_device_mapping):
"""Create an entry in the DB for this new instance,
including any related table updates (such as security group,
etc).
This is called by the scheduler after a location for the
instance has been determined.
"""
elevated = context.elevated()
if security_group is None:
security_group = ['default']
if not isinstance(security_group, list):
security_group = [security_group]
security_groups = []
for security_group_name in security_group:
group = self.db.security_group_get_by_name(context,
context.project_id,
security_group_name)
security_groups.append(group['id'])
base_options.setdefault('launch_index', 0)
instance = self.db.instance_create(context, base_options)
instance_id = instance['id']
instance_uuid = instance['uuid']
for security_group_id in security_groups:
self.db.instance_add_security_group(elevated,
instance_uuid,
security_group_id)
# BlockDeviceMapping table
self._update_image_block_device_mapping(elevated, instance_type,
instance_id, image['properties'].get('mappings', []))
self._update_block_device_mapping(elevated, instance_type, instance_id,
image['properties'].get('block_device_mapping', []))
# override via command line option
self._update_block_device_mapping(elevated, instance_type, instance_id,
block_device_mapping)
# Set sane defaults if not specified
updates = {}
display_name = instance.get('display_name')
if display_name is None:
display_name = self._default_display_name(instance_id)
hostname = instance.get('hostname')
if hostname is None:
hostname = display_name
updates['display_name'] = display_name
updates['hostname'] = utils.sanitize_hostname(hostname)
updates['vm_state'] = vm_states.BUILDING
updates['task_state'] = task_states.SCHEDULING
if (image['properties'].get('mappings', []) or
image['properties'].get('block_device_mapping', []) or
block_device_mapping):
updates['shutdown_terminate'] = False
instance = self.update(context, instance, **updates)
return instance
def _default_display_name(self, instance_id):
return "Server %s" % instance_id
def _schedule_run_instance(self,
rpc_method,
context, base_options,
instance_type,
availability_zone, injected_files,
admin_password, image,
num_instances,
requested_networks,
block_device_mapping,
security_group,
filter_properties):
"""Send a run_instance request to the schedulers for processing."""
pid = context.project_id
uid = context.user_id
LOG.debug(_("Sending create to scheduler for %(pid)s/%(uid)s's") %
locals())
request_spec = {
'image': utils.to_primitive(image),
'instance_properties': base_options,
'instance_type': instance_type,
'num_instances': num_instances,
'block_device_mapping': block_device_mapping,
'security_group': security_group,
}
return rpc_method(context,
FLAGS.scheduler_topic,
{"method": "run_instance",
"args": {"topic": FLAGS.compute_topic,
"request_spec": request_spec,
"admin_password": admin_password,
"injected_files": injected_files,
"requested_networks": requested_networks,
"is_first_time": True,
"filter_properties": filter_properties}})
def _check_create_policies(self, context, availability_zone,
requested_networks, block_device_mapping):
"""Check policies for create()."""
target = {'project_id': context.project_id,
'user_id': context.user_id,
'availability_zone': availability_zone}
check_policy(context, 'create', target)
if requested_networks:
check_policy(context, 'create:attach_network', target)
if block_device_mapping:
check_policy(context, 'create:attach_volume', target)
def create(self, context, instance_type,
image_href, kernel_id=None, ramdisk_id=None,
min_count=None, max_count=None,
display_name=None, display_description=None,
key_name=None, key_data=None, security_group=None,
availability_zone=None, user_data=None, metadata=None,
injected_files=None, admin_password=None,
block_device_mapping=None, access_ip_v4=None,
access_ip_v6=None, requested_networks=None, config_drive=None,
auto_disk_config=None, scheduler_hints=None):
"""
Provision instances, sending instance information to the
scheduler. The scheduler will determine where the instance(s)
go and will handle creating the DB entries.
Returns a tuple of (instances, reservation_id) where instances
could be 'None' or a list of instance dicts depending on if
we waited for information from the scheduler or not.
"""
self._check_create_policies(context, availability_zone,
requested_networks, block_device_mapping)
# We can create the DB entry for the instance here if we're
# only going to create 1 instance.
# This speeds up API responses for builds
# as we don't need to wait for the scheduler.
create_instance_here = max_count == 1
(instances, reservation_id) = self._create_instance(
context, instance_type,
image_href, kernel_id, ramdisk_id,
min_count, max_count,
display_name, display_description,
key_name, key_data, security_group,
availability_zone, user_data, metadata,
injected_files, admin_password,
access_ip_v4, access_ip_v6,
requested_networks, config_drive,
block_device_mapping, auto_disk_config,
create_instance_here=create_instance_here,
scheduler_hints=scheduler_hints)
if create_instance_here or instances is None:
return (instances, reservation_id)
inst_ret_list = []
for instance in instances:
if instance.get('_is_precooked', False):
inst_ret_list.append(instance)
else:
# Scheduler only gives us the 'id'. We need to pull
# in the created instances from the DB
instance = self.db.instance_get(context, instance['id'])
inst_ret_list.append(dict(instance.iteritems()))
return (inst_ret_list, reservation_id)
def ensure_default_security_group(self, context):
"""Ensure that a context has a security group.
Creates a security group for the security context if it does not
already exist.
:param context: the security context
"""
try:
self.db.security_group_get_by_name(context,
context.project_id,
'default')
except exception.NotFound:
values = {'name': 'default',
'description': 'default',
'user_id': context.user_id,
'project_id': context.project_id}
self.db.security_group_create(context, values)
def trigger_security_group_rules_refresh(self, context, security_group_id):
"""Called when a rule is added to or removed from a security_group."""
security_group = self.db.security_group_get(context, security_group_id)
hosts = set()
for instance in security_group['instances']:
if instance['host'] is not None:
hosts.add(instance['host'])
for host in hosts:
rpc.cast(context,
self.db.queue_get_for(context, FLAGS.compute_topic, host),
{"method": "refresh_security_group_rules",
"args": {"security_group_id": security_group.id}})
def trigger_security_group_members_refresh(self, context, group_ids):
"""Called when a security group gains a new or loses a member.
Sends an update request to each compute node for whom this is
relevant.
"""
# First, we get the security group rules that reference these groups as
# the grantee..
security_group_rules = set()
for group_id in group_ids:
security_group_rules.update(
self.db.security_group_rule_get_by_security_group_grantee(
context,
group_id))
# ..then we distill the security groups to which they belong..
security_groups = set()
for rule in security_group_rules:
security_group = self.db.security_group_get(
context,
rule['parent_group_id'])
security_groups.add(security_group)
# ..then we find the instances that are members of these groups..
instances = set()
for security_group in security_groups:
for instance in security_group['instances']:
instances.add(instance)
# ...then we find the hosts where they live...
hosts = set()
for instance in instances:
if instance['host']:
hosts.add(instance['host'])
# ...and finally we tell these nodes to refresh their view of this
# particular security group.
for host in hosts:
rpc.cast(context,
self.db.queue_get_for(context, FLAGS.compute_topic, host),
{"method": "refresh_security_group_members",
"args": {"security_group_id": group_id}})
def trigger_provider_fw_rules_refresh(self, context):
"""Called when a rule is added/removed from a provider firewall"""
hosts = [x['host'] for (x, idx)
in self.db.service_get_all_compute_sorted(context)]
for host in hosts:
rpc.cast(context,
self.db.queue_get_for(context, FLAGS.compute_topic, host),
{'method': 'refresh_provider_fw_rules', 'args': {}})
def _is_security_group_associated_with_server(self, security_group,
instance_uuid):
"""Check if the security group is already associated
with the instance. If Yes, return True.
"""
if not security_group:
return False
instances = security_group.get('instances')
if not instances:
return False
for inst in instances:
if (instance_uuid == inst['uuid']):
return True
return False
@wrap_check_policy
def add_security_group(self, context, instance, security_group_name):
"""Add security group to the instance"""
security_group = self.db.security_group_get_by_name(context,
context.project_id,
security_group_name)
instance_uuid = instance['uuid']
#check if the security group is associated with the server
if self._is_security_group_associated_with_server(security_group,
instance_uuid):
raise exception.SecurityGroupExistsForInstance(
security_group_id=security_group['id'],
instance_id=instance_uuid)
#check if the instance is in running state
if instance['power_state'] != power_state.RUNNING:
raise exception.InstanceNotRunning(instance_id=instance_uuid)
self.db.instance_add_security_group(context.elevated(),
instance_uuid,
security_group['id'])
params = {"security_group_id": security_group['id']}
# NOTE(comstud): No instance_uuid argument to this compute manager
# call
self._cast_compute_message('refresh_security_group_rules',
context, host=instance['host'], params=params)
@wrap_check_policy
def remove_security_group(self, context, instance, security_group_name):
"""Remove the security group associated with the instance"""
security_group = self.db.security_group_get_by_name(context,
context.project_id,
security_group_name)
instance_uuid = instance['uuid']
#check if the security group is associated with the server
if not self._is_security_group_associated_with_server(security_group,
instance_uuid):
raise exception.SecurityGroupNotExistsForInstance(
security_group_id=security_group['id'],
instance_id=instance_uuid)
#check if the instance is in running state
if instance['power_state'] != power_state.RUNNING:
raise exception.InstanceNotRunning(instance_id=instance_uuid)
self.db.instance_remove_security_group(context.elevated(),
instance_uuid,
security_group['id'])
params = {"security_group_id": security_group['id']}
# NOTE(comstud): No instance_uuid argument to this compute manager
# call
self._cast_compute_message('refresh_security_group_rules',
context, host=instance['host'], params=params)
@wrap_check_policy
def update(self, context, instance, **kwargs):
"""Updates the instance in the datastore.
:param context: The security context
:param instance: The instance to update
:param kwargs: All additional keyword args are treated
as data fields of the instance to be
updated
:returns: None
"""
rv = self.db.instance_update(context, instance["id"], kwargs)
return dict(rv.iteritems())
@wrap_check_policy
@check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.SHUTOFF,
vm_states.ERROR])
def soft_delete(self, context, instance):
"""Terminate an instance."""
LOG.debug(_('Going to try to soft delete instance'),
instance=instance)
if instance['disable_terminate']:
return
# NOTE(jerdfelt): The compute daemon handles reclaiming instances
# that are in soft delete. If there is no host assigned, there is
# no daemon to reclaim, so delete it immediately.
host = instance['host']
if host:
self.update(context,
instance,
vm_state=vm_states.SOFT_DELETE,
task_state=task_states.POWERING_OFF,
deleted_at=utils.utcnow())
self._cast_compute_message('power_off_instance',
context, instance)
else:
LOG.warning(_('No host for instance, deleting immediately'),
instance=instance)
try:
self.db.instance_destroy(context, instance['id'])
except exception.InstanceNotFound:
# NOTE(comstud): Race condition. Instance already gone.
pass
def _delete(self, context, instance):
host = instance['host']
try:
if host:
self.update(context,
instance,
task_state=task_states.DELETING,
progress=0)
self._cast_compute_message('terminate_instance',
context, instance)
else:
self.db.instance_destroy(context, instance['id'])
except exception.InstanceNotFound:
# NOTE(comstud): Race condition. Instance already gone.
pass
# NOTE(jerdfelt): The API implies that only ACTIVE and ERROR are
# allowed but the EC2 API appears to allow from RESCUED and STOPPED
# too
@wrap_check_policy
@check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.BUILDING,
vm_states.ERROR, vm_states.RESCUED,
vm_states.SHUTOFF, vm_states.STOPPED])
def delete(self, context, instance):
"""Terminate an instance."""
LOG.debug(_("Going to try to terminate instance"), instance=instance)
if instance['disable_terminate']:
return
self._delete(context, instance)
@wrap_check_policy
@check_instance_state(vm_state=[vm_states.SOFT_DELETE])
def restore(self, context, instance):
"""Restore a previously deleted (but not reclaimed) instance."""
self.update(context,
instance,
vm_state=vm_states.ACTIVE,
task_state=None,
deleted_at=None)
host = instance['host']
if host:
self.update(context,
instance,
task_state=task_states.POWERING_ON)
self._cast_compute_message('power_on_instance',
context, instance)
@wrap_check_policy
@check_instance_state(vm_state=[vm_states.SOFT_DELETE])
def force_delete(self, context, instance):
"""Force delete a previously deleted (but not reclaimed) instance."""
self._delete(context, instance)
@wrap_check_policy
@check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.SHUTOFF,
vm_states.RESCUED],
task_state=[None, task_states.RESIZE_VERIFY])
def stop(self, context, instance, do_cast=True):
"""Stop an instance."""
instance_uuid = instance["uuid"]
LOG.debug(_("Going to try to stop instance"), instance=instance)
self.update(context,
instance,
vm_state=vm_states.ACTIVE,
task_state=task_states.STOPPING,
terminated_at=utils.utcnow(),
progress=0)
rpc_method = rpc.cast if do_cast else rpc.call
self._cast_or_call_compute_message(rpc_method, 'stop_instance',
context, instance)
@wrap_check_policy
@check_instance_state(vm_state=[vm_states.STOPPED, vm_states.SHUTOFF])
def start(self, context, instance):
"""Start an instance."""
vm_state = instance["vm_state"]
instance_uuid = instance["uuid"]
LOG.debug(_("Going to try to start instance"), instance=instance)
if vm_state == vm_states.SHUTOFF:
if instance['shutdown_terminate']:
LOG.warning(_("Instance %(instance_uuid)s is not "
"stopped. (%(vm_state)s") % locals())
return
# NOTE(yamahata): nova compute doesn't reap instances
# which initiated shutdown itself. So reap it here.
self.stop(context, instance, do_cast=False)
self.update(context,
instance,
vm_state=vm_states.STOPPED,
task_state=task_states.STARTING)
# TODO(yamahata): injected_files isn't supported right now.
# It is used only for osapi. not for ec2 api.