-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpi-agent-v1.10.7.py
3787 lines (3303 loc) · 161 KB
/
pi-agent-v1.10.7.py
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
from flask import Flask, request, send_file, make_response, json #pip3 install flask
from waitress import serve #pip3 install waitress
import requests #pip3 install requests
import threading
import logging
import datetime
import time
import math
#Pi Monitor
import psutil
import numpy as np
import statistics #for using satistics.mean() #numpy also has mean()
import re
import copy
import RPi.GPIO as GPIO
from pijuice import PiJuice #sudo apt-get install pijuice-gui
from bluetooth import * #sudo apt-get install bluetooth bluez libbluetooth-dev && sudo python3 -m pip install pybluez
# sudo systemctl start bluetooth
# echo "power on" | bluetoothctl
import random
import socket
import os #file path
import shutil #empty a folder
#setup file exists?
dir_path=os.path.dirname(os.path.realpath(__file__))
if os.path.exists(dir_path + "/setup.py"): import setup
if os.path.exists(dir_path + "/excel_writer.py"): import excel_writer # pip3 install pythonpyxl
from os.path import expanduser #get home directory by home = expanduser("~")
app = Flask(__name__)
app.config["DEBUG"] = True
#config
node_name=socket.gethostname()
node_role="" #MONITOR #LOAD_GENERATOR #STANDALONE #MASTER
def set_ip():
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
actual_ip=s.getsockname()[0]
s.close()
return actual_ip
node_IP=set_ip()
gateway_IP="10.0.0.90" #??? set individually
peers=[]
test_index = 0
test_updates ={}
epoch = 0
test_name = socket.gethostname() + "_test"
workers = []
functions = []
history = {'functions':{}, 'workers': {}}
metrics = {}
debug=False
waitress_threads = 6 # default is 4
#get home directory
home = expanduser("~")
log_path = home + "/" + test_name
if not os.path.exists(log_path):
os.makedirs(log_path)
bluetooth_addr = "00:15:A3:00:52:2B"
#master: #00:15:A3:00:52:2B #w1: 00:15:A3:00:68:C4 #w2: 00:15:A5:00:03:E7 #W3: 00:15:A5:00:02:ED #w4: 00:15:A3:00:19:A7 #w5: 00:15:A3:00:5A:6F
pics_folder = "/home/pi/pics/"
pics_num = 170 #pics name "pic_#.jpg"
file_storage_folder = "/home/pi/storage/"
if not os.path.exists(file_storage_folder):
os.makedirs(file_storage_folder)
#settings
#[0]app name
#[1] run/not
#[2] w type: "static" or "poisson" or "exponential" or "exponential-poisson"
#[3] workload: [[0]iteration
#[1]interval/exponential lambda(10=avg 8s)
#[2]concurrently/poisson lambda (15=avg 17reqs ) [3] random seed (def=5)]
#[4] func_name [5] func_data [6] created [7] recv
#[8][min,max,requests,limits,env.counter, env.redisServerIp, env,redisServerPort,
#read,write,exec,handlerWaitDuration,linkerd,queue,profile
apps=[]
usb_meter_involved = False
#Either battery_operated or battery_cfg should be True, if the second, usb meter needs enabling
battery_operated=False
#Battery simulation
#1:max,2:initial #3current SoC,
#4: renewable type, 5:poisson seed&lambda,6:dataset, 7:interval, 8 dead charge
battery_cfg=[True, 906,906, 906,"poisson",[5,5], [], 30, 90]
#NOTE: apps and battery_cfg values change during execution
down_time = 0
time_based_termination= [False, 3600]
snapshot_report=['False', '200', '800'] #begin and end time
max_request_timeout = 30
min_request_generation_interval = 0
sensor_admission_timeout = 3
monitor_interval=1
failure_handler_interval = 3
scheduling_interval=600
overlapped_allowed= True
max_cpu_capacity=4000
boot_up_delay = 0
raspbian_upgrade_error= False #True, if psutil io_disk error due to upgrade
#controllers
test_started = None
test_finished = None
under_test=False
lock = threading.Lock()
actuations = 0
sock = None #bluetooth connection
sensor_log ={}
suspended_replies = []
#monitoring parameters
#in owl_actuator
response_time = []
#in pi_monitor
response_time_accumulative = []
current_time = []
current_time_ts = []
battery_charge = []
cpuUtil = []
cpu_temp = []
cpu_freq_curr=[]
cpu_freq_max=[]
cpu_freq_min=[]
cpu_ctx_swt = []
cpu_inter = []
cpu_soft_inter=[]
memory = []
disk_usage = []
disk_io_usage = []
bw_usage = []
power_usage = []
throughput=[]
throughput2=[]
if battery_operated:
relay_pin = 20
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
pijuice = PiJuice(1, 0x14)
def launcher(coordinator):
global logger
global node_name
global node_IP
logger.info('start')
#set plan for coordinator itself.
name=coordinator[1]
ip=coordinator[2]
plan=setup.plan[name]
#config for multi-tests
plan["test_name"] = setup.test_name[epoch]
#set counter per app
plan["apps"][0][8][4]=setup.counter[epoch]["yolo3"]
plan["apps"][1][8][4]=setup.counter[epoch]["irrigation"]
plan["apps"][2][8][4]=setup.counter[epoch]["crop-monitor"]
plan["apps"][3][8][4]=setup.counter[epoch]["short"]
#verify node_name
if name!=node_name:
logger.error('MAIN: Mismatch node name: actual= ' + node_name + ' assigned= ' + name)
return 'Mismatch node name: actual= ' + node_name + ' assigned= ' + name
#verify assigned ip
if ip != node_IP:
logger.error('Mismatch node ip: actual= ' + node_IP + ' assigned= ' + ip)
return ""
sender=plan["node_role"] #used in sending plan to peers
logger.info(name + ' : ' + str(ip))
#set local plan
reply=pi_service('plan', 'INTERNAL', plan)
if reply != "success":
logger.error('INTERNAL interrupted and stopped')
return "failed"
reply_success=0
#set peers plan, sequentially, including USB Meter connection
for node in setup.nodes:
position=node[0]
name=node[1]
ip=node[2]
plan=setup.plan[name]
#config for multi-test
plan["test_name"] = setup.test_name[epoch]
#set counter per app
plan["apps"][0][8][4]=setup.counter[epoch]["yolo3"]
plan["apps"][1][8][4]=setup.counter[epoch]["irrigation"]
plan["apps"][2][8][4]=setup.counter[epoch]["crop-monitor"]
plan["apps"][3][8][4]=setup.counter[epoch]["short"]
if position is "PEER":
logger.info('peers:' + name + ': ' + str(ip))
try:
response=requests.post('http://'+ip+':5000/pi_service/plan/' + sender, json=plan)
except Exception as e:
logger.error('peers: failed for ' + name + ":" + ip)
logger.error('peers: exception:' + str(e))
return
if response.text=="success":
logger.info(name + ' reply: ' + 'success')
reply_success+=1
else:
logger.error('peers: request.text for ' + name + ' ' + str(response.text))
#verify peers reply
peers= len([node for node in setup.nodes if node[0]=="PEER"])
if reply_success== peers:
logger.info('all ' + str(peers) + ' nodes successful')
#run local pi_service on
logger.info('run all nodes pi_service')
#internal
thread_pi_service = threading.Thread(target= pi_service, args=('on', 'INTERNAL',))
thread_pi_service.name = "pi-service"
#it calls scheduler and deploys functions
thread_pi_service.start()
#wait for initial function deployment roll-out
logger.info('function roll out wait ' + str(setup.function_creation_roll_out) + 's')
time.sleep(setup.function_creation_roll_out)
#set peers on sequentially
reply_success=0
for node in setup.nodes:
position=node[0]
name=node[1]
ip=node[2]
if position is "PEER":
logger.info('pi_service on: peers:' + name + ': ' + str(ip))
try:
response=requests.post('http://'+ip+':5000/pi_service/on/' + sender)
except Exception as e:
logger.error('pi_service on: peers: failed for ' + name + ":" + ip)
logger.error('pi_service on: peers: exception:' + str(e))
if response.text=="success":
logger.info('pi_service on:' + name + ' reply: ' + 'success')
reply_success+=1
else:
logger.info('pi_service on:' + name + ' reply: ' + str(response.text))
#verify peers reply
peers= len([node for node in setup.nodes if node[0]=="PEER"])
if reply_success== peers:
logger.info('pi_service on: all ' + str(peers) + ' nodes successful')
else:
logger.info('pi_service on: only ' + str(reply_success) + ' of ' + str(peers))
else:
logger.info('failed: only ' + str(reply_success) + ' of ' + str(len(setup.nodes)))
logger.info('stop')
#scheduler
def scheduler():
global epoch
global under_test
global logger
global debug
global scheduling_interval
global node_role
global battery_cfg
global workers
global functions
global max_cpu_capacity
global log_path
global history
logger.info('start')
#initialize workers and funcitons lists
#default all functions' host are set to be placed locally
workers, functions = initialize_workers_and_functions(setup.nodes, workers, functions,
battery_cfg, setup.plan, setup.zones)
#history
history["functions"]={}
history["workers"]={}
logger.info('after initialize_workers_and_functions:\n'
+ '\n'.join([str(worker) for worker in workers]))
logger.info('after initialize_workers_and_functions:\n'
+ '\n'.join([str(function) for function in functions]))
scheduling_round = 0
while under_test:
scheduling_round +=1
logger.info('################################')
logger.info('MAPE LOOP START: round #' + str(scheduling_round))
#monitor: update Soc
logger.info('monitor: call')
workers = scheduler_monitor(workers, node_role)
#ANALYZE (prepare for new placements)
logger.info('analyzer: call')
#definitions
new_functions = copy.deepcopy(functions)
#reset F's new location to null
for new_function in new_functions:
new_function[1] = []
#reset nodes' capacity to max
for worker in workers:
worker[3] = setup.max_cpu_capacity
#planner :workers set capacity, functions set hosts
logger.info('planner: call: ' + str(setup.scheduler_name[epoch]))
#Greedy
if "greedy" in setup.scheduler_name[epoch]:
workers, functions = scheduler_planner_greedy(workers, functions, new_functions,
setup.plan, setup.zones, setup.warm_scheduler,
setup.sticky, setup.stickiness[epoch], setup.scale_to_zero, debug)
#Local
elif "local" in setup.scheduler_name[epoch]:
workers, functions = scheduler_planner_local(workers, new_functions, debug)
#Default-Kubernetes
elif "default" in setup.scheduler_name[epoch]:
workers, functions = scheduler_planner_default(workers, new_functions, debug)
#Random
elif "random" in setup.scheduler_name[epoch]:
workers, functions = scheduler_planner_random(workers, new_functions, debug)
#Bin-Packing
elif "bin-packing" in setup.scheduler_name[epoch]:
workers, functions = scheduler_planner_binpacking(workers, functions, new_functions, debug)
#Optimal
elif "optimal" in setup.scheduler_name[epoch]:
pass
else:
logger.error('scheduler_name not found' + str(setup.scheduler_name[epoch]))
return
#EXECUTE
logger.info('executor: call')
#translate hosts to profile and then run helm command
#return functions as it is modifying functions (i.e., profiles)
functions = scheduler_executor(functions, setup.profile_chart,
setup.profile_creation_roll_out,
setup.function_chart, scheduling_round, log_path,
setup.scheduler_name[epoch], workers, debug)
#history
history["functions"][scheduling_round] = copy.deepcopy(functions)
history["workers"][scheduling_round] = copy.deepcopy(workers)
#sliced interval in 1 minutes
logger.info('MAPE LOOP (round #' + str(scheduling_round) + ') done: sleep for ' + str(scheduling_interval) + ' sec...')
remained= scheduling_interval
minute=60
while remained>0:
if remained>=minute:
time.sleep(minute)
remained-=minute
if not under_test:
break
else:
time.sleep(remained)
remained=0
#save history
#scheduler clean_up???
logger.info('stop')
#??? functions are received for only getting old_hosts. Only old_hosts can be sent to this planner
def scheduler_planner_greedy(workers, functions, new_functions, nodes_plan, zones,
warm_scheduler, sticky, stickiness, scale_to_zero, debug):
global logger
logger.info("scheduler_planner_greedy:start")
logger.info('scheduler_planner_greedy:\n available Workers \n'
+ '\n'.join([str(worker) for worker in workers]))
zone_name = {1:'rich', 2:'poor', 3: 'vulnerable', 4: 'dead'}
#update zones
for worker in workers:
soc = worker[2]
battery_max_cap = nodes_plan[worker[0]]["battery_cfg"][1]
soc_percent = round(soc / battery_max_cap * 100)
logger.info('soc percent: ' + str(soc_percent))
new_zone = [*(zone[1] for zone in zones if soc_percent <= zone[2]
and soc_percent > zone[3])][0]
worker[4]= new_zone
logger.info('scheduler_planner_greedy:updated zones by Soc:\n'
+ '\n'.join([str(worker) for worker in workers]))
#sort nodes by soc (large->small | descending)
workers.sort(key=lambda x:x[2], reverse=True)
logger.info('before showing : ' + str(workers))
logger.info('scheduler_planner_greedy:sorted nodes by Soc (large->small):\n'
+ '\n'.join([str([worker,zone_name[worker[4]]]) for worker in workers]))
logger.info('after showing : ' + str(workers))
#sort functions: A: by priority of their owner's zone (small -> large | ascending)
for i in range (len(new_functions)):
lowest_value_index = i
for j in range(i + 1, len(new_functions)):
#find function's owner zone
zone_j = [*(worker[4] for worker in workers if worker[0]==new_functions[j][0][0])][0]
zone_lowest_value_index = [*(worker[4] for worker in workers if worker[0]==new_functions[lowest_value_index][0][0])][0]
#compare zone priorities
if zone_j < zone_lowest_value_index:
lowest_value_index = j
#swap
new_functions[i], new_functions[lowest_value_index] = new_functions[lowest_value_index], new_functions[i]
#end sort
logger.info('scheduler_planner_greedy:sorted functions by owner\'s zone priority (small->large):\n'
+ '\n'.join([str(new_function[0]) for new_function in new_functions]))
#B: sort functions in each zone (small to large for poor and vulnerable) opposite dead, for rich does not matter
for i in range(len(new_functions)):
lowest_value_index = i
largest_value_index = i
lowest, largest = False, False
zone_i = [*(worker[4] for worker in workers if worker[0]==new_functions[i][0][0])][0]
#rich or dead
if zone_i == 1 or zone_i == 4:
#largest first
largest =True
#poor or vulnerable
else: lowest = True
for j in range(i + 1, len(new_functions)):
#get function's owner zone
zone_j = [*(worker[4] for worker in workers if worker[0]==new_functions[j][0][0])][0]
zone_lowest_value_index = [*(worker[4] for worker in workers if worker[0]==new_functions[lowest_value_index][0][0])][0]
zone_largest_value_index = [*(worker[4] for worker in workers if worker[0]==new_functions[largest_value_index][0][0])][0]
if zone_j == zone_lowest_value_index: #similar to say ==largest_value_index
#get functions' owner soc
soc_j = [*(worker[2] for worker in workers if worker[0]==new_functions[j][0][0])][0]
soc_lowest_value_index = [*(worker[2] for worker in workers if worker[0]==new_functions[lowest_value_index][0][0])][0]
soc_largest_value_index = [*(worker[2] for worker in workers if worker[0]==new_functions[largest_value_index][0][0])][0]
#compare socs based on zones policy
#if rich or dead , large to small
if zone_largest_value_index == 1 or zone_largest_value_index == 4 :
if soc_j > soc_largest_value_index:
largest_value_index = j
#if poor or vulnerable, small to large
elif zone_lowest_value_index == 2 or zone_lowest_value_index == 3 :
if soc_j < soc_lowest_value_index:
lowest_value_index = j
#swap
if lowest:
index = lowest_value_index
else:
index = largest_value_index
new_functions[i], new_functions[index] = new_functions[index], new_functions[i]
logger.info('scheduler_planner_greedy:sorted functions by soc in zones (poor and vulnerable small to large. Rich and dead opposite):\n'
+ '\n'.join([str(new_function[0]) for new_function in new_functions]))
#so far, new_functions have [] as hosts, workers have full as capacity and both workers and new_functions are sorted now
logger.info("scheduler_planner_greedy: start planning hosts for functions by priority")
#PLAN
#set hosts per function
for new_function in new_functions:
#function's old_hosts: last placement scheme
old_hosts = copy.deepcopy([*(function[1] for function in functions if function[0]==new_function[0])][0])
#old_hosts have zone numbers and Soc based on last epoch and the hosts zone may have changed now, so update their zones based on new status
for index, old_host in enumerate(old_hosts):
#update host's zone, capacity and Soc based on current status
old_hosts[index] = [*(worker for worker in workers if worker[0]==old_host[0])][0]
logger.info('greedy: old_hosts\n' + str(old_hosts))
#function's owner
owner = [*(worker for worker in workers if worker[0]==new_function[0][0])][0]
func_required_cpu_capacity = 0
#exclude 'm'
replica_cpu_limits = int(new_function[2][3].split('m')[0])
func_max_replica = new_function[2][1]
func_required_cpu_capacity = replica_cpu_limits * func_max_replica
owner_zone = owner[4]
logger.info('greedy: planning for *** ' + str(new_function[0][0]) + '-'
+ str(new_function[0][1])+ ' *** ')
#try to fill new hosts for new_function
new_hosts = []
#if new_function belongs to a rich node
if owner_zone == 1:
#place locally
logger.info('greedy: ' + owner[0] + '-' + new_function[0][1] + ' ---> locally')
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(owner))
#if poor, vulnerable or dead
else:
#if offloading
#if setup.offloading == True:
#if owners is dead, only offload if warm_scheduler is True; also if owner is poor or vulnerable, do the offloading
if not (owner_zone == 4 and warm_scheduler == False):
#Get rich and vulnerable (if the func is not vulnerable) workers
volunteers = [*(worker for worker in workers if worker[4] == 1
or (worker[4]==3 and owner_zone != 3))]
logger.info('greedy: call offloader: volunteers \n'
+ '\n'.join([str(volunteer) for volunteer in volunteers]))
new_hosts = offloader(workers, functions, volunteers, new_function, sticky, stickiness,
old_hosts, warm_scheduler,owner, func_max_replica,
func_required_cpu_capacity, scale_to_zero, debug)
# if not offloading was possible for fonctions owned by poor, vulnerable and dead nodes
if new_hosts == []:
#place locally
logger.info('greedy: ' + owner[0] + '-' + new_function[0][1] + ' ---> locally')
#how about functions belong to a dead node??? they are still scheduled locally
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(owner))
#deduct function cpu requirement from worker's cpu capacity
for new_host in new_hosts:
#get selected worker index per replica
index = workers.index([*(worker for worker in workers if worker[0]==new_host[0])][0])
#deduct replica cpu requirement
workers[index][3] -= replica_cpu_limits
#update new_host, particulalrly its capacity
new_host[3]= workers[index][3]
#set new_function new hosts
new_function[1] = new_hosts
if debug: logger.info("scheduler_planner_greedy: new_hosts for ("
+ new_function[0][0] + "-" + new_function[0][1] + "):\n" + str(new_function[1]))
#for loop: next new_function
#replacad original functions with new_functions to apply new_hosts (placements)
#functions = new_functions
logger.info('scheduler_planner_greedy: done: functions:\n'
+ '\n'.join([str(new_function) for new_function in new_functions]))
return workers, new_functions
#??? functions are received for only getting old_hosts. Only old_hosts can be sent to this planner
def scheduler_planner_binpacking(workers, functions, new_functions, debug):
global logger
logger.info("scheduler_planner_binpacking:start")
logger.info('scheduler_planner_binpacking:\n available Workers \n'
+ '\n'.join([str(worker) for worker in workers]))
#sort nodes by soc (large->small | descending)
workers.sort(key=lambda x:x[2], reverse=True)
logger.info('scheduler_planner_binpacking:sorted nodes by Soc (large->small):\n'
+ str(workers))
#sort functions: by owner's soc (small -> large | ascending)
for i in range (len(new_functions)):
lowest_value_index = i
for j in range(i + 1, len(new_functions)):
#find function's owner soc
soc_j = [*(worker[2] for worker in workers if worker[0]==new_functions[j][0][0])][0]
soc_lowest_value_index = [*(worker[2] for worker in workers if worker[0]==new_functions[lowest_value_index][0][0])][0]
#compare socs
if soc_j < soc_lowest_value_index:
lowest_value_index = j
#swap
new_functions[i], new_functions[lowest_value_index] = new_functions[lowest_value_index], new_functions[i]
#end sort
logger.info('scheduler_planner_binpacking:sorted functions by owner\'s soc(small->large):\n'
+ '\n'.join([str(new_function[0]) for new_function in new_functions]))
#so far, new_functions have [] as hosts, workers have full as capacity and both workers and new_functions are sorted now
logger.info("scheduler_planner_binpacking: start planning hosts for functions by soc")
#PLAN
#set hosts per function
for new_function in new_functions:
#function's owner
owner = [*(worker for worker in workers if worker[0]==new_function[0][0])][0]
func_required_cpu_capacity = 0
#exclude 'm'
replica_cpu_limits = int(new_function[2][3].split('m')[0])
func_max_replica = new_function[2][1]
func_required_cpu_capacity = replica_cpu_limits * func_max_replica
logger.info('binpacking: planning for *** ' + str(new_function[0][0]) + '-'
+ str(new_function[0][1])+ ' *** \n Required_cpu_capacity: '
+ str(func_required_cpu_capacity))
#try to fill new hosts for new_function
new_hosts = []
#only functions belong to up nodes are scheduled. Those belong to dead nodes schedule locally
min_battery_charge = battery_cfg[8]
if owner[2] >= min_battery_charge:
#pick the first possible option
for index , worker in enumerate(workers):
#if node is up
if worker[2] >= min_battery_charge:
#if node has capacity
if worker[3] >= func_required_cpu_capacity:
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(worker))
#if set
if new_hosts != []:
break
#dead node, schedule locally
else:
logger.info('bin_packing: locally')
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(owner))
#deduct function cpu requirement from worker's cpu capacity
for new_host in new_hosts:
#get selected worker index per replica
index = workers.index([*(worker for worker in workers if worker[0]==new_host[0])][0])
#deduct replica cpu requirement
workers[index][3] -= replica_cpu_limits
#update new_host, particulalrly its capacity
new_host[3]= workers[index][3]
logger.info('bin_packing: after deduction: new_hosts: ' + str(new_hosts))
#set new_function new hosts
new_function[1] = new_hosts
if debug: logger.info("scheduler_planner_binpacking: new_hosts for ("
+ new_function[0][0] + "-" + new_function[0][1] + "):\n" + str(new_function[1]))
#for loop: next new_function
#replacad original functions with new_functions to apply new_hosts (placements)
#functions = new_functions
logger.info('scheduler_planner_binpacking: done: functions:\n'
+ '\n'.join([str(new_function) for new_function in new_functions]))
return workers, new_functions
#scheduler_planner_local
def scheduler_planner_local(workers, new_functions, debug):
global logger
logger.info("scheduler_planner_local:start")
#set hosts for new_functions and update workers capacity
logger.info('scheduler_planner_local:\n available Workers \n'
+ '\n'.join([str(worker) for worker in workers]))
#PLAN
#set hosts per function
for new_function in new_functions:
#function's owner
owner = [*(worker for worker in workers if worker[0]==new_function[0][0])][0]
#func required cpu capacity
func_required_cpu_capacity = 0
#exclude 'm'
replica_cpu_limits = int(new_function[2][3].split('m')[0])
func_max_replica = new_function[2][1]
func_required_cpu_capacity = replica_cpu_limits * func_max_replica
#try to fill new hosts for new_function
new_hosts = []
#place locally
#how about functions belong to a dead node??? they are still scheduled locally
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(owner))
#deduct function cpu requirement from worker's cpu capacity per replica
for new_host in new_hosts:
#get selected worker index
index = workers.index([*(worker for worker in workers if worker[0]==new_host[0])][0])
#deduct replica cpu requirement
workers[index][3] -= replica_cpu_limits
#apply worker's updated capacity to new_host as well
new_host[3]= workers[index][3]
#set new_function new hosts
new_function[1] = new_hosts
if debug: logger.info("scheduler_planner_local: new_hosts for ("
+ new_function[0][0] + "-" + new_function[0][1] + "):\n" + str(new_function[1]))
#for loop: next new_function
logger.info('scheduler_planner_local: all done: functions:\n'
+ '\n'.join([str(new_function) for new_function in new_functions]))
return workers, new_functions
#scheduler_planner_default
#provide all nodes for each function scheduling. Kubenretes does it by nodes' performance, only once.
#If a node is under pressure, kubernetes is free to reschedule any time.
def scheduler_planner_default(workers, new_functions, debug):
global logger
logger.info("scheduler_planner_default:start")
#set hosts for new_functions and update workers capacity
logger.info('scheduler_planner_default:\n available Workers \n'
+ '\n'.join([str(worker) for worker in workers]))
#PLAN
#set hosts per function
for new_function in new_functions:
#function's owner
owner = [*(worker for worker in workers if worker[0]==new_function[0][0])][0]
#func required cpu capacity
func_required_cpu_capacity = 0
#exclude 'm'
replica_cpu_limits = int(new_function[2][3].split('m')[0])
func_max_replica = new_function[2][1]
func_required_cpu_capacity = replica_cpu_limits * func_max_replica
#try to fill new hosts for new_function
new_hosts = []
#place anywhere you like Kubernetes
#how about functions belong to a dead node??? they are still scheduled
for worker in workers:
new_hosts.append(copy.deepcopy(worker))
#deduct function cpu requirement from worker's cpu capacity per replica
for new_host in new_hosts:
#get selected worker index
index = workers.index([*(worker for worker in workers if worker[0]==new_host[0])][0])
#deduct replica cpu requirement
workers[index][3] -= replica_cpu_limits
#apply worker's updated capacity to new_host as well
new_host[3]= workers[index][3]
#set new_function new hosts
new_function[1] = new_hosts
if debug: logger.info("scheduler_planner_default: new_hosts for ("
+ new_function[0][0] + "-" + new_function[0][1] + "):\n" + str(new_function[1]))
#for loop: next new_function
logger.info('scheduler_planner_default: all done: functions:\n'
+ '\n'.join([str(new_function) for new_function in new_functions]))
return workers, new_functions
#scheduler_planner_random
def scheduler_planner_random(workers, new_functions, debug):
global logger
logger.info("scheduler_planner_random:start")
#set hosts for new_functions and update workers capacity
logger.info('scheduler_planner_random:\n available Workers \n'
+ '\n'.join([str(worker) for worker in workers]))
#PLAN
#set hosts per function
for new_function in new_functions:
#function's owner
owner = [*(worker for worker in workers if worker[0]==new_function[0][0])][0]
#func required cpu capacity
func_required_cpu_capacity = 0
#exclude 'm'
replica_cpu_limits = int(new_function[2][3].split('m')[0])
func_max_replica = new_function[2][1]
func_required_cpu_capacity = replica_cpu_limits * func_max_replica
#try to fill new hosts for new_function
new_hosts = []
#place on a random node that has capacity
#how about functions belong to a dead node??? they are still scheduled
random_places = []
while random_places == []:
random_index = random.randint(0, len(workers)-1) #0 to 5
#has enough capacity for all function replicas?
if workers[random_index][3] >= func_required_cpu_capacity:
#set place
for rep in range(func_max_replica):
random_places.append(copy.deepcopy(workers[random_index]))
new_hosts = random_places
#deduct function cpu requirement from worker's cpu capacity per replica
for new_host in new_hosts:
#get selected worker index
index = workers.index([*(worker for worker in workers if worker[0]==new_host[0])][0])
#deduct replica cpu requirement
workers[index][3] -= replica_cpu_limits
#apply worker's updated capacity to new_host as well
new_host[3]= workers[index][3]
#set new_function new hosts
new_function[1] = new_hosts
if debug: logger.info("scheduler_planner_random: new_hosts for ("
+ new_function[0][0] + "-" + new_function[0][1] + "):\n" + str(new_function[1]))
#for loop: next new_function
logger.info('scheduler_planner_random: all done: functions:\n'
+ '\n'.join([str(new_function) for new_function in new_functions]))
return workers, new_functions
#scheduler_monitor
def scheduler_monitor(workers, node_role):
global logger
logger.info("scheduler_monitor: start")
#MONITOR
#Update SoC
for worker in workers:
ip=worker[1]
success=False
#retry
while success == False:
try:
logger.info('scheduler_monitor: Soc req.: ' + worker[0])
response=requests.get('http://' + ip + ':5000/pi_service/charge/'
+ node_role, timeout = 10)
except Exception as e:
logger.error('scheduler_monitor:request failed for ' + worker[0] + ":" + str(e))
time.sleep(1)
else:
soc=round(float(response.text),2)
index=workers.index(worker)
workers[index][2]=soc
logger.info('scheduler_monitor: Soc recv.: ' + worker[0] + ":" + str(soc) + "mWh")
success=True
logger.info('scheduler_monitor:\n' + '\n'.join([str(worker) for worker in workers]))
logger.info("scheduler_monitor:done")
return workers
#set initial workers and functions
def initialize_workers_and_functions(nodes, workers, functions, battery_cfg, nodes_plan, zones):
global logger
logger.info("initialize_workers_and_functions: start")
#Set Workers & Functions
for node in nodes:
#worker = [name, ip, soc, capacity, zone]
position = node[0]
name = node[1]
ip= node[2]
soc= battery_cfg[3]#set current SoC
capacity=nodes_plan[name]["max_cpu_capacity"] #set capacity as full
#set zone
battery_max_cap = battery_cfg[1]
soc_percent = round(soc / battery_max_cap * 100)
zone = [*(zone[1] for zone in zones if soc_percent <= zone[2] and soc_percent > zone[3])][0]
#if node is involved in this tests
if position == "PEER":
#add worker
worker =[name,ip, soc, capacity, zone]
workers.append(worker)
#add functions
apps=nodes_plan[name]["apps"]
for app in apps:
if app[1]==True:
#function = [identity, hosts[], func_info, profile]
#set identity
worker_name=worker[0]
app_name=app[0]
identity = [worker_name, app_name]
#set hosts
hosts=[]
#set function info
func_info=app[8]
#create and set profile name in function info
func_info[13]=worker_name + '-' + app_name
#set profile
profile = app[9]
function=[]
#set local host per replicas and deduct cpu capacity from node
max_replica = func_info[1]
for rep in range (max_replica):
#update host capacity
replica_cpu_limits = func_info[3]
#exclude 'm'
replica_cpu_limits = int(replica_cpu_limits.split('m')[0])
index=workers.index(worker)
workers[index][3]-=replica_cpu_limits
#set host: default is local placement
hosts.append(worker)
#end for rep
#add function
function = [identity, hosts, func_info, profile]
functions.append(function)
f_name= function[0][0]+ '-'+function[0][1]
#end for app
#end for node
logger.info("initialize_workers_and_functions:stop")
return workers, functions
#executor :set functions' profile using hosts, apply helm charts
def scheduler_executor(functions, profile_chart, profile_creation_roll_out,
function_chart, scheduling_round, log_path, scheduler_name, workers, debug):
#1 set profile based on hosts= set function[3] by new updates on function[1]
logger.info('scheduler_executor:start')
logger.info("scheduler_executor:set_profile per function")
duration = datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()
for function in functions:
#if debug: logger.info('scheduler_executor: set_profile:before:\n' + str(function[3]))
#get old profile
old_profile=copy.deepcopy(function[3])
#translate hosts and map them to profile and set new profile scheme
function[3]=scheduler_executor_set_profile(function, scheduler_name, workers, debug)
#compare profiles, profile = function[3] looks like this ["w1", "nothing", "nothing",....]
if old_profile != function[3]:
#if profile is changed, set version to force re-schedule function based on new profile config
function[2][14] +=1
logger.info('scheduler_executor: ' + str(function[0][0]) + '-' + str(function[0][1])
+ ': version = ' + str(function[2][14]))
#if debug: logger.info('scheduler_executor: set_profile:after:\n' + str(function[3]))
#all new profiles
logger.info('scheduler_executor: All new profiles \n'
+ '\n'.join([str(str(function[0]) + '--->'
+ str(function[3])) for function in functions]))
#2 apply the new scheduling for functions by helm chart
#if no change is profile happend, no re-scheduling is affected
logger.info("scheduler_executor:apply all: call")
scheduler_executor_apply(functions, profile_chart, profile_creation_roll_out,
function_chart, scheduling_round, log_path,
setup.auto_scaling, setup.auto_scaling_factor)
duration= datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp() - duration
logger.info('scheduler_executor: done in ' + str(int(duration)) + 'sec')
return functions
#offload
def offloader(workers, functions, volunteers, new_function, sticky,stickiness, old_hosts,
warm_scheduler,owner, func_max_replica,func_required_cpu_capacity, scale_to_zero, debug):
global logger
logger.info("offloader: start: " + str(new_function[0][0] +'-' + new_function[0][1]))
new_hosts = []
#??? assume that all replicas are always placed on 1 node
#if sticky enabled and function was offloaded last time
if owner[0] != old_hosts[0][0] and sticky:
new_hosts = sticky_offloader(workers, functions, volunteers, stickiness, old_hosts,
owner, func_max_replica,func_required_cpu_capacity,
warm_scheduler, scale_to_zero)
else:
logger.info('offloader: skip sticky_offloader')
#if sticky unsuccessful
if new_hosts == []:
#iterate over rich and vulnerables, already sorted by SoC (large -> small)
for volunteer in volunteers:
#if function belongs to a poor node
if owner[4] == 2:
if debug: logger.info('offloader: poor function')
#if node is in rich zone
volunteer_zone = volunteer[4]
if volunteer_zone == 1:
if debug: logger.info('offloader: rich volunteer (' + volunteer[0] + ')')
#if enough capacity on volunteer node is available
if volunteer[3] >= func_required_cpu_capacity:
if debug: logger.info('offloader: rich volunteer has capacity')
#place this poor function on this rich volunteer per replica
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(volunteer))
#volunteer capacity is deducted later on in main algorithm
return new_hosts
else:
if debug: logger.info('offloader: rich volunteer has NOT capacity')
#OR volunteer node is in vulnerable zone
if volunteer_zone == 3:
if debug: logger.info('offloader: vulnerable volunteer (' + volunteer[0] + ')')
#evaluate cpu reservation for the vulnerable node own functions
reserved_capacity = 0
available_capacity = 0
for function in functions:
#if function belongs to this vulnerable volunteer node
if function[0][0] == volunteer[0]:
#caclulate reserved cpu capacity per replica for the function
reserved_capacity += function[2][1] * int(function[2][3].split('m')[0])
#if already one has offloaded on this, that one is also included here as volunteer[3] is the result of full capacity minus offloaded (end of each offloading this is deducted)
available_capacity = volunteer[3] - reserved_capacity
#if volunteer has enough cpu capacity, considering reservation
if available_capacity >= func_required_cpu_capacity:
if debug: logger.info('offloader: vulnerable volunteer has capacity + reservation')
#place functions belong to a poor node on volunteer per replica
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(volunteer))
return new_hosts
else:
if debug: logger.info('offloader: vulnerable volunteer has NOT capacity + reservation')
#if function belongs to a vulnerable zone
elif owner[4] == 3:
if debug: logger.info('offloader: vulnerable function')
#only if volunteer is in rich zone
if volunteer[4] == 1:
if debug: logger.info('offloader: volunteer node\'s zone is rich (' + volunteer[0] + ')')
#and volunteer has cpu capacity for function
if volunteer[3] >= func_required_cpu_capacity:
logger.info('offloader: volunteer rich has capacity')
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(volunteer))
return new_hosts
else:
if debug: logger.info('offloader: volunteer rich has NOT capacity')
else:
if debug: logger.info('offloader: volunteer node\'s zone is NOT rich')
#if function belongs to a dead node
elif owner[4] == 4:
if debug: logger.info('offloader: dead function')
#if warm_scheduler on, otherwise functions belong to dead nodes are just placed locally
if warm_scheduler == True:
if debug: logger.info('offloader: warm scheduler is True')
# if volunteer is in rich zone