-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit_diff.diff
More file actions
2666 lines (2572 loc) · 135 KB
/
Copy pathgit_diff.diff
File metadata and controls
2666 lines (2572 loc) · 135 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/loadbalancer/LB.conf b/loadbalancer/LB.conf
index e7481d3..66c9353 100644
--- a/loadbalancer/LB.conf
+++ b/loadbalancer/LB.conf
@@ -1,3 +1,4 @@
BATCH_SIZE=10
BATCH_TIMEOUT_SECONDS=15.0
-SCHEDULER_URLS=["http://10.8.1.18:8000/developers/run_service_async_batch/","http://10.1.19.78:8000/developers/run_service_async_batch/"]
+# SCHEDULER_URLS are still used to derive MQTT topics
+# They map to SCHEDULER_{host_with_underscores} topics
diff --git a/loadbalancer/README.md b/loadbalancer/README.md
index a433e95..95e9bac 100644
--- a/loadbalancer/README.md
+++ b/loadbalancer/README.md
@@ -104,7 +104,7 @@ curl -X POST "http://localhost:9001/loadbalancer/run_service/" \
-H "User-Agent: Thunder Client (https://www.thunderclient.com)" \
-H "Content-Type: application/json" \
-d '{
- "serviceID": 10,
+ "serviceID": 17,
"numberOfInvocations": 1,
"chained": false,
"input": "None",
diff --git a/loadbalancer/loadbalancer_with_logging.py b/loadbalancer/loadbalancer_with_logging.py
index bdfc0e7..5865a21 100644
--- a/loadbalancer/loadbalancer_with_logging.py
+++ b/loadbalancer/loadbalancer_with_logging.py
@@ -15,6 +15,8 @@ import time
import json
import os
import sys
+import uuid
+import socket
from typing import List, Dict, Any, Optional
import httpx
from fastapi import FastAPI, Request, BackgroundTasks
@@ -31,6 +33,80 @@ if project_root not in sys.path:
from scheduler.scheduler.settings import get_scheduler_endpoints
+# Global to store pending responses for correlation
+pending_responses = {}
+
+# Global to track scheduler last seen timestamps
+scheduler_last_seen = {}
+
+# Global to store discovered schedulers with stable ordering
+discovered_schedulers = {} # {uuid: {topic, last_seen, status, order_index, failure_count}}
+scheduler_order = [] # List of UUIDs in stable order
+next_scheduler_index = 0 # Current position in round-robin
+MAX_CONSECUTIVE_FAILURES = 3 # Mark scheduler as offline after 3 consecutive failures
+
+def get_loadbalancer_id():
+ """Get load balancer identifier"""
+ lb_id = os.environ.get('LOADBALANCER_ID')
+ if not lb_id:
+ hostname = socket.gethostname()
+ lb_id = f"LOADBALANCER_{hostname.split('.')[0]}"
+ return lb_id
+
+def handle_scheduler_failure(scheduler_uuid: str, reason: str):
+ """Handle scheduler failure with failure counting"""
+ if scheduler_uuid not in discovered_schedulers:
+ return
+
+ scheduler_info = discovered_schedulers[scheduler_uuid]
+
+ # Increment failure count
+ failure_count = scheduler_info.get('failure_count', 0) + 1
+ scheduler_info['failure_count'] = failure_count
+
+ logger.warning(f"Scheduler {scheduler_uuid} failure #{failure_count}: {reason}")
+
+ # Only mark as offline after multiple consecutive failures
+ if failure_count >= MAX_CONSECUTIVE_FAILURES:
+ scheduler_info['status'] = 'offline'
+ logger.error(f"Scheduler {scheduler_uuid} marked as offline after {failure_count} consecutive failures")
+ else:
+ logger.info(f"Scheduler {scheduler_uuid} still considered online (failure count: {failure_count}/{MAX_CONSECUTIVE_FAILURES})")
+
+def handle_scheduler_success(scheduler_uuid: str):
+ """Handle successful scheduler response - reset failure count"""
+ if scheduler_uuid not in discovered_schedulers:
+ return
+
+ scheduler_info = discovered_schedulers[scheduler_uuid]
+
+ # Reset failure count on success
+ if scheduler_info.get('failure_count', 0) > 0:
+ logger.info(f"Scheduler {scheduler_uuid} recovered - resetting failure count")
+ scheduler_info['failure_count'] = 0
+
+ # Ensure status is online
+ if scheduler_info['status'] != 'online':
+ scheduler_info['status'] = 'online'
+ logger.info(f"Scheduler {scheduler_uuid} marked as online")
+
+def get_scheduler_mqtt_topics():
+ """Get list of scheduler MQTT topics from scheduler endpoints"""
+ scheduler_endpoints = get_scheduler_endpoints()
+ topics = []
+
+ for endpoint in scheduler_endpoints:
+ # Extract identifier from endpoint URL
+ # e.g., http://10.8.1.18:8000 -> SCHEDULER_10_8_1_18
+ # or http://hostname:8000 -> SCHEDULER_hostname
+ if '://' in endpoint:
+ host = endpoint.split('://')[1].split(':')[0]
+ # Replace dots with underscores for valid MQTT topic
+ scheduler_id = host.replace('.', '_')
+ topics.append(f"SCHEDULER_{scheduler_id}")
+
+ return topics
+
def check_experiment_mode():
"""Check if experiment mode is enabled"""
try:
@@ -153,9 +229,12 @@ class Config:
def __init__(self):
self.BATCH_SIZE = 10
self.BATCH_TIMEOUT_SECONDS = 5.0
- self.SCHEDULER_ENDPOINTS = get_scheduler_endpoints()
- self.SCHEDULER_URLS = [endpoint+str('/developers/run_service_async_batch/') for endpoint in self.SCHEDULER_ENDPOINTS]
-
+
+ # Schedulers are discovered dynamically via MQTT
+ # No need for static SCHEDULER_MQTT_TOPICS
+
+ logger.info("Scheduler discovery enabled - will discover schedulers via MQTT announcements")
+
# Load from config file if it exists
self.load_from_file("LB.conf")
@@ -198,8 +277,8 @@ class BatchState:
def __init__(self):
self.current_batch: List[Dict[str, Any]] = []
self.last_batch_time = time.time()
- self.current_scheduler_index = 0
- self.scheduler_health: Dict[str, bool] = {url: True for url in settings.SCHEDULER_URLS} # All schedulers start as healthy
+ # Remove current_scheduler_index since we use global next_scheduler_index
+ # Remove scheduler_health since we track health in discovered_schedulers
self.lock = asyncio.Lock()
batch_state = BatchState()
@@ -212,9 +291,15 @@ BROKER_ID = "broker.hivemq.com"
def on_connect(mqtt_client, userdata, flags, rc, callback_api_version):
if rc == 0:
logger.info('Connected successfully to MQTT broker')
- mqtt_client.subscribe("EVERYONE") # Add your topics here
- mqtt_client.subscribe("ROTATION") # Subscribe to ROTATION topic
- logger.info('Subscribed to EVERYONE and ROTATION topics')
+
+ # Subscribe to load balancer's own topic for responses
+ lb_id = get_loadbalancer_id()
+ mqtt_client.subscribe(lb_id)
+ mqtt_client.subscribe("ROTATION")
+ mqtt_client.subscribe("EVERYONE") # For scheduler heartbeats
+ mqtt_client.subscribe("SCHEDULER_ANNOUNCEMENTS") # For scheduler discovery
+
+ logger.info(f'Subscribed to {lb_id}, ROTATION, EVERYONE, and SCHEDULER_ANNOUNCEMENTS topics')
else:
logger.error(f'Bad connection to MQTT broker. Code: {rc}')
@@ -222,37 +307,79 @@ def on_message(mqtt_client, userdata, msg):
logger.info(f'Received message on topic: {msg.topic} with payload: {msg.payload}')
global ilp_state
- # Check for ILP_DONE message
payload_str = msg.payload.decode("utf-8")
logger.debug(f"Decoded payload string: '{payload_str}'")
- logger.debug(f"Payload length: {len(payload_str)}")
- logger.debug(f"Payload type: {type(payload_str)}")
+ # Handle scheduler announcements
+ if msg.topic == "SCHEDULER_ANNOUNCEMENTS":
+ try:
+ announcement = json.loads(payload_str)
+ scheduler_uuid = announcement.get('scheduler_uuid')
+ scheduler_topic = announcement.get('scheduler_topic')
+ status = announcement.get('status')
+
+ if status == 'online':
+ # Check if this is a new scheduler
+ if scheduler_uuid not in discovered_schedulers:
+ # New scheduler - add to end of order
+ discovered_schedulers[scheduler_uuid] = {
+ 'topic': scheduler_topic,
+ 'last_seen': time.time(),
+ 'status': 'online',
+ 'order_index': len(scheduler_order),
+ 'failure_count': 0
+ }
+ scheduler_order.append(scheduler_uuid)
+ logger.info(f"New scheduler discovered: {scheduler_uuid} (order index: {len(scheduler_order)-1})")
+ else:
+ # Existing scheduler coming back online
+ discovered_schedulers[scheduler_uuid]['status'] = 'online'
+ discovered_schedulers[scheduler_uuid]['last_seen'] = time.time()
+ logger.info(f"Scheduler {scheduler_uuid} came back online")
+
+ elif status == 'offline':
+ if scheduler_uuid in discovered_schedulers:
+ discovered_schedulers[scheduler_uuid]['status'] = 'offline'
+ logger.info(f"Scheduler {scheduler_uuid} went offline")
+
+ except Exception as e:
+ logger.error(f"Error processing scheduler announcement: {e}")
+ return
+
+ # Handle batch responses
+ if payload_str.startswith("BATCH_RESPONSE:"):
+ response_json = payload_str[15:] # Remove prefix
+ try:
+ response_data = json.loads(response_json)
+ correlation_id = response_data.get('correlation_id')
+
+ if correlation_id and correlation_id in pending_responses:
+ pending_responses[correlation_id] = response_data
+ logger.info(f"Received BATCH_RESPONSE for correlation_id: {correlation_id}")
+ except Exception as e:
+ logger.error(f"Error processing BATCH_RESPONSE: {e}")
+ return
+
+ # Handle scheduler heartbeat/pong messages
+ if payload_str.startswith("SCHEDULER_PONG:"):
+ try:
+ pong_data = json.loads(payload_str[15:]) # Remove "SCHEDULER_PONG:" prefix
+ scheduler_uuid = pong_data.get('scheduler_uuid')
+ if scheduler_uuid and scheduler_uuid in discovered_schedulers:
+ discovered_schedulers[scheduler_uuid]['last_seen'] = time.time()
+ logger.debug(f"Received heartbeat from scheduler {scheduler_uuid}")
+ except Exception as e:
+ logger.error(f"Error processing SCHEDULER_PONG: {e}")
+ return
+
+ # Handle ILP_DONE signal
if payload_str == "ILP_DONE":
logger.info("Received ILP_DONE signal, setting ilp_state to 'done'")
ilp_state = "done"
return
- # Check if payload looks like JSON before trying to parse
- if payload_str.startswith('{') and payload_str.endswith('}'):
- logger.debug("Payload looks like JSON, attempting to parse")
- try:
- data = json.loads(payload_str)
- logger.debug(f"Successfully parsed JSON: {data}")
- # Add your message handling logic here
- except Exception as e:
- logger.error(f"Error processing MQTT message as JSON: {e}")
- else:
- logger.debug("Payload does not look like JSON, skipping JSON parsing")
- logger.debug(f"Payload starts with: '{payload_str[:20]}...' (first 20 chars)")
-
- # Check for known message patterns
- if payload_str.startswith('start_connect'):
- logger.debug("Detected 'start_connect' message")
- elif payload_str.startswith('get_efficiency_score'):
- logger.debug("Detected 'get_efficiency_score' message")
- else:
- logger.debug(f"Unknown message pattern: '{payload_str}'")
+ # Keep other existing message handlers if needed
+ logger.debug(f"Unhandled message type: {payload_str[:50]}...")
def on_subscribe(mqtt_client, userdata, mid, qos, properties=None):
logger.info(f"Subscribed with QOS: {qos}")
@@ -265,58 +392,87 @@ mclient.on_subscribe = on_subscribe
app = FastAPI(title="Load Balancer with Batching")
-async def check_scheduler_availability(url: str) -> bool:
- """Check if a scheduler is available by establishing a connection"""
- try:
- # Extract base URL and host/port
- base_url = url.rsplit('/', 1)[0] if '/' in url else url
- logger.debug(f"Checking scheduler availability for {url} (base: {base_url})")
- async with httpx.AsyncClient(timeout=2.0) as client:
- # Just try to connect to the server
- response = await client.head(base_url)
- logger.debug(f"Scheduler {url} responded with status {response.status_code}")
- return True
- except Exception as e:
- logger.debug(f"Connection check failed for {url}: {e}")
+async def check_scheduler_availability(topic: str) -> bool:
+ """
+ Check if a scheduler is available based on recent heartbeat
+ """
+ # Extract UUID from topic (SCHEDULER_{uuid})
+ scheduler_uuid = topic.replace("SCHEDULER_", "")
+
+ if scheduler_uuid not in discovered_schedulers:
+ logger.debug(f"Scheduler {scheduler_uuid} not in discovered list")
return False
+
+ scheduler_info = discovered_schedulers[scheduler_uuid]
+ last_seen = scheduler_info.get('last_seen', 0)
+ current_time = time.time()
+
+ # Consider available if seen within last 60 seconds (more lenient)
+ is_available = (current_time - last_seen) < 60.0
+
+ if is_available:
+ logger.debug(f"Scheduler {scheduler_uuid} is available (last seen {current_time - last_seen:.1f}s ago)")
+ else:
+ logger.debug(f"Scheduler {scheduler_uuid} is unavailable (last seen {current_time - last_seen:.1f}s ago)")
+
+ return is_available
async def get_next_active_scheduler() -> Optional[str]:
- """Get the next active scheduler URL in round-robin fashion"""
+ """Get the next active scheduler MQTT topic in round-robin fashion"""
+ global next_scheduler_index
async with batch_state.lock:
- # Get the number of schedulers
- num_schedulers = len(settings.SCHEDULER_URLS)
- logger.debug(f"Looking for active scheduler among {num_schedulers} schedulers")
- logger.debug(f"Current scheduler index: {batch_state.current_scheduler_index}")
-
- # Try each scheduler starting from the current index
- for i in range(num_schedulers):
- idx = (batch_state.current_scheduler_index + i) % num_schedulers
- scheduler_url = settings.SCHEDULER_URLS[idx]
- logger.debug(f"Trying scheduler {idx}: {scheduler_url}")
+ current_time = time.time()
+
+ # Get list of online schedulers in stable order
+ online_schedulers = []
+ for scheduler_uuid in scheduler_order:
+ if scheduler_uuid in discovered_schedulers:
+ scheduler_info = discovered_schedulers[scheduler_uuid]
+ # Consider online if status is online and seen within last 120 seconds (more lenient)
+ # This prevents schedulers from being marked offline too quickly
+ if (scheduler_info['status'] == 'online' and
+ (current_time - scheduler_info['last_seen']) < 120.0):
+ online_schedulers.append(scheduler_uuid)
+
+ num_online = len(online_schedulers)
+ if num_online == 0:
+ logger.error("No online schedulers found!")
+ return None
+
+ logger.debug(f"Found {num_online} online schedulers out of {len(scheduler_order)} total")
+ logger.debug(f"Current round-robin index: {next_scheduler_index}")
+
+ # Try schedulers starting from current index
+ for i in range(num_online):
+ # Calculate index in the online schedulers list
+ idx = (next_scheduler_index + i) % num_online
+ scheduler_uuid = online_schedulers[idx]
+ scheduler_topic = discovered_schedulers[scheduler_uuid]['topic']
+
+ logger.debug(f"Trying scheduler {idx}: {scheduler_uuid} -> {scheduler_topic}")
- # Quick check if scheduler is available
- is_available = await check_scheduler_availability(scheduler_url)
- batch_state.scheduler_health[scheduler_url] = is_available
+ # Check if scheduler is available (based on heartbeat)
+ is_available = await check_scheduler_availability(scheduler_topic)
if is_available:
- # Update the current index for next time
- batch_state.current_scheduler_index = (idx + 1) % num_schedulers
- logger.info(f"Selected active scheduler: {scheduler_url}")
- return scheduler_url
+ # Update the round-robin index for next time
+ # We increment by 1, not by the number of schedulers we checked
+ next_scheduler_index = (next_scheduler_index + 1) % len(scheduler_order)
+ logger.info(f"Selected scheduler: {scheduler_uuid} (round-robin index: {next_scheduler_index})")
+ return scheduler_topic
else:
- logger.warning(f"Scheduler {scheduler_url} is DOWN or not responding. Skipping to next scheduler.")
-
- # If we get here, no active schedulers were found
- logger.error("No active schedulers found!")
+ logger.warning(f"Scheduler {scheduler_uuid} is DOWN. Skipping to next scheduler.")
+
+ # If we get here, no available schedulers were found
+ logger.error("No available schedulers found!")
return None
async def process_batch():
- """Process the current batch and send to the next active scheduler if ILP is done"""
+ """Process the current batch and send to scheduler via MQTT"""
global ilp_state
logger.debug(f"process_batch called, current ILP state: {ilp_state}")
- # Check if ILP is in progress - if so, we need to wait
if ilp_state == "progress":
logger.debug("ILP is in progress. Waiting to process batch...")
return
@@ -326,20 +482,17 @@ async def process_batch():
logger.debug("No batch to process (batch is empty)")
return
- # Create a copy of the current batch
batch_to_send = batch_state.current_batch.copy()
logger.info(f"Processing batch with {len(batch_to_send)} requests")
- # Clear the current batch
batch_state.current_batch = []
batch_state.last_batch_time = time.time()
# Find an active scheduler
- scheduler_url = await get_next_active_scheduler()
+ scheduler_topic = await get_next_active_scheduler()
- if scheduler_url is None:
+ if scheduler_topic is None:
logger.error("No active schedulers available! Keeping batch in memory.")
- # Put the batch back
async with batch_state.lock:
batch_state.current_batch = batch_to_send
return
@@ -348,31 +501,76 @@ async def process_batch():
ilp_state = "progress"
logger.info("Setting ILP state to 'progress' before sending batch")
- # Send the batch to the scheduler
+ # Generate correlation ID
+ correlation_id = str(uuid.uuid4())
+ lb_id = get_loadbalancer_id()
+
+ # Prepare MQTT message with prefix pattern
+ mqtt_payload = {
+ 'correlation_id': correlation_id,
+ 'loadbalancer_id': lb_id,
+ 'batch_data': {"requests": batch_to_send}
+ }
+
+ # Store pending response
+ pending_responses[correlation_id] = None
+
try:
- async with httpx.AsyncClient() as client:
- response = await client.post(
- scheduler_url,
- json={"requests": batch_to_send},
- timeout=10.0, # 10 second timeout for batch processing
- headers={
- "Accept": "*/*",
- "User-Agent": "Thunder Client (https://www.thunderclient.com)",
- "Content-Type": "application/json"
- }
- )
- logger.info(f"Sent batch of {len(batch_to_send)} requests to {scheduler_url}, status: {response.status_code}")
+ # Publish to scheduler-specific topic with BATCH_REQUEST prefix
+ message = "BATCH_REQUEST:" + json.dumps(mqtt_payload)
+ mclient.publish(
+ topic=scheduler_topic,
+ payload=message,
+ qos=2
+ )
+ logger.info(f"Sent batch of {len(batch_to_send)} requests to {scheduler_topic} via MQTT")
+
+ # Wait for response (with timeout)
+ timeout = 10.0
+ start_time = time.time()
+ while pending_responses[correlation_id] is None:
+ if time.time() - start_time > timeout:
+ logger.error(f"Timeout waiting for scheduler response from {scheduler_topic}")
+
+ # Handle scheduler failure with failure counting
+ scheduler_uuid = scheduler_topic.replace("SCHEDULER_", "")
+ handle_scheduler_failure(scheduler_uuid, "timeout")
+
+ # Reset ILP state and retry
+ ilp_state = "done"
+ del pending_responses[correlation_id]
+
+ # Put batch back and try again
+ async with batch_state.lock:
+ batch_state.current_batch = batch_to_send + batch_state.current_batch
+ await process_batch()
+ return
+
+ await asyncio.sleep(0.1)
+
+ # Got response
+ response = pending_responses[correlation_id]
+ del pending_responses[correlation_id]
+ logger.info(f"Received response from {scheduler_topic}: {response}")
+
+ # Handle successful response
+ scheduler_uuid = scheduler_topic.replace("SCHEDULER_", "")
+ handle_scheduler_success(scheduler_uuid)
+
except Exception as e:
- logger.error(f"Error sending batch to {scheduler_url}: {e}")
- logger.warning(f"Scheduler {scheduler_url} is DOWN")
+ logger.error(f"Error sending batch to {scheduler_topic} via MQTT: {e}")
+ logger.warning(f"Scheduler {scheduler_topic} encountered error")
- # Mark this scheduler as unhealthy
- async with batch_state.lock:
- batch_state.scheduler_health[scheduler_url] = False
+ # Handle scheduler failure with failure counting
+ scheduler_uuid = scheduler_topic.replace("SCHEDULER_", "")
+ handle_scheduler_failure(scheduler_uuid, f"exception: {str(e)}")
- # Reset ILP state back to "done" since our attempt failed
+ # Reset ILP state
ilp_state = "done"
- logger.info("Reset ILP state to 'done' due to failed batch send")
+
+ # Clean up pending response if exists
+ if correlation_id in pending_responses:
+ del pending_responses[correlation_id]
# Try again with a different scheduler
async with batch_state.lock:
@@ -484,17 +682,35 @@ async def run_service(request: Request, background_tasks: BackgroundTasks):
@app.get("/status")
async def get_status():
"""Get current status of the load balancer"""
+ current_time = time.time()
+
+ # Get online schedulers
+ online_schedulers = []
+ for scheduler_uuid in scheduler_order:
+ if scheduler_uuid in discovered_schedulers:
+ scheduler_info = discovered_schedulers[scheduler_uuid]
+ if (scheduler_info['status'] == 'online' and
+ (current_time - scheduler_info['last_seen']) < 60.0):
+ online_schedulers.append({
+ 'uuid': scheduler_uuid,
+ 'topic': scheduler_info['topic'],
+ 'last_seen': scheduler_info['last_seen'],
+ 'order_index': scheduler_info['order_index']
+ })
+
async with batch_state.lock:
return {
"current_batch_size": len(batch_state.current_batch),
"batch_age_seconds": time.time() - batch_state.last_batch_time,
- "scheduler_health": batch_state.scheduler_health,
- "current_scheduler_index": batch_state.current_scheduler_index,
+ "discovered_schedulers": len(discovered_schedulers),
+ "online_schedulers": len(online_schedulers),
+ "next_scheduler_index": next_scheduler_index,
+ "scheduler_order": scheduler_order,
+ "online_scheduler_details": online_schedulers,
"ilp_state": ilp_state,
"config": {
"batch_size": settings.BATCH_SIZE,
- "batch_timeout": settings.BATCH_TIMEOUT_SECONDS,
- "scheduler_count": len(settings.SCHEDULER_URLS)
+ "batch_timeout": settings.BATCH_TIMEOUT_SECONDS
}
}
diff --git a/provider/provider1.py b/provider/provider1.py
index 351018a..e49f4de 100644
--- a/provider/provider1.py
+++ b/provider/provider1.py
@@ -120,28 +120,39 @@ def on_connect(mqtt_client, userdata, flags, rc, callback_api_version):
def process_dockernotrun_request(data):
global pending_jobs
+ print(f"[DEBUG] process_dockernotrun_request started for job_id: {data.get('job_id', 'unknown')}")
+
with pending_jobs_lock:
pending_jobs += 1
print(f"Pending jobs incremented: {pending_jobs}")
try:
+ print(f"[DEBUG] Processing job with runMultipleInvocations: {data.get('runMultipleInvocations', False)}")
if(data['runMultipleInvocations'] == True):
if(data['numberOfInvocations'] == 1) :
+ print(f"[DEBUG] Single invocation, calling on_request")
on_request(data)
elif(data['isChained'] == False):
+ print(f"[DEBUG] Multiple invocations (not chained), calling on_request {data['numberOfInvocations']} times")
for i in range(data['numberOfInvocations']):
container_name = str(data['job_id']) + "_container_" + str(i)
on_request(data)
else:
+ print(f"[DEBUG] Chained invocations, calling on_chained_request")
on_chained_request(data)
else:
+ print(f"[DEBUG] Single job, calling on_request")
on_request(data)
+
+ print(f"[DEBUG] Job processing completed successfully for job_id: {data.get('job_id', 'unknown')}")
except Exception as e:
+ print(f"[DEBUG] Exception in process_dockernotrun_request: {str(e)}")
print(str(e))
finally:
with pending_jobs_lock:
pending_jobs -= 1
print(f"Pending jobs decremented: {pending_jobs}")
+ print(f"[DEBUG] process_dockernotrun_request finished for job_id: {data.get('job_id', 'unknown')}")
def on_message(mqtt_client, userdata, msg):
print(f'=== MQTT MESSAGE RECEIVED ===')
@@ -251,7 +262,19 @@ def append_data_to_file(data, filename):
def load_data_from_file(filename):
with open(filename, 'r') as file:
data = [json.loads(line.strip()) for line in file]
- return data #returns a list
+
+ # Clean the data by removing entries with 'DID NOT RECIEVE' values
+ cleaned_data = []
+ for item in data:
+ # Check if any value contains 'DID NOT RECIEVE'
+ has_invalid_data = any('DID NOT RECIEVE' in str(value) for value in item.values())
+ if not has_invalid_data:
+ cleaned_data.append(item)
+ else:
+ print(f"[DEBUG] Skipping corrupted training data entry: {item}")
+
+ print(f"[DEBUG] Loaded {len(data)} entries, cleaned to {len(cleaned_data)} valid entries")
+ return cleaned_data #returns a list
# Function to save the trained model to disk
def save_model(model, filename):
@@ -266,30 +289,87 @@ def load_model(filename):
def train_regression_model(training_data):
+ print(f"[DEBUG] Training data length: {len(training_data)}")
+ if len(training_data) > 0:
+ print(f"[DEBUG] First training data sample: {training_data[0]}")
+ print(f"[DEBUG] Data types in first sample:")
+ for key, value in training_data[0].items():
+ print(f" {key}: {type(value)} = {value}")
+
X = []
y = []
- for data in training_data:
- X.append([data["cpu_usage"] * data["cpu_efficiency_score"],
- data["memory_usage"] * data["memory_efficiency_score"]])
- y.append(data["actual_runtime"])
-
+ for i, data in enumerate(training_data):
+ try:
+ # Convert to float to ensure numeric values
+ cpu_usage = float(data["cpu_usage"])
+ memory_usage = float(data["memory_usage"])
+ cpu_eff = float(data["cpu_efficiency_score"])
+ memory_eff = float(data["memory_efficiency_score"])
+ runtime = float(data["actual_runtime"])
+
+ X.append([cpu_usage * cpu_eff, memory_usage * memory_eff])
+ y.append(runtime)
+ print(f"[DEBUG] Sample {i}: cpu={cpu_usage}, mem={memory_usage}, runtime={runtime}")
+ except (ValueError, TypeError, KeyError) as e:
+ print(f"[DEBUG] Error processing training sample {i}: {e}")
+ print(f"[DEBUG] Problematic data: {data}")
+ # Skip samples with 'DID NOT RECIEVE' or other invalid data
+ if 'DID NOT RECIEVE' in str(data.values()):
+ print(f"[DEBUG] Skipping sample with 'DID NOT RECIEVE' data")
+ continue
+
+ if len(X) == 0:
+ print("[DEBUG] No valid training data found, returning dummy model")
+ # Return a dummy model that predicts 1000ms for any input
+ class DummyModel:
+ def predict(self, X):
+ return np.array([1000.0] * len(X))
+ return DummyModel()
+
+ print(f"[DEBUG] Training model with {len(X)} samples")
model = LinearRegression()
model.fit(X, y)
return model
def predict_runtime(service, provider, model):
+ print(f"[DEBUG] predict_runtime called with service: {service}")
+
+ try:
+ ref_service_list = load_data_from_file("TrainingData/Reference_Provider_Data.txt")
+ print(f"[DEBUG] Reference service list length: {len(ref_service_list)}")
+
+ reference_cpu_usage = None
+ reference_memory_usage = None
+
+ for item in ref_service_list:
+ if(item['service']==service):
+ reference_cpu_usage = float(item['cpu_usage'])
+ reference_memory_usage = float(item['memory_usage'])
+ print(f"[DEBUG] Found reference data: cpu={reference_cpu_usage}, mem={reference_memory_usage}")
+ break
+
+ if reference_cpu_usage is None:
+ print(f"[DEBUG] No reference data found for service {service}, using defaults")
+ reference_cpu_usage = 1000.0 # Default CPU usage
+ reference_memory_usage = 1000.0 # Default memory usage
+
+ global cpu_efficiency_score, memory_efficiency_score
+ print(f"[DEBUG] Efficiency scores: cpu={cpu_efficiency_score}, mem={memory_efficiency_score}")
- ref_service_list = load_data_from_file("TrainingData/Reference_Provider_Data.txt")
- for item in ref_service_list:
- if(item['service']==service):
- reference_cpu_usage=item['cpu_usage']
- reference_memory_usage=item['memory_usage']
- break
- global cpu_efficiency_score, memory_efficiency_score
-
- # For training in scheduler, instead of globals use provider.cpu_efficiency_score and provider.memory_efficiency_score
- X = np.array([[reference_cpu_usage * cpu_efficiency_score, reference_memory_usage * memory_efficiency_score]])
- return model.predict(X)
+ # For training in scheduler, instead of globals use provider.cpu_efficiency_score and provider.memory_efficiency_score
+ X = np.array([[reference_cpu_usage * float(cpu_efficiency_score), reference_memory_usage * float(memory_efficiency_score)]])
+ print(f"[DEBUG] Input features X: {X}")
+
+ prediction = model.predict(X)
+ print(f"[DEBUG] Model prediction: {prediction}")
+ return prediction
+
+ except Exception as e:
+ print(f"[DEBUG] Error in predict_runtime: {e}")
+ import traceback
+ traceback.print_exc()
+ # Return a default prediction
+ return np.array([1000.0])
def trainAndPredict(run_vars):
@@ -297,12 +377,26 @@ def trainAndPredict(run_vars):
#It also has service (task link) (to get corresponding reference stats), eff_scores for training+prediction the ones which we use in this function
#TRAINING
print("running predictions inside trainAndPredict")
- training_data=load_data_from_file("TrainingData/eff_score_data.txt")
- model = train_regression_model(training_data)
- #PREDICTION
- provider_id = 0 # this provider would be used if this training and prediction were to run in the scheduler. Here it is useless as we use globals.
- predicted_runtime = predict_runtime(run_vars['service'], provider_id, model)
- return predicted_runtime[0]
+ print(f"[DEBUG] run_vars: {run_vars}")
+
+ try:
+ training_data=load_data_from_file("TrainingData/eff_score_data.txt")
+ print(f"[DEBUG] Loaded training data from file")
+ model = train_regression_model(training_data)
+ print(f"[DEBUG] Model trained successfully")
+
+ #PREDICTION
+ provider_id = 0 # this provider would be used if this training and prediction were to run in the scheduler. Here it is useless as we use globals.
+ predicted_runtime = predict_runtime(run_vars['service'], provider_id, model)
+ print(f"[DEBUG] Prediction completed: {predicted_runtime}")
+ return predicted_runtime[0]
+
+ except Exception as e:
+ print(f"[DEBUG] Error in trainAndPredict: {e}")
+ import traceback
+ traceback.print_exc()
+ # Return a default prediction
+ return 1000.0
def run_docker(body, container_name, inputData=None):
@@ -398,18 +492,56 @@ def run_docker(body, container_name, inputData=None):
def monitor_container(cont, start_run_time, timeout):
stack = []
count = 0
+ print(f"[DEBUG] monitor_container started for container: {cont.name if cont else 'None'}")
+
while(str(cont.status)=='created'):
cont.reload()
+ print(f"[DEBUG] Container status: {cont.status}")
+ time.sleep(0.5) # Wait for container to start
+
while ((cont != None) and ((str(cont.status) == 'running') )):
if(time.time()-start_run_time > timeout):
print("timeout exceeded (cont not killed)")
+ # Force kill the container if it's been running too long
+ try:
+ cont.kill()
+ print(f"[DEBUG] Container killed due to timeout")
+ except Exception as e:
+ print(f"[DEBUG] Error killing container: {e}")
break
s = cont.stats(decode=False, stream=False)
+ print(f"[DEBUG] Container stats - memory_stats empty: {s['memory_stats'] == {}}")
if(s['memory_stats'] != {}):
stack.clear()
stack.append(s)
- else: break
+ print(f"[DEBUG] Added stats to stack, stack length: {len(stack)}")
+ else:
+ print(f"[DEBUG] Memory stats empty, but continuing monitoring (container may still be starting)")
+ # Don't break immediately - container might still be starting up
+ # Only break if we've been monitoring for a while and still no stats
+ if count > 5: # After 10+ seconds of no stats, then break
+ print(f"[DEBUG] No memory stats after {count} checks, breaking monitoring loop")
+ break
+
+ # Always try to get stats, even if memory_stats is empty
+ # This ensures we capture stats when the container exits
+ if not stack: # Only add if stack is empty
+ stack.append(s)
+ print(f"[DEBUG] Added stats to stack (even with empty memory_stats), stack length: {len(stack)}")
count+=1
+
+ # Add a delay to prevent excessive CPU usage and allow container to finish
+ time.sleep(2) # Check every 2 seconds instead of continuously
+
+ # Reload container status to check if it's still running
+ try:
+ cont.reload()
+ print(f"[DEBUG] Container status check: {cont.status}")
+ except Exception as e:
+ print(f"[DEBUG] Error reloading container: {e}")
+ break
+
+ print(f"[DEBUG] monitor_container finished, returning stack with length: {len(stack)}")
return stack
def get_docker_host_ip():
@@ -448,141 +580,309 @@ def get_docker_host_ip():
return '10.1.19.76'
def run_and_invoke_docker(body, container_name) -> dict:
-
- print("[run_and_invoke_docker]")
- #open a file and write the payload to it
- #with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
- # json.dump(payload, f)
- # f.flush()
- # input_file = f.name
-
- # Create output file
- #output_file = tempfile.NamedTemporaryFile(delete=False).name
-
- # Mount configurations for both input and output files
- #mounts = {
- # input_file: {'bind': '/tmp/input.json', 'mode': 'ro'},
- # output_file: {'bind': '/tmp/output.json', 'mode': 'rw'}
- #}
-
- start_pull_time = time.time()
- #image = client.images.pull(body)
- print("inside run_and_invoke_docker with body : " + body)
- image = imagePuller.request_image(body)
- print("Out of Hybrid Caching manager and inside run_and_invoke_docker again")
- print(image)
- pull_time = int((time.time() - start_pull_time) *1000)
-
- start_run_time = time.time()
- cont = None
- benchmark_no=body.split("/")[1].split(".")[1] # get number from peercompute/benchmark.010....
- payload=get_payload(benchmark_no, "large")
- # Temporarily override payload with a fixed value
-
- print(payload)
- response = None
- future=None
try:
- print("container started running")
- cont = client.containers.run(image,
- name=container_name,
- detach=True,
- ports={'8080/tcp': None}, #None dynamically allocates a port
- environment={
- 'AWS_ACCESS_KEY_ID': 'AKIA3KAG6W36BSXOEHWD',
- 'AWS_SECRET_ACCESS_KEY': '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',
- 'AWS_REGION': 'ap-south-1'
- }
- )
+ print(f"[DEBUG] run_and_invoke_docker started with body: {body}, container_name: {container_name}")
+ #open a file and write the payload to it
+ #with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
+ # json.dump(payload, f)
+ # f.flush()
+ # input_file = f.name
+
+ # Create output file
+ #output_file = tempfile.NamedTemporaryFile(delete=False).name
+
+ # Mount configurations for both input and output files
+ #mounts = {
+ # input_file: {'bind': '/tmp/input.json', 'mode': 'ro'},
+ # output_file: {'bind': '/tmp/output.json', 'mode': 'rw'}
+ #}
+
+ start_pull_time = time.time()
+ #image = client.images.pull(body)
+ print("inside run_and_invoke_docker with body : " + body)
+ print(f"[DEBUG] Requesting image: {body}")
+ image = imagePuller.request_image(body)
+ print("Out of Hybrid Caching manager and inside run_and_invoke_docker again")
+ print(f"[DEBUG] Image obtained: {image}")
+ pull_time = int((time.time() - start_pull_time) *1000)
+ print(f"[DEBUG] Image pull time: {pull_time}ms")
- # Wait a bit for container to start
- time.sleep(1)
- cont.reload() # Refresh container data
- port_info = cont.ports.get('8080/tcp')
- host_port = port_info[0]['HostPort'] #get the port
- print("container name ID: ", cont.id)
- print("container name: ", cont.name)
- # Make POST request to container # blocking
+ start_run_time = time.time()
+ cont = None
+ # Safely parse benchmark number from task_link
+ try:
+ benchmark_no=body.split("/")[1].split(".")[1] # get number from peercompute/benchmark.010....
+ payload=get_payload(benchmark_no, "large")
+ except (IndexError, AttributeError):
+ # Fallback for simple task names like "hello-world"
+ print(f"[DEBUG] Could not parse benchmark number from '{body}', using simple payload")
+ payload = {"message": "Hello from simple task", "input": "test"} # Simple payload for basic containers
+ # Temporarily override payload with a fixed value
- except Exception as e:
- print(e)
-
- finally:
- print(body)
- timeout = 3000
- print("monitoring container")
- with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor_for_cont_monitoring:
- # Submit the monitoring task to the executor
- future = executor_for_cont_monitoring.submit(monitor_container, cont, start_run_time, timeout)
- print("container monitored")
+ print(payload)
+ response = None
+ future=None
+ try:
+ print("container started running")
+ print(f"[DEBUG] Creating container with name: {container_name}")
+ cont = client.containers.run(image,
+ name=container_name,
+ detach=True,
+ ports={'8080/tcp': None}, #None dynamically allocates a port
+ environment={
+ 'AWS_ACCESS_KEY_ID': 'AKIA3KAG6W36BSXOEHWD',
+ 'AWS_SECRET_ACCESS_KEY': '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',
+ 'AWS_REGION': 'ap-south-1'
+ }
+ )
+ print(f"[DEBUG] Container created successfully: {cont.id}")
- # Get the appropriate host IP for container communication
- host_ip = get_docker_host_ip()
- print(f"Using host IP: {host_ip}")
+ # Wait a bit for container to start
+ time.sleep(2) # Increased wait time
+ cont.reload() # Refresh container data
+ print(f"[DEBUG] Container reloaded, status: {cont.status}")
- response = requests.post(f'http://{host_ip}:{host_port}',
- json=payload,
- headers={'Content-Type': 'application/json'},
- timeout=30) # Increased timeout to 5 minutes (300 seconds)
- print("post request sent")
-
- #result = "this is result" #remove this line uncomment below line
- #result = result.decode("utf-8") #this gives the Hello from Docker msg.
-
- stack=future.result()
- run_vars={}
- # Read result from output file
- #with open(output_file, 'r') as f:
- # result = f.read()
- #print("Result from container:", result)
- #print(response.json())
- result = response.json()
- print(result)
- print(stack) #uncomment this to get full stats
- run_time = int((time.time() - start_run_time)*1000) # get in ms
- #print(count)
- # run_vars['time_indexed_stats'] = time_indexed_stats
- run_vars['memory_usage'] = stack[0]['memory_stats']['usage']
- run_vars['cpu_usage'] = stack[0]['cpu_stats']['cpu_usage']['total_usage']
- #adding new lines for io_usage
- # blkio_read=0
- # blkio_write=0
- # for entry in stack[0]['blkio_stats']['io_service_bytes_recursive']:
- # if entry['op'] == 'Read':
- # blkio_read += entry['value']
- # elif entry['op'] == 'Write':
- # blkio_write += entry['value']
- # run_vars['io_read_stats'] = blkio_read
- # run_vars['io_write_stats'] = blkio_write
- #updated code till here
- run_vars['actual_runtime'] = run_time
- global cpu_efficiency_score
- run_vars['cpu_efficiency_score'] = cpu_efficiency_score
- global memory_efficiency_score
- run_vars['memory_efficiency_score'] = memory_efficiency_score
- # the below is service specific and has to be made for each service.
- append_data_to_file(run_vars, 'TrainingData/eff_score_data.txt')
- run_vars['service']=body # this is the task link
- print("runtime data: ")
- print(run_vars)
- print("Predicted Runtime:")
- print(trainAndPredict(run_vars))
- #print(predict_runtime(model, run_vars['time_indexed_stats'])) #a list of stats with timestamps
- print("Actual Runtime " + str(run_time))
- # Plot real-time predictions
- #plot_predictions(predictions)
+ # Check if container is actually running
+ if cont.status != 'running':
+ print(f"[DEBUG] ERROR: Container is not running! Status: {cont.status}")
+ # Try to get container logs to see what happened
+ try: