-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoscaling.py
6613 lines (5953 loc) · 231 KB
/
autoscaling.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 abc
import calendar
import csv
import datetime
import difflib
import enum
import filecmp
import hashlib
import inspect
import json
import logging
import math
import os
import re
import shutil
import signal
import subprocess
import sys
import textwrap
import time
import traceback
from functools import total_ordering
from logging.handlers import RotatingFileHandler
from multiprocessing import Process
from pathlib import Path
from pprint import pformat
from subprocess import PIPE, Popen
import matplotlib.backends.backend_pdf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import yaml
LOG_LEVEL = logging.DEBUG
OUTDATED_SCRIPT_MSG = (
"Your script is outdated [VERSION: {SCRIPT_VERSION} - latest is {LATEST_VERSION}] "
"- please download the current version and run it again!"
)
PORTAL_LINK = "https://cloud.denbi.de"
AUTOSCALING_VERSION_KEY = "AUTOSCALING_VERSION"
AUTOSCALING_VERSION = "1.8.7"
REPO_LINK = "https://github.com/deNBI/autoscaling-cluster/"
REPO_API_LINK = "https://api.github.com/repos/deNBI/autoscaling-cluster/"
RAW_REPO_LINK = "https://raw.githubusercontent.com/deNBI/autoscaling-cluster/"
HTTP_CODE_OK = 200
HTTP_CODE_UNAUTHORIZED = 401
HTTP_CODE_OUTDATED = 400
AUTOSCALING_FOLDER = os.path.dirname(os.path.realpath(__file__)) + "/"
IDENTIFIER = "autoscaling"
FILE_CONFIG = IDENTIFIER + "_config.yaml"
FILE_CONFIG_YAML = AUTOSCALING_FOLDER + FILE_CONFIG
FILE_ID = IDENTIFIER + ".py"
FILE_PROG = AUTOSCALING_FOLDER + FILE_ID
FILE_PID = IDENTIFIER + ".pid"
SOURCE_LINK_CONFIG = REPO_LINK + FILE_CONFIG
CLUSTER_PASSWORD_FILE = AUTOSCALING_FOLDER + "cluster_pw.json"
LOG_FILE = AUTOSCALING_FOLDER + IDENTIFIER + ".log"
LOG_CSV = AUTOSCALING_FOLDER + IDENTIFIER + ".csv"
NORM_HIGH = None
NORM_LOW = 0.0001
FORCE_LOW = 0.0001
FLAVOR_GPU_ONLY = -1
FLAVOR_GPU_REMOVE = 1
# ----- NODE STATES -----
NODE_ALLOCATED = "ALLOC"
NODE_MIX = "MIX"
NODE_IDLE = "IDLE"
NODE_DRAIN = "DRAIN"
NODE_DOWN = "DOWN"
NODE_DUMMY = "bibigrid-worker-autoscaling_dummy"
NODE_DUMMY_REQ = True
WORKER_SCHEDULING = "SCHEDULING"
WORKER_PLANNED = "PLANNED"
WORKER_ERROR = "ERROR"
WORKER_FAILED = "FAILED"
WORKER_PORT_CLOSED = "PORT_CLOSED"
WORKER_ACTIVE = "ACTIVE"
# flavor depth options
DEPTH_MAX_WORKER = -2
DEPTH_MULTI_SINGLE = -3
DEPTH_MULTI = -1
# ----- JOB STATE IDs -----
JOB_FINISHED = 3
JOB_PENDING = 0
JOB_RUNNING = 1
DOWNSCALE_LIMIT = 0
WAIT_CLUSTER_SCALING = 30
FLAVOR_HIGH_MEM = "hmf"
DATABASE_FILE = AUTOSCALING_FOLDER + IDENTIFIER + "_database.json"
DATA_LONG_TIME = 7
DATABASE_WORKER_PATTERN = " + ephemeral"
HOME = str(Path.home())
PLAYBOOK_DIR = HOME + "/playbook"
PLAYBOOK_VARS_DIR = HOME + "/playbook/vars"
COMMON_CONFIGURATION_YML = PLAYBOOK_VARS_DIR + "/common_configuration.yml"
ANSIBLE_HOSTS_FILE = PLAYBOOK_DIR + "/ansible_hosts"
INSTANCES_YML = PLAYBOOK_VARS_DIR + "/instances.yml"
SCHEDULER_YML = PLAYBOOK_VARS_DIR + "/scheduler_config.yml"
@total_ordering
class ScaleState(enum.Enum):
"""
Possible program scaling states.
"""
UP = 1
DOWN = 0
SKIP = 2
DONE = 3
DOWN_UP = 4
FORCE_UP = 5
DELAY = -1
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented
class Rescale(enum.Enum):
"""
Rescaling types.
"""
INIT = 0
CHECK = 1
NONE = 2
class TerminateProtected:
"""
Protect a section of code from being killed by SIGINT or SIGTERM.
Example:
with TerminateProtected():
function_1()
function_2()
"""
killed = False
def _handler(self, signum, frame):
logging.error(
"Received SIGINT or SIGTERM! Finishing this code block, then exiting."
)
self.killed = True
def __enter__(self):
self.old_sigint = signal.signal(signal.SIGINT, self._handler)
self.old_sigterm = signal.signal(signal.SIGTERM, self._handler)
def __exit__(self, type, value, traceback):
if self.killed:
sys.exit(0)
signal.signal(signal.SIGINT, self.old_sigint)
signal.signal(signal.SIGTERM, self.old_sigterm)
class ProcessFilter(logging.Filter):
"""
Only accept log records from a specific pid.
"""
def __init__(self, pid):
self._pid = pid
def filter(self, record):
return record.process == self._pid
class SchedulerInterface(abc.ABC):
"""
Scheduler interface template.
"""
@abc.abstractmethod
def scheduler_function_test(self):
"""
Test if scheduler can retrieve job and node data.
:return: boolean, success
"""
return False
@abc.abstractmethod
def fetch_scheduler_node_data(self):
"""
Read scheduler data from database and return a json object with node data.
Verify database data.
Example:
{
'bibigrid-worker-2-849-mhz6y1u0tnesizi':
{'cpus': 28,
'free_mem': 226280,
'gres': ['gpu:0'],
'node_hostname': 'bibigrid-worker-2-849-mhz6y1u0tnesizi',
'real_memory': 236000,
'state': 'MIX',
'tmp_disk': 1000000},
'bibigrid-worker-2-850-mhz6y1u0tnesizi':
{'cpus': 28,
'free_mem': 202908,
'gres': ['gpu:0'],
'node_hostname': 'bibigrid-worker-2-850-mhz6y1u0tnesizi',
'real_memory': 236000,
'state': 'ALLOC',
'tmp_disk': 1000000}
}
Node states:
* `NODE_ALLOCATED` = `'ALLOC'`
* `NODE_MIX` = `'MIX'`
* `NODE_IDLE` = `'IDLE'`
* `NODE_DRAIN` = `'DRAIN'`
* `NODE_DOWN` = `'DOWN'`
:return
- json object with node data,
- on error, return None
"""
return None
@abc.abstractmethod
def node_data_live(self):
"""
Receive node data from scheduler, without database usage. Provide more recent data.
:return: json object with node data
"""
return None
@abc.abstractmethod
def job_data_live(self):
"""
Receive job data from scheduler, without job history and database usage. Provide more recent data.
:return: json object with job data
"""
return None
@abc.abstractmethod
def fetch_scheduler_job_data(self, num_days):
"""
Read scheduler data from database and return a json object with job data.
Define the prerequisites for the json data structure and the required data.
Job states:
- 0: PENDING
- 1: RUNNING
- 3: COMPLETED
Example:
{20:
{
...
},
{33: {'cluster': 'bibigrid',
'elapsed': 0,
'end': 1668258570,
'jobid': 33,
'jobname': 'nf-sayHello_(6)',
'nodes': 'bibigrid-worker-3-1-gpwapcgoqhgkctt',
'partition': 'debug',
'priority': 71946,
'req_cpus': 1,
'req_mem': 5,
'start': 1668258570,
'state': 0,
'state_str': 'PENDING',
'tmp_disk': 0,
'comment': None}
}
:param num_days:
:return: json object with job data, return None on error
"""
return None
@abc.abstractmethod
def set_node_to_drain(self, w_key):
"""
Set scheduler option, node to drain.
- currently running jobs will keep running
- no further job will be scheduled on that node
:param w_key: node name
:return:
"""
@abc.abstractmethod
def set_node_to_resume(self, w_key):
"""
Set scheduler option, remove drain from required node
- further jobs will be scheduled on that node
:param w_key: node name
:return:
"""
class SlurmInterface(SchedulerInterface):
"""
Interface for the slurm scheduler.
"""
def scheduler_function_test(self):
"""
Test if scheduler can retrieve job and node data.
:return: boolean, success
"""
# try node data
try:
pyslurm.Nodes.load()
except ValueError as e:
logger.error("Error: unable to receive node data \n%s", e)
return False
# try job data
try:
pyslurm.db.Jobs.load()
except ValueError as e:
logger.error("Error: unable to receive job data \n%s", e)
return False
return True
def fetch_scheduler_node_data(self):
"""
Read scheduler data from database and return a json object with node data.
Verify database data.
:return:
- json object with node data
- on error, return None
"""
try:
nodes = pyslurm.Nodes.load()
node_dict = {}
for key, value in nodes.items():
node_dict[key] = value.to_dict()
logger.info(node_dict)
return node_dict
except ValueError as e:
logger.error("Error: unable to receive node data \n%s", e)
return None
@staticmethod
def get_json(slurm_command):
"""
Get all slurm data as string from squeue or sinfo
:param slurm_command:
:return: json data from slurm output
"""
process = Popen(
[slurm_command, "-o", "%all"],
stdout=PIPE,
stderr=PIPE,
shell=False,
universal_newlines=True,
)
proc_stdout, proc_stderr = process.communicate()
lines = proc_stdout.split("\n")
header_line = lines.pop(0)
header_cols = header_line.split("|")
entries = []
for line in lines:
parts = line.split("|")
val_dict = {}
if len(parts) == len(header_cols):
for i, key in enumerate(header_cols):
val_dict[key] = parts[i]
entries.append(val_dict)
return entries
@staticmethod
def __convert_node_state(state):
"""
Convert sinfo state to detailed database version.
- not possible to identify MIX+DRAIN
:param state: node state to convert
:return:
"""
state = state.upper()
if "DRNG" in state:
state = NODE_ALLOCATED + "+" + NODE_DRAIN
elif "DRAIN" in state:
state = NODE_IDLE + "+" + NODE_DRAIN
elif "ALLOC" in state:
state = NODE_ALLOCATED
elif "IDLE" in state:
state = NODE_IDLE
elif "MIX" in state:
state = NODE_MIX
elif "DOWN" in state:
state = NODE_DOWN
return state
@staticmethod
def __convert_job_state(state):
"""
Convert job state string to id.
:param state: job state to convert
:return:
"""
state = state.upper()
if state == "PENDING":
state_id = JOB_PENDING
elif state == "RUNNING":
state_id = JOB_RUNNING
else:
state_id = -1
return state_id
def node_data_live(self):
"""
Receive node data from sinfo.
:return: json object
"""
node_dict = self.get_json("sinfo")
node_dict_format = {}
for i in node_dict:
gres = i["GRES "].replace(" ", "")
free_mem = None
if "null" in gres:
gpu = ["gpu:0"]
else:
gpu = [gres]
if i["FREE_MEM"].isnumeric():
free_mem = int(i["FREE_MEM"])
node_dict_format.update(
{
i["HOSTNAMES"]: {
"total_cpus": int(i["CPUS"]),
"real_memory": int(i["MEMORY"]),
"state": self.__convert_node_state(i["STATE"]),
"temporary_disk": int(i["TMP_DISK"]),
"node_hostname": i["HOSTNAMES"],
"gres": gpu,
"free_mem": free_mem,
}
}
)
return node_dict_format
@staticmethod
def __time_to_seconds(time_str):
"""
Convert a time string to seconds.
:param time_str: example "1-04:27:12"
:return: seconds
"""
value = 0
ftr = [60, 1]
try:
time_split = time_str.split("-")
if len(time_split) > 1:
value += int(time_split[0]) * 3600 * 24
time_split = time_split[1]
else:
time_split = time_split[0]
time_split = time_split.split(":")
if len(time_split) == 3:
ftr = [3600, 60, 1]
value += sum([a * b for a, b in zip(ftr, map(int, time_split))])
except (ValueError, IndexError) as e:
logger.error("Error: time data %s", e)
return value
def job_data_live(self):
"""
Fetch live data from scheduler without database usage.
Use squeue output from slurm, should be faster up-to-date
:return: return current job data (no history) as dict
"""
squeue_json = self.get_json("squeue")
job_live_dict = {}
for i in squeue_json:
mem = re.split("(\\d+)", i["MIN_MEMORY"])
disk = re.split("(\\d+)", i["MIN_TMP_DISK"])
if i["COMMENT"] == "(null)":
comment = None
else:
comment = i["COMMENT"]
state_id = self.__convert_job_state(i["STATE"])
if state_id >= 0:
job_live_dict.update(
{
i["JOBID"]: {
"jobid": int(i["JOBID"]),
"req_cpus": int(i["MIN_CPUS"]),
"req_mem": self.memory_size_ib(mem[1], mem[2]),
"state": state_id,
"state_str": i["STATE"],
"temporary_disk": self.memory_size(disk[1], disk[2]),
"priority": int(i["PRIORITY"]),
"jobname": i["NAME"],
"req_gres": i["TRES_PER_NODE"],
"nodes": i["NODELIST"],
"elapsed": self.__time_to_seconds(i["TIME"]),
"comment": comment,
}
}
)
return job_live_dict
@staticmethod
def memory_size_ib(num, ending):
if ending == "G":
tmp_disk = convert_gb_to_mib(num)
elif ending == "M":
tmp_disk = int(num)
elif ending == "T":
tmp_disk = convert_tb_to_mib(num)
else:
tmp_disk = int(num)
return tmp_disk
@staticmethod
def memory_size(num, ending):
if ending == "G":
tmp_disk = convert_gb_to_mb(num)
elif ending == "M":
tmp_disk = int(num)
elif ending == "T":
tmp_disk = convert_tb_to_mb(num)
else:
tmp_disk = int(num)
return tmp_disk
def add_jobs_tmp_disk(self, jobs_dict):
"""
Add tmp disc data value to job dictionary.
:param jobs_dict: modified jobs_dict
:return:
"""
for key, entry in jobs_dict.items():
if "temporary_disk" not in entry:
jobs_dict[key]["temporary_disk"] = 0
return dict(jobs_dict)
def fetch_scheduler_job_data_by_range(self, start, end):
"""
Read scheduler data from database and return a json object with job data.
Define the prerequisites for the json data structure and the required data.
:param start: start time range
:param end: end time range
:return json object with job data, return None on error
"""
try:
db_filter = pyslurm.db.JobFilter(
start_time=start.encode("utf-8"), end_time=end.encode("utf-8")
)
jobs_dict = {
job.id: job.to_dict()
for job in pyslurm.db.Jobs.load(db_filter).values()
}
jobs_dict = self.add_jobs_tmp_disk(jobs_dict)
return jobs_dict
except ValueError as e:
logger.debug("Error: unable to receive job data \n%s", e)
return None
def fetch_scheduler_job_data(self, num_days):
"""
Read job data from database and return a json object with job data.
:param num_days: number of past days
:return: jobs_dict
"""
start = (
datetime.datetime.utcnow() - datetime.timedelta(days=num_days)
).strftime("%Y-%m-%dT00:00:00")
end = (datetime.datetime.utcnow() + datetime.timedelta(days=num_days)).strftime(
"%Y-%m-%dT00:00:00"
)
return self.fetch_scheduler_job_data_by_range(start, end)
def set_node_to_drain(self, w_key):
"""
Set scheduler option, node to drain.
- currently running jobs will keep running
- no further job will be scheduled on that node
:param w_key: node name
:return:
"""
logger.debug("drain node %s ", w_key)
os.system(
"sudo scontrol update nodename="
+ str(w_key)
+ " state=drain reason=REPLACE"
)
def set_node_to_resume(self, w_key):
"""
Set scheduler option, remove drain from required node
- further jobs will be scheduled on that node
:param w_key: node name
:return:
"""
logger.debug("undrain node %s ", w_key)
os.system("sudo scontrol update nodename=" + str(w_key) + " state=resume")
def run_ansible_playbook():
"""
Run ansible playbook with system call.
- ansible-playbook -v -i ansible_hosts site.yml
:return: boolean, success
"""
logger.debug("--- run playbook ---")
os.chdir(PLAYBOOK_DIR)
forks_num = str(os.cpu_count() * 4)
result_ = False
try:
# Run the subprocess and capture its output
process = subprocess.Popen(
[
"ansible-playbook",
"--forks",
forks_num,
"-v",
"-i",
"ansible_hosts",
"site.yml",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True, # To work with text output
)
# Log the output with the [ANSIBLE] prefix
for line in process.stdout:
logger.debug("[ANSIBLE] " + line.strip())
# Wait for the subprocess to complete and get the return code
return_code = process.wait()
if return_code == 0:
logger.debug("ansible playbook success")
result_ = True
else:
logger.error(
"ansible playbook failed with return code: " + str(return_code)
)
except Exception as e:
logger.error("Error running ansible-playbook: " + str(e))
return result_
def get_dummy_worker(flavors_data):
"""
Generate dummy worker entry from the highest flavor from available flavor data.
The highest flavor shut be on top on index 0.
Example:
{'cores': 28, 'ephemeral_disk': 4000, 'ephemerals': [],
'hostname': 'bibigrid-worker-autoscaling_dummy', 'ip': '0.0.0.4',
'memory': 512000, 'status': 'ACTIVE'}
:param flavors_data: available flavors
:return: dummy worker data as json
"""
ephemeral_disk = 0
max_gpu = 0
max_memory = 0
max_cpu = 0
if flavors_data:
# over all flavors - include gpu
for flavor_tmp in flavors_data:
ephemeral_disk = max(
ephemeral_disk,
convert_gb_to_mib(int(flavor_tmp["flavor"]["ephemeral_disk"])),
)
max_memory = max(
max_memory, convert_gb_to_mib(flavor_tmp["flavor"]["ram_gib"])
)
max_cpu = max(max_cpu, flavor_tmp["flavor"]["vcpus"])
max_gpu = max(max_gpu, int(flavor_tmp["flavor"]["gpu"]))
else:
logger.error("no flavor available")
ephemerals = [{"size": ephemeral_disk, "device": "/dev/vdb", "mountpoint": "/mnt"}]
dummy_worker = {
"cores": max_cpu,
"ephemeral_disk": ephemeral_disk,
"ephemerals": ephemerals,
"hostname": NODE_DUMMY,
"ip": "0.0.0.4",
"memory": max(max_memory, 8192),
"status": "ACTIVE",
"gpu": max_gpu,
}
logger.debug("dummy worker data: %s", dummy_worker)
return dummy_worker
def rescale_init(cluster_data, dummy_worker):
"""
Combine rescaling steps
- update dummy_worker worker, if required
- start scale function to generate and update the ansible playbook
- run the ansible playbook
:param cluster_data: cluster data from api
:param dummy_worker: dummy worker data
:return: boolean, success
"""
if NODE_DUMMY_REQ and not dummy_worker:
flavor_data = get_usable_flavors(True, False)
dummy_worker = get_dummy_worker(flavor_data)
logger.debug("calculated dummy_worker: %s", pformat(dummy_worker))
return update_all_yml_files_and_run_playbook(dummy_worker=dummy_worker)
def get_version():
"""
Print the current autoscaling version.
:return:
"""
logger.debug("Version: ", AUTOSCALING_VERSION)
def __update_playbook_scheduler_config(set_config):
"""
Update playbook scheduler configuration, skip with error message when missing.
:return:
"""
scheduler_config = __read_yaml_file(SCHEDULER_YML)
if scheduler_config is None:
logger.info("ignore individual scheduler settings, not supported")
elif scheduler_config["scheduler_config"]["priority_settings"]:
scheduler_config["scheduler_config"]["priority_settings"] = set_config
___write_yaml_file(SCHEDULER_YML, scheduler_config)
logger.debug("scheduler config updated")
else:
logger.error("scheduler_config, missing: scheduler_config, scheduler_settings")
def __current_usage(worker_json, jobs_json):
"""
DEBUG
For csv log only, temporary logging.
:param worker_json: worker information as json dictionary object
:param jobs_json: job information as json dictionary object
:return: usage dict
"""
cpu_alloc, mem_alloc, mem_alloc_drain, mem_alloc_no_drain = 0, 0, 0, 0
mem_mix_drain, mem_mix_no_drain = 0, 0
cpu_idle, mem_idle, mem_idle_drain, mem_idle_no_drain = 0, 0, 0, 0
jobs_cpu_alloc, jobs_mem_alloc = 0, 0
jobs_cpu_pending, jobs_mem_pending = 0, 0
if jobs_json:
for key, value in jobs_json.items():
if value["state"] == JOB_PENDING:
jobs_cpu_pending += value["req_cpus"]
jobs_mem_pending += value["req_mem"]
elif value["state"] == JOB_RUNNING:
jobs_cpu_alloc += value["req_cpus"]
jobs_mem_alloc += value["req_mem"]
if worker_json:
for key, value in worker_json.items():
if "worker" not in key:
continue
if (NODE_ALLOCATED in value["state"]) or (NODE_MIX in value["state"]):
cpu_alloc += value["total_cpus"]
mem_alloc += value["real_memory"]
if NODE_DRAIN in value["state"]:
if NODE_ALLOCATED in value["state"]:
mem_alloc_drain += value["real_memory"]
elif NODE_MIX in value["state"]:
mem_mix_drain += value["real_memory"]
else:
if NODE_ALLOCATED in value["state"]:
mem_alloc_no_drain += value["real_memory"]
elif NODE_MIX in value["state"]:
mem_mix_no_drain += value["real_memory"]
elif NODE_IDLE in value["state"]:
cpu_idle += value["total_cpus"]
mem_idle += value["real_memory"]
if NODE_DRAIN in value["state"]:
mem_idle_drain += value["real_memory"]
else:
mem_idle_no_drain += value["real_memory"]
usage_entry = {}
usage_entry.update({"cpu_alloc": cpu_alloc})
usage_entry.update({"mem_alloc": mem_alloc})
usage_entry.update({"cpu_idle": cpu_idle})
usage_entry.update({"mem_idle": mem_idle})
usage_entry.update({"jobs_cpu_alloc": jobs_cpu_alloc})
usage_entry.update({"jobs_mem_alloc": jobs_mem_alloc})
usage_entry.update({"jobs_cpu_pending": jobs_cpu_pending})
usage_entry.update({"jobs_mem_pending": jobs_mem_pending})
usage_entry.update({"worker_mem_alloc_drain": mem_alloc_drain})
usage_entry.update({"worker_mem_alloc": mem_alloc_no_drain})
usage_entry.update({"worker_mem_idle_drain": mem_idle_drain})
usage_entry.update({"worker_mem_idle": mem_idle_no_drain})
usage_entry.update({"worker_mem_mix_drain": mem_mix_drain})
usage_entry.update({"worker_mem_mix": mem_mix_no_drain})
return usage_entry
def cluster_credit_usage():
"""
DEBUG
Summarize the current credit values of the running workers on the cluster.
Stand-alone function for regular csv log creation including API data query.
:return: cluster_credit_usage
"""
flavors_data = get_usable_flavors(True, False)
cluster_workers = get_cluster_workers_from_api()
credit_sum = 0
worker_credit_data = {}
if cluster_workers is not None:
for c_worker in cluster_workers:
if c_worker["status"].upper() == WORKER_ACTIVE:
credit_sum += cluster_worker_to_credit(flavors_data, c_worker)
if c_worker["flavor"] in worker_credit_data:
worker_credit_data[c_worker["flavor"]]["cnt"] += 1
else:
worker_credit_data.update(
{
c_worker["flavor"]: {
"cnt": 0,
"credit": cluster_worker_to_credit(
flavors_data, c_worker
),
}
}
)
else:
cluster_workers = []
logger.info("current worker credit %s", credit_sum)
return credit_sum, cluster_workers, worker_credit_data
def cluster_worker_to_credit(flavors_data, cluster_worker):
"""
Return credit costs per hour
:param flavors_data: flavor data
:param cluster_worker: cluster data from worker
"""
fv_data = cluster_worker_to_flavor(flavors_data, cluster_worker)
if fv_data:
try:
credit = float(fv_data["flavor"]["credits_cost_per_hour"])
return credit
except KeyError:
logger.error("KeyError, missing credit in flavor data")
return 0
def worker_to_cluster_data(key, cluster_workers):
if cluster_workers:
for c_worker in cluster_workers:
if c_worker["hostname"] == key:
return c_worker
logger.error("worker %s not in cluster data", key)
return None
def cluster_worker_to_flavor(flavors_data, cluster_worker):
"""
Returns a corresponding flavor to a worker
:param flavors_data: flavor data
:param cluster_worker: cluster data from worker
:return: flavor
"""
if cluster_worker:
for fv_data in flavors_data:
if cluster_worker["flavor"] == fv_data["flavor"]["name"]:
return fv_data
logger.error("flavor not found for worker %s", cluster_worker["flavor"])
return None
def __csv_log_entry(scale_ud, worker_change, reason):
"""
DEBUG
Log current job and worker data
- refresh node and worker data
- write data to csv log
- if required create csv file with header.
:param scale_ud: marker
:param worker_change: scale count
:param reason: information
:return:
"""
logger.debug("---- __csv_log_entry %s ----", scale_ud)
header = [
"time",
"scale",
"worker_cnt",
"worker_cnt_use",
"worker_cnt_free",
"cpu_alloc",
"cpu_idle",
"mem_alloc",
"mem_idle",
"jobs_cnt_running",
"job_cnt_pending",
"jobs_cpu_alloc",
"jobs_cpu_pending",
"jobs_mem_alloc",
"jobs_mem_pending",
"worker_mem_alloc_drain",
"worker_mem_alloc",
"worker_mem_idle_drain",
"worker_mem_idle",
"worker_mem_mix_drain",
"worker_mem_mix",
"worker_drain_cnt",
"w_change",
"reason",
"credit",
"cluster_worker",
"worker_credit_data",
]
log_entry = {}
try:
if not os.path.exists(LOG_CSV) or os.path.getsize(LOG_CSV) == 0:
logger.debug("missing log file, create file and header")
__csv_writer(LOG_CSV, header)
if scale_ud == "C" and LOG_LEVEL == logging.DEBUG:
credit_, cluster_worker_list, worker_credit_data = cluster_credit_usage()
else:
credit_ = 0
cluster_worker_list = []
worker_credit_data = {}
jobs_pending_dict, jobs_running_dict = receive_job_data()
(
worker_json,
worker_count,
worker_in_use,
worker_drain,
_,
) = receive_node_data_db(True)
if worker_json is None:
return
log_entry.update({"time": __get_time()})
log_entry.update({"scale": scale_ud})
log_entry.update({"job_cnt_pending": len(jobs_pending_dict)})
log_entry.update({"jobs_cnt_running": len(jobs_running_dict)})
log_entry = {
**log_entry,
**__current_usage(worker_json, {**jobs_pending_dict, **jobs_running_dict}),
}
log_entry.update({"worker_cnt": worker_count})
log_entry.update({"worker_cnt_use": len(worker_in_use)})
log_entry.update({"worker_cnt_free": (worker_count - len(worker_in_use))})
log_entry.update({"worker_drain_cnt": len(worker_drain)})
log_entry.update({"worker_drain_cnt": len(worker_drain)})
log_entry.update({"w_change": worker_change})
log_entry.update({"reason": reason})
log_entry.update({"credit": credit_})
log_entry.update({"cluster_worker": len(cluster_worker_list)})
log_entry.update({"worker_credit_data": worker_credit_data})
except NameError as e:
logger.debug("job data from interface not usable, %s", e)
w_data = []
for data in header:
if data not in log_entry:
logger.debug("missing ", data)
continue
w_data.append(log_entry[data])
__csv_writer(LOG_CSV, w_data)
def __csv_writer(csv_file, log_data):
"""
Update log file.
:param csv_file: write to file
:param log_data: write this new line
:return:
"""
with open(csv_file, "a", newline="", encoding="utf8") as csvfile:
f_writer = csv.writer(csvfile, delimiter=",")