Skip to content

Commit 930ce2e

Browse files
authored
Merge pull request #91 from wdpypere/more_cleanup
more fstring and pylint cleanup
2 parents b190748 + 75fc74d commit 930ce2e

File tree

15 files changed

+64
-74
lines changed

15 files changed

+64
-74
lines changed

lib/vsc/utils/cache.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,15 @@
2929
@author: Andy Georges (Ghent University)
3030
"""
3131
import gzip
32-
import jsonpickle
3332
import os
3433
import time
3534
import pickle
35+
import jsonpickle
36+
3637

3738
from vsc.utils import fancylogger
3839

39-
class FileCache(object):
40+
class FileCache:
4041
"""File cache with a timestamp safety.
4142
4243
Stores data (something that can be pickled) into a dictionary
@@ -81,19 +82,19 @@ def __init__(self, filename, retain_old=True, raise_unpickable=False):
8182
try:
8283
g = gzip.GzipFile(mode='rb', fileobj=f) # no context manager available in python 26 yet
8384
s = g.read()
84-
except (IOError) as err:
85+
except (OSError) as _:
8586
self.log.error("Cannot load data from cache file %s as gzipped json", self.filename)
8687
try:
8788
f.seek(0)
8889
self.shelf = pickle.load(f)
8990
except pickle.UnpicklingError as err:
90-
msg = "Problem loading pickle data from %s (corrupt data)" % (self.filename,)
91+
msg = f"Problem loading pickle data from {self.filename} (corrupt data)"
9192
if raise_unpickable:
9293
self.log.raiseException(msg)
9394
else:
9495
self.log.error("%s. Continue with empty shelf: %s", msg, err)
9596
self.shelf = {}
96-
except (OSError, IOError):
97+
except OSError:
9798
self.log.raiseException("Could not load pickle data from %s", self.filename)
9899
else:
99100
try:
@@ -105,7 +106,7 @@ def __init__(self, filename, retain_old=True, raise_unpickable=False):
105106
finally:
106107
g.close()
107108

108-
except (OSError, IOError, ValueError, FileNotFoundError) as err:
109+
except (OSError, ValueError, FileNotFoundError) as err:
109110
self.log.warning("Could not access the file cache at %s [%s]", self.filename, err)
110111
self.shelf = {}
111112
self.log.info("Cache in %s starts with an empty shelf", (self.filename,))

lib/vsc/utils/fs_store.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,3 @@ def store_on_gpfs(user_name, path, key, information, gpfs, login_mount_point, gp
9696
gpfs.ignorerealpathmismatch = False
9797

9898
logger.info("Stored user %s %s information at %s", user_name, key, filename)
99-
100-
101-
102-

lib/vsc/utils/lock.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,11 @@ def lock_or_bork(lockfile, simple_nagios):
5555
lockfile.acquire()
5656
except LockFailed:
5757
logger.critical('Unable to obtain lock: lock failed')
58-
simple_nagios.critical("failed to take lock on %s" % (lockfile.path))
58+
simple_nagios.critical(f"failed to take lock on {lockfile.path}")
5959
sys.exit(NAGIOS_EXIT_CRITICAL)
6060
except LockError:
6161
logger.critical("Unable to obtain lock: could not read previous lock file %s", lockfile.path)
62-
simple_nagios.critical("failed to read lockfile %s" % (lockfile.path))
62+
simple_nagios.critical(f"failed to read lockfile {lockfile.path}")
6363
sys.exit(NAGIOS_EXIT_CRITICAL)
6464

6565

@@ -79,9 +79,9 @@ def release_or_bork(lockfile, simple_nagios):
7979
lockfile.release()
8080
except NotLocked:
8181
logger.critical('Lock release failed: was not locked.')
82-
simple_nagios.critical("Lock release failed on %s" % (lockfile.path,))
82+
simple_nagios.critical(f"Lock release failed on {lockfile.path}")
8383
sys.exit(NAGIOS_EXIT_CRITICAL)
8484
except NotMyLock:
8585
logger.error('Lock release failed: not my lock')
86-
simple_nagios.critical("Lock release failed on %s" % (lockfile.path,))
86+
simple_nagios.critical(f"Lock release failed on {lockfile.path}")
8787
sys.exit(NAGIOS_EXIT_CRITICAL)

lib/vsc/utils/nagios.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
2-
# -*- encoding: utf-8 -*-
31
#
42
# Copyright 2012-2023 Ghent University
53
#
@@ -143,7 +141,7 @@ def exit_from_errorcode(errorcode, msg, error_map=None):
143141
unknown_exit(f"{msg} (errorcode {errorcode} not found in {e_map}")
144142

145143

146-
class NagiosRange(object):
144+
class NagiosRange:
147145
"""Implement Nagios ranges"""
148146
DEFAULT_START = 0
149147
def __init__(self, nrange):
@@ -244,7 +242,7 @@ def alert(self, test):
244242
return not self.range_fn(test)
245243

246244

247-
class NagiosReporter(object):
245+
class NagiosReporter:
248246
"""Reporting class for Nagios/Icinga reports.
249247
250248
Can cache the result in a gzipped JSON file and print the result out at some later point.
@@ -282,7 +280,7 @@ def report_and_exit(self):
282280
"""
283281
try:
284282
nagios_cache = FileCache(self.filename, True)
285-
except (IOError, OSError):
283+
except OSError:
286284
self.log.critical("Error opening file %s for reading", self.filename)
287285
unknown_exit(f"{self.header} nagios gzipped JSON file unavailable ({self.filename})")
288286

@@ -309,7 +307,7 @@ def cache(self, nagios_exit, nagios_message):
309307
nagios_cache.update('nagios', (nagios_exit, nagios_message), 0) # always update
310308
nagios_cache.close()
311309
self.log.info("Wrote nagios check cache file %s at about %s", self.filename, time.ctime(time.time()))
312-
except (IOError, OSError) as exc:
310+
except OSError as exc:
313311
# raising an error is ok, since we usually do this as the very last thing in the script
314312
msg = f"Cannot save to the nagios gzipped JSON file ({self.filename})"
315313
self.log.exception(msg)
@@ -336,7 +334,7 @@ def cache(self, nagios_exit, nagios_message):
336334
return True
337335

338336

339-
class NagiosResult(object):
337+
class NagiosResult:
340338
"""Class representing the results of an Icinga/Nagios check.
341339
342340
It will contain a field with the message to be printed. And the
@@ -370,7 +368,7 @@ class NagiosResult(object):
370368
Nagios checks, please refer to
371369
U{http://docs.icinga.org/latest/en/perfdata.html}
372370
"""
373-
RESERVED_WORDS = set(['message'])
371+
RESERVED_WORDS = {'message'}
374372
NAME_REG = re.compile(r'^(?P<name>.*?)(?:_(?P<option>warning|critical))?$')
375373

376374
def __init__(self, message, **kwargs):
@@ -442,8 +440,8 @@ class SimpleNagios(NagiosResult):
442440
"""
443441

444442
USE_HEADER = True
445-
RESERVED_WORDS = set(['message', 'ok', 'warning', 'critical', 'unknown',
446-
'_exit', '_cache', '_cache_user', '_final', '_final_state', '_report', '_threshold'])
443+
RESERVED_WORDS = {'message', 'ok', 'warning', 'critical', 'unknown',
444+
'_exit', '_cache', '_cache_user', '_final', '_final_state', '_report', '_threshold'}
447445

448446
def __init__(self, **kwargs):
449447
"""Initialise message and perfdata"""

lib/vsc/utils/pickle_files.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
import stat
4141
import pickle
4242

43-
class TimestampPickle(object):
43+
class TimestampPickle:
4444
"""Stores a timestamp in some format in a file."""
4545

4646
def __init__(self, filename):
@@ -59,7 +59,7 @@ def read(self):
5959
try:
6060
with open (self.filename, "rb") as fih:
6161
timestamp = pickle.load(fih)
62-
except (IOError, OSError, FileNotFoundError):
62+
except (OSError, FileNotFoundError):
6363
logging.exception("Failed to load timestamp pickle from filename %s.", self.filename)
6464
return None
6565

lib/vsc/utils/rest_oauth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def make_api_request(opener, path, method='GET', payload="", access_token=""):
5353
"""
5454
request = Request(path, payload)
5555
request.add_header('Content-Type', 'application/json')
56-
request.add_header('Authorization', "Bearer %s" % (access_token,))
56+
request.add_header('Authorization', f"Bearer {access_token}")
5757
request.get_method = lambda: method
5858
uri = opener.open(request)
5959
response = uri.read()

lib/vsc/utils/script_tools.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ def do(self, dry_run): # pylint: disable=unused-argument
333333
"""
334334
logging.error("`do` method not implemented")
335335
raise NotImplementedError("Not implemented")
336-
return "Not implemented"
336+
return "Not Implemented"
337337

338338
def make_time(self):
339339
"""

lib/vsc/utils/timestamp_pid_lockfile.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ class LockFileReadError(Exception):
4444
pass
4545

4646

47-
class TimestampedPidLockfile(LockBase, object):
47+
class TimestampedPidLockfile(LockBase):
4848
'''Basic lock file implementation.
4949
'''
5050

@@ -124,20 +124,20 @@ def _read_pid_timestamp_file(path):
124124
Returns (pid :: Int, timestamp :: Int).
125125
'''
126126
try:
127-
with open(path, 'r') as pidfp:
128-
pidLine = pidfp.readline().strip()
129-
timestampLine = pidfp.readline().strip()
130-
pid = int(pidLine)
131-
timestamp = int(timestampLine)
127+
with open(path, encoding='utf8') as pidfp:
128+
pidline = pidfp.readline().strip()
129+
timestampline = pidfp.readline().strip()
130+
pid = int(pidline)
131+
timestamp = int(timestampline)
132132
return (pid, timestamp)
133133

134-
except IOError as err:
134+
except OSError as err:
135135
if err.errno == errno.ENOENT:
136136
return None
137137
else:
138138
raise LockFileReadError('Cannot get the information from the pid file.')
139139
except ValueError:
140-
raise LockFileReadError("Contents of pid file %s invalid" % (path))
140+
raise LockFileReadError(f"Contents of pid file {path} invalid")
141141

142142

143143
def _write_pid_timestamp_file(path):
@@ -147,7 +147,7 @@ def _write_pid_timestamp_file(path):
147147
'''
148148
pidfp = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
149149
pidfile = os.fdopen(pidfp, 'w')
150-
pidfile.write("%s\n%d\n" % (os.getpid(), int(time.time())))
150+
pidfile.write(f"{os.getpid()}\n{int(int(time.time()))}\n")
151151
pidfile.flush()
152152
pidfile.close()
153153

@@ -156,8 +156,8 @@ def _find_and_kill(pid):
156156
'''See if the process corresponding to the given PID is still running. If so,
157157
kill it (gently).
158158
'''
159-
for psLine in os.popen('ps ax'):
160-
fields = psLine.split()
159+
for psline in os.popen('ps ax'):
160+
fields = psline.split()
161161
if fields[0] == pid:
162162
os.kill(pid, signal.SIGHUP)
163163
return True

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
]
4242

4343
PACKAGE = {
44-
'version': '2.2.3',
44+
'version': '2.2.5',
4545
'author': [ag, sdw],
4646
'maintainer': [ag, sdw],
4747
'excluded_pkgs_rpm': ['vsc', 'vsc.utils'], # vsc is default, vsc.utils is provided by vsc-base

test/cache.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@
3030
"""
3131

3232
import gzip
33-
import mock
3433
import os
3534
import tempfile
3635
import time
3736
import shutil
3837
import sys
3938
import random
39+
import mock
4040

4141
from vsc.install.testing import TestCase
4242
from vsc.utils.cache import FileCache
@@ -48,7 +48,7 @@ def get_rand_data():
4848
"""Returns a random dict with between 0 and LIST_LEN elements and a random threshold"""
4949
length = random.randint(0, LIST_LEN)
5050
data = {}
51-
for x in range(length):
51+
for _ in range(length):
5252
data[random.randint(0, sys.maxsize)] = random.randint(0, sys.maxsize)
5353
threshold = random.randint(0, sys.maxsize)
5454
return data, threshold
@@ -69,11 +69,11 @@ def test_contents(self):
6969
cache.update(key, value, threshold)
7070

7171
now = time.time()
72-
for key in data.keys():
72+
for key, content in data.items():
7373
info = cache.load(key)
7474
self.assertFalse(info is None)
7575
(ts, value) = info
76-
self.assertTrue(value == data[key])
76+
self.assertTrue(value == content)
7777
self.assertTrue(ts <= now)
7878

7979
def test_save_and_load(self):
@@ -92,11 +92,11 @@ def test_save_and_load(self):
9292

9393
now = time.time()
9494
new_cache = FileCache(filename)
95-
for key in data.keys():
95+
for key, content in data.items():
9696
info = cache.load(key)
9797
self.assertTrue(info is not None)
9898
(ts, value) = info
99-
self.assertTrue(value == data[key])
99+
self.assertTrue(value == content)
100100
self.assertTrue(ts <= now)
101101
new_cache.close()
102102

0 commit comments

Comments
 (0)