-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathInfrastructureManager.py
2069 lines (1701 loc) · 84.4 KB
/
InfrastructureManager.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
# IM - Infrastructure Manager
# Copyright (C) 2011 - GRyCAP - Universitat Politecnica de Valencia
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import yaml
import json
import os
import string
import random
import logging
import threading
import IM.InfrastructureInfo
import IM.InfrastructureList
from IM.VMRC import VMRC
from IM.AppDBIS import AppDBIS
from IM.AppDB import AppDB
from IM.CloudInfo import CloudInfo
from IM.auth import Authentication
from IM.recipe import Recipe
from IM.config import Config
from IM.VirtualMachine import VirtualMachine
from radl import radl_parse
from radl.radl import Feature, RADL, system
from radl.radl_json import dump_radl as dump_radl_json
from IM.openid.JWT import JWT
from IM.openid.OpenIDClient import OpenIDClient
from IM.vault import VaultCredentials
from IM.Stats import Stats
if Config.MAX_SIMULTANEOUS_LAUNCHES > 1:
from multiprocessing.pool import ThreadPool
try:
unicode("hola")
except NameError:
unicode = str
class UnauthorizedUserException(Exception):
""" Invalid InfrastructureManager credentials to access an infrastructure"""
def __init__(self, msg="Access to this infrastructure not granted."):
Exception.__init__(self, msg)
self.message = msg
class IncorrectInfrastructureException(Exception):
""" Invalid infrastructure ID or access not granted. """
def __init__(self, msg="Invalid infrastructure ID or access not granted."):
Exception.__init__(self, msg)
self.message = msg
class DeletedInfrastructureException(Exception):
""" Deleted infrastructure. """
def __init__(self, msg="Deleted infrastructure."):
Exception.__init__(self, msg)
self.message = msg
class InvaliddUserException(Exception):
""" Invalid InfrastructureManager credentials """
def __init__(self, msg="Invalid InfrastructureManager credentials"):
Exception.__init__(self, msg)
self.message = msg
class DisabledFunctionException(Exception):
""" Disabled function called"""
def __init__(self, msg="Function currently disabled."):
Exception.__init__(self, msg)
self.message = msg
class InfrastructureManager:
"""
Front-end to the functionality of the service.
"""
logger = logging.getLogger('InfrastructureManager')
"""Logger object."""
@staticmethod
def _reinit():
"""Restart the class attributes to initial values."""
IM.InfrastructureList.InfrastructureList._reinit()
@staticmethod
def _compute_deploy_groups(radl):
"""
Group the virtual machines that had to be deployed together.
Args:
- radl(RADL): RADL to consider.
Return(list of list of deploy): list of group of deploys.
"""
# If some virtual machine is in two private networks, the machines in both
# networks will be in the same group
# NOTE: net_groups is a *Disjoint-set data structure*
net_groups = {}
for net in radl.networks:
net_groups[net.id] = net.id
def root(n):
while True:
n0 = net_groups[n]
if n0 == n:
return n
n = n0
for d in radl.deploys:
private_nets = [net.id for net in radl.networks if not net.isPublic() and
net.id in radl.get_system_by_name(d.id).getNetworkIDs()]
if not private_nets:
continue
for n in private_nets[1:]:
net_groups[root(n)] = net_groups[root(private_nets[0])]
deploy_groups = []
deploy_groups_net = {}
for d in radl.deploys:
private_nets = [net.id for net in radl.networks if not net.isPublic() and
net.id in radl.get_system_by_name(d.id).getNetworkIDs()]
# If no private net is set, every launch can go in a separate group
if not private_nets:
for _ in range(d.vm_number):
d0 = d.clone()
d0.vm_number = 1
deploy_groups.append([d0])
continue
# Otherwise the deploy goes to some group
net = net_groups[root(private_nets[0])]
if net not in deploy_groups_net:
deploy_groups_net[net] = [d]
else:
deploy_groups_net[net].append(d)
deploy_groups.extend(deploy_groups_net.values())
return deploy_groups
@staticmethod
def _launch_deploy(sel_inf, dep, cloud_id, cloud, concrete_systems, radl, auth, deployed_vm):
"""Launch a deploy."""
# Clone the deploy to avoid changes in the original inf deploys
deploy = dep.clone()
if deploy.vm_number <= 0:
InfrastructureManager.logger.warning(
"Inf ID: %s: deploy %s with 0 num: Ignoring." % (sel_inf.id, deploy.id))
return
if not deploy.id.startswith(IM.InfrastructureInfo.InfrastructureInfo.FAKE_SYSTEM):
concrete_system = concrete_systems[cloud_id][deploy.id][0]
launched_vms = []
launch_radl = radl.clone()
requested_radl = radl.clone()
requested_radl.systems = [radl.get_system_by_name(deploy.id)]
if not concrete_system:
InfrastructureManager.logger.error("Inf ID: " + str(sel_inf.id) +
". Error, no concrete system to deploy: " +
deploy.id + " in cloud: " + cloud_id +
". Check if a correct image is being used")
for _ in range(deploy.vm_number):
launched_vms.append((False, "Error, no concrete system to deploy: " + deploy.id +
" in cloud: " + cloud_id + ". Check if a correct image is being used"))
else:
launch_radl = radl.clone()
launch_radl.systems = [concrete_system.clone()]
requested_radl = radl.clone()
requested_radl.systems = [radl.get_system_by_name(concrete_system.name)]
(username, _, _, _) = concrete_system.getCredentialValues()
if not username:
for _ in range(deploy.vm_number):
launched_vms.append((False, "No username for deploy: " + deploy.id))
else:
InfrastructureManager.logger.debug("Inf ID: %s. Launching %d VMs of type %s" %
(sel_inf.id, deploy.vm_number, concrete_system.name))
launched_vms = cloud.cloud.getCloudConnector(sel_inf).launch_with_retry(
sel_inf, launch_radl, requested_radl, deploy.vm_number, auth, Config.MAX_VM_FAILS,
Config.DELAY_BETWEEN_VM_RETRIES)
# this must never happen ...
if len(launched_vms) < deploy.vm_number:
for _ in range(deploy.vm_number - len(launched_vms)):
launched_vms.append((False, "Error in deploy: " + deploy.id))
for success, launched_vm in launched_vms:
if success:
InfrastructureManager.logger.debug("Inf ID: %s. VM successfully launched: %s" % (sel_inf.id,
launched_vm.id))
deployed_vm.setdefault(deploy, []).append(launched_vm)
deploy.cloud_id = cloud_id
else:
InfrastructureManager.logger.error("Inf ID: %s. Error launching some of the "
"VMs: %s" % (sel_inf.id, launched_vm))
vm = VirtualMachine(sel_inf, None, cloud.cloud, launch_radl, requested_radl)
vm.state = VirtualMachine.FAILED
vm.info.systems[0].setValue('state', VirtualMachine.FAILED)
vm.error_msg = "Error launching the VMs of type %s to cloud ID %s of type %s. %s" % (
deploy.id, cloud.cloud.id, cloud.cloud.type, launched_vm)
sel_inf.add_vm(vm)
deployed_vm.setdefault(deploy, []).append(vm)
deploy.cloud_id = cloud_id
@staticmethod
def get_infrastructure(inf_id, auth):
"""Return infrastructure info with some id if valid authorization provided."""
if inf_id not in IM.InfrastructureList.InfrastructureList.get_inf_ids():
InfrastructureManager.logger.error("Error, incorrect Inf ID: %s" % inf_id)
raise IncorrectInfrastructureException()
sel_inf = IM.InfrastructureList.InfrastructureList.get_infrastructure(inf_id)
if not sel_inf:
InfrastructureManager.logger.error("Error loading Inf ID: %s" % inf_id)
raise IncorrectInfrastructureException("Error loading Inf ID data.")
if not sel_inf.is_authorized(auth):
InfrastructureManager.logger.error("Access Error to Inf ID: %s" % inf_id)
raise UnauthorizedUserException()
if sel_inf.deleted:
InfrastructureManager.logger.error("Inf ID: %s is deleted." % inf_id)
raise DeletedInfrastructureException()
return sel_inf
@staticmethod
def get_vm_from_inf(inf_id, vm_id, auth):
"""Return VirtualMachie info with some id of an infrastructure if valid authorization provided."""
sel_inf = InfrastructureManager.get_infrastructure(inf_id, auth)
return sel_inf.get_vm(vm_id)
@staticmethod
def Reconfigure(inf_id, radl_data, auth, vm_list=None):
"""
Add and update RADL definitions and reconfigure the infrastructure.
Args:
- inf_id(str): infrastructure id.
- radl_data(str): RADL description, it can be empty.
- auth(Authentication): parsed authentication tokens.
- vm_list(list of int): List of VM ids to reconfigure. If None all VMs will be reconfigured.
Return: "" if success.
"""
if Config.BOOT_MODE in [1, 2]:
raise DisabledFunctionException()
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info("Reconfiguring the Inf ID: " + str(inf_id))
if isinstance(radl_data, RADL):
radl = radl_data
else:
radl = radl_parse.parse_radl(radl_data)
InfrastructureManager.logger.debug("Inf ID: " + str(inf_id) + ": \n" + str(radl))
sel_inf = InfrastructureManager.get_infrastructure(inf_id, auth)
# Update infrastructure RADL with this new RADL
# Add or update configures
for s in radl.configures:
# first check that the YAML is correct
if s.recipes:
try:
yaml.safe_load(s.recipes)
except Exception as ex:
raise Exception("Error parsing YAML: %s" % str(ex))
sel_inf.radl.add(s.clone(), "replace")
InfrastructureManager.logger.info(
"Inf ID: " + sel_inf.id + ": " +
"(Re)definition of %s %s" % (type(s), s.getId()))
# and update contextualize
sel_inf.radl.add(radl.contextualize)
# Check if the user want to set a new password to any system:
for radl_system in sel_inf.radl.systems:
new_system = radl.get_system_by_name(radl_system.name)
if new_system:
new_creds = new_system.getCredentialValues(new=True)
# The user has specified a credential:
if len(list(set(new_creds))) > 1 or list(set(new_creds))[0] is not None:
creds = radl_system.getCredentialValues()
if new_creds != creds:
# The credentials have changed
(_, password, public_key, private_key) = new_creds
radl_system.setCredentialValues(
password=password, public_key=public_key, private_key=private_key, new=True)
# The user has new applications
curr_apps = radl_system.getValue("disk.0.applications")
if curr_apps is None:
curr_apps = {}
curr_apps_names = {}
if curr_apps:
for app_name in curr_apps.keys():
orig_app_name = app_name
if "," in app_name:
# remove version substring
pos = app_name.find(",")
app_name = app_name[:pos]
curr_apps_names[app_name] = orig_app_name
new_apps = new_system.getValue("disk.0.applications")
if new_apps:
for app_name, app in new_apps.items():
orig_app_name = app_name
if "," in app_name:
# remove version substring
pos = app_name.find(",")
app_name = app_name[:pos]
if app_name in list(curr_apps_names.keys()):
del curr_apps[curr_apps_names[app_name]]
curr_apps[orig_app_name] = app
# Stick all virtual machines to be reconfigured
InfrastructureManager.logger.info("Contextualize the Inf ID: " + sel_inf.id)
# reset ansible_configured to force the re-installation of galaxy roles
sel_inf.ansible_configured = None
sel_inf.Contextualize(auth, vm_list)
IM.InfrastructureList.InfrastructureList.save_data(inf_id)
return ""
@staticmethod
def _compute_score(system_score, requested_radl):
"""
Computes the score of a concrete radl comparing with the requested one.
Args:
- system_score(tuple(radl.system, int)): System object to deploy and the score
- requested_radl(radl.system): Original system requested by the user.
Return(tuple(radl.system, int)): System object to deploy and the new computed score
"""
concrete_system, score = system_score
req_apps = requested_radl.getApplications()
inst_apps = concrete_system.getApplications()
# Set highest priority to the original score
score *= 10000
# For each requested app installed in the VMI score with +100
if inst_apps:
for req_app in req_apps:
for inst_app in inst_apps:
if inst_app.isNewerThan(req_app):
score += 100
# For each installed app that is not requested score with -1
if inst_apps:
for inst_app in inst_apps:
if inst_app in req_apps:
# Check the version
for req_app in req_apps:
if req_app.isNewerThan(inst_app):
score -= 1
elif inst_app.getValue("version"):
# Only set score to -1 when the user requests a version
# to avoid score -1 if the user wants to install some packages
# if is not requested -1
score -= 1
return concrete_system, score
@staticmethod
def search_vm(inf, radl_sys, auth):
# If an images is already set do not search
if radl_sys.getValue("disk.0.image.url"):
return []
dist = radl_sys.getValue('disk.0.os.flavour')
version = radl_sys.getValue('disk.0.os.version')
res = []
for c in CloudInfo.get_cloud_list(auth):
cloud_site = c.getCloudConnector(inf)
try:
images = cloud_site.list_images(auth, filters={"distribution": dist, "version": version})
except Exception as ex:
images = []
InfrastructureManager.logger.warning("Inf ID: %s: Error getting images " % inf.id +
"from cloud: %s (%s)" % (c.id, ex))
if images:
new_sys = system(radl_sys.name)
new_sys.setValue("disk.0.image.url", images[0]["uri"])
res.append(new_sys)
return res
@staticmethod
def systems_with_iis(sel_inf, radl, auth):
"""
Concrete systems using Image Information Systems.
Currently supported VMRC and AppDBIS
NOTE: consider not-fake deploys (vm_number > 0)
"""
# Get VMRC credentials
vmrc_list = []
for vmrc_elem in auth.getAuthInfo('VMRC'):
if 'host' in vmrc_elem and 'username' in vmrc_elem and 'password' in vmrc_elem:
vmrc_list.append(VMRC(vmrc_elem['host'], vmrc_elem['username'], vmrc_elem['password']))
# Get AppDBIS credentials
appdbis_list = []
for appdbis_elem in auth.getAuthInfo('AppDBIS'):
host = None
if 'host' in appdbis_elem:
host = appdbis_elem['host']
appdbis_list.append(AppDBIS(host))
systems_with_vmrc = {}
for system_id in set([d.id for d in radl.deploys if d.vm_number > 0]):
s = radl.get_system_by_name(system_id)
if Config.SINGLE_SITE:
image_id = os.path.basename(s.getValue("disk.0.image.url"))
url_prefix = Config.SINGLE_SITE_IMAGE_URL_PREFIX
if not url_prefix.endswith("/"):
url_prefix = url_prefix + "/"
s.setValue("disk.0.image.url", url_prefix + image_id)
# Remove the requested apps from the system
s_without_apps = radl.get_system_by_name(system_id).clone()
s_without_apps.delValue("disk.0.applications")
# Set the default values for cpu, memory
defaults = (Feature("cpu.count", ">=", Config.DEFAULT_VM_CPUS),
Feature("memory.size", ">=", Config.DEFAULT_VM_MEMORY, Config.DEFAULT_VM_MEMORY_UNIT),
Feature("cpu.arch", "=", Config.DEFAULT_VM_CPU_ARCH))
for f in defaults:
if not s_without_apps.hasFeature(f.prop, check_softs=True):
s_without_apps.addFeature(f)
vmrc_res = [s0 for vmrc in vmrc_list for s0 in vmrc.search_vm(s)]
appdbis_res = [s0 for appdbis in appdbis_list for s0 in appdbis.search_vm(s)]
local_res = InfrastructureManager.search_vm(sel_inf, s, auth)
# Check that now the image URL is in the RADL
if not s.getValue("disk.0.image.url") and not vmrc_res and not appdbis_res and not local_res:
sel_inf.add_cont_msg("No VMI obtained from VMRC nor AppDBIS nor Sites to system: " + system_id)
raise Exception("No VMI obtained from VMRC nor AppDBIS not Sites to system: " + system_id)
n = [s_without_apps.clone().applyFeatures(s0, conflict="other", missing="other")
for s0 in (vmrc_res + appdbis_res + local_res)]
systems_with_vmrc[system_id] = n if n else [s_without_apps]
return systems_with_vmrc
@staticmethod
def sort_by_score(sel_inf, concrete_systems, cloud_list, deploy_groups, auth):
"""
Sort by score the cloud providers
NOTE: consider fake deploys (vm_number == 0)
"""
deploys_group_cloud = {}
# reverse the list to use the reverse order in the sort function
# list of ordered clouds
ordered_cloud_list = [c.id for c in CloudInfo.get_cloud_list(auth)]
ordered_cloud_list.reverse()
for deploy_group in deploy_groups:
suggested_cloud_ids = list(set([d.cloud_id for d in deploy_group if d.cloud_id]))
if len(suggested_cloud_ids) > 1:
raise Exception("Two deployments that have to be launched in the same cloud provider "
"are asked to be deployed in different cloud providers: %s" % deploy_group)
elif len(suggested_cloud_ids) == 1:
if suggested_cloud_ids[0] not in cloud_list:
InfrastructureManager.logger.debug("Inf ID: " + sel_inf.id + ": Cloud Provider list:")
InfrastructureManager.logger.debug("Inf ID: " + sel_inf.id + " - " + str(cloud_list))
raise Exception("No auth data for cloud with ID: %s" % suggested_cloud_ids[0])
else:
cloud_list0 = [(suggested_cloud_ids[0], cloud_list[suggested_cloud_ids[0]])]
else:
cloud_list0 = cloud_list.items()
scored_clouds = []
for cloud_id, _ in cloud_list0:
total = 0
for d in deploy_group:
if d.vm_number:
total += d.vm_number * concrete_systems[cloud_id][d.id][1]
else:
total += 1
scored_clouds.append((cloud_id, total))
# Order the clouds first by the score and then using the cloud
# order in the auth data
sorted_scored_clouds = sorted(scored_clouds,
key=lambda x: (x[1], ordered_cloud_list.index(x[0])),
reverse=True)
if sorted_scored_clouds and sorted_scored_clouds[0]:
deploys_group_cloud[id(deploy_group)] = sorted_scored_clouds[0][0]
else:
sel_inf.configured = False
sel_inf.add_cont_msg("No cloud provider available")
raise Exception("No cloud provider available")
return deploys_group_cloud
@staticmethod
def add_app_reqs(radl, inf_id=None):
""" Add apps requirements to the RADL. """
for radl_system in radl.systems:
apps_to_install = radl_system.getApplications()
for app_to_install in apps_to_install:
for app_avail, _, _, _, requirements in Recipe.getInstallableApps():
if requirements and app_avail.isNewerThan(app_to_install):
# This app must be installed and it has special
# requirements
try:
requirements_radl = radl_parse.parse_radl(requirements).systems[0]
radl_system.applyFeatures(requirements_radl, conflict="other", missing="other")
except Exception:
InfrastructureManager.logger.exception(
"Inf ID: " + inf_id + ": Error in the requirements of the app: " +
app_to_install.getValue("name") + ". Ignore them.")
InfrastructureManager.logger.debug("Inf ID: " + inf_id + ": " + str(requirements))
break
@staticmethod
def get_deploy_groups(cloud_list, radl, systems_with_iis, sel_inf, auth):
# Concrete systems with cloud providers and select systems with the greatest score
# in every cloud
concrete_systems = {}
for cloud_id, cloud in cloud_list.items():
for system_id, systems in systems_with_iis.items():
s1 = [InfrastructureManager._compute_score(s.clone().applyFeatures(s0,
conflict="other",
missing="other").concrete(),
radl.get_system_by_name(system_id))
for s in systems for s0 in cloud.concreteSystem(s, auth)]
# Store the concrete system with largest score
concrete_systems.setdefault(cloud_id, {})[system_id] = max(s1, key=lambda x: x[1]) if s1 else (None,
-1e9)
# Group virtual machines to deploy by network dependencies
deploy_groups = InfrastructureManager._compute_deploy_groups(radl)
InfrastructureManager.logger.debug("Inf ID: " + sel_inf.id + ": Groups of VMs with dependencies")
InfrastructureManager.logger.debug("Inf ID: " + sel_inf.id + "\n" + str(deploy_groups))
# Sort by score the cloud providers
deploys_group_cloud = InfrastructureManager.sort_by_score(sel_inf, concrete_systems, cloud_list,
deploy_groups, auth)
return concrete_systems, deploy_groups, deploys_group_cloud
@staticmethod
def AddResource(inf_id, radl_data, auth, context=True):
"""
Add the resources in the RADL to the infrastructure.
Args:
- inf_id(str): infrastructure id.
- radl(str): RADL description.
- auth(Authentication): parsed authentication tokens.
- context(bool): Flag to specify if the ctxt step will be made
Return(list of int): ids of the new virtual machine created.
"""
if Config.BOOT_MODE in [1, 2]:
raise DisabledFunctionException()
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info("Adding resources to Inf ID: " + str(inf_id))
sel_inf = InfrastructureManager.get_infrastructure(inf_id, auth)
if sel_inf.deleted:
InfrastructureManager.logger.info("Inf ID: %s: Deleted Infrastructure. Stop deploying!" % sel_inf.id)
return []
try:
if isinstance(radl_data, RADL):
radl = radl_data
else:
radl = radl_parse.parse_radl(radl_data)
InfrastructureManager.logger.debug("Inf ID: " + str(inf_id) + ": \n" + str(radl))
radl.check()
# Update infrastructure RADL with this new RADL
sel_inf.complete_radl(radl)
sel_inf.update_radl(radl, [])
# If any deploy is defined, only update definitions.
if not radl.deploys:
InfrastructureManager.logger.warning("Inf ID: " + sel_inf.id + ": without any deploy. Exiting.")
sel_inf.add_cont_msg("Infrastructure without any deploy. Exiting.")
if sel_inf.configured is None:
sel_inf.configured = False
return []
except Exception as ex:
sel_inf.configured = False
sel_inf.add_cont_msg("Error parsing RADL: %s" % str(ex))
InfrastructureManager.logger.exception("Inf ID: " + sel_inf.id + " error parsing RADL")
raise ex
InfrastructureManager.add_app_reqs(radl, sel_inf.id)
# Concrete systems using VMRC
try:
systems_with_iis = InfrastructureManager.systems_with_iis(sel_inf, radl, auth)
except Exception as ex:
sel_inf.configured = False
sel_inf.add_cont_msg("Error getting VM images: %s" % str(ex))
InfrastructureManager.logger.exception("Inf ID: " + sel_inf.id + " error getting VM images")
raise ex
# Concrete systems with cloud providers and select systems with the greatest score
# in every cloud
cloud_list = dict([(c.id, c.getCloudConnector(sel_inf)) for c in CloudInfo.get_cloud_list(auth)])
concrete_systems, deploy_groups, deploys_group_cloud = InfrastructureManager.get_deploy_groups(cloud_list,
radl,
systems_with_iis,
sel_inf,
auth)
# We are going to start adding resources
sel_inf.set_adding()
# Launch every group in the same cloud provider
deployed_vm = {}
deploy_items = []
for deploy_group in deploy_groups:
if not deploy_group:
InfrastructureManager.logger.warning("Inf ID: %s: No VMs to deploy!" % sel_inf.id)
sel_inf.add_cont_msg("No VMs to deploy. Exiting.")
if sel_inf.configured is None:
sel_inf.configured = False
return []
cloud_id = deploys_group_cloud[id(deploy_group)]
cloud = cloud_list[cloud_id]
for d in deploy_group:
deploy_items.append((d, cloud_id, cloud))
# Now launch all the deployments
if Config.MAX_SIMULTANEOUS_LAUNCHES > 1:
pool = ThreadPool(processes=Config.MAX_SIMULTANEOUS_LAUNCHES)
pool.map(
lambda depitem: InfrastructureManager._launch_deploy(sel_inf, depitem[0], depitem[1],
depitem[2], concrete_systems, radl, auth,
deployed_vm),
deploy_items)
pool.close()
else:
for deploy, cloud_id, cloud in deploy_items:
InfrastructureManager._launch_deploy(sel_inf, deploy, cloud_id,
cloud, concrete_systems, radl,
auth, deployed_vm)
# We make this to maintain the order of the VMs in the sel_inf.vm_list
# according to the deploys shown in the RADL
new_vms = []
for orig_dep in radl.deploys:
for deploy in deployed_vm.keys():
if orig_dep.id == deploy.id:
for vm in deployed_vm.get(deploy, []):
if vm not in new_vms:
new_vms.append(vm)
# Remove the VMs in creating state
sel_inf.remove_creating_vms()
all_failed = True
for vm in new_vms:
# Set now the VM as "created"
vm.creating = False
# and add it to the Inf
sel_inf.add_vm(vm)
if vm.state != VirtualMachine.FAILED:
all_failed = False
(_, passwd, _, _) = vm.info.systems[0].getCredentialValues()
(_, new_passwd, _, _) = vm.info.systems[0].getCredentialValues(new=True)
if passwd and not new_passwd:
# The VM uses the VMI password, set to change it
random_password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))
vm.info.systems[0].setCredentialValues(password=random_password, new=True)
error_msg = ""
# Add the new virtual machines to the infrastructure
sel_inf.update_radl(radl, deployed_vm, False)
if all_failed and new_vms:
InfrastructureManager.logger.error("VMs failed when adding to Inf ID: %s" % sel_inf.id)
sel_inf.add_cont_msg("All VMs failed. No contextualize.")
# in case of all VMs are failed delete it
delete_list = list(reversed(sel_inf.get_vm_list()))
for vm in new_vms:
if vm.error_msg:
error_msg += "%s\n" % vm.error_msg
vm.delete(delete_list, auth, [])
sel_inf.add_cont_msg(error_msg)
else:
InfrastructureManager.logger.info("VMs %s successfully added to Inf ID: %s" % (new_vms, sel_inf.id))
# The resources has been added
sel_inf.set_adding(False)
# Let's contextualize!
if context and new_vms and not all_failed:
sel_inf.Contextualize(auth)
if all_failed and new_vms:
# if there are no VMs, set it as unconfigured
if not sel_inf.get_vm_list():
sel_inf.configured = False
raise Exception("Error adding VMs: %s" % error_msg)
IM.InfrastructureList.InfrastructureList.save_data(inf_id)
return [vm.im_id for vm in new_vms]
@staticmethod
def RemoveResource(inf_id, vm_list, auth, context=True):
"""
Remove a list of resources from the infrastructure.
Args:
- inf_id(str): infrastructure id.
- vm_list(str, int or list of str): list of virtual machine ids.
- auth(Authentication): parsed authentication tokens.
- context(bool): Flag to specify if the ctxt step will be made
Return(int): number of undeployed virtual machines.
"""
if Config.BOOT_MODE in [1, 2]:
raise DisabledFunctionException()
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info("Removing the VMs: " + str(vm_list) + " from Inf ID: '" + str(inf_id) + "'")
sel_inf = InfrastructureManager.get_infrastructure(inf_id, auth)
if isinstance(vm_list, str):
vm_ids = vm_list.split(",")
elif isinstance(vm_list, int):
vm_ids = [str(vm_list)]
elif isinstance(vm_list, list):
vm_ids = vm_list
else:
raise Exception(
'Incorrect parameter type to RemoveResource function: expected: str, int or list of str.')
cont = 0
exceptions = []
delete_list = [sel_inf.get_vm(vmid) for vmid in vm_ids]
for vm in delete_list:
if vm.delete(delete_list, auth, exceptions):
cont += 1
InfrastructureManager.logger.info("Inf ID: " + sel_inf.id + ": %d VMs successfully removed" % cont)
if context and cont > 0:
# Now test again if the infrastructure is contextualizing
sel_inf.Contextualize(auth)
IM.InfrastructureList.InfrastructureList.save_data(inf_id)
if exceptions:
InfrastructureManager.logger.exception("Inf ID: " + sel_inf.id + ": Error removing resources")
raise Exception("Error removing resources: %s" % exceptions)
return cont
@staticmethod
def GetVMProperty(inf_id, vm_id, property_name, auth):
"""
Get a particular property about a virtual machine in an infrastructure.
Args:
- inf_id(str): infrastructure id.
- vm_id(str): virtual machine id.
- property(str): RADL property to get.
- auth(Authentication): parsed authentication tokens.
Return: a str with the property value
"""
auth = InfrastructureManager.check_auth_data(auth)
radl = InfrastructureManager.GetVMInfo(inf_id, vm_id, auth)
res = None
if radl.systems:
res = radl.systems[0].getValue(property_name)
return res
@staticmethod
def GetVMInfo(inf_id, vm_id, auth, json_res=False):
"""
Get information about a virtual machine in an infrastructure.
Args:
- inf_id(str): infrastructure id.
- vm_id(str): virtual machine id.
- auth(Authentication): parsed authentication tokens.
- json_res(bool): Flag to return the info in RADL JSON format
Return: the RADL with the information about the VM or a str with the JSON data if json_res flag.
"""
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info(
"Get information about the vm: '" + str(vm_id) + "' from Inf ID: " + str(inf_id))
vm = InfrastructureManager.get_vm_from_inf(inf_id, vm_id, auth)
success = vm.update_status(auth)
if not success:
InfrastructureManager.logger.debug(
"Inf ID: " + str(inf_id) + ": " +
"Information not updated. Using last information retrieved")
else:
IM.InfrastructureList.InfrastructureList.save_data(inf_id)
if json_res:
return dump_radl_json(vm.get_vm_info())
else:
return vm.get_vm_info()
@staticmethod
def GetVMContMsg(inf_id, vm_id, auth):
"""
Get the contextualization log of a virtual machine in an infrastructure.
Args:
- inf_id(str): infrastructure id.
- vm_id(str): virtual machine id.
- auth(Authentication): parsed authentication tokens.
Return: a str with the contextualization log of the VM
"""
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info(
"Get contextualization log of the vm: '" + str(vm_id) + "' from Inf ID: " + str(inf_id))
vm = InfrastructureManager.get_vm_from_inf(inf_id, vm_id, auth)
cont_msg = vm.get_cont_msg()
InfrastructureManager.logger.debug("Inf ID: " + str(inf_id) + ": " + cont_msg)
return cont_msg
@staticmethod
def AlterVM(inf_id, vm_id, radl_data, auth):
"""
Get information about a virtual machine in an infrastructure.
Args:
- inf_id(str): infrastructure id.
- vm_id(str): virtual machine id.
- radl(str): RADL description.
- auth(Authentication): parsed authentication tokens.
Return: a str with the information about the VM
"""
if Config.BOOT_MODE in [1, 2]:
raise DisabledFunctionException()
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info(
"Modifying the VM: '" + str(vm_id) + "' from Inf ID: " + str(inf_id))
vm = InfrastructureManager.get_vm_from_inf(inf_id, vm_id, auth)
if not vm:
InfrastructureManager.logger.info(
"Inf ID: " + str(inf_id) + ": " +
"VM does not exist or Access Error")
raise Exception("VM does not exist or Access Error")
if isinstance(radl_data, RADL):
radl = radl_data
else:
radl = radl_parse.parse_radl(radl_data)
(success, alter_res) = vm.alter(radl, auth)
if not success:
raise Exception("Error modifying the information about the VM %s: %s" % (vm_id, alter_res))
vm.update_status(auth)
IM.InfrastructureList.InfrastructureList.save_data(inf_id)
return vm.info
@staticmethod
def GetInfrastructureRADL(inf_id, auth):
"""
Get the original RADL of an infrastructure.
Args:
- inf_id(str): infrastructure id.
- auth(Authentication): parsed authentication tokens.
Return: str with the RADL
"""
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info("Getting RADL of the Inf ID: " + str(inf_id))
sel_inf = InfrastructureManager.get_infrastructure(inf_id, auth)
radl = str(sel_inf.get_radl())
InfrastructureManager.logger.debug("Inf ID: " + sel_inf.id + ": " + radl)
return radl
@staticmethod
def GetInfrastructureInfo(inf_id, auth):
"""
Get information about an infrastructure.
Args:
- inf_id(str): infrastructure id.
- auth(Authentication): parsed authentication tokens.
Return: a list of str: list of virtual machine ids.
"""
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info("Getting information about the Inf ID: " + str(inf_id))
sel_inf = InfrastructureManager.get_infrastructure(inf_id, auth)
res = [str(vm.im_id) for vm in sel_inf.get_vm_list()]
InfrastructureManager.logger.debug("Inf ID: " + sel_inf.id + ": " + str(res))
return res
@staticmethod
def GetInfrastructureContMsg(inf_id, auth, headeronly=False):
"""
Get cont msg of an infrastructure.
Args:
- inf_id(str): infrastructure id.
- auth(Authentication): parsed authentication tokens.
- headeronly(bool): Flag to return only the header part of the infra log.
Return: a str with the cont msg
"""
auth = InfrastructureManager.check_auth_data(auth)
InfrastructureManager.logger.info(
"Getting cont msg of the Inf ID: " + str(inf_id))
sel_inf = InfrastructureManager.get_infrastructure(inf_id, auth)
res = sel_inf.cont_out
if not headeronly:
for vm in sel_inf.get_vm_list():
if vm.get_cont_msg():
res += "VM " + str(vm.im_id) + ":\n" + vm.get_cont_msg() + "\n"
res += "***************************************************************************\n"
InfrastructureManager.logger.debug("Inf ID: " + sel_inf.id + ": " + res)
return res
@staticmethod
def GetInfrastructureState(inf_id, auth):