A Python library for code common to TripleO CLI and TripleO UI.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

707 lines
26KB

  1. # Copyright 2016 Red Hat, Inc.
  2. # All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. import copy
  16. import json
  17. import logging
  18. import uuid
  19. from heatclient import exc as heat_exc
  20. from mistral_lib import actions
  21. from swiftclient import exceptions as swiftexceptions
  22. from tripleo_common.actions import base
  23. from tripleo_common.actions import templates
  24. from tripleo_common import constants
  25. from tripleo_common import exception
  26. from tripleo_common.utils import nodes
  27. from tripleo_common.utils import parameters
  28. from tripleo_common.utils import passwords as password_utils
  29. from tripleo_common.utils import plan as plan_utils
  30. LOG = logging.getLogger(__name__)
  31. class GetParametersAction(templates.ProcessTemplatesAction):
  32. """Gets list of available heat parameters."""
  33. def run(self, context):
  34. cached = self.cache_get(context,
  35. self.container,
  36. "tripleo.parameters.get")
  37. if cached is not None:
  38. return cached
  39. processed_data = super(GetParametersAction, self).run(context)
  40. # If we receive a 'Result' instance it is because the parent action
  41. # had an error.
  42. if isinstance(processed_data, actions.Result):
  43. return processed_data
  44. processed_data['show_nested'] = True
  45. # respect previously user set param values
  46. swift = self.get_object_client(context)
  47. heat = self.get_orchestration_client(context)
  48. try:
  49. env = plan_utils.get_env(swift, self.container)
  50. except swiftexceptions.ClientException as err:
  51. err_msg = ("Error retrieving environment for plan %s: %s" % (
  52. self.container, err))
  53. LOG.exception(err_msg)
  54. return actions.Result(error=err_msg)
  55. params = env.get('parameter_defaults')
  56. fields = {
  57. 'template': processed_data['template'],
  58. 'files': processed_data['files'],
  59. 'environment': processed_data['environment'],
  60. 'show_nested': True
  61. }
  62. result = {
  63. 'heat_resource_tree': heat.stacks.validate(**fields),
  64. 'environment_parameters': params,
  65. }
  66. self.cache_set(context,
  67. self.container,
  68. "tripleo.parameters.get",
  69. result)
  70. return result
  71. class ResetParametersAction(base.TripleOAction):
  72. """Provides method to delete user set parameters."""
  73. def __init__(self, container=constants.DEFAULT_CONTAINER_NAME,
  74. key=constants.DEFAULT_PLAN_ENV_KEY):
  75. super(ResetParametersAction, self).__init__()
  76. self.container = container
  77. self.key = key
  78. def run(self, context):
  79. swift = self.get_object_client(context)
  80. try:
  81. env = plan_utils.get_env(swift, self.container)
  82. except swiftexceptions.ClientException as err:
  83. err_msg = ("Error retrieving environment for plan %s: %s" % (
  84. self.container, err))
  85. LOG.exception(err_msg)
  86. return actions.Result(error=err_msg)
  87. try:
  88. plan_utils.update_in_env(swift, env, self.key,
  89. delete_key=True)
  90. except swiftexceptions.ClientException as err:
  91. err_msg = ("Error updating environment for plan %s: %s" % (
  92. self.container, err))
  93. LOG.exception(err_msg)
  94. return actions.Result(error=err_msg)
  95. self.cache_delete(context,
  96. self.container,
  97. "tripleo.parameters.get")
  98. return env
  99. class UpdateParametersAction(templates.ProcessTemplatesAction):
  100. """Updates plan environment with parameters."""
  101. def __init__(self, parameters,
  102. container=constants.DEFAULT_CONTAINER_NAME,
  103. key=constants.DEFAULT_PLAN_ENV_KEY,
  104. validate=True):
  105. super(UpdateParametersAction, self).__init__()
  106. self.container = container
  107. self.parameters = parameters
  108. self.key = key
  109. self.validate = validate
  110. def run(self, context):
  111. swift = self.get_object_client(context)
  112. heat = self.get_orchestration_client(context)
  113. try:
  114. env = plan_utils.get_env(swift, self.container)
  115. except swiftexceptions.ClientException as err:
  116. err_msg = ("Error retrieving environment for plan %s: %s" % (
  117. self.container, err))
  118. LOG.exception(err_msg)
  119. return actions.Result(error=err_msg)
  120. saved_env = copy.deepcopy(env)
  121. try:
  122. plan_utils.update_in_env(swift, env, self.key,
  123. self.parameters)
  124. except swiftexceptions.ClientException as err:
  125. err_msg = ("Error updating environment for plan %s: %s" % (
  126. self.container, err))
  127. LOG.exception(err_msg)
  128. return actions.Result(error=err_msg)
  129. processed_data = super(UpdateParametersAction, self).run(context)
  130. # If we receive a 'Result' instance it is because the parent action
  131. # had an error.
  132. if isinstance(processed_data, actions.Result):
  133. return processed_data
  134. env = plan_utils.get_env(swift, self.container)
  135. if not self.validate:
  136. return env
  137. params = env.get('parameter_defaults')
  138. fields = {
  139. 'template': processed_data['template'],
  140. 'files': processed_data['files'],
  141. 'environment': processed_data['environment'],
  142. 'show_nested': True
  143. }
  144. try:
  145. result = {
  146. 'heat_resource_tree': heat.stacks.validate(**fields),
  147. 'environment_parameters': params,
  148. }
  149. # Validation passes so the old cache gets replaced.
  150. self.cache_set(context,
  151. self.container,
  152. "tripleo.parameters.get",
  153. result)
  154. if result['heat_resource_tree']:
  155. flattened = {'resources': {}, 'parameters': {}}
  156. _flat_it(flattened, 'Root',
  157. result['heat_resource_tree'])
  158. result['heat_resource_tree'] = flattened
  159. except heat_exc.HTTPException as err:
  160. LOG.debug("Validation failed rebuilding saved env")
  161. # There has been an error validating we must reprocess the
  162. # templates with the saved working env
  163. plan_utils.put_env(swift, saved_env)
  164. env = saved_env
  165. processed_data = super(UpdateParametersAction, self).run(context)
  166. err_msg = ("Error validating environment for plan %s: %s" % (
  167. self.container, err))
  168. LOG.exception(err_msg)
  169. return actions.Result(error=err_msg)
  170. LOG.debug("Validation worked new env is saved")
  171. return result
  172. class UpdateRoleParametersAction(UpdateParametersAction):
  173. """Updates role related parameters in plan environment ."""
  174. def __init__(self, role, container=constants.DEFAULT_CONTAINER_NAME):
  175. super(UpdateRoleParametersAction, self).__init__(parameters=None,
  176. container=container)
  177. self.role = role
  178. def run(self, context):
  179. baremetal_client = self.get_baremetal_client(context)
  180. compute_client = self.get_compute_client(context)
  181. self.parameters = parameters.set_count_and_flavor_params(
  182. self.role, baremetal_client, compute_client)
  183. return super(UpdateRoleParametersAction, self).run(context)
  184. class GeneratePasswordsAction(base.TripleOAction):
  185. """Generates passwords needed for Overcloud deployment
  186. This method generates passwords and ensures they are stored in the
  187. plan environment. This method respects previously generated passwords and
  188. adds new passwords as necessary.
  189. """
  190. def __init__(self, container=constants.DEFAULT_CONTAINER_NAME):
  191. super(GeneratePasswordsAction, self).__init__()
  192. self.container = container
  193. def run(self, context):
  194. heat = self.get_orchestration_client(context)
  195. swift = self.get_object_client(context)
  196. mistral = self.get_workflow_client(context)
  197. try:
  198. env = plan_utils.get_env(swift, self.container)
  199. except swiftexceptions.ClientException as err:
  200. err_msg = ("Error retrieving environment for plan %s: %s" % (
  201. self.container, err))
  202. LOG.exception(err_msg)
  203. return actions.Result(error=err_msg)
  204. try:
  205. stack_env = heat.stacks.environment(
  206. stack_id=self.container)
  207. # legacy heat resource names from overcloud.yaml
  208. # We don't modify these to avoid changing defaults
  209. for pw_res in constants.LEGACY_HEAT_PASSWORD_RESOURCE_NAMES:
  210. try:
  211. res = heat.resources.get(self.container, pw_res)
  212. param_defaults = stack_env.get('parameter_defaults', {})
  213. param_defaults[pw_res] = res.attributes['value']
  214. except heat_exc.HTTPNotFound:
  215. LOG.debug('Heat resouce not found: %s' % pw_res)
  216. pass
  217. except heat_exc.HTTPNotFound:
  218. stack_env = None
  219. passwords = password_utils.generate_passwords(mistral, stack_env)
  220. # if passwords don't yet exist in plan environment
  221. if 'passwords' not in env:
  222. env['passwords'] = {}
  223. # ensure all generated passwords are present in plan env,
  224. # but respect any values previously generated and stored
  225. for name, password in passwords.items():
  226. if name not in env['passwords']:
  227. env['passwords'][name] = password
  228. try:
  229. plan_utils.put_env(swift, env)
  230. except swiftexceptions.ClientException as err:
  231. err_msg = "Error uploading to container: %s" % err
  232. LOG.exception(err_msg)
  233. return actions.Result(error=err_msg)
  234. self.cache_delete(context,
  235. self.container,
  236. "tripleo.parameters.get")
  237. return env['passwords']
  238. class GetPasswordsAction(base.TripleOAction):
  239. """Get passwords from the environment
  240. This method returns the list passwords which are used for the deployment.
  241. It will return a merged list of user provided passwords and generated
  242. passwords, giving priority to the user provided passwords.
  243. """
  244. def __init__(self, container=constants.DEFAULT_CONTAINER_NAME):
  245. super(GetPasswordsAction, self).__init__()
  246. self.container = container
  247. def run(self, context):
  248. swift = self.get_object_client(context)
  249. try:
  250. env = plan_utils.get_env(swift, self.container)
  251. except swiftexceptions.ClientException as err:
  252. err_msg = ("Error retrieving environment for plan %s: %s" % (
  253. self.container, err))
  254. LOG.exception(err_msg)
  255. return actions.Result(error=err_msg)
  256. parameter_defaults = env.get('parameter_defaults', {})
  257. passwords = env.get('passwords', {})
  258. return self._get_overriden_passwords(passwords, parameter_defaults)
  259. def _get_overriden_passwords(self, env_passwords, parameter_defaults):
  260. for name in constants.PASSWORD_PARAMETER_NAMES:
  261. if name in parameter_defaults:
  262. env_passwords[name] = parameter_defaults[name]
  263. return env_passwords
  264. class GenerateFencingParametersAction(base.TripleOAction):
  265. """Generates fencing configuration for a deployment.
  266. :param nodes_json: list of nodes & attributes in json format
  267. :param os_auth: dictionary of OS client auth data (if using pxe_ssh)
  268. :param delay: time to wait before taking fencing action
  269. :param ipmi_level: IPMI user level to use
  270. :param ipmi_cipher: IPMI cipher suite to use
  271. :param ipmi_lanplus: whether to use IPMIv2.0
  272. """
  273. def __init__(self, nodes_json, os_auth, delay,
  274. ipmi_level, ipmi_cipher, ipmi_lanplus):
  275. super(GenerateFencingParametersAction, self).__init__()
  276. self.nodes_json = nodes_json
  277. self.os_auth = os_auth
  278. self.delay = delay
  279. self.ipmi_level = ipmi_level
  280. self.ipmi_cipher = ipmi_cipher
  281. self.ipmi_lanplus = ipmi_lanplus
  282. def run(self, context):
  283. """Returns the parameters for fencing controller nodes"""
  284. hostmap = nodes.generate_hostmap(self.get_baremetal_client(context),
  285. self.get_compute_client(context))
  286. fence_params = {"EnableFencing": True, "FencingConfig": {}}
  287. devices = []
  288. for node in self.nodes_json:
  289. node_data = {}
  290. params = {}
  291. if "mac" in node:
  292. # Not all Ironic drivers present a MAC address, so we only
  293. # capture it if it's present
  294. mac_addr = node["mac"][0].lower()
  295. node_data["host_mac"] = mac_addr
  296. # If the MAC isn't in the hostmap, this node hasn't been
  297. # provisioned, so no fencing parameters are necessary
  298. if hostmap and mac_addr not in hostmap:
  299. continue
  300. # Build up fencing parameters based on which Ironic driver this
  301. # node is using
  302. if hostmap and node["pm_type"] == "pxe_ssh":
  303. # Ironic fencing driver
  304. node_data["agent"] = "fence_ironic"
  305. params["auth_url"] = self.os_auth["auth_url"]
  306. params["login"] = self.os_auth["login"]
  307. params["passwd"] = self.os_auth["passwd"]
  308. params["tenant_name"] = self.os_auth["tenant_name"]
  309. params["pcmk_host_map"] = "%(compute_name)s:%(bm_name)s" % (
  310. {"compute_name": hostmap[mac_addr]["compute_name"],
  311. "bm_name": hostmap[mac_addr]["baremetal_name"]})
  312. if self.delay:
  313. params["delay"] = self.delay
  314. elif (node['pm_type'] in {'staging-ovirt'}):
  315. # fence_rhevm
  316. node_data["agent"] = "fence_rhevm"
  317. params["ipaddr"] = node["pm_addr"]
  318. params["passwd"] = node["pm_password"]
  319. params["login"] = node["pm_user"]
  320. params["port"] = node["pm_vm_name"]
  321. params["ssl"] = 1
  322. params["ssl_insecure"] = 1
  323. if hostmap:
  324. params["pcmk_host_list"] = \
  325. hostmap[mac_addr]["compute_name"]
  326. if self.delay:
  327. params["delay"] = self.delay
  328. elif (node['pm_type'] == 'ipmi' or node["pm_type"].split('_')[1] in
  329. ("ipmitool", "ilo", "drac")):
  330. # IPMI fencing driver
  331. node_data["agent"] = "fence_ipmilan"
  332. params["ipaddr"] = node["pm_addr"]
  333. params["passwd"] = node["pm_password"]
  334. params["login"] = node["pm_user"]
  335. if hostmap:
  336. params["pcmk_host_list"] = \
  337. hostmap[mac_addr]["compute_name"]
  338. if "pm_port" in node:
  339. params["ipport"] = node["pm_port"]
  340. if self.ipmi_lanplus:
  341. params["lanplus"] = self.ipmi_lanplus
  342. if self.delay:
  343. params["delay"] = self.delay
  344. if self.ipmi_cipher:
  345. params["cipher"] = self.ipmi_cipher
  346. if self.ipmi_level:
  347. params["privlvl"] = self.ipmi_level
  348. else:
  349. error = ("Unable to generate fencing parameters for %s" %
  350. node["pm_type"])
  351. raise ValueError(error)
  352. node_data["params"] = params
  353. devices.append(node_data)
  354. fence_params["FencingConfig"]["devices"] = devices
  355. return {"parameter_defaults": fence_params}
  356. class GetFlattenedParametersAction(GetParametersAction):
  357. """Get the heat stack tree and parameters in flattened structure.
  358. This method validates the stack of the container and returns the
  359. parameters and the heat stack tree. The heat stack tree is flattened
  360. for easy consumption.
  361. """
  362. def __init__(self, container=constants.DEFAULT_CONTAINER_NAME):
  363. super(GetFlattenedParametersAction, self).__init__(container)
  364. def run(self, context):
  365. # process all plan files and create or update a stack
  366. processed_data = super(GetFlattenedParametersAction, self).run(context)
  367. # If we receive a 'Result' instance it is because the parent action
  368. # had an error.
  369. if isinstance(processed_data, actions.Result):
  370. return processed_data
  371. if processed_data['heat_resource_tree']:
  372. flattened = {'resources': {}, 'parameters': {}}
  373. _flat_it(flattened, 'Root',
  374. processed_data['heat_resource_tree'])
  375. processed_data['heat_resource_tree'] = flattened
  376. return processed_data
  377. def _process_params(flattened, params):
  378. for item in params:
  379. if item not in flattened['parameters']:
  380. param_obj = {}
  381. for key, value in params.get(item).items():
  382. camel_case_key = key[0].lower() + key[1:]
  383. param_obj[camel_case_key] = value
  384. param_obj['name'] = item
  385. flattened['parameters'][item] = param_obj
  386. return list(params)
  387. def _flat_it(flattened, name, data):
  388. key = str(uuid.uuid4())
  389. value = {}
  390. value.update({
  391. 'name': name,
  392. 'id': key
  393. })
  394. if 'Type' in data:
  395. value['type'] = data['Type']
  396. if 'Description' in data:
  397. value['description'] = data['Description']
  398. if 'Parameters' in data:
  399. value['parameters'] = _process_params(flattened,
  400. data['Parameters'])
  401. if 'ParameterGroups' in data:
  402. value['parameter_groups'] = data['ParameterGroups']
  403. if 'NestedParameters' in data:
  404. nested = data['NestedParameters']
  405. nested_ids = []
  406. for nested_key in nested.keys():
  407. nested_data = _flat_it(flattened, nested_key,
  408. nested.get(nested_key))
  409. # nested_data will always have one key (and only one)
  410. nested_ids.append(list(nested_data)[0])
  411. value['resources'] = nested_ids
  412. flattened['resources'][key] = value
  413. return {key: value}
  414. class GetProfileOfFlavorAction(base.TripleOAction):
  415. """Gets the profile name for a given flavor name.
  416. Need flavor object to get profile name since get_keys method is
  417. not available for external access. so we have created an action
  418. to get profile name from flavor name.
  419. :param flavor_name: Flavor name
  420. :return: profile name
  421. """
  422. def __init__(self, flavor_name):
  423. super(GetProfileOfFlavorAction, self).__init__()
  424. self.flavor_name = flavor_name
  425. def run(self, context):
  426. compute_client = self.get_compute_client(context)
  427. try:
  428. return parameters.get_profile_of_flavor(self.flavor_name,
  429. compute_client)
  430. except exception.DeriveParamsError as err:
  431. LOG.error('Derive Params Error: %s', err)
  432. return actions.Result(error=str(err))
  433. class RotateFernetKeysAction(GetPasswordsAction):
  434. """Rotate fernet keys from the environment
  435. This method rotates the fernet keys that are saved in the environment, in
  436. the passwords parameter.
  437. """
  438. def __init__(self, container=constants.DEFAULT_CONTAINER_NAME):
  439. super(RotateFernetKeysAction, self).__init__()
  440. self.container = container
  441. def run(self, context):
  442. swift = self.get_object_client(context)
  443. try:
  444. env = plan_utils.get_env(swift, self.container)
  445. except swiftexceptions.ClientException as err:
  446. err_msg = ("Error retrieving environment for plan %s: %s" % (
  447. self.container, err))
  448. LOG.exception(err_msg)
  449. return actions.Result(error=err_msg)
  450. parameter_defaults = env.get('parameter_defaults', {})
  451. passwords = self._get_overriden_passwords(env.get('passwords', {}),
  452. parameter_defaults)
  453. next_index = self.get_next_index(passwords['KeystoneFernetKeys'])
  454. keys_map = self.rotate_keys(passwords['KeystoneFernetKeys'],
  455. next_index)
  456. max_keys = self.get_max_keys_value(parameter_defaults)
  457. keys_map = self.purge_excess_keys(max_keys, keys_map)
  458. env['passwords']['KeystoneFernetKeys'] = keys_map
  459. try:
  460. plan_utils.put_env(swift, env)
  461. except swiftexceptions.ClientException as err:
  462. err_msg = "Error uploading to container: %s" % err
  463. LOG.exception(err_msg)
  464. return actions.Result(error=err_msg)
  465. self.cache_delete(context,
  466. self.container,
  467. "tripleo.parameters.get")
  468. return keys_map
  469. @staticmethod
  470. def get_key_index_from_path(path):
  471. return int(path[path.rfind('/') + 1:])
  472. def get_next_index(self, keys_map):
  473. return self.get_key_index_from_path(
  474. max(keys_map, key=self.get_key_index_from_path)) + 1
  475. def get_key_path(self, index):
  476. return password_utils.KEYSTONE_FERNET_REPO + str(index)
  477. def rotate_keys(self, keys_map, next_index):
  478. next_index_path = self.get_key_path(next_index)
  479. zero_index_path = self.get_key_path(0)
  480. # promote staged key to be new primary
  481. keys_map[next_index_path] = keys_map[zero_index_path]
  482. # Set new staged key
  483. keys_map[zero_index_path] = {
  484. 'content': password_utils.create_keystone_credential()}
  485. return keys_map
  486. def get_max_keys_value(self, parameter_defaults):
  487. # The number of max keys should always be positive. The minimum amount
  488. # of keys is 3.
  489. return max(parameter_defaults.get('KeystoneFernetMaxActiveKeys', 5), 3)
  490. def purge_excess_keys(self, max_keys, keys_map):
  491. current_repo_size = len(keys_map)
  492. if current_repo_size <= max_keys:
  493. return keys_map
  494. key_paths = sorted(keys_map.keys(), key=self.get_key_index_from_path)
  495. keys_to_be_purged = current_repo_size - max_keys
  496. for key_path in key_paths[1:keys_to_be_purged + 1]:
  497. del keys_map[key_path]
  498. return keys_map
  499. class GetNetworkConfigAction(templates.ProcessTemplatesAction):
  500. """Gets network configuration details from available heat parameters."""
  501. def __init__(self, role_name, container=constants.DEFAULT_CONTAINER_NAME):
  502. super(GetNetworkConfigAction, self).__init__(container=container)
  503. self.role_name = role_name
  504. def run(self, context):
  505. processed_data = super(GetNetworkConfigAction, self).run(context)
  506. # If we receive a 'Result' instance it is because the parent action
  507. # had an error.
  508. if isinstance(processed_data, actions.Result):
  509. return processed_data
  510. # Default temporary value is used when no user input for any
  511. # interface routes for the role networks to find network config.
  512. role_networks = processed_data['template'].get('resources', {}).get(
  513. self.role_name + 'GroupVars', {}).get('properties', {}).get(
  514. 'value', {}).get('role_networks', [])
  515. for nw in role_networks:
  516. rt = nw + 'InterfaceRoutes'
  517. if rt not in processed_data['environment']['parameter_defaults']:
  518. processed_data['environment']['parameter_defaults'][rt] = [[]]
  519. # stacks.preview method raises validation message if stack is
  520. # already deployed. here renaming container to get preview data.
  521. container_temp = self.container + "-TEMP"
  522. fields = {
  523. 'template': processed_data['template'],
  524. 'files': processed_data['files'],
  525. 'environment': processed_data['environment'],
  526. 'stack_name': container_temp,
  527. }
  528. orc = self.get_orchestration_client(context)
  529. preview_data = orc.stacks.preview(**fields)
  530. try:
  531. result = self.get_network_config(preview_data, container_temp,
  532. self.role_name)
  533. return result
  534. except exception.DeriveParamsError as err:
  535. LOG.exception('Derive Params Error: %s' % err)
  536. return actions.Result(error=str(err))
  537. def get_network_config(self, preview_data, stack_name, role_name):
  538. result = None
  539. if preview_data:
  540. for res in preview_data.resources:
  541. net_script = self.process_preview_list(res,
  542. stack_name,
  543. role_name)
  544. if net_script:
  545. ns_len = len(net_script)
  546. start_index = (net_script.find(
  547. "echo '{\"network_config\"", 0, ns_len) + 6)
  548. end_index = net_script.find("'", start_index, ns_len)
  549. if (end_index > start_index):
  550. net_config = net_script[start_index:end_index]
  551. if net_config:
  552. result = json.loads(net_config)
  553. break
  554. if not result:
  555. err_msg = ("Unable to determine network config for role '%s'."
  556. % self.role_name)
  557. raise exception.DeriveParamsError(err_msg)
  558. return result
  559. def process_preview_list(self, res, stack_name, role_name):
  560. if type(res) == list:
  561. for item in res:
  562. out = self.process_preview_list(item, stack_name, role_name)
  563. if out:
  564. return out
  565. elif type(res) == dict:
  566. res_stack_name = stack_name + '-' + role_name
  567. if res['resource_name'] == "OsNetConfigImpl" and \
  568. res['resource_identity'] and \
  569. res_stack_name in res['resource_identity']['stack_name']:
  570. return res['properties']['config']
  571. return None