/
manager.py
2536 lines (2227 loc) · 116 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
# coding=utf-8
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# Copyright 2013 International Business Machines Corporation
# 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.
"""Conduct all activity related to bare-metal deployments.
A single instance of :py:class:`ironic.conductor.manager.ConductorManager` is
created within the *ironic-conductor* process, and is responsible for
performing all actions on bare metal resources (Chassis, Nodes, and Ports).
Commands are received via RPCs. The conductor service also performs periodic
tasks, eg. to monitor the status of active deployments.
Drivers are loaded via entrypoints by the
:py:class:`ironic.common.driver_factory` class. Each driver is instantiated
only once, when the ConductorManager service starts. In this way, a single
ConductorManager may use multiple drivers, and manage heterogeneous hardware.
When multiple :py:class:`ConductorManager` are run on different hosts, they are
all active and cooperatively manage all nodes in the deployment. Nodes are
locked by each conductor when performing actions which change the state of that
node; these locks are represented by the
:py:class:`ironic.conductor.task_manager.TaskManager` class.
A :py:class:`ironic.common.hash_ring.HashRing` is used to distribute nodes
across the set of active conductors which support each node's driver.
Rebalancing this ring can trigger various actions by each conductor, such as
building or tearing down the TFTP environment for a node, notifying Neutron of
a change, etc.
"""
import collections
import datetime
import tempfile
import eventlet
from futurist import periodics
from oslo_config import cfg
from oslo_log import log
import oslo_messaging as messaging
from oslo_utils import excutils
from oslo_utils import uuidutils
from ironic.common import dhcp_factory
from ironic.common import driver_factory
from ironic.common import exception
from ironic.common.glance_service import service_utils as glance_utils
from ironic.common.i18n import _
from ironic.common.i18n import _LE
from ironic.common.i18n import _LI
from ironic.common.i18n import _LW
from ironic.common import images
from ironic.common import states
from ironic.common import swift
from ironic.conductor import base_manager
from ironic.conductor import task_manager
from ironic.conductor import utils
from ironic import objects
from ironic.objects import base as objects_base
MANAGER_TOPIC = 'ironic.conductor_manager'
LOG = log.getLogger(__name__)
conductor_opts = [
cfg.StrOpt('api_url',
help=_('URL of Ironic API service. If not set ironic can '
'get the current value from the keystone service '
'catalog.')),
cfg.IntOpt('heartbeat_timeout',
default=60,
help=_('Maximum time (in seconds) since the last check-in '
'of a conductor. A conductor is considered inactive '
'when this time has been exceeded.')),
cfg.IntOpt('sync_power_state_interval',
default=60,
help=_('Interval between syncing the node power state to the '
'database, in seconds.')),
cfg.IntOpt('check_provision_state_interval',
default=60,
help=_('Interval between checks of provision timeouts, '
'in seconds.')),
cfg.IntOpt('deploy_callback_timeout',
default=1800,
help=_('Timeout (seconds) to wait for a callback from '
'a deploy ramdisk. Set to 0 to disable timeout.')),
cfg.BoolOpt('force_power_state_during_sync',
default=True,
help=_('During sync_power_state, should the hardware power '
'state be set to the state recorded in the database '
'(True) or should the database be updated based on '
'the hardware state (False).')),
cfg.IntOpt('power_state_sync_max_retries',
default=3,
help=_('During sync_power_state failures, limit the '
'number of times Ironic should try syncing the '
'hardware node power state with the node power state '
'in DB')),
cfg.IntOpt('periodic_max_workers',
default=8,
help=_('Maximum number of worker threads that can be started '
'simultaneously by a periodic task. Should be less '
'than RPC thread pool size.')),
cfg.IntOpt('node_locked_retry_attempts',
default=3,
help=_('Number of attempts to grab a node lock.')),
cfg.IntOpt('node_locked_retry_interval',
default=1,
help=_('Seconds to sleep between node lock attempts.')),
cfg.BoolOpt('send_sensor_data',
default=False,
help=_('Enable sending sensor data message via the '
'notification bus')),
cfg.IntOpt('send_sensor_data_interval',
default=600,
help=_('Seconds between conductor sending sensor data message'
' to ceilometer via the notification bus.')),
cfg.ListOpt('send_sensor_data_types',
default=['ALL'],
help=_('List of comma separated meter types which need to be'
' sent to Ceilometer. The default value, "ALL", is a '
'special value meaning send all the sensor data.')),
cfg.IntOpt('sync_local_state_interval',
default=180,
help=_('When conductors join or leave the cluster, existing '
'conductors may need to update any persistent '
'local state as nodes are moved around the cluster. '
'This option controls how often, in seconds, each '
'conductor will check for nodes that it should '
'"take over". Set it to a negative value to disable '
'the check entirely.')),
cfg.BoolOpt('configdrive_use_swift',
default=False,
help=_('Whether to upload the config drive to Swift.')),
cfg.StrOpt('configdrive_swift_container',
default='ironic_configdrive_container',
help=_('Name of the Swift container to store config drive '
'data. Used when configdrive_use_swift is True.')),
cfg.IntOpt('inspect_timeout',
default=1800,
help=_('Timeout (seconds) for waiting for node inspection. '
'0 - unlimited.')),
# TODO(rloo): Remove support for deprecated name 'clean_nodes' in Newton
# cycle.
cfg.BoolOpt('automated_clean',
default=True,
deprecated_name='clean_nodes',
help=_('Enables or disables automated cleaning. Automated '
'cleaning is a configurable set of steps, '
'such as erasing disk drives, that are performed on '
'the node to ensure it is in a baseline state and '
'ready to be deployed to. This is '
'done after instance deletion as well as during '
'the transition from a "manageable" to "available" '
'state. When enabled, the particular steps '
'performed to clean a node depend on which driver '
'that node is managed by; see the individual '
'driver\'s documentation for details. '
'NOTE: The introduction of the cleaning operation '
'causes instance deletion to take significantly '
'longer. In an environment where all tenants are '
'trusted (eg, because there is only one tenant), '
'this option could be safely disabled.')),
cfg.IntOpt('clean_callback_timeout',
default=1800,
help=_('Timeout (seconds) to wait for a callback from the '
'ramdisk doing the cleaning. If the timeout is reached '
'the node will be put in the "clean failed" provision '
'state. Set to 0 to disable timeout.')),
]
CONF = cfg.CONF
CONF.register_opts(conductor_opts, 'conductor')
SYNC_EXCLUDED_STATES = (states.DEPLOYWAIT, states.CLEANWAIT, states.ENROLL)
class ConductorManager(base_manager.BaseConductorManager):
"""Ironic Conductor manager main class."""
# NOTE(rloo): This must be in sync with rpcapi.ConductorAPI's.
RPC_API_VERSION = '1.33'
target = messaging.Target(version=RPC_API_VERSION)
def __init__(self, host, topic):
super(ConductorManager, self).__init__(host, topic)
self.power_state_sync_count = collections.defaultdict(int)
@messaging.expected_exceptions(exception.InvalidParameterValue,
exception.MissingParameterValue,
exception.NodeLocked)
def update_node(self, context, node_obj):
"""Update a node with the supplied data.
This method is the main "hub" for PUT and PATCH requests in the API.
It ensures that the requested change is safe to perform,
validates the parameters with the node's driver, if necessary.
:param context: an admin context
:param node_obj: a changed (but not saved) node object.
"""
node_id = node_obj.uuid
LOG.debug("RPC update_node called for node %s." % node_id)
# NOTE(jroll) clear maintenance_reason if node.update sets
# maintenance to False for backwards compatibility, for tools
# not using the maintenance endpoint.
delta = node_obj.obj_what_changed()
if 'maintenance' in delta and not node_obj.maintenance:
node_obj.maintenance_reason = None
driver_name = node_obj.driver if 'driver' in delta else None
with task_manager.acquire(context, node_id, shared=False,
driver_name=driver_name,
purpose='node update'):
node_obj.save()
return node_obj
@messaging.expected_exceptions(exception.InvalidParameterValue,
exception.MissingParameterValue,
exception.NoFreeConductorWorker,
exception.NodeLocked)
def change_node_power_state(self, context, node_id, new_state):
"""RPC method to encapsulate changes to a node's state.
Perform actions such as power on, power off. The validation is
performed synchronously, and if successful, the power action is
updated in the background (asynchronously). Once the power action
is finished and successful, it updates the power_state for the
node with the new power state.
:param context: an admin context.
:param node_id: the id or uuid of a node.
:param new_state: the desired power state of the node.
:raises: NoFreeConductorWorker when there is no free worker to start
async task.
"""
LOG.debug("RPC change_node_power_state called for node %(node)s. "
"The desired new state is %(state)s."
% {'node': node_id, 'state': new_state})
with task_manager.acquire(context, node_id, shared=False,
purpose='changing node power state') as task:
task.driver.power.validate(task)
# Set the target_power_state and clear any last_error, since we're
# starting a new operation. This will expose to other processes
# and clients that work is in progress.
if new_state == states.REBOOT:
task.node.target_power_state = states.POWER_ON
else:
task.node.target_power_state = new_state
task.node.last_error = None
task.node.save()
task.set_spawn_error_hook(utils.power_state_error_handler,
task.node, task.node.power_state)
task.spawn_after(self._spawn_worker, utils.node_power_action,
task, new_state)
@messaging.expected_exceptions(exception.NoFreeConductorWorker,
exception.NodeLocked,
exception.InvalidParameterValue,
exception.UnsupportedDriverExtension,
exception.MissingParameterValue)
def vendor_passthru(self, context, node_id, driver_method,
http_method, info):
"""RPC method to encapsulate vendor action.
Synchronously validate driver specific info or get driver status,
and if successful invokes the vendor method. If the method mode
is 'async' the conductor will start background worker to perform
vendor action.
:param context: an admin context.
:param node_id: the id or uuid of a node.
:param driver_method: the name of the vendor method.
:param http_method: the HTTP method used for the request.
:param info: vendor method args.
:raises: InvalidParameterValue if supplied info is not valid.
:raises: MissingParameterValue if missing supplied info
:raises: UnsupportedDriverExtension if current driver does not have
vendor interface or method is unsupported.
:raises: NoFreeConductorWorker when there is no free worker to start
async task.
:raises: NodeLocked if node is locked by another conductor.
:returns: A dictionary containing:
:return: The response of the invoked vendor method
:async: Boolean value. Whether the method was invoked
asynchronously (True) or synchronously (False). When invoked
asynchronously the response will be always None.
:attach: Boolean value. Whether to attach the response of
the invoked vendor method to the HTTP response object (True)
or return it in the response body (False).
"""
LOG.debug("RPC vendor_passthru called for node %s." % node_id)
# NOTE(max_lobur): Even though not all vendor_passthru calls may
# require an exclusive lock, we need to do so to guarantee that the
# state doesn't unexpectedly change between doing a vendor.validate
# and vendor.vendor_passthru.
with task_manager.acquire(context, node_id, shared=False,
purpose='calling vendor passthru') as task:
if not getattr(task.driver, 'vendor', None):
raise exception.UnsupportedDriverExtension(
driver=task.node.driver,
extension='vendor interface')
vendor_iface = task.driver.vendor
try:
vendor_opts = vendor_iface.vendor_routes[driver_method]
vendor_func = vendor_opts['func']
except KeyError:
raise exception.InvalidParameterValue(
_('No handler for method %s') % driver_method)
http_method = http_method.upper()
if http_method not in vendor_opts['http_methods']:
raise exception.InvalidParameterValue(
_('The method %(method)s does not support HTTP %(http)s') %
{'method': driver_method, 'http': http_method})
vendor_iface.validate(task, method=driver_method,
http_method=http_method, **info)
# Inform the vendor method which HTTP method it was invoked with
info['http_method'] = http_method
# Invoke the vendor method accordingly with the mode
is_async = vendor_opts['async']
ret = None
if is_async:
task.spawn_after(self._spawn_worker, vendor_func, task, **info)
else:
ret = vendor_func(task, **info)
return {'return': ret,
'async': is_async,
'attach': vendor_opts['attach']}
@messaging.expected_exceptions(exception.NoFreeConductorWorker,
exception.InvalidParameterValue,
exception.MissingParameterValue,
exception.UnsupportedDriverExtension,
exception.DriverNotFound)
def driver_vendor_passthru(self, context, driver_name, driver_method,
http_method, info):
"""Handle top-level vendor actions.
RPC method which handles driver-level vendor passthru calls. These
calls don't require a node UUID and are executed on a random
conductor with the specified driver. If the method mode is
async the conductor will start background worker to perform
vendor action.
:param context: an admin context.
:param driver_name: name of the driver on which to call the method.
:param driver_method: name of the vendor method, for use by the driver.
:param http_method: the HTTP method used for the request.
:param info: user-supplied data to pass through to the driver.
:raises: MissingParameterValue if missing supplied info
:raises: InvalidParameterValue if supplied info is not valid.
:raises: UnsupportedDriverExtension if current driver does not have
vendor interface, if the vendor interface does not implement
driver-level vendor passthru or if the passthru method is
unsupported.
:raises: DriverNotFound if the supplied driver is not loaded.
:raises: NoFreeConductorWorker when there is no free worker to start
async task.
:returns: A dictionary containing:
:return: The response of the invoked vendor method
:async: Boolean value. Whether the method was invoked
asynchronously (True) or synchronously (False). When invoked
asynchronously the response will be always None.
:attach: Boolean value. Whether to attach the response of
the invoked vendor method to the HTTP response object (True)
or return it in the response body (False).
"""
# Any locking in a top-level vendor action will need to be done by the
# implementation, as there is little we could reasonably lock on here.
LOG.debug("RPC driver_vendor_passthru for driver %s." % driver_name)
driver = driver_factory.get_driver(driver_name)
if not getattr(driver, 'vendor', None):
raise exception.UnsupportedDriverExtension(
driver=driver_name,
extension='vendor interface')
try:
vendor_opts = driver.vendor.driver_routes[driver_method]
vendor_func = vendor_opts['func']
except KeyError:
raise exception.InvalidParameterValue(
_('No handler for method %s') % driver_method)
http_method = http_method.upper()
if http_method not in vendor_opts['http_methods']:
raise exception.InvalidParameterValue(
_('The method %(method)s does not support HTTP %(http)s') %
{'method': driver_method, 'http': http_method})
# Inform the vendor method which HTTP method it was invoked with
info['http_method'] = http_method
# Invoke the vendor method accordingly with the mode
is_async = vendor_opts['async']
ret = None
driver.vendor.driver_validate(method=driver_method, **info)
if is_async:
self._spawn_worker(vendor_func, context, **info)
else:
ret = vendor_func(context, **info)
return {'return': ret,
'async': is_async,
'attach': vendor_opts['attach']}
@messaging.expected_exceptions(exception.UnsupportedDriverExtension)
def get_node_vendor_passthru_methods(self, context, node_id):
"""Retrieve information about vendor methods of the given node.
:param context: an admin context.
:param node_id: the id or uuid of a node.
:returns: dictionary of <method name>:<method metadata> entries.
"""
LOG.debug("RPC get_node_vendor_passthru_methods called for node %s"
% node_id)
lock_purpose = 'listing vendor passthru methods'
with task_manager.acquire(context, node_id, shared=True,
purpose=lock_purpose) as task:
if not getattr(task.driver, 'vendor', None):
raise exception.UnsupportedDriverExtension(
driver=task.node.driver,
extension='vendor interface')
return get_vendor_passthru_metadata(
task.driver.vendor.vendor_routes)
@messaging.expected_exceptions(exception.UnsupportedDriverExtension,
exception.DriverNotFound)
def get_driver_vendor_passthru_methods(self, context, driver_name):
"""Retrieve information about vendor methods of the given driver.
:param context: an admin context.
:param driver_name: name of the driver.
:returns: dictionary of <method name>:<method metadata> entries.
"""
# Any locking in a top-level vendor action will need to be done by the
# implementation, as there is little we could reasonably lock on here.
LOG.debug("RPC get_driver_vendor_passthru_methods for driver %s"
% driver_name)
driver = driver_factory.get_driver(driver_name)
if not getattr(driver, 'vendor', None):
raise exception.UnsupportedDriverExtension(
driver=driver_name,
extension='vendor interface')
return get_vendor_passthru_metadata(driver.vendor.driver_routes)
@messaging.expected_exceptions(exception.NoFreeConductorWorker,
exception.NodeLocked,
exception.NodeInMaintenance,
exception.InstanceDeployFailure,
exception.InvalidStateRequested)
def do_node_deploy(self, context, node_id, rebuild=False,
configdrive=None):
"""RPC method to initiate deployment to a node.
Initiate the deployment of a node. Validations are done
synchronously and the actual deploy work is performed in
background (asynchronously).
:param context: an admin context.
:param node_id: the id or uuid of a node.
:param rebuild: True if this is a rebuild request. A rebuild will
recreate the instance on the same node, overwriting
all disk. The ephemeral partition, if it exists, can
optionally be preserved.
:param configdrive: Optional. A gzipped and base64 encoded configdrive.
:raises: InstanceDeployFailure
:raises: NodeInMaintenance if the node is in maintenance mode.
:raises: NoFreeConductorWorker when there is no free worker to start
async task.
:raises: InvalidStateRequested when the requested state is not a valid
target from the current state.
"""
LOG.debug("RPC do_node_deploy called for node %s." % node_id)
# NOTE(comstud): If the _sync_power_states() periodic task happens
# to have locked this node, we'll fail to acquire the lock. The
# client should perhaps retry in this case unless we decide we
# want to add retries or extra synchronization here.
with task_manager.acquire(context, node_id, shared=False,
purpose='node deployment') as task:
node = task.node
if node.maintenance:
raise exception.NodeInMaintenance(op=_('provisioning'),
node=node.uuid)
if rebuild:
event = 'rebuild'
# Note(gilliard) Clear these to force the driver to
# check whether they have been changed in glance
# NOTE(vdrok): If image_source is not from Glance we should
# not clear kernel and ramdisk as they're input manually
if glance_utils.is_glance_image(
node.instance_info.get('image_source')):
instance_info = node.instance_info
instance_info.pop('kernel', None)
instance_info.pop('ramdisk', None)
node.instance_info = instance_info
else:
event = 'deploy'
driver_internal_info = node.driver_internal_info
# Infer the image type to make sure the deploy driver
# validates only the necessary variables for different
# image types.
# NOTE(sirushtim): The iwdi variable can be None. It's up to
# the deploy driver to validate this.
iwdi = images.is_whole_disk_image(context, node.instance_info)
driver_internal_info['is_whole_disk_image'] = iwdi
node.driver_internal_info = driver_internal_info
node.save()
try:
task.driver.power.validate(task)
task.driver.deploy.validate(task)
except (exception.InvalidParameterValue,
exception.MissingParameterValue) as e:
raise exception.InstanceDeployFailure(
_("RPC do_node_deploy failed to validate deploy or "
"power info for node %(node_uuid)s. Error: %(msg)s") %
{'node_uuid': node.uuid, 'msg': e})
LOG.debug("do_node_deploy Calling event: %(event)s for node: "
"%(node)s", {'event': event, 'node': node.uuid})
try:
task.process_event(
event,
callback=self._spawn_worker,
call_args=(do_node_deploy, task, self.conductor.id,
configdrive),
err_handler=utils.provisioning_error_handler)
except exception.InvalidState:
raise exception.InvalidStateRequested(
action=event, node=task.node.uuid,
state=task.node.provision_state)
@messaging.expected_exceptions(exception.NoFreeConductorWorker,
exception.NodeLocked,
exception.InstanceDeployFailure,
exception.InvalidStateRequested)
def do_node_tear_down(self, context, node_id):
"""RPC method to tear down an existing node deployment.
Validate driver specific information synchronously, and then
spawn a background worker to tear down the node asynchronously.
:param context: an admin context.
:param node_id: the id or uuid of a node.
:raises: InstanceDeployFailure
:raises: NoFreeConductorWorker when there is no free worker to start
async task
:raises: InvalidStateRequested when the requested state is not a valid
target from the current state.
"""
LOG.debug("RPC do_node_tear_down called for node %s." % node_id)
with task_manager.acquire(context, node_id, shared=False,
purpose='node tear down') as task:
try:
# NOTE(ghe): Valid power driver values are needed to perform
# a tear-down. Deploy info is useful to purge the cache but not
# required for this method.
task.driver.power.validate(task)
except (exception.InvalidParameterValue,
exception.MissingParameterValue) as e:
raise exception.InstanceDeployFailure(_(
"Failed to validate power driver interface. "
"Can not delete instance. Error: %(msg)s") % {'msg': e})
try:
task.process_event(
'delete',
callback=self._spawn_worker,
call_args=(self._do_node_tear_down, task),
err_handler=utils.provisioning_error_handler)
except exception.InvalidState:
raise exception.InvalidStateRequested(
action='delete', node=task.node.uuid,
state=task.node.provision_state)
def _do_node_tear_down(self, task):
"""Internal RPC method to tear down an existing node deployment."""
node = task.node
try:
task.driver.deploy.clean_up(task)
task.driver.deploy.tear_down(task)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.exception(_LE('Error in tear_down of node %(node)s: '
'%(err)s'),
{'node': node.uuid, 'err': e})
node.last_error = _("Failed to tear down. Error: %s") % e
task.process_event('error')
else:
# NOTE(deva): When tear_down finishes, the deletion is done,
# cleaning will start next
LOG.info(_LI('Successfully unprovisioned node %(node)s with '
'instance %(instance)s.'),
{'node': node.uuid, 'instance': node.instance_uuid})
finally:
# NOTE(deva): there is no need to unset conductor_affinity
# because it is a reference to the most recent conductor which
# deployed a node, and does not limit any future actions.
# But we do need to clear the instance-related fields.
node.instance_info = {}
node.instance_uuid = None
driver_internal_info = node.driver_internal_info
driver_internal_info.pop('instance', None)
node.driver_internal_info = driver_internal_info
node.save()
# Begin cleaning
try:
task.process_event('clean')
except exception.InvalidState:
raise exception.InvalidStateRequested(
action='clean', node=node.uuid,
state=node.provision_state)
self._do_node_clean(task)
def _get_node_next_clean_steps(self, task, skip_current_step=True):
"""Get the task's node's next clean steps.
This determines what the next (remaining) clean steps are, and
returns the index into the clean steps list that corresponds to the
next clean step. The remaining clean steps are determined as follows:
* If no clean steps have been started yet, all the clean steps
must be executed
* If skip_current_step is False, the remaining clean steps start
with the current clean step. Otherwise, the remaining clean steps
start with the clean step after the current one.
All the clean steps for an automated or manual cleaning are in
node.driver_internal_info['clean_steps']. node.clean_step is the
current clean step that was just executed (or None, {} if no steps
have been executed yet). node.driver_internal_info['clean_step_index']
is the index into the clean steps list (or None, doesn't exist if no
steps have been executed yet) and corresponds to node.clean_step.
:param task: A TaskManager object
:param skip_current_step: True to skip the current clean step; False to
include it.
:raises: NodeCleaningFailure if an internal error occurred when
getting the next clean steps
:returns: index of the next clean step; None if there are no clean
steps to execute.
"""
node = task.node
if not node.clean_step:
# first time through, all steps need to be done. Return the
# index of the first step in the list.
return 0
ind = None
if 'clean_step_index' in node.driver_internal_info:
ind = node.driver_internal_info['clean_step_index']
else:
# TODO(rloo). driver_internal_info['clean_step_index'] was
# added in Mitaka. We need to maintain backwards compatibility
# so this uses the original code to get the index of the current
# step. This will be deleted in the Newton cycle.
try:
next_steps = node.driver_internal_info['clean_steps']
ind = next_steps.index(node.clean_step)
except (KeyError, ValueError):
msg = (_('Node %(node)s got an invalid last step for '
'%(state)s: %(step)s.') %
{'node': node.uuid, 'step': node.clean_step,
'state': node.provision_state})
LOG.exception(msg)
utils.cleaning_error_handler(task, msg)
raise exception.NodeCleaningFailure(node=node.uuid,
reason=msg)
if ind is None:
return None
if skip_current_step:
ind += 1
if ind >= len(node.driver_internal_info['clean_steps']):
# no steps left to do
ind = None
return ind
@messaging.expected_exceptions(exception.InvalidParameterValue,
exception.InvalidStateRequested,
exception.NodeInMaintenance,
exception.NodeLocked,
exception.NoFreeConductorWorker)
def do_node_clean(self, context, node_id, clean_steps):
"""RPC method to initiate manual cleaning.
:param context: an admin context.
:param node_id: the ID or UUID of a node.
:param clean_steps: an ordered list of clean steps that will be
performed on the node. A clean step is a dictionary with required
keys 'interface' and 'step', and optional key 'args'. If
specified, the 'args' arguments are passed to the clean step
method.::
{ 'interface': <driver_interface>,
'step': <name_of_clean_step>,
'args': {<arg1>: <value1>, ..., <argn>: <valuen>} }
For example (this isn't a real example, this clean step
doesn't exist)::
{ 'interface': deploy',
'step': 'upgrade_firmware',
'args': {'force': True} }
:raises: InvalidParameterValue if power validation fails.
:raises: InvalidStateRequested if the node is not in manageable state.
:raises: NodeLocked if node is locked by another conductor.
:raises: NoFreeConductorWorker when there is no free worker to start
async task.
"""
with task_manager.acquire(context, node_id, shared=False,
purpose='node manual cleaning') as task:
node = task.node
if node.maintenance:
raise exception.NodeInMaintenance(op=_('cleaning'),
node=node.uuid)
# NOTE(rloo): _do_node_clean() will also make a similar call
# to validate the power, but we are doing it again here so that
# the user gets immediate feedback of any issues. This behaviour
# (of validating) is consistent with other methods like
# self.do_node_deploy().
try:
task.driver.power.validate(task)
except exception.InvalidParameterValue as e:
msg = (_('RPC do_node_clean failed to validate power info.'
' Cannot clean node %(node)s. Error: %(msg)s') %
{'node': node.uuid, 'msg': e})
raise exception.InvalidParameterValue(msg)
try:
task.process_event(
'clean',
callback=self._spawn_worker,
call_args=(self._do_node_clean, task, clean_steps),
err_handler=utils.provisioning_error_handler,
target_state=states.MANAGEABLE)
except exception.InvalidState:
raise exception.InvalidStateRequested(
action='manual clean', node=node.uuid,
state=node.provision_state)
def continue_node_clean(self, context, node_id):
"""RPC method to continue cleaning a node.
This is useful for cleaning tasks that are async. When they complete,
they call back via RPC, a new worker and lock are set up, and cleaning
continues. This can also be used to resume cleaning on take_over.
:param context: an admin context.
:param node_id: the id or uuid of a node.
:raises: InvalidStateRequested if the node is not in CLEANWAIT state
:raises: NoFreeConductorWorker when there is no free worker to start
async task
:raises: NodeLocked if node is locked by another conductor.
:raises: NodeNotFound if the node no longer appears in the database
:raises: NodeCleaningFailure if an internal error occurred when
getting the next clean steps
"""
LOG.debug("RPC continue_node_clean called for node %s.", node_id)
with task_manager.acquire(context, node_id, shared=False,
purpose='continue node cleaning') as task:
node = task.node
if node.target_provision_state == states.MANAGEABLE:
target_state = states.MANAGEABLE
else:
target_state = None
# TODO(lucasagomes): CLEANING here for backwards compat
# with previous code, otherwise nodes in CLEANING when this
# is deployed would fail. Should be removed once the Mitaka
# release starts.
if node.provision_state not in (states.CLEANWAIT,
states.CLEANING):
raise exception.InvalidStateRequested(_(
'Cannot continue cleaning on %(node)s, node is in '
'%(state)s state, should be %(clean_state)s') %
{'node': node.uuid,
'state': node.provision_state,
'clean_state': states.CLEANWAIT})
info = node.driver_internal_info
try:
skip_current_step = info.pop('skip_current_clean_step')
except KeyError:
skip_current_step = True
else:
node.driver_internal_info = info
node.save()
next_step_index = self._get_node_next_clean_steps(
task, skip_current_step=skip_current_step)
# If this isn't the final clean step in the cleaning operation
# and it is flagged to abort after the clean step that just
# finished, we abort the cleaning operation.
if node.clean_step.get('abort_after'):
step_name = node.clean_step['step']
if next_step_index is not None:
LOG.debug('The cleaning operation for node %(node)s was '
'marked to be aborted after step "%(step)s '
'completed. Aborting now that it has completed.',
{'node': task.node.uuid, 'step': step_name})
task.process_event(
'abort',
callback=self._spawn_worker,
call_args=(self._do_node_clean_abort,
task, step_name),
err_handler=utils.provisioning_error_handler,
target_state=target_state)
return
LOG.debug('The cleaning operation for node %(node)s was '
'marked to be aborted after step "%(step)s" '
'completed. However, since there are no more '
'clean steps after this, the abort is not going '
'to be done.', {'node': node.uuid,
'step': step_name})
# TODO(lucasagomes): This conditional is here for backwards
# compat with previous code. Should be removed once the Mitaka
# release starts.
if node.provision_state == states.CLEANWAIT:
task.process_event('resume', target_state=target_state)
task.set_spawn_error_hook(utils.spawn_cleaning_error_handler,
task.node)
task.spawn_after(
self._spawn_worker,
self._do_next_clean_step,
task, next_step_index)
def _do_node_clean(self, task, clean_steps=None):
"""Internal RPC method to perform cleaning of a node.
:param task: a TaskManager instance with an exclusive lock on its node
:param clean_steps: For a manual clean, the list of clean steps to
perform. Is None For automated cleaning (default).
For more information, see the clean_steps parameter
of :func:`ConductorManager.do_node_clean`.
"""
node = task.node
manual_clean = clean_steps is not None
clean_type = 'manual' if manual_clean else 'automated'
LOG.debug('Starting %(type)s cleaning for node %(node)s',
{'type': clean_type, 'node': node.uuid})
if not manual_clean and not CONF.conductor.automated_clean:
# Skip cleaning, move to AVAILABLE.
node.clean_step = None
node.save()
task.process_event('done')
LOG.info(_LI('Automated cleaning is disabled, node %s has been '
'successfully moved to AVAILABLE state.'), node.uuid)
return
try:
# NOTE(ghe): Valid power driver values are needed to perform
# a cleaning.
task.driver.power.validate(task)
except (exception.InvalidParameterValue,
exception.MissingParameterValue) as e:
msg = (_('Failed to validate power driver interface. '
'Can not clean node %(node)s. Error: %(msg)s') %
{'node': node.uuid, 'msg': e})
return utils.cleaning_error_handler(task, msg)
if manual_clean:
info = node.driver_internal_info
info['clean_steps'] = clean_steps
node.driver_internal_info = info
node.save()
# Allow the deploy driver to set up the ramdisk again (necessary for
# IPA cleaning)
try:
prepare_result = task.driver.deploy.prepare_cleaning(task)
except Exception as e:
msg = (_('Failed to prepare node %(node)s for cleaning: %(e)s')
% {'node': node.uuid, 'e': e})
LOG.exception(msg)
return utils.cleaning_error_handler(task, msg)
# TODO(lucasagomes): Should be removed once the Mitaka release starts
if prepare_result == states.CLEANING:
LOG.warning(_LW('Returning CLEANING for asynchronous prepare '
'cleaning has been deprecated. Please use '
'CLEANWAIT instead.'))
prepare_result = states.CLEANWAIT
if prepare_result == states.CLEANWAIT:
# Prepare is asynchronous, the deploy driver will need to
# set node.driver_internal_info['clean_steps'] and
# node.clean_step and then make an RPC call to
# continue_node_cleaning to start cleaning.
# For manual cleaning, the target provision state is MANAGEABLE,
# whereas for automated cleaning, it is AVAILABLE (the default).
target_state = states.MANAGEABLE if manual_clean else None
task.process_event('wait', target_state=target_state)
return
try:
utils.set_node_cleaning_steps(task)
except (exception.InvalidParameterValue,
exception.NodeCleaningFailure) as e:
msg = (_('Cannot clean node %(node)s. Error: %(msg)s')
% {'node': node.uuid, 'msg': e})
return utils.cleaning_error_handler(task, msg)
steps = node.driver_internal_info.get('clean_steps', [])
step_index = 0 if steps else None
self._do_next_clean_step(task, step_index)
def _do_next_clean_step(self, task, step_index):
"""Do cleaning, starting from the specified clean step.
:param task: a TaskManager instance with an exclusive lock
:param step_index: The first clean step in the list to execute. This
is the index (from 0) into the list of clean steps in the node's
driver_internal_info['clean_steps']. Is None if there are no steps
to execute.
"""
node = task.node
# For manual cleaning, the target provision state is MANAGEABLE,
# whereas for automated cleaning, it is AVAILABLE.
manual_clean = node.target_provision_state == states.MANAGEABLE
driver_internal_info = node.driver_internal_info
if step_index is None:
steps = []
else:
steps = driver_internal_info['clean_steps'][step_index:]
LOG.info(_LI('Executing %(state)s on node %(node)s, remaining steps: '
'%(steps)s'), {'node': node.uuid, 'steps': steps,
'state': node.provision_state})
# Execute each step until we hit an async step or run out of steps
for ind, step in enumerate(steps):
# Save which step we're about to start so we can restart
# if necessary
node.clean_step = step
driver_internal_info['clean_step_index'] = step_index + ind
node.driver_internal_info = driver_internal_info
node.save()
interface = getattr(task.driver, step.get('interface'))
LOG.info(_LI('Executing %(step)s on node %(node)s'),
{'step': step, 'node': node.uuid})
try:
result = interface.execute_clean_step(task, step)
except Exception as e:
msg = (_('Node %(node)s failed step %(step)s: '
'%(exc)s') %
{'node': node.uuid, 'exc': e,