/
helpers.py
1688 lines (1504 loc) · 66.3 KB
/
helpers.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 re
import sys
import os
import time
import tempfile
from copy import deepcopy
import collections
from os.path import expanduser, normpath, basename
from fabfile.config import *
import fabfile.common as common
from fabfile.utils.host import *
from fabfile.utils.multitenancy import *
from fabfile.utils.fabos import *
from fabric.contrib.files import exists
import datetime
from fabfile.tasks.esxi_defaults import apply_esxi_defaults
from fabfile.utils.cluster import get_orchestrator, get_all_hostnames, get_hostname
from fabfile.utils.analytics import get_analytics_data_dir, get_minimum_diskGB
from fabfile.tasks.ntp import setup_ntp, setup_ntp_node
from fabfile.utils.fabos import detect_ostype, is_package_installed, is_liberty_or_above
@task
def copydir(src_path, dst_path=None, src_host='localhost', dst_host=None):
if not dst_host:
raise RuntimeError("Please specify destination host")
if not dst_path:
dst_path = src_path
src_path = (normpath(expanduser(src_path)))
dst_path = normpath(expanduser(dst_path))
if not src_host == 'localhost':
with settings(host_string=src_host,
password=get_env_passwords(src_host)):
tmpdir = tempfile.mkdtemp()
get_as_sudo(src_path, tmpdir)
src_path = os.path.join(tmpdir, basename(src_path))
with settings(host_string=dst_host,
password=get_env_passwords(dst_host)):
sudo('mkdir -p %s' % dst_path)
put('%s/*' % src_path, dst_path, use_sudo=True)
@task
@parallel
@roles('compute')
def compute_reboot(waitup='yes'):
if env.roledefs['compute']:
reboot_node(waitup, env.host_string)
@task
def reboot_node(waitup, *args):
for host_string in args:
user, hostip = host_string.split('@')
with settings(hide('running'), host_string=host_string, warn_only=True):
#Fabric hangs when reboot --force is issued, so adding timeout
#as workaround.
try:
sudo("/etc/contrail/contrail_reboot", timeout=5)
except CommandTimeout:
pass
print 'Reboot issued; Waiting for the node (%s) to go down...' % hostip
common.wait_until_host_down(wait=300, host=hostip)
if waitup == 'no':
return
print 'Node (%s) is down... Waiting for node to come back' % hostip
sys.stdout.write('.')
count = 0
while not verify_sshd(hostip,
user,
get_env_passwords(host_string)):
sys.stdout.write('.')
sleep(2)
count+=1
if count <=1000:
continue
else:
print 'Timed out waiting for node to come back up'
sys.exit(1)
# end compute_reboot
def reimage_virtual_nodes(host, count):
with settings(
host_string='%s@%s' % (
env.virtual_nodes_info[host]['keystone_user'],
env.virtual_nodes_info[host]['keystone_ip']),
password=env.virtual_nodes_info[host]['keystone_pass'],
warn_only=True, abort_on_prompts=False, debug=True):
common_agrs = '--os-username %s --os-password %s --os-tenant-name %s \
--os-auth-url http://%s:5000/v2.0/' \
% (env.virtual_nodes_info[host]['user'],
env.virtual_nodes_info[host]['password'],
env.virtual_nodes_info[host]['tenant'],
env.virtual_nodes_info[host]['keystone_authip'])
for i in range(10):
status = run(
"nova %s delete %s" %
(common_agrs, get_hostname(host)))
sleep(5)
check = run(
"nova %s show %s | grep 'status'" %
(common_agrs, get_hostname(host)))
if 'status' in check:
if i > 5:
print 'Timed out waiting for vm to get deleted aborting'
sys.exit(1)
else:
print 'Waiting for vm to get deleted'
sleep(5)
else:
break
status = run(
"neutron %s port-create --tenant-id %s --mac-address %s \
--fixed-ip ip_address=%s --name %s %s" \
% (common_agrs,
env.virtual_nodes_info[host]['tenant_id'],
env.virtual_nodes_info[host]['mac-address'],
host.split('@')[1],
get_hostname(host),
env.virtual_nodes_info[host]['vn_id']))
m = re.search('\|\sid(.*)\|\s([\w-]+)(.*)\|', status)
port_id = m.group(2)
sleep(5)
run("nova %s boot --flavor %s --image %s --nic port-id=%s %s" \
% (common_agrs,
env.virtual_nodes_info[host]['flavor'],
env.virtual_nodes_info[host]['image_name'],
port_id,
get_hostname(host)))
for i in range(10):
check = run(
"nova %s show %s | grep 'status'" %
(common_agrs, get_hostname(host)))
if 'ACTIVE' not in check:
if i > 5:
print 'Timed out waiting for vm to become Active'
sys.exit(1)
else:
print 'Waiting for vm to get Active'
sleep(5)
else:
break
@roles('build')
@task
def all_reimage(build_param="@LATEST"):
count = 0
for host in env.roledefs["all"]:
if 'virtual_nodes_info' in env.keys() and host in env.virtual_nodes_info.keys():
reimage_virtual_nodes(host, count)
count = count + 1
else:
hostname = get_hostname(host)
if 'ostypes' in env.keys():
if 'xen' in env.ostypes[host]:
pass
elif 'ubuntu1404' == env.ostypes[host]:
base_img = 'ubuntu-14.04'
elif 'ubuntu' in env.ostypes[host]:
base_img = 'ubuntu-12.04.3'
elif 'centos70' == env.ostypes[host]:
base_img = 'centos-7.0'
elif 'centos71' == env.ostypes[host]:
base_img = 'centos-7.1'
elif 'centos65' == env.ostypes[host]:
base_img = 'centos-6.5'
elif 'centos' in env.ostypes[host]:
base_img = 'centos-6.4'
elif 'redhat70' in env.ostypes[host]:
base_img = 'redhat-7.0'
elif 'redhat' in env.ostypes[host]:
base_img = 'redhat'
with settings(warn_only=True):
local(
"/cs-shared/server-manager/client/server-manager reimage --no_confirm --server_id %s %s" %
(hostname, base_img))
else:
# CentOS
local(
"/cs-shared/server-manager/client/server-manager reimage --no_confirm --server_id %s centos-6.5" %
(hostname))
sleep(5)
# end all_reimage
@roles('build')
@task
def all_sm_reimage(build_param=None,smgr_client='/cs-shared/server-manager/client/server-manager'):
hosts = env.roledefs['all'][:]
esxi_hosts = getattr(testbed, 'esxi_hosts', None)
cluster_id=None
try:
cluster_id=env.cluster_id
except:
sys.stdout.write('No cluster_id specified in testbed file.\n')
sys.stdout.write('Reimage will be done on per node basis.\n')
if ((cluster_id is not None) and (not esxi_hosts)):
reimage_cmd=smgr_client + ' reimage --no_confirm --cluster_id '
if build_param is not None:
with settings(warn_only=True):
reimage_cmd = reimage_cmd + '%s %s' % (cluster_id,build_param)
local(reimage_cmd)
else:
if 'ostypes' in env.keys():
if 'ubuntu' in env.ostypes[env.ostypes.keys()[0]]:
with settings(warn_only=True):
reimage_cmd = reimage_cmd + '%s ubuntu-12.04.3' % cluster_id
local(reimage_cmd)
else:
# CentOS
with settings(warn_only=True):
reimage_cmd = reimage_cmd + '%s centos-6.4' % cluster_id
local(reimage_cmd)
else:
# CentOS
with settings(warn_only=True):
reimage_cmd = reimage_cmd + '%s centos-6.4' % cluster_id
local(reimage_cmd)
sleep(1)
sleep(30)
else:
if esxi_hosts:
for esxi in esxi_hosts:
if 'contrail_vm' in esxi:#In vcenter gateway,contrail_vm not there
hosts.remove(esxi_hosts[esxi]['contrail_vm']['host'])
for host in hosts:
hostname = get_hostname(host)
if build_param is not None:
with settings(warn_only=True):
local("/cs-shared/server-manager/client/server-manager reimage --no_confirm --server_id %s %s" % (hostname,build_param))
else:
if 'ostypes' in env.keys():
if 'ubuntu' in env.ostypes[host]:
with settings(warn_only=True):
local("/cs-shared/server-manager/client/server-manager reimage --no_confirm --server_id %s ubuntu-12.04.3" % (hostname))
else:
# CentOS
with settings(warn_only=True):
local("/cs-shared/server-manager/client/server-manager reimage --no_confirm --server_id %s centos-6.4" % (hostname))
else:
# CentOS
with settings(warn_only=True):
local("/cs-shared/server-manager/client/server-manager reimage --no_confirm --server_id %s centos-6.4" % (hostname))
sleep(1)
if esxi_hosts:
count=0
image="esx5.5"
for esxi in esxi_hosts:
if 'skip_reimage' not in esxi_hosts[esxi]:#Its a hack to avoid reimage of the esxi servers
count=count+1
image_id=image + "-" + str(count)
with settings(warn_only=True):
local("/cs-shared/server-manager/client/server-manager reimage --no_confirm --server_id %s %s" % (esxi,image_id))
sleep(10)
#end all_sm_reimage
@roles('compute')
@task
def contrail_version():
sudo("contrail-version")
@task
@parallel
@roles('all')
def all_reboot():
with settings(hide('running'), warn_only=True):
if env.host_string in env.roledefs['compute']:
compute_reboot()
else:
#Fabric hangs when reboot --force is issued, so adding timeout as
# workaround.
try:
sudo("reboot --force", timeout=5)
except CommandTimeout:
pass
#end all_reboot
@task
@roles('build')
def check_ssh():
sshd_down_hosts = ''
for host_string in env.roledefs["all"]:
user, hostip = host_string.split('@')
password = get_env_passwords(host_string)
if not verify_sshd(hostip, user, password):
sshd_down_hosts += "%s : %s\n" % (host_string, password)
if sshd_down_hosts:
raise Exception("Following list of hosts are down: \n %s" % sshd_down_hosts)
else:
print "\n\tAll nodes are Up."
@roles('all')
@task
def all_command(command):
sudo(command)
#run(command)
#end all_command
@roles('all')
@task
def all_ping():
for host in get_all_hostnames():
local("ping -c 1 -q %s " %(host))
#end all_ping
def ping_test(host_string):
with settings(host_string=host_string, warn_only = True):
result = local("ping -c 1 -q %s" % hstr_to_ip(host_string))
if result.return_code == 0:
return True
else:
return False
@roles('all')
@task
def all_version():
sudo("contrail-version")
#end all_ping
@roles('all')
@task
def check_reimage_state():
failed_host = []
hosts = get_all_hostnames()[:]
esxi_hosts = getattr(testbed, 'esxi_hosts', None)
if esxi_hosts:
for esxi in esxi_hosts:
try:
if env['host_string'] == esxi_hosts[esxi]['contrail_vm']['host']:
print "skipping contrail vm, continue..."
return
except Exception as e:
print "%s"%e
return #Handling the exception if contrail-vm not present in testbed.py,
#which is the case for vcenter gateway
for host in hosts:
if exists('/opt/contrail'):
failed_host.append(host)
if failed_host:
print "reimage failed on hosts: %s, aborting..." %failed_host
sys.exit(1)
else:
print "reimage successful, continue..."
#end check_reimage_state
@roles('all')
@task
def all_crash():
sudo("ls -l /var/crashes")
@roles('control')
@task
def control_crash():
sudo("ls -l /var/crashes")
@roles('compute')
@task
def compute_crash():
sudo("ls -l /var/crashes")
@roles('compute')
@task
def compute_provision():
cfgm_host = env.roledefs['cfgm'][0]
cfgm_ip = hstr_to_ip(cfgm_host)
tgt_ip = env.host_string.split('@')[1]
tgt_hostname = sudo("hostname")
prov_args = "--host_name %s --host_ip %s --api_server_ip %s --oper add " \
%(tgt_hostname, tgt_ip, cfgm_ip)
sudo("/opt/contrail/utils/provision_vrouter.py %s" %(prov_args))
@roles('compute')
@task
def install_img_agent():
sudo("yum localinstall %s/extras/contrail-agent*.rpm" %(INSTALLER_DIR))
#end install_img_agent
#@roles('compute')
@task
def test():
sudo('cd /; ls')
@roles('compute')
@task
def start_vnc():
sudo("vncserver")
@roles('cfgm')
@task
def cfgm_status():
sudo("service contrail-api status")
sudo("service contrail-schema status")
sudo("service contrail-discovery status")
if get_orchestrator is 'openstack':
sudo("service contrail-svc-monitor status")
sudo("service ifmap status")
#end cfgm_status
@roles('cfgm')
@task
def api_restart():
sudo("service contrail-api restart")
#end api_restart
@roles('cfgm')
@task
def schema_restart():
sudo("service contrail-schema restart")
#end schema_restart
@roles('database')
@task
def database_restart():
sudo("service contrail-database restart")
#end database_restart
@roles('database')
@task
def database_status():
sudo("service contrail-database status")
#end database_status
@roles('control')
@task
def control_restart():
sudo("service contrail-control restart")
#end control_restart
@roles('control')
@task
def control_status():
sudo("service contrail-control status")
#end control_status
@roles('compute')
@task
def compute_status():
nova_compute = "openstack-nova-compute"
if detect_ostype() in ['ubuntu']:
nova_compute = "nova-compute"
sudo("service %s status" % nova_compute)
sudo("service contrail-vrouter-agent status")
#end compute_status
@roles('compute')
@task
def agent_restart():
sudo("service contrail-vrouter-agent restart")
#end agent_restart
@roles('cfgm')
@task
def config_demo():
cfgm_ip = hstr_to_ip(get_control_host_string(env.roledefs['cfgm'][0]))
with cd(UTILS_DIR):
sudo("python demo_cfg.py --api_server_ip %s --api_server_port 8082 --public_subnet %s %s" %(cfgm_ip, testbed.public_vn_subnet, get_mt_opts()))
sudo("python add_route_target.py --routing_instance_name default-domain:demo:public:public --route_target_number %s --router_asn %s --api_server_ip %s --api_server_port 8082 %s" \
%(testbed.public_vn_rtgt, testbed.router_asn, cfgm_ip, get_mt_opts()))
sudo("python create_floating_pool.py --public_vn_name default-domain:demo:public --floating_ip_pool_name pub_fip_pool --api_server_ip %s --api_server_port 8082 %s" %(cfgm_ip, get_mt_opts()))
sudo("python use_floating_pool.py --project_name default-domain:demo --floating_ip_pool_name default-domain:demo:public:pub_fip_pool --api_server_ip %s --api_server_port 8082 %s" %(cfgm_ip, get_mt_opts()))
#end config_demo
@task
def add_images(image=None):
images = [ ("turnkey-redmine-12.0-squeeze-x86.vmdk", "redmine-web"),
("turnkey-redmine-12.0-squeeze-x86-mysql.vmdk", "redmine-db"),
("ubuntu.img", "ubuntu"),
("traffic/ubuntu-traffic.img", "ubuntu-traffic"),
("vsrx/junos-vsrx-12.1-in-network.img", "nat-service"),
("vsrx/junos-vsrx-12.1-transparent.img", "vsrx-bridge"),
("ubuntu-netperf.img", "ubuntu-netperf"),
("analyzer/analyzer-vm-console.qcow2", "analyzer"),
("ddos.qcow2", "ddos"),
("demo-ddos.vmdk", "demo-ddos"),
("Tier1-LB-Snapshot.qcow2", "Tier1-LB"),
("Tier2-Web-Snapshot.qcow2", "Tier2-Web"),
("Tier2-DB-Snapshot.qcow2", "Tier2-DB"),
("vsrx-fw-no-ping.qcow2", "vsrx-fw-no-ping"),
("sugarcrm.vmdk", "sugarcrm") ,
("docker/phusion-baseimage-enablesshd.tar", "phusion-baseimage-enablesshd"),
]
for (loc, name) in images:
if image is not None and image != name:
continue
local = "/images/"+loc+".gz"
remote = loc.split("/")[-1]
remote_gz = remote+".gz"
glance_host = env.roledefs['openstack'][0]
if 'docker' in loc:
if env.get('hypervisor', None):
docker_nodes = filter(lambda (node, hypervisor): hypervisor == 'docker',
env.hypervisor.items())
if docker_nodes:
# First docker compute
glance_host = docker_nodes[0][0]
else:
print "No compute is provisioned with docker as hypervisor. Skipping..."
continue
with settings(host_string=glance_host):
mount = None
if '10.84' in env.host_string:
mount = '10.84.5.120/cs-shared'
elif '10.204' in env.host_string:
mount = '10.204.217.158'
if not mount:
return
sudo("wget http://%s/%s" % (mount, local))
sudo("gunzip " + remote_gz)
os_type = detect_ostype()
openstack_sku = get_openstack_sku()
liberty_or_above = is_liberty_or_above()
if liberty_or_above:
cmd = "source /etc/contrail/openstackrc; {PRECMD}"\
" glance --insecure image-create --name {IMGNAME}"\
" --visibility public --container-format {IMGFORMAT}"\
" --disk-format {DISKFORMAT} {IMGFILE_OPT}"
else:
cmd = "source /etc/contrail/openstackrc; {PRECMD}"\
" glance --insecure image-create --name {IMGNAME}"\
" --is-public True --container-format {IMGFORMAT}"\
" --disk-format {DISKFORMAT} {IMGFILE_OPT}"
if ".vmdk" in loc:
glance_kwargs = {'PRECMD': '',
'IMGNAME' : name,
'IMGFORMAT' : 'ovf',
'DISKFORMAT' : 'vmdk',
'IMGFILE_OPT' : '--file %s' % remote}
elif "docker" in loc:
image_name = remote.split(".tar")[0]
sudo("docker load -i %s" % remote)
glance_kwargs = {'PRECMD': 'docker save %s |' % image_name,
'IMGNAME' : name,
'IMGFORMAT' : 'docker',
'DISKFORMAT' : 'raw',
'IMGFILE_OPT' : ''}
else:
glance_kwargs = {'PRECMD': '',
'IMGNAME' : name,
'IMGFORMAT' : 'ovf',
'DISKFORMAT' : 'qcow2',
'IMGFILE_OPT' : '--file %s' % remote}
sudo(cmd.format(**glance_kwargs))
sudo("rm %s" % remote)
#end add_images
def preload_image_to_esx(url, glance_id, sizes, version):
esxi_hosts = getattr(testbed, 'esxi_hosts', None)
if not esxi_hosts:
return
for esxi in esxi_hosts.values():
try:
if esxi['contrail_vm']['host'] in env.roledefs['compute']:
apply_esxi_defaults(esxi)
# for havana(2013.2), images are stored under datastore/vmware_base/
base = esxi['datastore'] + 'vmware_base/'
# for icehouse, images are stored under datstore/<ip>_base/<glanceid>/
if '2014.1' in version:
ip = esxi['contrail_vm']['host'].split('@')[-1]
base = esxi['datastore'] + '/' + ip + '_base/' + glance_id + '/'
with settings(host_string = esxi['username'] + '@' + esxi['ip'],
password = esxi['password'], warn_only=True,
shell = '/bin/sh -l -c'):
run('mkdir -p %s' % base)
with cd(base):
run('wget -O ' + glance_id + '-sparse.vmdk.gz ' + url)
run('gunzip ' + glance_id + '-sparse.vmdk.gz')
run('vmkfstools -i ' + glance_id + '-sparse.vmdk -a ide ' + glance_id + '.vmdk')
run('rm ' + glance_id + '-sparse.vmdk')
for size in sizes:
run('vmkfstools -i ' + glance_id + '.vmdk -a ide ' + glance_id + '.' + str(size) + '.vmdk')
run('vmkfstools -X ' + str(size) + 'G ' + glance_id + '.' + str(size) + '.vmdk')
except Exception as e:
print "%s"%e
pass #Handling exception for vcenter gateway
#end preload_images_to_esx
@hosts(*env.roledefs['openstack'][0:1])
@task
def add_basic_images(image=None):
mount=None
if '10.84' in env.host:
mount= '10.84.5.120/cs-shared'
elif '10.204' in env.host:
mount= '10.204.217.158'
if not mount :
return
openstack_version = run("source /etc/contrail/openstackrc; nova-manage version")
images = [ ("converts/ubuntu.vmdk", "ubuntu", [10,20]),
("converts/ubuntu-traffic.vmdk", "ubuntu-traffic", [10,20]),
("converts/centos-min.vmdk", "centos65-ipv6", [10]),
("converts/ubuntu-dhcp-server.vmdk", "ubuntu-dhcp-server", []),
("converts/cirros-0.3.0-x86_64-disk.vmdk", "cirros", [1,10]),
("vsrx/junos-vsrx-12.1-in-network.img", "vsrx", []),
("analyzer/analyzer-vm-console.qcow2", "analyzer", []),
("converts/ubuntu-dns-server.vmdk", "ubuntu-dns-server", []),
("converts/ubuntu-dhcpdns-server.vmdk", "ubuntu-dhcpdns-server", []),
("tinycore/tinycore-in-network-nat.qcow2", "tiny-nat-fw", []),
("tinycore/tinycore-in-network.qcow2", "tiny-in-net", []),
("tinycore/tinycore-net-transparent-fw.qcow2", "tiny-trans-fw", []),
]
for (loc, name, sizes) in images:
if image is not None and image != name:
continue
local = "/images/"+loc+".gz"
remote = loc.split("/")[-1]
remote_gz = remote+".gz"
run("wget http://%s/%s" % (mount, local))
run("gunzip " + remote_gz)
os_type = detect_ostype()
openstack_sku = get_openstack_sku()
liberty_or_above = is_liberty_or_above()
if liberty_or_above:
if ".vmdk" in loc:
if 'converts' in loc:
glance_id = run("(source /etc/contrail/openstackrc; glance --insecure image-create --name '"+name+"' --visibility public --container-format bare --disk-format vmdk --property vmware_disktype='sparse' --property vmware_adaptertype='ide' < "+remote+" | grep -e 'id\>' | awk '{printf $4}')")
else:
glance_id = run("(source /etc/contrail/openstackrc; glance --insecure add name='"+name+"' --visibility public container_format=ovf disk_format=vmdk < "+remote+" | grep -e 'id\>' | awk '{printf $4}')")
if glance_id.succeeded:
preload_image_to_esx('http://%s/%s' % (mount,local), glance_id, sizes, openstack_version)
else:
run("(source /etc/contrail/openstackrc; glance --insecure image-create --name '"+name+"' --visibility public --container-format ovf --disk-format qcow2 --property hypervisor_type=qemu < "+remote+")")
else:
if ".vmdk" in loc:
if 'converts' in loc:
glance_id = run("(source /etc/contrail/openstackrc; glance --insecure image-create --name '"+name+"' --is-public True --container-format bare --disk-format vmdk --property vmware_disktype='sparse' --property vmware_adaptertype='ide' < "+remote+" | grep -e 'id\>' | awk '{printf $4}')")
else:
glance_id = run("(source /etc/contrail/openstackrc; glance --insecure add name='"+name+"' is_public=true container_format=ovf disk_format=vmdk < "+remote+" | grep -e 'id\>' | awk '{printf $4}')")
if glance_id.succeeded:
preload_image_to_esx('http://%s/%s' % (mount,local), glance_id, sizes, openstack_version)
else:
run("(source /etc/contrail/openstackrc; glance --insecure image-create --name '"+name+"' --is-public True --container-format ovf --disk-format qcow2 --property hypervisor_type=qemu < "+remote+")")
run("rm "+remote)
#end add_basic_images
@roles('compute')
@task
def virsh_cleanup():
result = sudo("ls /etc/libvirt/qemu/instance*.xml | cut -d '/' -f 5 | cut -d '.' -f 1")
for inst_name in result.split():
if re.match('instance', inst_name):
with settings(warn_only = True):
sudo('virsh destroy %s' %(inst_name))
sudo('virsh undefine %s' %(inst_name))
sudo('rm -rf /var/lib/nova/instances/%s' %(inst_name))
#end virsh_cleanup
@task
def virsh_cmd(cmd):
result = sudo('virsh %s' %(cmd))
#end virsh_cmd
@task
def sudo_cmd(cmd):
result = sudo(cmd)
#end sudo_cmd
@roles('cfgm')
@task
def net_list():
cfgm_ip = hstr_to_ip(env.roledefs['cfgm'][0])
os_opts = ''
os_opts = os_opts + ' --os-username %s --os-password %s ' % get_authserver_credentials()
os_opts = os_opts + ' --os-tenant-name %s ' % get_admin_tenant_name()
os_opts = os_opts + ' --os-auth-url http://%s:5000/v2.0 ' %(cfgm_ip)
sudo('quantum %s net-list' %(os_opts))
#end net_list
@roles('cfgm')
@task
def demo_fixup():
sudo("service openstack-nova-compute restart")
sudo("service contrail-schema restart")
@task
def copy(src, dst = '.'):
put(src, dst, use_sudo=True)
#end copy
@roles('openstack')
def cleanup_os_config():
'''
This has to be run from reset_config() task only
'''
dbs=['nova', 'mysql', 'keystone', 'glance', 'cinder','heat']
services =['mysqld', 'openstack-nova-novncproxy', 'rabbitmq-server', 'openstack-cinder-volume', 'openstack-cinder-scheduler', 'openstack-cinder-api', 'openstack-glance-registry', 'openstack-glance-api', 'openstack-nova-xvpvncproxy', 'openstack-nova-scheduler', 'openstack-nova-objectstore', 'openstack-nova-metadata-api', 'openstack-nova-consoleauth', 'openstack-nova-console', 'openstack-nova-compute', 'openstack-nova-cert', 'openstack-nova-api', 'openstack-keystone']
ubuntu_services =['mysql', 'nova-novncproxy', 'rabbitmq-server', 'cinder-volume', 'cinder-scheduler', 'cinder-api', 'glance-registry', 'glance-api', 'nova-xvpvncproxy', 'nova-scheduler', 'nova-objectstore', 'nova-metadata-api', 'nova-consoleauth', 'nova-console', 'nova-compute', 'nova-cert', 'nova-api', 'contrail-vncserver', 'keystone', ]
# Drop all dbs
with settings(warn_only=True):
sudo('mysqladmin -u root -p$(cat /etc/contrail/mysql.token) password \'\' ')
for db in dbs:
sudo('mysql -u root -e \'drop database %s;\'' %(db))
if detect_ostype() == 'ubuntu':
services = ubuntu_services
for service in services :
sudo('sudo service %s stop' %(service))
sudo('sudo rm -f /etc/contrail/mysql.token')
sudo('sudo rm -f /etc/contrail/service.token')
sudo('sudo rm -f /etc/contrail/keystonerc')
#TODO
# In Ubuntu, by default glance uses sqlite
# Until we have a clean way of clearing glance image-data in sqlite,
# just skip removing the images on Ubuntu
if not detect_ostype() in ['ubuntu']:
sudo('sudo rm -rf /var/lib/glance/images/*')
sudo('sudo rm -rf /var/lib/nova/tmp/nova-iptables')
sudo('sudo rm -rf /var/lib/libvirt/qemu/instance*')
sudo('sudo rm -rf /var/log/libvirt/qemu/instance*')
sudo('sudo rm -rf /var/lib/nova/instances/*')
sudo('sudo rm -rf /etc/libvirt/nwfilter/nova-instance*')
sudo('sudo rm -rf /var/log/libvirt/qemu/inst*')
sudo('sudo rm -rf /etc/libvirt/qemu/inst*')
sudo('sudo rm -rf /var/lib/nova/instances/_base/*')
if detect_ostype() in ['ubuntu'] and env.host_string in env.roledefs['openstack']:
sudo('mysql_install_db --user=mysql --ldata=/var/lib/mysql/')
#end cleanup_os_config
@roles('build')
@task
def config_server_reset(option=None, hosts=[]):
for host_string in hosts:
api_config_file = '/etc/contrail/supervisord_config_files/contrail-api.ini'
disc_config_file = '/etc/contrail/supervisord_config_files/contrail-discovery.ini'
schema_config_file = '/etc/contrail/supervisord_config_files/contrail-schema.ini'
svc_m_config_file = '/etc/contrail/supervisord_config_files/contrail-svc-monitor.ini'
with settings(host_string=host_string):
try :
if option == "add" :
sudo('sudo sed -i \'s/contrail-api --conf_file/contrail-api --reset_config --conf_file/\' %s' %(api_config_file))
sudo('sudo sed -i \'s/discovery-server --conf_file/discovery-server --reset_config --conf_file/\' %s' %(disc_config_file))
sudo('sudo sed -i \'s/contrail-schema --conf_file/contrail-schema --reset_config --conf_file/\' %s' %(schema_config_file))
sudo('sudo sed -i \'s/contrail-svc-monitor --conf_file/contrail-svc-monitor --reset_config --conf_file/\' %s' %(svc_m_config_file))
elif option == 'delete' :
sudo('sudo sed -i \'s/contrail-api --reset_config/contrail-api/\' %s' %(api_config_file))
sudo('sudo sed -i \'s/discovery-server --reset_config/discovery-server/\' %s' %(disc_config_file))
sudo('sudo sed -i \'s/contrail-schema --reset_config/contrail-schema/\' %s' %(schema_config_file))
sudo('sudo sed -i \'s/contrail-svc-monitor --reset_config/contrail-svc-monitor/\' %s' %(svc_m_config_file))
except SystemExit as e:
print "Failure of one or more of these cmds are ok"
#end config_server_reset
@roles('compute')
@task
def start_servers(file_n="traffic_profile.py"):
file_fabt = os.getcwd() + "/fabfile/testbeds/traffic_fabfile.py"
file_proft = os.getcwd() + "/fabfile/testbeds/" + file_n
with settings(warn_only=True):
put(file_fabt, "~/fabfile.py", use_sudo=True)
put(file_proft, "~/traffic_profile.py", use_sudo=True)
sudo("fab setup_hosts start_servers")
@roles('compute')
@task
def start_clients():
with settings(warn_only=True):
sudo("fab setup_hosts start_clients")
# from build we go to each compute node, and from there fab run to each of the
# VMs to start traffic scripts
# testbeds/traffic_fabfile.py is copied to each compute node and is the fab file
# used to run traffic scripts in the VMs
# testbeds/traffic_profile.py describes the connections that are need to be made
# by the traffic scripts - testbeds/traffic_profile_sample.py gives one such example
@roles('build')
@task
def start_traffic():
execute(start_servers)
sleep(10)
execute(start_clients)
@roles('build')
@task
def ping_hostip(hostip='127.0.0.0'):
cmd = 'ping -c 3 -q %s' %hostip
output = 0
with settings(hide('running'), warn_only=True):
try:
output=local(cmd,capture=True)
except:
pass
if " 100% packet loss" in output:
output=0
else:
output=1
return output
@roles('build')
@task
def wait_till_all_up(attempts=90, interval=10, node=None, waitdown=True, contrail_role='all', reimaged=False):
''' Waits for given nodes to go down and then comeup within the given attempts.
Defaults: attempts = 90 retries
interval = 10 secs
node = env.roledefs['all']
'''
if node:
nodes = node
else:
nodes = env.roledefs[contrail_role][:]
if reimaged:
esxi_hosts = getattr(testbed, 'esxi_hosts', None)
if esxi_hosts:
for esxi in esxi_hosts:
hstr = esxi_hosts[esxi]['username'] + '@' + esxi_hosts[esxi]['ip']
nodes.append(hstr)
env.passwords[hstr] = esxi_hosts[esxi]['password']
try:
nodes.remove(esxi_hosts[esxi]['contrail_vm']['host'])
except Exception as e:
print "%s"%e
pass #Handing exception for vcenter gateway
#Entry for contrail_vm not there in testbed.py
nodes = [nodes] if type(nodes) is str else nodes
#Waits for node to shutdown
if waitdown != 'False' and not (reimaged and esxi_hosts):
for node in nodes:
nodeip = node.split('@')[1]
print 'Waiting for the node (%s) to go down...' %nodeip
common.wait_until_host_down(host=nodeip, wait=900)
print 'Given Nodes are down... Waiting for nodes to come back'
for node in nodes:
user, hostip = node.split('@')
count = 0
print 'Trying to ping node - %s' %hostip
while not ping_hostip(hostip):
sys.stdout.write('.')
sleep(int(interval))
count+=1
if count <= int(attempts):
continue
else:
print 'Ping failed to host - %s' %hostip
sys.exit(1)
while not verify_sshd(hostip,
user,
get_env_passwords(node)):
sys.stdout.write('.')
sleep(int(interval))
count+=1
if count <= int(attempts):
continue
else:
print 'Timed out waiting for node (%s) to come back up...' %node
sys.exit(1)
return 0
def enable_haproxy():
''' For Ubuntu. Set ENABLE=1 in /etc/default/haproxy
'''
if detect_ostype() == 'ubuntu':
with settings(warn_only=True):
sudo("sudo sed -i 's/ENABLED=.*/ENABLED=1/g' /etc/default/haproxy")
#end enable_haproxy
def qpidd_changes_for_ubuntu():
'''Qpidd.conf changes for Ubuntu
'''
qpid_file = '/etc/qpid/qpidd.conf'
if detect_ostype() == 'ubuntu':
with settings(warn_only=True):
sudo("sudo sed -i 's/load-module=\/usr\/lib\/qpid\/daemon\/acl.so/#load-module=\/usr\/lib\/qpid\/daemon\/acl.so/g' %s" %(qpid_file))
sudo("sudo sed -i 's/acl-file=\/etc\/qpid\/qpidd.acl/#acl-file=\/etc\/qpid\/qpidd.acl/g' %s" %(qpid_file))
sudo("sudo sed -i 's/max-connections=2048/#max-connections=2048/g' %s" %(qpid_file))
sudo('grep -q \'auth=no\' %s || echo \'auth=no\' >> %s' %(qpid_file,qpid_file))
sudo('service qpidd restart')
#end qpidd_changes_for_ubuntu
@task
def is_pingable(host_string, negate=False, maxwait=900):
result = 0
hostip = host_string.split('@')[1]
starttime = datetime.datetime.now()
timedelta = datetime.timedelta(seconds=int(maxwait))
runouput = collections.namedtuple('runouput', 'return_code')
with settings(host_string=host_string, warn_only=True):
while True:
try:
res = sudo('ping -q -w 2 -c 1 %s' %hostip)
except:
res = runouput(return_code=1)
if res.return_code == 0 and negate == 'False':
print 'Host (%s) is Pingable'
break
elif res.return_code != 0 and negate == 'True':
print 'Host (%s) is Down' %hostip
break
elif starttime + timedelta <= datetime.datetime.now():
print 'Timeout while trying to ping host (%s)' %hostip
result = 1
break
else:
print 'Retrying...'
time.sleep(1)
return result
@task
def setup_hugepages_node(*args):
"""Setup hugepages on one or list of nodes
USAGE: fab setup_hugepages_node:user@host1,user@host2,...
"""
# How many times DPDK inits hugepages (rte_eal_init())
# See function map_all_hugepages() in DPDK
DPDK_HUGEPAGES_INIT_TIMES = 2
for host_string in args:
dpdk = getattr(env, "dpdk", {})
if host_string not in dpdk:
print "Host %s is not dpdk enabled, not configuring hugepages" \
% host_string
return
# get required size of hugetlbfs
factor = int(dpdk[host_string]['huge_pages'])
if factor == 0:
factor = 1
with settings(host_string=host_string):
# set number of huge pages
memsize = sudo("grep MemTotal /proc/meminfo | tr -s ' ' | cut -d' ' -f 2")
pagesize = sudo("grep Hugepagesize /proc/meminfo | tr -s ' ' | cut -d' ' -f 2")
reserved = sudo("grep HugePages_Total /proc/meminfo | tr -s ' ' | cut -d' ' -f 2")
if (reserved == ""):
reserved = "0"
requested = ((int(memsize) * factor) / 100) / int(pagesize)
if (requested > int(reserved)):
pattern = "^vm.nr_hugepages ="
line = "vm.nr_hugepages = %d" %requested
insert_line_to_file(pattern = pattern, line = line,
file_name = '/etc/sysctl.conf')
current_max_map_count = sudo("sysctl -n vm.max_map_count")
if current_max_map_count == "":
current_max_map_count = 0
current_huge_pages = max(int(requested), int(reserved))
requested_max_map_count = DPDK_HUGEPAGES_INIT_TIMES * int(current_huge_pages)
if int(requested_max_map_count) > int(current_max_map_count):
pattern = "^vm.max_map_count ="
line = "vm.max_map_count = %d" %requested_max_map_count
insert_line_to_file(pattern = pattern, line = line,
file_name = '/etc/sysctl.conf')
mounted = sudo("mount | grep hugetlbfs | cut -d' ' -f 3")
if (mounted != ""):
print "hugepages already mounted on %s" %mounted
else:
sudo("mkdir -p /hugepages")
pattern = "^hugetlbfs"
line = "hugetlbfs /hugepages hugetlbfs defaults 0 0"
insert_line_to_file(pattern = pattern, line = line,
file_name = '/etc/fstab')
sudo("mount -t hugetlbfs hugetlbfs /hugepages")
@roles('compute')
@task
def setup_hugepages():