less blocking on fact reading (#73951)
* less blocking on fact reading Co-authored-by: Martin Krizek <martin.krizek@gmail.com>
This commit is contained in:
parent
2bff120db6
commit
232eeee206
2 changed files with 33 additions and 10 deletions
2
changelogs/fragments/less_blocks_on_facts.yml
Normal file
2
changelogs/fragments/less_blocks_on_facts.yml
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
bugfixes:
|
||||||
|
- Try to avoid kernel 'blocking' state on reading files while fact gathering.
|
|
@ -16,26 +16,47 @@
|
||||||
from __future__ import (absolute_import, division, print_function)
|
from __future__ import (absolute_import, division, print_function)
|
||||||
__metaclass__ = type
|
__metaclass__ = type
|
||||||
|
|
||||||
|
import fcntl
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
def get_file_content(path, default=None, strip=True):
|
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
|
data = default
|
||||||
if os.path.exists(path) and os.access(path, os.R_OK):
|
if os.path.exists(path) and os.access(path, os.R_OK):
|
||||||
try:
|
try:
|
||||||
|
datafile = open(path)
|
||||||
try:
|
try:
|
||||||
datafile = open(path)
|
# try to not enter kernel 'block' mode, which prevents timeouts
|
||||||
data = datafile.read()
|
fd = datafile.fileno()
|
||||||
if strip:
|
flag = fcntl.fcntl(fd, fcntl.F_GETFL)
|
||||||
data = data.strip()
|
fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
|
||||||
if len(data) == 0:
|
except Exception:
|
||||||
data = default
|
pass # not required to operate, but would have been nice!
|
||||||
finally:
|
|
||||||
datafile.close()
|
# actually read the data
|
||||||
|
data = datafile.read()
|
||||||
|
|
||||||
|
if strip:
|
||||||
|
data = data.strip()
|
||||||
|
|
||||||
|
if len(data) == 0:
|
||||||
|
data = default
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
# ignore errors as some jails/containers might have readable permissions but not allow reads to proc
|
# ignore errors as some jails/containers might have readable permissions but not allow reads
|
||||||
# done in 2 blocks for 2.4 compat
|
|
||||||
pass
|
pass
|
||||||
|
finally:
|
||||||
|
datafile.close()
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue