diff options
Diffstat (limited to 'azurelinuxagent/common/utils/fileutil.py')
-rw-r--r-- | azurelinuxagent/common/utils/fileutil.py | 56 |
1 files changed, 51 insertions, 5 deletions
diff --git a/azurelinuxagent/common/utils/fileutil.py b/azurelinuxagent/common/utils/fileutil.py index bae1957..96b5b82 100644 --- a/azurelinuxagent/common/utils/fileutil.py +++ b/azurelinuxagent/common/utils/fileutil.py @@ -21,15 +21,30 @@ File operation util functions """ +import errno as errno import glob import os +import pwd import re import shutil -import pwd +import string + import azurelinuxagent.common.logger as logger -from azurelinuxagent.common.future import ustr import azurelinuxagent.common.utils.textutil as textutil +from azurelinuxagent.common.future import ustr + +KNOWN_IOERRORS = [ + errno.EIO, # I/O error + errno.ENOMEM, # Out of memory + errno.ENFILE, # File table overflow + errno.EMFILE, # Too many open files + errno.ENOSPC, # Out of space + errno.ENAMETOOLONG, # Name too long + errno.ELOOP, # Too many symbolic links encountered + errno.EREMOTEIO # Remote I/O error +] + def copy_file(from_path, to_path=None, to_dir=None): if to_path is None: to_path = os.path.join(to_dir, os.path.basename(from_path)) @@ -160,18 +175,31 @@ def chmod_tree(path, mode): for file_name in files: os.chmod(os.path.join(root, file_name), mode) -def findstr_in_file(file_path, pattern_str): +def findstr_in_file(file_path, line_str): + """ + Return True if the line is in the file; False otherwise. + (Trailing whitespace is ignore.) + """ + try: + for line in (open(file_path, 'r')).readlines(): + if line_str == line.rstrip(): + return True + except Exception as e: + pass + return False + +def findre_in_file(file_path, line_re): """ Return match object if found in file. """ try: - pattern = re.compile(pattern_str) + pattern = re.compile(line_re) for line in (open(file_path, 'r')).readlines(): match = re.search(pattern, line) if match: return match except: - raise + pass return None @@ -184,3 +212,21 @@ def get_all_files(root_path): result.extend([os.path.join(root, file) for file in files]) return result + +def clean_ioerror(e, paths=[]): + """ + Clean-up possibly bad files and directories after an IO error. + The code ignores *all* errors since disk state may be unhealthy. + """ + if isinstance(e, IOError) and e.errno in KNOWN_IOERRORS: + for path in paths: + if path is None: + continue + + try: + if os.path.isdir(path): + shutil.rmtree(path, ignore_errors=True) + else: + os.remove(path) + except Exception as e: + pass |