Skip to content

Commit 3b10caa

Browse files
authored
Merge pull request #89 from wdpypere/more_clean
clean script_tools and timestamp for old py2isms
2 parents 078207e + 43fcbb5 commit 3b10caa

File tree

2 files changed

+30
-34
lines changed

2 files changed

+30
-34
lines changed

lib/vsc/utils/script_tools.py

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -45,15 +45,13 @@
4545
SimpleNagios, NAGIOS_CACHE_DIR, NAGIOS_CACHE_FILENAME_TEMPLATE, exit_from_errorcode,
4646
NAGIOS_EXIT_OK, NAGIOS_EXIT_WARNING, NAGIOS_EXIT_CRITICAL, NAGIOS_EXIT_UNKNOWN,
4747
)
48-
from vsc.utils.timestamp import (
49-
convert_timestamp, write_timestamp, retrieve_timestamp_with_default
50-
)
48+
from vsc.utils.timestamp import convert_timestamp, write_timestamp, retrieve_timestamp_with_default
5149
from vsc.utils.timestamp_pid_lockfile import TimestampedPidLockfile
5250

5351
DEFAULT_TIMESTAMP = "20140101000000Z"
54-
TIMESTAMP_FILE_OPTION = 'timestamp_file'
52+
TIMESTAMP_FILE_OPTION = "timestamp_file"
5553
DEFAULT_CLI_OPTIONS = {
56-
'start_timestamp': ("The timestamp form which to start, otherwise use the cached value", None, "store", None),
54+
"start_timestamp": ("The timestamp form which to start, otherwise use the cached value", None, "store", None),
5755
TIMESTAMP_FILE_OPTION: ("Location to cache the start timestamp", None, "store", None),
5856
}
5957
MAX_DELTA = 3
@@ -125,7 +123,7 @@ def __init__(self, options, run_prologue=True, excepthook=None, **kwargs):
125123
"""
126124

127125
options_ = _merge_options(options)
128-
super(ExtendedSimpleOption, self).__init__(options_, **kwargs)
126+
super().__init__(options_, **kwargs)
129127

130128
self.nagios_reporter = None
131129
self.lockfile = None
@@ -151,12 +149,13 @@ def prologue(self):
151149
"""
152150

153151
# bail if nagios report is requested
154-
self.nagios_reporter = SimpleNagios(_cache=self.options.nagios_check_filename,
155-
_report_and_exit=self.options.nagios_report,
156-
_threshold=self.options.nagios_check_interval_threshold,
157-
_cache_user=self.options.nagios_user,
158-
_world_readable=self.options.nagios_world_readable_check,
159-
)
152+
self.nagios_reporter = SimpleNagios(
153+
_cache=self.options.nagios_check_filename,
154+
_report_and_exit=self.options.nagios_report,
155+
_threshold=self.options.nagios_check_interval_threshold,
156+
_cache_user=self.options.nagios_user,
157+
_world_readable=self.options.nagios_world_readable_check,
158+
)
160159

161160
# check for HA host
162161
if self.options.ha and not proceed_on_ha_service(self.options.ha):
@@ -165,8 +164,9 @@ def prologue(self):
165164
sys.exit(NAGIOS_EXIT_OK)
166165

167166
if not self.options.disable_locking and not self.options.dry_run:
168-
self.lockfile = TimestampedPidLockfile(self.options.locking_filename,
169-
threshold=self.options.nagios_check_interval_threshold * 2)
167+
self.lockfile = TimestampedPidLockfile(
168+
self.options.locking_filename, threshold=self.options.nagios_check_interval_threshold * 2
169+
)
170170
lock_or_bork(self.lockfile, self.nagios_reporter)
171171

172172
self.log.info("%s has started", _script_name(sys.argv[0]))
@@ -182,7 +182,7 @@ def epilogue(self, nagios_message, nagios_thresholds=None):
182182

183183
self._epilogue()
184184

185-
nagios_thresholds['message'] = nagios_message
185+
nagios_thresholds["message"] = nagios_message
186186
self.nagios_reporter._eval_and_exit(**nagios_thresholds)
187187
self.log.info("%s has finished", _script_name(sys.argv[0])) # may not be reached
188188

@@ -223,14 +223,15 @@ def critical_exception_handler(self, tp, value, traceback):
223223
"""
224224
self.log.exception("unhandled exception detected: %s - %s", tp, value)
225225
self.log.debug("traceback %s", traceback)
226-
message = "Script failure: %s - %s" % (tp, value)
226+
message = f"Script failure: {tp} - {value}"
227227
self.critical(message)
228228

229229

230-
class CLI(object):
230+
class CLI:
231231
"""
232232
Base class to implement cli tools that require timestamps, nagios checks, etc.
233233
"""
234+
234235
TIMESTAMP_MANDATORY = True
235236

236237
CLI_OPTIONS = {}
@@ -255,7 +256,6 @@ def __init__(self, name=None, default_options=None):
255256
self.start_timestamp = None
256257
self.current_time = None
257258

258-
259259
def make_options(self, defaults=None):
260260
"""
261261
Take the default sync options, set the default timestamp file and merge
@@ -271,13 +271,13 @@ def make_options(self, defaults=None):
271271
# insert default timestamp value file based on name
272272
if TIMESTAMP_FILE_OPTION in options:
273273
tsopt = list(options[TIMESTAMP_FILE_OPTION])
274-
tsopt[-1] = os.path.join(self.CACHE_DIR, "%s.timestamp" % self.name)
274+
tsopt[-1] = os.path.join(self.CACHE_DIR, f"{self.name}.timestamp")
275275
options[TIMESTAMP_FILE_OPTION] = tuple(tsopt)
276276

277277
options.update(self.CLI_OPTIONS)
278278

279279
if TIMESTAMP_FILE_OPTION not in options and self.TIMESTAMP_MANDATORY:
280-
raise Exception("no mandatory %s option defined" % (TIMESTAMP_FILE_OPTION,))
280+
raise ValueError(f"no mandatory {TIMESTAMP_FILE_OPTION} option defined")
281281

282282
return ExtendedSimpleOption(options)
283283

@@ -320,7 +320,7 @@ def critical_exception(self, msg, exception):
320320
logging.exception("%s: %s", msg, exception)
321321
exit_from_errorcode(2, msg)
322322

323-
def do(self, dry_run): #pylint: disable=unused-argument
323+
def do(self, dry_run): # pylint: disable=unused-argument
324324
"""
325325
Method to add actual work to do.
326326
The method is executed in main method in a generic try/except/finally block
@@ -332,7 +332,7 @@ def do(self, dry_run): #pylint: disable=unused-argument
332332
self.thresholds can be used to pass the thresholds during epilogue
333333
"""
334334
logging.error("`do` method not implemented")
335-
raise Exception("Not implemented")
335+
raise NotImplementedError("Not implemented")
336336
return "Not implemented"
337337

338338
def make_time(self):
@@ -375,14 +375,13 @@ def post(self, errors, current_time=None):
375375
_, timestamp = convert_timestamp(current_time)
376376
write_timestamp(self.options.timestamp_file, timestamp)
377377
except Exception as err:
378-
txt = "Writing timestamp %s to %s failed: %s" % (timestamp, self.options.timestamp_file, err)
378+
txt = f"Writing timestamp {timestamp} to {self.options.timestamp_file} failed: {err}"
379379
self.critical_exception(txt, err)
380380

381381
def final(self):
382382
"""
383383
Run as finally block in main
384384
"""
385-
pass
386385

387386
def main(self):
388387
"""
@@ -406,14 +405,12 @@ def main(self):
406405

407406
self.post(errors)
408407

409-
self.fulloptions.epilogue("%s complete" % msg, self.thresholds)
410-
408+
self.fulloptions.epilogue(f"{msg} complete", self.thresholds)
411409

412410

413411
class NrpeCLI(CLI):
414-
415412
def __init__(self, name=None, default_options=None):
416-
super(NrpeCLI, self).__init__(name=name, default_options=default_options)
413+
super().__init__(name=name, default_options=default_options)
417414

418415
def ok(self, msg):
419416
"""

lib/vsc/utils/timestamp.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: latin-1 -*-
21
#
32
# Copyright 2009-2023 Ghent University
43
#
@@ -61,7 +60,7 @@ def convert_to_datetime(timestamp=None):
6160
return datetime.datetime.utcnow().replace(tzinfo=utc)
6261

6362
if isinstance(timestamp, int):
64-
timestamp = "%010d" % timestamp
63+
timestamp = f"{int(timestamp):010}"
6564
if isinstance(timestamp, datetime.datetime):
6665
if timestamp.tzinfo is None:
6766
timestamp = timestamp.replace(tzinfo=utc)
@@ -77,7 +76,7 @@ def convert_to_datetime(timestamp=None):
7776
elif len(timestamp) == 8:
7877
date_format = "%Y%m%d"
7978
else:
80-
raise Exception("invalid format provided %s" % timestamp)
79+
raise ValueError(f"invalid format provided {timestamp}")
8180
timestamp = datetime.datetime.strptime(timestamp, date_format)
8281

8382
return timestamp.replace(tzinfo=utc)
@@ -113,9 +112,9 @@ def read_timestamp(filename):
113112
"""
114113
cache = FileCache(filename)
115114
try:
116-
(_, timestamp) = cache.load('timestamp')
115+
(_, timestamp) = cache.load("timestamp")
117116
except TypeError:
118-
logging.warning('could not load timestamp from cache file %s', filename)
117+
logging.warning("could not load timestamp from cache file %s", filename)
119118
timestamp = None
120119

121120
return timestamp
@@ -135,7 +134,7 @@ def write_timestamp(filename, timestamp):
135134
timestamp_ = timestamp
136135

137136
cache = FileCache(filename)
138-
cache.update('timestamp', timestamp_, 0)
137+
cache.update("timestamp", timestamp_, 0)
139138
cache.close()
140139

141140

0 commit comments

Comments
 (0)