diff --git a/server/main.py b/server/main.py index 628a144..550db40 100644 --- a/server/main.py +++ b/server/main.py @@ -21,6 +21,35 @@ solar_data = {} from influxdb import InfluxDBClient client = InfluxDBClient('localhost', 8086, database='solar2') +influx_probe = InfluxDBClient('localhost', 8086, timeout=2) +INFLUX_STARTUP_TIMEOUT = 60 +INFLUX_RETRY_INTERVAL = 2 + +async def wait_for_influxdb(): + loop = asyncio.get_running_loop() + deadline = loop.time() + INFLUX_STARTUP_TIMEOUT + last_error = None + + while True: + remaining = deadline - loop.time() + if remaining <= 0: + logging.warning( + 'InfluxDB did not become ready within %s seconds; starting anyway (last error: %s)', + INFLUX_STARTUP_TIMEOUT, last_error) + return + + try: + await asyncio.wait_for( + asyncio.to_thread(influx_probe.ping), timeout=min(2, remaining)) + logging.info('InfluxDB is ready') + return + except Exception as err: + last_error = err + remaining = deadline - loop.time() + if remaining <= 0: + continue + logging.debug('InfluxDB is not ready yet: %s', err) + await asyncio.sleep(min(INFLUX_RETRY_INTERVAL, remaining)) async def proxy(reader, writer): message = await reader.read(1024) @@ -51,6 +80,7 @@ async def get_data(): global solar_data await asyncio.sleep(1) + await wait_for_influxdb() while True: try: