-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrend.py
More file actions
128 lines (106 loc) Β· 3.84 KB
/
rend.py
File metadata and controls
128 lines (106 loc) Β· 3.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import logging
import os
import sys
import time
import requests
DEFAULT_PING_INTERVAL = 240
MAX_FAILURES = 2
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger()
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
logger.addHandler(handler)
def get_app_url():
"""
Retrieves the app URL from the environment variable 'APP_URL' or
the first command-line argument. If neither is provided, returns None.
"""
app_url = os.getenv("APP_URL") or (sys.argv[1] if len(sys.argv) > 1 else None)
return app_url
def get_ping_interval():
"""
Returns the ping interval in seconds from the 'PING_INTERVAL' environment variable.
Falls back to DEFAULT_PING_INTERVAL if the environment variable is not set or invalid.
"""
try:
return int(os.getenv("PING_INTERVAL", DEFAULT_PING_INTERVAL))
except ValueError:
logging.warning("Invalid PING_INTERVAL value; using default.")
return DEFAULT_PING_INTERVAL
def get_delay():
"""
Returns the delay in seconds from the 'DELAY' environment variable.
Defaults to 300 seconds if not set or if the value is invalid.
"""
try:
return int(os.getenv("DELAY", 300))
except ValueError:
logging.warning("Invalid DELAY value; using default 300 seconds.")
return 300
def should_delay_ping():
"""
Determines whether to delay before starting to ping based on the 'DELAY_PING'
environment variable. Accepts values like 'True', '1', or 'yes' (case insensitive)
as True.
"""
return os.getenv("DELAY_PING", "False").lower() in ("true", "1", "yes")
def ping_url(session, url):
"""
Attempts to ping the specified URL using the provided session.
Returns True if the HTTP response status code is 200; otherwise, returns False.
"""
try:
response = session.get(url, timeout=10)
if response.status_code == 200:
logging.info(f"Ping successful: {response.status_code} - {url}")
logger.handlers[0].flush()
return True
else:
logging.warning(f"Ping failed with status: {response.status_code} - {url}")
logger.handlers[0].flush()
return False
except requests.RequestException as e:
logging.error(f"Error pinging URL: {e}")
logger.handlers[0].flush()
return False
def main():
app_url = get_app_url()
if not app_url:
logging.error(
"No app URL provided. Set the 'APP_URL' environment variable or pass the URL as a command-line argument."
)
logger.handlers[0].flush()
sys.exit(1)
ping_interval = get_ping_interval()
logging.info(f"Starting to ping {app_url} every {ping_interval / 60} minutes...")
logger.handlers[0].flush()
if should_delay_ping():
delay_seconds = get_delay()
logging.info(
f"Delaying start of pinging by {delay_seconds} seconds as per DELAY_PING setting."
)
logger.handlers[0].flush()
time.sleep(delay_seconds)
failure_count = 0
with requests.Session() as session:
try:
while True:
success = ping_url(session, app_url)
if success:
failure_count = 0
else:
failure_count += 1
if failure_count >= MAX_FAILURES:
logging.error(
f"Maximum failure count reached ({MAX_FAILURES}). Stopping ping function."
)
logger.handlers[0].flush()
break
time.sleep(ping_interval)
except KeyboardInterrupt:
logging.info("Ping process interrupted by user.")
logger.handlers[0].flush()
if __name__ == "__main__":
main()