Debian Codegraph @

ansible_collections/dellemc/unity/plugins/module_utils/storage/dell/utils.py

raw symbols SCIP
1 # Copyright: (c) 2020-2025, Dell Technologies
2
3 # Apache License version 2.0 (see MODULE-LICENSE or http://www.apache.org/licenses/LICENSE-2.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6
7 __metaclass__ = type
8
9 import logging
10 from decimal import Decimal
11 import re
12 import traceback
13 import math
14 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell.logging_handler \
15 import CustomRotatingFileHandler
16 from ansible.module_utils.basic import missing_required_lib
17
18 try:
19 import urllib3
20
21 urllib3.disable_warnings()
22 HAS_URLLIB3, URLLIB3_IMP_ERR = True, None
23 except ImportError:
24 HAS_URLLIB3, URLLIB3_IMP_ERR = False, traceback.format_exc()
25
26 try:
27 from storops import UnitySystem
28 from storops.unity.client import UnityClient # noqa # pylint: disable=unused-import
29 from storops.unity.resource import host, cg, snap_schedule, snap, \
30 cifs_share, nas_server # noqa # pylint: disable=unused-import
31 from storops.unity.resource.lun import UnityLun # noqa # pylint: disable=unused-import
32 from storops.unity.resource.pool import UnityPool, UnityPoolList, RaidGroupParameter # noqa # pylint: disable=unused-import
33 from storops.unity.resource.filesystem import UnityFileSystem, \
34 UnityFileSystemList # noqa # pylint: disable=unused-import
35 from storops.unity.resource.nas_server import UnityNasServer # noqa # pylint: disable=unused-import
36 from storops.unity.resource.nfs_share import UnityNfsShare, \
37 UnityNfsShareList # noqa # pylint: disable=unused-import
38 from storops.unity.resource.snap_schedule import UnitySnapScheduleList, \
39 UnitySnapSchedule # noqa # pylint: disable=unused-import
40 from storops.unity.resource.replication_session import UnityReplicationSession # noqa # pylint: disable=unused-import
41 from storops.unity.enums import HostInitiatorTypeEnum, \
42 TieringPolicyEnum, ScheduleTypeEnum, DayOfWeekEnum, NodeEnum # noqa # pylint: disable=unused-import
43 from storops.unity.enums import HostLUNAccessEnum, HostTypeEnum, AccessPolicyEnum, \
44 FilesystemTypeEnum, FSSupportedProtocolEnum, FSFormatEnum # noqa # pylint: disable=unused-import
45 from storops.unity.enums import NFSTypeEnum, NFSShareDefaultAccessEnum, NFSShareSecurityEnum, \
46 FilesystemSnapAccessTypeEnum, FSLockingPolicyEnum # noqa # pylint: disable=unused-import
47 from storops.unity.enums import CifsShareOfflineAvailabilityEnum, NasServerUnixDirectoryServiceEnum, \
48 KdcTypeEnum, NodeEnum, FileInterfaceRoleEnum, ReplicationOpStatusEnum # noqa # pylint: disable=unused-import
49 from storops.exception import UnityResourceNotFoundError, \
50 StoropsConnectTimeoutError, UnityNfsShareNameExistedError # noqa # pylint: disable=unused-import
51 from storops.connection.exceptions import HttpError, HTTPClientError # noqa # pylint: disable=unused-import
52 from storops.unity.resource.user_quota import UnityUserQuota, \
53 UnityUserQuotaList # noqa # pylint: disable=unused-import
54 from storops.unity.resource.tree_quota import UnityTreeQuota, \
55 UnityTreeQuotaList # noqa # pylint: disable=unused-import
56 from storops.unity.resource.quota_config import UnityQuotaConfig, \
57 UnityQuotaConfigList # noqa # pylint: disable=unused-import
58 from storops.unity.resource.storage_resource import UnityStorageResource # noqa # pylint: disable=unused-import
59 from storops.unity.enums import QuotaPolicyEnum, RaidTypeEnum, \
60 RaidStripeWidthEnum, StoragePoolTypeEnum # noqa # pylint: disable=unused-import
61 from storops.unity.resource.disk import UnityDisk, \
62 UnityDiskList, UnityDiskGroup, UnityDiskGroupList # noqa # pylint: disable=unused-import
63 from storops.unity.resource.cifs_server import UnityCifsServer # noqa # pylint: disable=unused-import
64 from storops.unity.resource.nfs_server import UnityNfsServer # noqa # pylint: disable=unused-import
65 from storops.unity.resource.interface import UnityFileInterface # noqa # pylint: disable=unused-import
66
67 HAS_UNITY_SDK, STOROPS_IMP_ERR = True, None
68 except ImportError:
69 HAS_UNITY_SDK, STOROPS_IMP_ERR = False, traceback.format_exc()
70
71 try:
72 from pkg_resources import parse_version
73 import pkg_resources
74
75 HAS_PKG_RESOURCE, PKG_RESOURCE_IMP_ERR = True, None
76 except ImportError:
77 HAS_PKG_RESOURCE, PKG_RESOURCE_IMP_ERR = False, traceback.format_exc()
78
79
80 def ensure_required_libs(module):
81 """Check required libraries"""
82
83 if not HAS_UNITY_SDK:
84 module.fail_json(msg=missing_required_lib("storops"),
85 exception=STOROPS_IMP_ERR)
86
87 if not HAS_PKG_RESOURCE:
88 module.fail_json(msg=missing_required_lib("pkg_resources"),
89 exception=PKG_RESOURCE_IMP_ERR)
90
91 if not HAS_URLLIB3:
92 module.fail_json(msg=missing_required_lib("urllib3"),
93 exception=URLLIB3_IMP_ERR)
94
95 min_ver = '1.2.12'
96 try:
97 curr_version = pkg_resources.require("storops")[0].version
98 except Exception as err:
99 module.fail_json(msg="Failed to get Storops SDK version - "
100 "{0}".format(str(err)))
101
102 if parse_version(curr_version) < parse_version(min_ver):
103 module.fail_json(msg="Storops {0} is not supported. "
104 "Required minimum version is "
105 "{1}".format(curr_version, min_ver))
106
107
108 def get_unity_management_host_parameters():
109 """Provides common access parameters required for the
110 ansible modules on Unity StorageSystem"""
111
112 return dict(
113 unispherehost=dict(type='str', required=True, no_log=True),
114 username=dict(type='str', required=True),
115 password=dict(type='str', required=True, no_log=True),
116 validate_certs=dict(type='bool', required=False,
117 aliases=['verifycert'], default=True),
118 port=dict(type='int', required=False, default=443, no_log=True)
119 )
120
121
122 def get_unity_unisphere_connection(module_params, application_type=None):
123 """Establishes connection with Unity array using storops SDK"""
124
125 if HAS_UNITY_SDK:
126 conn = UnitySystem(host=module_params['unispherehost'],
127 port=module_params['port'],
128 verify=module_params['validate_certs'],
129 username=module_params['username'],
130 password=module_params['password'],
131 application_type=application_type)
132 return conn
133
134
135 def get_logger(module_name, log_file_name='ansible_unity.log',
136 log_devel=logging.INFO):
137 """Intializes and returns the logger object
138
139 :param module_name: Name of module to be part of log message
140 :param log_file_name: Name of file in which the log messages get appended
141 :param log_devel: Log level
142 """
143
144 FORMAT = '%(asctime)-15s %(filename)s %(levelname)s : %(message)s'
145 max_bytes = 5 * 1024 * 1024
146 logging.basicConfig(filename=log_file_name, format=FORMAT)
147 LOG = logging.getLogger(module_name)
148 LOG.setLevel(log_devel)
149 handler = CustomRotatingFileHandler(log_file_name,
150 maxBytes=max_bytes,
151 backupCount=5)
152 formatter = logging.Formatter(FORMAT)
153 handler.setFormatter(formatter)
154 LOG.addHandler(handler)
155 LOG.propagate = False
156 return LOG
157
158
159 KB_IN_BYTES = 1024
160 MB_IN_BYTES = 1024 * 1024
161 GB_IN_BYTES = 1024 * 1024 * 1024
162 TB_IN_BYTES = 1024 * 1024 * 1024 * 1024
163
164
165 def get_size_bytes(size, cap_units):
166 """Convert the given size to bytes"""
167
168 if size is not None and size > 0:
169 if cap_units in ('kb', 'KB'):
170 return size * KB_IN_BYTES
171 elif cap_units in ('mb', 'MB'):
172 return size * MB_IN_BYTES
173 elif cap_units in ('gb', 'GB'):
174 return size * GB_IN_BYTES
175 elif cap_units in ('tb', 'TB'):
176 return size * TB_IN_BYTES
177 else:
178 return size
179 else:
180 return 0
181
182
183 def convert_size_with_unit(size_bytes):
184 """Convert size in byte with actual unit like KB,MB,GB,TB,PB etc."""
185
186 if not isinstance(size_bytes, int):
187 raise ValueError('This method takes Integer type argument only')
188 if size_bytes == 0:
189 return "0B"
190 size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
191 i = int(math.floor(math.log(size_bytes, 1024)))
192 p = math.pow(1024, i)
193 s = round(size_bytes / p, 2)
194 return "%s %s" % (s, size_name[i])
195
196
197 def get_size_in_gb(size, cap_units):
198 """Convert the given size to size in GB, size is restricted to 2 decimal places"""
199
200 size_in_bytes = get_size_bytes(size, cap_units)
201 size = Decimal(size_in_bytes / GB_IN_BYTES)
202 size_in_gb = round(size)
203 return size_in_gb
204
205
206 def is_input_empty(item):
207 """Check whether input string is empty"""
208
209 if item == "" or item.isspace():
210 return True
211 else:
212 return False
213
214
215 def is_size_negative(size):
216 """Check whether size is negative"""
217
218 if size and size < 0:
219 return True
220 else:
221 return False
222
223
224 def has_special_char(value):
225 """Check whether the string has any special character.
226 It allows '_' character"""
227
228 regex = re.compile(r'[@!#$%^&*()<>?/\|}{~:]')
229 if regex.search(value) is None:
230 return False
231 else:
232 return True
233
234
235 def is_initiator_valid(value):
236 """Validate format of the FC or iSCSI initiator"""
237
238 if value.startswith('iqn') or re.match(r"([A-Fa-f0-9]{2}:){15}[A-Fa-f0-9]{2}", value, re.I) is not None:
239 return True
240 else:
241 return False
242
243
244 def is_valid_netmask(netmask):
245 """Validates if ip is valid subnet mask"""
246
247 if netmask:
248 regexp = re.compile(r'^((128|192|224|240|248|252|254)\.0\.0\.0)|'
249 r'(255\.(((0|128|192|224|240|248|252|254)\.0\.0)|'
250 r'(255\.(((0|128|192|224|240|248|252|254)\.0)|'
251 r'255\.(0|128|192|224|240|248|252|254)))))$')
252 if not regexp.search(netmask):
253 return False
254 return True