# 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
from ironic_lib import metrics_utils
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 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_modes
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common import policy
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__)
_CLEAN_STEPS_SCHEMA = {
"$schema": "http://json-schema.org/schema#",
"title": "Clean 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": {}
},
},
# 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'])
_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
[docs]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
[docs]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},
'driver': {'type': 'string'},
'driver_info': {'type': ['object', 'null']},
'extra': {'type': ['object', 'null']},
'inspect_interface': {'type': ['string', 'null']},
'instance_info': {'type': ['object', 'null']},
'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']},
'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', {})
}
[docs]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,
instance_uuid=args.uuid,
protected=args.boolean,
maintenance=args.boolean,
retired=args.boolean,
uuid=args.uuid,
)
_NODE_VALIDATOR = None
_NODE_PATCH_VALIDATOR = None
[docs]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)
[docs]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',
'driver',
'driver_info',
'extra',
'inspect_interface',
'instance_info',
'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'
]
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)
)
[docs]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
[docs]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)
[docs]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()
[docs]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()
[docs]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
[docs]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)
[docs]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)
[docs] @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)
[docs] @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)
[docs] @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}
[docs]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"'))
[docs]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)
]
}
[docs]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}
[docs]class IndicatorController(rest.RestController):
[docs] @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)
[docs] @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}
[docs] @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)
[docs]class InjectNmiController(rest.RestController):
[docs] @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)
[docs]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"""
[docs]class NodeConsoleController(rest.RestController):
[docs] @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}
[docs] @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)
[docs]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
[docs]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"""
[docs] @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)
[docs] @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,