From bb10e95e9502ca139928757524c03e562aa44bbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elias=20H=C3=A4u=C3=9Fler?= Date: Sat, 6 Jul 2024 17:47:20 +0200 Subject: [PATCH] [BUGFIX] Define and handle request timeout --- metrics_exporter.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/metrics_exporter.py b/metrics_exporter.py index 9661862..e3d2dea 100644 --- a/metrics_exporter.py +++ b/metrics_exporter.py @@ -8,6 +8,7 @@ import logging import sys import time +import urllib from urllib.request import urlopen from prometheus_client import start_http_server from prometheus_client.core import GaugeMetricFamily, REGISTRY @@ -17,8 +18,8 @@ class DbTrainMetricsCollector(): Collect and export DB train metrics. """ - STATUS_URL="https://iceportal.de/api1/rs/status" - TRIP_URL="https://iceportal.de/api1/rs/tripInfo/trip" + STATUS_URL = "https://iceportal.de/api1/rs/status" + TRIP_URL = "https://iceportal.de/api1/rs/tripInfo/trip" def __init__(self, logger): self.logger = logger @@ -64,8 +65,11 @@ def collect_speed(self): """ try: - with urlopen(self.STATUS_URL) as res: + with urlopen(self.STATUS_URL, timeout=20) as res: status_response = json.load(res) + except urllib.error.URLError as error: + self.logger.error('Error while fetching JSON from %s: %s', self.STATUS_URL, str(error)) + return None except json.decoder.JSONDecodeError as error: self.logger.error('Error while decoding JSON from %s: %s', self.STATUS_URL, str(error)) return None @@ -78,8 +82,11 @@ def collect_trip(self): """ try: - with urlopen(self.TRIP_URL) as res: + with urlopen(self.TRIP_URL, timeout=20) as res: trip_response = json.load(res) + except urllib.error.URLError as error: + self.logger.error('Error while fetching JSON from %s: %s', self.TRIP_URL, str(error)) + return None, None, None except json.decoder.JSONDecodeError as error: self.logger.error('Error while decoding JSON from %s: %s', self.TRIP_URL, str(error)) return None, None, None