/
manager.py
1954 lines (1652 loc) · 86 KB
/
manager.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 Justin Santa Barbara
# 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 processes relating to instances (guest vms).
The :py:class:`ComputeManager` class is a :py:class:`nova.manager.Manager` that
handles RPC calls relating to creating instances. It is responsible for
building a disk image, launching it via the underlying virtualization driver,
responding to calls to check its state, attaching persistent storage, and
terminating it.
**Related Flags**
:instances_path: Where instances are kept on disk
:compute_driver: Name of class that is used to handle virtualization, loaded
by :func:`nova.utils.import_object`
"""
import contextlib
import datetime
import functools
import os
import socket
import sys
import tempfile
import time
from eventlet import greenthread
from nova import block_device
import nova.context
from nova.compute import instance_types
from nova.compute import power_state
from nova.compute import task_states
from nova.compute.utils import notify_usage_exists
from nova.compute import vm_states
from nova import exception
from nova import flags
import nova.image
from nova import log as logging
from nova import manager
from nova import network
from nova.notifier import api as notifier
from nova import rpc
from nova import utils
from nova.virt import driver
from nova import volume
FLAGS = flags.FLAGS
flags.DEFINE_string('instances_path', '$state_path/instances',
'where instances are stored on disk')
flags.DEFINE_string('compute_driver', 'nova.virt.connection.get_connection',
'Driver to use for controlling virtualization')
flags.DEFINE_string('console_host', socket.gethostname(),
'Console proxy host to use to connect to instances on'
'this host.')
flags.DEFINE_integer('live_migration_retry_count', 30,
"Retry count needed in live_migration."
" sleep 1 sec for each count")
flags.DEFINE_integer("reboot_timeout", 0,
"Automatically hard reboot an instance if it has been "
"stuck in a rebooting state longer than N seconds."
" Set to 0 to disable.")
flags.DEFINE_integer("rescue_timeout", 0,
"Automatically unrescue an instance after N seconds."
" Set to 0 to disable.")
flags.DEFINE_integer("resize_confirm_window", 0,
"Automatically confirm resizes after N seconds."
" Set to 0 to disable.")
flags.DEFINE_integer('host_state_interval', 120,
'Interval in seconds for querying the host status')
LOG = logging.getLogger('nova.compute.manager')
def publisher_id(host=None):
return notifier.publisher_id("compute", host)
def checks_instance_lock(function):
"""Decorator to prevent action against locked instances for non-admins."""
@functools.wraps(function)
def decorated_function(self, context, instance_id, *args, **kwargs):
#TODO(anyone): this being called instance_id is forcing a slightly
# confusing convention of pushing instance_uuids
# through an "instance_id" key in the queue args dict when
# casting through the compute API
LOG.info(_("check_instance_lock: decorating: |%s|"), function,
context=context)
LOG.info(_("check_instance_lock: arguments: |%(self)s| |%(context)s|"
" |%(instance_id)s|") % locals(), context=context)
locked = self.get_lock(context, instance_id)
admin = context.is_admin
LOG.info(_("check_instance_lock: locked: |%s|"), locked,
context=context)
LOG.info(_("check_instance_lock: admin: |%s|"), admin,
context=context)
# if admin or unlocked call function otherwise log error
if admin or not locked:
LOG.info(_("check_instance_lock: executing: |%s|"), function,
context=context)
function(self, context, instance_id, *args, **kwargs)
else:
LOG.error(_("check_instance_lock: not executing |%s|"),
function, context=context)
return False
return decorated_function
def _get_image_meta(context, image_ref):
image_service, image_id = nova.image.get_image_service(context, image_ref)
return image_service.show(context, image_id)
class ComputeManager(manager.SchedulerDependentManager):
"""Manages the running instances from creation to destruction."""
def __init__(self, compute_driver=None, *args, **kwargs):
"""Load configuration options and connect to the hypervisor."""
# TODO(vish): sync driver creation logic with the rest of the system
# and redocument the module docstring
if not compute_driver:
compute_driver = FLAGS.compute_driver
try:
self.driver = utils.check_isinstance(
utils.import_object(compute_driver),
driver.ComputeDriver)
except ImportError as e:
LOG.error(_("Unable to load the virtualization driver: %s") % (e))
sys.exit(1)
self.network_api = network.API()
self.network_manager = utils.import_object(FLAGS.network_manager)
self._last_host_check = 0
self._last_bw_usage_poll = 0
super(ComputeManager, self).__init__(service_name="compute",
*args, **kwargs)
def _instance_update(self, context, instance_id, **kwargs):
"""Update an instance in the database using kwargs as value."""
return self.db.instance_update(context, instance_id, kwargs)
def init_host(self):
"""Initialization for a standalone compute service."""
self.driver.init_host(host=self.host)
context = nova.context.get_admin_context()
instances = self.db.instance_get_all_by_host(context, self.host)
for instance in instances:
inst_name = instance['name']
db_state = instance['power_state']
drv_state = self._get_power_state(context, instance)
expect_running = db_state == power_state.RUNNING \
and drv_state != db_state
LOG.debug(_('Current state of %(inst_name)s is %(drv_state)s, '
'state in DB is %(db_state)s.'), locals())
if (expect_running and FLAGS.resume_guests_state_on_host_boot)\
or FLAGS.start_guests_on_host_boot:
LOG.info(_('Rebooting instance %(inst_name)s after '
'nova-compute restart.'), locals())
self.reboot_instance(context, instance['id'])
elif drv_state == power_state.RUNNING:
# Hyper-V and VMWareAPI drivers will raise an exception
try:
net_info = self._get_instance_nw_info(context, instance)
self.driver.ensure_filtering_rules_for_instance(instance,
net_info)
except NotImplementedError:
LOG.warning(_('Hypervisor driver does not '
'support firewall rules'))
def _get_power_state(self, context, instance):
"""Retrieve the power state for the given instance."""
LOG.debug(_('Checking state of %s'), instance['name'])
try:
return self.driver.get_info(instance['name'])["state"]
except exception.NotFound:
return power_state.FAILED
def get_console_topic(self, context, **kwargs):
"""Retrieves the console host for a project on this host.
Currently this is just set in the flags for each compute host.
"""
#TODO(mdragon): perhaps make this variable by console_type?
return self.db.queue_get_for(context,
FLAGS.console_topic,
FLAGS.console_host)
def get_console_pool_info(self, context, console_type):
return self.driver.get_console_pool_info(console_type)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def refresh_security_group_rules(self, context, security_group_id,
**kwargs):
"""Tell the virtualization driver to refresh security group rules.
Passes straight through to the virtualization driver.
"""
return self.driver.refresh_security_group_rules(security_group_id)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def refresh_security_group_members(self, context,
security_group_id, **kwargs):
"""Tell the virtualization driver to refresh security group members.
Passes straight through to the virtualization driver.
"""
return self.driver.refresh_security_group_members(security_group_id)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def refresh_provider_fw_rules(self, context, **_kwargs):
"""This call passes straight through to the virtualization driver."""
return self.driver.refresh_provider_fw_rules()
def _get_instance_nw_info(self, context, instance):
"""Get a list of dictionaries of network data of an instance.
Returns an empty list if stub_network flag is set."""
network_info = []
if not FLAGS.stub_network:
network_info = self.network_api.get_instance_nw_info(context,
instance)
return network_info
def _setup_block_device_mapping(self, context, instance_id):
"""setup volumes for block device mapping"""
volume_api = volume.API()
block_device_mapping = []
swap = None
ephemerals = []
for bdm in self.db.block_device_mapping_get_all_by_instance(
context, instance_id):
LOG.debug(_("setting up bdm %s"), bdm)
if bdm['no_device']:
continue
if bdm['virtual_name']:
virtual_name = bdm['virtual_name']
device_name = bdm['device_name']
assert block_device.is_swap_or_ephemeral(virtual_name)
if virtual_name == 'swap':
swap = {'device_name': device_name,
'swap_size': bdm['volume_size']}
elif block_device.is_ephemeral(virtual_name):
eph = {'num': block_device.ephemeral_num(virtual_name),
'virtual_name': virtual_name,
'device_name': device_name,
'size': bdm['volume_size']}
ephemerals.append(eph)
continue
if ((bdm['snapshot_id'] is not None) and
(bdm['volume_id'] is None)):
# TODO(yamahata): default name and description
vol = volume_api.create(context, bdm['volume_size'],
bdm['snapshot_id'], '', '')
# TODO(yamahata): creating volume simultaneously
# reduces creation time?
volume_api.wait_creation(context, vol['id'])
self.db.block_device_mapping_update(
context, bdm['id'], {'volume_id': vol['id']})
bdm['volume_id'] = vol['id']
if not ((bdm['snapshot_id'] is None) or
(bdm['volume_id'] is not None)):
LOG.error(_('corrupted state of block device mapping '
'id: %(id)s snapshot: %(snapshot_id)s '
'volume: %(volume_id)s') %
{'id': bdm['id'],
'snapshot_id': bdm['snapshot'],
'volume_id': bdm['volume_id']})
raise exception.ApiError(_('broken block device mapping %d') %
bdm['id'])
if bdm['volume_id'] is not None:
volume_api.check_attach(context,
volume_id=bdm['volume_id'])
cinfo = self._attach_volume_boot(context, instance_id,
bdm['volume_id'],
bdm['device_name'])
self.db.block_device_mapping_update(
context, bdm['id'],
{'connection_info': utils.dumps(cinfo)})
block_device_mapping.append({'connection_info': cinfo,
'mount_device':
bdm['device_name']})
return (swap, ephemerals, block_device_mapping)
def _run_instance(self, context, instance_id, **kwargs):
"""Launch a new instance with specified options."""
def _check_image_size(image_meta):
"""Ensure image is smaller than the maximum size allowed by the
instance_type.
The image stored in Glance is potentially compressed, so we use two
checks to ensure that the size isn't exceeded:
1) This one - checks compressed size, this a quick check to
eliminate any images which are obviously too large
2) Check uncompressed size in nova.virt.xenapi.vm_utils. This
is a slower check since it requires uncompressing the entire
image, but is accurate because it reflects the image's
actual size.
"""
try:
size_bytes = image_meta['size']
except KeyError:
# Size is not a required field in the image service (yet), so
# we are unable to rely on it being there even though it's in
# glance.
# TODO(jk0): Should size be required in the image service?
return
instance_type_id = instance['instance_type_id']
instance_type = instance_types.get_instance_type(instance_type_id)
allowed_size_gb = instance_type['local_gb']
# NOTE(jk0): Since libvirt uses local_gb as a secondary drive, we
# need to handle potential situations where local_gb is 0. This is
# the default for m1.tiny.
if allowed_size_gb == 0:
return
allowed_size_bytes = allowed_size_gb * 1024 * 1024 * 1024
image_id = image_meta['id']
LOG.debug(_("image_id=%(image_id)s, image_size_bytes="
"%(size_bytes)d, allowed_size_bytes="
"%(allowed_size_bytes)d") % locals())
if size_bytes > allowed_size_bytes:
LOG.info(_("Image '%(image_id)s' size %(size_bytes)d exceeded"
" instance_type allowed size "
"%(allowed_size_bytes)d")
% locals())
raise exception.ImageTooLarge()
def _make_network_info():
if FLAGS.stub_network:
# TODO(tr3buchet) not really sure how this should be handled.
# virt requires network_info to be passed in but stub_network
# is enabled. Setting to [] for now will cause virt to skip
# all vif creation and network injection, maybe this is correct
network_info = []
else:
# NOTE(vish): This could be a cast because we don't do
# anything with the address currently, but I'm leaving it as a
# call to ensure that network setup completes. We will
# eventually also need to save the address here.
network_info = self.network_api.allocate_for_instance(context,
instance, vpn=is_vpn,
requested_networks=requested_networks)
LOG.debug(_("instance network_info: |%s|"), network_info)
return network_info
def _make_block_device_info():
(swap, ephemerals,
block_device_mapping) = self._setup_block_device_mapping(
context, instance_id)
block_device_info = {
'root_device_name': instance['root_device_name'],
'swap': swap,
'ephemerals': ephemerals,
'block_device_mapping': block_device_mapping}
return block_device_info
def _deallocate_network():
if not FLAGS.stub_network:
LOG.debug(_("deallocating network for instance: %s"),
instance['id'])
self.network_api.deallocate_for_instance(context,
instance)
def _cleanup():
with utils.save_and_reraise_exception():
self._instance_update(context,
instance_id,
vm_state=vm_states.ERROR)
if network_info is not None:
_deallocate_network()
@contextlib.contextmanager
def _logging_error(instance_id, message):
try:
yield
except Exception as error:
with utils.save_and_reraise_exception():
LOG.exception(_("Instance '%(instance_id)s' "
"failed %(message)s.") % locals())
context = context.elevated()
instance = self.db.instance_get(context, instance_id)
requested_networks = kwargs.get('requested_networks', None)
if instance['name'] in self.driver.list_instances():
raise exception.Error(_("Instance has already been created"))
image_meta = _get_image_meta(context, instance['image_ref'])
_check_image_size(image_meta)
LOG.audit(_("instance %s: starting..."), instance_id,
context=context)
updates = {}
updates['host'] = self.host
updates['launched_on'] = self.host
updates['vm_state'] = vm_states.BUILDING
updates['task_state'] = task_states.NETWORKING
instance = self.db.instance_update(context, instance_id, updates)
instance['injected_files'] = kwargs.get('injected_files', [])
instance['admin_pass'] = kwargs.get('admin_password', None)
is_vpn = instance['image_ref'] == str(FLAGS.vpn_image_id)
try:
network_info = None
with _logging_error(instance_id, "network setup"):
network_info = _make_network_info()
self._instance_update(context,
instance_id,
vm_state=vm_states.BUILDING,
task_state=task_states.BLOCK_DEVICE_MAPPING)
with _logging_error(instance_id, "block device setup"):
block_device_info = _make_block_device_info()
self._instance_update(context,
instance_id,
vm_state=vm_states.BUILDING,
task_state=task_states.SPAWNING)
# TODO(vish) check to make sure the availability zone matches
with _logging_error(instance_id, "failed to spawn"):
self.driver.spawn(context, instance, image_meta,
network_info, block_device_info)
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_id,
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None,
launched_at=utils.utcnow())
usage_info = utils.usage_from_instance(instance)
notifier.notify('compute.%s' % self.host,
'compute.instance.create',
notifier.INFO, usage_info)
except exception.InstanceNotFound:
# FIXME(wwolf): We are just ignoring InstanceNotFound
# exceptions here in case the instance was immediately
# deleted before it actually got created. This should
# be fixed once we have no-db-messaging
pass
except Exception:
_cleanup()
def _get_instance_volume_bdms(self, context, instance_id):
bdms = self.db.block_device_mapping_get_all_by_instance(context,
instance_id)
return [bdm for bdm in bdms if bdm['volume_id']]
def _get_instance_volume_block_device_info(self, context, instance_id):
bdms = self._get_instance_volume_bdms(context, instance_id)
block_device_mapping = []
for bdm in bdms:
cinfo = utils.loads(bdm['connection_info'])
block_device_mapping.append({'connection_info': cinfo,
'mount_device':
bdm['device_name']})
## NOTE(vish): The mapping is passed in so the driver can disconnect
## from remote volumes if necessary
return {'block_device_mapping': block_device_mapping}
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def run_instance(self, context, instance_id, **kwargs):
self._run_instance(context, instance_id, **kwargs)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def start_instance(self, context, instance_id):
"""Starting an instance on this host."""
# TODO(yamahata): injected_files isn't supported.
# Anyway OSAPI doesn't support stop/start yet
# FIXME(vish): I've kept the files during stop instance, but
# I think start will fail due to the files still
self._run_instance(context, instance_id)
def _shutdown_instance(self, context, instance_id, action_str, cleanup):
"""Shutdown an instance on this host."""
context = context.elevated()
instance = self.db.instance_get(context, instance_id)
LOG.audit(_("%(action_str)s instance %(instance_id)s") %
{'action_str': action_str, 'instance_id': instance_id},
context=context)
network_info = self._get_instance_nw_info(context, instance)
if not FLAGS.stub_network:
self.network_api.deallocate_for_instance(context, instance)
for bdm in self._get_instance_volume_bdms(context, instance_id):
volume_id = bdm['volume_id']
try:
self._detach_volume(context, instance_id, volume_id)
except exception.DiskNotFound as exc:
LOG.warn(_("Ignoring DiskNotFound: %s") % exc)
if instance['power_state'] == power_state.SHUTOFF:
self.db.instance_destroy(context, instance_id)
raise exception.Error(_('trying to destroy already destroyed'
' instance: %s') % instance_id)
block_device_info = self._get_instance_volume_block_device_info(
context, instance_id)
self.driver.destroy(instance, network_info, block_device_info, cleanup)
def _cleanup_volumes(self, context, instance_id):
volume_api = volume.API()
bdms = self.db.block_device_mapping_get_all_by_instance(context,
instance_id)
for bdm in bdms:
LOG.debug(_("terminating bdm %s") % bdm)
if bdm['volume_id'] and bdm['delete_on_termination']:
volume_api.delete(context, bdm['volume_id'])
# NOTE(vish): bdms will be deleted on instance destroy
def _delete_instance(self, context, instance_id):
"""Delete an instance on this host."""
self._shutdown_instance(context, instance_id, 'Terminating', True)
self._cleanup_volumes(context, instance_id)
instance = self.db.instance_get(context.elevated(), instance_id)
self._instance_update(context,
instance_id,
vm_state=vm_states.DELETED,
task_state=None,
terminated_at=utils.utcnow())
self.db.instance_destroy(context, instance_id)
usage_info = utils.usage_from_instance(instance)
notifier.notify('compute.%s' % self.host,
'compute.instance.delete',
notifier.INFO, usage_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def terminate_instance(self, context, instance_id):
"""Terminate an instance on this host."""
#generate usage info.
instance = self.db.instance_get(context.elevated(), instance_id)
notify_usage_exists(instance, current_period=True)
self._delete_instance(context, instance_id)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def stop_instance(self, context, instance_id):
"""Stopping an instance on this host."""
# FIXME(vish): I've kept the files during stop instance, but
# I think start will fail due to the files still
# existing. I don't really know what the purpose of
# stop and start are when compared to pause and unpause
self._shutdown_instance(context, instance_id, 'Stopping', False)
self._instance_update(context,
instance_id,
vm_state=vm_states.STOPPED,
task_state=None)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def power_off_instance(self, context, instance_id):
"""Power off an instance on this host."""
instance = self.db.instance_get(context, instance_id)
self.driver.power_off(instance)
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_id,
power_state=current_power_state,
task_state=None)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def power_on_instance(self, context, instance_id):
"""Power on an instance on this host."""
instance = self.db.instance_get(context, instance_id)
self.driver.power_on(instance)
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_id,
power_state=current_power_state,
task_state=None)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def rebuild_instance(self, context, instance_id, **kwargs):
"""Destroy and re-make this instance.
A 'rebuild' effectively purges all existing data from the system and
remakes the VM with given 'metadata' and 'personalities'.
:param context: `nova.RequestContext` object
:param instance_id: Instance identifier (integer)
:param injected_files: Files to inject
:param new_pass: password to set on rebuilt instance
"""
context = context.elevated()
instance_ref = self.db.instance_get(context, instance_id)
LOG.audit(_("Rebuilding instance %s"), instance_id, context=context)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_id,
power_state=current_power_state,
vm_state=vm_states.REBUILDING,
task_state=None)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.destroy(instance_ref, network_info)
self._instance_update(context,
instance_id,
vm_state=vm_states.REBUILDING,
task_state=task_states.BLOCK_DEVICE_MAPPING)
instance_ref.injected_files = kwargs.get('injected_files', [])
network_info = self.network_api.get_instance_nw_info(context,
instance_ref)
bd_mapping = self._setup_block_device_mapping(context, instance_id)
self._instance_update(context,
instance_id,
vm_state=vm_states.REBUILDING,
task_state=task_states.SPAWNING)
# pull in new password here since the original password isn't in the db
instance_ref.admin_pass = kwargs.get('new_pass',
utils.generate_password(FLAGS.password_length))
image_meta = _get_image_meta(context, instance_ref['image_ref'])
self.driver.spawn(context, instance_ref, image_meta,
network_info, bd_mapping)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_id,
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None,
launched_at=utils.utcnow())
usage_info = utils.usage_from_instance(instance_ref)
notifier.notify('compute.%s' % self.host,
'compute.instance.rebuild',
notifier.INFO,
usage_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def reboot_instance(self, context, instance_id, reboot_type="SOFT"):
"""Reboot an instance on this host."""
LOG.audit(_("Rebooting instance %s"), instance_id, context=context)
context = context.elevated()
instance_ref = self.db.instance_get(context, instance_id)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_id,
power_state=current_power_state,
vm_state=vm_states.ACTIVE)
if instance_ref['power_state'] != power_state.RUNNING:
state = instance_ref['power_state']
running = power_state.RUNNING
LOG.warn(_('trying to reboot a non-running '
'instance: %(instance_id)s (state: %(state)s '
'expected: %(running)s)') % locals(),
context=context)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.reboot(instance_ref, network_info, reboot_type)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_id,
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def snapshot_instance(self, context, instance_id, image_id,
image_type='snapshot', backup_type=None,
rotation=None):
"""Snapshot an instance on this host.
:param context: security context
:param instance_id: nova.db.sqlalchemy.models.Instance.Id
:param image_id: glance.db.sqlalchemy.models.Image.Id
:param image_type: snapshot | backup
:param backup_type: daily | weekly
:param rotation: int representing how many backups to keep around;
None if rotation shouldn't be used (as in the case of snapshots)
"""
if image_type == "snapshot":
task_state = task_states.IMAGE_SNAPSHOT
elif image_type == "backup":
task_state = task_states.IMAGE_BACKUP
else:
raise Exception(_('Image type not recognized %s') % image_type)
context = context.elevated()
instance_ref = self.db.instance_get(context, instance_id)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_id,
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=task_state)
LOG.audit(_('instance %s: snapshotting'), instance_id,
context=context)
if instance_ref['power_state'] != power_state.RUNNING:
state = instance_ref['power_state']
running = power_state.RUNNING
LOG.warn(_('trying to snapshot a non-running '
'instance: %(instance_id)s (state: %(state)s '
'expected: %(running)s)') % locals())
self.driver.snapshot(context, instance_ref, image_id)
self._instance_update(context, instance_id, task_state=None)
if image_type == 'snapshot' and rotation:
raise exception.ImageRotationNotAllowed()
elif image_type == 'backup' and rotation:
instance_uuid = instance_ref['uuid']
self.rotate_backups(context, instance_uuid, backup_type, rotation)
elif image_type == 'backup':
raise exception.RotationRequiredForBackup()
def rotate_backups(self, context, instance_uuid, backup_type, rotation):
"""Delete excess backups associated to an instance.
Instances are allowed a fixed number of backups (the rotation number);
this method deletes the oldest backups that exceed the rotation
threshold.
:param context: security context
:param instance_uuid: string representing uuid of instance
:param backup_type: daily | weekly
:param rotation: int representing how many backups to keep around;
None if rotation shouldn't be used (as in the case of snapshots)
"""
# NOTE(jk0): Eventually extract this out to the ImageService?
def fetch_images():
images = []
marker = None
while True:
batch = image_service.detail(context, filters=filters,
marker=marker, sort_key='created_at', sort_dir='desc')
if not batch:
break
images += batch
marker = batch[-1]['id']
return images
image_service = nova.image.get_default_image_service()
filters = {'property-image_type': 'backup',
'property-backup_type': backup_type,
'property-instance_uuid': instance_uuid}
images = fetch_images()
num_images = len(images)
LOG.debug(_("Found %(num_images)d images (rotation: %(rotation)d)"
% locals()))
if num_images > rotation:
# NOTE(sirp): this deletes all backups that exceed the rotation
# limit
excess = len(images) - rotation
LOG.debug(_("Rotating out %d backups" % excess))
for i in xrange(excess):
image = images.pop()
image_id = image['id']
LOG.debug(_("Deleting image %s" % image_id))
image_service.delete(context, image_id)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def set_admin_password(self, context, instance_id, new_pass=None):
"""Set the root/admin password for an instance on this host.
This is generally only called by API password resets after an
image has been built.
"""
context = context.elevated()
if new_pass is None:
# Generate a random password
new_pass = utils.generate_password(FLAGS.password_length)
max_tries = 10
for i in xrange(max_tries):
instance_ref = self.db.instance_get(context, instance_id)
instance_id = instance_ref["id"]
instance_state = instance_ref["power_state"]
expected_state = power_state.RUNNING
if instance_state != expected_state:
self._instance_update(context, instance_id, task_state=None)
raise exception.Error(_('Instance is not running'))
else:
try:
self.driver.set_admin_password(instance_ref, new_pass)
LOG.audit(_("Instance %s: Root password set"),
instance_ref["name"])
self._instance_update(context,
instance_id,
task_state=None)
break
except NotImplementedError:
# NOTE(dprince): if the driver doesn't implement
# set_admin_password we break to avoid a loop
LOG.warn(_('set_admin_password is not implemented '
'by this driver.'))
self._instance_update(context,
instance_id,
task_state=None)
break
except Exception, e:
# Catch all here because this could be anything.
LOG.exception(e)
if i == max_tries - 1:
# At some point this exception may make it back
# to the API caller, and we don't want to reveal
# too much. The real exception is logged above
self._instance_update(context,
instance_id,
vm_state=vm_states.ERROR)
raise exception.Error(_('Internal error'))
time.sleep(1)
continue
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def inject_file(self, context, instance_id, path, file_contents):
"""Write a file to the specified path in an instance on this host."""
context = context.elevated()
instance_ref = self.db.instance_get(context, instance_id)
instance_id = instance_ref['id']
instance_state = instance_ref['power_state']
expected_state = power_state.RUNNING
if instance_state != expected_state:
LOG.warn(_('trying to inject a file into a non-running '
'instance: %(instance_id)s (state: %(instance_state)s '
'expected: %(expected_state)s)') % locals())
nm = instance_ref['name']
msg = _('instance %(nm)s: injecting file to %(path)s') % locals()
LOG.audit(msg)
self.driver.inject_file(instance_ref, path, file_contents)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def agent_update(self, context, instance_id, url, md5hash):
"""Update agent running on an instance on this host."""
context = context.elevated()
instance_ref = self.db.instance_get(context, instance_id)
instance_id = instance_ref['id']
instance_state = instance_ref['power_state']
expected_state = power_state.RUNNING
if instance_state != expected_state:
LOG.warn(_('trying to update agent on a non-running '
'instance: %(instance_id)s (state: %(instance_state)s '
'expected: %(expected_state)s)') % locals())
nm = instance_ref['name']
msg = _('instance %(nm)s: updating agent to %(url)s') % locals()
LOG.audit(msg)
self.driver.agent_update(instance_ref, url, md5hash)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def rescue_instance(self, context, instance_id, **kwargs):
"""
Rescue an instance on this host.
:param rescue_password: password to set on rescue instance
"""
LOG.audit(_('instance %s: rescuing'), instance_id, context=context)
context = context.elevated()
instance_ref = self.db.instance_get(context, instance_id)
instance_ref.admin_pass = kwargs.get('rescue_password',
utils.generate_password(FLAGS.password_length))
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.rescue(context, instance_ref, network_info)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_id,
vm_state=vm_states.RESCUED,
task_state=None,
power_state=current_power_state)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def unrescue_instance(self, context, instance_id):
"""Rescue an instance on this host."""
LOG.audit(_('instance %s: unrescuing'), instance_id, context=context)
context = context.elevated()
instance_ref = self.db.instance_get(context, instance_id)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.unrescue(instance_ref, network_info)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_id,
vm_state=vm_states.ACTIVE,
task_state=None,
power_state=current_power_state)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def confirm_resize(self, context, instance_id, migration_id):
"""Destroys the source instance."""
migration_ref = self.db.migration_get(context, migration_id)
instance_ref = self.db.instance_get_by_uuid(context,
migration_ref.instance_uuid)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.confirm_migration(
migration_ref, instance_ref, network_info)
usage_info = utils.usage_from_instance(instance_ref)
notifier.notify('compute.%s' % self.host,
'compute.instance.resize.confirm',
notifier.INFO,
usage_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def revert_resize(self, context, instance_id, migration_id):
"""Destroys the new instance on the destination machine.
Reverts the model changes, and powers on the old instance on the
source machine.
"""
migration_ref = self.db.migration_get(context, migration_id)
instance_ref = self.db.instance_get_by_uuid(context,
migration_ref.instance_uuid)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.destroy(instance_ref, network_info)
topic = self.db.queue_get_for(context, FLAGS.compute_topic,
instance_ref['host'])
rpc.cast(context, topic,
{'method': 'finish_revert_resize',
'args': {'instance_id': instance_ref['uuid'],
'migration_id': migration_ref['id']},
})
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
def finish_revert_resize(self, context, instance_id, migration_id):