/
remote_util.py
3148 lines (2893 loc) · 153 KB
/
remote_util.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 os
import sys
import urllib
import uuid
import time
import logging
import unittest
from datetime import datetime
import logger
from subprocess import Popen, PIPE
from builds.build_query import BuildQuery
import testconstants
from testconstants import WIN_REGISTER_ID
from testconstants import MEMBASE_VERSIONS
from testconstants import COUCHBASE_VERSIONS
from testconstants import MISSING_UBUNTU_LIB
from testconstants import MV_LATESTBUILD_REPO
from testconstants import SHERLOCK_BUILD_REPO
from testconstants import COUCHBASE_VERSIONS
from testconstants import WIN_CB_VERSION_3
from testconstants import COUCHBASE_VERSION_2
from testconstants import COUCHBASE_VERSION_3
from testconstants import COUCHBASE_RELEASE_VERSIONS_3
from testconstants import SHERLOCK_VERSION
from testconstants import RPM_DIS_NAME
from testconstants import LINUX_DISTRIBUTION_NAME
from testconstants import WIN_COUCHBASE_BIN_PATH
from testconstants import WIN_COUCHBASE_BIN_PATH_RAW
from membase.api.rest_client import RestConnection, RestHelper
log = logger.Logger.get_logger()
logging.getLogger("paramiko").setLevel(logging.WARNING)
try:
import paramiko
except ImportError:
log.warn("{0} {1} {2}".format("Warning: proceeding without importing",
"paramiko due to import error.",
"ssh connections to remote machines will fail!\n"))
class RemoteMachineInfo(object):
def __init__(self):
self.type = ''
self.ip = ''
self.distribution_type = ''
self.architecture_type = ''
self.distribution_version = ''
self.deliverable_type = ''
self.ram = ''
self.cpu = ''
self.disk = ''
self.hostname = ''
class RemoteMachineProcess(object):
def __init__(self):
self.pid = ''
self.name = ''
class RemoteMachineHelper(object):
remote_shell = None
def __init__(self, remote_shell):
self.remote_shell = remote_shell
def monitor_process(self, process_name,
duration_in_seconds=120):
# monitor this process and return if it crashes
end_time = time.time() + float(duration_in_seconds)
last_reported_pid = None
while time.time() < end_time:
# get the process list
process = self.is_process_running(process_name)
if process:
if not last_reported_pid:
last_reported_pid = process.pid
elif not last_reported_pid == process.pid:
message = 'process {0} was restarted. old pid : {1} new pid : {2}'
log.info(message.format(process_name, last_reported_pid, process.pid))
return False
# check if its equal
else:
# we should have an option to wait for the process
# to start during the timeout
# process might have crashed
log.info("{0}:process {1} is not running or it might have crashed!".format(self.remote_shell.ip, process_name))
return False
time.sleep(1)
# log.info('process {0} is running'.format(process_name))
return True
def is_process_running(self, process_name):
if getattr(self.remote_shell, "info", None) is None:
self.remote_shell.info = self.remote_shell.extract_remote_info()
if self.remote_shell.info.type.lower() == 'windows':
output, error = self.remote_shell.execute_command('tasklist| grep {0}'.format(process_name), debug=False)
if error or output == [""] or output == []:
return None
words = output[0].split(" ")
words = filter(lambda x: x != "", words)
process = RemoteMachineProcess()
process.pid = words[1]
process.name = words[0]
log.info("process is running on {0}: {1}".format(self.remote_shell.ip, words))
return process
else:
processes = self.remote_shell.get_running_processes()
for process in processes:
if process.name == process_name:
return process
return None
class RemoteMachineShellConnection:
_ssh_client = None
def __init__(self, username='root',
pkey_location='',
ip=''):
self.username = username
self.use_sudo = True
if self.username == 'root':
self.use_sudo = False
# let's create a connection
self._ssh_client = paramiko.SSHClient()
self.ip = ip
self.remote = (self.ip != "localhost" and self.ip != "127.0.0.1")
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
log.info('connecting to {0} with username : {1} pem key : {2}'.format(ip, username, pkey_location))
try:
if self.remote:
self._ssh_client.connect(hostname=ip, username=username, key_filename=pkey_location)
except paramiko.AuthenticationException:
log.info("Authentication failed for {0}".format(self.ip))
exit(1)
except paramiko.BadHostKeyException:
log.info("Invalid Host key for {0}".format(self.ip))
exit(1)
except Exception:
log.info("Can't establish SSH session with {0}".format(self.ip))
exit(1)
def __init__(self, serverInfo):
# let's create a connection
self.username = serverInfo.ssh_username
self.use_sudo = True
if self.username == 'root':
self.use_sudo = False
self._ssh_client = paramiko.SSHClient()
self.ip = serverInfo.ip
self.remote = (self.ip != "localhost" and self.ip != "127.0.0.1")
self.port = serverInfo.port
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
msg = 'connecting to {0} with username : {1} password : {2} ssh_key: {3}'
log.info(msg.format(serverInfo.ip, serverInfo.ssh_username, serverInfo.ssh_password, serverInfo.ssh_key))
# added attempts for connection because of PID check failed. RNG must be re-initialized after fork() error
# That's a paramiko bug
max_attempts_connect = 2
attempt = 0
while True:
try:
if self.remote and serverInfo.ssh_key == '':
self._ssh_client.connect(hostname=serverInfo.ip,
username=serverInfo.ssh_username,
password=serverInfo.ssh_password)
elif self.remote:
self._ssh_client.connect(hostname=serverInfo.ip,
username=serverInfo.ssh_username,
key_filename=serverInfo.ssh_key)
break
except paramiko.AuthenticationException:
log.error("Authentication failed")
exit(1)
except paramiko.BadHostKeyException:
log.error("Invalid Host key")
exit(1)
except Exception as e:
if str(e).find('PID check failed. RNG must be re-initialized') != -1 and\
attempt != max_attempts_connect:
log.error("Can't establish SSH session to node {1} :\
{0}. Will try again in 1 sec".format(e, self.ip))
attempt += 1
time.sleep(1)
else:
log.error("Can't establish SSH session to node {1} :\
{0}".format(e, self.ip))
exit(1)
log.info("Connected to {0}".format(serverInfo.ip))
def sleep(self, timeout=1, message=""):
log.info("{0}:sleep for {1} secs. {2} ...".format(self.ip, timeout, message))
time.sleep(timeout)
def get_running_processes(self):
# if its linux ,then parse each line
# 26989 ? 00:00:51 pdflush
# ps -Ao pid,comm
processes = []
output, error = self.execute_command('ps -Ao pid,comm', debug=False)
if output:
for line in output:
# split to words
words = line.strip().split(' ')
if len(words) >= 2:
process = RemoteMachineProcess()
process.pid = words[0]
process.name = words[1]
processes.append(process)
return processes
def get_mem_usage_by_process(self, process_name):
"""Now only linux"""
output, error = self.execute_command('ps -e -o %mem,cmd|grep {0}'.format(process_name),
debug=False)
if output:
for line in output:
if not 'grep' in line.strip().split(' '):
return float(line.strip().split(' ')[0])
def stop_membase(self):
self.extract_remote_info()
if self.info.type.lower() == 'windows':
log.info("STOP SERVER")
o, r = self.execute_command("net stop membaseserver")
self.log_command_output(o, r)
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
self.sleep(10, "Wait to stop service completely")
if self.info.type.lower() == "linux":
o, r = self.execute_command("/etc/init.d/membase-server stop")
self.log_command_output(o, r)
def start_membase(self):
self.extract_remote_info()
if self.info.type.lower() == 'windows':
o, r = self.execute_command("net start membaseserver")
self.log_command_output(o, r)
if self.info.type.lower() == "linux":
o, r = self.execute_command("/etc/init.d/membase-server start")
self.log_command_output(o, r)
def start_server(self, os="unix"):
if os == "windows":
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
elif os == "unix" or os == "linux":
if self.is_couchbase_installed():
o, r = self.execute_command("/etc/init.d/couchbase-server start")
else:
o, r = self.execute_command("/etc/init.d/membase-server start")
self.log_command_output(o, r)
elif os == "mac":
o, r = self.execute_command("open /Applications/Couchbase\ Server.app")
self.log_command_output(o, r)
else:
self.log.error("don't know operating system or product version")
def stop_server(self, os="unix"):
if os == "windows":
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
elif os == "unix" or os == "linux":
if self.is_couchbase_installed():
o, r = self.execute_command("/etc/init.d/couchbase-server stop", use_channel=True)
else:
o, r = self.execute_command("/etc/init.d/membase-server stop")
self.log_command_output(o, r)
elif os == "mac":
o, r = self.execute_command("ps aux | grep Couchbase | awk '{print $2}' | xargs kill -9")
self.log_command_output(o, r)
o, r = self.execute_command("killall -9 epmd")
self.log_command_output(o, r)
else:
self.log.error("don't know operating system or product version")
def stop_schedule_tasks(self):
log.info("STOP ALL SCHEDULE TASKS: installme, removeme and upgrademe")
output, error = self.execute_command("cmd /c schtasks /end /tn installme")
self.log_command_output(output, error)
output, error = self.execute_command("cmd /c schtasks /end /tn removeme")
self.log_command_output(output, error)
output, error = self.execute_command("cmd /c schtasks /end /tn upgrademe")
self.log_command_output(output, error)
def kill_erlang(self, os="unix"):
if os == "windows":
o, r = self.execute_command("taskkill /F /T /IM epmd.exe*")
self.log_command_output(o, r)
o, r = self.execute_command("taskkill /F /T /IM erl.exe*")
self.log_command_output(o, r)
else:
o, r = self.execute_command("killall -9 beam.smp")
self.log_command_output(o, r)
return o, r
def kill_memcached(self):
self.extract_remote_info()
if self.info.type.lower() == 'windows':
o, r = self.execute_command("taskkill /F /T /IM memcached*")
self.log_command_output(o, r)
else:
o, r = self.execute_command("killall -9 memcached")
self.log_command_output(o, r)
return o, r
def kill_goxdcr(self):
self.extract_remote_info()
if self.info.type.lower() == 'windows':
o, r = self.execute_command("taskkill /F /T /IM goxdcr*")
self.log_command_output(o, r)
else:
o, r = self.execute_command("killall -9 goxdcr")
self.log_command_output(o, r)
return o, r
def change_log_level(self, new_log_level):
log.info("CHANGE LOG LEVEL TO %s".format(new_log_level))
# ADD NON_ROOT user config_details
output, error = self.execute_command("sed -i '/loglevel_default, /c \\{loglevel_default, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_ns_server, /c \\{loglevel_ns_server, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_stats, /c \\{loglevel_stats, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_rebalance, /c \\{loglevel_rebalance, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_cluster, /c \\{loglevel_cluster, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_views, /c \\{loglevel_views, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_error_logger, /c \\{loglevel_error_logger, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_mapreduce_errors, /c \\{loglevel_mapreduce_errors, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_user, /c \\{loglevel_user, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_xdcr, /c \\{loglevel_xdcr, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/loglevel_menelaus, /c \\{loglevel_menelaus, %s\}'. %s"
% (new_log_level, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
def configure_log_location(self, new_log_location):
mv_logs = testconstants.LINUX_LOG_PATH + '/' + new_log_location
print " MV LOGS %s" % mv_logs
error_log_tag = "error_logger_mf_dir"
# ADD NON_ROOT user config_details
log.info("CHANGE LOG LOCATION TO %s".format(mv_logs))
output, error = self.execute_command("rm -rf %s" % mv_logs)
self.log_command_output(output, error)
output, error = self.execute_command("mkdir %s" % mv_logs)
self.log_command_output(output, error)
output, error = self.execute_command("chown -R couchbase %s" % mv_logs)
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/%s, /c \\{%s, \"%s\"\}.' %s"
% (error_log_tag, error_log_tag, mv_logs, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
def change_stat_periodicity(self, ticks):
# ADD NON_ROOT user config_details
log.info("CHANGE STAT PERIODICITY TO every %s seconds" % ticks)
output, error = self.execute_command("sed -i '$ a\{grab_stats_every_n_ticks, %s}.' %s"
% (ticks, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
def change_port_static(self, new_port):
# ADD NON_ROOT user config_details
log.info("=========CHANGE PORTS for REST: %s, MCCOUCH: %s,MEMCACHED: %s, MOXI: %s, CAPI: %s==============="
% (new_port, new_port + 1, new_port + 2, new_port + 3, new_port + 4))
output, error = self.execute_command("sed -i '/{rest_port/d' %s" % testconstants.LINUX_STATIC_CONFIG)
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '$ a\{rest_port, %s}.' %s"
% (new_port, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/{mccouch_port/d' %s" % testconstants.LINUX_STATIC_CONFIG)
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '$ a\{mccouch_port, %s}.' %s"
% (new_port + 1, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/{memcached_port/d' %s" % testconstants.LINUX_STATIC_CONFIG)
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '$ a\{memcached_port, %s}.' %s"
% (new_port + 2, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/{moxi_port/d' %s" % testconstants.LINUX_STATIC_CONFIG)
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '$ a\{moxi_port, %s}.' %s"
% (new_port + 3, testconstants.LINUX_STATIC_CONFIG))
self.log_command_output(output, error)
output, error = self.execute_command("sed -i '/port = /c\port = %s' %s"
% (new_port + 4, testconstants.LINUX_CAPI_INI))
self.log_command_output(output, error)
output, error = self.execute_command("rm %s" % testconstants.LINUX_CONFIG_FILE)
self.log_command_output(output, error)
output, error = self.execute_command("cat %s" % testconstants.LINUX_STATIC_CONFIG)
self.log_command_output(output, error)
def is_couchbase_installed(self):
self.extract_remote_info()
if self.info.type.lower() == 'windows':
if self.file_exists(testconstants.WIN_CB_PATH, testconstants.VERSION_FILE):
# print running process on windows
RemoteMachineHelper(self).is_process_running('memcached')
RemoteMachineHelper(self).is_process_running('erl')
return True
elif self.info.distribution_type.lower() == 'mac':
output, error = self.execute_command('ls %s%s' % (testconstants.MAC_CB_PATH, testconstants.VERSION_FILE))
self.log_command_output(output, error)
for line in output:
if line.find('No such file or directory') == -1:
return True
elif self.info.type.lower() == "linux":
if self.file_exists(testconstants.LINUX_CB_PATH, testconstants.VERSION_FILE):
return True
return False
def is_moxi_installed(self):
self.extract_remote_info()
if self.info.type.lower() == 'windows':
self.log.error('Not implemented')
elif self.info.distribution_type.lower() == 'mac':
self.log.error('Not implemented')
elif self.info.type.lower() == "linux":
if self.file_exists(testconstants.LINUX_MOXI_PATH, 'moxi'):
return True
return False
# /opt/moxi/bin/moxi -Z port_listen=11211 -u root -t 4 -O /var/log/moxi/moxi.log
def start_moxi(self, ip, bucket, port, user=None, threads=4, log_file="/var/log/moxi.log"):
if self.is_couchbase_installed():
prod = "couchbase"
else:
prod = "membase"
cli_path = "/opt/" + prod + "/bin/moxi"
args = ""
args += "http://{0}:8091/pools/default/bucketsStreaming/{1} ".format(ip, bucket)
args += "-Z port_listen={0} -u {1} -t {2} -O {3} -d".format(port,
user or prod,
threads, log_file)
self.extract_remote_info()
if self.info.type.lower() == "linux":
o, r = self.execute_command("{0} {1}".format(cli_path, args))
self.log_command_output(o, r)
else:
raise Exception("running standalone moxi is not supported for windows")
def stop_moxi(self):
self.extract_remote_info()
if self.info.type.lower() == "linux":
o, r = self.execute_command("killall -9 moxi")
self.log_command_output(o, r)
else:
raise Exception("stopping standalone moxi is not supported on windows")
def is_url_live(self, url):
live_url = False
log.info("Check if url {0} is ok".format(url))
status = urllib.urlopen(url).getcode()
if status == 200:
log.info("This url {0} is live".format(url))
live_url = True
else:
log.error("This url {0} is failed to connect".format(url))
return live_url
def download_build(self, build):
return self.download_binary(build.url, build.deliverable_type, build.name, latest_url=build.url_latest_build)
def disable_firewall(self):
self.extract_remote_info()
if self.info.type.lower() == "windows":
output, error = self.execute_command('netsh advfirewall set publicprofile state off')
self.log_command_output(output, error)
output, error = self.execute_command('netsh advfirewall set privateprofile state off')
self.log_command_output(output, error)
# for details see RemoteUtilHelper.enable_firewall for windows
output, error = self.execute_command('netsh advfirewall firewall delete rule name="block erl.exe in"')
self.log_command_output(output, error)
output, error = self.execute_command('netsh advfirewall firewall delete rule name="block erl.exe out"')
self.log_command_output(output, error)
else:
output, error = self.execute_command('/sbin/iptables -F')
self.log_command_output(output, error)
output, error = self.execute_command('/sbin/iptables -t nat -F')
self.log_command_output(output, error)
def download_binary(self, url, deliverable_type, filename, latest_url=None, skip_md5_check=True):
self.extract_remote_info()
self.disable_firewall()
if self.info.type.lower() == 'windows':
self.execute_command('taskkill /F /T /IM msiexec32.exe')
self.execute_command('taskkill /F /T /IM msiexec.exe')
self.execute_command('taskkill /F /T IM setup.exe')
self.execute_command('taskkill /F /T /IM ISBEW64.*')
self.execute_command('taskkill /F /T /IM firefox.*')
self.execute_command('taskkill /F /T /IM iexplore.*')
self.execute_command('taskkill /F /T /IM WerFault.*')
self.execute_command('taskkill /F /T /IM memcached.exe')
self.execute_command('taskkill /F /T /IM bash.exe')
self.disable_firewall()
remove_words = ["-rel", ".exe"]
for word in remove_words:
filename = filename.replace(word, "")
"""couchbase-server-enterprise_3.5.0-968-windows_amd64
couchbase-server-enterprise_4.0.0-1655-windows_amd64
sherlock changed from 3.5. to 4.0 """
if "4.0." in filename:
tmp = filename.split("_")
version = tmp[1].replace("-windows", "")
else:
tmp = filename.split("-")
tmp.reverse()
version = tmp[1] + "-" + tmp[0]
exist = self.file_exists('/cygdrive/c/tmp/', '{0}.exe'.format(version))
if not exist:
output, error = self.execute_command(
"cd /cygdrive/c/tmp;cmd /c 'c:\\automation\\wget.exe --no-check-certificate -q"
" {0} -O {1}.exe';ls -lh;".format(url, version))
self.log_command_output(output, error)
return self.file_exists('/cygdrive/c/tmp/', '{0}.exe'.format(version))
else:
log.info('File {0}.exe exist in tmp directory'.format(version))
return True
# output, error = self.execute_command("rm -rf /cygdrive/c/automation/setup.exe")
# self.log_command_output(output, error)
# output, error = self.execute_command(
# "cd /cygdrive/c/tmp;cmd /c 'c:\\automation\\wget.exe --no-check-certificate -q {0} -O setup.exe';ls -lh;".format(url))
# self.log_command_output(output, error)
#return self.file_exists('/cygdrive/c/tmp/', 'setup.exe')
elif self.info.distribution_type.lower() == 'mac':
output, error = self.execute_command('cd ~/Downloads ; rm -rf couchbase-server* ; rm -rf Couchbase\ Server.app ; curl -O {0}'.format(url))
self.log_command_output(output, error)
output, error = self.execute_command('ls -lh ~/Downloads/%s' % filename)
self.log_command_output(output, error)
for line in output:
if line.find('No such file or directory') == -1:
return True
return False
else:
# try to push this build into
# depending on the os
# build.product has the full name
# first remove the previous file if it exist ?
# fix this :
output, error = self.execute_command_raw('cd /tmp ; D=$(mktemp -d cb_XXXX) ; mv {0} $D ; mv core.* $D ; rm -f * ; mv $D/* . ; rmdir $D'.format(filename))
self.log_command_output(output, error)
if skip_md5_check:
output, error = self.execute_command_raw('cd /tmp;wget -q -O {0} {1};cd /tmp;ls -lh'.format(filename, url))
self.log_command_output(output, error)
else:
log.info('get md5 sum for local and remote')
output, error = self.execute_command_raw('cd /tmp ; rm -f *.md5 *.md5l ; wget -q -O {1}.md5 {0}.md5 ; md5sum {1} > {1}.md5l'.format(url, filename))
self.log_command_output(output, error)
if str(error).find('No such file or directory') != -1 and latest_url != '':
url = latest_url
output, error = self.execute_command_raw('cd /tmp ; rm -f *.md5 *.md5l ; wget -q -O {1}.md5 {0}.md5 ; md5sum {1} > {1}.md5l'.format(url, filename))
log.info('comparing md5 sum and downloading if needed')
output, error = self.execute_command_raw('cd /tmp;diff {0}.md5 {0}.md5l || wget -q -O {0} {1};rm -f *.md5 *.md5l'.format(filename, url))
self.log_command_output(output, error)
# check if the file exists there now ?
return self.file_exists('/tmp', filename)
# for linux environment we can just
# figure out what version , check if /tmp/ has the
# binary and then return True if binary is installed
def get_file(self, remotepath, filename, todir):
if self.file_exists(remotepath, filename):
if self.remote:
sftp = self._ssh_client.open_sftp()
try:
filenames = sftp.listdir(remotepath)
for name in filenames:
if name == filename:
sftp.get('{0}/{1}'.format(remotepath, filename), todir)
sftp.close()
return True
sftp.close()
return False
except IOError:
return False
else:
os.system("cp {0} {1}".format('{0}/{1}'.format(remotepath, filename), todir))
def read_remote_file(self, remote_path, filename):
if self.file_exists(remote_path, filename):
if self.remote:
sftp = self._ssh_client.open_sftp()
remote_file = sftp.open('{0}/{1}'.format(remote_path, filename))
try:
out = remote_file.readlines()
finally:
remote_file.close()
return out
else:
txt = open('{0}/{1}'.format(remote_path, filename))
return txt.read()
return None
def write_remote_file(self, remote_path, filename, lines):
cmd = 'echo "%s" > %s/%s' % (''.join(lines), remote_path, filename)
self.execute_command(cmd)
def remove_directory(self, remote_path):
if self.remote:
sftp = self._ssh_client.open_sftp()
try:
log.info("removing {0} directory...".format(remote_path))
sftp.rmdir(remote_path)
except IOError:
return False
finally:
sftp.close()
else:
try:
p = Popen("rm -rf {0}".format(remote_path) , shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderro = p.communicate()
except IOError:
return False
return True
def list_files(self, remote_path):
if self.remote:
sftp = self._ssh_client.open_sftp()
files = []
try:
file_names = sftp.listdir(remote_path)
for name in file_names:
files.append({'path': remote_path, 'file': name})
sftp.close()
except IOError:
return []
return files
else:
p = Popen("ls {0}".format(remote_path) , shell=True, stdout=PIPE, stderr=PIPE)
files, stderro = p.communicate()
return files
# check if this file exists in the remote
# machine or not
def file_starts_with(self, remotepath, pattern):
sftp = self._ssh_client.open_sftp()
files_matched = []
try:
file_names = sftp.listdir(remotepath)
for name in file_names:
if name.startswith(pattern):
files_matched.append("{0}/{1}".format(remotepath, name))
except IOError:
# ignore this error
pass
sftp.close()
if len(files_matched) > 0:
log.info("found these files : {0}".format(files_matched))
return files_matched
def file_exists(self, remotepath, filename):
sftp = self._ssh_client.open_sftp()
try:
filenames = sftp.listdir_attr(remotepath)
for name in filenames:
if name.filename == filename and int(name.st_size) > 0:
sftp.close()
return True
elif name.filename == filename and int(name.st_size) == 0:
log.info("File {0} will be deleted".format(filename))
sftp.remove(remotepath + filename)
sftp.close()
return False
except IOError:
return False
def download_binary_in_win(self, url, version):
self.execute_command('taskkill /F /T /IM msiexec32.exe')
self.execute_command('taskkill /F /T /IM msiexec.exe')
self.execute_command('taskkill /F /T IM setup.exe')
self.execute_command('taskkill /F /T /IM ISBEW64.*')
self.execute_command('taskkill /F /T /IM iexplore.*')
self.execute_command('taskkill /F /T /IM WerFault.*')
self.execute_command('taskkill /F /T /IM Firefox.*')
self.execute_command('taskkill /F /T /IM bash.exe')
self.disable_firewall()
version = version.replace("-rel", "")
exist = self.file_exists('/cygdrive/c/tmp/', '{0}.exe'.format(version))
if not exist:
output, error = self.execute_command(
"cd /cygdrive/c/tmp;cmd /c 'c:\\automation\\wget.exe --no-check-certificate -q"
" {0} -O {1}.exe';ls -lh;".format(url, version))
self.log_command_output(output, error)
else:
log.info('File {0}.exe exist in tmp directory'.format(version))
return self.file_exists('/cygdrive/c/tmp/', '{0}.exe'.format(version))
def copy_file_local_to_remote(self, src_path, des_path):
sftp = self._ssh_client.open_sftp()
try:
sftp.put(src_path, des_path)
except IOError:
log.error('Can not copy file')
finally:
sftp.close()
def copy_file_remote_to_local(self, rem_path, des_path):
sftp = self._ssh_client.open_sftp()
try:
sftp.get(rem_path, des_path)
except IOError:
log.error('Can not copy file')
finally:
sftp.close()
# copy multi files from local to remote server
def copy_files_local_to_remote(self, src_path, des_path):
files = os.listdir(src_path)
log.info("copy files from {0} to {1}".format(src_path, des_path))
# self.execute_batch_command("cp -r {0}/* {1}".format(src_path, des_path))
for file in files:
if file.find("wget") != 1:
a = ""
full_src_path = os.path.join(src_path, file)
full_des_path = os.path.join(des_path, file)
self.copy_file_local_to_remote(full_src_path, full_des_path)
# create a remote file from input string
def create_file(self, remote_path, file_data):
output, error = self.execute_command("echo '{0}' > {1}".format(file_data, remote_path))
def find_file(self, remote_path, file):
sftp = self._ssh_client.open_sftp()
try:
files = sftp.listdir(remote_path)
for name in files:
if name == file:
found_it = os.path.join(remote_path, name)
log.info("File {0} was found".format(found_it))
return found_it
else:
log.error('File(s) name in {0}'.format(remote_path))
for name in files:
log.info(name)
log.error('Can not find {0}'.format(file))
except IOError:
pass
sftp.close()
def find_build_version(self, path_to_version, version_file, product):
sftp = self._ssh_client.open_sftp()
ex_type = "exe"
version_file = testconstants.VERSION_FILE
if self.file_exists(testconstants.WIN_CB_PATH, testconstants.VERSION_FILE):
path_to_version = testconstants.WIN_CB_PATH
else:
path_to_version = testconstants.WIN_MB_PATH
try:
log.info(path_to_version)
f = sftp.open(os.path.join(path_to_version, version_file), 'r+')
tmp_str = f.read().strip()
full_version = tmp_str.replace("-rel", "")
if full_version == "1.6.5.4-win64":
full_version = "1.6.5.4"
build_name = short_version = full_version
return build_name, short_version, full_version
except IOError:
log.error('Can not read version file')
sftp.close()
def find_windows_info(self):
if self.remote:
found = self.find_file("/cygdrive/c/tmp", "windows_info.txt")
if isinstance(found, basestring):
if self.remote:
sftp = self._ssh_client.open_sftp()
try:
f = sftp.open(found)
log.info("get windows information")
info = {}
for line in f:
(key, value) = line.split('=')
key = key.strip(' \t\n\r')
value = value.strip(' \t\n\r')
info[key] = value
return info
except IOError:
log.error("can not find windows info file")
sftp.close()
else:
return self.create_windows_info()
else:
try:
txt = open("{0}/{1}".format("/cygdrive/c/tmp", "windows_info.txt"))
log.info("get windows information")
info = {}
for line in txt.read():
(key, value) = line.split('=')
key = key.strip(' \t\n\r')
value = value.strip(' \t\n\r')
info[key] = value
return info
except IOError:
log.error("can not find windows info file")
def create_windows_info(self):
systeminfo = self.get_windows_system_info()
info = {}
if "OS Name" in systeminfo:
info["os"] = systeminfo["OS Name"].find("indows") and "windows" or "NONE"
info["os_name"] = systeminfo["OS Name"].find("2008 R2") and "2k8" or "NONE"
if "System Type" in systeminfo:
info["os_arch"] = systeminfo["System Type"].find("64") and "x86_64" or "NONE"
info.update(systeminfo)
self.execute_batch_command("rm -rf /cygdrive/c/tmp/windows_info.txt")
self.execute_batch_command("touch /cygdrive/c/tmp/windows_info.txt")
sftp = self._ssh_client.open_sftp()
try:
f = sftp.open('/cygdrive/c/tmp/windows_info.txt', 'w')
content = ''
for key in sorted(info.keys()):
content += '{0} = {1}\n'.format(key, info[key])
f.write(content)
log.info("/cygdrive/c/tmp/windows_info.txt was created with content: {0}".format(content))
except IOError:
log.error('Can not write windows_info.txt file')
finally:
sftp.close()
return info
# Need to add new windows register ID in testconstant file when
# new couchbase server version comes out.
def create_windows_capture_file(self, task, product, version):
src_path = "resources/windows/automation"
des_path = "/cygdrive/c/automation"
# remove dot in version (like 2.0.0 ==> 200)
reg_version = version[0:5:2]
reg_id = WIN_REGISTER_ID[reg_version]
uuid_name = uuid.uuid4()
if task == "install":
template_file = "cb-install.wct"
file = "{0}_{1}_install.iss".format(uuid_name, self.ip)
#file = "{0}_install.iss".format(self.ip)
elif task == "uninstall":
template_file = "cb-uninstall.wct"
file = "{0}_{1}_uninstall.iss".format(uuid_name, self.ip)
#file = "{0}_uninstall.iss".format(self.ip)
# create in/uninstall file from windows capture template (wct) file
full_src_path_template = os.path.join(src_path, template_file)
full_src_path = os.path.join(src_path, file)
full_des_path = os.path.join(des_path, file)
f1 = open(full_src_path_template, 'r')
f2 = open(full_src_path, 'w')
""" replace ####### with reg ID to install/uninstall """
if "2.2.0-837" in version:
reg_id = "2B630EB8-BBC7-6FE4-C9B8-D8843EB1EFFA"
log.info("register ID: {0}".format(reg_id))
for line in f1:
line = line.replace("#######", reg_id)
if product == "mb" and task == "install":
line = line.replace("Couchbase", "Membase")
f2.write(line)
f1.close()
f2.close()
self.copy_file_local_to_remote(full_src_path, full_des_path)
""" remove capture file from source after copy to destination """
self.sleep(4, "wait for remote copy completed")
""" need to implement to remove only at the end
of installation """
#os.remove(full_src_path)
return uuid_name
def get_windows_system_info(self):
try:
info = {}
o, _ = self.execute_batch_command('systeminfo')
for line in o:
line_list = line.split(':')
if len(line_list) > 2:
if line_list[0] == 'Virtual Memory':
key = "".join(line_list[0:2])
value = " ".join(line_list[2:])
else:
key = line_list[0]
value = " ".join(line_list[1:])
elif len(line_list) == 2:
(key, value) = line_list
else:
continue
key = key.strip(' \t\n\r')
if key.find("[") != -1:
info[key_prev] += '|' + key + value.strip(' |')
else:
value = value.strip(' |')
info[key] = value
key_prev = key
return info
except Exception as ex:
log.error("error {0} appeared during getting windows info".format(ex))
# this function used to modify bat file to run task schedule in windows
def modify_bat_file(self, remote_path, file_name, name, version, task):
found = self.find_file(remote_path, file_name)
sftp = self._ssh_client.open_sftp()
product_version = ""
if version[:5] in MEMBASE_VERSIONS:
product_version = version[:5]
name = "mb"
elif version[:5] in COUCHBASE_VERSIONS:
product_version = version[:5]
name = "cb"
else:
log.error('Windows automation does not support {0} version yet'.format(version))
sys.exit()
if "upgrade" not in task:
uuid_name = self.create_windows_capture_file(task, name, version)
try:
f = sftp.open(found, 'w')
name = name.strip()
version = version.strip()
if task == "upgrade":
content = 'c:\\tmp\{3}.exe /s -f1c:\\automation\{0}_{1}_{2}.iss'.format(name,
product_version, task, version)
else:
content = 'c:\\tmp\{0}.exe /s -f1c:\\automation\{3}_{2}_{1}.iss' \
.format(version, task, self.ip, uuid_name)
log.info("create {0} task with content:{1}".format(task, content))
f.write(content)
log.info('Successful write to {0}'.format(found))
except IOError:
log.error('Can not write build name file to bat file {0}'.format(found))
sftp.close()
def set_vbuckets_win(self, vbuckets):
bin_path = WIN_COUCHBASE_BIN_PATH
bin_path = bin_path.replace("\\", "")
src_file = bin_path + "service_register.bat"
des_file = "/tmp/service_register.bat_{0}".format(self.ip)
local_file = "/tmp/service_register.bat.tmp_{0}".format(self.ip)
self.copy_file_remote_to_local(src_file, des_file)
f1 = open(des_file, "r")
f2 = open(local_file, "w")
""" when install new cb server on windows, there is not
env COUCHBASE_NUM_VBUCKETS yet. We need to insert this
env to service_register.bat right after ERL_FULLSWEEP_AFTER 512
like -env ERL_FULLSWEEP_AFTER 512 -env COUCHBASE_NUM_VBUCKETS vbuckets
where vbucket is params passed to function when run install scripts """
for line in f1:
if "-env COUCHBASE_NUM_VBUCKETS " in line:
tmp1 = line.split("COUCHBASE_NUM_VBUCKETS")
tmp2 = tmp1[1].strip().split(" ")
log.info("set vbuckets of node {0} to {1}" \
.format(self.ip, vbuckets))
tmp2[0] = vbuckets
tmp1[1] = " ".join(tmp2)
line = "COUCHBASE_NUM_VBUCKETS ".join(tmp1)
elif "-env ERL_FULLSWEEP_AFTER 512" in line:
log.info("set vbuckets of node {0} to {1}" \
.format(self.ip, vbuckets))
line = line.replace("-env ERL_FULLSWEEP_AFTER 512", \
"-env ERL_FULLSWEEP_AFTER 512 -env COUCHBASE_NUM_VBUCKETS {0}" \
.format(vbuckets))
f2.write(line)
f1.close()
f2.close()
self.copy_file_local_to_remote(local_file, src_file)
""" re-register new setup to cb server """
self.execute_command(WIN_COUCHBASE_BIN_PATH + "service_stop.bat")
self.execute_command(WIN_COUCHBASE_BIN_PATH + "service_unregister.bat")
self.execute_command(WIN_COUCHBASE_BIN_PATH + "service_register.bat")
self.execute_command(WIN_COUCHBASE_BIN_PATH + "service_start.bat")
self.sleep(10, "wait for cb server start completely after reset vbuckets!")