Skip to content

Commit 9130ac7

Browse files
committed
CHANGES:
- More robust handling of clusterdb.pkl on database password changes. BUGFIXES: - Install: did not consider alternate config dirs for database passwords.
1 parent 5f96b9f commit 9130ac7

File tree

3 files changed

+36
-15
lines changed

3 files changed

+36
-15
lines changed

core/data/impl/nodeimpl.py

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ def read_locals(self) -> dict:
265265
if not node:
266266
raise FatalException(f'No configuration found for node {self.name} in {config_file}!')
267267
dirty = False
268+
268269
# check if we need to secure the database URL
269270
database_url = node.get('database', {}).get('url')
270271
if database_url:
@@ -276,6 +277,16 @@ def read_locals(self) -> dict:
276277
f"{url.scheme}://{url.username}:SECRET@{url.hostname}:{port}{url.path}?sslmode=prefer"
277278
dirty = True
278279
self.log.info("Database password found, removing it from config.")
280+
else:
281+
# if we have a cluster.pkl, rename that
282+
cluserdb_pkl = os.path.join(self.config_dir, '.secret', 'clusterdb.pkl')
283+
if os.path.exists(cluserdb_pkl):
284+
database_pkl = os.path.join(self.config_dir, '.secret', 'database.pkl')
285+
# remove existing target to ensure a clean move
286+
if os.path.exists(database_pkl):
287+
os.remove(database_pkl)
288+
os.replace(cluserdb_pkl, database_pkl)
289+
279290
if 'DCS' in node:
280291
password = node['DCS'].pop('dcs_password', node['DCS'].pop('password', None))
281292
if password:
@@ -310,18 +321,28 @@ async def check_db(url: str) -> str | None:
310321

311322
cpool_url = self.config.get("database", self.locals.get('database'))['url']
312323
lpool_url = self.locals.get("database", self.config.get('database'))['url']
324+
313325
try:
314-
password = utils.get_password('clusterdb', self.config_dir)
326+
lpool_pwd = utils.get_password('database', self.config_dir)
315327
except ValueError:
328+
self.log.critical(
329+
"Please replace the SECRET keyword in your database URL with a password!"
330+
)
331+
exit(SHUTDOWN)
332+
333+
if cpool_url != lpool_url:
316334
try:
317-
password = utils.get_password('database', self.config_dir)
318-
utils.set_password('clusterdb', password, self.config_dir)
335+
cpool_pwd = utils.get_password('clusterdb', self.config_dir)
319336
except ValueError:
320-
self.log.critical("You need to replace the SECRET keyword in your database URL with a proper password!")
337+
self.log.critical(
338+
"Please replace the SECRET keyword in your database URL in main.yaml with a password!"
339+
)
321340
exit(SHUTDOWN)
341+
else:
342+
cpool_pwd = lpool_pwd
322343

323-
cpool_url = cpool_url.replace('SECRET', quote(password) or '')
324-
lpool_url = lpool_url.replace('SECRET', quote(utils.get_password('database', self.config_dir)) or '')
344+
cpool_url = cpool_url.replace('SECRET', quote(cpool_pwd) or '')
345+
lpool_url = lpool_url.replace('SECRET', quote(lpool_pwd) or '')
325346

326347
version = await check_db(lpool_url)
327348
if lpool_url != cpool_url:
@@ -1026,6 +1047,7 @@ async def check_nodes():
10261047
return True
10271048
# The master is not alive, take over
10281049
elif not master or not await is_node_alive(master, config.get('heartbeat', 30)):
1050+
self.log.warning("The master node is not responding, taking over ...")
10291051
await take_over()
10301052
return True
10311053
# Master is alive, but we are the preferred one

install.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def get_database_host(host: str = '127.0.0.1', port: int = 5432) -> tuple[str, i
106106
return host, port
107107

108108
@staticmethod
109-
def get_database_url(user: str, database: str) -> str | None:
109+
def get_database_url(user: str, database: str, config_dir: str | None = 'config') -> str | None:
110110
host, port = Install.get_database_host('127.0.0.1', 5432)
111111
while True:
112112
master_db = Prompt.ask(_('Please enter the name of your PostgreSQL master database'), default='postgres')
@@ -117,7 +117,7 @@ def get_database_url(user: str, database: str) -> str | None:
117117
with psycopg.connect(url, autocommit=True) as conn:
118118
with closing(conn.cursor()) as cursor:
119119
try:
120-
passwd = utils.get_password('database') or ''
120+
passwd = utils.get_password('database', config_dir) or ''
121121
except ValueError:
122122
passwd = secrets.token_urlsafe(8)
123123
try:
@@ -137,8 +137,8 @@ def get_database_url(user: str, database: str) -> str | None:
137137
print(_('[yellow]You have entered 3x a wrong password. I have reset it.[/]'))
138138
passwd = secrets.token_urlsafe(8)
139139
cursor.execute(f"ALTER USER {user} WITH ENCRYPTED PASSWORD '{passwd}'")
140-
# store the password
141-
utils.set_password('database', passwd)
140+
# store the (new) password
141+
utils.set_password('database', passwd, config_dir)
142142
with suppress(psycopg.Error):
143143
cursor.execute(f"CREATE DATABASE {database}")
144144
cursor.execute(f"GRANT ALL PRIVILEGES ON DATABASE {database} TO {user}")
@@ -340,7 +340,7 @@ def install(self, config_dir: str, user: str, database: str):
340340

341341
print(_("\n{}. [u]Database Setup[/]").format(i + 1))
342342
if master:
343-
database_url = Install.get_database_url(user, database)
343+
database_url = Install.get_database_url(user, database, config_dir)
344344
if not database_url:
345345
self.log.error(_("Aborted: No valid Database URL provided."))
346346
exit(-2)
@@ -357,7 +357,7 @@ def install(self, config_dir: str, user: str, database: str):
357357
hostname, port = self.get_database_host(url.hostname, url.port)
358358
database_url = f"{url.scheme}://{url.username}:{url.password}@{hostname}:{port}{url.path}?sslmode=prefer"
359359
else:
360-
database_url = Install.get_database_url(user, database)
360+
database_url = Install.get_database_url(user, database, config_dir)
361361
if not database_url:
362362
self.log.error(_("Aborted: No valid Database URL provided."))
363363
exit(-2)

services/bot/dcsserverbot.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import aiohttp
21
import asyncio
32
import discord
43

@@ -257,8 +256,8 @@ async def register_guild_name():
257256
self.log.warning('- Discord connection re-established.')
258257
except FatalException:
259258
raise
260-
except aiohttp.ServerDisconnectedError:
261-
self.log.warning("Discord connection lost.")
259+
except discord.HTTPException as ex:
260+
self.log.warning(f"Discord connection error: {repr(ex)}")
262261
pass
263262
except Exception as ex:
264263
self.log.exception(ex)

0 commit comments

Comments
 (0)