IDE reformat
This commit is contained in:
parent
b0e599dc68
commit
762ef62098
70
dockstat.py
70
dockstat.py
|
@ -16,8 +16,8 @@ import numpy
|
||||||
from prometheus_client import CollectorRegistry # type: ignore[import]
|
from prometheus_client import CollectorRegistry # type: ignore[import]
|
||||||
from prometheus_client import Gauge, MetricsHandler, generate_latest
|
from prometheus_client import Gauge, MetricsHandler, generate_latest
|
||||||
|
|
||||||
LISTEN_PORT = int(os.environ.get('DOCKSTAT_LISTEN_PORT', 8080))
|
LISTEN_PORT = int(os.environ.get("DOCKSTAT_LISTEN_PORT", 8080))
|
||||||
HEALTHY_STR = 'healthy'
|
HEALTHY_STR = "healthy"
|
||||||
|
|
||||||
|
|
||||||
class HTTPHandler(MetricsHandler): # type: ignore[misc]
|
class HTTPHandler(MetricsHandler): # type: ignore[misc]
|
||||||
|
@ -36,18 +36,18 @@ class HTTPHandler(MetricsHandler): # type: ignore[misc]
|
||||||
"""
|
"""
|
||||||
Handle GET requests
|
Handle GET requests
|
||||||
"""
|
"""
|
||||||
if self.path == '/metrics':
|
if self.path == "/metrics":
|
||||||
try:
|
try:
|
||||||
self._metrics()
|
self._metrics()
|
||||||
except docker.errors.NotFound:
|
except docker.errors.NotFound:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if self.path == '/healthcheck':
|
if self.path == "/healthcheck":
|
||||||
if not healthy():
|
if not healthy():
|
||||||
print('ERROR: Check requirements')
|
print("ERROR: Check requirements")
|
||||||
self._respond(500, 'ERR')
|
self._respond(500, "ERR")
|
||||||
|
|
||||||
self._respond(200, 'OK')
|
self._respond(200, "OK")
|
||||||
|
|
||||||
def _respond(self, status: int, message: str) -> None:
|
def _respond(self, status: int, message: str) -> None:
|
||||||
"""
|
"""
|
||||||
|
@ -71,40 +71,40 @@ class HTTPHandler(MetricsHandler): # type: ignore[misc]
|
||||||
Handle the request for metrics
|
Handle the request for metrics
|
||||||
"""
|
"""
|
||||||
if not healthy:
|
if not healthy:
|
||||||
print('ERROR: Check requirements')
|
print("ERROR: Check requirements")
|
||||||
self._respond(500, 'Server not configured correctly')
|
self._respond(500, "Server not configured correctly")
|
||||||
return
|
return
|
||||||
|
|
||||||
registry = CollectorRegistry()
|
registry = CollectorRegistry()
|
||||||
|
|
||||||
health_gauge = Gauge(
|
health_gauge = Gauge(
|
||||||
'container_inspect_state_health_status',
|
"container_inspect_state_health_status",
|
||||||
"Container's healthcheck value (binary)",
|
"Container's healthcheck value (binary)",
|
||||||
labelnames=['id', 'name', 'value'],
|
labelnames=["id", "name", "value"],
|
||||||
registry=registry,
|
registry=registry,
|
||||||
)
|
)
|
||||||
status_gauge = Gauge(
|
status_gauge = Gauge(
|
||||||
'container_inspect_state_running',
|
"container_inspect_state_running",
|
||||||
"Container's running state (binary)",
|
"Container's running state (binary)",
|
||||||
labelnames=['id', 'name'],
|
labelnames=["id", "name"],
|
||||||
registry=registry,
|
registry=registry,
|
||||||
)
|
)
|
||||||
started_at_gauge = Gauge(
|
started_at_gauge = Gauge(
|
||||||
'container_inspect_state_started_at',
|
"container_inspect_state_started_at",
|
||||||
"Container's start time (int)",
|
"Container's start time (int)",
|
||||||
labelnames=['id', 'name'],
|
labelnames=["id", "name"],
|
||||||
registry=registry,
|
registry=registry,
|
||||||
)
|
)
|
||||||
exit_code_gauge = Gauge(
|
exit_code_gauge = Gauge(
|
||||||
'container_inspect_state_exit_code',
|
"container_inspect_state_exit_code",
|
||||||
"Container's exit code (int)",
|
"Container's exit code (int)",
|
||||||
labelnames=['id', 'name'],
|
labelnames=["id", "name"],
|
||||||
registry=registry,
|
registry=registry,
|
||||||
)
|
)
|
||||||
alert_threshold_gauge = Gauge(
|
alert_threshold_gauge = Gauge(
|
||||||
'container_inspect_downtime_alert_threshold',
|
"container_inspect_downtime_alert_threshold",
|
||||||
"Container's downtime alert threshold in seconds (int)",
|
"Container's downtime alert threshold in seconds (int)",
|
||||||
labelnames=['id', 'name'],
|
labelnames=["id", "name"],
|
||||||
registry=registry,
|
registry=registry,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -112,16 +112,16 @@ class HTTPHandler(MetricsHandler): # type: ignore[misc]
|
||||||
try:
|
try:
|
||||||
data = self.docker_api.inspect_container(container.id)
|
data = self.docker_api.inspect_container(container.id)
|
||||||
except docker.errors.NotFound:
|
except docker.errors.NotFound:
|
||||||
print(f'WARNING: Container {container.id} does not exist. Skipping.')
|
print(f"WARNING: Container {container.id} does not exist. Skipping.")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
running = bool(data['State']['Running'])
|
running = bool(data["State"]["Running"])
|
||||||
started_at = data['State']['StartedAt']
|
started_at = data["State"]["StartedAt"]
|
||||||
exit_code = int(data['State']['ExitCode'])
|
exit_code = int(data["State"]["ExitCode"])
|
||||||
alert_threshold = int(
|
alert_threshold = int(
|
||||||
data['Config']['Labels'].get('io.prometheus.alert.downtime', 3600)
|
data["Config"]["Labels"].get("io.prometheus.alert.downtime", 3600)
|
||||||
)
|
)
|
||||||
starttime: numpy.longlong = numpy.datetime64(started_at, 's').astype('long')
|
starttime: numpy.longlong = numpy.datetime64(started_at, "s").astype("long")
|
||||||
|
|
||||||
status_gauge.labels(
|
status_gauge.labels(
|
||||||
container.id,
|
container.id,
|
||||||
|
@ -141,7 +141,7 @@ class HTTPHandler(MetricsHandler): # type: ignore[misc]
|
||||||
).set(alert_threshold)
|
).set(alert_threshold)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
health_str = data['State']['Health']['Status']
|
health_str = data["State"]["Health"]["Status"]
|
||||||
health_gauge.labels(
|
health_gauge.labels(
|
||||||
container.id,
|
container.id,
|
||||||
container.name,
|
container.name,
|
||||||
|
@ -162,12 +162,12 @@ def healthy() -> bool:
|
||||||
"""
|
"""
|
||||||
return all(
|
return all(
|
||||||
[
|
[
|
||||||
os.path.exists('/var/run/docker.sock'),
|
os.path.exists("/var/run/docker.sock"),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
|
|
||||||
def cli_parse() -> argparse.Namespace:
|
def cli_parse() -> argparse.Namespace:
|
||||||
"""
|
"""
|
||||||
|
@ -179,10 +179,10 @@ if __name__ == '__main__':
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'-H',
|
"-H",
|
||||||
'--healthcheck',
|
"--healthcheck",
|
||||||
action='store_true',
|
action="store_true",
|
||||||
help='Simply exit with 0 for healthy or 1 when unhealthy',
|
help="Simply exit with 0 for healthy or 1 when unhealthy",
|
||||||
)
|
)
|
||||||
|
|
||||||
return parser.parse_args()
|
return parser.parse_args()
|
||||||
|
@ -197,11 +197,11 @@ if __name__ == '__main__':
|
||||||
# Invert the sense of 'healthy' for Unix CLI usage
|
# Invert the sense of 'healthy' for Unix CLI usage
|
||||||
return not healthy()
|
return not healthy()
|
||||||
|
|
||||||
print(f'Starting web server on port {LISTEN_PORT}')
|
print(f"Starting web server on port {LISTEN_PORT}")
|
||||||
try:
|
try:
|
||||||
HTTPServer(('', LISTEN_PORT), HTTPHandler).serve_forever()
|
HTTPServer(("", LISTEN_PORT), HTTPHandler).serve_forever()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print('Exiting')
|
print("Exiting")
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue