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?
"""
# Read config file
log.info(f"Reading log file: {path}")
log.info("Reading log file: {}".format(path))
with open(path, 'r') as f:
try:
cfg = yaml.safe_load(f)
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
config_base = os.path.dirname(path)
@ -165,24 +165,24 @@ def read_config(path, included = False):
# Validate return types
try:
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:
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
query_dict = metric.get('query', {})
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:
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
for vers, query in metric['query'].items():
try:
int(vers)
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:'):
query_path = query[5:]
@ -215,7 +215,7 @@ def read_config(path, included = False):
# Validate the new log level before changing the config
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
config = new_config
@ -270,7 +270,7 @@ class ConnectionPool(ThreadedConnectionPool):
except psycopg2.pool.PoolError:
# If we failed to get the connection slot, wait a bit and try again
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):
"""
@ -287,7 +287,7 @@ def get_pool(dbname):
# Make sure nobody created the pool while we were waiting on the
# lock
if dbname not in connections:
log.info(f"Creating connection pool for: {dbname}")
log.info("Creating connection pool for: {}".format(dbname))
connections[dbname] = ConnectionPool(
dbname,
int(config['min_pool_size']),
@ -321,10 +321,10 @@ def get_query(metric, version):
for v in reversed(sorted(metric['query'].keys())):
if version >= v:
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]
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):
@ -403,8 +403,8 @@ def get_cluster_version():
pool = get_pool(config['dbname'])
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']))
log.info(f"Got PostgreSQL cluster version: {cluster_version}")
log.debug(f"Next PostgreSQL cluster version check will be after: {cluster_version_next_check}")
log.info("Got PostgreSQL cluster version: {}".format(cluster_version))
log.debug("Next PostgreSQL cluster version check will be after: {}".format(cluster_version_next_check))
return cluster_version
@ -440,7 +440,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
parsed_query = parse_qs(parsed_path.query)
if name == 'agent_version':
self._reply(200, f"{VERSION}")
self._reply(200, VERSION)
return
# Note: parse_qs returns the values as a list. Since we always expect
@ -451,7 +451,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
try:
metric = config['metrics'][name]
except KeyError:
log.error(f"Unknown metric: {name}")
log.error("Unknown metric: {}".format(name))
self._reply(404, 'Unknown metric')
return
@ -464,7 +464,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
try:
pool = get_pool(dbname)
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')
return
@ -475,10 +475,10 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
return
except Exception as e:
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')
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')
return
@ -486,7 +486,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
try:
query = get_query(metric, version)
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')
return
@ -496,10 +496,10 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
return
except Exception as e:
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')
else:
log.error(f"Error running query: {e}")
log.error("Error running query: {}".format(e))
self._reply(500, "Error running query")
return
@ -539,7 +539,7 @@ if __name__ == '__main__':
signal.signal(signal.SIGHUP, signal_handler)
# Handle requests.
log.info(f"Listening on port {config['port']}...")
log.info("Listening on port {}...".format(config['port']))
while running:
httpd.handle_request()