Remove f-strings for python2 compatibility

This commit is contained in:
James Campbell 2025-01-10 12:39:22 -05:00
parent 8b557d45dd
commit 2c87a41048
Signed by: james
GPG Key ID: 2287C33A40DC906A

View File

@ -150,12 +150,12 @@ def read_config(path, included = False):
included: is this file included by another file? included: is this file included by another file?
""" """
# Read config file # Read config file
log.info(f"Reading log file: {path}") log.info("Reading log file: {}".format(path))
with open(path, 'r') as f: with open(path, 'r') as f:
try: try:
cfg = yaml.safe_load(f) cfg = yaml.safe_load(f)
except yaml.parser.ParserError as e: except yaml.parser.ParserError as e:
raise ConfigError(f"Inavlid config file: {path}: {e}") raise ConfigError("Inavlid config file: {}: {}".format(path, e))
# Since we use it a few places, get the base directory from the config # Since we use it a few places, get the base directory from the config
config_base = os.path.dirname(path) config_base = os.path.dirname(path)
@ -165,24 +165,24 @@ def read_config(path, included = False):
# Validate return types # Validate return types
try: try:
if metric['type'] not in ['value', 'row', 'column', 'set']: if metric['type'] not in ['value', 'row', 'column', 'set']:
raise ConfigError(f"Invalid return type: {metric['type']} for metric {name} in {path}") raise ConfigError("Invalid return type: {} for metric {} in {}".format(metric['type'], name, path))
except KeyError: except KeyError:
raise ConfigError(f"No type specified for metric {name} in {path}") raise ConfigError("No type specified for metric {} in {}".format(name, path))
# Ensure queries exist # Ensure queries exist
query_dict = metric.get('query', {}) query_dict = metric.get('query', {})
if type(query_dict) is not dict: if type(query_dict) is not dict:
raise ConfigError(f"Query definition should be a dictionary, got: {query_dict} for metric {name} in {path}") raise ConfigError("Query definition should be a dictionary, got: {} for metric {} in {}".format(query_dict, name, path))
if len(query_dict) == 0: if len(query_dict) == 0:
raise ConfigError(f"Missing queries for metric {name} in {path}") raise ConfigError("Missing queries for metric {} in {}".format(name, path))
# Read external sql files and validate version keys # Read external sql files and validate version keys
for vers, query in metric['query'].items(): for vers, query in metric['query'].items():
try: try:
int(vers) int(vers)
except: except:
raise ConfigError(f"Invalid version: {vers} for metric {name} in {path}") raise ConfigError("Invalid version: {} for metric {} in {}".format(vers, name, path))
if query.startswith('file:'): if query.startswith('file:'):
query_path = query[5:] query_path = query[5:]
@ -215,7 +215,7 @@ def read_config(path, included = False):
# Validate the new log level before changing the config # Validate the new log level before changing the config
if new_config['log_level'].upper() not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']: if new_config['log_level'].upper() not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
raise ConfigError(f"Invalid log level: {new_config['log_level']}") raise ConfigError("Invalid log level: {}".format(new_config['log_level']))
global config global config
config = new_config config = new_config
@ -270,7 +270,7 @@ class ConnectionPool(ThreadedConnectionPool):
except psycopg2.pool.PoolError: except psycopg2.pool.PoolError:
# If we failed to get the connection slot, wait a bit and try again # If we failed to get the connection slot, wait a bit and try again
time.sleep(0.1) time.sleep(0.1)
raise TimeoutError(f"Timed out waiting for an available connection to {self.name}") raise TimeoutError("Timed out waiting for an available connection to {}".format(self.name))
def get_pool(dbname): def get_pool(dbname):
""" """
@ -287,7 +287,7 @@ def get_pool(dbname):
# Make sure nobody created the pool while we were waiting on the # Make sure nobody created the pool while we were waiting on the
# lock # lock
if dbname not in connections: if dbname not in connections:
log.info(f"Creating connection pool for: {dbname}") log.info("Creating connection pool for: {}".format(dbname))
connections[dbname] = ConnectionPool( connections[dbname] = ConnectionPool(
dbname, dbname,
int(config['min_pool_size']), int(config['min_pool_size']),
@ -321,10 +321,10 @@ def get_query(metric, version):
for v in reversed(sorted(metric['query'].keys())): for v in reversed(sorted(metric['query'].keys())):
if version >= v: if version >= v:
if len(metric['query'][v].strip()) == 0: if len(metric['query'][v].strip()) == 0:
raise MetricVersionError("Metric no longer applies to PostgreSQL {version}") raise MetricVersionError("Metric no longer applies to PostgreSQL {}".format(version))
return metric['query'][v] return metric['query'][v]
raise MetricVersionError('Missing metric query for PostgreSQL {version}') raise MetricVersionError('Missing metric query for PostgreSQL {}'.format(version))
def run_query_no_retry(pool, return_type, query, args): def run_query_no_retry(pool, return_type, query, args):
@ -403,8 +403,8 @@ def get_cluster_version():
pool = get_pool(config['dbname']) pool = get_pool(config['dbname'])
cluster_version = int(run_query(pool, 'value', 'SHOW server_version_num', None)) cluster_version = int(run_query(pool, 'value', 'SHOW server_version_num', None))
cluster_version_next_check = datetime.now() + timedelta(seconds=int(config['version_check_period'])) cluster_version_next_check = datetime.now() + timedelta(seconds=int(config['version_check_period']))
log.info(f"Got PostgreSQL cluster version: {cluster_version}") log.info("Got PostgreSQL cluster version: {}".format(cluster_version))
log.debug(f"Next PostgreSQL cluster version check will be after: {cluster_version_next_check}") log.debug("Next PostgreSQL cluster version check will be after: {}".format(cluster_version_next_check))
return cluster_version return cluster_version
@ -440,7 +440,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
parsed_query = parse_qs(parsed_path.query) parsed_query = parse_qs(parsed_path.query)
if name == 'agent_version': if name == 'agent_version':
self._reply(200, f"{VERSION}") self._reply(200, VERSION)
return return
# Note: parse_qs returns the values as a list. Since we always expect # Note: parse_qs returns the values as a list. Since we always expect
@ -451,7 +451,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
try: try:
metric = config['metrics'][name] metric = config['metrics'][name]
except KeyError: except KeyError:
log.error(f"Unknown metric: {name}") log.error("Unknown metric: {}".format(name))
self._reply(404, 'Unknown metric') self._reply(404, 'Unknown metric')
return return
@ -464,7 +464,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
try: try:
pool = get_pool(dbname) pool = get_pool(dbname)
except UnhappyDBError: except UnhappyDBError:
log.info(f"Database {dbname} is unhappy, please be patient") log.info("Database {} is unhappy, please be patient".format(dbname))
self._reply(503, 'Database unavailable') self._reply(503, 'Database unavailable')
return return
@ -475,10 +475,10 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
return return
except Exception as e: except Exception as e:
if dbname in unhappy_cooldown: if dbname in unhappy_cooldown:
log.info(f"Database {dbname} is unhappy, please be patient") log.info("Database {} is unhappy, please be patient".format(dbname))
self._reply(503, 'Database unavailable') self._reply(503, 'Database unavailable')
else: else:
log.error(f"Failed to get PostgreSQL version: {e}") log.error("Failed to get PostgreSQL version: {}".format(e))
self._reply(500, 'Error getting DB version') self._reply(500, 'Error getting DB version')
return return
@ -486,7 +486,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
try: try:
query = get_query(metric, version) query = get_query(metric, version)
except KeyError: except KeyError:
log.error(f"Failed to find a version of {name} for {version}") log.error("Failed to find a version of {} for {}".format(name, version))
self._reply(404, 'Unsupported version') self._reply(404, 'Unsupported version')
return return
@ -496,10 +496,10 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
return return
except Exception as e: except Exception as e:
if dbname in unhappy_cooldown: if dbname in unhappy_cooldown:
log.info(f"Database {dbname} is unhappy, please be patient") log.info("Database {} is unhappy, please be patient".format(dbname))
self._reply(503, 'Database unavailable') self._reply(503, 'Database unavailable')
else: else:
log.error(f"Error running query: {e}") log.error("Error running query: {}".format(e))
self._reply(500, "Error running query") self._reply(500, "Error running query")
return return
@ -539,7 +539,7 @@ if __name__ == '__main__':
signal.signal(signal.SIGHUP, signal_handler) signal.signal(signal.SIGHUP, signal_handler)
# Handle requests. # Handle requests.
log.info(f"Listening on port {config['port']}...") log.info("Listening on port {}...".format(config['port']))
while running: while running:
httpd.handle_request() httpd.handle_request()