-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathnode.py
More file actions
3341 lines (2879 loc) · 142 KB
/
node.py
File metadata and controls
3341 lines (2879 loc) · 142 KB
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
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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.
import copy
import datetime
from http import client as http_client
import json
import urllib.parse
import jsonschema
from jsonschema import exceptions as json_schema_exc
from oslo_log import log
from oslo_utils import strutils
from oslo_utils import uuidutils
import pecan
from pecan import rest
from ironic import api
from ironic.api.controllers import link
from ironic.api.controllers.v1 import allocation
from ironic.api.controllers.v1 import bios
from ironic.api.controllers.v1 import collection
from ironic.api.controllers.v1 import firmware
from ironic.api.controllers.v1 import notification_utils as notify
from ironic.api.controllers.v1 import port
from ironic.api.controllers.v1 import portgroup
from ironic.api.controllers.v1 import utils as api_utils
from ironic.api.controllers.v1 import versions
from ironic.api.controllers.v1 import volume
from ironic.api import method
from ironic.common import args
from ironic.common import boot_devices
from ironic.common import boot_modes
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common import image_publisher
from ironic.common import metrics_utils
from ironic.common import policy
from ironic.common import state_machine
from ironic.common import states as ir_states
from ironic.conductor import steps as conductor_steps
import ironic.conf
from ironic.drivers import base as driver_base
from ironic.drivers.modules import inspect_utils
from ironic import objects
CONF = ironic.conf.CONF
LOG = log.getLogger(__name__)
# TODO(TheJulia): We *really* need to just have *one* schema.
_STEPS_SCHEMA = {
"$schema": "http://json-schema.org/schema#",
"title": "Steps schema",
"type": "array",
# list of clean steps
"items": {
"type": "object",
# args is optional
"required": ["interface", "step"],
"properties": {
"interface": {
"description": "driver interface",
"enum": list(conductor_steps.CLEANING_INTERFACE_PRIORITY)
# interface value must be one of the valid interfaces
},
"step": {
"description": "name of clean step",
"type": "string",
"minLength": 1
},
"args": {
"description": "additional args",
"type": "object",
"properties": {}
},
'order': {'anyOf': [
{'type': 'integer', 'minimum': 0},
{'type': 'string', 'minLength': 1, 'pattern': '^[0-9]+$'}
]},
"execute_on_child_nodes": {
"description": "Boolean if the step should be executed "
"on child nodes.",
"type": "boolean",
},
"limit_child_node_execution": {
"description": "List of nodes upon which to execute child "
"node steps on.",
"type": "array",
}
},
# interface, step and args are the only expected keys
"additionalProperties": False
}
}
_DEPLOY_STEPS_SCHEMA = {
"$schema": "http://json-schema.org/schema#",
"title": "Deploy steps schema",
"type": "array",
"items": api_utils.DEPLOY_STEP_SCHEMA
}
METRICS = metrics_utils.get_metrics_logger(__name__)
# Vendor information for node's driver:
# key = driver name;
# value = dictionary of node vendor methods of that driver:
# key = method name.
# value = dictionary with the metadata of that method.
# NOTE(lucasagomes). This is cached for the lifetime of the API
# service. If one or more conductor services are restarted with new driver
# versions, the API service should be restarted.
_VENDOR_METHODS = {}
_DEFAULT_RETURN_FIELDS = ['instance_uuid', 'maintenance', 'power_state',
'provision_state', 'uuid', 'name']
# States where calling do_provisioning_action makes sense
PROVISION_ACTION_STATES = (ir_states.VERBS['manage'],
ir_states.VERBS['provide'],
ir_states.VERBS['abort'],
ir_states.VERBS['adopt'],
ir_states.VERBS['unhold'],
ir_states.VERBS['service'])
_NODES_CONTROLLER_RESERVED_WORDS = None
ALLOWED_TARGET_POWER_STATES = (ir_states.POWER_ON,
ir_states.POWER_OFF,
ir_states.REBOOT,
ir_states.SOFT_REBOOT,
ir_states.SOFT_POWER_OFF)
ALLOWED_TARGET_BOOT_MODES = (boot_modes.LEGACY_BIOS,
boot_modes.UEFI)
_NODE_DESCRIPTION_MAX_LENGTH = 4096
_NETWORK_DATA_SCHEMA = None
def network_data_schema():
global _NETWORK_DATA_SCHEMA
if _NETWORK_DATA_SCHEMA is None:
with open(CONF.api.network_data_schema) as fl:
_NETWORK_DATA_SCHEMA = json.load(fl)
return _NETWORK_DATA_SCHEMA
def node_schema():
network_data = network_data_schema()
return {
'$schema': 'http://json-schema.org/draft-07/schema#',
'type': 'object',
'properties': {
'automated_clean': {'type': ['string', 'boolean', 'null']},
'bios_interface': {'type': ['string', 'null']},
'boot_interface': {'type': ['string', 'null']},
'boot_mode': {'type': ['string', 'null']},
'chassis_uuid': {'type': ['string', 'null']},
'conductor_group': {'type': ['string', 'null']},
'console_enabled': {'type': ['string', 'boolean', 'null']},
'console_interface': {'type': ['string', 'null']},
'deploy_interface': {'type': ['string', 'null']},
'description': {'type': ['string', 'null'],
'maxLength': _NODE_DESCRIPTION_MAX_LENGTH},
'disable_power_off': {'type': ['string', 'boolean', 'null']},
'driver': {'type': 'string'},
'driver_info': {'type': ['object', 'null']},
'extra': {'type': ['object', 'null']},
'firmware_interface': {'type': ['string', 'null']},
'inspect_interface': {'type': ['string', 'null']},
'instance_info': {'type': ['object', 'null']},
'instance_name': {'type': ['string', 'null'], 'minLength': 1,
'maxLength': 255},
'instance_uuid': {'type': ['string', 'null']},
'lessee': {'type': ['string', 'null']},
'management_interface': {'type': ['string', 'null']},
'maintenance': {'type': ['string', 'boolean', 'null']},
'name': {'type': ['string', 'null']},
'network_data': {'anyOf': [
{'type': 'null'},
{'type': 'object', 'additionalProperties': False},
network_data
]},
'network_interface': {'type': ['string', 'null']},
'owner': {'type': ['string', 'null']},
'parent_node': {'type': ['string', 'null'], 'maxLength': 36},
'power_interface': {'type': ['string', 'null']},
'properties': {'type': ['object', 'null']},
'raid_interface': {'type': ['string', 'null']},
'rescue_interface': {'type': ['string', 'null']},
'resource_class': {'type': ['string', 'null'], 'maxLength': 80},
'retired': {'type': ['string', 'boolean', 'null']},
'retired_reason': {'type': ['string', 'null']},
'secure_boot': {'type': ['string', 'boolean', 'null']},
'shard': {'type': ['string', 'null']},
'storage_interface': {'type': ['string', 'null']},
'uuid': {'type': ['string', 'null']},
'vendor_interface': {'type': ['string', 'null']},
},
'required': ['driver'],
'additionalProperties': False,
'definitions': network_data.get('definitions', {})
}
def node_patch_schema():
node_patch = copy.deepcopy(node_schema())
# add schema for patchable fields
node_patch['properties']['protected'] = {
'type': ['string', 'boolean', 'null']}
node_patch['properties']['protected_reason'] = {
'type': ['string', 'null']}
return node_patch
NODE_VALIDATE_EXTRA = args.dict_valid(
automated_clean=args.boolean,
chassis_uuid=args.uuid,
console_enabled=args.boolean,
disable_power_off=args.boolean,
instance_uuid=args.uuid,
protected=args.boolean,
maintenance=args.boolean,
retired=args.boolean,
uuid=args.uuid,
)
_NODE_VALIDATOR = None
_NODE_PATCH_VALIDATOR = None
def node_validator(name, value):
global _NODE_VALIDATOR
if _NODE_VALIDATOR is None:
_NODE_VALIDATOR = args.and_valid(
args.schema(node_schema()),
NODE_VALIDATE_EXTRA
)
return _NODE_VALIDATOR(name, value)
def node_patch_validator(name, value):
global _NODE_PATCH_VALIDATOR
if _NODE_PATCH_VALIDATOR is None:
_NODE_PATCH_VALIDATOR = args.and_valid(
args.schema(node_patch_schema()),
NODE_VALIDATE_EXTRA
)
return _NODE_PATCH_VALIDATOR(name, value)
PATCH_ALLOWED_FIELDS = [
'automated_clean',
'bios_interface',
'boot_interface',
'chassis_uuid',
'conductor_group',
'console_interface',
'deploy_interface',
'description',
'disable_power_off',
'driver',
'driver_info',
'extra',
'inspect_interface',
'instance_info',
'instance_name',
'instance_uuid',
'lessee',
'maintenance',
'management_interface',
'name',
'network_data',
'network_interface',
'owner',
'power_interface',
'properties',
'protected',
'protected_reason',
'raid_interface',
'rescue_interface',
'resource_class',
'retired',
'retired_reason',
'shard',
'storage_interface',
'vendor_interface',
'parent_node',
'firmware_interface'
]
TRAITS_SCHEMA = {
'type': 'object',
'properties': {
'traits': {
'type': 'array',
'items': api_utils.TRAITS_SCHEMA
},
},
'additionalProperties': False,
}
VIF_VALIDATOR = args.and_valid(
args.schema({
'type': 'object',
'properties': {
'id': {'type': 'string'},
},
'required': ['id'],
'additionalProperties': True,
}),
args.dict_valid(id=args.uuid_or_name)
)
VMEDIA_ATTACH_VALIDATOR = args.schema({
'type': 'object',
'properties': {
'device_type': {
'type': 'string',
'enum': boot_devices.VMEDIA_DEVICES,
},
'image_url': {'type': 'string'},
'image_download_source': {
'type': 'string',
'enum': ['http', 'local', 'swift'],
},
# TODO(dtantsur): these are useful additions in the future, but the
# ISO image code does not support them.
# 'username': {'type': 'string'},
# 'password': {'type': 'string'},
# 'insecure': {'type': 'boolean'},
},
'required': ['device_type', 'image_url'],
'additionalProperties': False,
})
def get_nodes_controller_reserved_names():
global _NODES_CONTROLLER_RESERVED_WORDS
if _NODES_CONTROLLER_RESERVED_WORDS is None:
_NODES_CONTROLLER_RESERVED_WORDS = (
api_utils.get_controller_reserved_names(NodesController))
return _NODES_CONTROLLER_RESERVED_WORDS
def hide_fields_in_newer_versions(obj):
"""This method hides fields that were added in newer API versions.
Certain node fields were introduced at certain API versions.
These fields are only made available when the request's API version
matches or exceeds the versions when these fields were introduced.
"""
for field in api_utils.disallowed_fields():
obj.pop(field, None)
def reject_fields_in_newer_versions(obj):
"""When creating an object, reject fields that appear in newer versions."""
for field in api_utils.disallowed_fields():
if field == 'conductor_group':
# NOTE(jroll) this is special-cased to "" and not Unset,
# because it is used in hash ring calculations
empty_value = ''
elif field == 'name' and obj.get('name') is None:
# NOTE(dtantsur): for some reason we allow specifying name=None
# explicitly even in old API versions..
continue
else:
empty_value = None
if obj.get(field, empty_value) != empty_value:
LOG.debug('Field %(field)s is not acceptable in version %(ver)s',
{'field': field, 'ver': api.request.version})
raise exception.NotAcceptable()
def reject_patch_in_newer_versions(patch):
for field in api_utils.disallowed_fields():
value = api_utils.get_patch_values(patch, '/%s' % field)
if value:
LOG.debug('Field %(field)s is not acceptable in version %(ver)s',
{'field': field, 'ver': api.request.version})
raise exception.NotAcceptable()
def update_state_in_older_versions(obj):
"""Change provision state names for API backwards compatibility.
:param obj: The dict being returned to the API client that is
to be updated by this method.
"""
# if requested version is < 1.2, convert AVAILABLE to the old NOSTATE
if (api.request.version.minor < versions.MINOR_2_AVAILABLE_STATE
and obj.get('provision_state') == ir_states.AVAILABLE):
obj['provision_state'] = ir_states.NOSTATE
# if requested version < 1.39, convert INSPECTWAIT to INSPECTING
if (not api_utils.allow_inspect_wait_state()
and obj.get('provision_state') == ir_states.INSPECTWAIT):
obj['provision_state'] = ir_states.INSPECTING
def validate_network_data(network_data):
"""Validates node network_data field.
This method validates network data configuration against JSON
schema.
:param network_data: a network_data field to validate
:raises: Invalid if network data is not schema-compliant
"""
try:
jsonschema.validate(network_data, network_data_schema())
except json_schema_exc.ValidationError as e:
# NOTE: Even though e.message is deprecated in general, it is
# said in jsonschema documentation to use this still.
msg = _("Invalid network_data: %s ") % e.message
raise exception.Invalid(msg)
class GetNodeAndTopicMixin:
def _get_node_and_topic(self, policy_name):
rpc_node = api_utils.check_node_policy_and_retrieve(
policy_name, self.node_ident)
try:
return rpc_node, api.request.rpcapi.get_topic_for(rpc_node)
except exception.NoValidHost as e:
e.code = http_client.BAD_REQUEST
raise
class BootDeviceController(rest.RestController):
_custom_actions = {
'supported': ['GET'],
}
def _get_boot_device(self, rpc_node, supported=False):
"""Get the current boot device or a list of supported devices.
:param rpc_node: RPC Node object.
:param supported: Boolean value. If true return a list of
supported boot devices, if false return the
current boot device. Default: False.
:returns: The current boot device or a list of the supported
boot devices.
"""
topic = api.request.rpcapi.get_topic_for(rpc_node)
if supported:
return api.request.rpcapi.get_supported_boot_devices(
api.request.context, rpc_node.uuid, topic)
else:
return api.request.rpcapi.get_boot_device(api.request.context,
rpc_node.uuid, topic)
@METRICS.timer('BootDeviceController.put')
@method.expose(status_code=http_client.NO_CONTENT)
@args.validate(node_ident=args.uuid_or_name, boot_device=args.string,
persistent=args.boolean)
def put(self, node_ident, boot_device, persistent=False):
"""Set the boot device for a node.
Set the boot device to use on next reboot of the node.
:param node_ident: the UUID or logical name of a node.
:param boot_device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if the boot device will
persist to all future boots, False if not.
Default: False.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:set_boot_device', node_ident)
topic = api.request.rpcapi.get_topic_for(rpc_node)
api.request.rpcapi.set_boot_device(api.request.context,
rpc_node.uuid,
boot_device,
persistent=persistent,
topic=topic)
@METRICS.timer('BootDeviceController.get')
@method.expose()
@args.validate(node_ident=args.uuid_or_name)
def get(self, node_ident):
"""Get the current boot device for a node.
:param node_ident: the UUID or logical name of a node.
:returns: a json object containing:
:boot_device: the boot device, one of
:mod:`ironic.common.boot_devices` or None if it is unknown.
:persistent: Whether the boot device will persist to all
future boots or not, None if it is unknown.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:get_boot_device', node_ident)
return self._get_boot_device(rpc_node)
@METRICS.timer('BootDeviceController.supported')
@method.expose()
@args.validate(node_ident=args.uuid_or_name)
def supported(self, node_ident):
"""Get a list of the supported boot devices.
:param node_ident: the UUID or logical name of a node.
:returns: A json object with the list of supported boot
devices.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:get_boot_device', node_ident)
boot_devices = self._get_boot_device(rpc_node, supported=True)
return {'supported_boot_devices': boot_devices}
class IndicatorAtComponent(object):
def __init__(self, **kwargs):
name = kwargs.get('name')
component = kwargs.get('component')
unique_name = kwargs.get('unique_name')
if name and component:
self.unique_name = name + '@' + component
self.name = name
self.component = component
elif unique_name:
try:
index = unique_name.index('@')
except ValueError:
raise exception.InvalidParameterValue(
_('Malformed indicator name "%s"') % unique_name)
self.component = unique_name[index + 1:]
self.name = unique_name[:index]
self.unique_name = unique_name
else:
raise exception.MissingParameterValue(
_('Missing indicator name "%s"'))
def indicator_convert_with_links(node_uuid, rpc_component, rpc_name,
**rpc_fields):
"""Add links to the indicator."""
url = api.request.public_url
return {
'name': rpc_name,
'component': rpc_component,
'readonly': rpc_fields.get('readonly', True),
'states': rpc_fields.get('states', []),
'links': [
link.make_link(
'self', url, 'nodes',
'%s/management/indicators/%s' % (
node_uuid, rpc_name)),
link.make_link(
'bookmark', url, 'nodes',
'%s/management/indicators/%s' % (
node_uuid, rpc_name),
bookmark=True)
]
}
def indicator_list_from_dict(node_ident, indicators):
indicator_list = []
for component, names in indicators.items():
for name, fields in names.items():
indicator_at_component = IndicatorAtComponent(
component=component, name=name)
indicator = indicator_convert_with_links(
node_ident, component, indicator_at_component.unique_name,
**fields)
indicator_list.append(indicator)
return {'indicators': indicator_list}
class IndicatorController(rest.RestController):
@METRICS.timer('IndicatorController.put')
@method.expose(status_code=http_client.NO_CONTENT)
@args.validate(node_ident=args.uuid_or_name, indicator=args.string,
state=args.string)
def put(self, node_ident, indicator, state):
"""Set node hardware component indicator to the desired state.
:param node_ident: the UUID or logical name of a node.
:param indicator: Indicator ID (as reported by
`get_supported_indicators`).
:param state: Indicator state, one of
mod:`ironic.common.indicator_states`.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:set_indicator_state',
node_ident)
topic = pecan.request.rpcapi.get_topic_for(rpc_node)
indicator_at_component = IndicatorAtComponent(unique_name=indicator)
pecan.request.rpcapi.set_indicator_state(
pecan.request.context, rpc_node.uuid,
indicator_at_component.component, indicator_at_component.name,
state, topic=topic)
@METRICS.timer('IndicatorController.get_one')
@method.expose()
@args.validate(node_ident=args.uuid_or_name, indicator=args.string)
def get_one(self, node_ident, indicator):
"""Get node hardware component indicator and its state.
:param node_ident: the UUID or logical name of a node.
:param indicator: Indicator ID (as reported by
`get_supported_indicators`).
:returns: a dict with the "state" key and one of
mod:`ironic.common.indicator_states` as a value.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:get_indicator_state',
node_ident)
topic = pecan.request.rpcapi.get_topic_for(rpc_node)
indicator_at_component = IndicatorAtComponent(unique_name=indicator)
state = pecan.request.rpcapi.get_indicator_state(
pecan.request.context, rpc_node.uuid,
indicator_at_component.component, indicator_at_component.name,
topic=topic)
return {'state': state}
@METRICS.timer('IndicatorController.get_all')
@method.expose()
@args.validate(node_ident=args.uuid_or_name)
def get_all(self, node_ident, **kwargs):
"""Get node hardware components and their indicators.
:param node_ident: the UUID or logical name of a node.
:returns: A json object of hardware components
(:mod:`ironic.common.components`) as keys with indicator IDs
(from `get_supported_indicators`) as values.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:get_indicator_state',
node_ident)
topic = pecan.request.rpcapi.get_topic_for(rpc_node)
indicators = pecan.request.rpcapi.get_supported_indicators(
pecan.request.context, rpc_node.uuid, topic=topic)
return indicator_list_from_dict(
node_ident, indicators)
class InjectNmiController(rest.RestController):
@METRICS.timer('InjectNmiController.put')
@method.expose(status_code=http_client.NO_CONTENT)
@args.validate(node_ident=args.uuid_or_name)
def put(self, node_ident):
"""Inject NMI for a node.
Inject NMI (Non Maskable Interrupt) for a node immediately.
:param node_ident: the UUID or logical name of a node.
:raises: NotFound if requested version of the API doesn't support
inject nmi.
:raises: HTTPForbidden if the policy is not authorized.
:raises: NodeNotFound if the node is not found.
:raises: NodeLocked if the node is locked by another conductor.
:raises: UnsupportedDriverExtension if the node's driver doesn't
support management or management.inject_nmi.
:raises: InvalidParameterValue when the wrong driver info is
specified or an invalid boot device is specified.
:raises: MissingParameterValue if missing supplied info.
"""
if not api_utils.allow_inject_nmi():
raise exception.NotFound()
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:inject_nmi', node_ident)
topic = api.request.rpcapi.get_topic_for(rpc_node)
api.request.rpcapi.inject_nmi(api.request.context,
rpc_node.uuid,
topic=topic)
class NodeManagementController(rest.RestController):
boot_device = BootDeviceController()
"""Expose boot_device as a sub-element of management"""
inject_nmi = InjectNmiController()
"""Expose inject_nmi as a sub-element of management"""
indicators = IndicatorController()
"""Expose indicators as a sub-element of management"""
class NodeConsoleController(rest.RestController):
@METRICS.timer('NodeConsoleController.get')
@method.expose()
@args.validate(node_ident=args.uuid_or_name)
def get(self, node_ident):
"""Get connection information about the console.
:param node_ident: UUID or logical name of a node.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:get_console', node_ident)
topic = api.request.rpcapi.get_topic_for(rpc_node)
try:
console = api.request.rpcapi.get_console_information(
api.request.context, rpc_node.uuid, topic)
console_state = True
except exception.NodeConsoleNotEnabled:
console = None
console_state = False
return {'console_enabled': console_state, 'console_info': console}
@METRICS.timer('NodeConsoleController.put')
@method.expose(status_code=http_client.ACCEPTED)
@args.validate(node_ident=args.uuid_or_name, enabled=args.boolean)
def put(self, node_ident, enabled):
"""Start and stop the node console.
:param node_ident: UUID or logical name of a node.
:param enabled: Boolean value; whether to enable or disable the
console.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:set_console_state', node_ident)
topic = api.request.rpcapi.get_topic_for(rpc_node)
api.request.rpcapi.set_console_mode(api.request.context,
rpc_node.uuid, enabled, topic)
# Set the HTTP Location Header
url_args = '/'.join([node_ident, 'states', 'console'])
api.response.location = link.build_url('nodes', url_args)
def node_states_convert(rpc_node):
attr_list = ['console_enabled', 'last_error', 'power_state',
'provision_state', 'target_power_state',
'target_provision_state', 'provision_updated_at']
if api_utils.allow_raid_config():
attr_list.extend(['raid_config', 'target_raid_config'])
if api.request.version.minor >= versions.MINOR_75_NODE_BOOT_MODE:
attr_list.extend(['boot_mode', 'secure_boot'])
states = {}
for attr in attr_list:
states[attr] = getattr(rpc_node, attr)
if isinstance(states[attr], datetime.datetime):
states[attr] = states[attr].isoformat()
update_state_in_older_versions(states)
return states
class NodeStatesController(rest.RestController):
_custom_actions = {
'boot_mode': ['PUT'],
'secure_boot': ['PUT'],
'power': ['PUT'],
'provision': ['PUT'],
'raid': ['PUT'],
}
console = NodeConsoleController()
"""Expose console as a sub-element of states"""
@METRICS.timer('NodeStatesController.get')
@method.expose()
@args.validate(node_ident=args.uuid_or_name)
def get(self, node_ident):
"""List the states of the node.
:param node_ident: the UUID or logical_name of a node.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:get_states', node_ident)
# NOTE(lucasagomes): All these state values come from the
# DB. Ironic counts with a periodic task that verify the current
# power states of the nodes and update the DB accordingly.
return node_states_convert(rpc_node)
@METRICS.timer('NodeStatesController.raid')
@method.expose(status_code=http_client.NO_CONTENT)
@method.body('target_raid_config')
@args.validate(node_ident=args.uuid_or_name,
target_raid_config=args.types(dict))
def raid(self, node_ident, target_raid_config):
"""Set the target raid config of the node.
:param node_ident: the UUID or logical name of a node.
:param target_raid_config: Desired target RAID configuration of
the node. It may be an empty dictionary as well.
:raises: UnsupportedDriverExtension, if the node's driver doesn't
support RAID configuration.
:raises: InvalidParameterValue, if validation of target raid config
fails.
:raises: NotAcceptable, if requested version of the API is less than
1.12.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:set_raid_state', node_ident)
if not api_utils.allow_raid_config():
raise exception.NotAcceptable()
topic = api.request.rpcapi.get_topic_for(rpc_node)
try:
api.request.rpcapi.set_target_raid_config(
api.request.context, rpc_node.uuid,
target_raid_config, topic=topic)
except exception.UnsupportedDriverExtension as e:
# Change error code as 404 seems appropriate because RAID is a
# standard interface and all drivers might not have it.
e.code = http_client.NOT_FOUND
raise
@METRICS.timer('NodeStatesController.power')
@method.expose(status_code=http_client.ACCEPTED)
@args.validate(node_ident=args.uuid_or_name, target=args.string,
timeout=args.integer)
def power(self, node_ident, target, timeout=None):
"""Set the power state of the node.
:param node_ident: the UUID or logical name of a node.
:param target: The desired power state of the node.
:param timeout: timeout (in seconds) positive integer (> 0) for any
power state. ``None`` indicates to use default timeout.
:raises: ClientSideError (HTTP 409) if a power operation is
already in progress.
:raises: InvalidStateRequested (HTTP 400) if the requested target
state is not valid or if the node is in CLEANING state.
:raises: NotAcceptable (HTTP 406) for soft reboot, soft power off or
timeout parameter, if requested version of the API is less than 1.27.
:raises: Invalid (HTTP 400) if timeout value is less than 1.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:set_power_state', node_ident)
# TODO(lucasagomes): Test if it's able to transition to the
# target state from the current one
topic = api.request.rpcapi.get_topic_for(rpc_node)
if ((target in [ir_states.SOFT_REBOOT, ir_states.SOFT_POWER_OFF]
or timeout) and not api_utils.allow_soft_power_off()):
raise exception.NotAcceptable()
if timeout is not None and timeout < 1:
raise exception.Invalid(
_("timeout has to be positive integer"))
if target not in ALLOWED_TARGET_POWER_STATES:
raise exception.InvalidStateRequested(
action=target, node=node_ident,
state=rpc_node.power_state)
# Don't change power state for nodes being cleaned
elif rpc_node.provision_state in (ir_states.CLEANWAIT,
ir_states.CLEANING):
raise exception.InvalidStateRequested(
action=target, node=node_ident,
state=rpc_node.provision_state)
elif (target in (ir_states.POWER_OFF, ir_states.SOFT_POWER_OFF)
and rpc_node.disable_power_off):
raise exception.PowerStateFailure(pstate=target)
api.request.rpcapi.change_node_power_state(api.request.context,
rpc_node.uuid, target,
timeout=timeout,
topic=topic)
# Set the HTTP Location Header
url_args = '/'.join([node_ident, 'states'])
api.response.location = link.build_url('nodes', url_args)
@METRICS.timer('NodeStatesController.boot_mode')
@method.expose(status_code=http_client.ACCEPTED)
@args.validate(node_ident=args.uuid_or_name, target=args.string)
def boot_mode(self, node_ident, target):
"""Asynchronous set the boot mode of the node.
:param node_ident: the UUID or logical name of a node.
:param target: The desired boot_mode for the node (uefi/bios).
:raises: InvalidParameterValue (HTTP 400) if the requested target
state is not valid.
:raises: NotFound (HTTP 404) if requested version of the API
is less than 1.76.
:raises: Conflict (HTTP 409) if a node is in adopting state or
another transient state.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:set_boot_mode', node_ident)
topic = api.request.rpcapi.get_topic_for(rpc_node)
if (api.request.version.minor
< versions.MINOR_76_NODE_CHANGE_BOOT_MODE):
raise exception.NotFound(
(_("This endpoint is supported starting with the API version "
"1.%(min_version)s") %
{'min_version': versions.MINOR_76_NODE_CHANGE_BOOT_MODE}))
if target not in ALLOWED_TARGET_BOOT_MODES:
msg = (_("Invalid boot mode %(mode)s requested for node. "
"Allowed boot modes are: "
"%(modes)s") %
{'mode': target,
'modes': ', '.join(ALLOWED_TARGET_BOOT_MODES)})
raise exception.InvalidParameterValue(msg)
# NOTE(cenne): This currently includes the ADOPTING state
if rpc_node.provision_state in ir_states.UNSTABLE_STATES:
msg = _("Node is in %(state)s state. Since node is transitioning, "
"the boot mode will not be set as this may interfere "
"with ongoing changes and result in erroneous modification"
". Try again later.")
raise exception.Conflict(msg,
action=target, node=node_ident,
state=rpc_node.provision_state)
api.request.rpcapi.change_node_boot_mode(api.request.context,
rpc_node.uuid, target,
topic=topic)
# Set the HTTP Location Header
url_args = '/'.join([node_ident, 'states'])
api.response.location = link.build_url('nodes', url_args)
@METRICS.timer('NodeStatesController.secure_boot')
@method.expose(status_code=http_client.ACCEPTED)
@args.validate(node_ident=args.uuid_or_name, target=args.boolean)
def secure_boot(self, node_ident, target):
"""Asynchronous set the secure_boot state of the node.
:param node_ident: the UUID or logical name of a node.
:param target: Should secure_boot be enabled on node (True/False).
:raises: InvalidParameterValue (HTTP 400) if the requested target
state is not valid.
:raises: NotFound (HTTP 404) if requested version of the API
is less than 1.76.
:raises: Conflict (HTTP 409) if a node is in adopting state.
"""
rpc_node = api_utils.check_node_policy_and_retrieve(
'baremetal:node:set_secure_boot', node_ident)
topic = api.request.rpcapi.get_topic_for(rpc_node)
if (api.request.version.minor
< versions.MINOR_76_NODE_CHANGE_BOOT_MODE):
raise exception.NotFound(
(_("This endpoint is supported starting with the API version "
"1.%(min_version)s") %
{'min_version': versions.MINOR_76_NODE_CHANGE_BOOT_MODE}))
# NOTE(cenne): This is to exclude target=None or other invalid values
if target not in (True, False):
msg = (_("Invalid secure_boot %(state)s requested for node. "
"Allowed secure_boot states are: True, False) ") %
{'state': target})
raise exception.InvalidParameterValue(msg)
# NOTE(cenne): This currently includes the ADOPTING state
if rpc_node.provision_state in ir_states.UNSTABLE_STATES:
msg = _("Node is in %(state)s state. Since node is transitioning, "
"the boot mode will not be set as this may interfere "
"with ongoing changes and result in erroneous modification"
". Try again later.")
raise exception.Conflict(msg,
action=target, node=node_ident,
state=rpc_node.provision_state
)
api.request.rpcapi.change_node_secure_boot(api.request.context,