import os
import time
import json
import requests
from collections import defaultdict
from urllib.parse import urlparse
class ConfigFileMetrics:
def __init__(self, base_url, rate_limit=10):
self.base_url = base_url
self.rate_limit = rate_limit
self.request_counts = defaultdict(int) # Track requests per config
self.last_request_times = defaultdict(float) # Track last request time
self.lock = threading.Lock() # thread safety
def get_config_metrics(self, config_path):
"""
Collects metrics from a configuration file.
"""
config_name = os.path.basename(config_path)
with self.lock:
if self.request_counts[config_name] >= self.rate_limit:
wait_time = self.calculate_wait_time(config_name)
print(f"Rate limit exceeded for {config_name}. Waiting {wait_time:.2f} seconds.")
time.sleep(wait_time)
with self.lock:
self.request_counts[config_name] -= 1
current_time = time.time()
self.last_request_times[config_name] = current_time
self.request_counts[config_name] += 1
try:
# Simulate fetching config data. Replace with actual config loading.
config_data = self._fetch_config_data(config_path)
return config_data #Return the config data
except Exception as e:
print(f"Error processing {config_path}: {e}")
return None
def _fetch_config_data(self, config_path):
"""Simulates fetching config data from a URL or file."""
# Replace with your actual config fetching logic
try:
with open(config_path, 'r') as f:
config_data = json.load(f)
#Example of more complex data retrieval
#parsed_url = urlparse(config_path)
#response = requests.get(f"{self.base_url}{config_path}")
#response.raise_for_status()
#config_data = response.json()
return config_data
except FileNotFoundError:
print(f"Config file not found: {config_path}")
return None
except json.JSONDecodeError:
print(f"Invalid JSON in config file: {config_path}")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching config from {config_path}: {e}")
return None
def calculate_wait_time(self, config_name):
"""Calculates the wait time based on last request time."""
if not self.last_request_times[config_name]:
return 0.0 # No previous request, no wait
time_since_last_request = time.time() - self.last_request_times[config_name]
return max(0.0, self.rate_limit - time_since_last_request)
def get_metrics(self):
"""Returns the collected metrics."""
return {
"request_counts": self.request_counts,
"last_request_times": self.last_request_times
}
import threading
if __name__ == '__main__':
# Example Usage
base_url = "http://example.com/configs" #Replace with your base URL
metrics = ConfigFileMetrics(base_url, rate_limit=5)
# Simulate processing multiple configuration files
config_files = ["config1.json", "config2.json", "config3.json", "config1.json", "config2.json", "config1.json"] #Example files
for file in config_files:
metrics.get_config_metrics(file)
metrics_data = metrics.get_metrics()
print(json.dumps(metrics_data, indent=2))
Add your comment