-
Notifications
You must be signed in to change notification settings - Fork 0
/
machines.py
1467 lines (1284 loc) · 68.4 KB
/
machines.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
import math
import json
import time
import uuid
import random
import threading
import configparser
import fabric
import openstack
CONFIG_FILE = "./config.ini"
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
MACHINES_FILE = json.load(open("./machines.json"))
MACHINES_PARADIGMS = MACHINES_FILE["machines"]
KEYPAIRS_PARADIGMS = MACHINES_FILE["keypairs"]
SECGROUPS_PARADIGMS = MACHINES_FILE["security_groups"]
# Initialize and turn on debug logging
openstack.enable_logging(debug=False)
# Initialize connections
conns = {}
VERBOSE = False
class ThreadWithReturnValue(threading.Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, daemon=None):
threading.Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon)
self._return = None
def run(self):
if self._target is not None:
self._return = self._target(*self._args,
**self._kwargs)
def join(self, *args):
threading.Thread.join(self, *args)
return self._return
class Report():
def __init__(self, status, data, errors, msg, it, t):
uniques = list(set(errors))
err = {}
for e in uniques:
err[str(e)] = errors.count(e)
self.status = status
self.data = data
self.errors = err
self.msg = msg
self.iterations = it
self.time = t
def to_dict(self):
data = self.data
try:
data = data.to_dict()
except:
pass
return {
"status": self.status,
"data": data,
"errors": self.errors,
"msg": self.msg,
"iterations": self.iterations,
"time": self.time
}
def to_json(self):
return json.dumps(self.to_dict())
def __str__(self):
return self.to_json()
def __repr__(self):
return self.to_json()
def get_status(self):
return self.status
def get_data(self):
return self.data
def get_errors(self):
return self.errors
def get_msg(self):
return self.msg
def get_iterations(self):
return self.iterations
def get_time(self):
return self.time
def debug_print(*args, **kwargs):
verbose = kwargs.get("verbose", VERBOSE)
try:
kwargs.pop("verbose")
except KeyError:
pass
if verbose:
print("["+str(time.strftime("%Y-%m-%d %H:%M:%S"))+"]", flush=True, *args, **kwargs)
def report(status, data, errors, msg, it, t):
return Report(status, data, errors, msg, it, t)
def connect_clouds(clouds, *, verbose=VERBOSE):
if clouds is not None:
if type(clouds) is str:
clouds = [clouds]
for cloud in clouds:
if cloud not in conns:
try:
conns[cloud] = openstack.connect(cloud=cloud)
debug_print(f"Connected to {cloud}", verbose=verbose)
except Exception as e:
debug_print(f"Error connecting to {cloud}: {e}", verbose=verbose)
def get_clouds(*, verbose=VERBOSE):
return conns.keys()
FLAVORS_HEURISTICS = { # Heuristics for sorting flavors, extendible by the user
"cpu-ram-disk": lambda x: (x.vcpus, x.ram, x.disk), #order by smallest vcpus, then smallest ram, then smallest disk
"cpu-disk-ram": lambda x: (x.vcpus, x.disk, x.ram),
"ram-cpu-disk": lambda x: (x.ram, x.vcpus, x.disk),
"ram-disk-cpu": lambda x: (x.ram, x.disk, x.vcpus),
"disk-cpu-ram": lambda x: (x.disk, x.vcpus, x.ram),
"disk-ram-cpu": lambda x: (x.disk, x.ram, x.vcpus),
}
def find_flavor(cloud, vcpus, ram, disk, heuristic="cpu-ram-disk", *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
conn = conns[cloud]
available = []
for flavor in conn.list_flavors():
if flavor.vcpus >= vcpus and flavor.ram >= ram and flavor.disk >= disk:
available.append(flavor)
if len(available) == 0:
return None
else:
try:
available.sort(key=FLAVORS_HEURISTICS[heuristic])
except Exception as e:
debug_print(f"Error sorting flavors: {e}", verbose=verbose)
return available[0]
def get_geographical_coordinates(address):
try:
import requests
import urllib.parse
url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) +'?format=json'
response = requests.get(url).json()
return float(response[0]["lat"]), float(response[0]["lon"])
except Exception as e:
return None,None
def geo_distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295
hav = 0.5 - math.cos((lat2-lat1)*p)/2 + math.cos(lat1*p)*math.cos(lat2*p) * (1-math.cos((lon2-lon1)*p)) / 2
return 12742 * math.asin(math.sqrt(hav))
def find_cloud_by_address(address, *, verbose=VERBOSE):
lat,lon = get_geographical_coordinates(address)
return find_cloud(lat,lon,verbose=verbose)
def find_cloud(latitude, longitude, *, verbose=VERBOSE):
min_dist = None
min_cloud = None
if "clouds" in MACHINES_FILE:
for c,data in MACHINES_FILE["clouds"].items():
#find nearest cloud
if "latitude" not in data or "longitude" not in data:
if "address" in data:
lat, lon = get_geographical_coordinates(data["address"])
if lat is None or lon is None:
continue
if "latitude" not in data:
data["latitude"] = lat
if "longitude" not in data:
data["longitude"] = lon
else:
continue
if "latitude" in data and "longitude" in data:
dist = geo_distance(latitude, longitude, data["latitude"], data["longitude"])
if min_dist is None or dist < min_dist:
min_dist = dist
min_cloud = c
return min_cloud
def get_servers(by_metadata={}, clouds=None, tokens={}, *, verbose=VERBOSE):
connect_clouds(clouds, verbose=verbose)
clouds = get_clouds(verbose=verbose) if clouds is None else ([clouds] if type(clouds) is str else clouds)
new_metadata = {}
for k, v in by_metadata.items():
new_metadata[apply_tokens(k, tokens)] = apply_tokens(v, tokens)
by_metadata = new_metadata
servers = []
if len(by_metadata.keys()) == 0:
for cloud in clouds:
for server in conns[cloud].compute.servers():
servers.append(server)
else:
for cloud in clouds:
for server in conns[cloud].compute.servers():
flag = True
for key, value in by_metadata.items():
if key in server.metadata:
if type(value) is list:
if server.metadata[key] not in value:
flag = False
elif server.metadata[key] != value:
flag = False
else:
flag = False
if flag:
servers.append(server)
return servers
def get_server(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
if cloud is None or cloud in get_clouds(verbose=verbose):
clouds = get_clouds(verbose=verbose) if cloud is None else [cloud]
for cloud in clouds:
for server in get_servers(clouds=cloud, verbose=verbose):
if server.name == server_name:
return server
debug_print(f"Server {server_name} not found", verbose=verbose)
return None
else:
debug_print(f"Cloud {cloud} not found", verbose=verbose)
return None
def get_server_cloud(server_name, *, verbose=VERBOSE):
for cloud in get_clouds(verbose=verbose):
if get_server(server_name, cloud, verbose=verbose):
return cloud
debug_print(f"Server {server_name} not found in any cloud", verbose=verbose)
return None
def get_server_type(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
if server:
try:
return server.metadata["type"]
except Exception as e:
debug_print(f"Error getting server type {server_name}: {e}", verbose=verbose)
return None
else:
return None
def get_server_flavor(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
if server:
return server.flavor.name
else:
return None
def get_server_metadata(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
if server:
return server.metadata
else:
return {}
def get_ip(server, *, verbose=VERBOSE):
if server:
try:
for data in server.addresses["default"]:
if data["addr"] != "" and (not data["addr"].startswith("192.168")) and (not data["addr"].startswith("10.")):
return data["addr"]
except Exception as e:
debug_print(f"Error getting server ip {server.name}: {e}", verbose=verbose)
return None
else:
return None
def get_server_ip(server_name, cloud=None, *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
server = get_server(server_name, cloud, verbose=verbose)
return get_ip(server)
def delete_server(conn, server, sleep=int(config["TUNING"]["wait_after_delete"]), max_it=int(config["TUNING"]["max_it_vm_delete"]), *, verbose=VERBOSE):
n = conn.delete_unattached_floating_ips()
debug_print(f"* {n} IPs released [delete_server]", verbose=verbose)
errors = []
for i in range(max_it):
try:
start = time.time()
server.delete(session=conn.compute)
end = time.time()
debug_print(f"Server {server.name} deleted", verbose=verbose)
time.sleep(sleep)
return report(True, server.to_dict(), errors, f"Server {server.name} deleted", i+1, end-start)
except Exception as e:
debug_print(f"Error deleting server {server.name}: {e}", verbose=verbose)
errors.append(str(e))
time.sleep(sleep)
return report(False, str(server), errors, f"Error deleting server {server.name}", i+1, 0)
def remove_machine(server_name, cloud=None, sleep=int(config["TUNING"]["wait_after_delete"]), max_it=int(config["TUNING"]["max_it_vm_delete"]), *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
if cloud is None:
cloud = get_server_cloud(server_name, verbose=verbose)
if cloud is None:
return report(False, None, [], f"Server {server_name} cloud not found", 0, 0)
if cloud in get_clouds(verbose=verbose):
conn = conns[cloud]
n = conn.delete_unattached_floating_ips()
debug_print(f"* {n} IPs released on {cloud} [remove_machine]", verbose=verbose)
server = conn.compute.find_server(server_name)
if server:
return delete_server(conns[cloud], server, sleep, max_it, verbose=verbose)
else:
debug_print(f"Server {server_name} not found in {cloud}", verbose=verbose)
return Report(False, None, [], f"Server {server_name} not found in {cloud}", 0, 0)
else:
debug_print(f"Cloud {cloud} not found", verbose=verbose)
return Report(False, None, [], f"Cloud {cloud} not found", 0, 0)
def remove_all_machines(by_metadata={}, clouds=None, tokens={}, sleep=int(config["TUNING"]["wait_after_delete"]), max_it=int(config["TUNING"]["max_it_vm_delete"]), *, verbose=VERBOSE, sure = False):
connect_clouds(clouds, verbose=verbose)
clouds = get_clouds(verbose=verbose) if clouds is None else ([clouds] if type(clouds) is str else clouds)
threads = []
results = []
new_metadata = {}
for k, v in by_metadata.items():
new_metadata[apply_tokens(k, tokens)] = apply_tokens(v, tokens)
by_metadata = new_metadata
if len(by_metadata.keys()) == 0 and sure:
for cloud in clouds:
for server in get_servers(clouds=cloud, verbose=verbose):
t = ThreadWithReturnValue(target=remove_machine, args=(server.name, cloud, sleep, max_it), kwargs={"verbose":verbose})
t.start()
threads.append(t)
elif len(by_metadata.keys()) > 0:
for cloud in clouds:
for server in get_servers(clouds=cloud, verbose=verbose):
flag = True
for key, value in by_metadata.items():
if key in server.metadata:
if type(value) is list:
if server.metadata[key] not in value:
flag = False
elif server.metadata[key] != value:
flag = False
else:
flag = False
if flag:
t = ThreadWithReturnValue(target=remove_machine, args=(server.name, cloud, sleep, max_it), kwargs={"verbose":verbose})
t.start()
threads.append(t)
else:
debug_print(f"No machine removed, please set the 'sure' flag to remove all the machines", verbose=verbose)
return results
for t in threads:
results.append(t.join())
return results
def create_server(name, type, cloud, metadata={}, heuristic="cpu-ram-disk", max_attempts=int(config["TUNING"]["max_it_vm_create"]), timeout=float(config["TUNING"]["timeout_vm_create"]), sleep_time=int(config["TUNING"]["wait_vm_create"]), *, verbose=VERBOSE):
connect_clouds(cloud, verbose=verbose)
errors = []
it = 0
if cloud is not None and cloud in get_clouds(verbose=verbose):
conn = conns[cloud]
n = conn.delete_unattached_floating_ips()
debug_print(f"* {n} IPs released on {cloud} [create_server]", verbose=verbose)
s = get_server(name, cloud, verbose=False)
print("Checking if server already exists", name, s)
if s is not None:
debug_print(f"Attention: Server {name} already exists in {cloud}", verbose=verbose)
print("Deleted",delete_server(conn, s, verbose=verbose))
time.sleep(sleep_time)
vm = None
if "metadata" in MACHINES_PARADIGMS[type]:
meta = MACHINES_PARADIGMS[type]["metadata"]
else:
meta = {}
for k,v in metadata.items(): # merge metadata with priority to metadata argument than with default metadata in MACHINES_PARADIGMS
meta[k] = v
meta["type"] = type
meta["cloud"] = cloud
meta["name"] = name
if "flavor" in MACHINES_PARADIGMS[type]:
flavor = MACHINES_PARADIGMS[type]["flavor"]
else:
specs = MACHINES_PARADIGMS[type]["specs"]
flavor = find_flavor(cloud, specs["vcpus"], specs["ram"], specs["disk"], heuristic=heuristic, verbose=verbose)
if flavor is None:
return report(status=False, data=None, errors=errors, msg=f"Could not find flavor for {type} ({specs['vcpus']} vcpus, {specs['ram']} ram, {specs['disk']} disk)", it=0, t=0)
else:
MACHINES_PARADIGMS[type]["flavor"] = flavor.name
debug_print(f"Found flavor {flavor.name} ({flavor.vcpus} vcpus, {flavor.ram} ram, {flavor.disk} disk) for {type} ({specs['vcpus']} vcpus, {specs['ram']} ram, {specs['disk']} disk)", verbose=verbose)
flavor = flavor.name
if "network" not in MACHINES_PARADIGMS[type]:
MACHINES_PARADIGMS[type]["network"] = "default"
if "security_groups" not in MACHINES_PARADIGMS[type]:
MACHINES_PARADIGMS[type]["security_groups"] = ["default"]
while vm is None and it < max_attempts:
try:
s = get_server(name, cloud, verbose=False)
print("Checking if server already exists", name, s)
if s is not None:
debug_print(f"Attention: Server {name} already exists in {cloud}", verbose=verbose)
print("Deleted",delete_server(conn, s, verbose=verbose))
time.sleep(sleep_time)
start = time.time()
vm = conn.create_server(name=name,
image=MACHINES_PARADIGMS[type]["image"],
flavor=flavor,
key_name=MACHINES_PARADIGMS[type]["key_name"],
security_groups=MACHINES_PARADIGMS[type]["security_groups"],
network=MACHINES_PARADIGMS[type]["network"],
meta=meta,
wait=True,
auto_ip=True,
timeout=timeout,
reuse_ips=True
)
end = time.time()
debug_print(f"Server {name} created", verbose=verbose)
return report(status=True, data=vm.to_dict(), errors=errors, msg=f"Server {name} created", it=it+1, t=end-start)
except Exception as e:
debug_print(f"Error creating server {name}: {e}", verbose=verbose)
it += 1
errors.append(str(e))
time.sleep(sleep_time)
remove_machine(name, cloud, verbose=verbose)
err_msg = "Error creating server {name}".format(name=name)
else:
debug_print(f"Cloud {cloud} not found", verbose=verbose)
err_msg = "Cloud {cloud} not found".format(cloud=cloud)
return report(status=False, data=None, errors=errors, msg=err_msg, it=it+1, t=0)
# Python3 program to find the smallest window
# containing all characters of a pattern.
no_of_chars = 256
# Function to find smallest window
# containing all characters of 'pat'
def findSubString(string, pat, starts_with="", ends_with=""):
pat = starts_with + pat + ends_with
len1 = len(string)
len2 = len(pat)
# Check if string's length is
# less than pattern's
# length. If yes then no such
# window can exist
if len1 < len2:
return None
hash_pat = [0] * no_of_chars
hash_str = [0] * no_of_chars
# Store occurrence ofs characters of pattern
for i in range(0, len2):
hash_pat[ord(pat[i])] += 1
start, start_index, min_len = 0, -1, float('inf')
# Start traversing the string
count = 0 # count of characters
for j in range(0, len1):
# count occurrence of characters of string
hash_str[ord(string[j])] += 1
# If string's char matches with
# pattern's char then increment count
if (hash_str[ord(string[j])] <=
hash_pat[ord(string[j])]):
count += 1
# if all the characters are matched
if count == len2:
# Try to minimize the window
while (hash_str[ord(string[start])] >
hash_pat[ord(string[start])] or
hash_pat[ord(string[start])] == 0):
if (hash_str[ord(string[start])] >
hash_pat[ord(string[start])]):
hash_str[ord(string[start])] -= 1
start += 1
# update window size
len_window = j - start + 1
if min_len > len_window and (starts_with == "" or string[start] == starts_with) and (ends_with == "" or min_len==float('inf') or string[start+min_len] == ends_with):
min_len = len_window
start_index = start
# If no window found
if start_index == -1:
return None
# Return substring starting from
# start_index and length min_len
return string[start_index: start_index + min_len]
SEMANTIC_TOKENS_STATUS = {
}
def semantic_token_inc(token, server_name, cloud):
original = ""
for t in token:
original += str(t)+"_"
original = original[:-1]
if original not in SEMANTIC_TOKENS_STATUS:
SEMANTIC_TOKENS_STATUS[original] = 0
else:
SEMANTIC_TOKENS_STATUS[original] += 1
return SEMANTIC_TOKENS_STATUS[original]
def semantic_token_id(token, server_name, cloud):
original = ""
for t in token:
original += str(t)+"_"
original = original[:-1]
if original not in SEMANTIC_TOKENS_STATUS:
SEMANTIC_TOKENS_STATUS[original] = uuid.uuid4()
return SEMANTIC_TOKENS_STATUS[original]
SEMANTIC_TOKENS = { #extendible by the user
"CLOUD": {
"elements": 0,
"function": lambda token,server_name,cloud: get_server_cloud(server_name) if server_name is not None else cloud
},
"HOSTNAME": {
"elements": 0,
"function": lambda token,server_name,cloud: server_name
},
"ID": {
"elements": 1,
"function": semantic_token_id
},
"RANDOM": {
"elements": 2,
"function": lambda token,server_name,cloud: random.randint(int(token[1]), int(token[2]))
},
"INC": {
"elements": 1,
"function": semantic_token_inc
}
}
def apply_semantic_tokens(string, server_name=None, cloud=None):
global SEMANTIC_TOKENS_STATUS
for pat in SEMANTIC_TOKENS.keys():
size = int((SEMANTIC_TOKENS[pat]["elements"]))
exist = True
while exist:
token = findSubString(string, pat+("_"*size), starts_with="<", ends_with=">")
if token is not None:
original = token
token = token.replace("<", "").replace(">", "").split("_")
try:
if len(token) == size+1:
value = SEMANTIC_TOKENS[pat]["function"](token,server_name,cloud)
if value is not None:
string = string.replace(original, str(value), 1)
else:
exist = False
except Exception as e:
debug_print(f"Error applying semantic token {pat} to string {string}, server_name={server_name}, cloud={cloud}: {e}")
exist = False
else:
exist = False
return string
def apply_tokens(string, tokens, server_name=None, cloud=None):
if type(string) is str:
string = apply_semantic_tokens(string, server_name=server_name, cloud=cloud)
for k,v in tokens.items():
string = string.replace(k, v)
elif type(string) is list:
for i in range(len(string)):
string[i] = apply_tokens(string[i], tokens, server_name=server_name, cloud=cloud)
return string
def apply_tokens_list(script, tokens, server_name=None, cloud=None):
script = script.copy()
for i in range(len(script)):
script[i] = apply_tokens(script[i], tokens, server_name=server_name, cloud=cloud)
return script
def exec_script_by_ip(ip, script, user, key_filename, tokens={}, hide=True, timeout_cmd=int(config["TUNING"]["script_connect_timeout"]), max_script_attempts=int(config["TUNING"]["max_it_vm_execute_script"]), sleep_script=int(config["TUNING"]["wait_vm_execute_script"]), max_cmd_attempts=int(config["TUNING"]["max_it_vm_execute_cmd"]), sleep_cmd=int(config["TUNING"]["wait_vm_execute_cmd"]), server_name = "", *, verbose=VERBOSE):
script = apply_tokens_list(script, tokens, server_name=server_name)
debug_print(f"Executing script on {server_name} {ip}: {script}", verbose=verbose)
retry = True
errors = []
it = 0
msg = ""
last = None
if type(script) is not list:
debug_print(f"Script {script} for {server_name} is not a list", verbose=verbose)
return report(status=False, data=None, errors=errors, msg=f"Script {script} for {server_name} is not a list", it=0, t=0)
while retry:
debug_print("Trying to connect to {} ({})".format(server_name, ip), verbose=verbose)
start = time.time()
try:
if timeout_cmd != 0:
vm = fabric.Connection(ip,
user=user,
connect_kwargs={
"key_filename": key_filename,
},
connect_timeout = timeout_cmd,
)
else:
vm = fabric.Connection(ip,
user=user,
connect_kwargs={
"key_filename": key_filename,
},
)
debug_print("Connected to {} ({})".format(server_name, ip), verbose=verbose)
for cmd in script:
time.sleep(sleep_cmd)
debug_print("Executing command {} on {} ({})".format(cmd, server_name, ip), verbose=verbose)
t = 0
exc = None
while t < max_cmd_attempts:
try:
if timeout_cmd != 0:
last = vm.run(cmd, hide=hide, warn=True, timeout=timeout_cmd)
else:
last = vm.run(cmd, hide=hide, warn=True)
break
except Exception as e1:
debug_print("Error while '{}': {} on {} ({}) [{}/{}]".format(cmd, e1, server_name, ip, t+1, max_cmd_attempts), verbose=verbose)
errors.append(str(e1))
t += 1
exc = e1
time.sleep(1)
if exc is not None and t == max_cmd_attempts:
debug_print("Failed to connect to {} ({})".format(server_name, ip), verbose=verbose)
raise exc
end = time.time()
vm.close()
debug_print("Script executed on {} ({})".format(server_name, ip), verbose=verbose)
return report(status=True, data=str(last), errors=errors, msg=f"Script executed on {server_name} ({ip})", it=it+1, t=end-start)
except Exception as e:
debug_print(f"Error connecting to {server_name} ({ip}): {e}", verbose=verbose)
errors.append(str(e))
if len(e.args) == 2 and (not e.args[1].startswith("Unable to connect to port 22 on 90.147")):
print("Args",e.args)
it += 1
msg = f"Error connecting to {server_name} ({ip}): {e}"
if len(e.args) == 2 and any(err for err in ["Unable to connect", "Connection refused", "Encountered a bad command exit code"] if err.lower() in e.args[1].lower()): # "Timeout waiting for the server to come up"
if it < max_script_attempts:
time.sleep(sleep_script)
else:
retry = False
else:
retry = False
return report(status=False, data=None, errors=errors, msg=msg, it=it+1, t=0)
def exec_script(server_name, script, tokens={}, hide=True, timeout_cmd=int(config["TUNING"]["script_connect_timeout"]), max_script_attempts=int(config["TUNING"]["max_it_vm_execute_script"]), sleep_script=int(config["TUNING"]["wait_vm_execute_script"]), max_cmd_attempts=int(config["TUNING"]["max_it_vm_execute_cmd"]), sleep_cmd=int(config["TUNING"]["wait_vm_execute_cmd"]), *, verbose=VERBOSE):
ip = get_server_ip(server_name, verbose=verbose)
if ip is None:
debug_print(f"Server {server_name} IP not found", verbose=verbose)
return report(status=False, data=None, errors=[], msg=f"Server {server_name} IP not found", it=0, t=0)
debug_print("Executing script on {} ({})".format(server_name, ip), verbose=verbose)
server_type = get_server_type(server_name)
if server_type is None:
debug_print(f"Server {server_name} type not found", verbose=verbose)
return report(status=False, data=None, errors=[], msg=f"Server {server_name} type not found", it=0, t=0)
try:
key_filename = KEYPAIRS_PARADIGMS[MACHINES_PARADIGMS[server_type]["key_name"]]["key_filename"]
user = KEYPAIRS_PARADIGMS[MACHINES_PARADIGMS[server_type]["key_name"]]["user"]
except Exception as e:
debug_print(f"Error getting key_filename for {server_name}: {e}", verbose=verbose)
return report(status=False, data=None, errors=[str(e)], msg=f"Error getting key_filename for {server_name}", it=0, t=0)
if type(script) is str:
try:
script = MACHINES_PARADIGMS[server_type]["scripts"][script]
except Exception as e:
debug_print(f"Error getting script {script} for {server_name}: {e}", verbose=verbose)
return report(status=False, data=None, errors=[str(e)], msg=f"Error getting script {script} for {server_name} ({server_type})", it=0, t=0)
new_tokens = {}
try:
new_tokens = MACHINES_FILE["tokens"]
except Exception as e:
pass
try:
for k, v in MACHINES_PARADIGMS[server_type]["tokens"].items():
new_tokens[k] = v
except Exception as e:
pass
for k, v in tokens.items():
new_tokens[k] = v
return exec_script_by_ip(ip, script, user, key_filename, new_tokens, hide, timeout_cmd, max_script_attempts, sleep_script, max_cmd_attempts, sleep_cmd, server_name=server_name, verbose=verbose)
def exec_script_on_thread(server_name, script, tokens={}, hide=True, timeout_cmd=int(config["TUNING"]["script_connect_timeout"]), max_script_attempts=int(config["TUNING"]["max_it_vm_execute_script"]), sleep_script=int(config["TUNING"]["wait_vm_execute_script"]), max_cmd_attempts=int(config["TUNING"]["max_it_vm_execute_cmd"]), sleep_cmd=int(config["TUNING"]["wait_vm_execute_cmd"]), *, verbose=VERBOSE):
t = ThreadWithReturnValue(target=exec_script, args=(server_name, script, tokens, hide, timeout_cmd, max_script_attempts, sleep_script, max_cmd_attempts, sleep_cmd), kwargs={"verbose":verbose})
t.start()
return t
SERVERS_HEURISTICS = {
"enum": lambda x: x,
"random": lambda x: random.shuffle(x),
"alphabetical": lambda x: sorted(x, key=lambda x: x.name),
"alphabetical_reverse": lambda x: sorted(x, key=lambda x: x.name, reverse=True)
}
def exec_script_machines(script, by_metadata={}, clouds=None, tokens={}, count=float("inf"), heuristic="enum", hide=True, timeout_cmd=int(config["TUNING"]["script_connect_timeout"]), max_script_attempts=int(config["TUNING"]["max_it_vm_execute_script"]), sleep_script=int(config["TUNING"]["wait_vm_execute_script"]), max_cmd_attempts=int(config["TUNING"]["max_it_vm_execute_cmd"]), sleep_cmd=int(config["TUNING"]["wait_vm_execute_cmd"]), *, verbose=VERBOSE):
connect_clouds(clouds, verbose=verbose)
new_metadata = {}
for k, v in by_metadata.items():
new_metadata[apply_tokens(k, tokens)] = apply_tokens(v, tokens)
by_metadata = new_metadata
servers = []
threads = []
clouds = get_clouds(verbose=verbose) if clouds is None else ([clouds] if type(clouds) is str else clouds)
if len(by_metadata.keys()) == 0:
for cloud in clouds:
for server in get_servers(clouds=cloud, verbose=verbose):
if server.status == "ACTIVE":
servers.append(server)
else:
for cloud in clouds:
for server in get_servers(clouds=cloud, verbose=verbose):
flag = True
for key, value in by_metadata.items():
if key in server.metadata:
if type(value) is list:
if server.metadata[key] not in value:
flag = False
elif server.metadata[key] != value:
flag = False
else:
flag = False
if flag and server.status == "ACTIVE":
servers.append(server)
try:
servers = SERVERS_HEURISTICS[heuristic](servers)
except Exception as e:
debug_print(f"Error executing heuristic {heuristic}: {e}", verbose=verbose)
c = 0
for server in servers:
if c < count:
threads.append(exec_script_on_thread(server.name, script, tokens, hide, timeout_cmd, max_script_attempts, sleep_script, max_cmd_attempts, sleep_cmd, verbose=verbose))
c += 1
else:
break
results = []
for t in threads:
results.append(t.join())
return results
def get_tasks(server_name=None, type=None):
if type is None:
try:
metadata = get_server_metadata(server_name)
type = metadata["type"]
except Exception as e:
debug_print(f"Error in get_tasks getting type for {server_name}: {e}")
return None
try:
return MACHINES_PARADIGMS[type]["tasks"]
except Exception as e:
debug_print(f"Error in get_tasks getting tasks for {server_name}: {e}")
return []
def get_task(server_name=None, type=None, name=None):
tasks = get_tasks(server_name, type)
if tasks is None:
return None
for step in tasks:
for task in step:
if task["name"] == name:
return task
return None
def add_machine(name, type, cloud, metadata={}, tokens={}, heuristic="cpu-ram-disk", random_sleep=int(config["TUNING"]["random_sleep_vm_create"]), setup_timeout=float(config["TUNING"]["timeout_vm_setup"]), max_attempts=int(config["TUNING"]["max_it_vm_setup"]), sleep=int(config["TUNING"]["sleep_vm_setup"]), max_create_attempts=int(config["TUNING"]["max_it_vm_create"]), create_timeout=float(config["TUNING"]["timeout_vm_create"]), create_sleep_time=int(config["TUNING"]["wait_vm_create"]), *, verbose=VERBOSE, verbose_script=VERBOSE):
connect_clouds(cloud, verbose=verbose)
time.sleep(random.random() * random_sleep)
retry = True
it = 0
name = apply_tokens(name, tokens, cloud=cloud)
new_metadata = {}
for k, v in metadata.items():
new_metadata[apply_tokens(k, tokens, name, cloud)] = apply_tokens(v, tokens, name, cloud)
metadata = new_metadata
while retry:
result = {}
debug_print("Creating VM {} ({}) on {}".format(name, type, cloud), verbose=verbose)
vm = create_server(name, type, cloud, metadata, heuristic, max_create_attempts, create_timeout, create_sleep_time, verbose=verbose).to_dict()
if vm["status"] is False:
debug_print(f"Error creating VM {name} ({type}) on {cloud}", verbose=verbose)
return report(status=False, data={"create":vm,"setup":None}, errors=[], msg=f"Error creating VM {name} ({type}) on {cloud}", it=it+1, t=0)
else:
ip = None
start = time.time()
while ip is None and time.time() - start < setup_timeout:
ip = get_server_ip(name, verbose=verbose)
time.sleep(1)
if ip is None:
debug_print("Error getting IP for {}".format(name), verbose=verbose)
return report(status=False, data={"create":vm,"setup":None}, errors=[], msg=f"Timeout waiting for {name} IP", it=it+1, t=0)
debug_print("VM {} ({}) created".format(name, ip), verbose=verbose)
if "setup" not in MACHINES_PARADIGMS[type]["scripts"]:
MACHINES_PARADIGMS[type]["scripts"]["setup"] = []
if "files" not in MACHINES_PARADIGMS[type]:
MACHINES_PARADIGMS[type]["files"] = []
tasks = get_tasks(name, type)
if tasks is not None:
for step in tasks:
for task in step:
if "setup" in task:
for cmd in task["setup"]:
if cmd not in MACHINES_PARADIGMS[type]["scripts"]["setup"]:
MACHINES_PARADIGMS[type]["scripts"]["setup"].append(cmd)
if "files" in task:
for file in task["files"]:
if file not in MACHINES_PARADIGMS[type]["files"]:
MACHINES_PARADIGMS[type]["files"].append(file)
delta = 0
if "setup" in MACHINES_PARADIGMS[type]["scripts"] and len(MACHINES_PARADIGMS[type]["scripts"]["setup"]) > 0:
debug_print("Setting up VM {} ({})".format(name, ip), verbose=verbose)
start = time.time()
while delta < setup_timeout:
result = exec_script(name, "setup", tokens=tokens, hide=(not verbose_script), timeout_cmd=setup_timeout, max_script_attempts=1, sleep_script=1, max_cmd_attempts=1, sleep_cmd=1, verbose=False).to_dict()
if result["status"]:
break
delta = time.time() - start
time.sleep(1)
if result["status"] is False:
debug_print("Error setting up VM {} ({}): {}".format(name, ip, result["msg"]), verbose=verbose)
remove_machine(name, verbose=verbose)
it += 1
if it >= max_attempts:
retry = False
debug_print("Max attempts reached for {}".format(name), verbose=verbose)
remove_machine(name, verbose=verbose)
return report(status=False, data={"create":vm,"setup":result}, errors=[], msg=f"Max attempts reached for {name}", it=it+1, t=0)
else:
time.sleep(sleep)
else:
retry = False
else:
retry = False
files = {}
if ip is not None and "files" in MACHINES_PARADIGMS[type] and len(MACHINES_PARADIGMS[type]["files"]) > 0:
debug_print("Copying files to VM {} ({})".format(name, ip), verbose=verbose)
try:
files = MACHINES_PARADIGMS[type]["files"]
key_filename = KEYPAIRS_PARADIGMS[MACHINES_PARADIGMS[type]["key_name"]]["key_filename"]
user = KEYPAIRS_PARADIGMS[MACHINES_PARADIGMS[type]["key_name"]]["user"]
timeout_cmd=int(config["TUNING"]["script_connect_timeout"])
if timeout_cmd != 0:
c = fabric.Connection(ip,
user=user,
connect_kwargs={
"key_filename": key_filename,
},
connect_timeout = timeout_cmd,
)
else:
c = fabric.Connection(ip,
user=user,
connect_kwargs={
"key_filename": key_filename,
},
)
for file in files:
try:
source = file["source"]
source = apply_tokens(source, tokens, name, cloud)
destination = file["destination"]
destination = apply_tokens(destination, tokens, name, cloud)
c.put(source, destination)
file["result"] = True
c.close()
except Exception as e:
file["result"] = str(e)
debug_print("Files copied to VM {} ({})".format(name, ip), verbose=verbose)
except Exception as e:
debug_print("Error copying files to VM {} ({}): {}".format(name, ip, e), verbose=verbose)
files = report(status=False, data={"create":vm,"setup":result}, errors=[str(e)], msg=f"Error connecting to {name} ({ip}) to upload files", it=it+1, t=delta).to_dict()
debug_print("VM {} ({}) setup completed".format(name, ip), verbose=verbose)
return report(status=True, data={"create":vm,"setup":result, "files":files}, errors=[], msg=f"VM {name} ({ip}) created", it=it+1, t=delta)
class VMThread(threading.Thread):
def __init__(self, name, type, cloud, metadata={}, tokens={}, heuristic="cpu-ram-disk", random_sleep=int(config["TUNING"]["random_sleep_vm_create"]), setup_timeout=float(config["TUNING"]["timeout_vm_setup"]), max_attempts=int(config["TUNING"]["max_it_vm_setup"]), sleep=int(config["TUNING"]["sleep_vm_setup"]), max_create_attempts=int(config["TUNING"]["max_it_vm_create"]), create_timeout=float(config["TUNING"]["timeout_vm_create"]), create_sleep_time=int(config["TUNING"]["wait_vm_create"]), *, verbose=VERBOSE, verbose_script=VERBOSE):
threading.Thread.__init__(self, target=add_machine, args=(name, type, cloud, metadata, tokens, heuristic, random_sleep, setup_timeout, max_attempts, sleep, max_create_attempts, create_timeout, create_sleep_time), kwargs={"verbose":verbose, "verbose_script":verbose_script})
self._return = None
def run(self):
self._return = self._target(*self._args, **self._kwargs)
def join(self, *args):
threading.Thread.join(self, *args)
return self._return
def add_machines(specs, tokens={}, heuristic="cpu-ram-disk", random_sleep=int(config["TUNING"]["random_sleep_vm_create"]), setup_timeout=float(config["TUNING"]["timeout_vm_setup"]), max_attempts=int(config["TUNING"]["max_it_vm_setup"]), sleep=int(config["TUNING"]["sleep_vm_setup"]), max_create_attempts=int(config["TUNING"]["max_it_vm_create"]), create_timeout=float(config["TUNING"]["timeout_vm_create"]), create_sleep_time=int(config["TUNING"]["wait_vm_create"]), *, verbose=VERBOSE, verbose_script=VERBOSE):
threads = []
for name,spec in specs.items():
type = spec["type"]
metadata = {}
if "metadata" in spec:
metadata = spec["metadata"]
for cloud,count in spec["clouds"].items():
connect_clouds(cloud, verbose=verbose)
for _ in range(count):
t = VMThread(str(name), type, cloud, metadata, tokens, heuristic, random_sleep, setup_timeout, max_attempts, sleep, max_create_attempts, create_timeout, create_sleep_time, verbose=verbose, verbose_script=verbose_script)
t.start()
threads.append(t)
results = []
for t in threads:
results.append(t.join())
return results
def update_server(metadata, conn, server, sleep=int(config["TUNING"]["wait_after_update"]), max_it=int(config["TUNING"]["max_it_vm_update"]), *, verbose=VERBOSE):
errors = []
for i in range(max_it):
try:
old_metadata = get_server_metadata(server.name, verbose=verbose)
to_remove = []
for k, v in metadata.items():
if k not in ["type", "name", "cloud"]:
if (v is None or v.trim() == "" or v.lower() == "none" or v.lower() == "null"):
to_remove.append(k)
if k in old_metadata:
del old_metadata[k]
else:
old_metadata[k] = v
start = time.time()
conn.delete_server_metadata(server, to_remove)
time.sleep(sleep)
conn.set_server_metadata(server, old_metadata)
end = time.time()
debug_print(f"Server {server.name} updated", verbose=verbose)
time.sleep(sleep)