-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathConfManager.py
1635 lines (1424 loc) · 75.2 KB
/
ConfManager.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/etc/sudoers 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 json
import logging
import os
import threading
import time
import tempfile
import shutil
from packaging.version import Version
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from multiprocessing import Queue
from ansible import __version__ as ansible_version
try:
# for Ansible version 2.2.0 or higher
from ansible.module_utils._text import to_bytes
except ImportError:
from ansible.utils.unicode import to_bytes
from ansible.parsing.vault import VaultEditor
try:
# for Ansible version 2.4.0 or higher
from ansible.parsing.vault import VaultSecret
from ansible.parsing.vault import VaultLib
except ImportError:
# for Ansible version 2.3.2 or lower
pass
from IM.ansible_utils import merge_recipes
from IM.ansible_utils.ansible_launcher import AnsibleThread
import IM.InfrastructureList
from IM.LoggerMixin import LoggerMixin
from IM.VirtualMachine import VirtualMachine
from IM.SSH import AuthenticationException
from IM.SSHRetry import SSHRetry
from IM.recipe import Recipe
from IM.config import Config
from radl.radl import system, contextualize_item
from IM.CtxtAgentBase import CtxtAgentBase
class ConfManager(LoggerMixin, threading.Thread):
"""
Class to manage the contextualization steps
"""
MASTER_YAML = "conf-ansible.yml"
""" The file with the ansible steps to configure the master node """
def __init__(self, inf, auth, max_ctxt_time=1e9):
threading.Thread.__init__(self)
self.daemon = True
self.inf = inf
self.auth = auth
self.init_time = time.time()
self.max_ctxt_time = max_ctxt_time
self._stop_thread = False
self.ansible_process = None
self.logger = logging.getLogger('ConfManager')
def check_running_pids(self, vms_configuring):
"""
Update the status of the configuration processes
"""
res = {}
for step, vm_list in vms_configuring.items():
for vm in vm_list:
if isinstance(vm, VirtualMachine):
if vm.is_ctxt_process_running():
if step not in res:
res[step] = []
res[step].append(vm)
self.log_info("Ansible process to configure " + str(vm.im_id) +
" with PID " + vm.ctxt_pid + " is still running.")
else:
self.log_info("Configuration process in VM: " + str(vm.im_id) + " finished.")
if vm.configured:
self.log_info("Configuration process of VM %s success." % vm.im_id)
elif vm.configured is False:
self.log_info("Configuration process of VM %s failed." % vm.im_id)
else:
self.log_warn("Configuration process of VM %s in unfinished state." % vm.im_id)
# Force to save the data to store the log data ()
IM.InfrastructureList.InfrastructureList.save_data(self.inf.id)
else:
# General Infrastructure tasks
if vm.is_ctxt_process_running():
if step not in res:
res[step] = []
res[step].append(vm)
self.log_info("Configuration process of master node: " +
str(vm.get_ctxt_process_names()) + " is still running.")
else:
if vm.configured:
self.log_info("Configuration process of master node successfully finished.")
elif vm.configured is False:
self.log_info("Configuration process of master node failed.")
else:
self.log_warn("Configuration process of master node in unfinished state.")
# Force to save the data to store the log data
IM.InfrastructureList.InfrastructureList.save_data(self.inf.id)
return res
def stop(self):
self._stop_thread = True
# put a task to assure to wake up the thread
self.inf.add_ctxt_tasks([(-10, 0, None, None)])
self.log_info("Stop Configuration thread.")
if self.ansible_process and self.ansible_process.is_alive():
self.log_info("Stopping pending Ansible process.")
self.ansible_process.terminate()
def wait_all_vm_ips(self, timeout=Config.WAIT_PUBLIC_IP_TIMEOUT):
"""
Assure that all the VMs of the Inf. have all the requested public IPs assigned
"""
wait = 0
success = False
while not success and wait < timeout and not self._stop_thread:
success = True
for vm in self.inf.get_vm_list():
if not vm.contextualize():
continue
# If the VM is not in a "running" state, ignore it
if vm.state in VirtualMachine.NOT_RUNNING_STATES:
self.log_warn("The VM ID: " + str(vm.id) +
" is not running, do not wait it to have an IP.")
continue
if vm.hasPublicNet():
self.log_debug("VM %s requests a public IP." % vm.id)
if not vm.getPublicIP():
self.log_debug("And it does not have it assigned yet.")
success = False
vm.update_status(self.auth)
if not success:
self.log_warn("Still waiting all the VMs to have all the requested IPs")
wait += Config.CONFMAMAGER_CHECK_STATE_INTERVAL
time.sleep(Config.CONFMAMAGER_CHECK_STATE_INTERVAL)
if not success:
self.inf.set_configured(False)
self.log_warn("Error waiting all the VMs to have all the requested IPs")
else:
self.inf.set_configured(True)
self.log_info("All the VMs have all the requested IPs")
# do a final update of all VMs
for vm in self.inf.get_vm_list():
if vm.state not in VirtualMachine.NOT_RUNNING_STATES:
vm.update_status(self.auth)
return success
def check_vm_ips(self, timeout=Config.WAIT_RUNNING_VM_TIMEOUT):
"""
Assure that all the VMs of the Inf. have at least one IP
"""
wait = 0
success = False
while not success and wait < timeout and not self._stop_thread:
success = True
for vm in self.inf.get_vm_list():
if not vm.contextualize():
continue
if vm.hasPublicNet():
ip = vm.getPublicIP()
if not ip:
ip = vm.getPrivateIP()
else:
ip = vm.getPrivateIP()
if not ip:
ip = vm.getPublicIP()
if not ip:
# If the IP is not Available try to update the info
vm.update_status(self.auth)
# If the VM is not in a "running" state, ignore it
if vm.state in VirtualMachine.NOT_RUNNING_STATES:
self.log_warn("The VM ID: " + str(vm.id) +
" is not running, do not wait it to have an IP.")
continue
if vm.hasPublicNet():
ip = vm.getPublicIP()
if not ip:
ip = vm.getPrivateIP()
else:
ip = vm.getPrivateIP()
if not ip:
ip = vm.getPublicIP()
if not ip:
success = False
break
if not success:
self.log_warn("Still waiting all the VMs to have a correct IP")
wait += Config.CONFMAMAGER_CHECK_STATE_INTERVAL
time.sleep(Config.CONFMAMAGER_CHECK_STATE_INTERVAL)
if not success:
self.log_error("Error waiting all the VMs to have a correct IP")
self.inf.set_configured(False)
else:
self.log_info("All the VMs have a correct IP")
self.inf.set_configured(True)
return success
def kill_ctxt_processes(self):
"""
Kill all the ctxt processes
"""
for vm in self.inf.get_vm_list():
self.log_info("Killing ctxt processes in VM: %s" % vm.id)
try:
vm.kill_check_ctxt_process()
except Exception:
self.log_exception("Error killing ctxt processes in VM: %s" % vm.id)
def run(self):
self.log_info("Starting the ConfManager Thread")
last_step = None
vms_configuring = {}
while not self._stop_thread:
if self.init_time + self.max_ctxt_time < time.time():
self.log_info("Max contextualization time passed. Exit thread.")
self.inf.add_cont_msg("ERROR: Max contextualization time passed.")
# Remove tasks from queue
self.inf.reset_ctxt_tasks()
# Kill the ansible processes
self.kill_ctxt_processes()
if self.ansible_process and self.ansible_process.is_alive():
self.log_info("Stopping pending Ansible process.")
self.ansible_process.terminate()
self._stop_thread = True
# Set as unconfigured all non finished ctxt VMs
for vm in self.inf.get_vm_list():
if vm.configured is None:
vm.configured = False
return
vms_configuring = self.check_running_pids(vms_configuring)
# If the queue is empty but there are vms configuring wait and test
# again
if self.inf.ctxt_tasks.empty() and vms_configuring:
time.sleep(Config.CONFMAMAGER_CHECK_STATE_INTERVAL)
continue
(step, prio, vm, tasks) = self.inf.ctxt_tasks.get()
# stop the thread if the stop method has been called
if self._stop_thread:
self.log_info("Exit Configuration thread.")
return
# if this task is from a next step
if last_step is not None and last_step < step:
if vm.is_configured() is False:
self.log_debug("Configuration process of step " + str(last_step) +
" failed, ignoring tasks of later steps.")
else:
# Add the task again to the queue only if the last step was OK
self.inf.add_ctxt_tasks([(step, prio, vm, tasks)])
# If there are any process running of last step, wait
if last_step in vms_configuring and len(vms_configuring[last_step]) > 0:
self.log_info("Waiting processes of step " + str(last_step) + " to finish.")
time.sleep(Config.CONFMAMAGER_CHECK_STATE_INTERVAL)
else:
# if not, update the step, to go ahead with the new step
self.log_info("Step " + str(last_step) + " finished. Go to step: " + str(step))
last_step = step
else:
if isinstance(vm, VirtualMachine):
if vm.destroy:
self.log_warn("VM ID " + str(vm.im_id) +
" has been destroyed. Not launching new tasks for it.")
elif vm.is_configured() is False:
self.log_info("Configuration process of step %s failed, "
"ignoring tasks of step %s." % (last_step, step))
# Check that the VM has no other ansible process
# running
elif vm.ctxt_pid:
self.log_info("VM ID " + str(vm.im_id) + " has running processes, wait.")
# If there are, add the tasks again to the queue
# Set the priority to a higher number to decrease the
# priority enabling to select other items of the queue
# before
self.inf.add_ctxt_tasks([(step, prio + 1, vm, tasks)])
# Sleep to check this later
time.sleep(Config.CONFMAMAGER_CHECK_STATE_INTERVAL)
else:
if not tasks:
self.log_info("No tasks to execute. Ignore this step.")
else:
# If not, launch it
# Mark this VM as configuring
vm.configured = None
# Launch the ctxt_agent using a thread
t = threading.Thread(name="launch_ctxt_agent_" + str(
vm.id), target=self.launch_ctxt_agent, args=(vm, tasks))
t.daemon = True
t.start()
vm.inf.conf_threads.append(t)
if step not in vms_configuring:
vms_configuring[step] = []
vms_configuring[step].append(vm.inf)
# Add the VM to the list of configuring vms
vms_configuring[step].append(vm)
# Set the "special pid" to wait untill the real pid is
# assigned
vm.ctxt_pid = VirtualMachine.WAIT_TO_PID
# Force to save the data to store the log data
IM.InfrastructureList.InfrastructureList.save_data(self.inf.id)
else:
# Launch the Infrastructure tasks
vm.configured = None
for task in tasks:
t = threading.Thread(name=task, target=getattr(self, task))
t.daemon = True
t.start()
vm.conf_threads.append(t)
if step not in vms_configuring:
vms_configuring[step] = []
vms_configuring[step].append(vm)
# Force to save the data to store the log data
IM.InfrastructureList.InfrastructureList.save_data(self.inf.id)
last_step = step
def launch_ctxt_agent(self, vm, tasks):
"""
Launch the ctxt agent to configure the specified tasks in the specified VM
"""
ssh = None
pid = None
tmp_dir = None
try:
ip = vm.getPublicIP()
if not ip:
ip = vm.getPrivateIP()
if not ip:
self.log_error("VM with ID %s (%s) does not have an IP!!. "
"We cannot launch the ansible process!!" % (str(vm.im_id), vm.id))
else:
remote_dir = Config.REMOTE_CONF_DIR + "/" + str(self.inf.id) + "/" + ip + "_" + str(vm.im_id)
tmp_dir = tempfile.mkdtemp()
self.log_info("Create the configuration file for the contextualization agent")
conf_file = tmp_dir + "/config.cfg"
self.create_vm_conf_file(conf_file, vm, tasks, remote_dir)
self.log_info("Copy the contextualization agent config file")
# Copy the contextualization agent config file
ssh = vm.get_ssh_ansible_master(auto_close=False)
ssh.sftp_mkdir(remote_dir)
ssh.sftp_put(conf_file, remote_dir + "/" + os.path.basename(conf_file))
if vm.configured is None:
if len(self.inf.get_vm_list()) > Config.VM_NUM_USE_CTXT_DIST:
self.log_info("Using ctxt_agent_dist")
ctxt_agent_command = "/ctxt_agent_dist.py "
else:
self.log_info("Using ctxt_agent")
ctxt_agent_command = "/ctxt_agent.py "
vault_export = ""
vault_password = vm.info.systems[0].getValue("vault.password")
if vault_password:
vault_export = "export VAULT_PASS='%s' && " % vault_password
(pid, _, _) = ssh.execute("nohup sh -c \"" + vault_export + CtxtAgentBase.VENV_DIR +
"/bin/python3 " + Config.REMOTE_CONF_DIR +
"/" + str(self.inf.id) + "/" + ctxt_agent_command +
Config.REMOTE_CONF_DIR + "/" + str(self.inf.id) + "/" +
"/general_info.cfg " + remote_dir + "/" + os.path.basename(conf_file) +
"\" > " + remote_dir + "/stdout" + " 2> " + remote_dir +
"/stderr < /dev/null & echo -n $!")
self.log_info("Ansible process to configure " + str(vm.im_id) + " launched with pid: " + pid)
vm.ctxt_pid = pid
vm.launch_check_ctxt_process()
else:
self.log_warn("Ansible process to configure " + str(vm.im_id) + " NOT launched")
except Exception:
pid = None
self.log_exception("Error launching the ansible process to configure VM with ID %s" % str(vm.im_id))
finally:
if ssh:
ssh.close()
if tmp_dir:
shutil.rmtree(tmp_dir, ignore_errors=True)
# If the process is not correctly launched the configuration of this VM
# fails
if pid is None:
vm.ctxt_pid = None
vm.configured = False
vm.cont_out = "Error launching the contextualization agent to configure the VM. Check the SSH connection."
return pid
def generate_inventory(self, tmp_dir):
"""
Generate the ansible inventory file
"""
self.log_info("Create the ansible configuration file")
res_filename = "hosts"
ansible_file = tmp_dir + "/" + res_filename
out = open(ansible_file, 'w')
# get the master node name
if self.inf.radl.ansible_hosts:
(master_name, masterdom) = (
self.inf.radl.ansible_hosts[0].getHost(), "")
else:
(master_name, masterdom) = self.inf.vm_master.getRequestedName(
default_hostname=Config.DEFAULT_VM_NAME, default_domain=Config.DEFAULT_DOMAIN)
no_windows = ""
windows = ""
all_vars = ""
vm_group = self.inf.get_vm_list_by_system_name()
for group in vm_group:
vm = vm_group[group][0]
out.write('[' + group + ':vars]\n')
if vm.getOS().lower() == "windows":
out.write('ansible_connection=winrm\n')
out.write('ansible_winrm_server_cert_validation=ignore\n')
out.write('[' + group + ']\n')
# Set the vars with the number of nodes of each type
all_vars += 'IM_' + group.upper() + '_NUM_VMS=' + \
str(len(vm_group[group])) + '\n'
for vm in vm_group[group]:
if not vm.contextualize():
continue
# first try to use the public IP
ip = vm.getPublicIP()
if not ip:
ip = vm.getPrivateIP()
if not ip:
self.log_warn("The VM ID: " + str(vm.id) +
" does not have an IP. It will not be included in the inventory file.")
continue
if vm.state in VirtualMachine.NOT_RUNNING_STATES:
self.log_warn("The VM ID: " + str(vm.id) +
" is not running. It will not be included in the inventory file.")
continue
if vm.getOS().lower() == "windows":
windows += "%s_%d\n" % (ip, vm.im_id)
else:
no_windows += "%s_%d\n" % (ip, vm.im_id)
ifaces_im_vars = ''
for i in range(vm.getNumNetworkIfaces()):
iface_ip = vm.getIfaceIP(i)
if iface_ip:
ifaces_im_vars += ' IM_NODE_NET_' + \
str(i) + '_IP=' + iface_ip
if vm.getRequestedNameIface(i):
(nodename, nodedom) = vm.getRequestedNameIface(
i, default_domain=Config.DEFAULT_DOMAIN)
ifaces_im_vars += ' IM_NODE_NET_' + \
str(i) + '_HOSTNAME=' + nodename
ifaces_im_vars += ' IM_NODE_NET_' + \
str(i) + '_DOMAIN=' + nodedom
ifaces_im_vars += ' IM_NODE_NET_' + \
str(i) + '_FQDN=' + nodename + "." + nodedom
# the master node
# TODO: Known issue: the master VM must set the public network
# in the iface 0
(nodename, nodedom) = system.replaceTemplateName(
Config.DEFAULT_VM_NAME + "." + Config.DEFAULT_DOMAIN, str(vm.im_id))
if vm.getRequestedName():
(nodename, nodedom) = vm.getRequestedName(
default_domain=Config.DEFAULT_DOMAIN)
node_line = "%s_%d" % (ip, vm.im_id)
node_line += ' ansible_host=%s' % ip
# For compatibility with Ansible 1.X versions
node_line += ' ansible_ssh_host=%s' % ip
node_line += ' ansible_port=%d' % vm.getRemoteAccessPort()
# For compatibility with Ansible 1.X versions
node_line += ' ansible_ssh_port=%d' % vm.getRemoteAccessPort()
user = vm.getCredentialValues()[0]
if user:
node_line += ' ansible_user=%s' % user
# For compatibility with Ansible 1.X versions
node_line += ' ansible_ssh_user=%s' % user
else:
self.log_warn("The VM ID: " + str(vm.id) + " does not have username!!")
if self.inf.vm_master and vm.id == self.inf.vm_master.id:
node_line += ' ansible_connection=local'
if vm.getPublicIP():
node_line += ' IM_NODE_PUBLIC_IP=' + vm.getPublicIP()
if not vm.getPrivateIP():
# If the node only has a public IP set this variable to the public one
node_line += ' IM_NODE_PRIVATE_IP=' + vm.getPublicIP()
if vm.getPrivateIP():
node_line += ' IM_NODE_PRIVATE_IP=' + vm.getPrivateIP()
node_line += ' IM_NODE_HOSTNAME=' + nodename
node_line += ' IM_NODE_FQDN=' + nodename + "." + nodedom
node_line += ' IM_NODE_DOMAIN=' + nodedom
node_line += ' IM_NODE_NUM=' + str(vm.im_id)
node_line += ' IM_NODE_VMID=' + str(vm.id)
node_line += ' IM_NODE_CLOUD_TYPE=' + vm.cloud.type
if vm.cloud.server:
node_line += ' IM_NODE_CLOUD_SERVER=' + vm.cloud.server
node_line += ifaces_im_vars
for app in vm.getInstalledApplications():
if app.getValue("path"):
node_line += ' IM_APP_' + \
app.getValue("name").upper() + \
'_PATH=' + app.getValue("path")
if app.getValue("version"):
node_line += ' IM_APP_' + \
app.getValue("name").upper() + \
'_VERSION=' + app.getValue("version")
node_line += "\n"
out.write(node_line)
out.write("\n")
# set the IM global variables
out.write('[all:vars]\n')
out.write(all_vars)
out.write('IM_MASTER_HOSTNAME=' + master_name + '\n')
out.write('IM_MASTER_FQDN=' + master_name + "." + masterdom + '\n')
out.write('IM_MASTER_DOMAIN=' + masterdom + '\n')
out.write('IM_INFRASTRUCTURE_ID=' + self.inf.id + '\n')
out.write('IM_INFRASTRUCTURE_RADL=' + self.inf.get_json_radl() + '\n')
out.write('IM_INFRASTRUCTURE_AUTH=' + self.inf.get_auth() + '\n\n')
if windows:
out.write('[windows]\n' + windows + "\n")
# create the allnowindows group to launch the "all" tasks
if no_windows:
out.write('[allnowindows]\n' + no_windows + "\n")
out.close()
return res_filename
def generate_etc_hosts(self, tmp_dir):
"""
Generate the /etc/hosts file to the infrastructure
"""
res_filename = "etc_hosts"
hosts_file = tmp_dir + "/" + res_filename
hosts_out = open(hosts_file, 'w')
vm_group = self.inf.get_vm_list_by_system_name()
for group in vm_group:
vm = vm_group[group][0]
for vm in vm_group[group]:
# first try to use the public IP
if not vm.contextualize():
continue
ip = vm.getPublicIP()
if not ip:
ip = vm.getPrivateIP()
if not ip:
self.log_warn("The VM ID: " + str(vm.id) +
" does not have an IP. It will not be included in the /etc/hosts file.")
continue
for i in range(vm.getNumNetworkIfaces()):
if vm.getRequestedNameIface(i):
(nodename, nodedom) = vm.getRequestedNameIface(i, default_domain=Config.DEFAULT_DOMAIN)
if vm.getIfaceIP(i):
hosts_out.write(vm.getIfaceIP(
i) + " " + nodename + "." + nodedom + " " + nodename + "\r\n")
else:
self.log_warn("Net interface %d request a name, but it does not have an IP." % i)
for j in range(vm.getNumNetworkIfaces()):
if vm.getIfaceIP(j):
self.log_warn("Setting the IP of the iface %d." % j)
hosts_out.write(vm.getIfaceIP(
j) + " " + nodename + "." + nodedom + " " + nodename + "\r\n")
break
# the master node
# TODO: Known issue: the master VM must set the public
# network in the iface 0
(nodename, nodedom) = system.replaceTemplateName(
Config.DEFAULT_VM_NAME + "." + Config.DEFAULT_DOMAIN, str(vm.im_id))
if not vm.getRequestedName():
hosts_out.write(ip + " " + nodename +
"." + nodedom + " " + nodename + "\r\n")
hosts_out.close()
return res_filename
def generate_basic_playbook(self, tmp_dir):
"""
Generate the basic playbook to be launched in all the VMs
"""
recipe_files = []
pk_file = Config.REMOTE_CONF_DIR + "/" + \
str(self.inf.id) + "/ansible_key"
shutil.copy(Config.CONTEXTUALIZATION_DIR + "/basic.yml",
tmp_dir + "/basic_task_all.yml")
f = open(tmp_dir + '/basic_task_all.yml', 'a')
f.write("\n vars:\n")
f.write(" - pk_file: " + pk_file + ".pub\n")
f.write(" hosts: '{{IM_HOST}}'\n")
f.close()
recipe_files.append("basic_task_all.yml")
return recipe_files
@staticmethod
def generate_mount_disks_tasks(system):
"""
Generate a set of tasks to format and mount the specified disks
"""
res = ""
cont = 1
while system.getValue("disk." + str(cont) + ".size") or system.getValue("disk." + str(cont) + ".image.url"):
disk_device = system.getValue("disk." + str(cont) + ".device")
if disk_device:
disk_mount_path = system.getValue("disk." + str(cont) + ".mount_path")
disk_fstype = system.getValue("disk." + str(cont) + ".fstype")
if disk_fstype == 'swap':
disk_mount_path = 'swap'
# Only add the tasks if the user has specified a mount_path and a filesystem
if disk_mount_path and disk_fstype:
# This recipe works with EC2, OpenNebula and Azure. It must be
# tested/completed with other providers
res += ' - include_tasks: utils/tasks/disk_format_mount.yml\n'
res += ' vars:\n'
res += ' device: "/dev/{{item.key}}"\n'
res += ' mount_path: "' + disk_mount_path + '"\n'
res += ' fstype: "' + disk_fstype + '"\n'
res += " with_dict: '{{ ansible_devices }}'\n"
res += " when: ansible_os_family != 'Windows' and ("
# Devices hdb, sdb, xvdb, etc
res += "item.key.endswith('d%s') or " % disk_device[-1]
# Devices nvme0n1 (NVMe type in EC2)
res += "item.key.startswith('nvme%sn1') or " % (ord(disk_device[-1]) - 97)
# Full name device
res += "item.key == '%s' or " % disk_device
# Use also link names (Linode case)
res += "'%s' in item.value.links.ids" % disk_device
res += ")\n"
cont += 1
return res
def generate_main_playbook(self, vm, group, tmp_dir):
"""
Generate the main playbook to be launched in all the VMs.
This playbook basically install the apps specified in the RADL
(as apps not in the configure section)
"""
recipe_files = []
# Get the info about the apps from the recipes DB
_, recipes = Recipe.getInfoApps(vm.getAppsToInstall())
conf_out = open(tmp_dir + "/main_" + group + "_task.yml", 'w')
conf_content = self.add_ansible_header(vm.getOS().lower(), gather_facts=True)
conf_content += " pre_tasks: \n"
# Basic tasks set copy /etc/hosts ...
conf_content += " - include_tasks: utils/tasks/main.yml\n"
conf_content += " tasks: \n"
conf_content += " - debug: msg='Install user requested apps'\n"
# Generate a set of tasks to format and mount the specified disks
conf_content += self.generate_mount_disks_tasks(vm.info.systems[0])
for app_name, recipe in recipes:
self.inf.add_cont_msg("App: " + app_name + " set to be installed.")
# If there are a recipe, use it
if recipe:
conf_content = merge_recipes(conf_content, recipe)
conf_content += "\n\n"
else:
# use the app name as the package to install
parts = app_name.split(".")
short_app_name = parts[len(parts) - 1]
install_app = "- tasks: \n"
# TODO set other packagers: pacman, zypper ...
install_app += " - name: Apt install " + short_app_name + "\n"
install_app += " action: apt pkg=" + short_app_name + \
" state=installed update_cache=yes cache_valid_time=604800\n"
install_app += " when: \"ansible_os_family == 'Debian'\"\n"
install_app += " ignore_errors: yes\n"
install_app += " - name: Yum install " + short_app_name + "\n"
install_app += " action: yum pkg=" + short_app_name + " state=installed\n"
install_app += " when: \"ansible_os_family == 'RedHat'\"\n"
install_app += " ignore_errors: yes\n"
conf_content = merge_recipes(conf_content, install_app)
conf_out.write(conf_content)
conf_out.close()
recipe_files.append("main_" + group + "_task.yml")
# create the "all" to enable this playbook to see the facts of all the
# nodes
all_filename = self.create_all_recipe(tmp_dir, "main_" + group + "_task")
recipe_files.append(all_filename)
# all_windows_filename = self.create_all_recipe(tmp_dir, "main_" + group + "_task", "windows", "_all_win.yml")
# recipe_files.append(all_windows_filename)
return recipe_files
@staticmethod
def get_vault_editor(vault_password):
"""
Get the correct VaultEditor object in different Ansible versions
"""
if Version(ansible_version) >= Version("2.4.0"):
# for Ansible version 2.4.0 or higher
vault_secrets = [('default', VaultSecret(_bytes=to_bytes(vault_password)))]
return VaultEditor(VaultLib(vault_secrets))
else:
# for Ansible version 2.3.2 or lower
return VaultEditor(vault_password)
def generate_playbook(self, vm, ctxt_elem, tmp_dir):
"""
Generate the playbook for the specified configure section
"""
recipe_files = []
conf_filename = tmp_dir + "/" + ctxt_elem.configure + "_" + ctxt_elem.system + "_task.yml"
if not os.path.isfile(conf_filename):
configure = self.inf.radl.get_configure_by_name(ctxt_elem.configure)
conf_content = self.add_ansible_header(vm.getOS().lower())
vault_password = vm.info.systems[0].getValue("vault.password")
if vault_password:
vault_edit = self.get_vault_editor(vault_password)
if configure.recipes and configure.recipes.strip().startswith("$ANSIBLE_VAULT"):
recipes = vault_edit.vault.decrypt(configure.recipes.strip()).decode()
else:
recipes = configure.recipes or ""
conf_content = merge_recipes(conf_content, recipes)
conf_content = vault_edit.vault.encrypt(conf_content).decode()
else:
conf_content = merge_recipes(conf_content, configure.recipes or "")
conf_out = open(conf_filename, 'w')
conf_out.write(str(conf_content))
conf_out.close()
recipe_files.append(ctxt_elem.configure + "_" + ctxt_elem.system + "_task.yml")
# create the "all" to enable this playbook to see the facts of all
# the nodes
all_filename = self.create_all_recipe(
tmp_dir, ctxt_elem.configure + "_" + ctxt_elem.system + "_task")
recipe_files.append(all_filename)
# all_windows_filename = self.create_all_recipe(tmp_dir, ctxt_elem.configure + "_" +
# ctxt_elem.system + "_task", "windows", "_all_win.yml")
# recipe_files.append(all_windows_filename)
return recipe_files
def configure_master(self):
"""
Perform all the tasks to configure the master VM.
* Change the password
* Install ansible
* Copy the contextualization agent files
"""
success = True
tmp_dir = None
if self.inf.ansible_configured:
# Check that remote_dir exists
# Also check if virtual env exists (new in version 1.18.0)
remote_dir = Config.REMOTE_CONF_DIR + "/" + str(self.inf.id) + "/"
venv_dir = CtxtAgentBase.VENV_DIR + "/bin/"
for rd in [remote_dir, venv_dir]:
try:
ssh = self.inf.vm_master.get_ssh(retry=True)
files = ssh.sftp_list(rd)
except Exception as ex:
self.log_exception("Error listing remote dir %s (%s)." % (rd, str(ex)))
files = []
# if there are no files, reconfigure ansible
if len(files) < 4:
self.log_warn("Remote dir %s not found. Reinstall ansible on master node." % rd)
self.inf.ansible_configured = False
if not self.inf.ansible_configured:
success = False
cont = 0
while not self._stop_thread and not success and cont < Config.PLAYBOOK_RETRIES:
self.log_info("Sleeping %s secs." % (cont ** 2 * 5))
time.sleep(cont ** 2 * 5)
cont += 1
ssh = None
try:
self.log_info("Start the contextualization process.")
if self.inf.radl.ansible_hosts:
configured_ok = True
else:
if not self.inf.vm_master:
raise Exception("No master VM found.")
ssh = self.inf.vm_master.get_ssh(retry=True, auto_close=False)
if not ssh:
raise Exception("Master VM does not have IP.")
# Activate tty mode to avoid some problems with sudo in
# REL
ssh.tty = True
# configuration dir os th emaster node to copy all the
# contextualization files
tmp_dir = tempfile.mkdtemp()
# Now call the ansible installation process on the
# master node
ansible_version = None
if self.inf.radl.contextualize.options:
if 'ansible_version' in self.inf.radl.contextualize.options:
ansible_version = self.inf.radl.contextualize.options['ansible_version'].getValue()
configured_ok = self.configure_ansible(ssh, tmp_dir, ansible_version)
if not configured_ok:
self.log_error("Error in the ansible installation process")
if not self.inf.ansible_configured:
self.inf.ansible_configured = False
else:
self.log_info("Ansible installation finished successfully")
if configured_ok:
remote_dir = Config.REMOTE_CONF_DIR + "/" + str(self.inf.id) + "/"
self.log_info("Copy the contextualization agent files")
files = []
files.append((Config.IM_PATH + "/CtxtAgentBase.py", remote_dir + "/IM/CtxtAgentBase.py"))
files.append((Config.IM_PATH + "/SSH.py", remote_dir + "/IM/SSH.py"))
files.append((Config.IM_PATH + "/SSHRetry.py", remote_dir + "/IM/SSHRetry.py"))
files.append((Config.IM_PATH + "/retry.py", remote_dir + "/IM/retry.py"))
files.append((Config.CONTEXTUALIZATION_DIR + "/ctxt_agent_dist.py",
remote_dir + "/ctxt_agent_dist.py"))
files.append((Config.CONTEXTUALIZATION_DIR + "/ctxt_agent.py", remote_dir + "/ctxt_agent.py"))
# copy an empty init to make IM as package
files.append((Config.CONTEXTUALIZATION_DIR + "/__init__.py", remote_dir + "/IM/__init__.py"))
# copy the ansible_install script to install the nodes
files.append((Config.CONTEXTUALIZATION_DIR + "/ansible_install.sh",
remote_dir + "/ansible_install.sh"))
if self.inf.radl.ansible_hosts:
for ansible_host in self.inf.radl.ansible_hosts:
(user, passwd, private_key) = ansible_host.getCredentialValues()
ssh = SSHRetry(ansible_host.getHost(), user, passwd, private_key)
ssh.sftp_mkdir(Config.REMOTE_CONF_DIR, 0o755)
ssh.sftp_mkdir(remote_dir, 0o700)
ssh.sftp_mkdir(remote_dir + "/IM")
ssh.sftp_put_files(files)
# Copy the utils helper files
ssh.sftp_mkdir(remote_dir + "/utils")
ssh.sftp_put_dir(Config.RECIPES_DIR + "/utils", remote_dir + "//utils")
# Copy the ansible_utils files
ssh.sftp_mkdir(remote_dir + "/IM/ansible_utils")
ssh.sftp_put_dir(Config.IM_PATH + "/ansible_utils", remote_dir + "/IM/ansible_utils")
else:
ssh.sftp_mkdir(remote_dir, 0o700)
ssh.sftp_mkdir(remote_dir + "/IM")
ssh.sftp_put_files(files)
# Copy the utils helper files
ssh.sftp_mkdir(remote_dir + "/utils")
ssh.sftp_put_dir(Config.RECIPES_DIR + "/utils", remote_dir + "/utils")
# Copy the ansible_utils files
ssh.sftp_mkdir(remote_dir + "/IM/ansible_utils")
ssh.sftp_put_dir(Config.IM_PATH + "/ansible_utils", remote_dir + "/IM/ansible_utils")
success = configured_ok
except Exception as ex:
self.log_exception("Error in the ansible installation process")
self.inf.add_cont_msg("Error in the ansible installation process: " + str(ex))
if not self.inf.ansible_configured:
self.inf.ansible_configured = False
success = False
finally:
if ssh:
ssh.close()
if tmp_dir:
shutil.rmtree(tmp_dir, ignore_errors=True)
if success:
self.inf.ansible_configured = True
self.inf.set_configured(True)
# Force to save the data to store the log data
IM.InfrastructureList.InfrastructureList.save_data(self.inf.id)
else:
self.inf.ansible_configured = False
self.inf.set_configured(False)
return success
def wait_master(self):
"""
- Select the master VM
- Wait it to boot and has the SSH port open
"""
if self.inf.radl.ansible_hosts:
self.log_info("Usign ansible host: " + self.inf.radl.ansible_hosts[0].getHost())
self.inf.set_configured(True)
return True
# First assure that ansible is installed in the master
if not self.inf.vm_master or self.inf.vm_master.destroy:
# If the user has deleted the master vm, it must be configured
# again
self.inf.ansible_configured = None
success = True
if not self.inf.ansible_configured:
# Select the master VM
ssh = None
try:
self.inf.add_cont_msg("Select master VM")
self.inf.select_vm_master()
if not self.inf.vm_master:
# If there are not a valid master VM, exit
self.log_error("No correct Master VM found. Exit")
self.inf.add_cont_msg("Contextualization Error: No correct Master VM found. Check if there a "
"linux VM with Public IP.")
self.inf.set_configured(False)
return
self.log_info("Wait the master VM to be running")
self.inf.add_cont_msg("Wait master VM to boot")
all_running = self.wait_vm_running(self.inf.vm_master, Config.WAIT_RUNNING_VM_TIMEOUT)
if not all_running:
self.log_error("Error Waiting the Master VM to boot, exit")
self.inf.add_cont_msg("Contextualization Error: Error Waiting the Master VM to boot")
self.inf.set_configured(False)
return
self.inf.add_cont_msg("Wait master VM to have the SSH active.")
is_connected, msg = self.wait_vm_ssh_acccess(self.inf.vm_master, Config.WAIT_SSH_ACCCESS_TIMEOUT)
if not is_connected:
self.log_error("Error Waiting the Master VM to have the SSH active, exit: " + msg)
self.inf.add_cont_msg("Contextualization Error: Error Waiting the Master VM to have the SSH"
" active: " + msg)
self.inf.set_configured(False)
return
self.log_info("VMs available.")