Debian Codegraph @

ansible_collections/community/sap_libs/plugins/modules/sapcar_extract.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: sapcar_extract
26 short_description: Manages SAP SAPCAR archives
27 version_added: "1.0.0"
28 description:
29 - Provides support for unpacking C(sar)/C(car) files with the SAPCAR binary from SAP and pulling
30 information back into Ansible.
31 options:
32 path:
33 description: The path to the SAR/CAR file.
34 type: path
35 required: true
36 dest:
37 description:
38 - The destination where SAPCAR extracts the SAR file. Missing folders will be created.
39 If this parameter is not provided, it will unpack in the same folder as the SAR file.
40 type: path
41 binary_path:
42 description:
43 - The path to the SAPCAR binary, for example, C(/home/dummy/sapcar) or C(https://myserver/SAPCAR).
44 If this parameter is not provided, the module will look in C(PATH).
45 type: path
46 signature:
47 description:
48 - If C(true), the signature will be extracted.
49 default: false
50 type: bool
51 security_library:
52 description:
53 - The path to the security library, for example, C(/usr/sap/hostctrl/exe/libsapcrytp.so), for signature operations.
54 type: path
55 manifest:
56 description:
57 - The name of the manifest.
58 default: "SIGNATURE.SMF"
59 type: str
60 remove:
61 description:
62 - If C(true), the SAR/CAR file will be removed. B(This should be used with caution!)
63 default: false
64 type: bool
65 overwrite:
66 description:
67 - If C(true), existing files will be overwritten during extraction. B(This should be used with caution!)
68 - If C(false), the module checks if the expected file names are already present in the destination folder and only extracts if they are not found.
69 - It does not remove files, but overwrites them if they are already present in the destination folder.
70 default: false
71 type: bool
72 author:
73 - Rainer Leber (@RainerLeber)
74 notes:
75 - Always returns C(changed=true) in C(check_mode).
76 '''
77
78 EXAMPLES = r"""
79 - name: Extract SAR file
80 community.sap_libs.sapcar_extract:
81 path: "~/source/hana.sar"
82
83 - name: Extract SAR file with destination
84 community.sap_libs.sapcar_extract:
85 path: "~/source/hana.sar"
86 dest: "~/test/"
87
88 - name: Extract SAR file with destination and download from webserver can be a fileshare as well
89 community.sap_libs.sapcar_extract:
90 path: "~/source/hana.sar"
91 dest: "~/dest/"
92 binary_path: "https://myserver/SAPCAR"
93
94 - name: Extract SAR file and delete SAR after extract
95 community.sap_libs.sapcar_extract:
96 path: "~/source/hana.sar"
97 remove: true
98
99 - name: Extract SAR file with manifest
100 community.sap_libs.sapcar_extract:
101 path: "~/source/hana.sar"
102 signature: true
103
104 - name: Extract SAR file with manifest and rename it
105 community.sap_libs.sapcar_extract:
106 path: "~/source/hana.sar"
107 manifest: "MyNewSignature.SMF"
108 signature: true
109 """
110
111 RETURN = r'''
112 msg:
113 description: Status message about the extraction operation.
114 type: str
115 returned: always
116 sample: "Files extracted to /tmp/test2 (overwrite mode enabled)"
117 stdout:
118 description: Standard output from the SAPCAR command.
119 type: str
120 returned: always
121 sample: "SAPCAR: processing archive /tmp/hana.sar (version 2.01)\\nfile1\\nfile2"
122 stderr:
123 description: Standard error from the SAPCAR command.
124 type: str
125 returned: always
126 sample: ""
127 command:
128 description: The full SAPCAR command that was executed.
129 type: str
130 returned: always
131 sample: "/tmp/sapcar -xvf /tmp/hana.sar -R /tmp/test2"
132 changed:
133 description: Whether the module made changes.
134 type: bool
135 returned: always
136 sample: true
137 '''
138
139 import os
140 from tempfile import NamedTemporaryFile
141 from ansible.module_utils.basic import AnsibleModule
142 from ansible.module_utils.urls import open_url
143 from ansible.module_utils.common.text.converters import to_native
144
145
146 def get_list_of_files(dir_name):
147 # create a list of file and directories
148 # names in the given directory
149 list_of_file = os.listdir(dir_name)
150 allFiles = list()
151 # Iterate over all the entries
152 for entry in list_of_file:
153 # Create full path
154 fullPath = os.path.join(dir_name, entry)
155 # If entry is a directory then get the list of files in this directory
156 if os.path.isdir(fullPath):
157 allFiles = allFiles + [fullPath]
158 allFiles = allFiles + get_list_of_files(fullPath)
159 else:
160 allFiles.append(fullPath)
161 return allFiles
162
163
164 def download_SAPCAR(binary_path, module):
165 bin_path = None
166 # download sapcar binary if url is provided otherwise path is returned
167 if binary_path is not None:
168 if binary_path.startswith('https://') or binary_path.startswith('http://'):
169 random_file = NamedTemporaryFile(delete=False)
170 with open_url(binary_path) as response:
171 with random_file as out_file:
172 data = response.read()
173 out_file.write(data)
174 os.chmod(out_file.name, 0o700)
175 bin_path = out_file.name
176 module.add_cleanup_file(bin_path)
177 else:
178 bin_path = binary_path
179 return bin_path
180
181
182 def check_if_present(command, path, dest, signature, manifest, module):
183 # Get list of files from sar file without extraction
184 iter_command = [command, '-tvf', path]
185 sar_out = module.run_command(iter_command)[1]
186 sar_raw = sar_out.split("\n")[1:]
187
188 if dest[-1] != "/":
189 dest = dest + "/"
190 sar_files = [dest + x.split(" ")[-1] for x in sar_raw if x]
191
192 # remove any SIGNATURE.SMF from list because it will not unpacked if signature is false
193 if not signature:
194 sar_files = [item for item in sar_files if not item.endswith('.SMF')]
195
196 # if signature is renamed manipulate files in list of sar file for compare.
197 if manifest != "SIGNATURE.SMF":
198 sar_files = [item for item in sar_files if not item.endswith('.SMF')]
199 sar_files = sar_files + [manifest]
200
201 # get extracted files if present
202 files_extracted = get_list_of_files(dest)
203 # compare extracted files with files in sar file
204 present = all(elem in files_extracted for elem in sar_files)
205
206 return present
207
208
209 def main():
210 module = AnsibleModule(
211 argument_spec=dict(
212 path=dict(type='path', required=True),
213 dest=dict(type='path'),
214 binary_path=dict(type='path'),
215 signature=dict(type='bool', default=False),
216 security_library=dict(type='path'),
217 manifest=dict(type='str', default="SIGNATURE.SMF"),
218 remove=dict(type='bool', default=False),
219 overwrite=dict(type='bool', default=False)
220 ),
221 supports_check_mode=True,
222 )
223 rc, out, err = [0, "", ""]
224 params = module.params
225 check_mode = module.check_mode
226
227 bin_path = download_SAPCAR(params['binary_path'], module)
228
229 # Check if path is present and readable
230 if os.path.isfile(params['path']):
231 if not os.access(params['path'], os.R_OK):
232 module.fail_json(msg="Permission denied: File defined in the 'path' parameter is not readable: {0}".format(params['path']))
233 else:
234 module.fail_json(msg='File missing: File defined in the "path" parameter does not exist: {0}'.format(params['path']))
235
236 # Check if destination exists and it is directory, if not create it.
237 dest = params['dest']
238 if dest is None:
239 dest_head_tail = os.path.split(params['path'])
240 dest = dest_head_tail[0] + '/'
241 else:
242 if not os.path.exists(dest):
243 os.makedirs(dest, 0o755)
244
245 if bin_path is not None:
246 command = [module.get_bin_path(bin_path, required=True)]
247 else:
248 try:
249 command = [module.get_bin_path('sapcar', required=True)]
250 except Exception as e:
251 module.fail_json(msg='Failed to find SAPCAR at the expected path or URL "{0}". Please check whether it is available: {1}'
252 .format(bin_path, to_native(e)))
253
254 present = check_if_present(command[0], params['path'], dest, params['signature'], params['manifest'], module)
255
256 if not present or params['overwrite']:
257 command.extend(['-xvf', params['path'], '-R', dest])
258
259 if params['security_library']:
260 command.extend(['-L', params['security_library']])
261
262 if params['signature']:
263 command.extend(['-manifest', params['manifest']])
264
265 if not check_mode:
266 (rc, out, err) = module.run_command(command, check_rc=True)
267 changed = True
268 msg = "Files extracted to {0}".format(dest)
269 if params['overwrite']:
270 msg += " (overwrite mode enabled)"
271
272 else:
273 changed = False
274 msg = "Expected file names were found in {0}. No extraction needed.".format(dest)
275 out = ""
276
277 if params['remove']:
278 os.remove(params['path'])
279
280 module.exit_json(changed=changed, msg=msg, stdout=out,
281 stderr=err, command=' '.join(command))
282
283
284 if __name__ == '__main__':
285 main()