Debian Codegraph @

ansible_collections/purestorage/flasharray/plugins/modules/purefa_sessions.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2024, Simon Dodsley ([email protected])
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefa_sessions
20 version_added: '1.29.0'
21 short_description: List FlashArray Sessions
22 description:
23 - List sessions based on filters provided
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 start:
28 description:
29 - Start date and time (based on array local time)
30 - If not provided epoch is assumed
31 - Expected format "YYYY-MM-DD hh:mm:ss"
32 type: str
33 end:
34 description:
35 - End date and time (based on array local time)
36 - If not provided epoch is assumed
37 - Expected format "YYYY-MM-DD hh:mm:ss"
38 type: str
39 timezone:
40 description:
41 - The timezone of the FlashArray
42 - If not provided, the module will attempt to get the current local timezone
43 from the server however from Purity//FA 6.5.3 this value will calculated
44 automatically from the FlashArray
45 type: str
46 extends_documentation_fragment:
47 - purestorage.flasharray.purestorage.fa
48 """
49
50 EXAMPLES = r"""
51 - name: Show all sessions that started after the specified date/time
52 purefa_sessions:
53 start: "2024-06-29 12:31:34"
54 fa_url: 10.10.10.2
55 api_token: 89a9356f-c203-d263-8a89-c229486a13ba
56
57 - name: Show all sessions that started and ended between specified dates/times
58 purefa_sessions:
59 start: "2024-06-29 12:31:34"
60 end: "2024-06-30 04:23:34"
61 fa_url: 10.10.10.2
62 api_token: 89a9356f-c203-d263-8a89-c229486a13ba
63
64 - name: Show all sessions that ended after the specified date/time
65 purefa_sessions:
66 end: "2024-06-30 04:23:34"
67 fa_url: 10.10.10.2
68 api_token: 89a9356f-c203-d263-8a89-c229486a13ba
69
70 - name: Show all sessions that have been logged by the array (to the internal limit of the array)
71 purefa_sessions:
72 fa_url: 10.10.10.2
73 api_token: 89a9356f-c203-d263-8a89-c229486a13ba
74 """
75
76 RETURN = r"""
77 """
78
79 HAS_PYTZ = True
80 try:
81 import pytz
82 except ImportError:
83 HAS_PYTX = False
84
85 import datetime
86 from ansible.module_utils.basic import AnsibleModule
87 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
88 get_array,
89 purefa_argument_spec,
90 )
91 from ansible_collections.purestorage.flasharray.plugins.module_utils.version import (
92 LooseVersion,
93 )
94 from ansible_collections.purestorage.flasharray.plugins.module_utils.common import (
95 get_local_tz,
96 )
97
98 TZ_VERSION = "2.26"
99
100
101 def _get_filter_string(module, timezone):
102 filter_string = ""
103 if module.params["end"]:
104 if module.params["end"] != "0":
105 end = module.params["end"] + " " + timezone
106 end_timestamp = int(
107 1000
108 * datetime.datetime.timestamp(
109 datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S %z")
110 )
111 )
112 else:
113 end_timestamp = 0
114 if module.params["start"]:
115 if module.params["start"] != "0":
116 start = module.params["start"] + " " + timezone
117 start_timestamp = int(
118 1000
119 * datetime.datetime.timestamp(
120 datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S %z")
121 )
122 )
123 else:
124 start_timestamp = 0
125 if module.params["end"] and module.params["start"]:
126 filter_string = (
127 "start_time>="
128 + str(start_timestamp)
129 + " and end_time<="
130 + str(end_timestamp)
131 )
132 elif module.params["end"] and not module.params["start"]:
133 filter_string = "end_time<=" + str(end_timestamp)
134 elif module.params["start"] and not module.params["end"]:
135 filter_string = "start_time>=" + str(start_timestamp)
136 return filter_string
137
138
139 def main():
140 argument_spec = purefa_argument_spec()
141 argument_spec.update(
142 dict(
143 start=dict(type="str"),
144 end=dict(type="str"),
145 timezone=dict(type="str"),
146 )
147 )
148
149 module = AnsibleModule(argument_spec, supports_check_mode=True)
150
151 if not HAS_PYTZ:
152 module.fail_json(msg="pytz is required for this module")
153
154 array = get_array(module)
155 api_version = array.get_rest_version()
156 if not module.params["timezone"] and LooseVersion(TZ_VERSION) <= LooseVersion(
157 api_version
158 ):
159 timezone = list(array.get_arrays().items)[0].time_zone
160 elif not module.params["timezone"]:
161 timezone = get_local_tz(module)
162 elif module.params["timezone"] not in pytz.all_timezones_set:
163 module.fail_json(
164 msg="Timezone {0} is not valid".format(module.params["timezone"])
165 )
166 else:
167 timezone = module.params["timezone"]
168 tzoffset = datetime.datetime.now(pytz.timezone(timezone)).strftime("%z")
169 filter_string = _get_filter_string(module, tzoffset)
170 session_log = {}
171 if filter_string:
172 res = array.get_sessions(filter=filter_string)
173 else:
174 res = array.get_sessions()
175 if res.status_code == 200:
176 sessions = list(res.items)
177 else:
178 module.fail_json(
179 msg="Failed to get sessions. Error: {0}".format(res.errors[0].message)
180 )
181 for session in sessions:
182 name = session.name
183 if hasattr(session, "start_time"):
184 start_time = datetime.datetime.fromtimestamp(
185 session.start_time / 1000, tz=pytz.timezone(timezone)
186 ).strftime("%Y-%m-%d %H:%M:%S")
187 else:
188 start_time = "0"
189 if hasattr(session, "end_time"):
190 end_time = datetime.datetime.fromtimestamp(
191 session.end_time / 1000, tz=pytz.timezone(timezone)
192 ).strftime("%Y-%m-%d %H:%M:%S")
193 else:
194 end_time = "0"
195 session_log[name] = {
196 "start_time": start_time,
197 "end_time": end_time,
198 "interface": session.user_interface,
199 "user": getattr(session, "user", ""),
200 "location": getattr(session, "location", ""),
201 "repeat": getattr(session, "event_count", ""),
202 "event": session.event,
203 "method": getattr(session, "method", ""),
204 }
205 module.exit_json(changed=False, purefa_sessions=session_log)
206
207
208 if __name__ == "__main__":
209 main()