Debian Codegraph @

ansible_collections/community/sap_libs/plugins/modules/sap_system_facts.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2022-2026 The Project Contributors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # For a detailed list of copyright holders and contribution history,
18 # please refer to the CONTRIBUTORS.md file in the project root.
19
20 from __future__ import (absolute_import, division, print_function)
21 __metaclass__ = type
22
23 DOCUMENTATION = r'''
24 ---
25 module: sap_system_facts
26
27 short_description: Gathers SAP facts in a host
28
29 version_added: "1.0.0"
30
31 description:
32 - This facts module gathers SAP system facts about the running instance.
33
34 author:
35 - Rainer Leber (@rainerleber)
36
37 notes:
38 - Supports C(check_mode).
39 - The user executing the module must have execute permissions for C(/usr/sap/hostctrl/exe/sapcontrol).
40 - Only directories matching SAP SID and Instance naming conventions are scanned.
41 '''
42
43 EXAMPLES = r'''
44 - name: Return SAP system ansible_facts
45 community.sap_libs.sap_system_facts:
46 '''
47
48 RETURN = r'''
49 # These are examples of possible return values,
50 # and in general should use other names for return values.
51 ansible_facts:
52 description: Facts about the running SAP systems.
53 returned: always
54 type: dict
55 contains:
56 sap:
57 description: Facts about the running SAP systems.
58 type: list
59 elements: dict
60 returned: When SAP system fact is present
61 sample: [
62 {
63 "InstanceType": "NW",
64 "NR": "00",
65 "SID": "ABC",
66 "TYPE": "ASCS"
67 },
68 {
69 "InstanceType": "NW",
70 "NR": "01",
71 "SID": "ABC",
72 "TYPE": "PAS"
73 },
74 {
75 "InstanceType": "HANA",
76 "NR": "02",
77 "SID": "HDB",
78 "TYPE": "HDB"
79 },
80 {
81 "InstanceType": "NW",
82 "NR": "80",
83 "SID": "WEB",
84 "TYPE": "WebDisp"
85 }
86 ]
87 '''
88
89 from ansible.module_utils.basic import AnsibleModule
90 import os
91 import re
92
93
94 def get_all_hana_sid():
95 hana_sid = list()
96
97 # Expected SID pattern: 3 character in specific pattern (e.g., ABC, D01, etc.)
98 sid_pattern = re.compile(r'^[A-Z][A-Z0-9][A-Z0-9]$')
99
100 shared_path = "/hana/shared"
101
102 if is_accessible_dir(shared_path):
103 try:
104 for sid in os.listdir(shared_path):
105 if not sid_pattern.match(sid):
106 continue
107
108 target_path = os.path.join("/usr/sap", sid)
109
110 try:
111 if is_accessible_dir(target_path):
112 hana_sid.append(sid)
113 except OSError:
114 # Individual SID folder is problematic, move to next
115 continue
116
117 except OSError:
118 # Entire shared_path is inaccessible
119 pass
120
121 return hana_sid
122
123
124 def get_all_nw_sid():
125 nw_sid = list()
126
127 # Expected SID pattern with only 3 character in specific pattern (e.g., ABC, D01, etc.)
128 sid_pattern = re.compile(r'^[A-Z][A-Z0-9][A-Z0-9]$')
129
130 sapmnt_path = "/sapmnt"
131
132 if is_accessible_dir(sapmnt_path):
133 try:
134 for sid in os.listdir(sapmnt_path):
135 if not sid_pattern.match(sid):
136 continue
137
138 target_path = os.path.join("/usr/sap", sid)
139
140 try:
141 if is_accessible_dir(target_path):
142 nw_sid.append(sid)
143 else:
144 # Check to see if /sapmnt/SID/sap_bobj exists and is accessible
145 bobj_path = os.path.join(sapmnt_path, sid, "sap_bobj")
146 if is_accessible_dir(bobj_path):
147 nw_sid.append(sid)
148 except OSError:
149 # Individual SID folder is problematic, move to next
150 continue
151
152 except OSError:
153 # Entire shared_path is inaccessible
154 pass
155
156 return nw_sid
157
158
159 def get_hana_nr(sids, module):
160 hana_list = list()
161
162 # Expected Instance pattern: HDB followed by exactly 2 digits (e.g., HDB00, HDB01, etc.)
163 instance_pattern = re.compile(r'^HDB(\d{2})$')
164
165 sapcontrol_path = module.get_bin_path('/usr/sap/hostctrl/exe/sapcontrol', required=True)
166
167 for sid in sids:
168 path = os.path.join('/usr/sap', sid)
169
170 if not is_accessible_dir(path):
171 continue
172
173 for instance in os.listdir(path):
174 match = instance_pattern.match(instance)
175 if match:
176 # 'match.group(1)' is the 2 digits captured by (\d{2})
177 instance_nr = match.group(1)
178
179 command = [sapcontrol_path]
180 command.extend(['-nr', instance_nr, '-function', 'GetProcessList'])
181
182 check_instance = module.run_command(command, check_rc=False)
183
184 # sapcontrol returns (0-5) exit codes; (1) usually means unavailable
185 if check_instance[0] != 1:
186 hana_list.append({
187 'NR': instance_nr,
188 'SID': sid,
189 'TYPE': 'HDB',
190 'InstanceType': 'HANA'
191 })
192
193 return hana_list
194
195
196 def get_nw_nr(sids, module):
197 nw_list = list()
198
199 # Expected Instance pattern: letters followed by exactly 2 digits (e.g., ASCS00, D01)
200 # Excludes 'SYS', 'exe', 'hdbclient', etc.
201 instance_pattern = re.compile(r'^[a-zA-Z]+(\d{2})$')
202
203 sapcontrol_path = module.get_bin_path('/usr/sap/hostctrl/exe/sapcontrol', required=True)
204 type = ""
205
206 for sid in sids:
207 path = os.path.join('/usr/sap', sid)
208
209 if not is_accessible_dir(path):
210 continue
211
212 for instance in os.listdir(path):
213 match = instance_pattern.match(instance)
214 if match:
215 # 'match.group(1)' is the 2 digits captured by (\d{2})
216 instance_nr = match.group(1)
217
218 command = [sapcontrol_path]
219 command.extend(['-nr', instance_nr, '-function', 'GetInstanceProperties'])
220
221 check_instance = module.run_command(command, check_rc=False)
222 if check_instance[0] != 1:
223 for line in check_instance[1].splitlines():
224 if re.search('INSTANCE_NAME', line):
225 # convert to list and extract last
226 type_raw = (line.strip('][').split(', '))[-1]
227 # split instance number
228 type = type_raw[:-2]
229 nw_list.append({'NR': instance_nr, 'SID': sid, 'TYPE': get_instance_type(type), 'InstanceType': 'NW'})
230
231 return nw_list
232
233
234 def get_instance_type(raw_type):
235 if raw_type[0] == "D":
236 # It's a PAS
237 type = "PAS"
238 elif raw_type[0] == "A":
239 # It's an ASCS
240 type = "ASCS"
241 elif raw_type[0] == "W":
242 # It's a Webdisp
243 type = "WebDisp"
244 elif raw_type[0] == "J":
245 # It's a Java
246 type = "Java"
247 elif raw_type[0] == "S":
248 # It's an SCS
249 type = "SCS"
250 elif raw_type[0] == "E":
251 # It's an ERS
252 type = "ERS"
253 else:
254 # Unknown instance type
255 type = "XXX"
256 return type
257
258
259 def is_accessible_dir(path):
260 return os.path.isdir(path) and os.access(path, os.R_OK)
261
262
263 def run_module():
264 module_args = dict()
265 system_result = list()
266
267 result = dict(
268 changed=False,
269 ansible_facts=dict(),
270 )
271
272 module = AnsibleModule(
273 argument_spec=module_args,
274 supports_check_mode=True,
275 )
276
277 # Fail if execution user does not have permission for sapcontrol
278 sapcontrol_path = module.get_bin_path('/usr/sap/hostctrl/exe/sapcontrol', required=True)
279 if not os.access(sapcontrol_path, os.X_OK):
280 module.fail_json(msg="Permission denied: Ansible user cannot execute {0}".format(sapcontrol_path))
281
282 hana_sid = get_all_hana_sid()
283 if hana_sid:
284 system_result = system_result + get_hana_nr(hana_sid, module)
285
286 nw_sid = get_all_nw_sid()
287 if nw_sid:
288 system_result = system_result + get_nw_nr(nw_sid, module)
289
290 if system_result:
291 result['ansible_facts'] = {'sap': system_result}
292 result['msg'] = "SAP System facts were collected."
293 else:
294 result['ansible_facts']
295 result['msg'] = "No running SAP instances found or Ansible user cannot access them."
296
297 if module.check_mode:
298 module.exit_json(**result)
299
300 module.exit_json(**result)
301
302
303 def main():
304 run_module()
305
306
307 if __name__ == '__main__':
308 main()