devendergarg14 commited on
Commit
b7df051
·
verified ·
1 Parent(s): 4310b84

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -68
app.py CHANGED
@@ -11,55 +11,45 @@ import socket
11
  app = Flask(__name__, static_folder='.', static_url_path='')
12
 
13
  # --- Configuration ---
14
- DATA_DIR = "/data" # Writable directory on Hugging Face Spaces
15
- if not os.path.exists(DATA_DIR) and not os.environ.get('SPACE_ID'): # For local dev if /data isn't preset
16
- print(f"Warning: {DATA_DIR} not found. Using current directory for data.json (local dev mode).")
17
- DATA_DIR = "." # Fallback to current dir for local testing if /data does not exist
18
-
19
- DATA_FILE = os.path.join(DATA_DIR, "data.json")
20
- PING_INTERVAL_SECONDS = 60
21
- HISTORY_DURATION_SECONDS = 60 * 60
22
-
23
- monitored_urls_store = {}
24
- lock = threading.Lock()
25
 
26
  # --- Helper Functions ---
27
- def ensure_data_dir_exists():
28
- """Ensures the data directory exists."""
29
- if DATA_DIR == ".": # No need to create current directory
30
- return
31
- if not os.path.exists(DATA_DIR):
32
- try:
33
- os.makedirs(DATA_DIR)
34
- print(f"Created data directory: {DATA_DIR}")
35
- except OSError as e:
36
- print(f"Error creating data directory {DATA_DIR}: {e}. Data persistence may fail.")
37
-
38
  def save_data_to_json():
39
- with lock:
40
- ensure_data_dir_exists() # Ensure directory exists before attempting to write
41
- serializable_data = {}
42
- for url_id, data in monitored_urls_store.items():
43
- s_data = data.copy()
44
- s_data.pop("_thread", None)
45
- s_data.pop("_stop_event", None)
46
- serializable_data[url_id] = s_data
47
- try:
48
- with open(DATA_FILE, 'w') as f:
49
- json.dump(serializable_data, f, indent=2)
50
- except IOError as e:
51
- print(f"Error saving data to {DATA_FILE}: {e}") # This is where your error was logged
52
 
53
  def load_data_from_json():
54
  global monitored_urls_store
55
- ensure_data_dir_exists() # Ensure directory exists before attempting to read
56
  if os.path.exists(DATA_FILE):
57
  try:
58
  with open(DATA_FILE, 'r') as f:
59
  loaded_json_data = json.load(f)
 
60
 
61
  temp_store = {}
62
  for url_id_key, data_item in loaded_json_data.items():
 
63
  data_item.setdefault('id', url_id_key)
64
  current_id = data_item['id']
65
  data_item.setdefault('status', 'pending')
@@ -69,7 +59,7 @@ def load_data_from_json():
69
  data_item.setdefault('history', data_item.get('history', []))
70
  temp_store[current_id] = data_item
71
 
72
- with lock:
73
  monitored_urls_store = temp_store
74
 
75
  except json.JSONDecodeError:
@@ -91,9 +81,11 @@ def load_data_from_json():
91
 
92
  def get_host_ip_address(hostname_str):
93
  try:
94
- socket.inet_aton(hostname_str)
 
95
  return hostname_str
96
  except OSError:
 
97
  try:
98
  ip_address = socket.gethostbyname(hostname_str)
99
  return ip_address
@@ -105,6 +97,7 @@ def get_host_ip_address(hostname_str):
105
  return 'N/A'
106
 
107
  def prune_url_history(url_data_entry):
 
108
  cutoff_time = time.time() - HISTORY_DURATION_SECONDS
109
  url_data_entry['history'] = [
110
  entry for entry in url_data_entry.get('history', []) if entry['timestamp'] >= cutoff_time
@@ -120,19 +113,21 @@ def execute_url_check(url_id_to_check):
120
 
121
  print(f"Checking {current_url_data['url']} (ID: {url_id_to_check})...")
122
  current_url_data['status'] = 'checking'
123
- url_config_snapshot = current_url_data.copy()
124
 
125
  if not url_config_snapshot: return
126
 
127
  check_start_time = time.perf_counter()
128
  final_check_status = 'error'
129
  http_response_time_ms = None
 
130
  http_headers = {'User-Agent': 'URLPinger/1.0 (HuggingFace Space Bot)'}
131
 
132
  try:
 
133
  try:
134
  head_response = requests.head(url_config_snapshot['url'], timeout=10, allow_redirects=True, headers=http_headers)
135
- if 200 <= head_response.status_code < 400:
136
  final_check_status = 'ok'
137
  else:
138
  print(f"HEAD for {url_config_snapshot['url']} returned {head_response.status_code}. Trying GET.")
@@ -141,10 +136,11 @@ def execute_url_check(url_id_to_check):
141
  except requests.RequestException as e_head:
142
  print(f"HEAD failed for {url_config_snapshot['url']}: {e_head}. Trying GET...")
143
 
 
144
  if final_check_status != 'ok':
145
  try:
146
  get_response = requests.get(url_config_snapshot['url'], timeout=15, allow_redirects=True, headers=http_headers)
147
- if get_response.ok:
148
  final_check_status = 'ok'
149
  else:
150
  print(f"GET for {url_config_snapshot['url']} status: {get_response.status_code}")
@@ -164,24 +160,25 @@ def execute_url_check(url_id_to_check):
164
  final_check_status = 'error'
165
 
166
  with lock:
167
- if url_id_to_check not in monitored_urls_store: return
168
 
169
  live_url_data = monitored_urls_store[url_id_to_check]
170
  live_url_data['status'] = final_check_status
171
  live_url_data['responseTime'] = round(http_response_time_ms) if http_response_time_ms is not None else None
172
- live_url_data['lastChecked'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
173
 
174
  current_history_list = live_url_data.get('history', [])
175
- current_history_list.append({'timestamp': time.time(), 'status': final_check_status})
176
  live_url_data['history'] = current_history_list
177
  prune_url_history(live_url_data)
178
 
179
- save_data_to_json() # This will now try to save to /data/data.json
180
  print(f"Finished check for {live_url_data['url']}: {final_check_status}, {http_response_time_ms} ms")
181
 
182
  def pinger_thread_function(url_id_param, stop_event_param):
183
  while not stop_event_param.is_set():
184
  execute_url_check(url_id_param)
 
185
  for _ in range(PING_INTERVAL_SECONDS):
186
  if stop_event_param.is_set(): break
187
  time.sleep(1)
@@ -195,13 +192,15 @@ def start_url_monitoring_thread(target_url_id):
195
 
196
  url_data_entry = monitored_urls_store[target_url_id]
197
 
 
198
  if "_thread" in url_data_entry and url_data_entry["_thread"].is_alive():
199
  print(f"Monitor for URL ID {target_url_id} already running. Attempting to restart.")
200
- if "_stop_event" in url_data_entry and url_data_entry["_stop_event"]:
201
  url_data_entry["_stop_event"].set()
202
- url_data_entry["_thread"].join(timeout=3)
203
 
204
  new_stop_event = threading.Event()
 
205
  new_thread = threading.Thread(target=pinger_thread_function, args=(target_url_id, new_stop_event), daemon=True)
206
 
207
  url_data_entry["_thread"] = new_thread
@@ -211,15 +210,16 @@ def start_url_monitoring_thread(target_url_id):
211
  print(f"Started/Restarted monitoring for URL ID {target_url_id}: {url_data_entry['url']}")
212
 
213
  def stop_url_monitoring_thread(target_url_id):
214
- with lock:
215
- if target_url_id in monitored_urls_store:
216
- url_data_entry = monitored_urls_store[target_url_id]
217
- if "_thread" in url_data_entry and url_data_entry["_thread"].is_alive():
218
- print(f"Signaling stop for monitor thread of URL ID {target_url_id}")
219
- if "_stop_event" in url_data_entry and url_data_entry["_stop_event"]:
220
- url_data_entry["_stop_event"].set()
221
- url_data_entry.pop("_thread", None)
222
- url_data_entry.pop("_stop_event", None)
 
223
 
224
  # --- API Endpoints ---
225
  @app.route('/')
@@ -229,6 +229,7 @@ def serve_index():
229
  @app.route('/api/urls', methods=['GET'])
230
  def get_all_urls():
231
  with lock:
 
232
  response_list = []
233
  for data_item in monitored_urls_store.values():
234
  display_item = data_item.copy()
@@ -246,7 +247,7 @@ def add_new_url():
246
  input_url = request_data['url'].strip()
247
 
248
  if not input_url.startswith('http://') and not input_url.startswith('https://'):
249
- input_url = 'https://' + input_url
250
 
251
  try:
252
  parsed_input_url = urlparse(input_url)
@@ -257,11 +258,12 @@ def add_new_url():
257
  return jsonify({"error": "Invalid URL format"}), 400
258
 
259
  with lock:
 
260
  normalized_new_url = input_url.rstrip('/').lower()
261
- for existing_url_id in list(monitored_urls_store.keys()):
262
  existing_url_data = monitored_urls_store.get(existing_url_id)
263
  if existing_url_data and existing_url_data['url'].rstrip('/').lower() == normalized_new_url:
264
- return jsonify({"error": "URL already monitored"}), 409
265
 
266
  new_url_id = str(uuid.uuid4())
267
  resolved_ip = get_host_ip_address(url_hostname) if url_hostname else 'N/A'
@@ -271,13 +273,19 @@ def add_new_url():
271
  "ip": resolved_ip, "responseTime": None, "lastChecked": None, "history": []
272
  }
273
 
 
 
274
  response_payload = url_entry_to_add.copy()
275
- monitored_urls_store[new_url_id] = url_entry_to_add
 
276
  save_data_to_json()
277
 
278
- start_url_monitoring_thread(new_url_id)
 
 
279
  return jsonify(response_payload), 201
280
 
 
281
  @app.route('/api/urls/<string:target_url_id>', methods=['DELETE'])
282
  def delete_existing_url(target_url_id):
283
  with lock:
@@ -286,7 +294,8 @@ def delete_existing_url(target_url_id):
286
  removed_url_entry = monitored_urls_store.pop(target_url_id)
287
  save_data_to_json()
288
 
289
- response_data = removed_url_entry.copy()
 
290
  response_data.pop("_thread", None)
291
  response_data.pop("_stop_event", None)
292
  print(f"Deleted URL ID {target_url_id}")
@@ -295,13 +304,20 @@ def delete_existing_url(target_url_id):
295
  return jsonify({"error": "URL not found"}), 404
296
 
297
  # --- Main Execution / Gunicorn Entry Point ---
298
- if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
299
- ensure_data_dir_exists() # Ensure data dir exists before loading
 
300
  load_data_from_json()
301
 
302
  if __name__ == '__main__':
303
- if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
304
- ensure_data_dir_exists() # Ensure data dir exists before loading in reloader
 
 
 
 
305
  load_data_from_json()
306
- # The DATA_DIR fallback for local dev will be used here if /data doesn't exist
307
- app.run(debug=True, host='0.0.0.0', port=7860)
 
 
 
11
  app = Flask(__name__, static_folder='.', static_url_path='')
12
 
13
  # --- Configuration ---
14
+ DATA_FILE = "/tmp/data.json" # MODIFIED LINE: Use the /tmp directory for writing
15
+ PING_INTERVAL_SECONDS = 60 # Backend pings every 60 seconds
16
+ HISTORY_DURATION_SECONDS = 60 * 60 # Store history for 1 hour
17
+
18
+ # --- Data Store ---
19
+ # Structure: { "id": "uuid", "url": "string", "status": "pending/ok/error/checking",
20
+ # "ip": "string", "responseTime": float_ms, "lastChecked": "iso_string_utc",
21
+ # "history": [{"timestamp": float_unix_ts_seconds, "status": "ok/error"}],
22
+ # "_thread": threading.Thread_object, "_stop_event": threading.Event_object }
23
+ monitored_urls_store = {} # In-memory store: id -> url_data
24
+ lock = threading.Lock() # To protect access to monitored_urls_store
25
 
26
  # --- Helper Functions ---
 
 
 
 
 
 
 
 
 
 
 
27
  def save_data_to_json():
28
+ # This function must be called with 'lock' acquired
29
+ serializable_data = {}
30
+ for url_id, data in monitored_urls_store.items():
31
+ s_data = data.copy()
32
+ s_data.pop("_thread", None)
33
+ s_data.pop("_stop_event", None)
34
+ serializable_data[url_id] = s_data
35
+ try:
36
+ with open(DATA_FILE, 'w') as f:
37
+ json.dump(serializable_data, f, indent=2)
38
+ print(f"Data saved to {DATA_FILE}")
39
+ except IOError as e:
40
+ print(f"Error saving data to {DATA_FILE}: {e}") # This error will now show the /tmp path
41
 
42
  def load_data_from_json():
43
  global monitored_urls_store
 
44
  if os.path.exists(DATA_FILE):
45
  try:
46
  with open(DATA_FILE, 'r') as f:
47
  loaded_json_data = json.load(f)
48
+ print(f"Data loaded from {DATA_FILE}")
49
 
50
  temp_store = {}
51
  for url_id_key, data_item in loaded_json_data.items():
52
+ # Ensure essential fields and use 'id' from data if present, else key
53
  data_item.setdefault('id', url_id_key)
54
  current_id = data_item['id']
55
  data_item.setdefault('status', 'pending')
 
59
  data_item.setdefault('history', data_item.get('history', []))
60
  temp_store[current_id] = data_item
61
 
62
+ with lock: # Lock before modifying global monitored_urls_store
63
  monitored_urls_store = temp_store
64
 
65
  except json.JSONDecodeError:
 
81
 
82
  def get_host_ip_address(hostname_str):
83
  try:
84
+ # Check if hostname_str is already a valid IP address
85
+ socket.inet_aton(hostname_str) # Throws an OSError if not a valid IPv4 string
86
  return hostname_str
87
  except OSError:
88
+ # It's not an IP, so try to resolve it as a hostname
89
  try:
90
  ip_address = socket.gethostbyname(hostname_str)
91
  return ip_address
 
97
  return 'N/A'
98
 
99
  def prune_url_history(url_data_entry):
100
+ # Assumes 'lock' is acquired or called from the thread managing this entry
101
  cutoff_time = time.time() - HISTORY_DURATION_SECONDS
102
  url_data_entry['history'] = [
103
  entry for entry in url_data_entry.get('history', []) if entry['timestamp'] >= cutoff_time
 
113
 
114
  print(f"Checking {current_url_data['url']} (ID: {url_id_to_check})...")
115
  current_url_data['status'] = 'checking'
116
+ url_config_snapshot = current_url_data.copy() # Snapshot for use outside lock
117
 
118
  if not url_config_snapshot: return
119
 
120
  check_start_time = time.perf_counter()
121
  final_check_status = 'error'
122
  http_response_time_ms = None
123
+ # Identify your bot to website owners
124
  http_headers = {'User-Agent': 'URLPinger/1.0 (HuggingFace Space Bot)'}
125
 
126
  try:
127
+ # Attempt HEAD request first
128
  try:
129
  head_response = requests.head(url_config_snapshot['url'], timeout=10, allow_redirects=True, headers=http_headers)
130
+ if 200 <= head_response.status_code < 400: # OK or Redirect
131
  final_check_status = 'ok'
132
  else:
133
  print(f"HEAD for {url_config_snapshot['url']} returned {head_response.status_code}. Trying GET.")
 
136
  except requests.RequestException as e_head:
137
  print(f"HEAD failed for {url_config_snapshot['url']}: {e_head}. Trying GET...")
138
 
139
+ # If HEAD was not conclusive, try GET
140
  if final_check_status != 'ok':
141
  try:
142
  get_response = requests.get(url_config_snapshot['url'], timeout=15, allow_redirects=True, headers=http_headers)
143
+ if get_response.ok: # Only 2xx status codes
144
  final_check_status = 'ok'
145
  else:
146
  print(f"GET for {url_config_snapshot['url']} status: {get_response.status_code}")
 
160
  final_check_status = 'error'
161
 
162
  with lock:
163
+ if url_id_to_check not in monitored_urls_store: return # URL might have been removed during check
164
 
165
  live_url_data = monitored_urls_store[url_id_to_check]
166
  live_url_data['status'] = final_check_status
167
  live_url_data['responseTime'] = round(http_response_time_ms) if http_response_time_ms is not None else None
168
+ live_url_data['lastChecked'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) # ISO 8601 UTC
169
 
170
  current_history_list = live_url_data.get('history', [])
171
+ current_history_list.append({'timestamp': time.time(), 'status': final_check_status}) # timestamp in seconds
172
  live_url_data['history'] = current_history_list
173
  prune_url_history(live_url_data)
174
 
175
+ save_data_to_json()
176
  print(f"Finished check for {live_url_data['url']}: {final_check_status}, {http_response_time_ms} ms")
177
 
178
  def pinger_thread_function(url_id_param, stop_event_param):
179
  while not stop_event_param.is_set():
180
  execute_url_check(url_id_param)
181
+ # Sleep for PING_INTERVAL_SECONDS, but check stop_event periodically
182
  for _ in range(PING_INTERVAL_SECONDS):
183
  if stop_event_param.is_set(): break
184
  time.sleep(1)
 
192
 
193
  url_data_entry = monitored_urls_store[target_url_id]
194
 
195
+ # Stop existing thread if it's alive
196
  if "_thread" in url_data_entry and url_data_entry["_thread"].is_alive():
197
  print(f"Monitor for URL ID {target_url_id} already running. Attempting to restart.")
198
+ if "_stop_event" in url_data_entry and url_data_entry["_stop_event"]: # Check if _stop_event exists
199
  url_data_entry["_stop_event"].set()
200
+ url_data_entry["_thread"].join(timeout=3) # Wait for thread to stop
201
 
202
  new_stop_event = threading.Event()
203
+ # daemon=True allows main program to exit even if threads are running
204
  new_thread = threading.Thread(target=pinger_thread_function, args=(target_url_id, new_stop_event), daemon=True)
205
 
206
  url_data_entry["_thread"] = new_thread
 
210
  print(f"Started/Restarted monitoring for URL ID {target_url_id}: {url_data_entry['url']}")
211
 
212
  def stop_url_monitoring_thread(target_url_id):
213
+ # This function must be called with 'lock' acquired
214
+ if target_url_id in monitored_urls_store:
215
+ url_data_entry = monitored_urls_store[target_url_id]
216
+ if "_thread" in url_data_entry and url_data_entry["_thread"].is_alive():
217
+ print(f"Signaling stop for monitor thread of URL ID {target_url_id}")
218
+ if "_stop_event" in url_data_entry and url_data_entry["_stop_event"]: # Check if _stop_event exists
219
+ url_data_entry["_stop_event"].set()
220
+ # Not joining here to keep API responsive, daemon thread will exit.
221
+ url_data_entry.pop("_thread", None)
222
+ url_data_entry.pop("_stop_event", None)
223
 
224
  # --- API Endpoints ---
225
  @app.route('/')
 
229
  @app.route('/api/urls', methods=['GET'])
230
  def get_all_urls():
231
  with lock:
232
+ # Prepare data for sending: list of url data, no thread objects
233
  response_list = []
234
  for data_item in monitored_urls_store.values():
235
  display_item = data_item.copy()
 
247
  input_url = request_data['url'].strip()
248
 
249
  if not input_url.startswith('http://') and not input_url.startswith('https://'):
250
+ input_url = 'https://' + input_url # Default to https
251
 
252
  try:
253
  parsed_input_url = urlparse(input_url)
 
258
  return jsonify({"error": "Invalid URL format"}), 400
259
 
260
  with lock:
261
+ # Check for duplicates (case-insensitive, ignoring trailing slashes)
262
  normalized_new_url = input_url.rstrip('/').lower()
263
+ for existing_url_id in list(monitored_urls_store.keys()): # Iterate over keys to avoid issues if store is modified
264
  existing_url_data = monitored_urls_store.get(existing_url_id)
265
  if existing_url_data and existing_url_data['url'].rstrip('/').lower() == normalized_new_url:
266
+ return jsonify({"error": "URL already monitored"}), 409 # Conflict
267
 
268
  new_url_id = str(uuid.uuid4())
269
  resolved_ip = get_host_ip_address(url_hostname) if url_hostname else 'N/A'
 
273
  "ip": resolved_ip, "responseTime": None, "lastChecked": None, "history": []
274
  }
275
 
276
+ # Make a copy of the entry for the response *before* it's potentially modified
277
+ # by start_url_monitoring_thread with non-serializable objects.
278
  response_payload = url_entry_to_add.copy()
279
+
280
+ monitored_urls_store[new_url_id] = url_entry_to_add # url_entry_to_add will be modified by start_url_monitoring_thread
281
  save_data_to_json()
282
 
283
+ start_url_monitoring_thread(new_url_id) # This will add _thread and _stop_event to monitored_urls_store[new_url_id]
284
+
285
+ # Return the clean response_payload, which does not have _thread or _stop_event
286
  return jsonify(response_payload), 201
287
 
288
+
289
  @app.route('/api/urls/<string:target_url_id>', methods=['DELETE'])
290
  def delete_existing_url(target_url_id):
291
  with lock:
 
294
  removed_url_entry = monitored_urls_store.pop(target_url_id)
295
  save_data_to_json()
296
 
297
+ # Prepare data for response (without thread objects)
298
+ response_data = removed_url_entry.copy() # Copy before potential modification if stop_url_monitoring_thread didn't pop everything
299
  response_data.pop("_thread", None)
300
  response_data.pop("_stop_event", None)
301
  print(f"Deleted URL ID {target_url_id}")
 
304
  return jsonify({"error": "URL not found"}), 404
305
 
306
  # --- Main Execution / Gunicorn Entry Point ---
307
+ # Load data once when the application module is initialized
308
+ # This handles both `flask run` and gunicorn scenarios.
309
+ if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': # Avoids double load in Flask debug mode
310
  load_data_from_json()
311
 
312
  if __name__ == '__main__':
313
+ # This block is for local development (e.g., `python app.py`)
314
+ # `load_data_from_json()` is called above unless Werkzeug reloader is active.
315
+ # If using Flask's reloader, load_data_from_json will be called twice:
316
+ # once by the main process, once by the reloader's child process.
317
+ # The check for WERKZEUG_RUN_MAIN ensures it only loads in the main one or the child.
318
+ if os.environ.get('WERKZEUG_RUN_MAIN') == 'true': # Ensure data is loaded in the reloaded process too
319
  load_data_from_json()
320
+ app.run(debug=True, host='0.0.0.0', port=7860)
321
+
322
+ # When run with Gunicorn, Gunicorn imports `app` from this `app.py` file.
323
+ # `load_data_from_json()` will have been called during that import (due to the WERKZEUG_RUN_MAIN check).