Debian Codegraph @

lib/ansible/modules/find.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2014, Ruggero Marchei <[email protected]>
4 # Copyright: (c) 2015, Brian Coca <[email protected]>
5 # Copyright: (c) 2016-2017, Konstantin Shalygin <[email protected]>
6 # Copyright: (c) 2017, Ansible Project
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import annotations
10
11
12 DOCUMENTATION = r"""
13 ---
14 module: find
15 author: Brian Coca (@bcoca)
16 version_added: "2.0"
17 short_description: Return a list of files based on specific criteria
18 description:
19 - Return a list of files based on specific criteria. Multiple criteria are AND'd together.
20 - For Windows targets, use the M(ansible.windows.win_find) module instead.
21 - This module does not use the C(find) command, it is a much simpler and slower Python implementation.
22 It is intended for small and simple uses. Those that need the extra power or speed and have expertise
23 with the UNIX command, should use it directly.
24 options:
25 age:
26 description:
27 - Select files whose age is equal to or greater than the specified time.
28 - Use a negative age to find files equal to or less than the specified time.
29 - You can choose seconds, minutes, hours, days, or weeks by specifying the
30 first letter of any of those words (for example V(1w)).
31 type: str
32 get_checksum:
33 default: false
34 checksum_algorithm:
35 version_added: "2.19"
36 patterns:
37 default: []
38 description:
39 - One or more (shell or regex) patterns, which type is controlled by O(use_regex) option.
40 - The patterns restrict the list of files to be returned to those whose base names match at
41 least one of the patterns specified. Multiple patterns can be specified using a list.
42 - The pattern is matched against the file base name, excluding the directory.
43 - If O(use_regex=true), the pattern matches against the beginning of the file name using Python's
44 C(re.match(\)). To match the entire file name rather than just a prefix, anchor the end of the
45 pattern with V($). For example, to match all C(.md) files, use V(.*\\.md$) instead of V(\\.md).
46 - This parameter expects a list, which can be either comma separated or YAML. If any of the
47 patterns contain a comma, make sure to put them in a list to avoid splitting the patterns
48 in undesirable ways.
49 - Defaults to V(*) when O(use_regex=false), or V(.*) when O(use_regex=true).
50 type: list
51 aliases: [ pattern ]
52 elements: str
53 excludes:
54 description:
55 - One or more (shell or regex) patterns, which type is controlled by O(use_regex) option.
56 - Items whose base names match an O(excludes) pattern are culled from O(patterns) matches.
57 Multiple patterns can be specified using a list.
58 type: list
59 aliases: [ exclude ]
60 version_added: "2.5"
61 elements: str
62 contains:
63 description:
64 - A regular expression or pattern which should be matched against the file content.
65 - If O(read_whole_file=false) it matches against the beginning of the line (uses
66 C(re.match(\))). If O(read_whole_file=true), it searches anywhere for that pattern
67 (uses C(re.search(\))).
68 - Works only when O(file_type) is V(file).
69 type: str
70 read_whole_file:
71 description:
72 - When doing a O(contains) search, determines whether the whole file should be read into
73 memory or if the regex should be applied to the file line-by-line.
74 - Setting this to V(true) can have performance and memory implications for large files.
75 - This uses C(re.search(\)) instead of C(re.match(\)).
76 type: bool
77 default: false
78 version_added: "2.11"
79 paths:
80 description:
81 - List of paths of directories to search. All paths must be fully qualified.
82 - From ansible-core 2.18 and onwards, the data type has changed from C(str) to C(path).
83 type: list
84 required: true
85 aliases: [ name, path ]
86 elements: path
87 file_type:
88 description:
89 - Type of file to select.
90 - The V(link) and V(any) choices were added in Ansible 2.3.
91 type: str
92 choices: [ any, directory, file, link ]
93 default: file
94 recurse:
95 description:
96 - If target is a directory, recursively descend into the directory looking for files.
97 type: bool
98 default: no
99 size:
100 description:
101 - Select files whose size is equal to or greater than the specified size.
102 - Use a negative size to find files equal to or less than the specified size.
103 - Unqualified values are in bytes but V(b), V(k), V(m), V(g), and V(t) can be appended to specify
104 bytes, kilobytes, megabytes, gigabytes, and terabytes, respectively.
105 - Size is not evaluated for directories.
106 type: str
107 age_stamp:
108 description:
109 - Choose the file property against which we compare age.
110 type: str
111 choices: [ atime, ctime, mtime ]
112 default: mtime
113 hidden:
114 description:
115 - Set this to V(true) to include hidden files, otherwise they are ignored.
116 type: bool
117 default: no
118 mode:
119 description:
120 - Choose objects matching a specified permission. This value is
121 restricted to modes that can be applied using the python
122 C(os.chmod(\)) function.
123 - The mode can be provided as an octal such as V("0644") or
124 as symbolic such as V(u=rw,g=r,o=r).
125 type: raw
126 version_added: '2.16'
127 exact_mode:
128 description:
129 - Restrict mode matching to exact matches only, and not as a
130 minimum set of permissions to match.
131 type: bool
132 default: true
133 version_added: '2.16'
134 follow:
135 description:
136 - Set this to V(true) to follow symlinks in path for systems with python 2.6+.
137 type: bool
138 default: no
139 use_regex:
140 description:
141 - If V(false), the patterns are file globs (shell).
142 - If V(true), they are Python regular expressions.
143 type: bool
144 default: no
145 depth:
146 description:
147 - Set the maximum number of levels to descend into.
148 - Setting O(recurse=false) is effectively O(depth=1) and overrides this value.
149 - Default is unlimited depth.
150 type: int
151 version_added: "2.6"
152 encoding:
153 description:
154 - When doing a O(contains) search, determine the encoding of the files to be searched.
155 - When no value is provided, the Python default encoding is used.
156 type: str
157 version_added: "2.17"
158 limit:
159 description:
160 - Limit the maximum number of matching paths returned. After finding this many, the find action stops looking.
161 - Matches are made from the top, down (meaning the shallowest directory first).
162 - If not set, or set to V(null), it performs unlimited matches.
163 - Default is unlimited matches.
164 type: int
165 version_added: "2.18"
166 extends_documentation_fragment: [action_common_attributes, checksum_common]
167 attributes:
168 check_mode:
169 details: since this action does not modify the target it just executes normally during check mode
170 support: full
171 diff_mode:
172 support: none
173 platform:
174 platforms: posix
175 seealso:
176 - module: ansible.windows.win_find
177 """
178
179
180 EXAMPLES = r"""
181 - name: Recursively find /tmp files older than 2 days
182 ansible.builtin.find:
183 paths: /tmp
184 age: 2d
185 recurse: yes
186
187 - name: Recursively find /tmp files older than 4 weeks and equal or greater than 1 megabyte
188 ansible.builtin.find:
189 paths: /tmp
190 age: 4w
191 size: 1m
192 recurse: yes
193
194 - name: Recursively find /var/tmp files with last access time greater than 3600 seconds
195 ansible.builtin.find:
196 paths: /var/tmp
197 age: 3600
198 age_stamp: atime
199 recurse: yes
200
201 - name: Find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz
202 ansible.builtin.find:
203 paths: /var/log
204 patterns: '*.old,*.log.gz'
205 size: 10m
206
207 # Note that YAML double quotes require escaping backslashes but yaml single quotes do not.
208 - name: Find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz via regex
209 ansible.builtin.find:
210 paths: /var/log
211 patterns: "^.*?\\.(?:old|log\\.gz)$"
212 size: 10m
213 use_regex: yes
214
215 - name: Find /var/log all directories, exclude nginx and mysql
216 ansible.builtin.find:
217 paths: /var/log
218 recurse: no
219 file_type: directory
220 excludes: 'nginx,mysql'
221
222 # When using patterns that contain a comma, make sure they are formatted as lists to avoid splitting the pattern
223 - name: Use a single pattern that contains a comma formatted as a list
224 ansible.builtin.find:
225 paths: /var/log
226 file_type: file
227 use_regex: yes
228 patterns: ['^_[0-9]{2,4}_.*.log$']
229
230 - name: Use multiple patterns that contain a comma formatted as a YAML list
231 ansible.builtin.find:
232 paths: /var/log
233 file_type: file
234 use_regex: yes
235 patterns:
236 - '^_[0-9]{2,4}_.*.log$'
237 - '^[a-z]{1,5}_.*log$'
238
239 - name: Find file containing "wally" without necessarily reading all files
240 ansible.builtin.find:
241 paths: /var/log
242 file_type: file
243 contains: wally
244 read_whole_file: true
245 patterns: "^.*\\.log$"
246 use_regex: true
247 recurse: true
248 limit: 1
249 """
250
251 RETURN = r"""
252 files:
253 description: All matches found with the specified criteria (see stat module for full output of each dictionary)
254 returned: success
255 type: list
256 sample: [
257 { path: "/var/tmp/test1",
258 mode: "0644",
259 "...": "...",
260 checksum: 16fac7be61a6e4591a33ef4b729c5c3302307523
261 },
262 { path: "/var/tmp/test2",
263 "...": "..."
264 },
265 ]
266 matched:
267 description: Number of matches
268 returned: success
269 type: int
270 sample: 14
271 examined:
272 description: Number of filesystem objects looked at
273 returned: success
274 type: int
275 sample: 34
276 skipped_paths:
277 description: skipped paths and reasons they were skipped
278 returned: success
279 type: dict
280 sample: {"/laskdfj": "'/laskdfj' is not a directory"}
281 version_added: '2.12'
282 """
283
284 import errno
285 import fnmatch
286 import grp
287 import locale
288 import os
289 import pwd
290 import re
291 import stat
292 import time
293
294 from ansible.module_utils.common.text.converters import to_text, to_native
295 from ansible.module_utils.basic import AnsibleModule
296
297
298 class _Object:
299 def __init__(self, **kwargs):
300 for k, v in kwargs.items():
301 setattr(self, k, v)
302
303
304 def pfilter(f, patterns=None, excludes=None, use_regex=False):
305 """filter using glob patterns"""
306 if not patterns and not excludes:
307 return True
308
309 if use_regex:
310 if patterns and not excludes:
311 for p in patterns:
312 r = re.compile(p)
313 if r.match(f):
314 return True
315
316 elif patterns and excludes:
317 for p in patterns:
318 r = re.compile(p)
319 if r.match(f):
320 for e in excludes:
321 r = re.compile(e)
322 if r.match(f):
323 return False
324 return True
325
326 else:
327 if patterns and not excludes:
328 for p in patterns:
329 if fnmatch.fnmatch(f, p):
330 return True
331
332 elif patterns and excludes:
333 for p in patterns:
334 if fnmatch.fnmatch(f, p):
335 for e in excludes:
336 if fnmatch.fnmatch(f, e):
337 return False
338 return True
339
340 return False
341
342
343 def agefilter(st, now, age, timestamp):
344 """filter files older than age"""
345 if age is None:
346 return True
347 elif age >= 0 and now - getattr(st, "st_%s" % timestamp) >= abs(age):
348 return True
349 elif age < 0 and now - getattr(st, "st_%s" % timestamp) <= abs(age):
350 return True
351 return False
352
353
354 def sizefilter(st, size):
355 """filter files greater than size"""
356 if size is None:
357 return True
358 elif size >= 0 and st.st_size >= abs(size):
359 return True
360 elif size < 0 and st.st_size <= abs(size):
361 return True
362 return False
363
364
365 def contentfilter(fsname, pattern, encoding, read_whole_file=False):
366 """
367 Filter files which contain the given expression
368 :arg fsname: Filename to scan for lines matching a pattern
369 :arg pattern: Pattern to look for inside of line
370 :arg encoding: Encoding of the file to be scanned
371 :arg read_whole_file: If true, the whole file is read into memory before the regex is applied against it. Otherwise, the regex is applied line-by-line.
372 :rtype: bool
373 :returns: True if one of the lines in fsname matches the pattern. Otherwise False
374 """
375 if pattern is None:
376 return True
377
378 prog = re.compile(pattern)
379
380 try:
381 with open(fsname, encoding=encoding) as f:
382 if read_whole_file:
383 return bool(prog.search(f.read()))
384
385 for line in f:
386 if prog.match(line):
387 return True
388
389 except LookupError as e:
390 raise e
391 except UnicodeDecodeError as e:
392 if encoding is None:
393 # Get the default encoding for the current locale
394 # This is the same encoding that the open() function uses by default
395 # when no encoding is specified. This value is platform dependent.
396 #
397 # https://docs.python.org/3/library/functions.html#open
398 encoding = f"{locale.getpreferredencoding(False).lower()} (Python default)"
399 msg = f'Failed to decode the file {fsname!r} with encoding: {encoding}'
400 raise Exception(msg) from e
401 except Exception:
402 pass
403
404 return False
405
406
407 def mode_filter(st, mode, exact, module):
408 if not mode:
409 return True
410
411 st_mode = stat.S_IMODE(st.st_mode)
412
413 try:
414 mode = int(mode, 8)
415 except ValueError:
416 mode = module._symbolic_mode_to_octal(_Object(st_mode=0), mode)
417
418 mode = stat.S_IMODE(mode)
419
420 if exact:
421 return st_mode == mode
422
423 return bool(st_mode & mode)
424
425
426 def statinfo(st):
427 pw_name = ""
428 gr_name = ""
429
430 try: # user data
431 pw_name = pwd.getpwuid(st.st_uid).pw_name
432 except Exception:
433 pass
434
435 try: # group data
436 gr_name = grp.getgrgid(st.st_gid).gr_name
437 except Exception:
438 pass
439
440 output = {
441 'mode': "%04o" % stat.S_IMODE(st.st_mode),
442 'isdir': stat.S_ISDIR(st.st_mode),
443 'ischr': stat.S_ISCHR(st.st_mode),
444 'isblk': stat.S_ISBLK(st.st_mode),
445 'isreg': stat.S_ISREG(st.st_mode),
446 'isfifo': stat.S_ISFIFO(st.st_mode),
447 'islnk': stat.S_ISLNK(st.st_mode),
448 'issock': stat.S_ISSOCK(st.st_mode),
449 'uid': st.st_uid,
450 'gid': st.st_gid,
451 'size': st.st_size,
452 'inode': st.st_ino,
453 'dev': st.st_dev,
454 'nlink': st.st_nlink,
455 'atime': st.st_atime,
456 'mtime': st.st_mtime,
457 'ctime': st.st_ctime,
458 'gr_name': gr_name,
459 'pw_name': pw_name,
460 'wusr': bool(st.st_mode & stat.S_IWUSR),
461 'rusr': bool(st.st_mode & stat.S_IRUSR),
462 'xusr': bool(st.st_mode & stat.S_IXUSR),
463 'wgrp': bool(st.st_mode & stat.S_IWGRP),
464 'rgrp': bool(st.st_mode & stat.S_IRGRP),
465 'xgrp': bool(st.st_mode & stat.S_IXGRP),
466 'woth': bool(st.st_mode & stat.S_IWOTH),
467 'roth': bool(st.st_mode & stat.S_IROTH),
468 'xoth': bool(st.st_mode & stat.S_IXOTH),
469 'isuid': bool(st.st_mode & stat.S_ISUID),
470 'isgid': bool(st.st_mode & stat.S_ISGID),
471 }
472
473 if hasattr(st, 'st_blocks'):
474 output['blocks'] = st.st_blocks
475 output['disk_usage_bytes'] = st.st_blocks * 512
476
477 return output
478
479
480 def main():
481 module = AnsibleModule(
482 argument_spec=dict(
483 paths=dict(type='list', required=True, aliases=['name', 'path'], elements='path'),
484 patterns=dict(type='list', default=[], aliases=['pattern'], elements='str'),
485 excludes=dict(type='list', aliases=['exclude'], elements='str'),
486 contains=dict(type='str'),
487 read_whole_file=dict(type='bool', default=False),
488 file_type=dict(type='str', default="file", choices=['any', 'directory', 'file', 'link']),
489 age=dict(type='str'),
490 age_stamp=dict(type='str', default="mtime", choices=['atime', 'ctime', 'mtime']),
491 size=dict(type='str'),
492 recurse=dict(type='bool', default=False),
493 hidden=dict(type='bool', default=False),
494 follow=dict(type='bool', default=False),
495 get_checksum=dict(type='bool', default=False),
496 checksum_algorithm=dict(type='str', default='sha1',
497 choices=['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
498 aliases=['checksum', 'checksum_algo']),
499 use_regex=dict(type='bool', default=False),
500 depth=dict(type='int'),
501 mode=dict(type='raw'),
502 exact_mode=dict(type='bool', default=True),
503 encoding=dict(type='str'),
504 limit=dict(type='int')
505 ),
506 supports_check_mode=True,
507 )
508
509 params = module.params
510
511 if params['mode'] and not isinstance(params['mode'], str):
512 module.fail_json(
513 msg="argument 'mode' is not a string and conversion is not allowed, value is of type %s" % params['mode'].__class__.__name__
514 )
515
516 # Set the default match pattern to either a match-all glob or
517 # regex depending on use_regex being set. This makes sure if you
518 # set excludes: without a pattern pfilter gets something it can
519 # handle.
520 if not params['patterns']:
521 if params['use_regex']:
522 params['patterns'] = ['.*']
523 else:
524 params['patterns'] = ['*']
525
526 filelist = []
527 skipped = {}
528
529 def handle_walk_errors(e):
530 if e.errno in (errno.EPERM, errno.EACCES, errno.ENOENT):
531 skipped[e.filename] = to_text(e)
532 return
533 raise e
534
535 if params['age'] is None:
536 age = None
537 else:
538 # convert age to seconds:
539 m = re.match(r"^(-?\d+)(s|m|h|d|w)?$", params['age'].lower())
540 seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
541 if m:
542 age = int(m.group(1)) * seconds_per_unit.get(m.group(2), 1)
543 else:
544 module.fail_json(age=params['age'], msg="failed to process age")
545
546 if params['size'] is None:
547 size = None
548 else:
549 # convert size to bytes:
550 m = re.match(r"^(-?\d+)(b|k|m|g|t)?$", params['size'].lower())
551 bytes_per_unit = {"b": 1, "k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4}
552 if m:
553 size = int(m.group(1)) * bytes_per_unit.get(m.group(2), 1)
554 else:
555 module.fail_json(size=params['size'], msg="failed to process size")
556
557 if params['limit'] is not None and params['limit'] <= 0:
558 module.fail_json(msg="limit cannot be %d (use None for unlimited)" % params['limit'])
559
560 now = time.time()
561 msg = 'All paths examined'
562 looked = 0
563 has_warnings = False
564 for npath in params['paths']:
565 try:
566 if not os.path.isdir(npath):
567 raise Exception("'%s' is not a directory" % to_native(npath))
568
569 # Setting `topdown=True` to explicitly guarantee matches are made from the shallowest directory first
570 for root, dirs, files in os.walk(npath, onerror=handle_walk_errors, followlinks=params['follow'], topdown=True):
571 looked = looked + len(files) + len(dirs)
572 for fsobj in (files + dirs):
573 fsname = os.path.normpath(os.path.join(root, fsobj))
574 if params['depth']:
575 wpath = npath.rstrip(os.path.sep) + os.path.sep
576 depth = int(fsname.count(os.path.sep)) - int(wpath.count(os.path.sep)) + 1
577 if depth > params['depth']:
578 # Empty the list used by os.walk to avoid traversing deeper unnecessarily
579 del dirs[:]
580 continue
581 if os.path.basename(fsname).startswith('.') and not params['hidden']:
582 continue
583
584 try:
585 st = os.lstat(fsname)
586 except OSError as ex:
587 module.error_as_warning(f"Skipped entry {fsname!r} due to access issue.", exception=ex)
588 skipped[fsname] = str(ex)
589 has_warnings = True
590 continue
591
592 r = {'path': fsname}
593 if params['file_type'] == 'any':
594 if (pfilter(fsobj, params['patterns'], params['excludes'], params['use_regex']) and
595 agefilter(st, now, age, params['age_stamp']) and
596 mode_filter(st, params['mode'], params['exact_mode'], module)):
597
598 r.update(statinfo(st))
599 if stat.S_ISREG(st.st_mode) and params['get_checksum']:
600 r['checksum'] = module.digest_from_file(fsname, params['checksum_algorithm'])
601
602 if stat.S_ISREG(st.st_mode):
603 if sizefilter(st, size):
604 filelist.append(r)
605 else:
606 filelist.append(r)
607
608 elif stat.S_ISDIR(st.st_mode) and params['file_type'] == 'directory':
609 if (pfilter(fsobj, params['patterns'], params['excludes'], params['use_regex']) and
610 agefilter(st, now, age, params['age_stamp']) and
611 mode_filter(st, params['mode'], params['exact_mode'], module)):
612
613 r.update(statinfo(st))
614 filelist.append(r)
615
616 elif stat.S_ISREG(st.st_mode) and params['file_type'] == 'file':
617 if (pfilter(fsobj, params['patterns'], params['excludes'], params['use_regex']) and
618 agefilter(st, now, age, params['age_stamp']) and
619 sizefilter(st, size) and
620 contentfilter(fsname, params['contains'], params['encoding'], params['read_whole_file']) and
621 mode_filter(st, params['mode'], params['exact_mode'], module)):
622
623 r.update(statinfo(st))
624 if params['get_checksum']:
625 r['checksum'] = module.digest_from_file(fsname, params['checksum_algorithm'])
626 filelist.append(r)
627
628 elif stat.S_ISLNK(st.st_mode) and params['file_type'] == 'link':
629 if (pfilter(fsobj, params['patterns'], params['excludes'], params['use_regex']) and
630 agefilter(st, now, age, params['age_stamp']) and
631 mode_filter(st, params['mode'], params['exact_mode'], module)):
632
633 r.update(statinfo(st))
634 filelist.append(r)
635
636 if len(filelist) == params["limit"]:
637 # Breaks out of directory files loop only
638 msg = "Limit of matches reached"
639 break
640
641 if not params['recurse'] or len(filelist) == params["limit"]:
642 break
643 except Exception as e:
644 skipped[npath] = to_text(e)
645 module.warn("Skipped '%s' path due to this access issue: %s\n" % (to_text(npath), skipped[npath]))
646 has_warnings = True
647
648 if has_warnings:
649 msg = 'Not all paths examined, check warnings for details'
650 matched = len(filelist)
651 module.exit_json(files=filelist, changed=False, msg=msg, matched=matched, examined=looked, skipped_paths=skipped)
652
653
654 if __name__ == '__main__':
655 main()