ChandimaPrabath commited on
Commit
4e9654b
·
1 Parent(s): b844929
Files changed (1) hide show
  1. LoadBalancer.py +68 -93
LoadBalancer.py CHANGED
@@ -2,7 +2,6 @@ import os
2
  import requests
3
  import json
4
  import urllib.request
5
- import shutil
6
  from tqdm import tqdm
7
  from indexer import indexer
8
  import re
@@ -37,41 +36,30 @@ class LoadBalancer:
37
  self.file_structure = None
38
 
39
  # Ensure CACHE_DIR exists
40
- os.makedirs(self.CACHE_DIR, exist_ok=True)
 
41
 
42
- # Initialize JSON files
43
- self.initialize_json_file(self.FILM_STORE_JSON_PATH)
44
- self.initialize_json_file(self.TV_STORE_JSON_PATH)
 
45
 
46
  # Index the file structure
47
  indexer()
48
 
49
  # Load the file structure JSON
50
- self.load_file_structure()
 
 
 
 
51
 
52
- # Start prefetching
53
  prefetch_thread = Thread(target=self.start_prefetching)
54
  prefetch_thread.daemon = True
55
  prefetch_thread.start()
56
 
57
- def initialize_json_file(self, path):
58
- """Initialize a JSON file with an empty object if it does not exist."""
59
- if not os.path.exists(path):
60
- with open(path, 'w') as json_file:
61
- json.dump({}, json_file)
62
- logging.info(f"Created JSON file: {path}")
63
-
64
- def load_file_structure(self):
65
- """Load the file structure from the index file."""
66
- if not os.path.exists(self.INDEX_FILE):
67
- raise FileNotFoundError(f"{self.INDEX_FILE} not found. Please make sure the file exists.")
68
-
69
- with open(self.INDEX_FILE, 'r') as f:
70
- self.file_structure = json.load(f)
71
- logging.info(f"Loaded file structure from {self.INDEX_FILE}")
72
 
73
  def register_instance(self, instance_url):
74
- """Register a new instance."""
75
  if instance_url not in self.instances:
76
  self.instances.append(instance_url)
77
  logging.info(f"Registered instance {instance_url}")
@@ -79,7 +67,6 @@ class LoadBalancer:
79
  logging.info(f"Instance {instance_url} is already registered.")
80
 
81
  def remove_instance(self, instance_url):
82
- """Remove an instance."""
83
  if instance_url in self.instances:
84
  self.instances.remove(instance_url)
85
  self.instances_health.pop(instance_url, None)
@@ -88,101 +75,45 @@ class LoadBalancer:
88
  logging.info(f"Removed instance {instance_url}")
89
  else:
90
  logging.info(f"Instance {instance_url} not found for removal.")
91
-
92
  def get_reports(self):
93
- """Fetch reports from instances and update JSON files."""
94
  reports = self.instances_api.fetch_reports()
95
- temp_film_store_path = 'temp_film_store.json'
96
- temp_tv_store_path = 'temp_tv_store.json'
97
-
98
- # Initialize temporary JSON files
99
- self.initialize_json_file(temp_film_store_path)
100
- self.initialize_json_file(temp_tv_store_path)
101
-
102
- for instance_url in self.instances[:]:
103
  if instance_url in reports:
104
  report = reports[instance_url]
105
  logging.info(f"Report from {instance_url}: {report}")
106
- self.process_report(instance_url, report, temp_film_store_path, temp_tv_store_path)
107
  else:
108
  logging.error(f"Failed to get report from {instance_url}. Removing instance.")
109
  self.remove_instance(instance_url)
110
 
111
- # Replace actual JSON files with updated temporary files
112
- self.replace_json_files(temp_film_store_path, self.FILM_STORE_JSON_PATH)
113
- self.replace_json_files(temp_tv_store_path, self.TV_STORE_JSON_PATH)
114
-
115
- def process_report(self, instance_url, report, temp_film_store_path, temp_tv_store_path):
116
- """Process the report from an instance and update temporary JSON files."""
117
  film_store = report.get('film_store', {})
118
  tv_store = report.get('tv_store', {})
119
  cache_size = report.get('cache_size')
120
 
121
  logging.info(f"Processing report from {instance_url}")
 
 
 
122
 
123
- # Update temporary film store JSON
124
  for title, path in film_store.items():
125
  url = f"{instance_url}/api/film/{title.replace(' ', '%20')}"
126
- self.update_film_store_json(title, url, temp_film_store_path)
127
 
128
- # Update temporary TV store JSON
 
129
  for title, seasons in tv_store.items():
130
  for season, episodes in seasons.items():
131
  for episode, path in episodes.items():
132
  url = f"{instance_url}/api/tv/{title.replace(' ', '%20')}/{season.replace(' ', '%20')}/{episode.replace(' ', '%20')}"
133
- self.update_tv_store_json(title, season, episode, url, temp_tv_store_path)
134
 
135
  logging.info("Film and TV Stores processed successfully.")
136
  self.update_instances_health(instance=instance_url, cache_size=cache_size)
137
 
138
- def update_film_store_json(self, title, url, temp_film_store_path):
139
- """Update the temporary film store JSON with the new file."""
140
- film_store_data = {}
141
- if os.path.exists(temp_film_store_path):
142
- with open(temp_film_store_path, 'r') as json_file:
143
- film_store_data = json.load(json_file)
144
-
145
- film_store_data[title] = url
146
-
147
- with open(temp_film_store_path, 'w') as json_file:
148
- json.dump(film_store_data, json_file, indent=2)
149
-
150
- logging.info(f'Film store updated with {title}. Content: {film_store_data}')
151
-
152
- def update_tv_store_json(self, title, season, episode, url, temp_tv_store_path):
153
- """Update the temporary TV store JSON with the new file."""
154
- tv_store_data = {}
155
- if os.path.exists(temp_tv_store_path):
156
- with open(temp_tv_store_path, 'r') as json_file:
157
- tv_store_data = json.load(json_file)
158
-
159
- if title not in tv_store_data:
160
- tv_store_data[title] = {}
161
-
162
- if season not in tv_store_data[title]:
163
- tv_store_data[title][season] = {}
164
-
165
- tv_store_data[title][season][episode] = url
166
-
167
- with open(temp_tv_store_path, 'w') as json_file:
168
- json.dump(tv_store_data, json_file, indent=2)
169
-
170
- logging.info(f'TV store updated with {title}, {season}, {episode}. Content: {tv_store_data}')
171
-
172
- def replace_json_files(self, temp_file_path, actual_file_path):
173
- """Replace the actual JSON file with the temporary JSON file."""
174
- try:
175
- if os.path.exists(temp_file_path):
176
- shutil.copy(temp_file_path, actual_file_path)
177
- os.remove(temp_file_path)
178
- logging.info(f'Updated {actual_file_path} with new data.')
179
- else:
180
- logging.error(f'Temporary file {temp_file_path} does not exist.')
181
- except Exception as e:
182
- logging.error(f'Error replacing JSON files: {e}')
183
-
184
  def start_polling(self):
185
- """Start polling for reports."""
186
  logging.info("Starting polling.")
187
  while not self.stop_event.is_set():
188
  self.get_reports()
@@ -190,7 +121,6 @@ class LoadBalancer:
190
  logging.info("Polling stopped.")
191
 
192
  def stop_polling(self):
193
- """Stop polling."""
194
  logging.info("Stopping polling.")
195
  self.stop_event.set()
196
 
@@ -222,6 +152,51 @@ class LoadBalancer:
222
  print(f"Error getting system proxies: {e}")
223
  return {}
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  @staticmethod
226
  def clear_json_file(file_path):
227
  """
 
2
  import requests
3
  import json
4
  import urllib.request
 
5
  from tqdm import tqdm
6
  from indexer import indexer
7
  import re
 
36
  self.file_structure = None
37
 
38
  # Ensure CACHE_DIR exists
39
+ if not os.path.exists(self.CACHE_DIR):
40
+ os.makedirs(self.CACHE_DIR)
41
 
42
+ for path in [self.FILM_STORE_JSON_PATH, self.TV_STORE_JSON_PATH]:
43
+ if not os.path.exists(path):
44
+ with open(path, 'w') as json_file:
45
+ json.dump({}, json_file)
46
 
47
  # Index the file structure
48
  indexer()
49
 
50
  # Load the file structure JSON
51
+ if not os.path.exists(self.INDEX_FILE):
52
+ raise FileNotFoundError(f"{self.INDEX_FILE} not found. Please make sure the file exists.")
53
+
54
+ with open(self.INDEX_FILE, 'r') as f:
55
+ self.file_structure = json.load(f)
56
 
 
57
  prefetch_thread = Thread(target=self.start_prefetching)
58
  prefetch_thread.daemon = True
59
  prefetch_thread.start()
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  def register_instance(self, instance_url):
 
63
  if instance_url not in self.instances:
64
  self.instances.append(instance_url)
65
  logging.info(f"Registered instance {instance_url}")
 
67
  logging.info(f"Instance {instance_url} is already registered.")
68
 
69
  def remove_instance(self, instance_url):
 
70
  if instance_url in self.instances:
71
  self.instances.remove(instance_url)
72
  self.instances_health.pop(instance_url, None)
 
75
  logging.info(f"Removed instance {instance_url}")
76
  else:
77
  logging.info(f"Instance {instance_url} not found for removal.")
78
+
79
  def get_reports(self):
 
80
  reports = self.instances_api.fetch_reports()
81
+ for instance_url in self.instances[:]: # Copy list to avoid modification during iteration
 
 
 
 
 
 
 
82
  if instance_url in reports:
83
  report = reports[instance_url]
84
  logging.info(f"Report from {instance_url}: {report}")
85
+ self.process_report(instance_url, report)
86
  else:
87
  logging.error(f"Failed to get report from {instance_url}. Removing instance.")
88
  self.remove_instance(instance_url)
89
 
90
+ def process_report(self, instance_url, report):
 
 
 
 
 
91
  film_store = report.get('film_store', {})
92
  tv_store = report.get('tv_store', {})
93
  cache_size = report.get('cache_size')
94
 
95
  logging.info(f"Processing report from {instance_url}")
96
+ # logging.info(f"Film Store: {film_store}")
97
+ # logging.info(f"TV Store: {tv_store}")
98
+ # logging.info(f"Cache Size: {cache_size}")
99
 
100
+ # Process films
101
  for title, path in film_store.items():
102
  url = f"{instance_url}/api/film/{title.replace(' ', '%20')}"
103
+ self.update_film_store_json(title, url)
104
 
105
+
106
+ # Process TV shows
107
  for title, seasons in tv_store.items():
108
  for season, episodes in seasons.items():
109
  for episode, path in episodes.items():
110
  url = f"{instance_url}/api/tv/{title.replace(' ', '%20')}/{season.replace(' ', '%20')}/{episode.replace(' ', '%20')}"
111
+ self.update_tv_store_json(title, season, episode, url)
112
 
113
  logging.info("Film and TV Stores processed successfully.")
114
  self.update_instances_health(instance=instance_url, cache_size=cache_size)
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  def start_polling(self):
 
117
  logging.info("Starting polling.")
118
  while not self.stop_event.is_set():
119
  self.get_reports()
 
121
  logging.info("Polling stopped.")
122
 
123
  def stop_polling(self):
 
124
  logging.info("Stopping polling.")
125
  self.stop_event.set()
126
 
 
152
  print(f"Error getting system proxies: {e}")
153
  return {}
154
 
155
+ def update_film_store_json(self,title, url):
156
+ """
157
+ Updates the film store JSON with the new file.
158
+
159
+ Args:
160
+ title (str): The title of the film.
161
+ url (str): The url.
162
+ """
163
+ FILM_STORE_JSON_PATH = self.FILM_STORE_JSON_PATH
164
+
165
+ film_store_data = {}
166
+ if os.path.exists(FILM_STORE_JSON_PATH):
167
+ with open(FILM_STORE_JSON_PATH, 'r') as json_file:
168
+ film_store_data = json.load(json_file)
169
+
170
+ film_store_data[title] = url
171
+
172
+ with open(FILM_STORE_JSON_PATH, 'w') as json_file:
173
+ json.dump(film_store_data, json_file, indent=2)
174
+ print(f'Film store updated with {title}.')
175
+
176
+ def update_tv_store_json(self, title, season, episode, url):
177
+ """
178
+ Updates the TV store JSON with the new file, organizing by title, season, and episode.
179
+ """
180
+ TV_STORE_JSON_PATH = self.TV_STORE_JSON_PATH
181
+
182
+ tv_store_data = {}
183
+ if os.path.exists(TV_STORE_JSON_PATH):
184
+ with open(TV_STORE_JSON_PATH, 'r') as json_file:
185
+ tv_store_data = json.load(json_file)
186
+
187
+ if title not in tv_store_data:
188
+ tv_store_data[title] = {}
189
+
190
+ if season not in tv_store_data[title]:
191
+ tv_store_data[title][season] = {}
192
+
193
+ tv_store_data[title][season][episode] = url
194
+
195
+ with open(TV_STORE_JSON_PATH, 'w') as json_file:
196
+ json.dump(tv_store_data, json_file, indent=2)
197
+
198
+ print(f'TV store updated with {title}, {season}, {episode}.')
199
+
200
  @staticmethod
201
  def clear_json_file(file_path):
202
  """