Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/netapp_e_auditlog.py

raw
1 #!/usr/bin/python
2
3 # (c) 2018, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 ANSIBLE_METADATA = {'metadata_version': '1.1',
11 'status': ['deprecated'],
12 'supported_by': 'community'}
13
14 DOCUMENTATION = """
15 ---
16 module: netapp_e_auditlog
17 short_description: NetApp E-Series manage audit-log configuration
18 description:
19 - This module allows an e-series storage system owner to set audit-log configuration parameters.
20 version_added: '2.7.0'
21 author: Nathan Swartz (@ndswartz)
22 extends_documentation_fragment:
23 - netapp_eseries.santricity.santricity.netapp.eseries
24 options:
25 max_records:
26 description:
27 - The maximum number log messages audit-log will retain.
28 - Max records must be between and including 100 and 50000.
29 default: 50000
30 type: int
31 log_level:
32 description: Filters the log messages according to the specified log level selection.
33 choices:
34 - all
35 - writeOnly
36 default: writeOnly
37 type: str
38 full_policy:
39 description: Specifies what audit-log should do once the number of entries approach the record limit.
40 choices:
41 - overWrite
42 - preventSystemAccess
43 default: overWrite
44 type: str
45 threshold:
46 description:
47 - This is the memory full percent threshold that audit-log will start issuing warning messages.
48 - Percent range must be between and including 60 and 90.
49 default: 90
50 type: int
51 force:
52 description:
53 - Forces the audit-log configuration to delete log history when log messages fullness cause immediate
54 warning or full condition.
55 - Warning! This will cause any existing audit-log messages to be deleted.
56 - This is only applicable for I(full_policy=preventSystemAccess).
57 type: bool
58 default: no
59 log_path:
60 description: A local path to a file to be used for debug logging.
61 required: no
62 type: str
63 notes:
64 - Check mode is supported.
65 - This module is currently only supported with the Embedded Web Services API v3.0 and higher.
66 """
67
68 EXAMPLES = """
69 - name: Define audit-log to prevent system access if records exceed 50000 with warnings occurring at 60% capacity.
70 netapp_e_auditlog:
71 api_url: "https://{{ netapp_e_api_host }}/devmgr/v2"
72 api_username: "{{ netapp_e_api_username }}"
73 api_password: "{{ netapp_e_api_password }}"
74 ssid: "{{ netapp_e_ssid }}"
75 validate_certs: no
76 max_records: 50000
77 log_level: all
78 full_policy: preventSystemAccess
79 threshold: 60
80 log_path: /path/to/log_file.log
81 - name: Define audit-log utilize the default values.
82 netapp_e_auditlog:
83 api_url: "https://{{ netapp_e_api_host }}/devmgr/v2"
84 api_username: "{{ netapp_e_api_username }}"
85 api_password: "{{ netapp_e_api_password }}"
86 ssid: "{{ netapp_e_ssid }}"
87 - name: Force audit-log configuration when full or warning conditions occur while enacting preventSystemAccess policy.
88 netapp_e_auditlog:
89 api_url: "https://{{ netapp_e_api_host }}/devmgr/v2"
90 api_username: "{{ netapp_e_api_username }}"
91 api_password: "{{ netapp_e_api_password }}"
92 ssid: "{{ netapp_e_ssid }}"
93 max_records: 5000
94 log_level: all
95 full_policy: preventSystemAccess
96 threshold: 60
97 force: yes
98 """
99
100 RETURN = """
101 msg:
102 description: Success message
103 returned: on success
104 type: str
105 sample: The settings have been updated.
106 """
107
108 import json
109 import logging
110 from pprint import pformat
111
112 from ansible.module_utils.basic import AnsibleModule
113 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.netapp import request, eseries_host_argument_spec
114 from ansible.module_utils._text import to_native
115
116 try:
117 from urlparse import urlparse, urlunparse
118 except Exception:
119 from urllib.parse import urlparse, urlunparse
120
121
122 class AuditLog(object):
123 """Audit-log module configuration class."""
124 MAX_RECORDS = 50000
125 HEADERS = {"Content-Type": "application/json",
126 "Accept": "application/json"}
127
128 def __init__(self):
129 argument_spec = eseries_host_argument_spec()
130 argument_spec.update(dict(
131 max_records=dict(type="int", default=50000),
132 log_level=dict(type="str", default="writeOnly", choices=["all", "writeOnly"]),
133 full_policy=dict(type="str", default="overWrite", choices=["overWrite", "preventSystemAccess"]),
134 threshold=dict(type="int", default=90),
135 force=dict(type="bool", default=False),
136 log_path=dict(type='str', required=False)))
137
138 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
139 args = self.module.params
140
141 self.max_records = args["max_records"]
142 if self.max_records < 100 or self.max_records > self.MAX_RECORDS:
143 self.module.fail_json(msg="Audit-log max_records count must be between 100 and 50000: [%s]"
144 % self.max_records)
145 self.threshold = args["threshold"]
146 if self.threshold < 60 or self.threshold > 90:
147 self.module.fail_json(msg="Audit-log percent threshold must be between 60 and 90: [%s]" % self.threshold)
148 self.log_level = args["log_level"]
149 self.full_policy = args["full_policy"]
150 self.force = args["force"]
151 self.ssid = args['ssid']
152 self.url = args['api_url']
153 if not self.url.endswith('/'):
154 self.url += '/'
155 self.creds = dict(url_password=args['api_password'],
156 validate_certs=args['validate_certs'],
157 url_username=args['api_username'], )
158
159 # logging setup
160 log_path = args['log_path']
161 self._logger = logging.getLogger(self.__class__.__name__)
162
163 if log_path:
164 logging.basicConfig(
165 level=logging.DEBUG, filename=log_path, filemode='w',
166 format='%(relativeCreated)dms %(levelname)s %(module)s.%(funcName)s:%(lineno)d\n %(message)s')
167
168 self.proxy_used = self.is_proxy()
169 self._logger.info(self.proxy_used)
170 self.check_mode = self.module.check_mode
171
172 def is_proxy(self):
173 """Determine whether the API is embedded or proxy."""
174 try:
175
176 # replace http url path with devmgr/utils/about
177 about_url = list(urlparse(self.url))
178 about_url[2] = "devmgr/utils/about"
179 about_url = urlunparse(about_url)
180
181 rc, data = request(about_url, timeout=300, headers=self.HEADERS, **self.creds)
182
183 return data["runningAsProxy"]
184 except Exception as err:
185 self.module.fail_json(msg="Failed to retrieve the webservices about information! Array Id [%s]. Error [%s]."
186 % (self.ssid, to_native(err)))
187
188 def get_configuration(self):
189 """Retrieve the existing audit-log configurations.
190
191 :returns: dictionary containing current audit-log configuration
192 """
193 try:
194 if self.proxy_used:
195 rc, data = request(self.url + "audit-log/config", timeout=300, headers=self.HEADERS, **self.creds)
196 else:
197 rc, data = request(self.url + "storage-systems/%s/audit-log/config" % self.ssid,
198 timeout=300, headers=self.HEADERS, **self.creds)
199 return data
200 except Exception as err:
201 self.module.fail_json(msg="Failed to retrieve the audit-log configuration! "
202 "Array Id [%s]. Error [%s]."
203 % (self.ssid, to_native(err)))
204
205 def build_configuration(self):
206 """Build audit-log expected configuration.
207
208 :returns: Tuple containing update boolean value and dictionary of audit-log configuration
209 """
210 config = self.get_configuration()
211
212 current = dict(auditLogMaxRecords=config["auditLogMaxRecords"],
213 auditLogLevel=config["auditLogLevel"],
214 auditLogFullPolicy=config["auditLogFullPolicy"],
215 auditLogWarningThresholdPct=config["auditLogWarningThresholdPct"])
216
217 body = dict(auditLogMaxRecords=self.max_records,
218 auditLogLevel=self.log_level,
219 auditLogFullPolicy=self.full_policy,
220 auditLogWarningThresholdPct=self.threshold)
221
222 update = current != body
223
224 self._logger.info(pformat(update))
225 self._logger.info(pformat(body))
226 return update, body
227
228 def delete_log_messages(self):
229 """Delete all audit-log messages."""
230 self._logger.info("Deleting audit-log messages...")
231 try:
232 if self.proxy_used:
233 rc, result = request(self.url + "audit-log?clearAll=True", timeout=300,
234 method="DELETE", headers=self.HEADERS, **self.creds)
235 else:
236 rc, result = request(self.url + "storage-systems/%s/audit-log?clearAll=True" % self.ssid, timeout=300,
237 method="DELETE", headers=self.HEADERS, **self.creds)
238 except Exception as err:
239 self.module.fail_json(msg="Failed to delete audit-log messages! Array Id [%s]. Error [%s]."
240 % (self.ssid, to_native(err)))
241
242 def update_configuration(self, update=None, body=None, attempt_recovery=True):
243 """Update audit-log configuration."""
244 if update is None or body is None:
245 update, body = self.build_configuration()
246
247 if update and not self.check_mode:
248 try:
249 if self.proxy_used:
250 rc, result = request(self.url + "storage-systems/audit-log/config", timeout=300,
251 data=json.dumps(body), method='POST', headers=self.HEADERS,
252 ignore_errors=True, **self.creds)
253 else:
254 rc, result = request(self.url + "storage-systems/%s/audit-log/config" % self.ssid, timeout=300,
255 data=json.dumps(body), method='POST', headers=self.HEADERS,
256 ignore_errors=True, **self.creds)
257
258 if rc == 422:
259 if self.force and attempt_recovery:
260 self.delete_log_messages()
261 update = self.update_configuration(update, body, False)
262 else:
263 self.module.fail_json(msg="Failed to update audit-log configuration! Array Id [%s]. Error [%s]."
264 % (self.ssid, to_native(rc, result)))
265
266 except Exception as error:
267 self.module.fail_json(msg="Failed to update audit-log configuration! Array Id [%s]. Error [%s]."
268 % (self.ssid, to_native(error)))
269 return update
270
271 def update(self):
272 """Update the audit-log configuration."""
273 update = self.update_configuration()
274 self.module.exit_json(msg="Audit-log update complete", changed=update)
275
276 def __call__(self):
277 self.update()
278
279
280 def main():
281 auditlog = AuditLog()
282 auditlog()
283
284
285 if __name__ == "__main__":
286 main()