Skip to content
Permalink
Browse files

Revert "Python 3: Replacing file() with io open() 2"

This reverts commit 9d75ceb.

Change-Id: Ia08d6dd042265a0aeaf5369835294fb841c93db5
  • Loading branch information...
si-23 committed Sep 4, 2019
1 parent 0d5d3a0 commit 54b52d110071798c09bd4f9fa5255bd4d9329233
@@ -46,7 +46,6 @@ import time
import threading
import traceback
import json
from io import open
from tarfile import TarFile, ReadError
from hashlib import md5

@@ -170,7 +169,7 @@ def acquire_backup_lock():
except (IOError, OSError) as e:
raise MKGeneralException("Failed to open lock file \"%s\": %s" % (lock_file_path, e))
else:
g_backup_lock_f = open(lock_file_path, "a", encoding="utf-8")
g_backup_lock_f = file(lock_file_path, "a")

try:
fcntl.flock(g_backup_lock_f, fcntl.LOCK_EX | fcntl.LOCK_NB)
@@ -261,7 +260,7 @@ def makedir(path, user=None, group=None, mode=None):
# - Site-Konfiguration laden
def load_config():
def load_file(path):
return ast.literal_eval(open(path, encoding="utf-8").read())
return ast.literal_eval(file(path).read())

if is_root():
config = load_file(system_config_path())
@@ -286,7 +285,7 @@ def load_config():

# TODO: Duplicate code with htdocs/backup.py
def load_backup_info(path):
info = json.load(open(path, encoding="utf-8"))
info = json.load(file(path))

# Load the backup_id from the second right path component. This is the
# base directory of the mkbackup.info file. The user might have moved
@@ -303,7 +302,7 @@ def get_site_ids_of_backup(info):


def save_backup_info(info):
with open(backup_info_path(), "w", encoding="utf-8") as f:
with open(backup_info_path(), "w") as f:
json.dump(info, f, sort_keys=True, indent=4, separators=(',', ': '))


@@ -368,7 +367,7 @@ def get_files_for_backup_info():

def file_checksum(path):
hash_md5 = md5()
with open(path, "rb", encoding="utf-8") as f:
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
@@ -630,7 +629,7 @@ def do_site_backup(opts, site=None, try_stop=True):
stderr=subprocess.PIPE,
stdin=open(os.devnull))

with open(backup_path, "w", encoding="utf-8") as backup_file:
with open(backup_path, "w") as backup_file:
s = BackupStream(stream=p.stdout,
is_alive=lambda: p.poll() is None,
key_ident=g_job_config["encrypt"])
@@ -806,7 +805,7 @@ class MKBackupStream(object):

variables = {"keys": {}}
if os.path.exists(path):
exec (open(path, encoding="utf-8").read(), variables, variables)
exec (open(path).read(), variables, variables)
return variables["keys"]


@@ -1151,7 +1150,7 @@ def do_system_backup(opts):


def do_system_rw_backup(opts):
with open(system_backup_archive_path(), "w", encoding="utf-8") as backup_file:
with open(system_backup_archive_path(), "w") as backup_file:
pipein_fd, pipeout_fd = os.pipe()
pipein = os.fdopen(pipein_fd)

@@ -1168,7 +1167,7 @@ def do_system_rw_backup(opts):


def do_system_data_backup(opts):
with open(system_data_backup_archive_path(), "w", encoding="utf-8") as backup_file:
with file(system_data_backup_archive_path(), "w") as backup_file:
pipein_fd, pipeout_fd = os.pipe()
pipein = os.fdopen(pipein_fd)

@@ -1347,7 +1346,7 @@ g_state = None
def load_state():
global g_state
if g_state is None:
g_state = json.load(open(state_path(), encoding="utf-8"))
g_state = json.load(file(state_path()))

return g_state

@@ -1511,7 +1510,7 @@ def do_site_restore(opts, info, site=None):

p = subprocess.Popen(cmd, close_fds=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

with open(backup_path, "r", encoding="utf-8") as backup_file:
with open(backup_path, "r") as backup_file:
s = RestoreStream(stream=backup_file,
is_alive=lambda: False,
key_ident=g_job_config["encrypt"])
@@ -1738,7 +1737,7 @@ def do_system_data_restore(opts, info):


def restore_system_backup(backup_path):
with open(backup_path, "r", encoding="utf-8") as backup_file:
with open(backup_path, "r") as backup_file:
s = RestoreStream(stream=backup_file,
is_alive=lambda: False,
key_ident=g_job_config["encrypt"])
@@ -26,13 +26,12 @@

from __future__ import division
import math
from io import open

import cmk.utils.debug


def our_uptime():
return float((open("/proc/uptime", encoding="utf-8").read().split()[0]))
return float((file("/proc/uptime").read().split()[0]))


# replace simulator tags in output
@@ -29,7 +29,6 @@
import os
import sys
import ast
from io import open
from pathlib2 import Path
import six

@@ -145,9 +144,9 @@ def _read_raw_autochecks_of(self, hostname):
check_config = config.get_check_variables()
try:
cmk_base.console.vverbose("Loading autochecks from %s\n", filepath)
autochecks_raw = eval(open(filepath, encoding="utf-8").read(),
check_config) # type: List[Dict]

autochecks_raw = eval(
file(filepath).read().decode("utf-8"), check_config,
check_config) # type: List[Dict]
except SyntaxError as e:
cmk_base.console.verbose("Syntax error in file %s: %s\n",
filepath,
@@ -213,7 +212,7 @@ def parse_autochecks_file(hostname):
services = [] # type: List[DiscoveredService]

try:
tree = ast.parse(open(path, encoding="utf-8").read())
tree = ast.parse(open(path).read())
except SyntaxError as e:
if cmk.utils.debug.enabled():
raise
@@ -34,7 +34,6 @@
import shutil
import cStringIO
import contextlib
from io import open
from typing import Tuple, Optional, Dict, Any, Text, List # pylint: disable=unused-import

import cmk.utils.paths
@@ -479,8 +478,8 @@ def _omd_rename_host(self, oldname, newname):
# Create a file "renamed_hosts" with the information about the
# renaming of the hosts. The core will honor this file when it
# reads the status file with the saved state.
open(cmk.utils.paths.var_dir + "/core/renamed_hosts", "w",
encoding="utf-8").write("%s\n%s\n" % (oldname, newname))
file(cmk.utils.paths.var_dir + "/core/renamed_hosts",
"w").write("%s\n%s\n" % (oldname, newname))
actions.append("retention")

# NagVis maps
@@ -861,8 +860,8 @@ def flush(self):
cmk_base.core.do_core_action(self._mode())
else:
broken_config_path = "%s/check_mk_objects.cfg.broken" % cmk.utils.paths.tmp_dir
open(broken_config_path, "w", encoding="utf-8").write(
open(cmk.utils.paths.nagios_objects_file, encoding="utf-8").read())
file(broken_config_path,
"w").write(file(cmk.utils.paths.nagios_objects_file).read())

if backup_path:
os.rename(backup_path, objects_file)
@@ -974,8 +973,7 @@ def execute(self, args):
manfile = manuals.get(check_plugin_name)
# TODO: Use cmk.utils.man_pages module standard functions to read the title
if manfile:
title = open(manfile, encoding="utf-8").readline().strip().split(":",
1)[1].strip()
title = file(manfile).readline().strip().split(":", 1)[1].strip()
else:
title = check_plugin_name
check_infos[check_plugin_name] = {"title": title.decode("utf-8")}
@@ -1012,8 +1010,7 @@ def execute(self, args):
try:
manfile = manuals.get(check_plugin_name)
if manfile:
title = open(manfile,
encoding="utf-8").readline().strip().split(":", 1)[1].strip()
title = file(manfile).readline().strip().split(":", 1)[1].strip()
except Exception:
if cmk.utils.debug.enabled():
raise
@@ -1322,8 +1319,7 @@ def execute(self, args):

def _load_resource_file(self, macros):
try:
for line in open(cmk.utils.paths.omd_root + "/etc/nagios/resource.cfg",
encoding="utf-8"):
for line in file(cmk.utils.paths.omd_root + "/etc/nagios/resource.cfg"):
line = line.strip()
if not line or line[0] == '#':
continue
@@ -31,7 +31,6 @@
import shutil
import tarfile
import time
from io import open
import cStringIO as StringIO

import cmk.utils.paths
@@ -73,7 +72,7 @@ def do_backup(tarname):
subdata = subfile.getvalue()
else:
subtarname = canonical_name
subdata = open(absdir, encoding="utf-8").read()
subdata = file(absdir).read()

info = tarfile.TarInfo(subtarname)
info.mtime = time.time()
@@ -31,7 +31,6 @@
import time
import copy
from typing import List, Tuple, Optional # pylint: disable=unused-import
from io import open

import six

@@ -656,7 +655,7 @@ def _close_checkresult_file():
global _checkresult_file_fd
if _checkresult_file_fd is not None:
os.close(_checkresult_file_fd)
open(_checkresult_file_path + ".ok", "w", encoding="utf-8")
file(_checkresult_file_path + ".ok", "w")
_checkresult_file_fd = None


@@ -684,9 +683,7 @@ def _open_command_pipe():
try:
signal.signal(signal.SIGALRM, _core_pipe_open_timeout)
signal.alarm(3) # three seconds to open pipe
_nagios_command_pipe = open(cmk.utils.paths.nagios_command_pipe_path,
'w',
encoding="utf-8")
_nagios_command_pipe = file(cmk.utils.paths.nagios_command_pipe_path, 'w')
signal.alarm(0) # cancel alarm
except Exception as e:
_nagios_command_pipe = False
@@ -29,7 +29,6 @@
# logfiles and then compress them. Do *not* compress compressed
# files again.
import logging
from io import open

from cmk.utils.exceptions import MKBailOut
from cmk.utils.log import VERBOSE
@@ -56,8 +55,8 @@ def compress_history_file(input_path, output_path):
known_services = {}
machine_state = "START"

output = open(output_path, "w", encoding="utf-8")
for line in open(input_path, encoding="utf-8"):
output = file(output_path, "w")
for line in file(input_path):
skip_this_line = False
timestamp = int(line[1:11])
line_type, host, service = parse_history_line(line)
@@ -30,7 +30,6 @@
import subprocess
import sys
import errno
from io import open

import cmk.utils.paths
import cmk.utils.debug
@@ -110,8 +109,7 @@ def do_restart(core, only_reload=False):
console.error("Configuration for monitoring core is invalid. Rolling back.\n")

broken_config_path = "%s/check_mk_objects.cfg.broken" % cmk.utils.paths.tmp_dir
open(broken_config_path, "w", encoding="utf-8").write(
open(cmk.utils.paths.nagios_objects_file, encoding="utf-8").read())
file(broken_config_path, "w").write(file(cmk.utils.paths.nagios_objects_file).read())
console.error("The broken file has been copied to \"%s\" for analysis.\n" %
broken_config_path)

@@ -31,7 +31,6 @@
import py_compile
import tempfile
import errno
from io import open
from typing import Dict # pylint: disable=unused-import

import cmk.utils.paths
@@ -920,7 +919,7 @@ def stripped_python_file(filename):
if filename in g_stripped_file_cache:
return g_stripped_file_cache[filename]
a = ""
for line in open(filename, encoding="utf-8"):
for line in file(filename):
l = line.strip()
if l == "" or l[0] != '#':
a += line # not stripped line because of indentation!
@@ -949,7 +948,7 @@ def _precompile_hostcheck(config_cache, hostname):
console.verbose("(no Check_MK checks)\n")
return

output = open(source_filename + ".new", "w", encoding="utf-8")
output = file(source_filename + ".new", "w")
output.write("#!/usr/bin/env python\n")
output.write("# encoding: utf-8\n\n")

@@ -1078,8 +1077,7 @@ def _precompile_hostcheck(config_cache, hostname):
# code has not changed. The Python compilation is the most costly
# operation here.
if os.path.exists(source_filename):
if open(source_filename, encoding="utf-8").read() == open(source_filename + ".new",
encoding="utf-8").read():
if file(source_filename).read() == file(source_filename + ".new").read():
console.verbose(" (%s is unchanged)\n", source_filename, stream=sys.stderr)
os.remove(source_filename + ".new")
return

0 comments on commit 54b52d1

Please sign in to comment.
You can’t perform that action at this time.