Database private url not working

anubhav1603HOBBY

10 months ago

Mounting volume on: /var/lib/containers/railwayapp/bind-mounts/2ff8f070-ab0c-4ee7-9676-2d3b36a36e0f/vol_8chdamizrj575fwk

Starting Container

[2024-08-12 19:18:19] [INFO    ] discord.client: logging in using static token

2024-08-12 19:18:40.255 | WARNING  | afw_bot.ext.utils.database:connect:15 - 2024-08-12 19:18:40 Failed to connect to the database: Multiple exceptions: [Errno 111] Connect call failed ('::1', 5432, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 5432)

Traceback (most recent call last):

  File "/app/afw_bot/main.py", line 155, in run

    super().run(*args, **kwargs)

  File "/root/.cache/pypoetry/virtualenvs/afw-bot-9TtSrW0h-py3.11/lib/python3.11/site-packages/discord/client.py", line 869, in run

    asyncio.run(runner())

  File "/root/.nix-profile/lib/python3.11/asyncio/runners.py", line 190, in run

    return runner.run(main)

           ^^^^^^^^^^^^^^^^

  File "/root/.nix-profile/lib/python3.11/asyncio/runners.py", line 118, in run

    return self._loop.run_until_complete(task)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/root/.nix-profile/lib/python3.11/asyncio/base_events.py", line 654, in run_until_complete

    return future.result()

           ^^^^^^^^^^^^^^^

  File "/root/.cache/pypoetry/virtualenvs/afw-bot-9TtSrW0h-py3.11/lib/python3.11/site-packages/discord/client.py", line 858, in runner

    await self.start(token, reconnect=reconnect)

  File "/root/.cache/pypoetry/virtualenvs/afw-bot-9TtSrW0h-py3.11/lib/python3.11/site-packages/discord/client.py", line 786, in start

    await self.login(token)

  File "/root/.cache/pypoetry/virtualenvs/afw-bot-9TtSrW0h-py3.11/lib/python3.11/site-packages/discord/client.py", line 629, in login

    await self.setup_hook()

  File "/app/afw_bot/main.py", line 59, in setup_hook

    await self.db.create_tables()

  File "/app/afw_bot/ext/utils/database.py", line 22, in create_tables

    raise RuntimeError("Database pool is not initialized")

RuntimeError: Database pool is not initialized

2024-08-12 19:18:40.284 | CRITICAL | afw_bot.main:run:158 - 2024-08-12 19:18:40 Login Failed

Reason: Database pool is not initialized

Unclosed client session

client_session: 

container event container died

0 Replies

anubhav1603HOBBY

10 months ago

wow


anubhav1603HOBBY

10 months ago

it auto detected


anubhav1603HOBBY

10 months ago

dont know why but its not getting connected


anubhav1603HOBBY

10 months ago

my service is down and i want to make it active again : ( urgently


anubhav1603HOBBY

10 months ago

import asyncpg

from afw_bot.ext.utils.loggers import log_message


class Database:
    def __init__(self, dsn):
        self.dsn = dsn

    async def connect(self):
        try:
            self.pool = await asyncpg.create_pool(dsn=self.dsn)
            log_message(log_level="INFO", message="DATABASE Successfully connected")
        except Exception as e:
            log_message(
                log_level="WARNING", message=f"Failed to connect to the database: {e}"
            )
            self.pool = None  # Ensure pool is set to None on failure

    async def create_tables(self):
        if not self.pool:
            raise RuntimeError("Database pool is not initialized")
        async with self.pool.acquire() as conn:
            await conn.execute(
                """
                CREATE TABLE IF NOT EXISTS audit (
                    thread_id BIGINT PRIMARY KEY,
                    clan_tag TEXT UNIQUE NOT NULL,
                    war_status TEXT NOT NULL,
                    applicant_id BIGINT NOT NULL,
                    war_end_timestamp BIGINT NOT NULL
                );
            """
            )

    async def close(self):
        if self.pool:
            await self.pool.close()

this is how i am connecting to db


anubhav1603HOBBY

10 months ago

i really need to get this service up quickly : (


10 months ago

@Anubhav

Make sure you're giving enough time for the private network to initialize.

Currently, private networks take up to 3 seconds to initialize on deploy.

If you experience errors like those above, consider implementing a sleep or other wait mechanism in your app, before attempting to connect.

https://docs.railway.app/guides/private-networking#initialization-time


anubhav1603HOBBY

10 months ago

i am using poetry run start does it will support sleep?


anubhav1603HOBBY

10 months ago

sleep 3 && poetry run start right?


10 months ago

I'm not familiar with poetry sorry so I'm not sure what the command would be.


anubhav1603HOBBY

10 months ago

: (


10 months ago

In my program I just check to see if the DB connection failed and then try again in 5 seconds. That fixed it for me.


anubhav1603HOBBY

10 months ago

ok i just deployed with sleep 3 hoping to work


anubhav1603HOBBY

10 months ago

i have added asyncio.sleep at my connect method


anubhav1603HOBBY

10 months ago

so it waits


anubhav1603HOBBY

10 months ago

hopefully it works


anubhav1603HOBBY

10 months ago

2024-08-12 20:37:38.877 | WARNING  | afw_bot.ext.utils.database:connect:16 - 2024-08-12 20:37:38 Failed to connect to the database: Multiple exceptions: [Errno 111] Connect call failed ('::1', 5432, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 5432)

i am still getting same warning


anubhav1603HOBBY

10 months ago

not fixed at all


anubhav1603HOBBY

10 months ago

class Database:
    def __init__(self, dsn):
        self.dsn = dsn

    async def connect(self):
        await asyncio.sleep(5)
        try:
            self.pool = await asyncpg.create_pool(dsn=self.dsn)
            log_message(log_level="INFO", message="DATABASE Successfully connected")
        except Exception as e:
            log_message(
                log_level="WARNING", message=f"Failed to connect to the database: {e}"
            )
            self.pool = None  # Ensure pool is set to None on failure

anubhav1603HOBBY

10 months ago

my code


anubhav1603HOBBY

10 months ago

: (


10 months ago

Does this work locally? I'm not seeing in your code where you're getting the env variable (I'm assuming you're using an env variable to pass your DB private URL to your application).


anubhav1603HOBBY

10 months ago

class MyBot(commands.Bot):

    def __init__(self, *, intents: discord.Intents):
        super().__init__(
            command_prefix="supersecretjutsu",
            help_command=None,
            intents=intents,
            tree_cls=CommandErrorHandler,
        )

    async def setup_hook(self):
        coc_client = coc.EventsClient(key_names=DevCreds.DEV_TOKEN_NAME)
        await coc_client.login(
            email=DevCreds.DEV_SITE_EMAIL, password=DevCreds.DEV_SITE_PASSWORD
        )
        self.coc_client: coc.Client = coc_client

        self.db = Database(dsn=Core.DATABSE_URL)
        await self.db.connect()

anubhav1603HOBBY

10 months ago

it does work locally


anubhav1603HOBBY

10 months ago

and works perfectly : (


anubhav1603HOBBY

10 months ago

i am not able to establish connection on railway for some reason


10 months ago

If you print out [DevCreds.DEV](DevCreds.DEV)_SITE_PASSWORD does it print out what you expect?


anubhav1603HOBBY

10 months ago

yep


anubhav1603HOBBY

10 months ago

its another api creds


10 months ago

Also the private url isn't just the password. It's the full connecction string.


anubhav1603HOBBY

10 months ago

i referenced it


10 months ago

Does it work locally if you use the public connection string?


anubhav1603HOBBY

10 months ago

${{Postgres.DATABASE_URL}}


anubhav1603HOBBY

10 months ago

i have not connected to railway db locally , i use local db for bot for testing only for production i use railway db


anubhav1603HOBBY

10 months ago

1272657732406612000


10 months ago

I'd try connecting to your railway db locally. There is a public connection string you can use.


10 months ago

So run your app locally and use the public connection string to connect to that Postgres instance.


anubhav1603HOBBY

10 months ago

ok i will try


anubhav1603HOBBY

10 months ago

2024-08-13 02:18:24 INFO     discord.client logging in using static token
2024-08-13 02:19:04.516 | INFO     | afw_bot.ext.utils.database:connect:12 - 2024-08-13 02:19:04 DATABASE Successfully connected

anubhav1603HOBBY

10 months ago

it connected succsfully


anubhav1603HOBBY

10 months ago

but at railway its different


anubhav1603HOBBY

10 months ago

thats failing there


anubhav1603HOBBY

10 months ago

so locally railway db works but when i try to connect with app it doesnt


anubhav1603HOBBY

10 months ago

@𝐗-𝐥𝐞𝐦
2024-08-12 21:08:18.540 | WARNING | afw_bot.ext.utils.database:connect:14 - 2024-08-12 21:08:18 Failed to connect to the database: Multiple exceptions: [Errno 111] Connect call failed ('::1', 5432, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 5432)

i changed to public url which is not 5432 still it showing this only

port should be 40317


10 months ago

The connection string should have the port already? Where are you seeing the port is wrong? In the DB env variables?


anubhav1603HOBBY

10 months ago

in the error


anubhav1603HOBBY

10 months ago

connection string have 40317 port


10 months ago

Check the DB service env variables. That's probably the port it's using.


anubhav1603HOBBY

10 months ago

postgresql://postgres:pass@monorail.proxy.rlwy.net:40317/railway


anubhav1603HOBBY

10 months ago

you are right but when i copy the public url why it has different port?


anubhav1603HOBBY

10 months ago

and i am able to connect with the 40317 port in my program locally on my pc


10 months ago

I'm assuming one's the internal port and one's the external port.

If your AFW-bot has an env called Core.DATABSE_URL and it's set to ${{Postgres.DATABASE_URL}} then it should work. I'm not sure what else the issue would be :/


anubhav1603HOBBY

10 months ago

this is exactly what i tried but it didnt connected on railway but locally with public url it did connect


anubhav1603HOBBY

10 months ago

@𝐗-𝐥𝐞𝐦 i am very sorry i wasted your time and i seriously apologize for this , being a absolute stupid person i mispelled a letter in my actual code DATBSEURL and tried to connect with DATABASEURL


anubhav1603HOBBY

10 months ago

its connecting now


10 months ago

😛


10 months ago

spelling mistakes kill us all


anubhav1603HOBBY

10 months ago

literally wasted 4h for nothing


10 months ago

Did you not have that spelling mistake locally?


anubhav1603HOBBY

10 months ago

actually suggestion from my IDE


anubhav1603HOBBY

10 months ago

it suggested me wrong as i have created wrong var name at starting


anubhav1603HOBBY

10 months ago

so i didnt noticed


Database private url not working - Railway Help Station