Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

less blocking on fact reading #73951

Merged
merged 5 commits into from Mar 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelogs/fragments/less_blocks_on_facts.yml
@@ -0,0 +1,2 @@
bugfixes:
- Try to avoid kernel 'blocking' state on reading files while fact gathering.
41 changes: 31 additions & 10 deletions lib/ansible/module_utils/facts/utils.py
Expand Up @@ -16,26 +16,47 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import fcntl
import os


def get_file_content(path, default=None, strip=True):
'''
Return the contents of a given file path

:args path: path to file to return contents from
:args default: value to return if we could not read file
:args strip: controls if we strip whitespace from the result or not

:returns: String with file contents (optionally stripped) or 'default' value
'''
data = default
if os.path.exists(path) and os.access(path, os.R_OK):
try:
datafile = open(path)
try:
datafile = open(path)
data = datafile.read()
if strip:
data = data.strip()
if len(data) == 0:
data = default
finally:
datafile.close()
# try to not enter kernel 'block' mode, which prevents timeouts
fd = datafile.fileno()
flag = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
except Exception:
pass # not required to operate, but would have been nice!

# actually read the data
data = datafile.read()

if strip:
data = data.strip()

if len(data) == 0:
data = default

except Exception:
# ignore errors as some jails/containers might have readable permissions but not allow reads to proc
# done in 2 blocks for 2.4 compat
# ignore errors as some jails/containers might have readable permissions but not allow reads
pass
finally:
datafile.close()

return data


Expand Down