Shared filesystem management project for OpenStack.
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.

3828 lines
141KB

  1. # Copyright (c) 2014 Alex Meade. All rights reserved.
  2. # Copyright (c) 2015 Clinton Knight. All rights reserved.
  3. # Copyright (c) 2015 Tom Barron. All rights reserved.
  4. # Copyright (c) 2018 Jose Porrua. All rights reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  7. # not use this file except in compliance with the License. You may obtain
  8. # a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. # License for the specific language governing permissions and limitations
  16. # under the License.
  17. import copy
  18. import hashlib
  19. import re
  20. import time
  21. from oslo_log import log
  22. from oslo_utils import strutils
  23. from oslo_utils import units
  24. import six
  25. from manila import exception
  26. from manila.i18n import _
  27. from manila.share.drivers.netapp.dataontap.client import api as netapp_api
  28. from manila.share.drivers.netapp.dataontap.client import client_base
  29. from manila.share.drivers.netapp import utils as na_utils
  30. LOG = log.getLogger(__name__)
  31. DELETED_PREFIX = 'deleted_manila_'
  32. DEFAULT_IPSPACE = 'Default'
  33. DEFAULT_MAX_PAGE_LENGTH = 50
  34. CUTOVER_ACTION_MAP = {
  35. 'defer': 'defer_on_failure',
  36. 'abort': 'abort_on_failure',
  37. 'force': 'force',
  38. 'wait': 'wait',
  39. }
  40. class NetAppCmodeClient(client_base.NetAppBaseClient):
  41. def __init__(self, **kwargs):
  42. super(NetAppCmodeClient, self).__init__(**kwargs)
  43. self.vserver = kwargs.get('vserver')
  44. self.connection.set_vserver(self.vserver)
  45. # Default values to run first api.
  46. self.connection.set_api_version(1, 15)
  47. (major, minor) = self.get_ontapi_version(cached=False)
  48. self.connection.set_api_version(major, minor)
  49. system_version = self.get_system_version(cached=False)
  50. self.connection.set_system_version(system_version)
  51. self._init_features()
  52. def _init_features(self):
  53. """Initialize cDOT feature support map."""
  54. super(NetAppCmodeClient, self)._init_features()
  55. ontapi_version = self.get_ontapi_version(cached=True)
  56. ontapi_1_20 = ontapi_version >= (1, 20)
  57. ontapi_1_2x = (1, 20) <= ontapi_version < (1, 30)
  58. ontapi_1_30 = ontapi_version >= (1, 30)
  59. ontapi_1_110 = ontapi_version >= (1, 110)
  60. self.features.add_feature('SNAPMIRROR_V2', supported=ontapi_1_20)
  61. self.features.add_feature('SYSTEM_METRICS', supported=ontapi_1_2x)
  62. self.features.add_feature('SYSTEM_CONSTITUENT_METRICS',
  63. supported=ontapi_1_30)
  64. self.features.add_feature('BROADCAST_DOMAINS', supported=ontapi_1_30)
  65. self.features.add_feature('IPSPACES', supported=ontapi_1_30)
  66. self.features.add_feature('SUBNETS', supported=ontapi_1_30)
  67. self.features.add_feature('CLUSTER_PEER_POLICY', supported=ontapi_1_30)
  68. self.features.add_feature('ADVANCED_DISK_PARTITIONING',
  69. supported=ontapi_1_30)
  70. self.features.add_feature('FLEXVOL_ENCRYPTION', supported=ontapi_1_110)
  71. def _invoke_vserver_api(self, na_element, vserver):
  72. server = copy.copy(self.connection)
  73. server.set_vserver(vserver)
  74. result = server.invoke_successfully(na_element, True)
  75. return result
  76. def _has_records(self, api_result_element):
  77. if (not api_result_element.get_child_content('num-records') or
  78. api_result_element.get_child_content('num-records') == '0'):
  79. return False
  80. else:
  81. return True
  82. def _get_record_count(self, api_result_element):
  83. try:
  84. return int(api_result_element.get_child_content('num-records'))
  85. except TypeError:
  86. msg = _('Missing record count for NetApp iterator API invocation.')
  87. raise exception.NetAppException(msg)
  88. def set_vserver(self, vserver):
  89. self.vserver = vserver
  90. self.connection.set_vserver(vserver)
  91. def send_iter_request(self, api_name, api_args=None,
  92. max_page_length=DEFAULT_MAX_PAGE_LENGTH):
  93. """Invoke an iterator-style getter API."""
  94. if not api_args:
  95. api_args = {}
  96. api_args['max-records'] = max_page_length
  97. # Get first page
  98. result = self.send_request(api_name, api_args)
  99. # Most commonly, we can just return here if there is no more data
  100. next_tag = result.get_child_content('next-tag')
  101. if not next_tag:
  102. return result
  103. # Ensure pagination data is valid and prepare to store remaining pages
  104. num_records = self._get_record_count(result)
  105. attributes_list = result.get_child_by_name('attributes-list')
  106. if not attributes_list:
  107. msg = _('Missing attributes list for API %s.') % api_name
  108. raise exception.NetAppException(msg)
  109. # Get remaining pages, saving data into first page
  110. while next_tag is not None:
  111. next_api_args = copy.deepcopy(api_args)
  112. next_api_args['tag'] = next_tag
  113. next_result = self.send_request(api_name, next_api_args)
  114. next_attributes_list = next_result.get_child_by_name(
  115. 'attributes-list') or netapp_api.NaElement('none')
  116. for record in next_attributes_list.get_children():
  117. attributes_list.add_child_elem(record)
  118. num_records += self._get_record_count(next_result)
  119. next_tag = next_result.get_child_content('next-tag')
  120. result.get_child_by_name('num-records').set_content(
  121. six.text_type(num_records))
  122. result.get_child_by_name('next-tag').set_content('')
  123. return result
  124. @na_utils.trace
  125. def create_vserver(self, vserver_name, root_volume_aggregate_name,
  126. root_volume_name, aggregate_names, ipspace_name):
  127. """Creates new vserver and assigns aggregates."""
  128. create_args = {
  129. 'vserver-name': vserver_name,
  130. 'root-volume-security-style': 'unix',
  131. 'root-volume-aggregate': root_volume_aggregate_name,
  132. 'root-volume': root_volume_name,
  133. 'name-server-switch': {
  134. 'nsswitch': 'file',
  135. },
  136. }
  137. if ipspace_name:
  138. if not self.features.IPSPACES:
  139. msg = 'IPSpaces are not supported on this backend.'
  140. raise exception.NetAppException(msg)
  141. else:
  142. create_args['ipspace'] = ipspace_name
  143. self.send_request('vserver-create', create_args)
  144. aggr_list = [{'aggr-name': aggr_name} for aggr_name in aggregate_names]
  145. modify_args = {
  146. 'aggr-list': aggr_list,
  147. 'vserver-name': vserver_name,
  148. }
  149. self.send_request('vserver-modify', modify_args)
  150. @na_utils.trace
  151. def vserver_exists(self, vserver_name):
  152. """Checks if Vserver exists."""
  153. LOG.debug('Checking if Vserver %s exists', vserver_name)
  154. api_args = {
  155. 'query': {
  156. 'vserver-info': {
  157. 'vserver-name': vserver_name,
  158. },
  159. },
  160. 'desired-attributes': {
  161. 'vserver-info': {
  162. 'vserver-name': None,
  163. },
  164. },
  165. }
  166. result = self.send_iter_request('vserver-get-iter', api_args)
  167. return self._has_records(result)
  168. @na_utils.trace
  169. def get_vserver_root_volume_name(self, vserver_name):
  170. """Get the root volume name of the vserver."""
  171. api_args = {
  172. 'query': {
  173. 'vserver-info': {
  174. 'vserver-name': vserver_name,
  175. },
  176. },
  177. 'desired-attributes': {
  178. 'vserver-info': {
  179. 'root-volume': None,
  180. },
  181. },
  182. }
  183. vserver_info = self.send_iter_request('vserver-get-iter', api_args)
  184. try:
  185. root_volume_name = vserver_info.get_child_by_name(
  186. 'attributes-list').get_child_by_name(
  187. 'vserver-info').get_child_content('root-volume')
  188. except AttributeError:
  189. msg = _('Could not determine root volume name '
  190. 'for Vserver %s.') % vserver_name
  191. raise exception.NetAppException(msg)
  192. return root_volume_name
  193. @na_utils.trace
  194. def get_vserver_ipspace(self, vserver_name):
  195. """Get the IPspace of the vserver, or None if not supported."""
  196. if not self.features.IPSPACES:
  197. return None
  198. api_args = {
  199. 'query': {
  200. 'vserver-info': {
  201. 'vserver-name': vserver_name,
  202. },
  203. },
  204. 'desired-attributes': {
  205. 'vserver-info': {
  206. 'ipspace': None,
  207. },
  208. },
  209. }
  210. vserver_info = self.send_iter_request('vserver-get-iter', api_args)
  211. try:
  212. ipspace = vserver_info.get_child_by_name(
  213. 'attributes-list').get_child_by_name(
  214. 'vserver-info').get_child_content('ipspace')
  215. except AttributeError:
  216. msg = _('Could not determine IPspace for Vserver %s.')
  217. raise exception.NetAppException(msg % vserver_name)
  218. return ipspace
  219. @na_utils.trace
  220. def ipspace_has_data_vservers(self, ipspace_name):
  221. """Check whether an IPspace has any data Vservers assigned to it."""
  222. if not self.features.IPSPACES:
  223. return False
  224. api_args = {
  225. 'query': {
  226. 'vserver-info': {
  227. 'ipspace': ipspace_name,
  228. 'vserver-type': 'data'
  229. },
  230. },
  231. 'desired-attributes': {
  232. 'vserver-info': {
  233. 'vserver-name': None,
  234. },
  235. },
  236. }
  237. result = self.send_iter_request('vserver-get-iter', api_args)
  238. return self._has_records(result)
  239. @na_utils.trace
  240. def list_vservers(self, vserver_type='data'):
  241. """Get the names of vservers present, optionally filtered by type."""
  242. query = {
  243. 'vserver-info': {
  244. 'vserver-type': vserver_type,
  245. }
  246. } if vserver_type else None
  247. api_args = {
  248. 'desired-attributes': {
  249. 'vserver-info': {
  250. 'vserver-name': None,
  251. },
  252. },
  253. }
  254. if query:
  255. api_args['query'] = query
  256. result = self.send_iter_request('vserver-get-iter', api_args)
  257. vserver_info_list = result.get_child_by_name(
  258. 'attributes-list') or netapp_api.NaElement('none')
  259. return [vserver_info.get_child_content('vserver-name')
  260. for vserver_info in vserver_info_list.get_children()]
  261. @na_utils.trace
  262. def get_vserver_volume_count(self):
  263. """Get the number of volumes present on a cluster or vserver.
  264. Call this on a vserver client to see how many volumes exist
  265. on that vserver.
  266. """
  267. api_args = {
  268. 'desired-attributes': {
  269. 'volume-attributes': {
  270. 'volume-id-attributes': {
  271. 'name': None,
  272. },
  273. },
  274. },
  275. }
  276. volumes_data = self.send_iter_request('volume-get-iter', api_args)
  277. return self._get_record_count(volumes_data)
  278. @na_utils.trace
  279. def delete_vserver(self, vserver_name, vserver_client,
  280. security_services=None):
  281. """Delete Vserver.
  282. Checks if Vserver exists and does not have active shares.
  283. Offlines and destroys root volumes. Deletes Vserver.
  284. """
  285. if not self.vserver_exists(vserver_name):
  286. LOG.error("Vserver %s does not exist.", vserver_name)
  287. return
  288. root_volume_name = self.get_vserver_root_volume_name(vserver_name)
  289. volumes_count = vserver_client.get_vserver_volume_count()
  290. if volumes_count == 1:
  291. try:
  292. vserver_client.offline_volume(root_volume_name)
  293. except netapp_api.NaApiError as e:
  294. if e.code == netapp_api.EVOLUMEOFFLINE:
  295. LOG.error("Volume %s is already offline.",
  296. root_volume_name)
  297. else:
  298. raise
  299. vserver_client.delete_volume(root_volume_name)
  300. elif volumes_count > 1:
  301. msg = _("Cannot delete Vserver. Vserver %s has shares.")
  302. raise exception.NetAppException(msg % vserver_name)
  303. if security_services:
  304. self._terminate_vserver_services(vserver_name, vserver_client,
  305. security_services)
  306. self.send_request('vserver-destroy', {'vserver-name': vserver_name})
  307. @na_utils.trace
  308. def _terminate_vserver_services(self, vserver_name, vserver_client,
  309. security_services):
  310. for service in security_services:
  311. if service['type'] == 'active_directory':
  312. api_args = {
  313. 'admin-password': service['password'],
  314. 'admin-username': service['user'],
  315. }
  316. try:
  317. vserver_client.send_request('cifs-server-delete', api_args)
  318. except netapp_api.NaApiError as e:
  319. if e.code == netapp_api.EOBJECTNOTFOUND:
  320. LOG.error('CIFS server does not exist for '
  321. 'Vserver %s.', vserver_name)
  322. else:
  323. vserver_client.send_request('cifs-server-delete')
  324. @na_utils.trace
  325. def is_nve_supported(self):
  326. """Determine whether NVE is supported on this platform and version."""
  327. nodes = self.list_cluster_nodes()
  328. system_version = self.get_system_version()
  329. version = system_version.get('version')
  330. version_tuple = system_version.get('version-tuple')
  331. # NVE requires an ONTAP version >= 9.1. Also, not all platforms
  332. # support this feature. NVE is not supported if the version
  333. # includes the substring '<1no-DARE>' (no Data At Rest Encryption).
  334. if version_tuple >= (9, 1, 0) and "<1no-DARE>" not in version:
  335. if nodes is not None:
  336. return self.get_security_key_manager_nve_support(nodes[0])
  337. else:
  338. LOG.debug('Cluster credentials are required in order to '
  339. 'determine whether NetApp Volume Encryption is '
  340. 'supported or not on this platform.')
  341. return False
  342. else:
  343. LOG.debug('NetApp Volume Encryption is not supported on this '
  344. 'ONTAP version: %(version)s, %(version_tuple)s. ',
  345. {'version': version, 'version_tuple': version_tuple})
  346. return False
  347. @na_utils.trace
  348. def list_cluster_nodes(self):
  349. """Get all available cluster nodes."""
  350. api_args = {
  351. 'desired-attributes': {
  352. 'node-details-info': {
  353. 'node': None,
  354. },
  355. },
  356. }
  357. result = self.send_iter_request('system-node-get-iter', api_args)
  358. nodes_info_list = result.get_child_by_name(
  359. 'attributes-list') or netapp_api.NaElement('none')
  360. return [node_info.get_child_content('node') for node_info
  361. in nodes_info_list.get_children()]
  362. @na_utils.trace
  363. def get_security_key_manager_nve_support(self, node):
  364. """Determine whether the cluster platform supports Volume Encryption"""
  365. api_args = {'node': node}
  366. try:
  367. result = self.send_request(
  368. 'security-key-manager-volume-encryption-supported', api_args)
  369. vol_encryption_supported = result.get_child_content(
  370. 'vol-encryption-supported') or 'false'
  371. except netapp_api.NaApiError as e:
  372. LOG.debug("NVE disabled due to error code: %s - %s",
  373. e.code, e.message)
  374. return False
  375. return strutils.bool_from_string(vol_encryption_supported)
  376. @na_utils.trace
  377. def list_node_data_ports(self, node):
  378. ports = self.get_node_data_ports(node)
  379. return [port.get('port') for port in ports]
  380. @na_utils.trace
  381. def get_node_data_ports(self, node):
  382. """Get applicable data ports on the node."""
  383. api_args = {
  384. 'query': {
  385. 'net-port-info': {
  386. 'node': node,
  387. 'link-status': 'up',
  388. 'port-type': 'physical|if_group',
  389. 'role': 'data',
  390. },
  391. },
  392. 'desired-attributes': {
  393. 'net-port-info': {
  394. 'port': None,
  395. 'node': None,
  396. 'operational-speed': None,
  397. 'ifgrp-port': None,
  398. },
  399. },
  400. }
  401. result = self.send_iter_request('net-port-get-iter', api_args)
  402. net_port_info_list = result.get_child_by_name(
  403. 'attributes-list') or netapp_api.NaElement('none')
  404. ports = []
  405. for port_info in net_port_info_list.get_children():
  406. # Skip physical ports that are part of interface groups.
  407. if port_info.get_child_content('ifgrp-port'):
  408. continue
  409. port = {
  410. 'node': port_info.get_child_content('node'),
  411. 'port': port_info.get_child_content('port'),
  412. 'speed': port_info.get_child_content('operational-speed'),
  413. }
  414. ports.append(port)
  415. return self._sort_data_ports_by_speed(ports)
  416. @na_utils.trace
  417. def _sort_data_ports_by_speed(self, ports):
  418. def sort_key(port):
  419. value = port.get('speed')
  420. if not (value and isinstance(value, six.string_types)):
  421. return 0
  422. elif value.isdigit():
  423. return int(value)
  424. elif value == 'auto':
  425. return 3
  426. elif value == 'undef':
  427. return 2
  428. else:
  429. return 1
  430. return sorted(ports, key=sort_key, reverse=True)
  431. @na_utils.trace
  432. def list_root_aggregates(self):
  433. """Get names of all aggregates that contain node root volumes."""
  434. desired_attributes = {
  435. 'aggr-attributes': {
  436. 'aggregate-name': None,
  437. 'aggr-raid-attributes': {
  438. 'has-local-root': None,
  439. 'has-partner-root': None,
  440. },
  441. },
  442. }
  443. aggrs = self._get_aggregates(desired_attributes=desired_attributes)
  444. root_aggregates = []
  445. for aggr in aggrs:
  446. aggr_name = aggr.get_child_content('aggregate-name')
  447. aggr_raid_attrs = aggr.get_child_by_name('aggr-raid-attributes')
  448. local_root = strutils.bool_from_string(
  449. aggr_raid_attrs.get_child_content('has-local-root'))
  450. partner_root = strutils.bool_from_string(
  451. aggr_raid_attrs.get_child_content('has-partner-root'))
  452. if local_root or partner_root:
  453. root_aggregates.append(aggr_name)
  454. return root_aggregates
  455. @na_utils.trace
  456. def list_non_root_aggregates(self):
  457. """Get names of all aggregates that don't contain node root volumes."""
  458. query = {
  459. 'aggr-attributes': {
  460. 'aggr-raid-attributes': {
  461. 'has-local-root': 'false',
  462. 'has-partner-root': 'false',
  463. }
  464. },
  465. }
  466. return self._list_aggregates(query=query)
  467. @na_utils.trace
  468. def _list_aggregates(self, query=None):
  469. """Get names of all aggregates."""
  470. try:
  471. api_args = {
  472. 'desired-attributes': {
  473. 'aggr-attributes': {
  474. 'aggregate-name': None,
  475. },
  476. },
  477. }
  478. if query:
  479. api_args['query'] = query
  480. result = self.send_iter_request('aggr-get-iter', api_args)
  481. aggr_list = result.get_child_by_name(
  482. 'attributes-list').get_children()
  483. except AttributeError:
  484. msg = _("Could not list aggregates.")
  485. raise exception.NetAppException(msg)
  486. return [aggr.get_child_content('aggregate-name') for aggr
  487. in aggr_list]
  488. @na_utils.trace
  489. def list_vserver_aggregates(self):
  490. """Returns a list of aggregates available to a vserver.
  491. This must be called against a Vserver LIF.
  492. """
  493. return list(self.get_vserver_aggregate_capacities().keys())
  494. @na_utils.trace
  495. def create_network_interface(self, ip, netmask, vlan, node, port,
  496. vserver_name, lif_name, ipspace_name, mtu):
  497. """Creates LIF on VLAN port."""
  498. home_port_name = port
  499. if vlan:
  500. self._create_vlan(node, port, vlan)
  501. home_port_name = '%(port)s-%(tag)s' % {'port': port, 'tag': vlan}
  502. if self.features.BROADCAST_DOMAINS:
  503. self._ensure_broadcast_domain_for_port(
  504. node, home_port_name, mtu, ipspace=ipspace_name)
  505. LOG.debug('Creating LIF %(lif)s for Vserver %(vserver)s ',
  506. {'lif': lif_name, 'vserver': vserver_name})
  507. api_args = {
  508. 'address': ip,
  509. 'administrative-status': 'up',
  510. 'data-protocols': [
  511. {'data-protocol': 'nfs'},
  512. {'data-protocol': 'cifs'},
  513. ],
  514. 'home-node': node,
  515. 'home-port': home_port_name,
  516. 'netmask': netmask,
  517. 'interface-name': lif_name,
  518. 'role': 'data',
  519. 'vserver': vserver_name,
  520. }
  521. self.send_request('net-interface-create', api_args)
  522. @na_utils.trace
  523. def _create_vlan(self, node, port, vlan):
  524. try:
  525. api_args = {
  526. 'vlan-info': {
  527. 'parent-interface': port,
  528. 'node': node,
  529. 'vlanid': vlan,
  530. },
  531. }
  532. self.send_request('net-vlan-create', api_args)
  533. except netapp_api.NaApiError as e:
  534. if e.code == netapp_api.EDUPLICATEENTRY:
  535. LOG.debug('VLAN %(vlan)s already exists on port %(port)s',
  536. {'vlan': vlan, 'port': port})
  537. else:
  538. msg = _('Failed to create VLAN %(vlan)s on '
  539. 'port %(port)s. %(err_msg)s')
  540. msg_args = {'vlan': vlan, 'port': port, 'err_msg': e.message}
  541. raise exception.NetAppException(msg % msg_args)
  542. @na_utils.trace
  543. def delete_vlan(self, node, port, vlan):
  544. try:
  545. api_args = {
  546. 'vlan-info': {
  547. 'parent-interface': port,
  548. 'node': node,
  549. 'vlanid': vlan,
  550. },
  551. }
  552. self.send_request('net-vlan-delete', api_args)
  553. except netapp_api.NaApiError as e:
  554. p = re.compile('port already has a lif bound.*', re.IGNORECASE)
  555. if (e.code == netapp_api.EAPIERROR and re.match(p, e.message)):
  556. LOG.debug('VLAN %(vlan)s on port %(port)s node %(node)s '
  557. 'still used by LIF and cannot be deleted.',
  558. {'vlan': vlan, 'port': port, 'node': node})
  559. else:
  560. msg = _('Failed to delete VLAN %(vlan)s on '
  561. 'port %(port)s node %(node)s: %(err_msg)s')
  562. msg_args = {
  563. 'vlan': vlan,
  564. 'port': port,
  565. 'node': node,
  566. 'err_msg': e.message
  567. }
  568. raise exception.NetAppException(msg % msg_args)
  569. @na_utils.trace
  570. def create_route(self, gateway, destination=None):
  571. if not gateway:
  572. return
  573. if not destination:
  574. if ':' in gateway:
  575. destination = '::/0'
  576. else:
  577. destination = '0.0.0.0/0'
  578. try:
  579. api_args = {
  580. 'destination': destination,
  581. 'gateway': gateway,
  582. 'return-record': 'true',
  583. }
  584. self.send_request('net-routes-create', api_args)
  585. except netapp_api.NaApiError as e:
  586. p = re.compile('.*Duplicate route exists.*', re.IGNORECASE)
  587. if (e.code == netapp_api.EAPIERROR and re.match(p, e.message)):
  588. LOG.debug('Route to %(destination)s via gateway %(gateway)s '
  589. 'exists.',
  590. {'destination': destination, 'gateway': gateway})
  591. else:
  592. msg = _('Failed to create a route to %(destination)s via '
  593. 'gateway %(gateway)s: %(err_msg)s')
  594. msg_args = {
  595. 'destination': destination,
  596. 'gateway': gateway,
  597. 'err_msg': e.message,
  598. }
  599. raise exception.NetAppException(msg % msg_args)
  600. @na_utils.trace
  601. def _ensure_broadcast_domain_for_port(self, node, port, mtu,
  602. ipspace=DEFAULT_IPSPACE):
  603. """Ensure a port is in a broadcast domain. Create one if necessary.
  604. If the IPspace:domain pair match for the given port, which commonly
  605. happens in multi-node clusters, then there isn't anything to do.
  606. Otherwise, we can assume the IPspace is correct and extant by this
  607. point, so the remaining task is to remove the port from any domain it
  608. is already in, create the domain for the IPspace if it doesn't exist,
  609. and add the port to this domain.
  610. """
  611. # Derive the broadcast domain name from the IPspace name since they
  612. # need to be 1-1 and the default for both is the same name, 'Default'.
  613. domain = re.sub(r'ipspace', 'domain', ipspace)
  614. port_info = self._get_broadcast_domain_for_port(node, port)
  615. # Port already in desired ipspace and broadcast domain.
  616. if (port_info['ipspace'] == ipspace
  617. and port_info['broadcast-domain'] == domain):
  618. self._modify_broadcast_domain(domain, ipspace, mtu)
  619. return
  620. # If in another broadcast domain, remove port from it.
  621. if port_info['broadcast-domain']:
  622. self._remove_port_from_broadcast_domain(
  623. node, port, port_info['broadcast-domain'],
  624. port_info['ipspace'])
  625. # If desired broadcast domain doesn't exist, create it.
  626. if not self._broadcast_domain_exists(domain, ipspace):
  627. self._create_broadcast_domain(domain, ipspace, mtu)
  628. else:
  629. self._modify_broadcast_domain(domain, ipspace, mtu)
  630. # Move the port into the broadcast domain where it is needed.
  631. self._add_port_to_broadcast_domain(node, port, domain, ipspace)
  632. @na_utils.trace
  633. def _get_broadcast_domain_for_port(self, node, port):
  634. """Get broadcast domain for a specific port."""
  635. api_args = {
  636. 'query': {
  637. 'net-port-info': {
  638. 'node': node,
  639. 'port': port,
  640. },
  641. },
  642. 'desired-attributes': {
  643. 'net-port-info': {
  644. 'broadcast-domain': None,
  645. 'ipspace': None,
  646. },
  647. },
  648. }
  649. result = self.send_iter_request('net-port-get-iter', api_args)
  650. net_port_info_list = result.get_child_by_name(
  651. 'attributes-list') or netapp_api.NaElement('none')
  652. port_info = net_port_info_list.get_children()
  653. if not port_info:
  654. msg = _('Could not find port %(port)s on node %(node)s.')
  655. msg_args = {'port': port, 'node': node}
  656. raise exception.NetAppException(msg % msg_args)
  657. port = {
  658. 'broadcast-domain':
  659. port_info[0].get_child_content('broadcast-domain'),
  660. 'ipspace': port_info[0].get_child_content('ipspace')
  661. }
  662. return port
  663. @na_utils.trace
  664. def _broadcast_domain_exists(self, domain, ipspace):
  665. """Check if a broadcast domain exists."""
  666. api_args = {
  667. 'query': {
  668. 'net-port-broadcast-domain-info': {
  669. 'ipspace': ipspace,
  670. 'broadcast-domain': domain,
  671. },
  672. },
  673. 'desired-attributes': {
  674. 'net-port-broadcast-domain-info': None,
  675. },
  676. }
  677. result = self.send_iter_request('net-port-broadcast-domain-get-iter',
  678. api_args)
  679. return self._has_records(result)
  680. @na_utils.trace
  681. def _create_broadcast_domain(self, domain, ipspace, mtu):
  682. """Create a broadcast domain."""
  683. api_args = {
  684. 'ipspace': ipspace,
  685. 'broadcast-domain': domain,
  686. 'mtu': mtu,
  687. }
  688. self.send_request('net-port-broadcast-domain-create', api_args)
  689. @na_utils.trace
  690. def _modify_broadcast_domain(self, domain, ipspace, mtu):
  691. """Modify a broadcast domain."""
  692. api_args = {
  693. 'ipspace': ipspace,
  694. 'broadcast-domain': domain,
  695. 'mtu': mtu,
  696. }
  697. self.send_request('net-port-broadcast-domain-modify', api_args)
  698. @na_utils.trace
  699. def _delete_broadcast_domain(self, domain, ipspace):
  700. """Delete a broadcast domain."""
  701. api_args = {
  702. 'ipspace': ipspace,
  703. 'broadcast-domain': domain,
  704. }
  705. self.send_request('net-port-broadcast-domain-destroy', api_args)
  706. @na_utils.trace
  707. def _delete_broadcast_domains_for_ipspace(self, ipspace_name):
  708. """Deletes all broadcast domains in an IPspace."""
  709. ipspaces = self.get_ipspaces(ipspace_name=ipspace_name)
  710. if not ipspaces:
  711. return
  712. ipspace = ipspaces[0]
  713. for broadcast_domain_name in ipspace['broadcast-domains']:
  714. self._delete_broadcast_domain(broadcast_domain_name, ipspace_name)
  715. @na_utils.trace
  716. def _add_port_to_broadcast_domain(self, node, port, domain, ipspace):
  717. qualified_port_name = ':'.join([node, port])
  718. try:
  719. api_args = {
  720. 'ipspace': ipspace,
  721. 'broadcast-domain': domain,
  722. 'ports': {
  723. 'net-qualified-port-name': qualified_port_name,
  724. }
  725. }
  726. self.send_request('net-port-broadcast-domain-add-ports', api_args)
  727. except netapp_api.NaApiError as e:
  728. if e.code == (netapp_api.
  729. E_VIFMGR_PORT_ALREADY_ASSIGNED_TO_BROADCAST_DOMAIN):
  730. LOG.debug('Port %(port)s already exists in broadcast domain '
  731. '%(domain)s', {'port': port, 'domain': domain})
  732. else:
  733. msg = _('Failed to add port %(port)s to broadcast domain '
  734. '%(domain)s. %(err_msg)s')
  735. msg_args = {
  736. 'port': qualified_port_name,
  737. 'domain': domain,
  738. 'err_msg': e.message,
  739. }
  740. raise exception.NetAppException(msg % msg_args)
  741. @na_utils.trace
  742. def _remove_port_from_broadcast_domain(self, node, port, domain, ipspace):
  743. qualified_port_name = ':'.join([node, port])
  744. api_args = {
  745. 'ipspace': ipspace,
  746. 'broadcast-domain': domain,
  747. 'ports': {
  748. 'net-qualified-port-name': qualified_port_name,
  749. }
  750. }
  751. self.send_request('net-port-broadcast-domain-remove-ports', api_args)
  752. @na_utils.trace
  753. def network_interface_exists(self, vserver_name, node, port, ip, netmask,
  754. vlan):
  755. """Checks if LIF exists."""
  756. home_port_name = (port if not vlan else
  757. '%(port)s-%(tag)s' % {'port': port, 'tag': vlan})
  758. api_args = {
  759. 'query': {
  760. 'net-interface-info': {
  761. 'address': ip,
  762. 'home-node': node,
  763. 'home-port': home_port_name,
  764. 'netmask': netmask,
  765. 'vserver': vserver_name,
  766. },
  767. },
  768. 'desired-attributes': {
  769. 'net-interface-info': {
  770. 'interface-name': None,
  771. },
  772. },
  773. }
  774. result = self.send_iter_request('net-interface-get-iter', api_args)
  775. return self._has_records(result)
  776. @na_utils.trace
  777. def list_network_interfaces(self):
  778. """Get the names of available LIFs."""
  779. api_args = {
  780. 'desired-attributes': {
  781. 'net-interface-info': {
  782. 'interface-name': None,
  783. },
  784. },
  785. }
  786. result = self.send_iter_request('net-interface-get-iter', api_args)
  787. lif_info_list = result.get_child_by_name(
  788. 'attributes-list') or netapp_api.NaElement('none')
  789. return [lif_info.get_child_content('interface-name') for lif_info
  790. in lif_info_list.get_children()]
  791. @na_utils.trace
  792. def get_network_interfaces(self, protocols=None):
  793. """Get available LIFs."""
  794. protocols = na_utils.convert_to_list(protocols)
  795. protocols = [protocol.lower() for protocol in protocols]
  796. api_args = {
  797. 'query': {
  798. 'net-interface-info': {
  799. 'data-protocols': {
  800. 'data-protocol': '|'.join(protocols),
  801. }
  802. }
  803. }
  804. } if protocols else None
  805. result = self.send_iter_request('net-interface-get-iter', api_args)
  806. lif_info_list = result.get_child_by_name(
  807. 'attributes-list') or netapp_api.NaElement('none')
  808. interfaces = []
  809. for lif_info in lif_info_list.get_children():
  810. lif = {
  811. 'address': lif_info.get_child_content('address'),
  812. 'home-node': lif_info.get_child_content('home-node'),
  813. 'home-port': lif_info.get_child_content('home-port'),
  814. 'interface-name': lif_info.get_child_content('interface-name'),
  815. 'netmask': lif_info.get_child_content('netmask'),
  816. 'role': lif_info.get_child_content('role'),
  817. 'vserver': lif_info.get_child_content('vserver'),
  818. }
  819. interfaces.append(lif)
  820. return interfaces
  821. @na_utils.trace
  822. def get_ipspaces(self, ipspace_name=None):
  823. """Gets one or more IPSpaces."""
  824. if not self.features.IPSPACES:
  825. return []
  826. api_args = {}
  827. if ipspace_name:
  828. api_args['query'] = {
  829. 'net-ipspaces-info': {
  830. 'ipspace': ipspace_name,
  831. }
  832. }
  833. result = self.send_iter_request('net-ipspaces-get-iter', api_args)
  834. if not self._has_records(result):
  835. return []
  836. ipspaces = []
  837. for net_ipspaces_info in result.get_child_by_name(
  838. 'attributes-list').get_children():
  839. ipspace = {
  840. 'ports': [],
  841. 'vservers': [],
  842. 'broadcast-domains': [],
  843. }
  844. ports = net_ipspaces_info.get_child_by_name(
  845. 'ports') or netapp_api.NaElement('none')
  846. for port in ports.get_children():
  847. ipspace['ports'].append(port.get_content())
  848. vservers = net_ipspaces_info.get_child_by_name(
  849. 'vservers') or netapp_api.NaElement('none')
  850. for vserver in vservers.get_children():
  851. ipspace['vservers'].append(vserver.get_content())
  852. broadcast_domains = net_ipspaces_info.get_child_by_name(
  853. 'broadcast-domains') or netapp_api.NaElement('none')
  854. for broadcast_domain in broadcast_domains.get_children():
  855. ipspace['broadcast-domains'].append(
  856. broadcast_domain.get_content())
  857. ipspace['ipspace'] = net_ipspaces_info.get_child_content('ipspace')
  858. ipspace['id'] = net_ipspaces_info.get_child_content('id')
  859. ipspace['uuid'] = net_ipspaces_info.get_child_content('uuid')
  860. ipspaces.append(ipspace)
  861. return ipspaces
  862. @na_utils.trace
  863. def ipspace_exists(self, ipspace_name):
  864. """Checks if IPspace exists."""
  865. if not self.features.IPSPACES:
  866. return False
  867. api_args = {
  868. 'query': {
  869. 'net-ipspaces-info': {
  870. 'ipspace': ipspace_name,
  871. },
  872. },
  873. 'desired-attributes': {
  874. 'net-ipspaces-info': {
  875. 'ipspace': None,
  876. },
  877. },
  878. }
  879. result = self.send_iter_request('net-ipspaces-get-iter', api_args)
  880. return self._has_records(result)
  881. @na_utils.trace
  882. def create_ipspace(self, ipspace_name):
  883. """Creates an IPspace."""
  884. api_args = {'ipspace': ipspace_name}
  885. self.send_request('net-ipspaces-create', api_args)
  886. @na_utils.trace
  887. def delete_ipspace(self, ipspace_name):
  888. """Deletes an IPspace."""
  889. self._delete_broadcast_domains_for_ipspace(ipspace_name)
  890. api_args = {'ipspace': ipspace_name}
  891. self.send_request('net-ipspaces-destroy', api_args)
  892. @na_utils.trace
  893. def add_vserver_to_ipspace(self, ipspace_name, vserver_name):
  894. """Assigns a vserver to an IPspace."""
  895. api_args = {'ipspace': ipspace_name, 'vserver': vserver_name}
  896. self.send_request('net-ipspaces-assign-vserver', api_args)
  897. @na_utils.trace
  898. def get_node_for_aggregate(self, aggregate_name):
  899. """Get home node for the specified aggregate.
  900. This API could return None, most notably if it was sent
  901. to a Vserver LIF, so the caller must be able to handle that case.
  902. """
  903. if not aggregate_name:
  904. return None
  905. desired_attributes = {
  906. 'aggr-attributes': {
  907. 'aggregate-name': None,
  908. 'aggr-ownership-attributes': {
  909. 'home-name': None,
  910. },
  911. },
  912. }
  913. try:
  914. aggrs = self._get_aggregates(aggregate_names=[aggregate_name],
  915. desired_attributes=desired_attributes)
  916. except netapp_api.NaApiError as e:
  917. if e.code == netapp_api.EAPINOTFOUND:
  918. return None
  919. else:
  920. raise
  921. if len(aggrs) < 1:
  922. return None
  923. aggr_ownership_attrs = aggrs[0].get_child_by_name(
  924. 'aggr-ownership-attributes') or netapp_api.NaElement('none')
  925. return aggr_ownership_attrs.get_child_content('home-name')
  926. @na_utils.trace
  927. def get_cluster_aggregate_capacities(self, aggregate_names):
  928. """Calculates capacity of one or more aggregates.
  929. Returns dictionary of aggregate capacity metrics.
  930. 'size-used' is the actual space consumed on the aggregate.
  931. 'size-available' is the actual space remaining.
  932. 'size-total' is the defined total aggregate size, such that
  933. used + available = total.
  934. """
  935. if aggregate_names is not None and len(aggregate_names) == 0:
  936. return {}
  937. desired_attributes = {
  938. 'aggr-attributes': {
  939. 'aggregate-name': None,
  940. 'aggr-space-attributes': {
  941. 'size-available': None,
  942. 'size-total': None,
  943. 'size-used': None,
  944. },
  945. },
  946. }
  947. aggrs = self._get_aggregates(aggregate_names=aggregate_names,
  948. desired_attributes=desired_attributes)
  949. aggr_space_dict = dict()
  950. for aggr in aggrs:
  951. aggr_name = aggr.get_child_content('aggregate-name')
  952. aggr_space_attrs = aggr.get_child_by_name('aggr-space-attributes')
  953. aggr_space_dict[aggr_name] = {
  954. 'available':
  955. int(aggr_space_attrs.get_child_content('size-available')),
  956. 'total':
  957. int(aggr_space_attrs.get_child_content('size-total')),
  958. 'used':
  959. int(aggr_space_attrs.get_child_content('size-used')),
  960. }
  961. return aggr_space_dict
  962. @na_utils.trace
  963. def get_vserver_aggregate_capacities(self, aggregate_names=None):
  964. """Calculates capacity of one or more aggregates for a vserver.
  965. Returns dictionary of aggregate capacity metrics. This must
  966. be called against a Vserver LIF.
  967. """
  968. if aggregate_names is not None and len(aggregate_names) == 0:
  969. return {}
  970. api_args = {
  971. 'desired-attributes': {
  972. 'vserver-info': {
  973. 'vserver-name': None,
  974. 'vserver-aggr-info-list': {
  975. 'vserver-aggr-info': {
  976. 'aggr-name': None,
  977. 'aggr-availsize': None,
  978. },
  979. },
  980. },
  981. },
  982. }
  983. result = self.send_request('vserver-get', api_args)
  984. attributes = result.get_child_by_name('attributes')
  985. if not attributes:
  986. raise exception.NetAppException('Failed to read Vserver info')
  987. vserver_info = attributes.get_child_by_name('vserver-info')
  988. vserver_name = vserver_info.get_child_content('vserver-name')
  989. vserver_aggr_info_element = vserver_info.get_child_by_name(
  990. 'vserver-aggr-info-list') or netapp_api.NaElement('none')
  991. vserver_aggr_info_list = vserver_aggr_info_element.get_children()
  992. if not vserver_aggr_info_list:
  993. LOG.warning('No aggregates assigned to Vserver %s.',
  994. vserver_name)
  995. # Return dict of key-value pair of aggr_name:aggr_size_available.
  996. aggr_space_dict = {}
  997. for aggr_info in vserver_aggr_info_list:
  998. aggr_name = aggr_info.get_child_content('aggr-name')
  999. if aggregate_names is None or aggr_name in aggregate_names:
  1000. aggr_size = int(aggr_info.get_child_content('aggr-availsize'))
  1001. aggr_space_dict[aggr_name] = {'available': aggr_size}
  1002. LOG.debug('Found available Vserver aggregates: %s', aggr_space_dict)
  1003. return aggr_space_dict
  1004. @na_utils.trace
  1005. def _get_aggregates(self, aggregate_names=None, desired_attributes=None):
  1006. query = {
  1007. 'aggr-attributes': {
  1008. 'aggregate-name': '|'.join(aggregate_names),
  1009. }
  1010. } if aggregate_names else None
  1011. api_args = {}
  1012. if query:
  1013. api_args['query'] = query
  1014. if desired_attributes:
  1015. api_args['desired-attributes'] = desired_attributes
  1016. result = self.send_iter_request('aggr-get-iter', api_args)
  1017. if not self._has_records(result):
  1018. return []
  1019. else:
  1020. return result.get_child_by_name('attributes-list').get_children()
  1021. def get_performance_instance_uuids(self, object_name, node_name):
  1022. """Get UUIDs of performance instances for a cluster node."""
  1023. api_args = {
  1024. 'objectname': object_name,
  1025. 'query': {
  1026. 'instance-info': {
  1027. 'uuid': node_name + ':*',
  1028. }
  1029. }
  1030. }
  1031. result = self.send_request('perf-object-instance-list-info-iter',
  1032. api_args)
  1033. uuids = []
  1034. instances = result.get_child_by_name(
  1035. 'attributes-list') or netapp_api.NaElement('None')
  1036. for instance_info in instances.get_children():
  1037. uuids.append(instance_info.get_child_content('uuid'))
  1038. return uuids
  1039. def get_performance_counter_info(self, object_name, counter_name):
  1040. """Gets info about one or more Data ONTAP performance counters."""
  1041. api_args = {'objectname': object_name}
  1042. result = self.send_request('perf-object-counter-list-info', api_args)
  1043. counters = result.get_child_by_name(
  1044. 'counters') or netapp_api.NaElement('None')
  1045. for counter in counters.get_children():
  1046. if counter.get_child_content('name') == counter_name:
  1047. labels = []
  1048. label_list = counter.get_child_by_name(
  1049. 'labels') or netapp_api.NaElement('None')
  1050. for label in label_list.get_children():
  1051. labels.extend(label.get_content().split(','))
  1052. base_counter = counter.get_child_content('base-counter')
  1053. return {
  1054. 'name': counter_name,
  1055. 'labels': labels,
  1056. 'base-counter': base_counter,
  1057. }
  1058. else:
  1059. raise exception.NotFound(_('Counter %s not found') % counter_name)
  1060. def get_performance_counters(self, object_name, instance_uuids,
  1061. counter_names):
  1062. """Gets one or more cDOT performance counters."""
  1063. api_args = {
  1064. 'objectname': object_name,
  1065. 'instance-uuids': [
  1066. {'instance-uuid': instance_uuid}
  1067. for instance_uuid in instance_uuids
  1068. ],
  1069. 'counters': [
  1070. {'counter': counter} for counter in counter_names
  1071. ],
  1072. }
  1073. result = self.send_request('perf-object-get-instances', api_args)
  1074. counter_data = []
  1075. timestamp = result.get_child_content('timestamp')
  1076. instances = result.get_child_by_name(
  1077. 'instances') or netapp_api.NaElement('None')
  1078. for instance in instances.get_children():
  1079. instance_name = instance.get_child_content('name')
  1080. instance_uuid = instance.get_child_content('uuid')
  1081. node_name = instance_uuid.split(':')[0]
  1082. counters = instance.get_child_by_name(
  1083. 'counters') or netapp_api.NaElement('None')
  1084. for counter in counters.get_children():
  1085. counter_name = counter.get_child_content('name')
  1086. counter_value = counter.get_child_content('value')
  1087. counter_data.append({
  1088. 'instance-name': instance_name,
  1089. 'instance-uuid': instance_uuid,
  1090. 'node-name': node_name,
  1091. 'timestamp': timestamp,
  1092. counter_name: counter_value,
  1093. })
  1094. return counter_data
  1095. @na_utils.trace
  1096. def setup_security_services(self, security_services, vserver_client,
  1097. vserver_name):
  1098. api_args = {
  1099. 'name-mapping-switch': [
  1100. {'nmswitch': 'ldap'},
  1101. {'nmswitch': 'file'}
  1102. ],
  1103. 'name-server-switch': [
  1104. {'nsswitch': 'ldap'},
  1105. {'nsswitch': 'file'}
  1106. ],
  1107. 'vserver-name': vserver_name,
  1108. }
  1109. self.send_request('vserver-modify', api_args)
  1110. for security_service in security_services:
  1111. if security_service['type'].lower() == 'ldap':
  1112. vserver_client.configure_ldap(security_service)
  1113. elif security_service['type'].lower() == 'active_directory':
  1114. vserver_client.configure_active_directory(security_service,
  1115. vserver_name)
  1116. elif security_service['type'].lower() == 'kerberos':
  1117. self.create_kerberos_realm(security_service)
  1118. vserver_client.configure_kerberos(security_service,
  1119. vserver_name)
  1120. else:
  1121. msg = _('Unsupported security service type %s for '
  1122. 'Data ONTAP driver')
  1123. raise exception.NetAppException(msg % security_service['type'])
  1124. @na_utils.trace
  1125. def enable_nfs(self, versions):
  1126. """Enables NFS on Vserver."""
  1127. self.send_request('nfs-enable')
  1128. self._enable_nfs_protocols(versions)
  1129. self._create_default_nfs_export_rules()
  1130. @na_utils.trace
  1131. def _enable_nfs_protocols(self, versions):
  1132. """Set the enabled NFS protocol versions."""
  1133. nfs3 = 'true' if 'nfs3' in versions else 'false'
  1134. nfs40 = 'true' if 'nfs4.0' in versions else 'false'
  1135. nfs41 = 'true' if 'nfs4.1' in versions else 'false'
  1136. nfs_service_modify_args = {
  1137. 'is-nfsv3-enabled': nfs3,
  1138. 'is-nfsv40-enabled': nfs40,
  1139. 'is-nfsv41-enabled': nfs41,
  1140. }
  1141. self.send_request('nfs-service-modify', nfs_service_modify_args)
  1142. @na_utils.trace
  1143. def _create_default_nfs_export_rules(self):
  1144. """Create the default export rule for the NFS service."""
  1145. export_rule_create_args = {
  1146. 'client-match': '0.0.0.0/0',
  1147. 'policy-name': 'default',
  1148. 'ro-rule': {
  1149. 'security-flavor': 'any',
  1150. },
  1151. 'rw-rule': {
  1152. 'security-flavor': 'never',
  1153. },
  1154. }
  1155. self.send_request('export-rule-create', export_rule_create_args)
  1156. export_rule_create_args['client-match'] = '::/0'
  1157. self.send_request('export-rule-create', export_rule_create_args)
  1158. @na_utils.trace
  1159. def configure_ldap(self, security_service):
  1160. """Configures LDAP on Vserver."""
  1161. config_name = hashlib.md5(six.b(security_service['id'])).hexdigest()
  1162. api_args = {
  1163. 'ldap-client-config': config_name,
  1164. 'servers': {
  1165. 'ip-address': security_service['server'],
  1166. },
  1167. 'tcp-port': '389',
  1168. 'schema': 'RFC-2307',
  1169. 'bind-password': security_service['password'],
  1170. }
  1171. self.send_request('ldap-client-create', api_args)
  1172. api_args = {'client-config': config_name, 'client-enabled': 'true'}
  1173. self.send_request('ldap-config-create', api_args)
  1174. @na_utils.trace
  1175. def configure_active_directory(self, security_service, vserver_name):
  1176. """Configures AD on Vserver."""
  1177. self.configure_dns(security_service)
  1178. # 'cifs-server' is CIFS Server NetBIOS Name, max length is 15.
  1179. # Should be unique within each domain (data['domain']).
  1180. cifs_server = (vserver_name[0:7] + '..' + vserver_name[-6:]).upper()
  1181. api_args = {
  1182. 'admin-username': security_service['user'],
  1183. 'admin-password': security_service['password'],
  1184. 'force-account-overwrite': 'true',
  1185. 'cifs-server': cifs_server,
  1186. 'domain': security_service['domain'],
  1187. }
  1188. try:
  1189. LOG.debug("Trying to setup CIFS server with data: %s", api_args)
  1190. self.send_request('cifs-server-create', api_args)
  1191. except netapp_api.NaApiError as e:
  1192. msg = _("Failed to create CIFS server entry. %s")
  1193. raise exception.NetAppException(msg % e.message)
  1194. @na_utils.trace
  1195. def create_kerberos_realm(self, security_service):
  1196. """Creates Kerberos realm on cluster."""
  1197. api_args = {
  1198. 'admin-server-ip': security_service['server'],
  1199. 'admin-server-port': '749',
  1200. 'clock-skew': '5',
  1201. 'comment': '',
  1202. 'config-name': security_service['id'],
  1203. 'kdc-ip': security_service['server'],
  1204. 'kdc-port': '88',
  1205. 'kdc-vendor': 'other',
  1206. 'password-server-ip': security_service['server'],
  1207. 'password-server-port': '464',
  1208. 'realm': security_service['domain'].upper(),
  1209. }
  1210. try:
  1211. self.send_request('kerberos-realm-create', api_args)
  1212. except netapp_api.NaApiError as e:
  1213. if e.code == netapp_api.EDUPLICATEENTRY:
  1214. LOG.debug('Kerberos realm config already exists.')
  1215. else:
  1216. msg = _('Failed to create Kerberos realm. %s')
  1217. raise exception.NetAppException(msg % e.message)
  1218. @na_utils.trace
  1219. def configure_kerberos(self, security_service, vserver_name):
  1220. """Configures Kerberos for NFS on Vserver."""
  1221. self.configure_dns(security_service)
  1222. spn = self._get_kerberos_service_principal_name(
  1223. security_service, vserver_name)
  1224. lifs = self.list_network_interfaces()
  1225. if not lifs:
  1226. msg = _("Cannot set up Kerberos. There are no LIFs configured.")
  1227. raise exception.NetAppException(msg)
  1228. for lif_name in lifs:
  1229. api_args = {
  1230. 'admin-password': security_service['password'],
  1231. 'admin-user-name': security_service['user'],
  1232. 'interface-name': lif_name,
  1233. 'is-kerberos-enabled': 'true',
  1234. 'service-principal-name': spn,
  1235. }
  1236. self.send_request('kerberos-config-modify', api_args)
  1237. @na_utils.trace
  1238. def _get_kerberos_service_principal_name(self, security_service,
  1239. vserver_name):
  1240. return ('nfs/' + vserver_name.replace('_', '-') + '.' +
  1241. security_service['domain'] + '@' +
  1242. security_service['domain'].upper())
  1243. @na_utils.trace
  1244. def configure_dns(self, security_service):
  1245. api_args = {
  1246. 'domains': {
  1247. 'string': security_service['domain'],
  1248. },
  1249. 'name-servers': {
  1250. 'ip-address': security_service['dns_ip'],
  1251. },
  1252. 'dns-state': 'enabled',
  1253. }
  1254. try:
  1255. self.send_request('net-dns-create', api_args)
  1256. except netapp_api.NaApiError as e:
  1257. if e.code == netapp_api.EDUPLICATEENTRY:
  1258. LOG.error("DNS exists for Vserver.")
  1259. else:
  1260. msg = _("Failed to configure DNS. %s")
  1261. raise exception.NetAppException(msg % e.message)
  1262. @na_utils.trace
  1263. def create_volume(self, aggregate_name, volume_name, size_gb,
  1264. thin_provisioned=False, snapshot_policy=None,
  1265. language=None, dedup_enabled=False,
  1266. compression_enabled=False, max_files=None,
  1267. snapshot_reserve=None, volume_type='rw',
  1268. qos_policy_group=None,
  1269. encrypt=False, **options):
  1270. """Creates a volume."""
  1271. api_args = {
  1272. 'containing-aggr-name': aggregate_name,
  1273. 'size': six.text_type(size_gb) + 'g',
  1274. 'volume': volume_name,
  1275. 'volume-type': volume_type,
  1276. }
  1277. if volume_type != 'dp':
  1278. api_args['junction-path'] = '/%s' % volume_name
  1279. if thin_provisioned:
  1280. api_args['space-reserve'] = 'none'
  1281. if snapshot_policy is not None:
  1282. api_args['snapshot-policy'] = snapshot_policy
  1283. if language is not None:
  1284. api_args['language-code'] = language
  1285. if snapshot_reserve is not None:
  1286. api_args['percentage-snapshot-reserve'] = six.text_type(
  1287. snapshot_reserve)
  1288. if qos_policy_group is not None:
  1289. api_args['qos-policy-group-name'] = qos_policy_group
  1290. if encrypt is True:
  1291. if not self.features.FLEXVOL_ENCRYPTION:
  1292. msg = 'Flexvol encryption is not supported on this backend.'
  1293. raise exception.NetAppException(msg)
  1294. else:
  1295. api_args['encrypt'] = 'true'
  1296. self.send_request('volume-create', api_args)
  1297. self.update_volume_efficiency_attributes(volume_name,
  1298. dedup_enabled,
  1299. compression_enabled)
  1300. if max_files is not None:
  1301. self.set_volume_max_files(volume_name, max_files)
  1302. @na_utils.trace
  1303. def enable_dedup(self, volume_name):
  1304. """Enable deduplication on volume."""
  1305. api_args = {'path': '/vol/%s' % volume_name}
  1306. self.send_request('sis-enable', api_args)
  1307. @na_utils.trace
  1308. def disable_dedup(self, volume_name):
  1309. """Disable deduplication on volume."""
  1310. api_args = {'path': '/vol/%s' % volume_name}
  1311. self.send_request('sis-disable', api_args)
  1312. @na_utils.trace
  1313. def enable_compression(self, volume_name):
  1314. """Enable compression on volume."""
  1315. api_args = {
  1316. 'path': '/vol/%s' % volume_name,
  1317. 'enable-compression': 'true'
  1318. }
  1319. self.send_request('sis-set-config', api_args)
  1320. @na_utils.trace
  1321. def disable_compression(self, volume_name):
  1322. """Disable compression on volume."""
  1323. api_args = {
  1324. 'path': '/vol/%s' % volume_name,
  1325. 'enable-compression': 'false'
  1326. }
  1327. self.send_request('sis-set-config', api_args)
  1328. @na_utils.trace
  1329. def get_volume_efficiency_status(self, volume_name):
  1330. """Get dedupe & compression status for a volume."""
  1331. api_args = {
  1332. 'query': {
  1333. 'sis-status-info': {
  1334. 'path': '/vol/%s' % volume_name,
  1335. },
  1336. },
  1337. 'desired-attributes': {
  1338. 'sis-status-info': {
  1339. 'state': None,
  1340. 'is-compression-enabled': None,
  1341. },
  1342. },
  1343. }
  1344. result = self.send_iter_request('sis-get-iter', api_args)
  1345. attributes_list = result.get_child_by_name(
  1346. 'attributes-list') or netapp_api.NaElement('none')
  1347. sis_status_info = attributes_list.get_child_by_name(
  1348. 'sis-status-info') or netapp_api.NaElement('none')
  1349. return {
  1350. 'dedupe': True if 'enabled' == sis_status_info.get_child_content(
  1351. 'state') else False,
  1352. 'compression': True if 'true' == sis_status_info.get_child_content(
  1353. 'is-compression-enabled') else False,
  1354. }
  1355. @na_utils.trace
  1356. def set_volume_max_files(self, volume_name, max_files):
  1357. """Set flexvol file limit."""
  1358. api_args = {
  1359. 'query': {
  1360. 'volume-attributes': {
  1361. 'volume-id-attributes': {
  1362. 'name': volume_name,
  1363. },
  1364. },
  1365. },
  1366. 'attributes': {
  1367. 'volume-attributes': {
  1368. 'volume-inode-attributes': {
  1369. 'files-total': max_files,
  1370. },
  1371. },
  1372. },
  1373. }
  1374. self.send_request('volume-modify-iter', api_args)
  1375. @na_utils.trace
  1376. def set_volume_size(self, volume_name, size_gb):
  1377. """Set volume size."""
  1378. api_args = {
  1379. 'query': {
  1380. 'volume-attributes': {
  1381. 'volume-id-attributes': {
  1382. 'name': volume_name,
  1383. },
  1384. },
  1385. },
  1386. 'attributes': {
  1387. 'volume-attributes': {
  1388. 'volume-space-attributes': {
  1389. 'size': int(size_gb) * units.Gi,
  1390. },
  1391. },
  1392. },
  1393. }
  1394. result = self.send_request('volume-modify-iter', api_args)
  1395. failures = result.get_child_content('num-failed')
  1396. if failures and int(failures) > 0:
  1397. failure_list = result.get_child_by_name(
  1398. 'failure-list') or netapp_api.NaElement('none')
  1399. errors = failure_list.get_children()
  1400. if errors:
  1401. raise netapp_api.NaApiError(
  1402. errors[0].get_child_content('error-code'),
  1403. errors[0].get_child_content('error-message'))
  1404. @na_utils.trace
  1405. def set_volume_filesys_size_fixed(self,
  1406. volume_name, filesys_size_fixed=False):
  1407. """Set volume file system size fixed to true/false."""
  1408. api_args = {
  1409. 'query': {
  1410. 'volume-attributes': {
  1411. 'volume-id-attributes': {
  1412. 'name': volume_name,
  1413. },
  1414. },
  1415. },
  1416. 'attributes': {
  1417. 'volume-attributes': {
  1418. 'volume-space-attributes': {
  1419. 'is-filesys-size-fixed': six.text_type(
  1420. filesys_size_fixed).lower(),
  1421. },
  1422. },
  1423. },
  1424. }
  1425. result = self.send_request('volume-modify-iter', api_args)
  1426. failures = result.get_child_content('num-failed')
  1427. if failures and int(failures) > 0:
  1428. failure_list = result.get_child_by_name(
  1429. 'failure-list') or netapp_api.NaElement('none')
  1430. errors = failure_list.get_children()
  1431. if errors:
  1432. raise netapp_api.NaApiError(
  1433. errors[0].get_child_content('error-code'),
  1434. errors[0].get_child_content('error-message'))
  1435. @na_utils.trace
  1436. def set_volume_security_style(self, volume_name, security_style='unix'):
  1437. """Set volume security style"""
  1438. api_args = {
  1439. 'query': {
  1440. 'volume-attributes': {
  1441. 'volume-id-attributes': {
  1442. 'name': volume_name,
  1443. },
  1444. },
  1445. },
  1446. 'attributes': {
  1447. 'volume-attributes': {
  1448. 'volume-security-attributes': {
  1449. 'style': security_style,
  1450. },
  1451. },
  1452. },
  1453. }
  1454. result = self.send_request('volume-modify-iter', api_args)
  1455. failures = result.get_child_content('num-failed')
  1456. if failures and int(failures) > 0:
  1457. failure_list = result.get_child_by_name(
  1458. 'failure-list') or netapp_api.NaElement('none')
  1459. errors = failure_list.get_children()
  1460. if errors:
  1461. raise netapp_api.NaApiError(
  1462. errors[0].get_child_content('error-code'),
  1463. errors[0].get_child_content('error-message'))
  1464. @na_utils.trace
  1465. def set_volume_name(self, volume_name, new_volume_name):
  1466. """Set flexvol name."""
  1467. api_args = {
  1468. 'volume': volume_name,
  1469. 'new-volume-name': new_volume_name,
  1470. }
  1471. self.send_request('volume-rename', api_args)
  1472. @na_utils.trace
  1473. def modify_volume(self, aggregate_name, volume_name,
  1474. thin_provisioned=False, snapshot_policy=None,
  1475. language=None, dedup_enabled=False,
  1476. compression_enabled=False, max_files=None,
  1477. qos_policy_group=None, **options):
  1478. """Update backend volume for a share as necessary."""
  1479. api_args = {
  1480. 'query': {
  1481. 'volume-attributes': {
  1482. 'volume-id-attributes': {
  1483. 'containing-aggregate-name': aggregate_name,
  1484. 'name': volume_name,
  1485. },
  1486. },
  1487. },
  1488. 'attributes': {
  1489. 'volume-attributes': {
  1490. 'volume-inode-attributes': {},
  1491. 'volume-language-attributes': {},
  1492. 'volume-snapshot-attributes': {},
  1493. 'volume-space-attributes': {
  1494. 'space-guarantee': ('none' if thin_provisioned else
  1495. 'volume'),
  1496. },
  1497. },
  1498. },
  1499. }
  1500. if language:
  1501. api_args['attributes']['volume-attributes'][
  1502. 'volume-language-attributes']['language'] = language
  1503. if max_files:
  1504. api_args['attributes']['volume-attributes'][
  1505. 'volume-inode-attributes']['files-total'] = max_files
  1506. if snapshot_policy:
  1507. api_args['attributes']['volume-attributes'][
  1508. 'volume-snapshot-attributes'][
  1509. 'snapshot-policy'] = snapshot_policy
  1510. if qos_policy_group:
  1511. api_args['attributes']['volume-attributes'][
  1512. 'volume-qos-attributes'] = {
  1513. 'policy-group-name': qos_policy_group,
  1514. }
  1515. self.send_request('volume-modify-iter', api_args)
  1516. # Efficiency options must be handled separately
  1517. self.update_volume_efficiency_attributes(volume_name,
  1518. dedup_enabled,
  1519. compression_enabled)
  1520. @na_utils.trace
  1521. def update_volume_efficiency_attributes(self, volume_name, dedup_enabled,
  1522. compression_enabled):
  1523. """Update dedupe & compression attributes to match desired values."""
  1524. efficiency_status = self.get_volume_efficiency_status(volume_name)
  1525. # cDOT compression requires dedup to be enabled
  1526. dedup_enabled = dedup_enabled or compression_enabled
  1527. # enable/disable dedup if needed
  1528. if dedup_enabled and not efficiency_status['dedupe']:
  1529. self.enable_dedup(volume_name)
  1530. elif not dedup_enabled and efficiency_status['dedupe']:
  1531. self.disable_dedup(volume_name)
  1532. # enable/disable compression if needed
  1533. if compression_enabled and not efficiency_status['compression']:
  1534. self.enable_compression(volume_name)
  1535. elif not compression_enabled and efficiency_status['compression']:
  1536. self.disable_compression(volume_name)
  1537. @na_utils.trace
  1538. def volume_exists(self, volume_name):
  1539. """Checks if volume exists."""
  1540. LOG.debug('Checking if volume %s exists', volume_name)
  1541. api_args = {
  1542. 'query': {
  1543. 'volume-attributes': {
  1544. 'volume-id-attributes': {
  1545. 'name': volume_name,
  1546. },
  1547. },
  1548. },
  1549. 'desired-attributes': {
  1550. 'volume-attributes': {
  1551. 'volume-id-attributes': {
  1552. 'name': None,
  1553. },
  1554. },
  1555. },
  1556. }
  1557. result = self.send_iter_request('volume-get-iter', api_args)
  1558. return self._has_records(result)
  1559. @na_utils.trace
  1560. def is_flexvol_encrypted(self, volume_name, vserver_name):
  1561. """Checks whether the volume is encrypted or not."""
  1562. if not self.features.FLEXVOL_ENCRYPTION:
  1563. return False
  1564. api_args = {
  1565. 'query': {
  1566. 'volume-attributes': {
  1567. 'encrypt': 'true',
  1568. 'volume-id-attributes': {
  1569. 'name': volume_name,
  1570. 'owning-vserver-name': vserver_name,
  1571. },
  1572. },
  1573. },
  1574. 'desired-attributes': {
  1575. 'volume-attributes': {
  1576. 'encrypt': None,
  1577. },
  1578. },
  1579. }
  1580. result = self.send_iter_request('volume-get-iter', api_args)
  1581. if self._has_records(result):
  1582. attributes_list = result.get_child_by_name(
  1583. 'attributes-list') or netapp_api.NaElement('none')
  1584. volume_attributes = attributes_list.get_child_by_name(
  1585. 'volume-attributes') or netapp_api.NaElement('none')
  1586. encrypt = volume_attributes.get_child_content('encrypt')
  1587. if encrypt:
  1588. return True
  1589. return False
  1590. @na_utils.trace
  1591. def get_aggregate_for_volume(self, volume_name):
  1592. """Get the name of the aggregate containing a volume."""
  1593. api_args = {
  1594. 'query': {
  1595. 'volume-attributes': {
  1596. 'volume-id-attributes': {
  1597. 'name': volume_name,
  1598. },
  1599. },
  1600. },
  1601. 'desired-attributes': {
  1602. 'volume-attributes': {
  1603. 'volume-id-attributes': {
  1604. 'containing-aggregate-name': None,
  1605. 'name': None,
  1606. },
  1607. },
  1608. },
  1609. }
  1610. result = self.send_iter_request('volume-get-iter', api_args)
  1611. attributes_list = result.get_child_by_name(
  1612. 'attributes-list') or netapp_api.NaElement('none')
  1613. volume_attributes = attributes_list.get_child_by_name(
  1614. 'volume-attributes') or netapp_api.NaElement('none')
  1615. volume_id_attributes = volume_attributes.get_child_by_name(
  1616. 'volume-id-attributes') or netapp_api.NaElement('none')
  1617. aggregate = volume_id_attributes.get_child_content(
  1618. 'containing-aggregate-name')
  1619. if not aggregate:
  1620. msg = _('Could not find aggregate for volume %s.')
  1621. raise exception.NetAppException(msg % volume_name)
  1622. return aggregate
  1623. @na_utils.trace
  1624. def volume_has_luns(self, volume_name):
  1625. """Checks if volume has LUNs."""
  1626. LOG.debug('Checking if volume %s has LUNs', volume_name)
  1627. api_args = {
  1628. 'query': {
  1629. 'lun-info': {
  1630. 'volume': volume_name,
  1631. },
  1632. },
  1633. 'desired-attributes': {
  1634. 'lun-info': {
  1635. 'path': None,
  1636. },
  1637. },
  1638. }
  1639. result = self.send_iter_request('lun-get-iter', api_args)
  1640. return self._has_records(result)
  1641. @na_utils.trace
  1642. def volume_has_junctioned_volumes(self, volume_name):
  1643. """Checks if volume has volumes mounted beneath its junction path."""
  1644. junction_path = self.get_volume_junction_path(volume_name)
  1645. if not junction_path:
  1646. return False
  1647. api_args = {
  1648. 'query': {
  1649. 'volume-attributes': {
  1650. 'volume-id-attributes': {
  1651. 'junction-path': junction_path + '/*',
  1652. },
  1653. },
  1654. },
  1655. 'desired-attributes': {
  1656. 'volume-attributes': {
  1657. 'volume-id-attributes': {
  1658. 'name': None,
  1659. },
  1660. },
  1661. },
  1662. }
  1663. result = self.send_iter_request('volume-get-iter', api_args)
  1664. return self._has_records(result)
  1665. @na_utils.trace
  1666. def get_volume(self, volume_name):
  1667. """Returns the volume with the specified name, if present."""
  1668. api_args = {
  1669. 'query': {
  1670. 'volume-attributes': {
  1671. 'volume-id-attributes': {
  1672. 'name': volume_name,
  1673. },
  1674. },
  1675. },
  1676. 'desired-attributes': {
  1677. 'volume-attributes': {
  1678. 'volume-id-attributes': {
  1679. 'containing-aggregate-name': None,
  1680. 'junction-path': None,
  1681. 'name': None,
  1682. 'owning-vserver-name': None,
  1683. 'type': None,
  1684. 'style': None,
  1685. },
  1686. 'volume-qos-attributes': {
  1687. 'policy-group-name': None,
  1688. },
  1689. 'volume-space-attributes': {
  1690. 'size': None,
  1691. },
  1692. },
  1693. },
  1694. }
  1695. result = self.send_request('volume-get-iter', api_args)
  1696. attributes_list = result.get_child_by_name(
  1697. 'attributes-list') or netapp_api.NaElement('none')
  1698. volume_attributes_list = attributes_list.get_children()
  1699. if not self._has_records(result):
  1700. raise exception.StorageResourceNotFound(name=volume_name)
  1701. elif len(volume_attributes_list) > 1:
  1702. msg = _('Could not find unique volume %(vol)s.')
  1703. msg_args = {'vol': volume_name}
  1704. raise exception.NetAppException(msg % msg_args)
  1705. volume_attributes = volume_attributes_list[0]
  1706. volume_id_attributes = volume_attributes.get_child_by_name(
  1707. 'volume-id-attributes') or netapp_api.NaElement('none')
  1708. volume_qos_attributes = volume_attributes.get_child_by_name(
  1709. 'volume-qos-attributes') or netapp_api.NaElement('none')
  1710. volume_space_attributes = volume_attributes.get_child_by_name(
  1711. 'volume-space-attributes') or netapp_api.NaElement('none')
  1712. volume = {
  1713. 'aggregate': volume_id_attributes.get_child_content(
  1714. 'containing-aggregate-name'),
  1715. 'junction-path': volume_id_attributes.get_child_content(
  1716. 'junction-path'),
  1717. 'name': volume_id_attributes.get_child_content('name'),
  1718. 'owning-vserver-name': volume_id_attributes.get_child_content(
  1719. 'owning-vserver-name'),
  1720. 'type': volume_id_attributes.get_child_content('type'),
  1721. 'style': volume_id_attributes.get_child_content('style'),
  1722. 'size': volume_space_attributes.get_child_content('size'),
  1723. 'qos-policy-group-name': volume_qos_attributes.get_child_content(
  1724. 'policy-group-name')
  1725. }
  1726. return volume
  1727. @na_utils.trace
  1728. def get_volume_at_junction_path(self, junction_path):
  1729. """Returns the volume with the specified junction path, if present."""
  1730. if not junction_path:
  1731. return None
  1732. api_args = {
  1733. 'query': {
  1734. 'volume-attributes': {
  1735. 'volume-id-attributes': {
  1736. 'junction-path': junction_path,
  1737. },
  1738. },
  1739. },
  1740. 'desired-attributes': {
  1741. 'volume-attributes': {
  1742. 'volume-id-attributes': {
  1743. 'containing-aggregate-name': None,
  1744. 'junction-path': None,
  1745. 'name': None,
  1746. 'type': None,
  1747. 'style': None,
  1748. },
  1749. 'volume-space-attributes': {
  1750. 'size': None,
  1751. }
  1752. },
  1753. },
  1754. }
  1755. result = self.send_iter_request('volume-get-iter', api_args)
  1756. if not self._has_records(result):
  1757. return None
  1758. attributes_list = result.get_child_by_name(
  1759. 'attributes-list') or netapp_api.NaElement('none')
  1760. volume_attributes = attributes_list.get_child_by_name(
  1761. 'volume-attributes') or netapp_api.NaElement('none')
  1762. volume_id_attributes = volume_attributes.get_child_by_name(
  1763. 'volume-id-attributes') or netapp_api.NaElement('none')
  1764. volume_space_attributes = volume_attributes.get_child_by_name(
  1765. 'volume-space-attributes') or netapp_api.NaElement('none')
  1766. volume = {
  1767. 'aggregate': volume_id_attributes.get_child_content(
  1768. 'containing-aggregate-name'),
  1769. 'junction-path': volume_id_attributes.get_child_content(
  1770. 'junction-path'),
  1771. 'name': volume_id_attributes.get_child_content('name'),
  1772. 'type': volume_id_attributes.get_child_content('type'),
  1773. 'style': volume_id_attributes.get_child_content('style'),
  1774. 'size': volume_space_attributes.get_child_content('size'),
  1775. }
  1776. return volume
  1777. @na_utils.trace
  1778. def get_volume_to_manage(self, aggregate_name, volume_name):
  1779. """Get flexvol to be managed by Manila."""
  1780. api_args = {
  1781. 'query': {
  1782. 'volume-attributes': {
  1783. 'volume-id-attributes': {
  1784. 'containing-aggregate-name': aggregate_name,
  1785. 'name': volume_name,
  1786. },
  1787. },
  1788. },
  1789. 'desired-attributes': {
  1790. 'volume-attributes': {
  1791. 'volume-id-attributes': {
  1792. 'containing-aggregate-name': None,
  1793. 'junction-path': None,
  1794. 'name': None,
  1795. 'type': None,
  1796. 'style': None,
  1797. 'owning-vserver-name': None,
  1798. },
  1799. 'volume-qos-attributes': {
  1800. 'policy-group-name': None,
  1801. },
  1802. 'volume-space-attributes': {
  1803. 'size': None,
  1804. },
  1805. },
  1806. },
  1807. }
  1808. result = self.send_iter_request('volume-get-iter', api_args)
  1809. if not self._has_records(result):
  1810. return None
  1811. attributes_list = result.get_child_by_name(
  1812. 'attributes-list') or netapp_api.NaElement('none')
  1813. volume_attributes = attributes_list.get_child_by_name(
  1814. 'volume-attributes') or netapp_api.NaElement('none')
  1815. volume_id_attributes = volume_attributes.get_child_by_name(
  1816. 'volume-id-attributes') or netapp_api.NaElement('none')
  1817. volume_qos_attributes = volume_attributes.get_child_by_name(
  1818. 'volume-qos-attributes') or netapp_api.NaElement('none')
  1819. volume_space_attributes = volume_attributes.get_child_by_name(
  1820. 'volume-space-attributes') or netapp_api.NaElement('none')
  1821. volume = {
  1822. 'aggregate': volume_id_attributes.get_child_content(
  1823. 'containing-aggregate-name'),
  1824. 'junction-path': volume_id_attributes.get_child_content(
  1825. 'junction-path'),
  1826. 'name': volume_id_attributes.get_child_content('name'),
  1827. 'type': volume_id_attributes.get_child_content('type'),
  1828. 'style': volume_id_attributes.get_child_content('style'),
  1829. 'owning-vserver-name': volume_id_attributes.get_child_content(
  1830. 'owning-vserver-name'),
  1831. 'size': volume_space_attributes.get_child_content('size'),
  1832. 'qos-policy-group-name': volume_qos_attributes.get_child_content(
  1833. 'policy-group-name')
  1834. }
  1835. return volume
  1836. @na_utils.trace
  1837. def create_volume_clone(self, volume_name, parent_volume_name,
  1838. parent_snapshot_name=None, split=False,
  1839. qos_policy_group=None, **options):
  1840. """Clones a volume."""
  1841. api_args = {
  1842. 'volume': volume_name,
  1843. 'parent-volume': parent_volume_name,
  1844. 'parent-snapshot': parent_snapshot_name,
  1845. 'junction-path': '/%s' % volume_name,
  1846. }
  1847. if qos_policy_group is not None:
  1848. api_args['qos-policy-group-name'] = qos_policy_group
  1849. self.send_request('volume-clone-create', api_args)
  1850. if split:
  1851. self.split_volume_clone(volume_name)
  1852. @na_utils.trace
  1853. def split_volume_clone(self, volume_name):
  1854. """Begins splitting a clone from its parent."""
  1855. try:
  1856. api_args = {'volume': volume_name}
  1857. self.send_request('volume-clone-split-start', api_args)
  1858. except netapp_api.NaApiError as e:
  1859. if e.code == netapp_api.EVOL_CLONE_BEING_SPLIT:
  1860. return
  1861. raise
  1862. @na_utils.trace
  1863. def get_clone_children_for_snapshot(self, volume_name, snapshot_name):
  1864. """Returns volumes that are keeping a snapshot locked."""
  1865. api_args = {
  1866. 'query': {
  1867. 'volume-attributes': {
  1868. 'volume-clone-attributes': {
  1869. 'volume-clone-parent-attributes': {
  1870. 'name': volume_name,
  1871. 'snapshot-name': snapshot_name,
  1872. },
  1873. },
  1874. },
  1875. },
  1876. 'desired-attributes': {
  1877. 'volume-attributes': {
  1878. 'volume-id-attributes': {
  1879. 'name': None,
  1880. },
  1881. },
  1882. },
  1883. }
  1884. result = self.send_iter_request('volume-get-iter', api_args)
  1885. if not self._has_records(result):
  1886. return []
  1887. volume_list = []
  1888. attributes_list = result.get_child_by_name(
  1889. 'attributes-list') or netapp_api.NaElement('none')
  1890. for volume_attributes in attributes_list.get_children():
  1891. volume_id_attributes = volume_attributes.get_child_by_name(
  1892. 'volume-id-attributes') or netapp_api.NaElement('none')
  1893. volume_list.append({
  1894. 'name': volume_id_attributes.get_child_content('name'),
  1895. })
  1896. return volume_list
  1897. @na_utils.trace
  1898. def get_volume_junction_path(self, volume_name, is_style_cifs=False):
  1899. """Gets a volume junction path."""
  1900. api_args = {
  1901. 'volume': volume_name,
  1902. 'is-style-cifs': six.text_type(is_style_cifs).lower(),
  1903. }
  1904. result = self.send_request('volume-get-volume-path', api_args)
  1905. return result.get_child_content('junction')
  1906. @na_utils.trace
  1907. def mount_volume(self, volume_name, junction_path=None):
  1908. """Mounts a volume on a junction path."""
  1909. api_args = {
  1910. 'volume-name': volume_name,
  1911. 'junction-path': (junction_path if junction_path
  1912. else '/%s' % volume_name)
  1913. }
  1914. self.send_request('volume-mount', api_args)
  1915. @na_utils.trace
  1916. def offline_volume(self, volume_name):
  1917. """Offlines a volume."""
  1918. try:
  1919. self.send_request('volume-offline', {'name': volume_name})
  1920. except netapp_api.NaApiError as e:
  1921. if e.code == netapp_api.EVOLUMEOFFLINE:
  1922. return
  1923. raise
  1924. @na_utils.trace
  1925. def _unmount_volume(self, volume_name, force=False):
  1926. """Unmounts a volume."""
  1927. api_args = {
  1928. 'volume-name': volume_name,
  1929. 'force': six.text_type(force).lower(),
  1930. }
  1931. try:
  1932. self.send_request('volume-unmount', api_args)
  1933. except netapp_api.NaApiError as e:
  1934. if e.code == netapp_api.EVOL_NOT_MOUNTED:
  1935. return
  1936. raise
  1937. @na_utils.trace
  1938. def unmount_volume(self, volume_name, force=False, wait_seconds=30):
  1939. """Unmounts a volume, retrying if a clone split is ongoing.
  1940. NOTE(cknight): While unlikely to happen in normal operation, any client
  1941. that tries to delete volumes immediately after creating volume clones
  1942. is likely to experience failures if cDOT isn't quite ready for the
  1943. delete. The volume unmount is the first operation in the delete
  1944. path that fails in this case, and there is no proactive check we can
  1945. use to reliably predict the failure. And there isn't a specific error
  1946. code from volume-unmount, so we have to check for a generic error code
  1947. plus certain language in the error code. It's ugly, but it works, and
  1948. it's better than hard-coding a fixed delay.
  1949. """
  1950. # Do the unmount, handling split-related errors with retries.
  1951. retry_interval = 3 # seconds
  1952. for retry in range(int(wait_seconds / retry_interval)):
  1953. try:
  1954. self._unmount_volume(volume_name, force=force)
  1955. LOG.debug('Volume %s unmounted.', volume_name)
  1956. return
  1957. except netapp_api.NaApiError as e:
  1958. if e.code == netapp_api.EAPIERROR and 'job ID' in e.message:
  1959. msg = ('Could not unmount volume %(volume)s due to '
  1960. 'ongoing volume operation: %(exception)s')
  1961. msg_args = {'volume': volume_name, 'exception': e}
  1962. LOG.warning(msg, msg_args)
  1963. time.sleep(retry_interval)
  1964. continue
  1965. raise
  1966. msg = _('Failed to unmount volume %(volume)s after '
  1967. 'waiting for %(wait_seconds)s seconds.')
  1968. msg_args = {'volume': volume_name, 'wait_seconds': wait_seconds}
  1969. LOG.error(msg, msg_args)
  1970. raise exception.NetAppException(msg % msg_args)
  1971. @na_utils.trace
  1972. def delete_volume(self, volume_name):
  1973. """Deletes a volume."""
  1974. self.send_request('volume-destroy', {'name': volume_name})
  1975. @na_utils.trace
  1976. def create_snapshot(self, volume_name, snapshot_name):
  1977. """Creates a volume snapshot."""
  1978. api_args = {'volume': volume_name, 'snapshot': snapshot_name}
  1979. self.send_request('snapshot-create', api_args)
  1980. @na_utils.trace
  1981. def snapshot_exists(self, snapshot_name, volume_name):
  1982. """Checks if Snapshot exists for a specified volume."""
  1983. LOG.debug('Checking if snapshot %(snapshot)s exists for '
  1984. 'volume %(volume)s',
  1985. {'snapshot': snapshot_name, 'volume': volume_name})
  1986. """Gets a single snapshot."""
  1987. api_args = {
  1988. 'query': {
  1989. 'snapshot-info': {
  1990. 'name': snapshot_name,
  1991. 'volume': volume_name,
  1992. },
  1993. },
  1994. 'desired-attributes': {
  1995. 'snapshot-info': {
  1996. 'name': None,
  1997. 'volume': None,
  1998. 'busy': None,
  1999. 'snapshot-owners-list': {
  2000. 'snapshot-owner': None,
  2001. }
  2002. },
  2003. },
  2004. }
  2005. result = self.send_request('snapshot-get-iter', api_args)
  2006. error_record_list = result.get_child_by_name(
  2007. 'volume-errors') or netapp_api.NaElement('none')
  2008. errors = error_record_list.get_children()
  2009. if errors:
  2010. error = errors[0]
  2011. error_code = error.get_child_content('errno')
  2012. error_reason = error.get_child_content('reason')
  2013. msg = _('Could not read information for snapshot %(name)s. '
  2014. 'Code: %(code)s. Reason: %(reason)s')
  2015. msg_args = {
  2016. 'name': snapshot_name,
  2017. 'code': error_code,
  2018. 'reason': error_reason
  2019. }
  2020. if error_code == netapp_api.ESNAPSHOTNOTALLOWED:
  2021. raise exception.SnapshotUnavailable(msg % msg_args)
  2022. else:
  2023. raise exception.NetAppException(msg % msg_args)
  2024. return self._has_records(result)
  2025. @na_utils.trace
  2026. def get_snapshot(self, volume_name, snapshot_name):
  2027. """Gets a single snapshot."""
  2028. api_args = {
  2029. 'query': {
  2030. 'snapshot-info': {
  2031. 'name': snapshot_name,
  2032. 'volume': volume_name,
  2033. },
  2034. },
  2035. 'desired-attributes': {
  2036. 'snapshot-info': {
  2037. 'access-time': None,
  2038. 'name': None,
  2039. 'volume': None,
  2040. 'busy': None,
  2041. 'snapshot-owners-list': {
  2042. 'snapshot-owner': None,
  2043. }
  2044. },
  2045. },
  2046. }
  2047. result = self.send_request('snapshot-get-iter', api_args)
  2048. error_record_list = result.get_child_by_name(
  2049. 'volume-errors') or netapp_api.NaElement('none')
  2050. errors = error_record_list.get_children()
  2051. if errors:
  2052. error = errors[0]
  2053. error_code = error.get_child_content('errno')
  2054. error_reason = error.get_child_content('reason')
  2055. msg = _('Could not read information for snapshot %(name)s. '
  2056. 'Code: %(code)s. Reason: %(reason)s')
  2057. msg_args = {
  2058. 'name': snapshot_name,
  2059. 'code': error_code,
  2060. 'reason': error_reason
  2061. }
  2062. if error_code == netapp_api.ESNAPSHOTNOTALLOWED:
  2063. raise exception.SnapshotUnavailable(msg % msg_args)
  2064. else:
  2065. raise exception.NetAppException(msg % msg_args)
  2066. attributes_list = result.get_child_by_name(
  2067. 'attributes-list') or netapp_api.NaElement('none')
  2068. snapshot_info_list = attributes_list.get_children()
  2069. if not self._has_records(result):
  2070. raise exception.SnapshotResourceNotFound(name=snapshot_name)
  2071. elif len(snapshot_info_list) > 1:
  2072. msg = _('Could not find unique snapshot %(snap)s on '
  2073. 'volume %(vol)s.')
  2074. msg_args = {'snap': snapshot_name, 'vol': volume_name}
  2075. raise exception.NetAppException(msg % msg_args)
  2076. snapshot_info = snapshot_info_list[0]
  2077. snapshot = {
  2078. 'access-time': snapshot_info.get_child_content('access-time'),
  2079. 'name': snapshot_info.get_child_content('name'),
  2080. 'volume': snapshot_info.get_child_content('volume'),
  2081. 'busy': strutils.bool_from_string(
  2082. snapshot_info.get_child_content('busy')),
  2083. }
  2084. snapshot_owners_list = snapshot_info.get_child_by_name(
  2085. 'snapshot-owners-list') or netapp_api.NaElement('none')
  2086. snapshot_owners = set([
  2087. snapshot_owner.get_child_content('owner')
  2088. for snapshot_owner in snapshot_owners_list.get_children()])
  2089. snapshot['owners'] = snapshot_owners
  2090. return snapshot
  2091. @na_utils.trace
  2092. def rename_snapshot(self, volume_name, snapshot_name, new_snapshot_name):
  2093. api_args = {
  2094. 'volume': volume_name,
  2095. 'current-name': snapshot_name,
  2096. 'new-name': new_snapshot_name
  2097. }
  2098. self.send_request('snapshot-rename', api_args)
  2099. @na_utils.trace
  2100. def restore_snapshot(self, volume_name, snapshot_name):
  2101. """Reverts a volume to the specified snapshot."""
  2102. api_args = {
  2103. 'volume': volume_name,
  2104. 'snapshot': snapshot_name,
  2105. }
  2106. self.send_request('snapshot-restore-volume', api_args)
  2107. @na_utils.trace
  2108. def delete_snapshot(self, volume_name, snapshot_name, ignore_owners=False):
  2109. """Deletes a volume snapshot."""
  2110. ignore_owners = ('true' if strutils.bool_from_string(ignore_owners)
  2111. else 'false')
  2112. api_args = {
  2113. 'volume': volume_name,
  2114. 'snapshot': snapshot_name,
  2115. 'ignore-owners': ignore_owners,
  2116. }
  2117. self.send_request('snapshot-delete', api_args)
  2118. @na_utils.trace
  2119. def soft_delete_snapshot(self, volume_name, snapshot_name):
  2120. """Deletes a volume snapshot, or renames it if delete fails."""
  2121. try:
  2122. self.delete_snapshot(volume_name, snapshot_name)
  2123. except netapp_api.NaApiError:
  2124. self.rename_snapshot(volume_name,
  2125. snapshot_name,
  2126. DELETED_PREFIX + snapshot_name)
  2127. msg = _('Soft-deleted snapshot %(snapshot)s on volume %(volume)s.')
  2128. msg_args = {'snapshot': snapshot_name, 'volume': volume_name}
  2129. LOG.info(msg, msg_args)
  2130. @na_utils.trace
  2131. def prune_deleted_snapshots(self):
  2132. """Deletes non-busy snapshots that were previously soft-deleted."""
  2133. deleted_snapshots_map = self._get_deleted_snapshots()
  2134. for vserver in deleted_snapshots_map:
  2135. client = copy.deepcopy(self)
  2136. client.set_vserver(vserver)
  2137. for snapshot in deleted_snapshots_map[vserver]:
  2138. try:
  2139. client.delete_snapshot(snapshot['volume'],
  2140. snapshot['name'])
  2141. except netapp_api.NaApiError:
  2142. msg = _('Could not delete snapshot %(snap)s on '
  2143. 'volume %(volume)s.')
  2144. msg_args = {
  2145. 'snap': snapshot['name'],
  2146. 'volume': snapshot['volume'],
  2147. }
  2148. LOG.exception(msg, msg_args)
  2149. @na_utils.trace
  2150. def _get_deleted_snapshots(self):
  2151. """Returns non-busy, soft-deleted snapshots suitable for reaping."""
  2152. api_args = {
  2153. 'query': {
  2154. 'snapshot-info': {
  2155. 'name': DELETED_PREFIX + '*',
  2156. 'busy': 'false',
  2157. },
  2158. },
  2159. 'desired-attributes': {
  2160. 'snapshot-info': {
  2161. 'name': None,
  2162. 'vserver': None,
  2163. 'volume': None,
  2164. },
  2165. },
  2166. }
  2167. result = self.send_iter_request('snapshot-get-iter', api_args)
  2168. attributes_list = result.get_child_by_name(
  2169. 'attributes-list') or netapp_api.NaElement('none')
  2170. # Build a map of snapshots, one list of snapshots per vserver
  2171. snapshot_map = {}
  2172. for snapshot_info in attributes_list.get_children():
  2173. vserver = snapshot_info.get_child_content('vserver')
  2174. snapshot_list = snapshot_map.get(vserver, [])
  2175. snapshot_list.append({
  2176. 'name': snapshot_info.get_child_content('name'),
  2177. 'volume': snapshot_info.get_child_content('volume'),
  2178. 'vserver': vserver,
  2179. })
  2180. snapshot_map[vserver] = snapshot_list
  2181. return snapshot_map
  2182. @na_utils.trace
  2183. def create_cg_snapshot(self, volume_names, snapshot_name):
  2184. """Creates a consistency group snapshot of one or more flexvols."""
  2185. cg_id = self._start_cg_snapshot(volume_names, snapshot_name)
  2186. if not cg_id:
  2187. msg = _('Could not start consistency group snapshot %s.')
  2188. raise exception.NetAppException(msg % snapshot_name)
  2189. self._commit_cg_snapshot(cg_id)
  2190. @na_utils.trace
  2191. def _start_cg_snapshot(self, volume_names, snapshot_name):
  2192. api_args = {
  2193. 'snapshot': snapshot_name,
  2194. 'timeout': 'relaxed',
  2195. 'volumes': [
  2196. {'volume-name': volume_name} for volume_name in volume_names
  2197. ],
  2198. }
  2199. result = self.send_request('cg-start', api_args)
  2200. return result.get_child_content('cg-id')
  2201. @na_utils.trace
  2202. def _commit_cg_snapshot(self, cg_id):
  2203. api_args = {'cg-id': cg_id}
  2204. self.send_request('cg-commit', api_args)
  2205. @na_utils.trace
  2206. def create_cifs_share(self, share_name):
  2207. share_path = '/%s' % share_name
  2208. api_args = {'path': share_path, 'share-name': share_name}
  2209. self.send_request('cifs-share-create', api_args)
  2210. @na_utils.trace
  2211. def get_cifs_share_access(self, share_name):
  2212. api_args = {
  2213. 'query': {
  2214. 'cifs-share-access-control': {
  2215. 'share': share_name,
  2216. },
  2217. },
  2218. 'desired-attributes': {
  2219. 'cifs-share-access-control': {
  2220. 'user-or-group': None,
  2221. 'permission': None,
  2222. },
  2223. },
  2224. }
  2225. result = self.send_iter_request('cifs-share-access-control-get-iter',
  2226. api_args)
  2227. attributes_list = result.get_child_by_name(
  2228. 'attributes-list') or netapp_api.NaElement('none')
  2229. rules = {}
  2230. for rule in attributes_list.get_children():
  2231. user_or_group = rule.get_child_content('user-or-group')
  2232. permission = rule.get_child_content('permission')
  2233. rules[user_or_group] = permission
  2234. return rules
  2235. @na_utils.trace
  2236. def add_cifs_share_access(self, share_name, user_name, readonly):
  2237. api_args = {
  2238. 'permission': 'read' if readonly else 'full_control',
  2239. 'share': share_name,
  2240. 'user-or-group': user_name,
  2241. }
  2242. self.send_request('cifs-share-access-control-create', api_args)
  2243. @na_utils.trace
  2244. def modify_cifs_share_access(self, share_name, user_name, readonly):
  2245. api_args = {
  2246. 'permission': 'read' if readonly else 'full_control',
  2247. 'share': share_name,
  2248. 'user-or-group': user_name,
  2249. }
  2250. self.send_request('cifs-share-access-control-modify', api_args)
  2251. @na_utils.trace
  2252. def remove_cifs_share_access(self, share_name, user_name):
  2253. api_args = {'user-or-group': user_name, 'share': share_name}
  2254. self.send_request('cifs-share-access-control-delete', api_args)
  2255. @na_utils.trace
  2256. def remove_cifs_share(self, share_name):
  2257. self.send_request('cifs-share-delete', {'share-name': share_name})
  2258. @na_utils.trace
  2259. def add_nfs_export_rule(self, policy_name, client_match, readonly):
  2260. rule_indices = self._get_nfs_export_rule_indices(policy_name,
  2261. client_match)
  2262. if not rule_indices:
  2263. self._add_nfs_export_rule(policy_name, client_match, readonly)
  2264. else:
  2265. # Update first rule and delete the rest
  2266. self._update_nfs_export_rule(
  2267. policy_name, client_match, readonly, rule_indices.pop(0))
  2268. self._remove_nfs_export_rules(policy_name, rule_indices)
  2269. @na_utils.trace
  2270. def _add_nfs_export_rule(self, policy_name, client_match, readonly):
  2271. api_args = {
  2272. 'policy-name': policy_name,
  2273. 'client-match': client_match,
  2274. 'ro-rule': {
  2275. 'security-flavor': 'sys',
  2276. },
  2277. 'rw-rule': {
  2278. 'security-flavor': 'sys' if not readonly else 'never',
  2279. },
  2280. 'super-user-security': {
  2281. 'security-flavor': 'sys',
  2282. },
  2283. }
  2284. self.send_request('export-rule-create', api_args)
  2285. @na_utils.trace
  2286. def _update_nfs_export_rule(self, policy_name, client_match, readonly,
  2287. rule_index):
  2288. api_args = {
  2289. 'policy-name': policy_name,
  2290. 'rule-index': rule_index,
  2291. 'client-match': client_match,
  2292. 'ro-rule': {
  2293. 'security-flavor': 'sys'
  2294. },
  2295. 'rw-rule': {
  2296. 'security-flavor': 'sys' if not readonly else 'never'
  2297. },
  2298. 'super-user-security': {
  2299. 'security-flavor': 'sys'
  2300. },
  2301. }
  2302. self.send_request('export-rule-modify', api_args)
  2303. @na_utils.trace
  2304. def _get_nfs_export_rule_indices(self, policy_name, client_match):
  2305. api_args = {
  2306. 'query': {
  2307. 'export-rule-info': {
  2308. 'policy-name': policy_name,
  2309. 'client-match': client_match,
  2310. },
  2311. },
  2312. 'desired-attributes': {
  2313. 'export-rule-info': {
  2314. 'vserver-name': None,
  2315. 'policy-name': None,
  2316. 'client-match': None,
  2317. 'rule-index': None,
  2318. },
  2319. },
  2320. }
  2321. result = self.send_iter_request('export-rule-get-iter', api_args)
  2322. attributes_list = result.get_child_by_name(
  2323. 'attributes-list') or netapp_api.NaElement('none')
  2324. export_rule_info_list = attributes_list.get_children()
  2325. rule_indices = [int(export_rule_info.get_child_content('rule-index'))
  2326. for export_rule_info in export_rule_info_list]
  2327. rule_indices.sort()
  2328. return [six.text_type(rule_index) for rule_index in rule_indices]
  2329. @na_utils.trace
  2330. def remove_nfs_export_rule(self, policy_name, client_match):
  2331. rule_indices = self._get_nfs_export_rule_indices(policy_name,
  2332. client_match)
  2333. self._remove_nfs_export_rules(policy_name, rule_indices)
  2334. @na_utils.trace
  2335. def _remove_nfs_export_rules(self, policy_name, rule_indices):
  2336. for rule_index in rule_indices:
  2337. api_args = {
  2338. 'policy-name': policy_name,
  2339. 'rule-index': rule_index
  2340. }
  2341. try:
  2342. self.send_request('export-rule-destroy', api_args)
  2343. except netapp_api.NaApiError as e:
  2344. if e.code != netapp_api.EOBJECTNOTFOUND:
  2345. raise
  2346. @na_utils.trace
  2347. def clear_nfs_export_policy_for_volume(self, volume_name):
  2348. self.set_nfs_export_policy_for_volume(volume_name, 'default')
  2349. @na_utils.trace
  2350. def set_nfs_export_policy_for_volume(self, volume_name, policy_name):
  2351. api_args = {
  2352. 'query': {
  2353. 'volume-attributes': {
  2354. 'volume-id-attributes': {
  2355. 'name': volume_name,
  2356. },
  2357. },
  2358. },
  2359. 'attributes': {
  2360. 'volume-attributes': {
  2361. 'volume-export-attributes': {
  2362. 'policy': policy_name,
  2363. },
  2364. },
  2365. },
  2366. }
  2367. self.send_request('volume-modify-iter', api_args)
  2368. @na_utils.trace
  2369. def set_qos_policy_group_for_volume(self, volume_name,
  2370. qos_policy_group_name):
  2371. api_args = {
  2372. 'query': {
  2373. 'volume-attributes': {
  2374. 'volume-id-attributes': {
  2375. 'name': volume_name,
  2376. },
  2377. },
  2378. },
  2379. 'attributes': {
  2380. 'volume-attributes': {
  2381. 'volume-qos-attributes': {
  2382. 'policy-group-name': qos_policy_group_name,
  2383. },
  2384. },
  2385. },
  2386. }
  2387. self.send_request('volume-modify-iter', api_args)
  2388. @na_utils.trace
  2389. def get_nfs_export_policy_for_volume(self, volume_name):
  2390. """Get the name of the export policy for a volume."""
  2391. api_args = {
  2392. 'query': {
  2393. 'volume-attributes': {
  2394. 'volume-id-attributes': {
  2395. 'name': volume_name,
  2396. },
  2397. },
  2398. },
  2399. 'desired-attributes': {
  2400. 'volume-attributes': {
  2401. 'volume-export-attributes': {
  2402. 'policy': None,
  2403. },
  2404. },
  2405. },
  2406. }
  2407. result = self.send_iter_request('volume-get-iter', api_args)
  2408. attributes_list = result.get_child_by_name(
  2409. 'attributes-list') or netapp_api.NaElement('none')
  2410. volume_attributes = attributes_list.get_child_by_name(
  2411. 'volume-attributes') or netapp_api.NaElement('none')
  2412. volume_export_attributes = volume_attributes.get_child_by_name(
  2413. 'volume-export-attributes') or netapp_api.NaElement('none')
  2414. export_policy = volume_export_attributes.get_child_content('policy')
  2415. if not export_policy:
  2416. msg = _('Could not find export policy for volume %s.')
  2417. raise exception.NetAppException(msg % volume_name)
  2418. return export_policy
  2419. @na_utils.trace
  2420. def create_nfs_export_policy(self, policy_name):
  2421. api_args = {'policy-name': policy_name}
  2422. try:
  2423. self.send_request('export-policy-create', api_args)
  2424. except netapp_api.NaApiError as e:
  2425. if e.code != netapp_api.EDUPLICATEENTRY:
  2426. raise
  2427. @na_utils.trace
  2428. def soft_delete_nfs_export_policy(self, policy_name):
  2429. try:
  2430. self.delete_nfs_export_policy(policy_name)
  2431. except netapp_api.NaApiError:
  2432. # NOTE(cknight): Policy deletion can fail if called too soon after
  2433. # removing from a flexvol. So rename for later harvesting.
  2434. self.rename_nfs_export_policy(policy_name,
  2435. DELETED_PREFIX + policy_name)
  2436. @na_utils.trace
  2437. def delete_nfs_export_policy(self, policy_name):
  2438. api_args = {'policy-name': policy_name}
  2439. try:
  2440. self.send_request('export-policy-destroy', api_args)
  2441. except netapp_api.NaApiError as e:
  2442. if e.code == netapp_api.EOBJECTNOTFOUND:
  2443. return
  2444. raise
  2445. @na_utils.trace
  2446. def rename_nfs_export_policy(self, policy_name, new_policy_name):
  2447. api_args = {
  2448. 'policy-name': policy_name,
  2449. 'new-policy-name': new_policy_name
  2450. }
  2451. self.send_request('export-policy-rename', api_args)
  2452. @na_utils.trace
  2453. def prune_deleted_nfs_export_policies(self):
  2454. deleted_policy_map = self._get_deleted_nfs_export_policies()
  2455. for vserver in deleted_policy_map:
  2456. client = copy.deepcopy(self)
  2457. client.set_vserver(vserver)
  2458. for policy in deleted_policy_map[vserver]:
  2459. try:
  2460. client.delete_nfs_export_policy(policy)
  2461. except netapp_api.NaApiError:
  2462. LOG.debug('Could not delete export policy %s.', policy)
  2463. @na_utils.trace
  2464. def _get_deleted_nfs_export_policies(self):
  2465. api_args = {
  2466. 'query': {
  2467. 'export-policy-info': {
  2468. 'policy-name': DELETED_PREFIX + '*',
  2469. },
  2470. },
  2471. 'desired-attributes': {
  2472. 'export-policy-info': {
  2473. 'policy-name': None,
  2474. 'vserver': None,
  2475. },
  2476. },
  2477. }
  2478. result = self.send_iter_request('export-policy-get-iter', api_args)
  2479. attributes_list = result.get_child_by_name(
  2480. 'attributes-list') or netapp_api.NaElement('none')
  2481. policy_map = {}
  2482. for export_info in attributes_list.get_children():
  2483. vserver = export_info.get_child_content('vserver')
  2484. policies = policy_map.get(vserver, [])
  2485. policies.append(export_info.get_child_content('policy-name'))
  2486. policy_map[vserver] = policies
  2487. return policy_map
  2488. @na_utils.trace
  2489. def _get_ems_log_destination_vserver(self):
  2490. """Returns the best vserver destination for EMS messages."""
  2491. major, minor = self.get_ontapi_version(cached=True)
  2492. if (major > 1) or (major == 1 and minor > 15):
  2493. # Prefer admin Vserver (requires cluster credentials).
  2494. admin_vservers = self.list_vservers(vserver_type='admin')
  2495. if admin_vservers:
  2496. return admin_vservers[0]
  2497. # Fall back to data Vserver.
  2498. data_vservers = self.list_vservers(vserver_type='data')
  2499. if data_vservers:
  2500. return data_vservers[0]
  2501. # If older API version, or no other Vservers found, use node Vserver.
  2502. node_vservers = self.list_vservers(vserver_type='node')
  2503. if node_vservers:
  2504. return node_vservers[0]
  2505. raise exception.NotFound("No Vserver found to receive EMS messages.")
  2506. @na_utils.trace
  2507. def send_ems_log_message(self, message_dict):
  2508. """Sends a message to the Data ONTAP EMS log."""
  2509. # NOTE(cknight): Cannot use deepcopy on the connection context
  2510. node_client = copy.copy(self)
  2511. node_client.connection = copy.copy(self.connection)
  2512. node_client.connection.set_timeout(25)
  2513. try:
  2514. node_client.set_vserver(self._get_ems_log_destination_vserver())
  2515. node_client.send_request('ems-autosupport-log', message_dict)
  2516. LOG.debug('EMS executed successfully.')
  2517. except netapp_api.NaApiError as e:
  2518. LOG.warning('Failed to invoke EMS. %s', e)
  2519. @na_utils.trace
  2520. def get_aggregate(self, aggregate_name):
  2521. """Get aggregate attributes needed for the storage service catalog."""
  2522. if not aggregate_name:
  2523. return {}
  2524. desired_attributes = {
  2525. 'aggr-attributes': {
  2526. 'aggregate-name': None,
  2527. 'aggr-raid-attributes': {
  2528. 'raid-type': None,
  2529. 'is-hybrid': None,
  2530. },
  2531. },
  2532. }
  2533. try:
  2534. aggrs = self._get_aggregates(aggregate_names=[aggregate_name],
  2535. desired_attributes=desired_attributes)
  2536. except netapp_api.NaApiError:
  2537. msg = _('Failed to get info for aggregate %s.')
  2538. LOG.exception(msg, aggregate_name)
  2539. return {}
  2540. if len(aggrs) < 1:
  2541. return {}
  2542. aggr_attributes = aggrs[0]
  2543. aggr_raid_attrs = aggr_attributes.get_child_by_name(
  2544. 'aggr-raid-attributes') or netapp_api.NaElement('none')
  2545. aggregate = {
  2546. 'name': aggr_attributes.get_child_content('aggregate-name'),
  2547. 'raid-type': aggr_raid_attrs.get_child_content('raid-type'),
  2548. 'is-hybrid': strutils.bool_from_string(
  2549. aggr_raid_attrs.get_child_content('is-hybrid')),
  2550. }
  2551. return aggregate
  2552. @na_utils.trace
  2553. def get_aggregate_disk_types(self, aggregate_name):
  2554. """Get the disk type(s) of an aggregate."""
  2555. disk_types = set()
  2556. disk_types.update(self._get_aggregate_disk_types(aggregate_name))
  2557. if self.features.ADVANCED_DISK_PARTITIONING:
  2558. disk_types.update(self._get_aggregate_disk_types(aggregate_name,
  2559. shared=True))
  2560. return list(disk_types) if disk_types else None
  2561. @na_utils.trace
  2562. def _get_aggregate_disk_types(self, aggregate_name, shared=False):
  2563. """Get the disk type(s) of an aggregate."""
  2564. disk_types = set()
  2565. if shared:
  2566. disk_raid_info = {
  2567. 'disk-shared-info': {
  2568. 'aggregate-list': {
  2569. 'shared-aggregate-info': {
  2570. 'aggregate-name': aggregate_name,
  2571. },
  2572. },
  2573. },
  2574. }
  2575. else:
  2576. disk_raid_info = {
  2577. 'disk-aggregate-info': {
  2578. 'aggregate-name': aggregate_name,
  2579. },
  2580. }
  2581. api_args = {
  2582. 'query': {
  2583. 'storage-disk-info': {
  2584. 'disk-raid-info': disk_raid_info,
  2585. },
  2586. },
  2587. 'desired-attributes': {
  2588. 'storage-disk-info': {
  2589. 'disk-raid-info': {
  2590. 'effective-disk-type': None,
  2591. },
  2592. },
  2593. },
  2594. }
  2595. try:
  2596. result = self.send_iter_request('storage-disk-get-iter', api_args)
  2597. except netapp_api.NaApiError:
  2598. msg = _('Failed to get disk info for aggregate %s.')
  2599. LOG.exception(msg, aggregate_name)
  2600. return disk_types
  2601. attributes_list = result.get_child_by_name(
  2602. 'attributes-list') or netapp_api.NaElement('none')
  2603. for storage_disk_info in attributes_list.get_children():
  2604. disk_raid_info = storage_disk_info.get_child_by_name(
  2605. 'disk-raid-info') or netapp_api.NaElement('none')
  2606. disk_type = disk_raid_info.get_child_content(
  2607. 'effective-disk-type')
  2608. if disk_type:
  2609. disk_types.add(disk_type)
  2610. return disk_types
  2611. @na_utils.trace
  2612. def check_for_cluster_credentials(self):
  2613. try:
  2614. self.list_cluster_nodes()
  2615. # API succeeded, so definitely a cluster management LIF
  2616. return True
  2617. except netapp_api.NaApiError as e:
  2618. if e.code == netapp_api.EAPINOTFOUND:
  2619. LOG.debug('Not connected to cluster management LIF.')
  2620. return False
  2621. else:
  2622. raise
  2623. @na_utils.trace
  2624. def create_cluster_peer(self, addresses, username=None, password=None,
  2625. passphrase=None):
  2626. """Creates a cluster peer relationship."""
  2627. api_args = {
  2628. 'peer-addresses': [
  2629. {'remote-inet-address': address} for address in addresses
  2630. ],
  2631. }
  2632. if username:
  2633. api_args['user-name'] = username
  2634. if password:
  2635. api_args['password'] = password
  2636. if passphrase:
  2637. api_args['passphrase'] = passphrase
  2638. self.send_request('cluster-peer-create', api_args)
  2639. @na_utils.trace
  2640. def get_cluster_peers(self, remote_cluster_name=None):
  2641. """Gets one or more cluster peer relationships."""
  2642. api_args = {}
  2643. if remote_cluster_name:
  2644. api_args['query'] = {
  2645. 'cluster-peer-info': {
  2646. 'remote-cluster-name': remote_cluster_name,
  2647. }
  2648. }
  2649. result = self.send_iter_request('cluster-peer-get-iter', api_args)
  2650. if not self._has_records(result):
  2651. return []
  2652. cluster_peers = []
  2653. for cluster_peer_info in result.get_child_by_name(
  2654. 'attributes-list').get_children():
  2655. cluster_peer = {
  2656. 'active-addresses': [],
  2657. 'peer-addresses': []
  2658. }
  2659. active_addresses = cluster_peer_info.get_child_by_name(
  2660. 'active-addresses') or netapp_api.NaElement('none')
  2661. for address in active_addresses.get_children():
  2662. cluster_peer['active-addresses'].append(address.get_content())
  2663. peer_addresses = cluster_peer_info.get_child_by_name(
  2664. 'peer-addresses') or netapp_api.NaElement('none')
  2665. for address in peer_addresses.get_children():
  2666. cluster_peer['peer-addresses'].append(address.get_content())
  2667. cluster_peer['availability'] = cluster_peer_info.get_child_content(
  2668. 'availability')
  2669. cluster_peer['cluster-name'] = cluster_peer_info.get_child_content(
  2670. 'cluster-name')
  2671. cluster_peer['cluster-uuid'] = cluster_peer_info.get_child_content(
  2672. 'cluster-uuid')
  2673. cluster_peer['remote-cluster-name'] = (
  2674. cluster_peer_info.get_child_content('remote-cluster-name'))
  2675. cluster_peer['serial-number'] = (
  2676. cluster_peer_info.get_child_content('serial-number'))
  2677. cluster_peer['timeout'] = cluster_peer_info.get_child_content(
  2678. 'timeout')
  2679. cluster_peers.append(cluster_peer)
  2680. return cluster_peers
  2681. @na_utils.trace
  2682. def delete_cluster_peer(self, cluster_name):
  2683. """Deletes a cluster peer relationship."""
  2684. api_args = {'cluster-name': cluster_name}
  2685. self.send_request('cluster-peer-delete', api_args)
  2686. @na_utils.trace
  2687. def get_cluster_peer_policy(self):
  2688. """Gets the cluster peering policy configuration."""
  2689. if not self.features.CLUSTER_PEER_POLICY:
  2690. return {}
  2691. result = self.send_request('cluster-peer-policy-get')
  2692. attributes = result.get_child_by_name(
  2693. 'attributes') or netapp_api.NaElement('none')
  2694. cluster_peer_policy = attributes.get_child_by_name(
  2695. 'cluster-peer-policy') or netapp_api.NaElement('none')
  2696. policy = {
  2697. 'is-unauthenticated-access-permitted':
  2698. cluster_peer_policy.get_child_content(
  2699. 'is-unauthenticated-access-permitted'),
  2700. 'passphrase-minimum-length':
  2701. cluster_peer_policy.get_child_content(
  2702. 'passphrase-minimum-length'),
  2703. }
  2704. if policy['is-unauthenticated-access-permitted'] is not None:
  2705. policy['is-unauthenticated-access-permitted'] = (
  2706. strutils.bool_from_string(
  2707. policy['is-unauthenticated-access-permitted']))
  2708. if policy['passphrase-minimum-length'] is not None:
  2709. policy['passphrase-minimum-length'] = int(
  2710. policy['passphrase-minimum-length'])
  2711. return policy
  2712. @na_utils.trace
  2713. def set_cluster_peer_policy(self, is_unauthenticated_access_permitted=None,
  2714. passphrase_minimum_length=None):
  2715. """Modifies the cluster peering policy configuration."""
  2716. if not self.features.CLUSTER_PEER_POLICY:
  2717. return
  2718. if (is_unauthenticated_access_permitted is None and
  2719. passphrase_minimum_length is None):
  2720. return
  2721. api_args = {}
  2722. if is_unauthenticated_access_permitted is not None:
  2723. api_args['is-unauthenticated-access-permitted'] = (
  2724. 'true' if strutils.bool_from_string(
  2725. is_unauthenticated_access_permitted) else 'false')
  2726. if passphrase_minimum_length is not None:
  2727. api_args['passphrase-minlength'] = six.text_type(
  2728. passphrase_minimum_length)
  2729. self.send_request('cluster-peer-policy-modify', api_args)
  2730. @na_utils.trace
  2731. def create_vserver_peer(self, vserver_name, peer_vserver_name):
  2732. """Creates a Vserver peer relationship for SnapMirrors."""
  2733. api_args = {
  2734. 'vserver': vserver_name,
  2735. 'peer-vserver': peer_vserver_name,
  2736. 'applications': [
  2737. {'vserver-peer-application': 'snapmirror'},
  2738. ],
  2739. }
  2740. self.send_request('vserver-peer-create', api_args)
  2741. @na_utils.trace
  2742. def delete_vserver_peer(self, vserver_name, peer_vserver_name):
  2743. """Deletes a Vserver peer relationship."""
  2744. api_args = {'vserver': vserver_name, 'peer-vserver': peer_vserver_name}
  2745. self.send_request('vserver-peer-delete', api_args)
  2746. @na_utils.trace
  2747. def accept_vserver_peer(self, vserver_name, peer_vserver_name):
  2748. """Accepts a pending Vserver peer relationship."""
  2749. api_args = {'vserver': vserver_name, 'peer-vserver': peer_vserver_name}
  2750. self.send_request('vserver-peer-accept', api_args)
  2751. @na_utils.trace
  2752. def get_vserver_peers(self, vserver_name=None, peer_vserver_name=None):
  2753. """Gets one or more Vserver peer relationships."""
  2754. api_args = None
  2755. if vserver_name or peer_vserver_name:
  2756. api_args = {'query': {'vserver-peer-info': {}}}
  2757. if vserver_name:
  2758. api_args['query']['vserver-peer-info']['vserver'] = (
  2759. vserver_name)
  2760. if peer_vserver_name:
  2761. api_args['query']['vserver-peer-info']['peer-vserver'] = (
  2762. peer_vserver_name)
  2763. result = self.send_iter_request('vserver-peer-get-iter', api_args)
  2764. if not self._has_records(result):
  2765. return []
  2766. vserver_peers = []
  2767. for vserver_peer_info in result.get_child_by_name(
  2768. 'attributes-list').get_children():
  2769. vserver_peer = {
  2770. 'vserver': vserver_peer_info.get_child_content('vserver'),
  2771. 'peer-vserver':
  2772. vserver_peer_info.get_child_content('peer-vserver'),
  2773. 'peer-state':
  2774. vserver_peer_info.get_child_content('peer-state'),
  2775. 'peer-cluster':
  2776. vserver_peer_info.get_child_content('peer-cluster'),
  2777. }
  2778. vserver_peers.append(vserver_peer)
  2779. return vserver_peers
  2780. def _ensure_snapmirror_v2(self):
  2781. """Verify support for SnapMirror control plane v2."""
  2782. if not self.features.SNAPMIRROR_V2:
  2783. msg = _('SnapMirror features require Data ONTAP 8.2 or later.')
  2784. raise exception.NetAppException(msg)
  2785. @na_utils.trace
  2786. def create_snapmirror(self, source_vserver, source_volume,
  2787. destination_vserver, destination_volume,
  2788. schedule=None, policy=None,
  2789. relationship_type='data_protection'):
  2790. """Creates a SnapMirror relationship (cDOT 8.2 or later only)."""
  2791. self._ensure_snapmirror_v2()
  2792. api_args = {
  2793. 'source-volume': source_volume,
  2794. 'source-vserver': source_vserver,
  2795. 'destination-volume': destination_volume,
  2796. 'destination-vserver': destination_vserver,
  2797. 'relationship-type': relationship_type,
  2798. }
  2799. if schedule:
  2800. api_args['schedule'] = schedule
  2801. if policy:
  2802. api_args['policy'] = policy
  2803. try:
  2804. self.send_request('snapmirror-create', api_args)
  2805. except netapp_api.NaApiError as e:
  2806. if e.code != netapp_api.ERELATION_EXISTS:
  2807. raise
  2808. @na_utils.trace
  2809. def initialize_snapmirror(self, source_vserver, source_volume,
  2810. destination_vserver, destination_volume,
  2811. source_snapshot=None, transfer_priority=None):
  2812. """Initializes a SnapMirror relationship (cDOT 8.2 or later only)."""
  2813. self._ensure_snapmirror_v2()
  2814. api_args = {
  2815. 'source-volume': source_volume,
  2816. 'source-vserver': source_vserver,
  2817. 'destination-volume': destination_volume,
  2818. 'destination-vserver': destination_vserver,
  2819. }
  2820. if source_snapshot:
  2821. api_args['source-snapshot'] = source_snapshot
  2822. if transfer_priority:
  2823. api_args['transfer-priority'] = transfer_priority
  2824. result = self.send_request('snapmirror-initialize', api_args)
  2825. result_info = {}
  2826. result_info['operation-id'] = result.get_child_content(
  2827. 'result-operation-id')
  2828. result_info['status'] = result.get_child_content('result-status')
  2829. result_info['jobid'] = result.get_child_content('result-jobid')
  2830. result_info['error-code'] = result.get_child_content(
  2831. 'result-error-code')
  2832. result_info['error-message'] = result.get_child_content(
  2833. 'result-error-message')
  2834. return result_info
  2835. @na_utils.trace
  2836. def release_snapmirror(self, source_vserver, source_volume,
  2837. destination_vserver, destination_volume,
  2838. relationship_info_only=False):
  2839. """Removes a SnapMirror relationship on the source endpoint."""
  2840. self._ensure_snapmirror_v2()
  2841. api_args = {
  2842. 'query': {
  2843. 'snapmirror-destination-info': {
  2844. 'source-volume': source_volume,
  2845. 'source-vserver': source_vserver,
  2846. 'destination-volume': destination_volume,
  2847. 'destination-vserver': destination_vserver,
  2848. 'relationship-info-only': ('true' if relationship_info_only
  2849. else 'false'),
  2850. }
  2851. }
  2852. }
  2853. self.send_request('snapmirror-release-iter', api_args)
  2854. @na_utils.trace
  2855. def quiesce_snapmirror(self, source_vserver, source_volume,
  2856. destination_vserver, destination_volume):
  2857. """Disables future transfers to a SnapMirror destination."""
  2858. self._ensure_snapmirror_v2()
  2859. api_args = {
  2860. 'source-volume': source_volume,
  2861. 'source-vserver': source_vserver,
  2862. 'destination-volume': destination_volume,
  2863. 'destination-vserver': destination_vserver,
  2864. }
  2865. self.send_request('snapmirror-quiesce', api_args)
  2866. @na_utils.trace
  2867. def abort_snapmirror(self, source_vserver, source_volume,
  2868. destination_vserver, destination_volume,
  2869. clear_checkpoint=False):
  2870. """Stops ongoing transfers for a SnapMirror relationship."""
  2871. self._ensure_snapmirror_v2()
  2872. api_args = {
  2873. 'source-volume': source_volume,
  2874. 'source-vserver': source_vserver,
  2875. 'destination-volume': destination_volume,
  2876. 'destination-vserver': destination_vserver,
  2877. 'clear-checkpoint': 'true' if clear_checkpoint else 'false',
  2878. }
  2879. try:
  2880. self.send_request('snapmirror-abort', api_args)
  2881. except netapp_api.NaApiError as e:
  2882. if e.code != netapp_api.ENOTRANSFER_IN_PROGRESS:
  2883. raise
  2884. @na_utils.trace
  2885. def break_snapmirror(self, source_vserver, source_volume,
  2886. destination_vserver, destination_volume):
  2887. """Breaks a data protection SnapMirror relationship."""
  2888. self._ensure_snapmirror_v2()
  2889. api_args = {
  2890. 'source-volume': source_volume,
  2891. 'source-vserver': source_vserver,
  2892. 'destination-volume': destination_volume,
  2893. 'destination-vserver': destination_vserver,
  2894. }
  2895. self.send_request('snapmirror-break', api_args)
  2896. @na_utils.trace
  2897. def modify_snapmirror(self, source_vserver, source_volume,
  2898. destination_vserver, destination_volume,
  2899. schedule=None, policy=None, tries=None,
  2900. max_transfer_rate=None):
  2901. """Modifies a SnapMirror relationship."""
  2902. self._ensure_snapmirror_v2()
  2903. api_args = {
  2904. 'source-volume': source_volume,
  2905. 'source-vserver': source_vserver,
  2906. 'destination-volume': destination_volume,
  2907. 'destination-vserver': destination_vserver,
  2908. }
  2909. if schedule:
  2910. api_args['schedule'] = schedule
  2911. if policy:
  2912. api_args['policy'] = policy
  2913. if tries is not None:
  2914. api_args['tries'] = tries
  2915. if max_transfer_rate is not None:
  2916. api_args['max-transfer-rate'] = max_transfer_rate
  2917. self.send_request('snapmirror-modify', api_args)
  2918. @na_utils.trace
  2919. def delete_snapmirror(self, source_vserver, source_volume,
  2920. destination_vserver, destination_volume):
  2921. """Destroys a SnapMirror relationship."""
  2922. self._ensure_snapmirror_v2()
  2923. api_args = {
  2924. 'query': {
  2925. 'snapmirror-info': {
  2926. 'source-volume': source_volume,
  2927. 'source-vserver': source_vserver,
  2928. 'destination-volume': destination_volume,
  2929. 'destination-vserver': destination_vserver,
  2930. }
  2931. }
  2932. }
  2933. self.send_request('snapmirror-destroy-iter', api_args)
  2934. @na_utils.trace
  2935. def update_snapmirror(self, source_vserver, source_volume,
  2936. destination_vserver, destination_volume):
  2937. """Schedules a snapmirror update."""
  2938. self._ensure_snapmirror_v2()
  2939. api_args = {
  2940. 'source-volume': source_volume,
  2941. 'source-vserver': source_vserver,
  2942. 'destination-volume': destination_volume,
  2943. 'destination-vserver': destination_vserver,
  2944. }
  2945. try:
  2946. self.send_request('snapmirror-update', api_args)
  2947. except netapp_api.NaApiError as e:
  2948. if (e.code != netapp_api.ETRANSFER_IN_PROGRESS and
  2949. e.code != netapp_api.EANOTHER_OP_ACTIVE):
  2950. raise
  2951. @na_utils.trace
  2952. def resume_snapmirror(self, source_vserver, source_volume,
  2953. destination_vserver, destination_volume):
  2954. """Resume a SnapMirror relationship if it is quiesced."""
  2955. self._ensure_snapmirror_v2()
  2956. api_args = {
  2957. 'source-volume': source_volume,
  2958. 'source-vserver': source_vserver,
  2959. 'destination-volume': destination_volume,
  2960. 'destination-vserver': destination_vserver,
  2961. }
  2962. try:
  2963. self.send_request('snapmirror-resume', api_args)
  2964. except netapp_api.NaApiError as e:
  2965. if e.code != netapp_api.ERELATION_NOT_QUIESCED:
  2966. raise
  2967. @na_utils.trace
  2968. def resync_snapmirror(self, source_vserver, source_volume,
  2969. destination_vserver, destination_volume):
  2970. """Resync a SnapMirror relationship."""
  2971. self._ensure_snapmirror_v2()
  2972. api_args = {
  2973. 'source-volume': source_volume,
  2974. 'source-vserver': source_vserver,
  2975. 'destination-volume': destination_volume,
  2976. 'destination-vserver': destination_vserver,
  2977. }
  2978. self.send_request('snapmirror-resync', api_args)
  2979. @na_utils.trace
  2980. def _get_snapmirrors(self, source_vserver=None, source_volume=None,
  2981. destination_vserver=None, destination_volume=None,
  2982. desired_attributes=None):
  2983. query = None
  2984. if (source_vserver or source_volume or destination_vserver or
  2985. destination_volume):
  2986. query = {'snapmirror-info': {}}
  2987. if source_volume:
  2988. query['snapmirror-info']['source-volume'] = source_volume
  2989. if destination_volume:
  2990. query['snapmirror-info']['destination-volume'] = (
  2991. destination_volume)
  2992. if source_vserver:
  2993. query['snapmirror-info']['source-vserver'] = source_vserver
  2994. if destination_vserver:
  2995. query['snapmirror-info']['destination-vserver'] = (
  2996. destination_vserver)
  2997. api_args = {}
  2998. if query:
  2999. api_args['query'] = query
  3000. if desired_attributes:
  3001. api_args['desired-attributes'] = desired_attributes
  3002. result = self.send_iter_request('snapmirror-get-iter', api_args)
  3003. if not self._has_records(result):
  3004. return []
  3005. else:
  3006. return result.get_child_by_name('attributes-list').get_children()
  3007. @na_utils.trace
  3008. def get_snapmirrors(self, source_vserver, source_volume,
  3009. destination_vserver, destination_volume,
  3010. desired_attributes=None):
  3011. """Gets one or more SnapMirror relationships.
  3012. Either the source or destination info may be omitted.
  3013. Desired attributes should be a flat list of attribute names.
  3014. """
  3015. self._ensure_snapmirror_v2()
  3016. if desired_attributes is not None:
  3017. desired_attributes = {
  3018. 'snapmirror-info': {attr: None for attr in desired_attributes},
  3019. }
  3020. result = self._get_snapmirrors(
  3021. source_vserver=source_vserver,
  3022. source_volume=source_volume,
  3023. destination_vserver=destination_vserver,
  3024. destination_volume=destination_volume,
  3025. desired_attributes=desired_attributes)
  3026. snapmirrors = []
  3027. for snapmirror_info in result:
  3028. snapmirror = {}
  3029. for child in snapmirror_info.get_children():
  3030. name = self._strip_xml_namespace(child.get_name())
  3031. snapmirror[name] = child.get_content()
  3032. snapmirrors.append(snapmirror)
  3033. return snapmirrors
  3034. def volume_has_snapmirror_relationships(self, volume):
  3035. """Return True if snapmirror relationships exist for a given volume.
  3036. If we have snapmirror control plane license, we can verify whether
  3037. the given volume is part of any snapmirror relationships.
  3038. """
  3039. try:
  3040. # Check if volume is a source snapmirror volume
  3041. snapmirrors = self.get_snapmirrors(
  3042. volume['owning-vserver-name'], volume['name'], None, None)
  3043. # Check if volume is a destination snapmirror volume
  3044. if not snapmirrors:
  3045. snapmirrors = self.get_snapmirrors(
  3046. None, None, volume['owning-vserver-name'], volume['name'])
  3047. has_snapmirrors = len(snapmirrors) > 0
  3048. except netapp_api.NaApiError:
  3049. msg = ("Could not determine if volume %s is part of "
  3050. "existing snapmirror relationships.")
  3051. LOG.exception(msg, volume['name'])
  3052. has_snapmirrors = False
  3053. return has_snapmirrors
  3054. def list_snapmirror_snapshots(self, volume_name, newer_than=None):
  3055. """Gets SnapMirror snapshots on a volume."""
  3056. api_args = {
  3057. 'query': {
  3058. 'snapshot-info': {
  3059. 'dependency': 'snapmirror',
  3060. 'volume': volume_name,
  3061. },
  3062. },
  3063. }
  3064. if newer_than:
  3065. api_args['query']['snapshot-info'][
  3066. 'access-time'] = '>' + newer_than
  3067. result = self.send_iter_request('snapshot-get-iter', api_args)
  3068. attributes_list = result.get_child_by_name(
  3069. 'attributes-list') or netapp_api.NaElement('none')
  3070. return [snapshot_info.get_child_content('name')
  3071. for snapshot_info in attributes_list.get_children()]
  3072. @na_utils.trace
  3073. def start_volume_move(self, volume_name, vserver, destination_aggregate,
  3074. cutover_action='wait', encrypt_destination=None):
  3075. """Moves a FlexVol across Vserver aggregates.
  3076. Requires cluster-scoped credentials.
  3077. """
  3078. self._send_volume_move_request(
  3079. volume_name, vserver,
  3080. destination_aggregate,
  3081. cutover_action=cutover_action,
  3082. encrypt_destination=encrypt_destination)
  3083. @na_utils.trace
  3084. def check_volume_move(self, volume_name, vserver, destination_aggregate,
  3085. encrypt_destination=None):
  3086. """Moves a FlexVol across Vserver aggregates.
  3087. Requires cluster-scoped credentials.
  3088. """
  3089. self._send_volume_move_request(
  3090. volume_name,
  3091. vserver,
  3092. destination_aggregate,
  3093. validation_only=True,
  3094. encrypt_destination=encrypt_destination)
  3095. @na_utils.trace
  3096. def _send_volume_move_request(self, volume_name, vserver,
  3097. destination_aggregate,
  3098. cutover_action='wait',
  3099. validation_only=False,
  3100. encrypt_destination=None):
  3101. """Send request to check if vol move is possible, or start it.
  3102. :param volume_name: Name of the FlexVol to be moved.
  3103. :param destination_aggregate: Name of the destination aggregate
  3104. :param cutover_action: can have one of ['force', 'defer', 'abort',
  3105. 'wait']. 'force' will force a cutover despite errors (causing
  3106. possible client disruptions), 'wait' will wait for cutover to be
  3107. triggered manually. 'abort' will rollback move on errors on
  3108. cutover, 'defer' will attempt a cutover, but wait for manual
  3109. intervention in case of errors.
  3110. :param validation_only: If set to True, only validates if the volume
  3111. move is possible, does not trigger data copy.
  3112. :param encrypt_destination: If set to True, it encrypts the Flexvol
  3113. after the volume move is complete.
  3114. """
  3115. api_args = {
  3116. 'source-volume': volume_name,
  3117. 'vserver': vserver,
  3118. 'dest-aggr': destination_aggregate,
  3119. 'cutover-action': CUTOVER_ACTION_MAP[cutover_action],
  3120. }
  3121. if self.features.FLEXVOL_ENCRYPTION and encrypt_destination:
  3122. api_args['encrypt-destination'] = 'true'
  3123. elif encrypt_destination:
  3124. msg = 'Flexvol encryption is not supported on this backend.'
  3125. raise exception.NetAppException(msg)
  3126. else:
  3127. api_args['encrypt-destination'] = 'false'
  3128. if validation_only:
  3129. api_args['perform-validation-only'] = 'true'
  3130. self.send_request('volume-move-start', api_args)
  3131. @na_utils.trace
  3132. def abort_volume_move(self, volume_name, vserver):
  3133. """Aborts an existing volume move operation."""
  3134. api_args = {
  3135. 'source-volume': volume_name,
  3136. 'vserver': vserver,
  3137. }
  3138. self.send_request('volume-move-trigger-abort', api_args)
  3139. @na_utils.trace
  3140. def trigger_volume_move_cutover(self, volume_name, vserver, force=True):
  3141. """Triggers the cut-over for a volume in data motion."""
  3142. api_args = {
  3143. 'source-volume': volume_name,
  3144. 'vserver': vserver,
  3145. 'force': 'true' if force else 'false',
  3146. }
  3147. self.send_request('volume-move-trigger-cutover', api_args)
  3148. @na_utils.trace
  3149. def get_volume_move_status(self, volume_name, vserver):
  3150. """Gets the current state of a volume move operation."""
  3151. api_args = {
  3152. 'query': {
  3153. 'volume-move-info': {
  3154. 'volume': volume_name,
  3155. 'vserver': vserver,
  3156. },
  3157. },
  3158. 'desired-attributes': {
  3159. 'volume-move-info': {
  3160. 'percent-complete': None,
  3161. 'estimated-completion-time': None,
  3162. 'state': None,
  3163. 'details': None,
  3164. 'cutover-action': None,
  3165. 'phase': None,
  3166. },
  3167. },
  3168. }
  3169. result = self.send_iter_request('volume-move-get-iter', api_args)
  3170. if not self._has_records(result):
  3171. msg = _("Volume %(vol)s in Vserver %(server)s is not part of any "
  3172. "data motion operations.")
  3173. msg_args = {'vol': volume_name, 'server': vserver}
  3174. raise exception.NetAppException(msg % msg_args)
  3175. attributes_list = result.get_child_by_name(
  3176. 'attributes-list') or netapp_api.NaElement('none')
  3177. volume_move_info = attributes_list.get_child_by_name(
  3178. 'volume-move-info') or netapp_api.NaElement('none')
  3179. status_info = {
  3180. 'percent-complete': volume_move_info.get_child_content(
  3181. 'percent-complete'),
  3182. 'estimated-completion-time': volume_move_info.get_child_content(
  3183. 'estimated-completion-time'),
  3184. 'state': volume_move_info.get_child_content('state'),
  3185. 'details': volume_move_info.get_child_content('details'),
  3186. 'cutover-action': volume_move_info.get_child_content(
  3187. 'cutover-action'),
  3188. 'phase': volume_move_info.get_child_content('phase'),
  3189. }
  3190. return status_info
  3191. @na_utils.trace
  3192. def qos_policy_group_exists(self, qos_policy_group_name):
  3193. """Checks if a QoS policy group exists."""
  3194. try:
  3195. self.qos_policy_group_get(qos_policy_group_name)
  3196. except exception.NetAppException:
  3197. return False
  3198. return True
  3199. @na_utils.trace
  3200. def qos_policy_group_get(self, qos_policy_group_name):
  3201. """Checks if a QoS policy group exists."""
  3202. api_args = {
  3203. 'query': {
  3204. 'qos-policy-group-info': {
  3205. 'policy-group': qos_policy_group_name,
  3206. },
  3207. },
  3208. 'desired-attributes': {
  3209. 'qos-policy-group-info': {
  3210. 'policy-group': None,
  3211. 'vserver': None,
  3212. 'max-throughput': None,
  3213. 'num-workloads': None
  3214. },
  3215. },
  3216. }
  3217. try:
  3218. result = self.send_request('qos-policy-group-get-iter',
  3219. api_args,
  3220. False)
  3221. except netapp_api.NaApiError as e:
  3222. if e.code == netapp_api.EAPINOTFOUND:
  3223. msg = _("Configured ONTAP login user cannot retrieve "
  3224. "QoS policies.")
  3225. LOG.error(msg)
  3226. raise exception.NetAppException(msg)
  3227. else:
  3228. raise
  3229. if not self._has_records(result):
  3230. msg = _("No QoS policy group found with name %s.")
  3231. raise exception.NetAppException(msg % qos_policy_group_name)
  3232. attributes_list = result.get_child_by_name(
  3233. 'attributes-list') or netapp_api.NaElement('none')
  3234. qos_policy_group_info = attributes_list.get_child_by_name(
  3235. 'qos-policy-group-info') or netapp_api.NaElement('none')
  3236. policy_info = {
  3237. 'policy-group': qos_policy_group_info.get_child_content(
  3238. 'policy-group'),
  3239. 'vserver': qos_policy_group_info.get_child_content('vserver'),
  3240. 'max-throughput': qos_policy_group_info.get_child_content(
  3241. 'max-throughput'),
  3242. 'num-workloads': int(qos_policy_group_info.get_child_content(
  3243. 'num-workloads')),
  3244. }
  3245. return policy_info
  3246. @na_utils.trace
  3247. def qos_policy_group_create(self, qos_policy_group_name, vserver,
  3248. max_throughput=None):
  3249. """Creates a QoS policy group."""
  3250. api_args = {
  3251. 'policy-group': qos_policy_group_name,
  3252. 'vserver': vserver,
  3253. }
  3254. if max_throughput:
  3255. api_args['max-throughput'] = max_throughput
  3256. return self.send_request('qos-policy-group-create', api_args, False)
  3257. @na_utils.trace
  3258. def qos_policy_group_modify(self, qos_policy_group_name, max_throughput):
  3259. """Modifies a QoS policy group."""
  3260. api_args = {
  3261. 'policy-group': qos_policy_group_name,
  3262. 'max-throughput': max_throughput,
  3263. }
  3264. return self.send_request('qos-policy-group-modify', api_args, False)
  3265. @na_utils.trace
  3266. def qos_policy_group_delete(self, qos_policy_group_name):
  3267. """Attempts to delete a QoS policy group."""
  3268. api_args = {'policy-group': qos_policy_group_name}
  3269. return self.send_request('qos-policy-group-delete', api_args, False)
  3270. @na_utils.trace
  3271. def qos_policy_group_rename(self, qos_policy_group_name, new_name):
  3272. """Renames a QoS policy group."""
  3273. api_args = {
  3274. 'policy-group-name': qos_policy_group_name,
  3275. 'new-name': new_name,
  3276. }
  3277. return self.send_request('qos-policy-group-rename', api_args, False)
  3278. @na_utils.trace
  3279. def mark_qos_policy_group_for_deletion(self, qos_policy_group_name):
  3280. """Soft delete backing QoS policy group for a manila share."""
  3281. # NOTE(gouthamr): ONTAP deletes storage objects asynchronously. As
  3282. # long as garbage collection hasn't occurred, assigned QoS policy may
  3283. # still be tagged "in use". So, we rename the QoS policy group using a
  3284. # specific pattern and later attempt on a best effort basis to
  3285. # delete any QoS policy groups matching that pattern.
  3286. if self.qos_policy_group_exists(qos_policy_group_name):
  3287. new_name = DELETED_PREFIX + qos_policy_group_name
  3288. try:
  3289. self.qos_policy_group_rename(qos_policy_group_name, new_name)
  3290. except netapp_api.NaApiError as ex:
  3291. msg = ('Rename failure in cleanup of cDOT QoS policy '
  3292. 'group %(name)s: %(ex)s')
  3293. msg_args = {'name': qos_policy_group_name, 'ex': ex}
  3294. LOG.warning(msg, msg_args)
  3295. # Attempt to delete any QoS policies named "deleted_manila-*".
  3296. self.remove_unused_qos_policy_groups()
  3297. @na_utils.trace
  3298. def remove_unused_qos_policy_groups(self):
  3299. """Deletes all QoS policy groups that are marked for deletion."""
  3300. api_args = {
  3301. 'query': {
  3302. 'qos-policy-group-info': {
  3303. 'policy-group': '%s*' % DELETED_PREFIX,
  3304. }
  3305. },
  3306. 'max-records': 3500,
  3307. 'continue-on-failure': 'true',
  3308. 'return-success-list': 'false',
  3309. 'return-failure-list': 'false',
  3310. }
  3311. try:
  3312. self.send_request('qos-policy-group-delete-iter', api_args, False)
  3313. except netapp_api.NaApiError as ex:
  3314. msg = 'Could not delete QoS policy groups. Details: %(ex)s'
  3315. msg_args = {'ex': ex}
  3316. LOG.debug(msg, msg_args)
  3317. @na_utils.trace
  3318. def get_net_options(self):
  3319. result = self.send_request('net-options-get', None, False)
  3320. options = result.get_child_by_name('net-options')
  3321. ipv6_enabled = False
  3322. ipv6_info = options.get_child_by_name('ipv6-options-info')
  3323. if ipv6_info:
  3324. ipv6_enabled = ipv6_info.get_child_content('enabled') == 'true'
  3325. return {
  3326. 'ipv6-enabled': ipv6_enabled,
  3327. }