-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhedgi.py
More file actions
executable file
·5823 lines (5024 loc) · 259 KB
/
hedgi.py
File metadata and controls
executable file
·5823 lines (5024 loc) · 259 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
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 logging
import datetime
import time
import math
# 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
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 = 6 # 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"
# 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
# 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
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 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 (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)
def launcher(coordinator):
global logger
global node_name
global node_IP
global epoch
logger.info('start')
# set plan for coordinator itself.
name = coordinator[1]
ip = coordinator[2]
plan = copy.deepcopy(setup.plan[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_paramters
# # 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_paramters 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]
# set cpu governor per test
plan["cpu_freq_config"]["governors"] = setup.cpu_governor[epoch if 'cpu_governor' 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')
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]
plan = copy.deepcopy(setup.plan[name])
# config for multi-test
plan["test_name"] = setup.test_name[epoch]
# set counter per app ???
plan["apps"][0][8][6] = setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["ssd"]
plan["apps"][1][8][6] = setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["yolo3"]
plan["apps"][2][8][6] = setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["irrigation"]
plan["apps"][3][8][6] = setup.counter[epoch if 'counter' in setup.variable_parameters else 0]["crop-monitor"]
plan["apps"][4][8][6] = 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
plan["apps"][0][3][2] = plan["apps"][0][3][2][epoch if 'workload_cfg' in setup.variable_parameters else 0]
# #if workload_cfg in variable_paramters
# 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_paramters 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
plan["battery_cfg"][1] = setup.max_battery_charge[epoch if 'max_battery_charge' 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]
logger.info('peers:' + name + ': ' + str(ip))
response = None
replier =10
while replier > 0:
replier -= 1
try:
response = requests.post('http://' + ip + ':5000/main_handler/plan/' + sender, json=plan, timeout=10)
break
except Exception as e:
logger.error('peers: failed for ' + name + ":" + ip)
logger.error('peers: exception:' + str(e))
#restart network manager
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 = requests.post('http://' + ip + ':5000/main_handler/on/' + sender)
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)))
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 = setup.load_balancing
#history initializing
history['load_balancer']= []
#counter initializing
load_balancing_round = 0
#create nodes list
nodes = []
for node in setup.nodes:
if node[0] == 'PEER':
nodes.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 = monitor_pull(nodes, 'MASTER')
#update load_balancing_config
load_balancing_config['nodes'] = nodes
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
load_balancing_config, msg, error = pyloadbalancing.plan(**load_balancing_config)
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 = requests.get('http://' + node['ip'] + ':5000/main_handler/pull/'
+ current_node_role, timeout=10, json=template)
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 = 30
#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.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 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,
setup.sticky, setup.stickiness[epoch if 'stickiness' in setup.variable_parameters else 0], setup.scale_to_zero,
debug)
# scoring
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,
setup.plugins[epoch if 'plugins' in setup.variable_parameters else 0], debug)
# 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")
logger.info('shortfaas:\n available Workers \n'
+ '\n'.join([str(worker) for worker in workers]))
# define and initialize scoring scheme
scoring = {new_function[0][0] + '-' + new_function[0][1]:
{worker[0]:
{plugin: 0 for plugin in plugins}
for worker in workers} for new_function in new_functions}
logger.info('shortfaas: set ' + '\n' + str(scoring))
# add summations initialize
for func, value in scoring.items():
#
for worker_name, value2 in scoring[func].items():
scoring[func][worker_name]['sum_worker_scores'] = 0
scoring[func]['sum_function_scores'] = 0
# E.g.,
# print(scoring['f1'])
# print(scoring['f1']['w1'])
# print(scoring['f1']['w1']['energy'])
# print(scoring['f1']['sum_func_score'])
# print(scoring['f1']['w1']['sum_worker_score'])
logger.info('shortfaas: sum ' + '\n' + str(scoring))
# calculate and set soc percent and normalize to -1-1 (index 4 of worker used for soc percent, instead of zone)
for worker in workers:
soc = worker[2]
# assume all nodes have batteries of same size????
# max_battery_charge = copy.deepcopy(nodes_plan[worker[0]]["battery_cfg"][1])
soc_percent = round(soc / max_battery_charge * 100)
logger.info(worker[0] + ' soc : ' + str(soc_percent) + ' %')
# normalize to 0-1
worker[4] = round(soc_percent / 100, 2)
logger.info('shortfaas:updated soc %:\n'
+ '\n'.join([str(worker) for worker in workers]))
# so far, new_functions have [] as hosts, workers have full as capacity and both workers and new_functions are sorted now
logger.info('shortfaas: start setting scores per functions')
for new_function in new_functions:
# function_name
function_name = new_function[0][0] + '-' + new_function[0][1]
logger.info('shortfaas: functions **** ' + function_name + ' ****')
logger.info('lworkers:\n'
+ '\n'.join([str(worker) for worker in workers]))
# 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 soc value based on last epoch, so update them
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('old_hosts\n' + str(old_hosts))
# function's owner
owner = [*(worker for worker in workers if worker[0] == new_function[0][0])][0]
owner_name = owner[0]
# owner soc normalized
owner_soc_normalized = copy.deepcopy(owner[4])
logger.info('start scoring for ' + function_name)
# score per node
for worker in workers:
worker_name = copy.deepcopy(worker[0])
worker_soc_normalized = copy.deepcopy(worker[4])
# per plugin
# energy
# deduct remote soc from owner
scoring[function_name][worker_name]['energy'] = (round((
worker_soc_normalized - owner_soc_normalized) *
plugins['energy'], 2))
# locally
if owner_name == worker_name:
# if itself, score locally
scoring[function_name][worker_name]['locally'] = (round(
owner_soc_normalized * plugins['locally'], 2))
else:
# default 0
pass
# sticky
# assume first replica (old_hosts[0]) location represents the whole replicas ???
if old_hosts[0][0] != owner_name:
# has been offloaded in last round
if old_hosts[0][0] == worker_name:
# if this worker was the last place
scoring[function_name][worker_name]['sticky'] = (
round(1 * plugins['sticky'], 2))
else:
# default 0
pass
else:
# default 0
pass
# sum worker scores
scoring[function_name][worker_name]['sum_worker_scores'] = (
scoring[function_name][worker_name]['energy']
+ scoring[function_name][worker_name]['locally']
+ scoring[function_name][worker_name]['sticky'])
# sum function scores
for key, value in scoring[function_name].items():
worker_name = key
# items, except the summation
if worker_name != 'sum_function_scores':
# add per worker
scoring[function_name]['sum_function_scores'] += (
scoring[function_name][worker_name]['sum_worker_scores'])
logger.info('shortfaas: end scoring for ' + function_name + '\n' +
str(scoring[function_name]))
# end scoring
logger.info('scoring done:' + '\n'.join(str(func) + str(info) for func, info in scoring.items()))
# get a scores_tmp dict of function_name: sum_function_scores
scores_tmp = {} # function_name: sum_function_scores
# create a dict
for k, v in scoring.items():
func_name = k
sum_function_scores = v['sum_function_scores']
scores_tmp[func_name] = sum_function_scores
# sort dict (large to small)
# scores_tmp={k: v for k,v in sorted(scores_tmp.items(), key=lambda item: item[],
# reverse=True)}
logger.info('scored functions in tmp \n' + str(scores_tmp))
logger.info('******* start placements *******')
# place by max score
while len(scores_tmp):
# get max scored functions
function_name = max(scores_tmp.items(), key=lambda k: k[1])[0] # key
sum_function_scores = max(scores_tmp.items(), key=lambda k: k[1])[1] # value
logger.info('placement for ----- ' + function_name + '(sum scores=' + str(sum_function_scores) + ') -----')
# get full function
new_function = [*(new_function for new_function in new_functions if
new_function[0][0] == function_name.split('-')[0] and new_function[0][1] ==
function_name.split('-', 1)[1])][0]
# function required capacity
func_required_cpu_capacity = 0
# exclude 'm'
replica_cpu_limits = int(new_function[2][5].split('m')[0])
func_max_replica = new_function[2][1]
func_required_cpu_capacity = replica_cpu_limits * func_max_replica
# placement
# set new hosts
new_hosts = []
owner_name = function_name.split('-')[0] # e.g. w1-irrigation
owner = [*(worker for worker in workers if worker[0] == owner_name)][0]
owner_soc = owner[2]
logger.info('function owner \n' + str(owner))
# if function not belong to a dead node
if owner_soc >= battery_cfg[8]:
# get max scored worker of this function
max_score = float('-inf') # minimum value, for max value remove '-' from inf
selected_worker_name = ""
nodes_score = scoring[function_name]
for key, value in nodes_score.items():
# keys: w1, w2, w3, sum_function_scores
# e.g. {'w1': {'energy': 0, 'locally': 0, 'sticky': 0, 'sum_worker_score': 0}, 'w2': {'energy': 0, 'locally': 0, 'sticky': 0, 'sum_worker_score': 0}, 'sum_func_score': 1}
# items, except 'sum_function_scores'
if key != 'sum_function_scores':
if value['sum_worker_scores'] > max_score:
worker = [*(worker for worker in workers if worker[0] == key)][0]
# if capacity
if worker[3] >= func_required_cpu_capacity:
max_score = value['sum_worker_scores']
selected_worker_name = key
# get the remote host
worker = [*(worker for worker in workers if worker[0] == selected_worker_name)][0]
# if offloading placement, first localize functions of remote host
if worker[0] != owner_name:
worker, new_functions, scores_tmp = localizer(worker, new_functions, scores_tmp)
# set new_hosts
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(worker))
logger.info('placement for ' + function_name + '\n' + str(worker))
else:
# if owner is dead
logger.info('(dead node) placement locally for ' + function_name)
# 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))
logger.info('deduct capacity for ' + function_name)
# 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("shortfaas: new_hosts for ("
+ new_function[0][0] + "-" + new_function[0][1] + "):\n" + str(new_function[1]))
# delete
del scores_tmp[function_name]
# for loop: next new_function
logger.info('shortfaas: done: functions:\n'
+ '\n'.join([str(new_function) for new_function in new_functions]))
return workers, new_functions
def getFunctionName(function):
return function[0][0] + '-' + function[0][1]
def localizer(worker, new_functions, scores_tmp):
global logger
logger.info('localizer: start for worker ' + str(worker))
logger.info('localizer: scores_tmp \n' + str(scores_tmp))
worker_name = worker[0]
# get functions of the worker
for new_function in new_functions:
# get function name
function_name = getFunctionName(new_function)
# get function owner
function_owner = new_function[0][0]
# if this function belongs to the worker, place locally
if function_owner == worker[0]:
logger.info('localizer: placement for ----- ' + function_name + ' -----')
# if already placed, skip
hosts = new_function[1]
# if hosts not set yet
if hosts != []:
logger.info('localizer: already done, localizer skip for ' + function_name)
continue
# else place locally
else:
# function required capacity
func_required_cpu_capacity = 0
# exclude 'm'
replica_cpu_limits = int(new_function[2][5].split('m')[0])
func_max_replica = new_function[2][1]
func_required_cpu_capacity = replica_cpu_limits * func_max_replica
# placement
# set new hosts
new_hosts = []
logger.info('localizer: placement locally for ' + function_name)
for rep in range(func_max_replica):
new_hosts.append(copy.deepcopy(worker))
# deduct capacity
logger.info('localizer: deduct capacity for ' + function_name)
# deduct function cpu requirement from worker's cpu capacity
for new_host in new_hosts:
# deduct replica cpu requirement
worker[3] -= replica_cpu_limits
# update new_host, particulalrly its capacity
new_host[3] = worker[3]
# set new_function new hosts
new_function[1] = new_hosts
if debug: logger.info("localizer: new_hosts for ("
+ new_function[0][0] + "-" + new_function[0][1] + "):\n" + str(new_function[1]))
# delete
del scores_tmp[function_name]
logger.info('localizer: deleted scores_tmp: ' + str(scores_tmp))
return worker, new_functions, scores_tmp
# -----------------
# ??? 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, max_battery_charge, 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]
# assume nodes have same size battery???
# max_battery_charge = copy.deepcopy(nodes_plan[worker[0]]["battery_cfg"][1])
soc_percent = round(soc / max_battery_charge * 100)
logger.info('soc percent: ' + str(soc_percent))
new_zone = [*(zone[1] for zone in zones if soc_percent <= zone[2]