1. import os
  2. import time
  3. import json
  4. import requests
  5. from collections import defaultdict
  6. from urllib.parse import urlparse
  7. class ConfigFileMetrics:
  8. def __init__(self, base_url, rate_limit=10):
  9. self.base_url = base_url
  10. self.rate_limit = rate_limit
  11. self.request_counts = defaultdict(int) # Track requests per config
  12. self.last_request_times = defaultdict(float) # Track last request time
  13. self.lock = threading.Lock() # thread safety
  14. def get_config_metrics(self, config_path):
  15. """
  16. Collects metrics from a configuration file.
  17. """
  18. config_name = os.path.basename(config_path)
  19. with self.lock:
  20. if self.request_counts[config_name] >= self.rate_limit:
  21. wait_time = self.calculate_wait_time(config_name)
  22. print(f"Rate limit exceeded for {config_name}. Waiting {wait_time:.2f} seconds.")
  23. time.sleep(wait_time)
  24. with self.lock:
  25. self.request_counts[config_name] -= 1
  26. current_time = time.time()
  27. self.last_request_times[config_name] = current_time
  28. self.request_counts[config_name] += 1
  29. try:
  30. # Simulate fetching config data. Replace with actual config loading.
  31. config_data = self._fetch_config_data(config_path)
  32. return config_data #Return the config data
  33. except Exception as e:
  34. print(f"Error processing {config_path}: {e}")
  35. return None
  36. def _fetch_config_data(self, config_path):
  37. """Simulates fetching config data from a URL or file."""
  38. # Replace with your actual config fetching logic
  39. try:
  40. with open(config_path, 'r') as f:
  41. config_data = json.load(f)
  42. #Example of more complex data retrieval
  43. #parsed_url = urlparse(config_path)
  44. #response = requests.get(f"{self.base_url}{config_path}")
  45. #response.raise_for_status()
  46. #config_data = response.json()
  47. return config_data
  48. except FileNotFoundError:
  49. print(f"Config file not found: {config_path}")
  50. return None
  51. except json.JSONDecodeError:
  52. print(f"Invalid JSON in config file: {config_path}")
  53. return None
  54. except requests.exceptions.RequestException as e:
  55. print(f"Error fetching config from {config_path}: {e}")
  56. return None
  57. def calculate_wait_time(self, config_name):
  58. """Calculates the wait time based on last request time."""
  59. if not self.last_request_times[config_name]:
  60. return 0.0 # No previous request, no wait
  61. time_since_last_request = time.time() - self.last_request_times[config_name]
  62. return max(0.0, self.rate_limit - time_since_last_request)
  63. def get_metrics(self):
  64. """Returns the collected metrics."""
  65. return {
  66. "request_counts": self.request_counts,
  67. "last_request_times": self.last_request_times
  68. }
  69. import threading
  70. if __name__ == '__main__':
  71. # Example Usage
  72. base_url = "http://example.com/configs" #Replace with your base URL
  73. metrics = ConfigFileMetrics(base_url, rate_limit=5)
  74. # Simulate processing multiple configuration files
  75. config_files = ["config1.json", "config2.json", "config3.json", "config1.json", "config2.json", "config1.json"] #Example files
  76. for file in config_files:
  77. metrics.get_config_metrics(file)
  78. metrics_data = metrics.get_metrics()
  79. print(json.dumps(metrics_data, indent=2))

Add your comment