Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_debug.py

raw
1 #!/usr/bin/python
2 """
3 create Debug module to diagnose netapp-lib import and connection
4 """
5
6 # (c) 2020-2026, NetApp, Inc
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 ANSIBLE_METADATA = {'metadata_version': '1.1',
13 'status': ['preview'],
14 'supported_by': 'certified'}
15
16
17 DOCUMENTATION = '''
18 module: na_ontap_debug
19 short_description: NetApp ONTAP Debug netapp-lib import and connection.
20 extends_documentation_fragment:
21 - netapp.ontap.netapp.na_ontap
22 version_added: 21.1.0
23 author: NetApp Ansible Team (@carchi8py) <[email protected]>
24 description:
25 - Display issues related to importing netapp-lib and connection with diagnose
26 options:
27 vserver:
28 description:
29 - The vserver name to test for ZAPI tunneling.
30 required: false
31 type: str
32
33 lambda_config:
34 description:
35 - Configuration parameters for AWS Lambda proxy functionality.
36 - These option and suboptions are only supported with REST.
37 type: dict
38 version_added: 23.5.0
39 suboptions:
40 function_name:
41 description:
42 - The name of the AWS Lambda function to invoke.
43 type: str
44 required: true
45 aws_region:
46 description:
47 - The name of the AWS region.
48 type: str
49 required: true
50 aws_profile:
51 description:
52 - The name of the AWS profile to use for authentication.
53 type: str
54
55 notes:
56 - Supports AWS Lambda proxy functionality when using REST. See README for example usage.
57 '''
58 EXAMPLES = """
59 - name: Check import netapp-lib
60 netapp.ontap.na_ontap_debug:
61 hostname: "{{ netapp_hostname }}"
62 username: "{{ netapp_username }}"
63 password: "{{ netapp_password }}"
64
65 - name: Debug vserver
66 netapp.ontap.na_ontap_debug:
67 hostname: "{{ netapp_hostname }}"
68 username: "{{ netapp_username }}"
69 password: "{{ netapp_password }}"
70 vserver: ansibleSVM
71 """
72
73 RETURN = """
74 """
75 import sys
76 from ansible.module_utils.basic import AnsibleModule
77 from ansible.module_utils._text import to_native
78 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
79 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
80 from ansible_collections.netapp.ontap.plugins.module_utils.rest_user import get_users
81 from ansible_collections.netapp.ontap.plugins.module_utils.rest_vserver import get_vserver
82
83
84 class NetAppONTAPDebug(object):
85 """Class with Debug methods"""
86
87 def __init__(self):
88 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
89 self.argument_spec.update(dict(
90 vserver=dict(required=False, type="str"),
91 ))
92 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
93
94 self.module = AnsibleModule(
95 argument_spec=self.argument_spec,
96 required_if=[
97 ('use_lambda', True, ['lambda_config']),
98 ],
99 )
100 self.na_helper = NetAppModule()
101 self.parameters = self.na_helper.set_parameters(self.module.params)
102 self.rest_api = netapp_utils.OntapRestAPI(self.module)
103 self.use_rest = self.rest_api.is_rest()
104 if not self.use_rest:
105 if self.parameters.get('use_lambda'):
106 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
107 self.log_list = []
108 self.error_list = []
109 self.note_list = []
110 self.server = None
111
112 def list_versions(self):
113 self.log_list.append('Ansible version: %s' % netapp_utils.ANSIBLE_VERSION)
114 self.log_list.append('ONTAP collection version: %s' % netapp_utils.COLLECTION_VERSION)
115 self.log_list.append('Python version: %s' % sys.version[:3])
116 self.log_list.append('Python executable path: %s' % sys.executable)
117
118 def import_lib(self):
119 if not netapp_utils.has_netapp_lib():
120 msgs = [
121 'Error importing netapp-lib or a dependency: %s.' % str(netapp_utils.IMPORT_EXCEPTION),
122 'Install the python netapp-lib module or a missing dependency.',
123 'Additional diagnostic information:',
124 'Python Executable Path: %s.' % sys.executable,
125 'Python Version: %s.' % sys.version,
126 'System Path: %s.' % ','.join(sys.path),
127 ]
128 self.error_list.append(' '.join(msgs))
129 return
130 self.log_list.append('netapp-lib imported successfully.')
131
132 def check_connection(self, connection_type):
133 """
134 check connection errors and diagnose
135 """
136 error_string = None
137 result = None
138 if connection_type == "REST":
139 api = 'cluster'
140 message, error_string = self.rest_api.get(api)
141 elif connection_type == "ZAPI":
142 if 'vserver' not in self.parameters:
143 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
144 else:
145 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
146 version_obj = netapp_utils.zapi.NaElement("system-get-version")
147 try:
148 result = self.server.invoke_successfully(version_obj, True)
149 except netapp_utils.zapi.NaApiError as error:
150 error_string = to_native(error)
151 else:
152 self.module.fail_json(msg='Internal error, unexpected connection type: %s' % connection_type)
153
154 if error_string is not None:
155 summary_msg = None
156 error_patterns = ['Connection timed out',
157 'Resource temporarily unavailable',
158 'ConnectTimeoutError',
159 'Network is unreachable']
160 if any(x in error_string for x in error_patterns):
161 summary_msg = 'Error: invalid or unreachable hostname: %s' % self.parameters['hostname']
162 if 'vserver' in self.parameters:
163 summary_msg += ' for SVM: %s ' % self.parameters['vserver']
164 self.error_list.append('Error in hostname - Address does not exist or is not reachable: ' + error_string)
165 self.error_list.append(summary_msg + ' using %s.' % connection_type)
166 return
167 error_patterns = ['Name or service not known', 'Name does not resolve']
168 if any(x in error_string for x in error_patterns):
169 summary_msg = 'Error: unknown or not resolvable hostname: %s' % self.parameters['hostname']
170 if 'vserver' in self.parameters:
171 summary_msg += ' for SVM: %s ' % self.parameters['vserver']
172 self.error_list.append('Error in hostname - DNS name cannot be resolved: ' + error_string)
173 self.error_list.append('%s cannot be resolved using %s.' % (summary_msg, connection_type))
174 else:
175 self.error_list.append('Other error for hostname: %s using %s: %s.' % (self.parameters['hostname'], connection_type, error_string))
176 self.error_list.append('Unclassified, see msg')
177 return False
178
179 ontap_version = message['version']['full'] if connection_type == 'REST' else result['version']
180 self.log_list.append('%s connected successfully.' % connection_type)
181 self.log_list.append('ONTAP version: %s' % ontap_version)
182 return True
183
184 def list_interfaces(self, vserver_name):
185 vserver, error = get_vserver(self.rest_api, vserver_name, fields='ip_interfaces')
186 if not error and not vserver:
187 error = 'not found'
188 if error:
189 self.error_list.append('Error getting vserver in list_interfaces: %s: %s' % (vserver_name, error))
190 else:
191 interfaces = vserver.get('ip_interfaces')
192 if not interfaces:
193 self.error_list.append('Error vserver is not associated with a network interface: %s' % vserver_name)
194 return
195 for interface in interfaces:
196 data = [vserver_name]
197 for field in (['name'], ['ip', 'address'], ['services']):
198 value = self.na_helper.safe_get(interface, field)
199 if isinstance(value, list):
200 value = ','.join(value)
201 if field == ['services'] and value and 'management' not in value:
202 self.note_list.append('NOTE: no management policy in services for %s: %s' % (data, value))
203 data.append(value)
204 self.log_list.append('vserver: %s, interface: %s, IP: %s, service policies: %s' % tuple(data))
205
206 def validate_user(self, user):
207 locked = user.get('locked')
208 if locked:
209 self.note_list.append('NOTE: user: %s is locked on vserver: %s' % (user['name'], self.na_helper.safe_get(user, ['owner', 'name'])))
210 applications = user.get('applications', [])
211 apps = [app['application'] for app in applications]
212 role = self.na_helper.safe_get(user, ['role', 'name'])
213 for application in ('http', 'ontapi', 'console'):
214 if application not in apps and (application != 'console' or role == 'admin'):
215 self.note_list.append('NOTE: application %s not found for user: %s: %s' % (application, user['name'], apps))
216 if application == 'console':
217 self.note_list.append("NOTE: console access is only needed for na_ontap_command.")
218 has_http = locked is False and 'http' in apps
219 has_ontapi = locked is False and 'ontapi' in apps
220 return has_http, has_ontapi
221
222 def list_users(self, vserver_name=None, user_name=None):
223 query = {'owner.name': vserver_name} if vserver_name else {'name': user_name}
224 users, error = get_users(self.rest_api, query, 'applications,locked,owner,role')
225 if not error and not users:
226 error = 'none found'
227 name = vserver_name or user_name
228 if error:
229 if 'not authorized for that command' in error:
230 self.log_list.append('Not autorized to get accounts for: %s: %s' % (name, error))
231 else:
232 self.error_list.append('Error getting accounts for: %s: %s' % (name, error))
233 else:
234 one_http, one_ontapi = False, False
235 for user in users:
236 data = {}
237 for field in ('owner', 'name', 'role', 'locked', 'applications'):
238 if field in ('owner', 'role'):
239 value = str(self.na_helper.safe_get(user, [field, 'name']))
240 else:
241 value = str(user.get(field))
242 data[field] = value
243 self.log_list.append(', '. join('%s: %s' % x for x in data.items()))
244 has_http, has_ontapi = self.validate_user(user)
245 one_http |= has_http
246 one_ontapi |= has_ontapi
247 msg = 'Error: no unlocked user for %s on vserver: %s'if vserver_name else\
248 'Error: %s is not enabled for user %s'
249 if not one_http:
250 self.error_list.append(msg % ('http', name))
251 if not one_ontapi:
252 self.error_list.append(msg % ('ontapi', name))
253
254 def check_vserver(self, name):
255
256 self.list_interfaces(name)
257 self.list_users(vserver_name=name)
258
259 def apply(self):
260 """
261 Apply debug
262 """
263 # report Ansible and our collection versions
264 self.list_versions()
265
266 # check import netapp-lib when not using REST
267 if not self.use_rest:
268 self.import_lib()
269
270 # check zapi connection errors only if import successful
271 if netapp_utils.has_netapp_lib():
272 self.check_connection("ZAPI")
273
274 # check rest connection errors
275 has_rest = self.check_connection("REST")
276
277 if has_rest:
278 self.list_users(user_name=self.parameters.get('username'))
279 if 'vserver' in self.parameters:
280 self.check_vserver(self.parameters['vserver'])
281
282 msgs = {}
283 if self.note_list:
284 msgs['notes'] = self.note_list
285 if self.error_list:
286 msgs['msg'] = self.error_list
287 if self.log_list:
288 msgs['msg_passed'] = self.log_list
289 self.module.fail_json(**msgs)
290 msgs['msg'] = self.log_list
291 self.module.exit_json(**msgs)
292
293
294 def main():
295 """Execute action"""
296 debug_obj = NetAppONTAPDebug()
297 debug_obj.apply()
298
299
300 if __name__ == '__main__':
301 main()