instruction
stringclasses 14
values | output
stringlengths 105
12.9k
| input
stringlengths 0
4.12k
|
|---|---|---|
generate code for the following
|
def start_server(self):
"""
Starts the Couchbase server on the remote server.
The method runs the sever from non-default location if it's run as nonroot user. Else from default location.
:return: None
"""
o, r = self.execute_command("open /Applications/Couchbase\ Server.app")
self.log_command_output(o, r)
|
Starts the Couchbase server on the remote server.
The method runs the sever from non-default location if it's run as nonroot user. Else from default location.
|
def get_process_id(self, process_name):
"""
Get the process id for the given process
Override method for Windows
:param process_name: name of the process to get pid for
:return: pid of the process
"""
raise NotImplementedError
|
def get_process_id(self, process_name):
raise NotImplementedError
|
|
generate comment:
|
def stop_current_python_running(self, mesg):
"""
Stop the current python process that's running this script.
:param mesg: message to display before killing the process
:return: None
"""
os.system("ps aux | grep python | grep %d " % os.getpid())
log.info(mesg)
self.sleep(5, "==== delay kill pid %d in 5 seconds to printout message ==="\
% os.getpid())
os.system('kill %d' % os.getpid())
|
def stop_current_python_running(self, mesg):
os.system("ps aux | grep python | grep %d " % os.getpid())
log.info(mesg)
self.sleep(5, "==== delay kill pid %d in 5 seconds to printout message ==="\
% os.getpid())
os.system('kill %d' % os.getpid())
|
generate python code for
|
def pause_beam(self):
"""
Pauses the beam.smp process on remote server
Override method for Windows
:return: None
"""
raise NotImplementedError
|
Pauses the beam.smp process on remote server
Override method for Windows
|
generate code for the following
|
def restart_couchbase(self):
"""
Restarts the Couchbase server on the remote server
:return: None
"""
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
|
Restarts the Couchbase server on the remote server
|
give python code to
|
def get_cbversion(self):
"""
Get the installed version of Couchbase Server installed on the remote server.
This gets the versions from both default path or non-default paths.
Returns in format fv = a.b.c-xxxx, sv = a.b.c, bn = xxxx
:return: full version, main version and the build version of the Couchbase Server installed
"""
fv = sv = bn = ""
if self.file_exists(self.cb_path, self.version_file):
output = self.read_remote_file(self.cb_path, self.version_file)
if output:
for x in output:
x = x.strip()
if x and x[:5] in self.cb_release_builds.keys() \
and "-" in x:
fv = x
tmp = x.split("-")
sv = tmp[0]
bn = tmp[1]
break
else:
self.log.info("%s - Couchbase Server not found" % self.ip)
return fv, sv, bn
|
Get the installed version of Couchbase Server installed on the remote server.
This gets the versions from both default path or non-default paths.
Returns in format fv = a.b.c-xxxx, sv = a.b.c, bn = xxxx
|
generate python code for the following
|
def cleanup_data_config(self, data_path):
"""
Cleans up the data config directory and its contents
Override method for Windows
:param data_path: path to data config directory
:return: None
"""
if "c:/Program Files" in data_path:
data_path = data_path.replace("c:/Program Files",
"/cygdrive/c/Program\ Files")
o, r = self.execute_command("rm -rf ""{0}""/*".format(data_path))
self.log_command_output(o, r)
o, r = self.execute_command("rm -rf ""{0}""/*" \
.format(
data_path.replace("data", "config")))
self.log_command_output(o, r)
|
Cleans up the data config directory and its contents
Override method for Windows
|
give python code to
|
def execute_commands_inside(self, main_command, query, queries,
bucket1, password, bucket2, source,
subcommands=[], min_output_size=0,
end_msg='', timeout=250):
"""
Override method to handle windows specific file name
"""
filename = "/cygdrive/c/tmp/test.txt"
filedata = ""
if not(query == ""):
main_command = main_command + " -s=\"" + query+ '"'
elif (self.remote and not(queries == "")):
sftp = self._ssh_client.open_sftp()
filein = sftp.open(filename, 'w')
for query in queries:
filein.write(query)
filein.write('\n')
fileout = sftp.open(filename, 'r')
filedata = fileout.read()
#print filedata
fileout.close()
elif not(queries==""):
f = open(filename, 'w')
for query in queries:
f.write(query)
f.write('\n')
f.close()
fileout = open(filename, 'r')
filedata = fileout.read()
fileout.close()
if type(filedata) == bytes:
filedata = filedata.decode()
newdata = filedata.replace("bucketname",bucket2)
newdata = newdata.replace("user",bucket1)
newdata = newdata.replace("pass",password)
newdata = newdata.replace("bucket1",bucket1)
newdata = newdata.replace("user1",bucket1)
newdata = newdata.replace("pass1",password)
newdata = newdata.replace("bucket2",bucket2)
newdata = newdata.replace("user2",bucket2)
newdata = newdata.replace("pass2",password)
if (self.remote and not(queries=="")) :
f = sftp.open(filename,'w')
f.write(newdata)
f.close()
elif not(queries==""):
f = open(filename,'w')
f.write(newdata)
f.close()
if not(queries==""):
if (source):
main_command = main_command + " -s=\"\SOURCE " + 'c:\\\\tmp\\\\test.txt'
else:
main_command = main_command + " -f=" + 'c:\\\\tmp\\\\test.txt'
log.info("running command on {0}: {1}".format(self.ip, main_command))
output=""
if self.remote:
(stdin, stdout, stderro) = self._ssh_client.exec_command(main_command)
time.sleep(10)
count = 0
for line in stdout.readlines():
if (count == 0) and line.lower().find("error") > 0:
output = "status:FAIL"
break
#if line.find("results") > 0 or line.find("status") > 0 or line.find("metrics") or line.find("elapsedTime")> 0 or line.find("executionTime")> 0 or line.find("resultCount"):
if (count > 0):
output+=line.strip()
output = output.strip()
if "Inputwasnotastatement" in output:
output = "status:FAIL"
break
if "timeout" in output:
output = "status:timeout"
else:
count+=1
stdin.close()
stdout.close()
stderro.close()
else:
p = Popen(main_command , shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderro = p.communicate()
output = stdout
print(output)
time.sleep(1)
if (self.remote and not(queries=="")) :
sftp.remove(filename)
sftp.close()
elif not(queries==""):
os.remove(filename)
output = re.sub('\s+', '', output)
return (output)
|
Override method to handle windows specific file name
|
generate comment for above
|
def kill_erlang(self, delay=0):
"""
Kill the erlang process in the remote server. If delay is specified, the process is killed after the
delay
:param delay: time to delay the process kill
:return: output and error of executing process kill command
"""
if delay:
time.sleep(delay)
o, r = self.execute_command("killall -9 beam.smp")
if r and r[0] and "command not found" in r[0]:
o, r = self.execute_command("pkill beam.smp")
self.log_command_output(o, r)
self.log_command_output(o, r, debug=False)
all_killed = False
count = 0
while not all_killed and count < 6:
process_count = 0
self.sleep(2, "wait for erlang processes terminated")
out, _ = self.execute_command("ps aux | grep beam.smp")
for idx, val in enumerate(out):
if "/opt/couchbase" in val:
process_count += 1
if process_count == 0:
all_killed = True
if count == 3:
o, r = self.execute_command("killall -9 beam.smp")
if r and r[0] and "command not found" in r[0]:
o, r = self.execute_command("pkill beam.smp")
self.log_command_output(o, r)
count += 1
if not all_killed:
raise Exception("Could not kill erlang process")
return o, r
|
def kill_erlang(self, delay=0):
if delay:
time.sleep(delay)
o, r = self.execute_command("killall -9 beam.smp")
if r and r[0] and "command not found" in r[0]:
o, r = self.execute_command("pkill beam.smp")
self.log_command_output(o, r)
self.log_command_output(o, r, debug=False)
all_killed = False
count = 0
while not all_killed and count < 6:
process_count = 0
self.sleep(2, "wait for erlang processes terminated")
out, _ = self.execute_command("ps aux | grep beam.smp")
for idx, val in enumerate(out):
if "/opt/couchbase" in val:
process_count += 1
if process_count == 0:
all_killed = True
if count == 3:
o, r = self.execute_command("killall -9 beam.smp")
if r and r[0] and "command not found" in r[0]:
o, r = self.execute_command("pkill beam.smp")
self.log_command_output(o, r)
count += 1
if not all_killed:
raise Exception("Could not kill erlang process")
return o, r
|
generate comment for following function:
|
def handle_command_line_s(argument):
"""
Parse command line argument for -s option (servers)
:param argument: argument to parse
:return: list of server TestInputServer objects
"""
#ip:port:username:password:clipath
ips = argument.split(",")
servers = []
for ip in ips:
server = TestInputServer()
if ip.find(":") == -1:
pass
else:
info = ip.split(":")
#info[0] : ip
#info[1] : port
#info[2] :username
#info[3] : password
#info[4] : cli path
server.ip = info[0]
server.port = info[1]
server.ssh_username = info[2]
server.ssh_password = info[3]
server.cli_path = info[4]
servers.append(server)
return servers
|
def handle_command_line_s(argument):
#ip:port:username:password:clipath
ips = argument.split(",")
servers = []
for ip in ips:
server = TestInputServer()
if ip.find(":") == -1:
pass
else:
info = ip.split(":")
#info[0] : ip
#info[1] : port
#info[2] :username
#info[3] : password
#info[4] : cli path
server.ip = info[0]
server.port = info[1]
server.ssh_username = info[2]
server.ssh_password = info[3]
server.cli_path = info[4]
servers.append(server)
return servers
|
generate code for the above:
|
def restart_couchbase(self):
"""
Restarts the Couchbase server on the remote server
:return: None
"""
o, r = self.execute_command("open /Applications/Couchbase\ Server.app")
self.log_command_output(o, r)
|
Restarts the Couchbase server on the remote server
|
generate comment for following function:
|
def windows_process_utils(self, ps_name_or_id, cmd_file_name, option=""):
"""
Windows process utility. This adds firewall rules to Windows system.
If a previously suspended process is detected, it continues with the process instead.
:param ps_name_or_id: process name or process id
:param cmd_file_name: file containing firewall rules
:param option: arguments to pass to command file
:return: True if firewall rules were set else False
"""
success = False
files_path = "cygdrive/c/utils/suspend/"
# check to see if suspend files exist in server
file_existed = self.file_exists(files_path, cmd_file_name)
if file_existed:
command = "{0}{1} {2} {3}".format(files_path, cmd_file_name,
option, ps_name_or_id)
o, r = self.execute_command(command)
if not r:
success = True
self.log_command_output(o, r)
self.sleep(30, "Wait for windows to execute completely")
else:
log.error(
"Command didn't run successfully. Error: {0}".format(r))
else:
o, r = self.execute_command(
"netsh advfirewall firewall add rule name=\"block erl.exe in\" dir=in action=block program=\"%ProgramFiles%\Couchbase\Server\\bin\erl.exe\"")
if not r:
success = True
self.log_command_output(o, r)
o, r = self.execute_command(
"netsh advfirewall firewall add rule name=\"block erl.exe out\" dir=out action=block program=\"%ProgramFiles%\Couchbase\Server\\bin\erl.exe\"")
if not r:
success = True
self.log_command_output(o, r)
return success
|
def windows_process_utils(self, ps_name_or_id, cmd_file_name, option=""):
success = False
files_path = "cygdrive/c/utils/suspend/"
# check to see if suspend files exist in server
file_existed = self.file_exists(files_path, cmd_file_name)
if file_existed:
command = "{0}{1} {2} {3}".format(files_path, cmd_file_name,
option, ps_name_or_id)
o, r = self.execute_command(command)
if not r:
success = True
self.log_command_output(o, r)
self.sleep(30, "Wait for windows to execute completely")
else:
log.error(
"Command didn't run successfully. Error: {0}".format(r))
else:
o, r = self.execute_command(
"netsh advfirewall firewall add rule name=\"block erl.exe in\" dir=in action=block program=\"%ProgramFiles%\Couchbase\Server\\bin\erl.exe\"")
if not r:
success = True
self.log_command_output(o, r)
o, r = self.execute_command(
"netsh advfirewall firewall add rule name=\"block erl.exe out\" dir=out action=block program=\"%ProgramFiles%\Couchbase\Server\\bin\erl.exe\"")
if not r:
success = True
self.log_command_output(o, r)
return success
|
give a code to
|
def give_directory_permissions_to_couchbase(self, location):
"""
Change the directory permission of the location mentioned
to include couchbase as the user
:param location: Directory location whoes permissions has to be changed
:return: None
"""
command = "chown 'couchbase' {0}".format(location)
output, error = self.execute_command(command)
command = "chmod 777 {0}".format(location)
output, error = self.execute_command(command)
|
Change the directory permission of the location mentioned
to include couchbase as the user
|
def copy_build_to_server(self, node_installer, build_url):
"""
Copies the downloaded Couchbase build from local to remote server
:param node_installer: node installer object
:param build_url: build url to download the Couchbase build from. This is used to get the file name
to store in the remote server
:return: True if the file was successfully copied else False
"""
f_path = "{}/{}".format(".", build_url.split('/')[-1])
result = node_installer.shell.copy_file_local_to_remote(
f_path, node_installer.shell.download_dir)
node_installer.shell.disconnect()
return result
|
def copy_build_to_server(self, node_installer, build_url):
f_path = "{}/{}".format(".", build_url.split('/')[-1])
result = node_installer.shell.copy_file_local_to_remote(
f_path, node_installer.shell.download_dir)
node_installer.shell.disconnect()
return result
|
|
generate python code for
|
def populate_debug_build_url(self):
"""
Populates the debug_info build url variable.
:return: None
"""
self.node_install_info.debug_build_url = self.__construct_build_url(
is_debuginfo_build=True)
self.log.info("{} - Debug build url :: {}"
.format(self.node_install_info.server.ip,
self.node_install_info.debug_build_url))
|
Populates the debug_info build url variable.
|
Code the following:
|
def __init__(self, logger):
"""
Creates an instance of InstallHelper object
:param logger: logger object
"""
self.log = logger
|
Creates an instance of InstallHelper object
|
generate python code for the following
|
def get_memcache_pid(self):
"""
Get the pid of memcached process
:return: pid of memcached process
"""
raise NotImplementedError
|
Get the pid of memcached process
|
generate python code for the above
|
def __init__(self):
"""
Creates an instance of the TestInputBuild class
"""
self.version = ''
self.url = ''
|
Creates an instance of the TestInputBuild class
|
generate code for the above:
|
def kill_eventing_process(self, name):
"""
Kill eventing process on remote server
:param name: name of eventing process
:return: None
"""
o, r = self.execute_command(command="killall -9 {0}".format(name))
self.log_command_output(o, r)
|
Kill eventing process on remote server
|
give a code to
|
def restart_couchbase(self):
"""
Restarts the Couchbase server on the remote server
:return: None
"""
o, r = self.execute_command("service couchbase-server restart")
self.log_command_output(o, r)
|
Restarts the Couchbase server on the remote server
|
from shell_util.remote_connection import RemoteMachineShellConnection
def __init__(self, test_server):
"""
Creates an instance of Linux installer class
:param test_server: server object of type TestInputServer
"""
super(Linux, self).__init__()
self.shell = RemoteMachineShellConnection(test_server)
|
Creates an instance of Linux installer class
|
|
generate doc string for following function:
|
def get_hostname(self):
"""
Get the hostname of the remote server.
:return: hostname of the remote server if found else None
"""
o, r = self.execute_command_raw('hostname', debug=False)
if o:
return o
|
def get_hostname(self):
o, r = self.execute_command_raw('hostname', debug=False)
if o:
return o
|
Code the following:
|
def cleanup_data_config(self, data_path):
"""
Cleans up the data config directory and its contents
:param data_path: path to data config directory
:return: None
"""
self.extract_remote_info()
o, r = self.execute_command("rm -rf {0}/*".format(data_path))
self.log_command_output(o, r)
o, r = self.execute_command(
"rm -rf {0}/*".format(data_path.replace("data", "config")))
self.log_command_output(o, r)
|
Cleans up the data config directory and its contents
|
Code the following:
|
def flush_os_caches(self):
"""
Flush OS caches on remote server
:return: None
"""
o, r = self.execute_command("sync")
self.log_command_output(o, r)
o, r = self.execute_command("/sbin/sysctl vm.drop_caches=3")
self.log_command_output(o, r)
|
Flush OS caches on remote server
|
def stop_indexer(self):
"""
Stop indexer process on remote server
:return: None
"""
o, r = self.execute_command("taskkill /F /T /IM indexer*")
self.log_command_output(o, r, debug=False)
|
Stop indexer process on remote server
|
|
def uninstall(self):
"""
Uninstalls Couchbase server on Unix machine
:return: True on success
"""
self.shell.stop_couchbase()
cmd = self.cmds["uninstall"]
if self.shell.nonroot:
cmd = self.non_root_cmds["uninstall"]
self.shell.execute_command(cmd)
return True
|
def uninstall(self):
self.shell.stop_couchbase()
cmd = self.cmds["uninstall"]
if self.shell.nonroot:
cmd = self.non_root_cmds["uninstall"]
self.shell.execute_command(cmd)
return True
|
|
def unpause_memcached(self, os="linux"):
"""
Unpauses the memcached process on remote server
:param os: os type of remote server
:return: None
"""
log.info("*** unpause memcached process ***")
if self.nonroot:
o, r = self.execute_command("killall -SIGCONT memcached.bin")
else:
o, r = self.execute_command("killall -SIGCONT memcached")
self.log_command_output(o, r)
|
Unpauses the memcached process on remote server
|
|
def stop_membase(self, num_retries=10, poll_interval=1):
"""
Stop membase process on remote server
:param num_retries: number of retries before giving up
:param poll_interval: wait time between each retry.
:return: None
"""
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)
retries = num_retries
while retries > 0:
if self.is_process_running('membaseserver') is None:
break
retries -= 1
self.sleep(poll_interval)
|
def stop_membase(self, num_retries=10, poll_interval=1):
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)
retries = num_retries
while retries > 0:
if self.is_process_running('membaseserver') is None:
break
retries -= 1
self.sleep(poll_interval)
|
|
generate comment.
|
def get_ip_address(self):
"""
Get ip address of a remote server
Override method for Windows
:return: ip address of remote server
"""
raise NotImplementedError
|
def get_ip_address(self):
raise NotImplementedError
|
generate python code for the following
|
def connect_with_user(self, user="root"):
"""
Connect to the remote server with given user
Override method since this is not required for Unix
:param user: user to connect to remote server with
:return: None
"""
return
|
Connect to the remote server with given user
Override method since this is not required for Unix
|
generate code for the following
|
def get_disk_info(self, win_info=None, mac=False):
"""
Get disk info of a remote server
:param win_info: windows info
:param mac: get disk info from macOS if True
:return: disk info of remote server
"""
if win_info:
if 'Total Physical Memory' not in win_info:
win_info = self.create_windows_info()
o = "Total Physical Memory =" + win_info['Total Physical Memory'] + '\n'
o += "Available Physical Memory =" + win_info['Available Physical Memory']
elif mac:
o, r = self.execute_command_raw('df -hl', debug=False)
else:
o, r = self.execute_command_raw('df -Thl', debug=False)
if o:
return o
|
Get disk info of a remote server
|
give python code to
|
def start_indexer(self):
"""
Start indexer process on remote server
:return: None
"""
o, r = self.execute_command("kill -SIGCONT $(pgrep indexer)")
self.log_command_output(o, r)
|
Start indexer process on remote server
|
generate comment.
|
def execute_non_sudo_command(self, command, info=None, debug=True,
use_channel=False):
"""
Execute command in non-sudo mode.
:param command: command to be executed
:param info: None
:param debug: print debug information in logs if True
:param use_channel: use an SSH channel if True.
:return: Command output as a list of lines.
"""
return self.execute_command_raw(command, debug=debug,
use_channel=use_channel)
|
def execute_non_sudo_command(self, command, info=None, debug=True,
use_channel=False):
return self.execute_command_raw(command, debug=debug,
use_channel=use_channel)
|
generate doc string for following function:
|
def is_couchbase_installed(self):
"""
Check if Couchbase is installed on the remote server.
This checks if the couchbase is installed in default or non default path.
:return: True if Couchbase is installed on the remote server else False
"""
output, error = self.execute_command('ls %s%s' % (self.cb_path,
self.version_file))
self.log_command_output(output, error)
for line in output:
if line.find('No such file or directory') == -1:
return True
return False
|
def is_couchbase_installed(self):
output, error = self.execute_command('ls %s%s' % (self.cb_path,
self.version_file))
self.log_command_output(output, error)
for line in output:
if line.find('No such file or directory') == -1:
return True
return False
|
generate python code for the following
|
def copy_file_local_to_remote(self, src_path, des_path):
"""
Copy file from local to remote server
:param src_path: source path of the file to be copied
:param des_path: destination path of the file to be copied
:return: True if the file was successfully copied else False
"""
result = True
sftp = self._ssh_client.open_sftp()
try:
sftp.put(src_path, des_path)
except IOError:
self.log.error('Can not copy file')
result = False
finally:
sftp.close()
return result
|
Copy file from local to remote server
|
give a code to
|
def enable_file_limit_desc(self):
"""
Change the file limit for all processes to 100
:return: None
"""
o, r = self.execute_command("sysctl -w fs.file-max=100;sysctl -p")
self.log_command_output(o, r)
|
Change the file limit for all processes to 100
|
generate code for the following
|
def cleanup_all_configuration(self, data_path):
"""
Deletes the contents of the parent folder that holds the data and config directories.
:param data_path: The path key from the /nodes/self end-point which
looks something like "/opt/couchbase/var/lib/couchbase/data" on
Linux or "c:/Program Files/Couchbase/Server/var/lib/couchbase/data"
on Windows.
:return: None
"""
# The path returned on both Linux and Windows by the /nodes/self end-point uses forward slashes.
path = data_path.replace("/data", "")
o, r = self.execute_command("rm -rf %s/*" % path)
self.log_command_output(o, r)
|
Deletes the contents of the parent folder that holds the data and config directories.
|
generate comment for above
|
def reboot_node(self):
"""
Reboot the remote server
:return: None
"""
o, r = self.execute_command("shutdown -r -f -t 0")
self.log_command_output(o, r)
|
def reboot_node(self):
o, r = self.execute_command("shutdown -r -f -t 0")
self.log_command_output(o, r)
|
def get_instances(cls):
"""
Returns a list of instances of the class
:return: generator that yields instances of the class
"""
for ins in cls.__refs__:
yield ins
|
Returns a list of instances of the class
|
|
give a code to
|
def alt_addr_add_node(self, main_server=None, internal_IP=None,
server_add=None, user="Administrator",
passwd="password", services="kv", cmd_ext=""):
"""
Add node to couchbase cluster using alternative address
:param main_server: couchbase cluster address
:param internal_IP: internal or alternate address to the server to add
:param server_add: server object of the server to add to cluster
:param user: username to connect to cluster
:param passwd: password to connect to cluster
:param services: services that's part of the node to be added
:param cmd_ext: curl extension to execute with
:return: output of the curl command adding node to cluster.
"""
""" in alternate address, we need to use curl to add node """
if internal_IP is None:
raise Exception("Need internal IP to add node.")
if main_server is None:
raise Exception("Need master IP to run")
cmd = 'curl{0} -X POST -d "hostname={1}&user={2}&password={3}&services={4}" '\
.format(cmd_ext, internal_IP, server_add.rest_username,
server_add.rest_password, services)
cmd += '-u {0}:{1} https://{2}:18091/controller/addNode'\
.format(main_server.rest_username, main_server.rest_password,
main_server.ip)
output, error = self.execute_command(cmd)
return output, error
|
Add node to couchbase cluster using alternative address
|
generate code for the following
|
def start_server(self):
"""
Starts the Couchbase server on the remote server.
The method runs the sever from non-default location if it's run as nonroot user. Else from default location.
:return: None
"""
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
|
Starts the Couchbase server on the remote server.
The method runs the sever from non-default location if it's run as nonroot user. Else from default location.
|
generate python code for
|
def file_starts_with(self, remotepath, pattern):
"""
Check if file starting with this pattern is present in remote machine.
:param remotepath: path of the file to check
:param pattern: pattern to check against
:return: True if file starting with this pattern is present in remote machine else False
"""
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
|
Check if file starting with this pattern is present in remote machine.
|
give python code to
|
def pause_beam(self):
"""
Pauses the beam.smp process on remote server
Override method for Windows
:return: None
"""
raise NotImplementedError
|
Pauses the beam.smp process on remote server
Override method for Windows
|
generate doc string for following function:
|
def terminate_processes(self, info, p_list):
"""
Terminate a list of processes on remote server
:param info: None
:param p_list: List of processes to terminate
:return: None
"""
for process in p_list:
self.terminate_process(info, process, force=True)
|
def terminate_processes(self, info, p_list):
for process in p_list:
self.terminate_process(info, process, force=True)
|
generate python code for the above
|
from subprocess import Popen
def remove_directory(self, remote_path):
"""
Remove the directory specified from system.
:param remote_path: Directory path to remove.
:return: True if the directory was removed else False
"""
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
|
Remove the directory specified from system.
|
generate comment for following function:
|
def stop_schedule_tasks(self):
"""
Stop the scheduled tasks. Stops installme, removeme and upgrademe processes on remote server
:return: None
"""
self.log.info("STOP SCHEDULE TASKS: installme, removeme & upgrademe")
for task in ["installme", "removeme", "upgrademe"]:
output, error = self.execute_command("cmd /c schtasks /end /tn %s"
% task)
self.log_command_output(output, error)
|
def stop_schedule_tasks(self):
self.log.info("STOP SCHEDULE TASKS: installme, removeme & upgrademe")
for task in ["installme", "removeme", "upgrademe"]:
output, error = self.execute_command("cmd /c schtasks /end /tn %s"
% task)
self.log_command_output(output, error)
|
generate code for the following
|
def validate_server_status(self, node_helpers):
"""
Checks if the servers are supported OS for Couchbase installation
:param node_helpers: list of node helpers of type NodeInstallInfo
:return: True if the servers are supported OS for Couchbase installation else False
"""
result = True
known_os = set()
for node_helper in node_helpers:
if node_helper.os_type not in SUPPORTED_OS:
self.log.critical(
"{} - Unsupported os: {}"
.format(node_helper.server.ip, node_helper.os_type))
result = False
else:
known_os.add(node_helper.os_type)
if len(known_os) != 1:
self.log.critical("Multiple OS versions found!")
result = False
return result
|
Checks if the servers are supported OS for Couchbase installation
|
give a code to
|
def mount_partition_ext4(self, location):
"""
Mount a partition at the location specified
:param location: Mount location
:return: Output and error message from the mount command
"""
command = "mount -o loop,rw,usrquota,grpquota /usr/disk-img/disk-quota.ext4 {0}; df -Thl".format(location)
output, error = self.execute_command(command)
return output, error
|
Mount a partition at the location specified
|
give a code to
|
def execute_cbcollect_info(self, file, options=""):
"""
Execute cbcollect command on remote server
:param file: file name to store the cbcollect as
:param options: options for the cbcollect command
:return: output of the cbcollect command
"""
cbcollect_command = "%scbcollect_info" % (LINUX_COUCHBASE_BIN_PATH)
if self.nonroot:
cbcollect_command = "%scbcollect_info" % (LINUX_NONROOT_CB_BIN_PATH)
self.extract_remote_info()
if self.info.type.lower() == 'windows':
cbcollect_command = "%scbcollect_info.exe" % (WIN_COUCHBASE_BIN_PATH)
if self.info.distribution_type.lower() == 'mac':
cbcollect_command = "%scbcollect_info" % (MAC_COUCHBASE_BIN_PATH)
command = "%s %s %s" % (cbcollect_command, file, options)
output, error = self.execute_command(command, use_channel=True)
return output, error
|
Execute cbcollect command on remote server
|
generate code for the above:
|
def stop_memcached(self):
"""
Stop memcached process on remote server
:return: None
"""
o, r = self.execute_command("taskkill /F /T /IM memcached*")
self.log_command_output(o, r, debug=False)
|
Stop memcached process on remote server
|
give python code to
|
def reset_env_variables(self):
"""
Reset environment previously set and restart couchbase server
:return: None
"""
shell = self._ssh_client.invoke_shell()
if getattr(self, "info", None) is None:
self.info = self.extract_remote_info()
init_file = "couchbase-server"
file_path = "/opt/couchbase/bin/"
backupfile = file_path + init_file + ".bak"
sourceFile = file_path + init_file
o, r = self.execute_command("mv " + backupfile + " " + sourceFile)
self.log_command_output(o, r)
# Restart Couchbase
o, r = self.execute_command("service couchbase-server restart")
self.log_command_output(o, r)
shell.close()
|
Reset environment previously set and restart couchbase server
|
generate code for the above:
|
def get_process_statistics(self, process_name=None, process_pid=None):
"""
Get the process statistics for given parameter
Gets process statistics for windows nodes
WMI is required to be intalled on the node
stats_windows_helper should be located on the node
:param parameter: parameter to get statistics for
:param process_name: name of process to get statistics for
:param process_pid: pid of process to get statistics for
:return: process statistics for parameter if present else None
"""
self.extract_remote_info()
remote_command = "cd ~; /cygdrive/c/Python27/python stats_windows_helper.py"
if process_name:
remote_command.append(" " + process_name)
elif process_pid:
remote_command.append(" " + process_pid)
o, r = self.execute_command(remote_command, self.info)
if r:
log.error("Command didn't run successfully. Error: {0}".format(r))
return o
|
Get the process statistics for given parameter
Gets process statistics for windows nodes
WMI is required to be intalled on the node
stats_windows_helper should be located on the node
|
generate code for the above:
|
import sys
from install_util.constants.build import BuildUrl
from install_util.install_lib.helper import InstallHelper
from install_util.install_lib.node_helper import NodeInstaller
from install_util.install_lib.node_helper import NodeInstallInfo
from install_util.test_input import TestInputParser
from shell_util.remote_connection import RemoteMachineShellConnection
def main(logger):
"""
Main function of the installation script.
:param logger: logger object to use
:return: status code for the installation process
"""
helper = InstallHelper(logger)
args = helper.parse_command_line_args(sys.argv[1:])
logger.setLevel(args.log_level.upper())
user_input = TestInputParser.get_test_input(args)
for server in user_input.servers:
server.install_status = "not_started"
logger.info("Node health check")
if not helper.check_server_state(user_input.servers):
return 1
# Populate valid couchbase version and validate the input version
try:
helper.populate_cb_server_versions()
except Exception as e:
logger.warning("Error while reading couchbase version: {}".format(e))
if args.version[:3] not in BuildUrl.CB_VERSION_NAME.keys():
log.critical("Version '{}' not yet supported".format(args.version[:3]))
return 1
# Objects for each node to track the URLs / state to reuse
node_helpers = list()
for server in user_input.servers:
server_info = RemoteMachineShellConnection.get_info_for_server(server)
node_helpers.append(
NodeInstallInfo(server,
server_info,
helper.get_os(server_info),
args.version,
args.edition))
# Validate os_type across servers
okay = helper.validate_server_status(node_helpers)
if not okay:
return 1
# Populating build url to download
if args.url:
for node_helper in node_helpers:
node_helper.build_url = args.url
else:
tasks_to_run = ["populate_build_url"]
if args.install_debug_info:
tasks_to_run.append("populate_debug_build_url")
url_builder_threads = \
[NodeInstaller(logger, node_helper, tasks_to_run)
for node_helper in node_helpers]
okay = start_and_wait_for_threads(url_builder_threads, 60)
if not okay:
return 1
# Checking URL status
url_builder_threads = \
[NodeInstaller(logger, node_helper, ["check_url_status"])
for node_helper in node_helpers]
okay = start_and_wait_for_threads(url_builder_threads, 60)
if not okay:
return 1
# Downloading build
if args.skip_local_download:
# Download on individual nodes
download_threads = \
[NodeInstaller(logger, node_helper, ["download_build"])
for node_helper in node_helpers]
else:
# Local file download and scp to all nodes
download_threads = [
NodeInstaller(logger, node_helpers[0], ["local_download_build"])]
okay = start_and_wait_for_threads(download_threads,
args.build_download_timeout)
if not okay:
return 1
download_threads = \
[NodeInstaller(logger, node_helper, ["copy_local_build_to_server"])
for node_helper in node_helpers]
okay = start_and_wait_for_threads(download_threads,
args.build_download_timeout)
if not okay:
return 1
install_tasks = args.install_tasks.split("-")
logger.info("Starting installation tasks :: {}".format(install_tasks))
install_threads = [
NodeInstaller(logger, node_helper, install_tasks)
for node_helper in node_helpers]
okay = start_and_wait_for_threads(install_threads, args.timeout)
print_install_status(install_threads, logger)
if not okay:
return 1
return 0
|
Main function of the installation script.
|
generate doc string for following function:
|
def execute_commands_inside(self, main_command, query, queries,
bucket1, password, bucket2, source,
subcommands=[], min_output_size=0,
end_msg='', timeout=250):
"""
Override method to handle windows specific file name
"""
filename = "/cygdrive/c/tmp/test.txt"
filedata = ""
if not(query == ""):
main_command = main_command + " -s=\"" + query+ '"'
elif (self.remote and not(queries == "")):
sftp = self._ssh_client.open_sftp()
filein = sftp.open(filename, 'w')
for query in queries:
filein.write(query)
filein.write('\n')
fileout = sftp.open(filename, 'r')
filedata = fileout.read()
#print filedata
fileout.close()
elif not(queries==""):
f = open(filename, 'w')
for query in queries:
f.write(query)
f.write('\n')
f.close()
fileout = open(filename, 'r')
filedata = fileout.read()
fileout.close()
if type(filedata) == bytes:
filedata = filedata.decode()
newdata = filedata.replace("bucketname",bucket2)
newdata = newdata.replace("user",bucket1)
newdata = newdata.replace("pass",password)
newdata = newdata.replace("bucket1",bucket1)
newdata = newdata.replace("user1",bucket1)
newdata = newdata.replace("pass1",password)
newdata = newdata.replace("bucket2",bucket2)
newdata = newdata.replace("user2",bucket2)
newdata = newdata.replace("pass2",password)
if (self.remote and not(queries=="")) :
f = sftp.open(filename,'w')
f.write(newdata)
f.close()
elif not(queries==""):
f = open(filename,'w')
f.write(newdata)
f.close()
if not(queries==""):
if (source):
main_command = main_command + " -s=\"\SOURCE " + 'c:\\\\tmp\\\\test.txt'
else:
main_command = main_command + " -f=" + 'c:\\\\tmp\\\\test.txt'
log.info("running command on {0}: {1}".format(self.ip, main_command))
output=""
if self.remote:
(stdin, stdout, stderro) = self._ssh_client.exec_command(main_command)
time.sleep(10)
count = 0
for line in stdout.readlines():
if (count == 0) and line.lower().find("error") > 0:
output = "status:FAIL"
break
#if line.find("results") > 0 or line.find("status") > 0 or line.find("metrics") or line.find("elapsedTime")> 0 or line.find("executionTime")> 0 or line.find("resultCount"):
if (count > 0):
output+=line.strip()
output = output.strip()
if "Inputwasnotastatement" in output:
output = "status:FAIL"
break
if "timeout" in output:
output = "status:timeout"
else:
count+=1
stdin.close()
stdout.close()
stderro.close()
else:
p = Popen(main_command , shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderro = p.communicate()
output = stdout
print(output)
time.sleep(1)
if (self.remote and not(queries=="")) :
sftp.remove(filename)
sftp.close()
elif not(queries==""):
os.remove(filename)
output = re.sub('\s+', '', output)
return (output)
|
def execute_commands_inside(self, main_command, query, queries,
bucket1, password, bucket2, source,
subcommands=[], min_output_size=0,
end_msg='', timeout=250):
filename = "/cygdrive/c/tmp/test.txt"
filedata = ""
if not(query == ""):
main_command = main_command + " -s=\"" + query+ '"'
elif (self.remote and not(queries == "")):
sftp = self._ssh_client.open_sftp()
filein = sftp.open(filename, 'w')
for query in queries:
filein.write(query)
filein.write('\n')
fileout = sftp.open(filename, 'r')
filedata = fileout.read()
#print filedata
fileout.close()
elif not(queries==""):
f = open(filename, 'w')
for query in queries:
f.write(query)
f.write('\n')
f.close()
fileout = open(filename, 'r')
filedata = fileout.read()
fileout.close()
if type(filedata) == bytes:
filedata = filedata.decode()
newdata = filedata.replace("bucketname",bucket2)
newdata = newdata.replace("user",bucket1)
newdata = newdata.replace("pass",password)
newdata = newdata.replace("bucket1",bucket1)
newdata = newdata.replace("user1",bucket1)
newdata = newdata.replace("pass1",password)
newdata = newdata.replace("bucket2",bucket2)
newdata = newdata.replace("user2",bucket2)
newdata = newdata.replace("pass2",password)
if (self.remote and not(queries=="")) :
f = sftp.open(filename,'w')
f.write(newdata)
f.close()
elif not(queries==""):
f = open(filename,'w')
f.write(newdata)
f.close()
if not(queries==""):
if (source):
main_command = main_command + " -s=\"\SOURCE " + 'c:\\\\tmp\\\\test.txt'
else:
main_command = main_command + " -f=" + 'c:\\\\tmp\\\\test.txt'
log.info("running command on {0}: {1}".format(self.ip, main_command))
output=""
if self.remote:
(stdin, stdout, stderro) = self._ssh_client.exec_command(main_command)
time.sleep(10)
count = 0
for line in stdout.readlines():
if (count == 0) and line.lower().find("error") > 0:
output = "status:FAIL"
break
#if line.find("results") > 0 or line.find("status") > 0 or line.find("metrics") or line.find("elapsedTime")> 0 or line.find("executionTime")> 0 or line.find("resultCount"):
if (count > 0):
output+=line.strip()
output = output.strip()
if "Inputwasnotastatement" in output:
output = "status:FAIL"
break
if "timeout" in output:
output = "status:timeout"
else:
count+=1
stdin.close()
stdout.close()
stderro.close()
else:
p = Popen(main_command , shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderro = p.communicate()
output = stdout
print(output)
time.sleep(1)
if (self.remote and not(queries=="")) :
sftp.remove(filename)
sftp.close()
elif not(queries==""):
os.remove(filename)
output = re.sub('\s+', '', output)
return (output)
|
generate python code for
|
def check_build_url_status(self):
"""
Checks the build url status. Checks if the url is reachable and valid.
:return: None
"""
self.check_url_status(self.node_install_info.build_url)
|
Checks the build url status. Checks if the url is reachable and valid.
|
generate python code for
|
def stop_membase(self):
"""
Override method
"""
raise NotImplementedError
|
Override method
|
generate code for the above:
|
def uninstall(self):
"""
Uninstalls Couchbase server on Windows machine
:return: True on success
"""
self.shell.stop_couchbase()
cmd = self.cmds["uninstall"]
self.shell.execute_command(cmd)
return True
|
Uninstalls Couchbase server on Windows machine
|
give a code to
|
def enable_disk_readonly(self, disk_location):
"""
Enables read-only mode for the specified disk location.
:param disk_location: disk location to enable read-only mode.
:return: None
"""
o, r = self.execute_command("chmod -R 444 {}".format(disk_location))
self.log_command_output(o, r)
|
Enables read-only mode for the specified disk location.
|
give python code to
|
def delete_files(self, file_location, debug=False):
"""
Delete the files in the specified location
:param file_location: path to files to delete
:param debug: print debug information if True
:return: None
"""
command = "%s%s" % ("rm -rf ", file_location)
output, error = self.execute_command(command, debug=debug)
if debug:
self.log_command_output(output, error)
|
Delete the files in the specified location
|
generate python code for
|
def __init__(self):
"""
Creates an instance of RemoteMachineProcess class
"""
self.pid = ''
self.name = ''
self.vsz = 0
self.rss = 0
self.args = ''
|
Creates an instance of RemoteMachineProcess class
|
generate comment for following function:
|
def pause_beam(self):
"""
Pauses the beam.smp process on remote server
Override method for Windows
:return: None
"""
raise NotImplementedError
|
def pause_beam(self):
raise NotImplementedError
|
generate python code for
|
def kill_eventing_process(self, name):
"""
Kill eventing process on remote server
:param name: name of eventing process
:return: None
"""
o, r = self.execute_command(command="taskkill /F /T /IM {0}*".format(name))
self.log_command_output(o, r)
|
Kill eventing process on remote server
|
generate code for the following
|
def kill_eventing_process(self, name):
"""
Kill eventing process on remote server
:param name: name of eventing process
:return: None
"""
o, r = self.execute_command(command="killall -9 {0}".format(name))
self.log_command_output(o, r)
|
Kill eventing process on remote server
|
give a code to
|
def get_server_ips(config, section):
"""
Get server IPs from config
:param config: config
:param section: section to get server IPs from
:return: list of IP addresses
"""
ips = []
options = config.options(section)
for option in options:
ips.append(config.get(section, option))
return ips
|
Get server IPs from config
|
generate comment for above
|
def change_env_variables(self, dict):
"""
Change environment variables mentioned in dictionary and restart Couchbase server
:param dict: key value pair of environment variables and their values to change to
:return: None
"""
prefix = "\\n "
shell = self._ssh_client.invoke_shell()
environmentVariables = ""
init_file = "service_start.bat"
file_path = "\"/cygdrive/c/Program Files/Couchbase/Server/bin/\""
prefix = "\\n"
backupfile = file_path + init_file + ".bak"
sourceFile = file_path + init_file
o, r = self.execute_command("cp " + sourceFile + " " + backupfile)
self.log_command_output(o, r)
for key in list(dict.keys()):
o, r = self.execute_command("sed -i 's/{1}.*//' {0}"
.format(sourceFile, key))
self.log_command_output(o, r)
o, r = self.execute_command(
"sed -i 's/export ERL_FULLSWEEP_AFTER/export "
"ERL_FULLSWEEP_AFTER\\n{1}={2}\\nexport {1}/' {0}"
.format(sourceFile, key, dict[key]))
self.log_command_output(o, r)
for key in list(dict.keys()):
environmentVariables += prefix + 'set {0}={1}'.format(key, dict[key])
command = "sed -i 's/{0}/{0}".format("set NS_ERTS=%NS_ROOT%\erts-5.8.5.cb1\bin")
command += environmentVariables + "/'" + " " + sourceFile
o, r = self.execute_command(command)
self.log_command_output(o, r)
# Restart couchbase
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
shell.close()
|
def change_env_variables(self, dict):
prefix = "\\n "
shell = self._ssh_client.invoke_shell()
environmentVariables = ""
init_file = "service_start.bat"
file_path = "\"/cygdrive/c/Program Files/Couchbase/Server/bin/\""
prefix = "\\n"
backupfile = file_path + init_file + ".bak"
sourceFile = file_path + init_file
o, r = self.execute_command("cp " + sourceFile + " " + backupfile)
self.log_command_output(o, r)
for key in list(dict.keys()):
o, r = self.execute_command("sed -i 's/{1}.*//' {0}"
.format(sourceFile, key))
self.log_command_output(o, r)
o, r = self.execute_command(
"sed -i 's/export ERL_FULLSWEEP_AFTER/export "
"ERL_FULLSWEEP_AFTER\\n{1}={2}\\nexport {1}/' {0}"
.format(sourceFile, key, dict[key]))
self.log_command_output(o, r)
for key in list(dict.keys()):
environmentVariables += prefix + 'set {0}={1}'.format(key, dict[key])
command = "sed -i 's/{0}/{0}".format("set NS_ERTS=%NS_ROOT%\erts-5.8.5.cb1\bin")
command += environmentVariables + "/'" + " " + sourceFile
o, r = self.execute_command(command)
self.log_command_output(o, r)
# Restart couchbase
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
shell.close()
|
generate doc string for following function:
|
def __init__(self):
"""
Creates an instance of RemoteMachineInfo class
"""
self.type = ''
self.ip = ''
self.distribution_type = ''
self.architecture_type = ''
self.distribution_version = ''
self.deliverable_type = ''
self.ram = ''
self.cpu = ''
self.disk = ''
self.hostname = ''
|
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 = ''
|
generate python code for the following
|
import weakref
import paramiko
def __init__(self, test_server):
"""
Create an instance of Shell connection for the given test server.
This class is responsible for executing remote shell commands on a remote server.
:param test_server: remote server to connect to. This is an object with following attributes:
self.ip = ''
self.id = ''
self.hostname = ''
self.ssh_username = ''
self.ssh_password = ''
self.ssh_key = ''
self.rest_username = ''
self.rest_password = ''
self.services = ''
self.port = ''
self.memcached_port = 11210
self.cli_path = ''
self.data_path = ''
self.index_path = ''
self.cbas_path = ''
self.eventing_path = ''
self.n1ql_port = ''
self.index_port = ''
self.fts_port = ''
self.es_username = ''
self.es_password = ''
self.upgraded = False
self.remote_info = None
self.use_sudo = False
self.type = ""
In the above, ip, ssh_username, ssh_password or ssh_key, port, rest_username and rest_password are required.
Rest are optional.
"""
super(ShellConnection, self).__init__()
ShellConnection.__refs__.append(weakref.ref(self)())
self.ip = test_server.ip
self.port = test_server.port
self.server = test_server
self.remote = (self.ip != "localhost" and self.ip != "127.0.0.1")
self.info = None
self.log = log
ShellConnection.connections += 1
self._ssh_client = paramiko.SSHClient()
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
Create an instance of Shell connection for the given test server.
This class is responsible for executing remote shell commands on a remote server.
|
Code the following:
|
def get_data_file_size(self, path=None):
"""
Get the size of the file in the specified path
:param path: path of the file to get the size of
:return: size of the file in the path
"""
output, error = self.execute_command('du -b {0}'.format(path))
if error:
return 0
else:
for line in output:
size = line.strip().split('\t')
if size[0].isdigit():
print((size[0]))
return size[0]
else:
return 0
|
Get the size of the file in the specified path
|
generate python code for the following
|
def get_mem_usage_by_process(self, process_name):
"""
Get the memory usage of a process
:param process_name: name of the process to get the memory usage for
:return: the memory usage of the process if available else None
"""
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])
|
Get the memory usage of a process
|
generate code for the above:
|
def kill_eventing_process(self, name):
"""
Kill eventing process on remote server
:param name: name of eventing process
:return: None
"""
o, r = self.execute_command(command="taskkill /F /T /IM {0}*".format(name))
self.log_command_output(o, r)
|
Kill eventing process on remote server
|
generate python code for the following
|
def get_os(info):
"""
Gets os name from info
:param info: server info dictionary to get the data from
:return: os name
"""
os = info.distribution_version.lower()
to_be_replaced = ['\n', ' ', 'gnu/linux']
for _ in to_be_replaced:
if _ in os:
os = os.replace(_, '')
if info.deliverable_type == "dmg":
major_version = os.split('.')
os = major_version[0] + '.' + major_version[1]
if info.distribution_type == "Amazon Linux 2":
os = "amzn2"
return os
|
Gets os name from info
|
generate code for the following
|
def get_cbversion(self):
"""
Get the installed version of Couchbase Server installed on the remote server.
This gets the versions from both default path or non-default paths.
Returns in format fv = a.b.c-xxxx, sv = a.b.c, bn = xxxx
:return: full version, main version and the build version of the Couchbase Server installed
"""
fv = sv = bn = ""
if self.file_exists(self.cb_path, self.version_file):
output = self.read_remote_file(self.cb_path, self.version_file)
if output:
for x in output:
x = x.strip()
if x and x[:5] in self.cb_release_builds.keys() \
and "-" in x:
fv = x
tmp = x.split("-")
sv = tmp[0]
bn = tmp[1]
break
else:
self.log.info("%s - Couchbase Server not found" % self.ip)
return fv, sv, bn
|
Get the installed version of Couchbase Server installed on the remote server.
This gets the versions from both default path or non-default paths.
Returns in format fv = a.b.c-xxxx, sv = a.b.c, bn = xxxx
|
generate doc string for following function:
|
def get_ram_info(self, win_info=None, mac=False):
"""
Get the RAM info of the remote server
:param win_info: Windows info in case of windows
:param mac: Get info for macOS if True
:return: RAM info of the remote server if found else None
"""
if win_info:
if 'Virtual Memory Max Size' not in win_info:
win_info = self.create_windows_info()
o = "Virtual Memory Max Size =" \
+ win_info['Virtual Memory Max Size'] + '\n' \
+ "Virtual Memory Available =" \
+ win_info['Virtual Memory Available'] + '\n' \
+ "Virtual Memory In Use =" + win_info['Virtual Memory In Use']
elif mac:
o, r = self.execute_command_raw(
'/sbin/sysctl -n hw.memsize', debug=False)
else:
o, r = self.execute_command_raw('cat /proc/meminfo', debug=False)
if o:
return o
|
def get_ram_info(self, win_info=None, mac=False):
if win_info:
if 'Virtual Memory Max Size' not in win_info:
win_info = self.create_windows_info()
o = "Virtual Memory Max Size =" \
+ win_info['Virtual Memory Max Size'] + '\n' \
+ "Virtual Memory Available =" \
+ win_info['Virtual Memory Available'] + '\n' \
+ "Virtual Memory In Use =" + win_info['Virtual Memory In Use']
elif mac:
o, r = self.execute_command_raw(
'/sbin/sysctl -n hw.memsize', debug=False)
else:
o, r = self.execute_command_raw('cat /proc/meminfo', debug=False)
if o:
return o
|
Code the following:
|
def get_membase_build(config, section):
"""
Get the membase build information from the config
:param config: config
:param section: section to get information from
:return: membase build information
"""
membase_build = TestInputBuild()
for option in config.options(section):
if option == 'version':
pass
if option == 'url':
pass
return membase_build
|
Get the membase build information from the config
|
generate doc string for following function:
|
def kill_goxdcr(self):
"""
Kill XDCR process on remote server
:return: None
"""
o, r = self.execute_command("taskkill /F /T /IM goxdcr*")
self.log_command_output(o, r)
|
def kill_goxdcr(self):
o, r = self.execute_command("taskkill /F /T /IM goxdcr*")
self.log_command_output(o, r)
|
give a code to
|
def __init__(self, logger, node_install_info):
"""
Creates an instance of the InstallSteps class.
:param logger:
:param node_install_info:
"""
self.log = logger
self.node_install_info = node_install_info
self.result = True
|
Creates an instance of the InstallSteps class.
|
generate comment:
|
def get_aws_public_hostname(self):
"""
Get aws meta data like public hostnames of an instance from shell
:return: curl output as a list of strings containing public hostnames
"""
output, _ = self.execute_command(
"curl -s http://169.254.169.254/latest/meta-data/public-hostname")
return output[0]
|
def get_aws_public_hostname(self):
output, _ = self.execute_command(
"curl -s http://169.254.169.254/latest/meta-data/public-hostname")
return output[0]
|
generate python code for
|
import os
import uuid
from subprocess import Popen
from shell_util.remote_machine import RemoteMachineInfo
def extract_remote_info(self):
"""
Extract the remote information about the remote server.
This method is used to extract the following information of the remote server:\n
- type of OS distribution (Linux, Windows, macOS)
- ip address
- OS distribution type
- OS architecture
- OS distribution version
- extension of the packages (.deb, .rpm, .exe etc)
- total RAM available
- Number of CPUs
- disk space available
- hostname
- domain
:return: remote info dictionary of type RemoteMachineInfo
"""
# initialize params
os_distro = "linux"
os_version = "default"
is_linux_distro = True
self.use_sudo = False
is_mac = False
self.reconnect_if_inactive()
mac_check_cmd = "sw_vers | grep ProductVersion | awk '{ print $2 }'"
if self.remote:
stdin, stdout, stderro = self._ssh_client.exec_command(mac_check_cmd)
stdin.close()
ver, err = stdout.read(), stderro.read()
else:
p = Popen(mac_check_cmd, shell=True, stdout=PIPE, stderr=PIPE)
ver, err = p.communicate()
if not err and ver:
os_distro = "Mac"
try:
ver = ver.decode()
except AttributeError:
pass
os_version = ver
is_linux_distro = True
is_mac = True
self.use_sudo = False
elif self.remote:
is_mac = False
sftp = self._ssh_client.open_sftp()
filenames = sftp.listdir('/etc/')
os_distro = ''
os_version = ''
is_linux_distro = False
for name in filenames:
if name == 'os-release':
# /etc/os-release - likely standard across linux distros
filename = 'etc-os-release-{0}'.format(uuid.uuid4())
sftp.get(localpath=filename, remotepath='/etc/os-release')
file = open(filename)
line = file.readline()
is_version_id = False
is_pretty_name = False
os_pretty_name = ''
while line and (not is_version_id or not is_pretty_name):
log.debug(line)
if line.startswith('VERSION_ID'):
os_version = line.split('=')[1].replace('"', '')
os_version = os_version.rstrip('\n').rstrip(' ').rstrip('\\l').rstrip(
' ').rstrip('\\n').rstrip(' ')
is_version_id = True
elif line.startswith('PRETTY_NAME'):
os_pretty_name = line.split('=')[1].replace('"', '')
is_pretty_name = True
line = file.readline()
os_distro_dict = {'ubuntu': 'Ubuntu', 'debian': 'Ubuntu',
'mint': 'Ubuntu',
'centos': 'CentOS',
'openshift': 'CentOS',
'amazon linux 2': 'CentOS',
'amazon linux 2023': 'CentOS',
'opensuse': 'openSUSE',
'red': 'Red Hat',
'suse': 'SUSE',
'oracle': 'Oracle Linux',
'almalinux': 'AlmaLinux OS',
'rocky': 'Rocky Linux'}
os_shortname_dict = {'ubuntu': 'ubuntu', 'mint': 'ubuntu',
'debian': 'debian',
'centos': 'centos',
'openshift': 'centos',
'suse': 'suse',
'opensuse': 'suse',
'amazon linux 2': 'amzn2',
'amazon linux 2023': 'al2023',
'red': 'rhel',
'oracle': 'oel',
'almalinux': 'alma',
'rocky': 'rocky'}
log.debug("os_pretty_name:" + os_pretty_name)
if os_pretty_name and "Amazon Linux 2" not in os_pretty_name:
os_name = os_pretty_name.split(' ')[0].lower()
os_distro = os_distro_dict[os_name]
if os_name != 'ubuntu':
os_version = os_shortname_dict[os_name] + " " + os_version.split('.')[0]
else:
os_version = os_shortname_dict[os_name] + " " + os_version
if os_distro:
is_linux_distro = True
log.info("os_distro: " + os_distro + ", os_version: " + os_version +
", is_linux_distro: " + str(is_linux_distro))
file.close()
# now remove this file
os.remove(filename)
break
else:
os_distro = "linux"
os_version = "default"
is_linux_distro = True
self.use_sudo = False
is_mac = False
filenames = []
""" for Amazon Linux 2 only"""
for name in filenames:
if name == 'system-release' and os_distro == "":
# it's a amazon linux 2_distro . let's download this file
filename = 'amazon-linux2-release-{0}'.format(uuid.uuid4())
sftp.get(localpath=filename, remotepath='/etc/system-release')
file = open(filename)
etc_issue = ''
# let's only read the first line
for line in file:
# for SuSE that has blank first line
if line.rstrip('\n'):
etc_issue = line
break
# strip all extra characters
if etc_issue.lower().find('oracle linux') != -1:
os_distro = 'Oracle Linux'
for i in etc_issue:
if i.isdigit():
dist_version = i
break
os_version = "oel{}".format(dist_version)
is_linux_distro = True
break
elif etc_issue.lower().find('amazon linux 2') != -1 or \
etc_issue.lower().find('amazon linux release 2') != -1:
etc_issue = etc_issue.rstrip('\n').rstrip(' ').rstrip('\\l').rstrip(' ').rstrip('\\n').rstrip(
' ')
os_distro = 'Amazon Linux 2'
os_version = etc_issue
is_linux_distro = True
file.close()
# now remove this file
os.remove(filename)
break
""" for centos 7 or rhel8 """
for name in filenames:
if name == "redhat-release" and os_distro == "":
filename = 'redhat-release-{0}'.format(uuid.uuid4())
if self.remote:
sftp.get(localpath=filename, remotepath='/etc/redhat-release')
else:
p = Popen("cat /etc/redhat-release > {0}".format(filename), shell=True, stdout=PIPE, stderr=PIPE)
var, err = p.communicate()
file = open(filename)
redhat_release = ''
for line in file:
redhat_release = line
break
redhat_release = redhat_release.rstrip('\n').rstrip('\\l').rstrip('\\n')
""" in ec2: Red Hat Enterprise Linux Server release 7.2 """
if redhat_release.lower().find('centos') != -1 \
or redhat_release.lower().find('linux server') != -1 \
or redhat_release.lower().find('red hat') != -1:
if redhat_release.lower().find('release 7') != -1:
os_distro = 'CentOS'
os_version = "CentOS 7"
is_linux_distro = True
elif redhat_release.lower().find('release 8') != -1:
os_distro = 'CentOS'
os_version = "CentOS 8"
is_linux_distro = True
elif redhat_release.lower().find('red hat enterprise') != -1:
if "8.0" in redhat_release.lower():
os_distro = "Red Hat"
os_version = "rhel8"
is_linux_distro = True
else:
log.error("Could not find OS name."
"It could be unsupport OS")
file.close()
os.remove(filename)
break
if self.remote:
if self.find_file("/cygdrive/c/Windows", "win.ini"):
log.info("This is windows server!")
is_linux_distro = False
if not is_linux_distro:
win_info = self.__find_windows_info()
info = RemoteMachineInfo()
info.type = win_info['os']
info.windows_name = win_info['os_name']
info.distribution_type = win_info['os']
info.architecture_type = win_info['os_arch']
info.ip = self.ip
info.distribution_version = win_info['os']
info.deliverable_type = 'msi'
info.cpu = self.get_cpu_info(win_info)
info.disk = self.get_disk_info(win_info)
info.ram = self.get_ram_info(win_info)
info.hostname = self.get_hostname()
info.domain = self.get_domain(win_info)
self.info = info
return info
else:
# now run uname -m to get the architechtre type
if self.remote:
stdin, stdout, _ = self._ssh_client.exec_command('uname -m')
stdin.close()
os_arch = ''
text = stdout.read().splitlines()
else:
p = Popen('uname -m', shell=True, stdout=PIPE, stderr=PIPE)
text, err = p.communicate()
os_arch = ''
for line in text:
try:
os_arch += line.decode("utf-8")
except AttributeError:
os_arch += str(line)
# at this point we should know if its a linux or windows ditro
ext = {'Ubuntu': 'deb',
'CentOS': 'rpm',
'Red Hat': 'rpm',
'openSUSE': 'rpm',
'SUSE': 'rpm',
'Oracle Linux': 'rpm',
'Amazon Linux 2023': 'rpm',
'Amazon Linux 2': 'rpm',
'AlmaLinux OS': 'rpm',
'Rocky Linux': 'rpm',
'Mac': 'dmg',
'Debian': 'deb'}.get(os_distro, '')
arch = {'i686': "x86",
'i386': "x86"}.get(os_arch, os_arch)
info = RemoteMachineInfo()
info.type = "Linux"
info.distribution_type = os_distro
info.architecture_type = arch
info.ip = self.ip
try:
info.distribution_version = os_version.decode()
except AttributeError:
info.distribution_version = os_version
info.deliverable_type = ext
info.cpu = self.get_cpu_info(mac=is_mac)
info.disk = self.get_disk_info(mac=is_mac)
info.ram = self.get_ram_info(mac=is_mac)
info.hostname = self.get_hostname()
info.domain = self.get_domain()
self.info = info
log.info("%s - distribution_type: %s, distribution_version: %s"
% (self.server.ip, info.distribution_type,
info.distribution_version))
return info
|
Extract the remote information about the remote server.
This method is used to extract the following information of the remote server:
- type of OS distribution (Linux, Windows, macOS)
- ip address
- OS distribution type
- OS architecture
- OS distribution version
- extension of the packages (.deb, .rpm, .exe etc)
- total RAM available
- Number of CPUs
- disk space available
- hostname
- domain
|
generate python code for
|
def delete_files(self, file_location, debug=False):
"""
Delete the files in the specified location
:param file_location: path to files to delete
:param debug: print debug information if True
:return: None
"""
command = "%s%s" % ("rm -rf ", file_location)
output, error = self.execute_command(command, debug=debug)
if debug:
self.log_command_output(output, error)
|
Delete the files in the specified location
|
generate comment for following function:
|
def cleanup_all_configuration(self, data_path):
"""
Deletes the contents of the parent folder that holds the data and config directories.
Override method for Windows
:param data_path: The path key from the /nodes/self end-point which
looks something like "/opt/couchbase/var/lib/couchbase/data" on
Linux or "c:/Program Files/Couchbase/Server/var/lib/couchbase/data"
on Windows.
:return: None
"""
path = data_path.replace("/data", "")
if "c:/Program Files" in path:
path = path.replace("c:/Program Files", "/cygdrive/c/Program\ Files")
o, r = self.execute_command(f"rm -rf {path}/*")
self.log_command_output(o, r)
|
def cleanup_all_configuration(self, data_path):
path = data_path.replace("/data", "")
if "c:/Program Files" in path:
path = path.replace("c:/Program Files", "/cygdrive/c/Program\ Files")
o, r = self.execute_command(f"rm -rf {path}/*")
self.log_command_output(o, r)
|
generate code for the above:
|
def start_server(self):
"""
Starts the Couchbase server on the remote server.
The method runs the sever from non-default location if it's run as nonroot user. Else from default location.
:return: None
"""
if self.is_couchbase_installed():
if self.nonroot:
cmd = '%s%scouchbase-server \-- -noinput -detached '\
% (self.nr_home_path, LINUX_COUCHBASE_BIN_PATH)
else:
cmd = "systemctl start couchbase-server.service"
o, r = self.execute_command(cmd)
self.log_command_output(o, r)
|
Starts the Couchbase server on the remote server.
The method runs the sever from non-default location if it's run as nonroot user. Else from default location.
|
generate comment.
|
def is_enterprise(self):
"""
Check if the couchbase installed is enterprise edition or not
:return: True if couchbase installed is enterprise edition else False
"""
enterprise = False
runtime_file_path = ""
if self.nonroot:
if self.file_exists("%s/opt/couchbase/etc/" % self.nr_home_path,
"runtime.ini"):
runtime_file_path = "%s/opt/couchbase/etc/" % self.nr_home_path
else:
log.info("couchbase server at {0} may not installed yet in nonroot server"
.format(self.ip))
elif self.file_exists("/opt/couchbase/etc/", "runtime.ini"):
runtime_file_path = "/opt/couchbase/etc/"
else:
log.info("{} - Couchbase server not found".format(self.ip))
output = self.read_remote_file(runtime_file_path, "runtime.ini")
for x in output:
x = x.strip()
if x and "license = enterprise" in x:
enterprise = True
return enterprise
|
def is_enterprise(self):
enterprise = False
runtime_file_path = ""
if self.nonroot:
if self.file_exists("%s/opt/couchbase/etc/" % self.nr_home_path,
"runtime.ini"):
runtime_file_path = "%s/opt/couchbase/etc/" % self.nr_home_path
else:
log.info("couchbase server at {0} may not installed yet in nonroot server"
.format(self.ip))
elif self.file_exists("/opt/couchbase/etc/", "runtime.ini"):
runtime_file_path = "/opt/couchbase/etc/"
else:
log.info("{} - Couchbase server not found".format(self.ip))
output = self.read_remote_file(runtime_file_path, "runtime.ini")
for x in output:
x = x.strip()
if x and "license = enterprise" in x:
enterprise = True
return enterprise
|
give python code to
|
def stop_indexer(self):
"""
Stop indexer process on remote server
:return: None
"""
o, r = self.execute_command("kill -SIGSTOP $(pgrep indexer)")
self.log_command_output(o, r, debug=False)
|
Stop indexer process on remote server
|
generate code for the above:
|
def change_log_level(self, new_log_level):
"""
Change the log level of couchbase processes on a remote server
:param new_log_level: new log level to set
:return: None
"""
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)
|
Change the log level of couchbase processes on a remote server
|
generate python code for the following
|
def stop_network(self, stop_time):
"""
Stop the network for given time period and then restart the network
on the machine.
Override method for Windows
:param stop_time: Time duration for which the network service needs
to be down in the machine
:return: None
"""
command = "net stop Netman && timeout {} && net start Netman"
output, error = self.execute_command(command.format(stop_time))
self.log_command_output(output, error)
|
Stop the network for given time period and then restart the network
on the machine.
Override method for Windows
|
give python code to
|
def init_cluster(self, node):
"""
Initializes Couchbase cluster
Override method for Unix
:param node: server object
:return: True on success
"""
return True
|
Initializes Couchbase cluster
Override method for Unix
|
generate comment:
|
def connect_with_user(self, user="root"):
"""
Connect to the remote server with given user
Override method since this is not required for Unix
:param user: user to connect to remote server with
:return: None
"""
return
|
def connect_with_user(self, user="root"):
return
|
give python code to
|
def get_elastic_config(config, section, global_properties):
"""
Get elasticsearch config from config
:param config: config
:param section: section to get elasticsearch property
:param global_properties: dict of global properties
:return: elasticsearch server
"""
server = TestInputServer()
options = config.options(section)
for option in options:
if option == 'ip':
server.ip = config.get(section, option)
if option == 'port':
server.port = config.get(section, option)
if option == 'es_username':
server.es_username = config.get(section, option)
if option == 'es_password':
server.es_password = config.get(section, option)
if option == 'username':
server.ssh_username = config.get(section, option)
if option == 'password':
server.ssh_password = config.get(section, option)
if server.ssh_username == '' and 'username' in global_properties:
server.ssh_username = global_properties['username']
if server.ssh_password == '' and 'password' in global_properties:
server.ssh_password = global_properties['password']
return server
|
Get elasticsearch config from config
|
generate python code for the following
|
def get_full_hostname(self):
"""
Get full hostname of a server.
:return: hostname string
"""
if not info.domain:
return None
self.log.info("%s - Hostname is %s" % (self.ip, info.hostname[0]))
if info.domain[0]:
if info.domain[0][0]:
self.log.info("domain name of this {0} is {1}"
.format(self.ip, info.domain[0][0]))
if info.domain[0][0] in info.hostname[0]:
return "{0}".format(info.hostname[0])
else:
return "{0}.{1}".format(info.hostname[0], info.domain[0][0])
else:
mesg = "Need to set domain name in server {0} like 'sc.couchbase.com'"\
.format(self.ip)
raise Exception(mesg)
else:
return "{0}.{1}".format(info.hostname[0], 'sc.couchbase.com')
|
Get full hostname of a server.
|
generate doc string for following function:
|
def change_port_static(self, new_port):
"""
Change Couchbase ports for rest, mccouch, memcached, capi to new port
:param new_port: new port to change the ports to
:return: None
"""
# ADD NON_ROOT user config_details
log.info("=========CHANGE PORTS for REST: %s, MCCOUCH: %s,MEMCACHED: %s, CAPI: %s==============="
% (new_port, new_port + 1, new_port + 2, 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 '/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 change_port_static(self, new_port):
# ADD NON_ROOT user config_details
log.info("=========CHANGE PORTS for REST: %s, MCCOUCH: %s,MEMCACHED: %s, CAPI: %s==============="
% (new_port, new_port + 1, new_port + 2, 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 '/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)
|
generate python code for
|
def execute_non_sudo_command(self, command, info=None, debug=True,
use_channel=False):
"""
Execute command in non-sudo mode.
:param command: command to be executed
:param info: None
:param debug: print debug information in logs if True
:param use_channel: use an SSH channel if True.
:return: Command output as a list of lines.
"""
return self.execute_command_raw(command, debug=debug,
use_channel=use_channel)
|
Execute command in non-sudo mode.
|
generate code for the above:
|
def cpu_stress(self, stop_time):
"""
Applies CPU stress for a specified duration on the 20 CPU cores.
Override method for Windows
:param stop_time: duration to apply the CPU stress for.
:return: None
"""
raise NotImplementedError
|
Applies CPU stress for a specified duration on the 20 CPU cores.
Override method for Windows
|
generate comment for above
|
def download_build_locally(self, build_url):
"""
Downloads the Couchbase build locally
:param build_url: Download url to download the build from
:return: tuple containing the path to the download build file as well as the resulting HTTPMessage object.
"""
f_path = "{}/{}".format(".", build_url.split('/')[-1])
f, r = urllib.request.urlretrieve(build_url, f_path)
return f, r
|
def download_build_locally(self, build_url):
f_path = "{}/{}".format(".", build_url.split('/')[-1])
f, r = urllib.request.urlretrieve(build_url, f_path)
return f, r
|
generate doc string for following function:
|
def change_env_variables(self, dict):
"""
Change environment variables mentioned in dictionary and restart Couchbase server
:param dict: key value pair of environment variables and their values to change to
:return: None
"""
prefix = "\\n "
shell = self._ssh_client.invoke_shell()
init_file = "couchbase-server"
file_path = "/opt/couchbase/bin/"
environmentVariables = ""
backupfile = file_path + init_file + ".bak"
sourceFile = file_path + init_file
o, r = self.execute_command("cp " + sourceFile + " " + backupfile)
self.log_command_output(o, r)
command = "sed -i 's/{0}/{0}".format("ulimit -l unlimited")
for key in list(dict.keys()):
o, r = self.execute_command(
"sed -i 's/{1}.*//' {0}".format(sourceFile, key))
self.log_command_output(o, r)
o, r = self.execute_command(
"sed -i 's/export ERL_FULLSWEEP_AFTER/export "
"ERL_FULLSWEEP_AFTER\\n{1}={2}\\nexport {1}/' {0}"
.format(sourceFile, key, dict[key]))
self.log_command_output(o, r)
for key in list(dict.keys()):
environmentVariables += prefix \
+ 'export {0}={1}'.format(key, dict[key])
command += environmentVariables + "/'" + " " + sourceFile
o, r = self.execute_command(command)
self.log_command_output(o, r)
# Restart Couchbase
o, r = self.execute_command("service couchbase-server restart")
self.log_command_output(o, r)
shell.close()
|
def change_env_variables(self, dict):
prefix = "\\n "
shell = self._ssh_client.invoke_shell()
init_file = "couchbase-server"
file_path = "/opt/couchbase/bin/"
environmentVariables = ""
backupfile = file_path + init_file + ".bak"
sourceFile = file_path + init_file
o, r = self.execute_command("cp " + sourceFile + " " + backupfile)
self.log_command_output(o, r)
command = "sed -i 's/{0}/{0}".format("ulimit -l unlimited")
for key in list(dict.keys()):
o, r = self.execute_command(
"sed -i 's/{1}.*//' {0}".format(sourceFile, key))
self.log_command_output(o, r)
o, r = self.execute_command(
"sed -i 's/export ERL_FULLSWEEP_AFTER/export "
"ERL_FULLSWEEP_AFTER\\n{1}={2}\\nexport {1}/' {0}"
.format(sourceFile, key, dict[key]))
self.log_command_output(o, r)
for key in list(dict.keys()):
environmentVariables += prefix \
+ 'export {0}={1}'.format(key, dict[key])
command += environmentVariables + "/'" + " " + sourceFile
o, r = self.execute_command(command)
self.log_command_output(o, r)
# Restart Couchbase
o, r = self.execute_command("service couchbase-server restart")
self.log_command_output(o, r)
shell.close()
|
from shell_util.remote_machine import RemoteMachineProcess
def is_process_running(self, process_name):
"""
Check if a process is running currently
Override method for Windows
:param process_name: name of the process to check
:return: True if process is running else False
"""
self.log.info("%s - Checking for process %s" % (self.ip, process_name))
output, error = self.execute_command(
'tasklist | grep {0}'.format(process_name), debug=False)
if error or output == [""] or output == []:
return None
words = output[0].split(" ")
words = [x for x in words if x != ""]
process = RemoteMachineProcess()
process.pid = words[1]
process.name = words[0]
self.log.debug("Process is running: %s" % words)
return process
|
Check if a process is running currently
Override method for Windows
|
|
generate comment for following function:
|
def monitor_process_memory(self, process_name, duration_in_seconds=180,
end=False):
"""
Monitor this process and return list of memories in 7 secs interval till the duration specified
:param process_name: the name of the process to monitor
:param duration_in_seconds: the duration to monitor the process till, in seconds
:param end: False
:return: list of virtual size (in kB) and resident set size for
"""
end_time = time.time() + float(duration_in_seconds)
count = 0
vsz = []
rss = []
while time.time() < end_time and not end:
# get the process list
process = self.is_process_running(process_name)
if process:
vsz.append(process.vsz)
rss.append(process.rss)
else:
log.info("{0}:process {1} is not running. Wait for 2 seconds"
.format(self.remote_shell.ip, process_name))
count += 1
self.sleep(2)
if count == 5:
log.error("{0}:process {1} is not running at all."
.format(self.remote_shell.ip, process_name))
exit(1)
log.info("sleep for 7 seconds before poll new processes")
self.sleep(7)
return vsz, rss
|
def monitor_process_memory(self, process_name, duration_in_seconds=180,
end=False):
end_time = time.time() + float(duration_in_seconds)
count = 0
vsz = []
rss = []
while time.time() < end_time and not end:
# get the process list
process = self.is_process_running(process_name)
if process:
vsz.append(process.vsz)
rss.append(process.rss)
else:
log.info("{0}:process {1} is not running. Wait for 2 seconds"
.format(self.remote_shell.ip, process_name))
count += 1
self.sleep(2)
if count == 5:
log.error("{0}:process {1} is not running at all."
.format(self.remote_shell.ip, process_name))
exit(1)
log.info("sleep for 7 seconds before poll new processes")
self.sleep(7)
return vsz, rss
|
generate comment:
|
def kill_cbft_process(self):
"""
Kill the full text search process on remote server
:return: output and error of command killing FTS process
"""
o, r = self.execute_command("killall -9 cbft")
self.log_command_output(o, r)
if r and r[0] and "command not found" in r[0]:
o, r = self.execute_command("pkill cbft")
self.log_command_output(o, r)
return o, r
|
def kill_cbft_process(self):
o, r = self.execute_command("killall -9 cbft")
self.log_command_output(o, r)
if r and r[0] and "command not found" in r[0]:
o, r = self.execute_command("pkill cbft")
self.log_command_output(o, r)
return o, r
|
Code the following:
|
import time
from time import sleep
def monitor_process_memory(self, process_name, duration_in_seconds=180,
end=False):
"""
Monitor this process and return list of memories in 7 secs interval till the duration specified
:param process_name: the name of the process to monitor
:param duration_in_seconds: the duration to monitor the process till, in seconds
:param end: False
:return: list of virtual size (in kB) and resident set size for
"""
end_time = time.time() + float(duration_in_seconds)
count = 0
vsz = []
rss = []
while time.time() < end_time and not end:
# get the process list
process = self.is_process_running(process_name)
if process:
vsz.append(process.vsz)
rss.append(process.rss)
else:
log.info("{0}:process {1} is not running. Wait for 2 seconds"
.format(self.remote_shell.ip, process_name))
count += 1
self.sleep(2)
if count == 5:
log.error("{0}:process {1} is not running at all."
.format(self.remote_shell.ip, process_name))
exit(1)
log.info("sleep for 7 seconds before poll new processes")
self.sleep(7)
return vsz, rss
|
Monitor this process and return list of memories in 7 secs interval till the duration specified
|
generate code for the following
|
import os
import paramiko
import signal
from time import sleep
def ssh_connect_with_retries(self, ip, ssh_username, ssh_password, ssh_key,
exit_on_failure=False, max_attempts_connect=5,
backoff_time=10):
"""
Connect to the remote server with given user and password, with exponential backoff delay
:param ip: IP address of the remote server to connect to
:param ssh_username: user to connect to remote server with
:param ssh_password: password to connect to remote server with
:param ssh_key: ssh key to connect to remote server with
:param exit_on_failure: exit the function on error if True
:param max_attempts_connect: max number of attempts before giving up
:param backoff_time: time to wait between attempts
:return: None
"""
attempt = 0
is_ssh_ok = False
while not is_ssh_ok and attempt < max_attempts_connect:
attempt += 1
log.info("SSH Connecting to {} with username:{}, attempt#{} of {}"
.format(ip, ssh_username, attempt, max_attempts_connect))
try:
if self.remote and ssh_key == '':
self._ssh_client.connect(
hostname=ip.replace('[', '').replace(']', ''),
username=ssh_username, password=ssh_password,
look_for_keys=False)
elif self.remote:
self._ssh_client.connect(
hostname=ip.replace('[', '').replace(']', ''),
username=ssh_username, key_filename=ssh_key,
look_for_keys=False)
is_ssh_ok = True
except paramiko.BadHostKeyException as bhke:
log.error("Can't establish SSH (Invalid host key) to {}: {}"
.format(ip, bhke))
raise Exception(bhke)
except Exception as e:
log.error("Can't establish SSH (unknown reason) to {}: {}"
.format(ip, e, ssh_username, ssh_password))
if attempt < max_attempts_connect:
log.info("Retrying with back off delay for {} secs."
.format(backoff_time))
self.sleep(backoff_time)
backoff_time *= 2
if not is_ssh_ok:
error_msg = "-->No SSH connectivity to {} even after {} times!\n".format(self.ip, attempt)
log.error(error_msg)
if exit_on_failure:
log.error("Exit on failure: killing process")
os.kill(os.getpid(), signal.SIGKILL)
else:
log.error("No exit on failure, raise exception")
raise Exception(error_msg)
else:
log.info("SSH Connected to {} as {}".format(ip, ssh_username))
|
Connect to the remote server with given user and password, with exponential backoff delay
|
def get_memcache_pid(self):
"""
Get the pid of memcached process
:return: pid of memcached process
"""
o, _ = self.execute_command(
"ps -eo comm,pid | awk '$1 == \"memcached\" { print $2 }'")
return o[0]
|
def get_memcache_pid(self):
o, _ = self.execute_command(
"ps -eo comm,pid | awk '$1 == \"memcached\" { print $2 }'")
return o[0]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.