forked from aslanpour/faasHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhedgi.py
executable file
·8315 lines (7032 loc) · 377 KB
/
hedgi.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
#!/usr/bin/python3
import tracemalloc #By examining the traceback, you can identify the specific part of the code that is causing the socket to remain unclosed.
tracemalloc.start()
from gevent import monkey;monkey.patch_all() #for gevent use: this allows async gevent (without it pool.join() is needed so gevents wrok that will block the workload generator) and must be placed before import Flask
from flask import Flask, request, send_file, make_response, json, jsonify # pip3 install flask
from waitress import serve # pip3 install waitress
import requests # pip3 install requests
import threading
# import jsonpickle
import logging
from logging.handlers import RotatingFileHandler
import datetime
import time
import math
from random import choice
# Monitor
import psutil
from cpufreq import cpuFreq
import numpy as np
import statistics # for using satistics.mean() #numpy also has mean()
import re
import copy
import utils
if utils.what_device_is_it('raspberry pi 3') or utils.what_device_is_it('raspberry pi 4'):
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, copy a file
import subprocess as sp # to run cmd to disconnect Bluetooth
import getpass
# 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("~")
if os.path.exists(dir_path + "/pyhpa.py"): import pyhpa
if os.path.exists(dir_path + "/pyloadbalancing.py"): import pyloadbalancing
if os.path.exists(dir_path + "/pymanifest.py"): import pymanifest
if os.path.exists(dir_path + "/pykubectl.py"): import pykubectl
app = Flask(__name__)
app.config["DEBUG"] = True
from gevent.pool import Pool
from gevent import Timeout
session_enabled = False
# 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
cluster_info = None
node_IP = set_ip()
load_balancing ={}
peers = []
test_index = 0
test_updates = {}
epoch = 0
test_name = socket.gethostname() + "_test"
workers = []
functions = []
history = {'functions': [], 'workers': [], 'load_balancer': [], 'scheduler': [], 'autoscaler': []}
metrics = {}
sessions = {}
debug = False
erro_collector = []
waitress_threads = 8 # default is 4
try:
cpuFreq = cpuFreq()
except FileNotFoundError as e:
#This error happens for intel devices since Intel is not publishing available frequencies, ref: https://askubuntu.com/questions/1064269/cpufrequtils-available-frequencies
#Instead, all CPU informations are in files located in 'cd /sys/devices/system/cpu/cpu0/cpufreq'
#Collect informations by 'paste <(ls *) <(cat *) | column -s $'\t' -t'
#???If an Intel device is part of experiments + measurements, this is not considering them.
cpuFreq = None
print('cpuFreq object is not created. If this is a master node and Intel, dismiss it.\n' + str(e))
# 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"
hiccups_injection = []
active_sensor_time_slots=[]
# 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/" + getpass.getuser()+ "/pics/"
pics_num = 170 # pics name "pic_#.jpg"
file_storage_folder = "/home/" + getpass.getuser() + "/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,mem requests, mem limits, cpu req, cpu 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
#0: battery_sim True/False, 1:max (variable), 2:initial #3current SoC,
#4: renewable type, 5:poisson seed&lambda,6:dataset, 7:interval, 8 min_battery_charge, 9 turned on at,10 soc_unlimited, 11 battery_excess_input per charge input mwh
#12: status 0/1, 13: energy_input, 14: energy_consumed
# battery_cfg = []
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
node_down_sensor_hold_duration = 0
monitor_interval = 1
failure_handler_interval = 3
overlapped_allowed = True
max_cpu_capacity = 4000
boot_up_delay = 0
usb_eth_ports = None
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()
metrcis_received = []
actuations = 0
# network_name_server={}
sock = None # bluetooth connection
sensor_log = {}
suspended_replies = []
# monitoring parameters
# in owl_actuator
response_time = []
# in monitor
response_time_accumulative = []
current_time = []
current_time_ts = []
battery_charge = []
node_op = []
battery_history = []
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 (utils.what_device_is_it('raspberry pi 3') or utils.what_device_is_it('raspberry pi 4')) and battery_operated:
relay_pin = 20
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
pijuice = PiJuice(1, 0x14)
##############################
internal_session = requests.Session()
# s.keep_alive = False # Disable keep-alive to close connections immediately after sending requests
# s.mount('http://', requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1)) # Limit the connection pool to 1
# s.mount('https://', requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1))
# Set the SO_LINGER option with a timeout of 10 seconds
internal_session.socket_options = [
(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 10)),
]
############################
#reboot_agents
def reboot_agents(nodes, action):
logger.info('reboot_agents: start...')
#reboot
if 're-boot' in action:
logger.info('reboot_agents start re-boot')
for node in nodes:
position = node[0]
if position != "PEER":
continue
name = node[1]
ip = node[2]
user_name = node[3] #ubuntu
#reboot
cmd= "ssh " + user_name + "@" + ip + " sudo reboot "
logger.info(f'reboot_agents. cmd= {cmd}')
out, error = utils.shell(cmd)
logger.info(out + error)
#ping to ensure all nodes are up
for node in nodes:
position = node[0]
if position != "PEER":
continue
name = node[1]
ip = node[2]
user_name = node[3] #ubuntu
#wait until ping is done
ping(ip)
#wait till peers bootup after ping
logger.info(f'reboot_agents: wait for peers bootup after ping for {setup.agents_bootup_sec} sec...')
time.sleep(setup.agents_bootup_sec)
#run agents
if 're-execute' in action:
logger.info('reboot_agents start re-execute')
for node in nodes:
position = node[0]
if position != "PEER":
continue
name = node[1]
ip = node[2]
user_name = node[3] #ubuntu
#wait until ping is done
ping(ip)
#kill current one
agent_name = os.path.basename(__file__)
agent_path = os.path.abspath(os.path.basename(__file__))
#kill
# cmd= "ssh " + user_name + "@" + ip + " kill -9 \$(ps -aux |grep " + agent_name + " | awk '{print \$2}')"
cmd = "ssh " + user_name + "@" + ip + " 'kill -9 $(ps -aux | grep " + agent_name + " | awk \"{print \$2}\")'"
logger.info(f'reboot_agents. cmd= {cmd}')
out, error = utils.shell(cmd)
logger.info(f'out={out}. error={error}')
time.sleep(1)
#run
agent_name = os.path.basename(__file__)
agent_path = os.path.abspath(os.path.basename(__file__))
cmd= "ssh " + user_name + "@" + ip + " nohup python3 " + agent_path + "> " + agent_name.split('.')[0] + ".out" + " 2> " + agent_name.split('.')[0] + ".err" + " < /dev/null & "
logger.info(f'reboot_agents. cmd= {cmd}')
out, error = utils.shell(cmd)
logger.info(out + error)
logger.warning('Note: as agent is run in background using nohup, no output is received, so ensure agent is running remotely')
logger.info('reboot_agents: done')
# #restart_agents
# def restart_agents(nodes):
# logger.info('restart_agent: start')
# for node in nodes:
# position = node[0]
# if position != "PEER":
# continue
# name = node[1]
# ip = node[2]
# user_name = node[3] #ubuntu
# #kill current one
# agent_name = os.path.basename(__file__)
# agent_path = os.path.abspath(os.path.basename(__file__))
# #kill
# # cmd= "ssh " + user_name + "@" + ip + " kill -9 \$(ps -aux |grep " + agent_name + " | awk '{print \$2}')"
# cmd = "ssh " + user_name + "@" + ip + " 'kill -9 $(ps -aux | grep " + agent_name + " | awk \"{print \$2}\")'"
# logger.info(f'restart_agent. cmd= {cmd}')
# out, error = utils.shell(cmd)
# logger.info(f'out={out}. error={error}')
# #run
# cmd= "ssh " + user_name + "@" + ip + " nohup python3 " + agent_path + "> " + agent_name.split('.')[0] + ".out" + " 2> " + agent_name.split('.')[0] + ".err" + " < /dev/null & "
# logger.info(f'restart_agent. cmd= {cmd}')
# #run
# out, error = utils.shell(cmd)
# logger.info(out + error)
# logger.warning('Note: as agent is run in background using nohup, no output is received, so ensure agent is running remotely')
# logger.info('restart_agent: done')
def ping(ip):
done=False
while True:
#ping
cmd = "ping -c 1 " + ip
logger.info(cmd)
out, error = utils.shell(cmd)
logger.info(out + error)
if "1 received" in out:
logger.info('ping OK')
done=True
break
else:
time.sleep(1)
return done
def launcher(coordinator):
global logger
global node_name
global node_IP
global epoch
global internal_session
logger.info('start')
#if continous test, no change to epoch
#if master reboot, get epoch from config file
if setup.master_behavior_after_test_if_multiple_tests == 'reboot-before-starting-next-test':
cmd='grep "epoch" /home/ubuntu/logs/config.txt'
logger.info('read epoch value: ' + cmd)
out, error = utils.shell(cmd)
logger.info(out + error)
try:
epoch = int(out.split('=')[1])
except Exception as e:
logger.exception(f'Error: make sure epoch=? a number is in /home/ubuntu/logs/config.txt \n{e}')
sys.exit()
#exit if epochs are done already
if epoch >= len(setup.test_name):
logger.info(f"all tests are done already as epoch={epoch}, so sys.exit()")
sys.exit()
# set plan for coordinator itself.
name = coordinator[1]
ip = coordinator[2]
plan = copy.deepcopy(setup.plans[name])
# config for multi-tests
plan["test_name"] = setup.test_name[epoch]
# # set counter per app ???
# #This f'{foo=}'.split('=')[0].split('.')[-1] returns the name of the given variable 'foo' by excluding the value '=*' and prefix 'setup.' from f'{foo=}'
# plan["apps"][0][8][6] = setup.counter[epoch if f'{setup.counter=}'.split('=')[0].split('.')[-1] in setup.variable_parameters else 0 ]["ssd"]
# plan["apps"][1][8][6] = setup.counter[epoch if f'{setup.counter=}'.split('=')[0].split('.')[-1] in setup.variable_parameters else 0]["yolo3"]
# plan["apps"][2][8][6] = setup.counter[epoch if f'{setup.counter=}'.split('=')[0].split('.')[-1] in setup.variable_parameters else 0]["irrigation"]
# plan["apps"][3][8][6] = setup.counter[epoch if f'{setup.counter=}'.split('=')[0].split('.')[-1] in setup.variable_parameters else 0]["crop-monitor"]
# plan["apps"][4][8][6] = setup.counter[epoch if f'{setup.counter=}'.split('=')[0].split('.')[-1] in setup.variable_parameters else 0]["short"]
# print('111111111111111111111')
# print(plan["apps"][0][3][2])
# #set [0]ssd, [3]workload_cfg, [2] concurrency. ???this applies for only for ssd app
# #This plan["apps"][0][3] retruns [10000, 1, [7],seed, shapes["w7"],worker]
# #if workload_cfg in setup.variable_parameters, get concurrency item with the index of epoch' otherwise get the index 0 and set it as a float/int single value for concurrency
# plan["apps"][0][3][2] = plan["apps"][0][3][2][epoch if f'{setup.workload_cfg=}'.split('=')[0].split('.')[-1] in setup.variable_parameters else 0]
# #if workload_cfg in variable_parameters
# # if f'{setup.workload_cfg=}'.split('=')[0].split('.')[-1] in setup.variable_parameters:
# # #if concurrency for ssd app is a list of values [] in setup.workload_cfg
# # if isinstance(plan["apps"][0][3][2], list):
# # #get concurrency for this epoch from list and set it as a single int/float
# # plan["apps"][0][3][2] = plan["apps"][0][3][2][epoch]
# # #if concurrency is not a list, it is wrong
# # else:
# # logger.error('workload_cfg in setup.variable_parameters, but plan["apps"][0][3][2] is NOT a list')
# # time.sleep(3600)
# # #if workload_cfg is Not in variable_parameters and concurrency is a list, that is wrong.
# # elif isinstance(plan["apps"][0][3][2], list):
# # logger.error('workload_cfg NOT in setup.variable_parameters, but plan["apps"][0][3][2] is a list. Change it to single int/float')
# # time.sleep(3600)
# set battery size per test. All batteries are considered homogeneous.
plan["battery_cfg"][1] = setup.max_battery_charge[epoch if 'max_battery_charge' in setup.variable_parameters else 0]
#solar_panel_scale
plan["battery_cfg"][17] = setup.solar_panel_scale[epoch if 'solar_panel_scale' in setup.variable_parameters else 0]
# set cpu governor per test
plan["cpu_freq_config"]["governors"] = setup.cpu_governor[epoch if 'cpu_governor' in setup.variable_parameters else 0]
#set interarrival_rate
if plan['active_sensor_time_slots']['enabled'] == True:
plan['active_sensor_time_slots']['interarrival_rate'] = setup.interarrival_rate[epoch if 'interarrival_rate' in setup.variable_parameters else 0]
# 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 = main_handler('plan', 'INTERNAL', plan)
if reply != "success":
logger.error('INTERNAL interrupted and stopped')
return "failed"
else:
logger.info(name + ' reply: ' + 'success')
#agent_reuse
logger.info('agent_reuse...')
if 're-execute-at-start' in setup.agents_reuse:
action="re-execute"
reboot_agents(setup.nodes, action)
elif 're-boot-at-start' in setup.agents_reuse:
action= ""
#as of second test onward
if epoch > 0 :
action="re-boot-then-re-execute"
reboot_agents(setup.nodes, action)
else:
action="re-execute"
reboot_agents(setup.nodes, action)
else:
logger.error('ERROR - setup.agents_reuse not found, ' + str(setup.agents_reuse) )
time.sleep(3)
try:
#peers
reply_success = 0
# set peers plan, sequentially, including USB Meter connection
for node in setup.nodes:
position = node[0]
if position != "PEER":
continue
name = node[1]
ip = node[2]
user_name = node[3] #ubuntu
logger.info('********* peer plan set for ' + name)
plan = {}
plan = copy.deepcopy(setup.plans[name])
# config for multi-test
plan["test_name"] = setup.test_name[epoch]
# set counter per app ???
plan["apps"][0][8][6] = copy.deepcopy(setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["ssd"])
plan["apps"][1][8][6] = copy.deepcopy(setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["yolo3"])
plan["apps"][2][8][6] = copy.deepcopy(setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["irrigation"])
plan["apps"][3][8][6] = copy.deepcopy(setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["crop-monitor"])
plan["apps"][4][8][6] = copy.deepcopy(setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["short"])
#set [0]ssd, [3]workload_cfg, [2] concurrency. ???this applies for only for ssd app
#This plan["apps"][0][3] retruns [10000, 1, [7],seed, shapes["w7"],worker]
#if workload_cfg in setup.variable_parameters, get concurrency item with the index of epoch' otherwise get the index 0 and set it as a float/int single value for concurrency
for app in plan['apps']:
#if app is True
if app[1] == False:
continue
#if workload_config not in variable_parameters, get the first value in the list of concurrency always
concurrency_index = 0
if 'workload_cfg' in setup.variable_parameters:
#otherwise, get the corresponding index to the current epoch
concurrency_index = epoch
#pick correspondng value from the list that is prepared in setup.py
concurrency_value = app[3][2]
if isinstance(concurrency_value, list):
logger.info(f'isinstace list, ---------')
picked_concurrency = app[3][2][concurrency_index]
elif 'workload_cfg' in setup.variable_parameters:
logger.error('ERORRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR')
logger.error(f'plan could not pick concurrency for app {app[0]} as a list. It must be a list if workload_cfg is in setup.parameters, so it can be picked based on epoch')
else:
pass
logger.info(f'picked_concurrency={picked_concurrency}')
#set it. only a single int/float is given to the node, not a list
app[3][2] = picked_concurrency
# plan["apps"][0][3][2] = copy.deepcopy(plan["apps"][0][3][2][epoch if 'workload_cfg' in setup.variable_parameters else 0])
# set battery size per test
plan["battery_cfg"][1] = copy.deepcopy(setup.max_battery_charge[epoch if 'max_battery_charge' in setup.variable_parameters else 0])
#solar_panel_scale
plan["battery_cfg"][17] = copy.deepcopy(setup.solar_panel_scale[epoch if 'solar_panel_scale' in setup.variable_parameters else 0])
# set cpu governor per test
plan["cpu_freq_config"]["governors"] = copy.deepcopy(setup.cpu_governor[epoch if 'cpu_governor' in setup.variable_parameters else 0])
#set interarrival_rate
if plan['active_sensor_time_slots']['enabled'] == True:
plan['active_sensor_time_slots']['interarrival_rate'] = copy.deepcopy(setup.interarrival_rate[epoch if 'interarrival_rate' in setup.variable_parameters else 0])
logger.info('peers:' + name + ': ' + str(ip))
response = None
logger.info('********************************* start')
for k,v in plan.items():
logger.info(f'**************key={k}')
logger.info(v)
# logger.info(plan)
logger.info('************ dumps')
# logger.info(json.dumps(plan, indent=4))
logger.info(json.dumps(plan))
#send plan
while True:
# replier -= 1
try:
# url = 'http://' + ip + ':5000/main_handler/plan/' + sender
response = internal_session.post('http://' + ip + ':5000/main_handler/plan/' + sender, json=plan, timeout=10)
# serialized_data = jsonpickle.encode(plan, unpicklable=False)
# response.close()
break
except Exception as e:
logger.error('peers: failed for ' + name + ":" + ip)
logger.error('peers: exception:' + str(e))
#ping and wait until done
ping(ip)
# cmd = "ping -c 1 " + ip
# logger.info('ping before network restart ' + cmd)
# out, error = utils.shell(cmd)
# logger.info(out + error)
# if "1 received" in out:
# logger.info('ping OK')
# if replier < 7 and replier > 3:
#re-run the app on the remote host
filename = os.path.basename(__file__)
cmd="ssh " + user_name + "@" + ip + " ./" + "nohup python3 " + filename + " > hedgi.out 2> hedgi.err < /dev/null &"
logger.info('re-run remote code ' + cmd)
out, error = utils.shell(cmd)
logger.info(out + error)
#wait to run
time.sleep(5)
# else:
# logger.error('ping Fail')
#restart network manager
net_interface_manager_restart()
# cmd = "sudo systemctl restart NetworkManager.service"
# logger.info('restart network manager: ' + cmd)
# out, error = utils.shell(cmd)
# logger.info(out + error)
time.sleep(3)
if response and response.text == "success":
logger.info(name + ' reply: ' + 'success')
reply_success += 1
elif response:
logger.error('peers: request.text for ' + name + ' ' + str(response.text))
else:
logger.error('peer: failed to connect to ' + ip)
# 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 main_handler on
logger.info('run all nodes main_handler')
# internal
thread_main_handler = threading.Thread(target=main_handler, args=('on', 'INTERNAL',))
thread_main_handler.name = "main_handler"
# it calls scheduler that initiates functions & workers and deploys functions also calls autoscaler and load balancer
thread_main_handler.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 == "PEER":
logger.info('main_handler on: peers:' + name + ': ' + str(ip))
try:
response = internal_session.post('http://' + ip + ':5000/main_handler/on/' + sender)
# response.close()
except Exception as e:
logger.error('main_handler on: peers: failed for ' + name + ":" + ip)
logger.error('main_handler on: peers: exception:' + str(e))
if response.text == "success":
logger.info('main_handler on:' + name + ' reply: ' + 'success')
reply_success += 1
else:
logger.info('main_handler 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('main_handler on: all ' + str(peers) + ' nodes successful')
else:
logger.info('main_handler on: only ' + str(reply_success) + ' of ' + str(peers))
else:
logger.info('failed: only ' + str(reply_success) + ' of ' + str(len(peers)))
except Exception as e:
logger.info('ERROR - call peers ' + str(e))
logger.info('stop')
#load balancer
def load_balancer():
global logger
global under_test
global debug
global epoch
global history
#timing
logger.info("started...")
start = datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()
#get config (as dict)
load_balancing_config = copy.deepcopy(setup.load_balancing)
#history initializing
history['load_balancer']= []
#counter initializing
load_balancing_round = 0
#create nodes list
nodes_new = []
for node in setup.nodes:
if node[0] == 'PEER':
nodes_new.append({'name': node[1], 'ip': node[2]})
#load balance
while under_test:
#[new round timing]
now = datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()
logger.info('Load balancing round #' + str(load_balancing_round) + ' started at ' + str(now))
#set round number
load_balancing_config['load_balancing_round'] = load_balancing_round
#[MONITORING]
logger.info('monitoring...')
#get nodes status like cpuUtil or charge
nodes_new = monitor_pull(nodes_new, 'MASTER')
#update load_balancing_config
load_balancing_config['nodes'] = nodes_new
logger.info('load_balancing_config=\n' + str(load_balancing_config))
#[ANALYZING]
logger.info('analyzing...')
#[PLANNING]: run an algorithm and get updated plan for backends
logger.info('planning...')
#update backends
##???test
logger.info('backend_discovery before load blaancing plan in setup.py=\n' + str(setup.load_balancing['backend_discovery']))
load_balancing_config, msg, error = pyloadbalancing.plan(**load_balancing_config)
logger.info('backend_discovery after update in setup.py=\n' + str(setup.load_balancing['backend_discovery']))
logger.info('plan:' + msg)
if error:
logger.error('load_balancing plan failed \n' + str(error))
time.sleep(3600)
#[Execution]
logger.info('execution...')
#execute
load_balancing_config, msg, error = pyloadbalancing.execute(**load_balancing_config)
logger.info('execution:' + msg)
if error:
logger.error('execution failed err\n' + error)
time.sleep(3600)
#print logs
logger.info(load_balancing_config)
#history
history['load_balancer'].append(load_balancing_config)
# sliced interval in 1 minutes
logger.info('Load balancer done (round #' + str(load_balancing_round) + ') --- sleep for ' + str(
load_balancing_config['interval']) + ' sec / ' + str(load_balancing_config['interval']/60) + ' min.')
remained = load_balancing_config['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
load_balancing_round +=1
# load balancer clean_up???
logger.info('stop')
# monitor_fetch
def monitor_pull(nodes, current_node_role):
global logger
logger.info("monitor_pull: start")
# MONITOR
template = {'cpuUtil': -1, 'charge': -1}
# Fetch data from peers
for node in nodes:
success = False
# retry
while success == False:
try:
logger.info('monitor_pull: get ' + node['name'] + ' ...')
response = internal_session.get('http://' + node['ip'] + ':5000/main_handler/pull/'
+ current_node_role, timeout=10, json=template)
# response.close()
except Exception as e:
logger.error('monitor_pull: get failed for ' + node['name'] + ":" + str(e))
time.sleep(1)
else:
logger.info('monitor_pull response \n' + str(response.json()))
if response.json() and 'cpuUtil' in response.json():
# if response.json().get('cpuUtil'):
node['cpuUtil'] = response.json()['cpuUtil']
logger.info('pull_monitor: response of ' + node['name'] + ' is ' + str(node['cpuUtil']) + '%')
success = True
else:
logger.error('key cpuUtil not found in response.json()')
logger.error(str(response.headers))
logger.info('pull_monitor:\n' + '\n'.join([str(node) for node in nodes]))
logger.info("pull_monitor: done")
return nodes
#autoscaler
def autoscaler():
global logger
global under_test
global debug
global epoch
global functions
global history
if setup.auto_scaling == "openfaas":
logger.info("openfaas will handle the autoscaling by a request-per second policy")
return None
autoscaling_interval = setup.autoscaling_interval
#this thread is started after launcher method, so functions are already created.
logger.info("started...")
start = datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()
#wait for the scheduler to initialize functions variable, then get functions name
while functions == []:
time.sleep(1)
end = datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()
logger.info("waited for functions variable to be set by scheduler for " + str(round(end-start,2)) + "s")
#create HPA objects for functions and keep replacing them according to the load
autoscaling_round = 0
while under_test:
autoscaling_round +=1
logger.info("Started round #" + str(autoscaling_round))
start = datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()
for function in functions:
# function = [identity, hosts[], func_info, profile]
#identify function's name, i.e, from function[0]
function_identity = function[0]
function_node_name = function_identity[0] #e.g., "w1"
function_app_name = function_identity[1] #e.g., "yolo3"
function_name = function_node_name + "-" + function_app_name
#get the following from function_info, i.e., from function[2]
function_info = function[2]
#set min replica
min_replicas = function_info[0]
#set max replicas
max_replicas = function_info[1]
#get the following from global values in setup.py file
#set avg CPU utilization condition
avg_cpu_utilization = setup.avg_cpu_utilization
#set scale down stabilaztion window
scale_down_stabilizationWindowSeconds = setup.scale_down_stabilizationWindowSeconds
#create HPA
pyhpa.auto_scaling_by_hpa(logger,
function_name,
min_replicas,
max_replicas,
avg_cpu_utilization,
scale_down_stabilizationWindowSeconds)
end = datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()
#sleep
# sliced interval in 1 minutes
logger.info('End autoscaler round #' + str(autoscaling_round) + ' in ' + str(round(end-start,2)) + 's: sleep for ' + str(
autoscaling_interval) + ' sec...')
remained = autoscaling_interval
minute = 60
while remained > 0:
sleep_duration = min(minute, remained)
time.sleep(sleep_duration)
remained -= sleep_duration
if not under_test:
break
logger.info("stopped.")
# scheduler
def scheduler():
global epoch
global under_test
global logger
global debug
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.plans, 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 if 'scheduler_name' in setup.variable_parameters else 0]))
# Greedy
if "greedy" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_greedy(workers, functions, new_functions,
setup.max_battery_charge[epoch if 'max_battery_charge' in setup.variable_parameters else 0], setup.zones,
setup.warm_scheduler[epoch if 'warm_scheduler' in setup.variable_parameters else 0],
setup.sticky, setup.stickiness[epoch if 'stickiness' in setup.variable_parameters else 0], setup.scale_to_zero,
debug)
# shortfaas
elif "shortfaas" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_shortfaas(workers, functions, new_functions,
setup.max_battery_charge[epoch if 'max_battery_charge' in setup.variable_parameters else 0], setup.warm_scheduler[epoch if 'warm_scheduler' in setup.variable_parameters else 0],
setup.plugins[epoch if 'plugins' in setup.variable_parameters else 0], debug)
# hospital_resident
elif "hospital_resident" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_hospital_resident(workers, functions, new_functions,
setup.max_battery_charge[epoch if 'max_battery_charge' in setup.variable_parameters else 0], setup.warm_scheduler[epoch if 'warm_scheduler' in setup.variable_parameters else 0],
setup.plugins[epoch if 'plugins' in setup.variable_parameters else 0], debug)
#mthg
elif "mthg" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_mthg(workers, functions, new_functions,
setup.max_battery_charge[epoch if 'max_battery_charge' in setup.variable_parameters else 0], setup.warm_scheduler[epoch if 'warm_scheduler' in setup.variable_parameters else 0],
setup.plugins[epoch if 'plugins' in setup.variable_parameters else 0], debug, scheduling_round)
#mthg
elif "ffd" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_first_fit_decreasing(workers, functions, new_functions,
setup.max_battery_charge[epoch if 'max_battery_charge' in setup.variable_parameters else 0], setup.warm_scheduler[epoch if 'warm_scheduler' in setup.variable_parameters else 0],
setup.plugins[epoch if 'plugins' in setup.variable_parameters else 0], debug, scheduling_round)
# Local
elif "local" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_local(workers, new_functions, debug)
# Default-Kubernetes
elif "default" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_default(workers, new_functions, debug)
# Random
elif "random" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_random(workers, new_functions, debug)
# Bin-Packing
elif "bin-packing" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
workers, functions = scheduler_planner_binpacking(workers, functions, new_functions, debug)
# Optimal
elif "optimal" in setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]:
pass
else:
logger.error('scheduler_name not found: ' + str(setup.scheduler_name[epoch if 'scheduler_name' in setup.variable_parameters else 0]))
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 if 'scheduler_name' in setup.variable_parameters else 0], workers, debug)
# history
history["functions"].append(copy.deepcopy(functions))
history["workers"].append(copy.deepcopy(workers))
# sliced interval in 1 minutes
logger.info('MAPE LOOP (round #' + str(scheduling_round) + ') done: sleep for ' + str(
setup.scheduling_interval[epoch if 'scheduling_interval' in setup.variable_parameters else 0]) + ' sec...')
remained = setup.scheduling_interval[epoch if 'scheduling_interval' in setup.variable_parameters else 0]
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')
# scoring
def scheduler_planner_shortfaas(workers, functions, new_functions,
max_battery_charge, warm_scheduler, plugins, debug):
global logger
# workers have full capacity available
# new_functions have null as hosts
logger.info("shortfaas:start")