instruction
stringclasses 14
values | output
stringlengths 105
12.9k
| input
stringlengths 0
4.12k
|
|---|---|---|
generate code for the above:
|
import install_util.constants
from install_util.constants.build import BuildUrl
from shell_util.remote_connection import RemoteMachineShellConnection
def __construct_build_url(self, is_debuginfo_build=False):
"""
Constructs the build url for the given node.
This url is used to download the installation package.
:param is_debuginfo_build: gets debug_info build url if True
:return: build url
"""
file_name = None
build_version = self.node_install_info.version.split("-")
os_type = self.node_install_info.os_type
node_info = RemoteMachineShellConnection.get_info_for_server(
self.node_install_info.server)
# Decide between release / regular build URL path
if len(build_version) == 1:
# Release build url
url_path = "http://{}/{}/{}" \
.format(BuildUrl.CB_DOWNLOAD_SERVER,
BuildUrl.CB_RELEASE_URL_PATH,
build_version[0])
else:
# Build_number specific url
main_version = ".".join(build_version[0].split(".")[:2])
# Reference: builds/latestbuilds/couchbase-server/trinity/1000
url_path = "http://{}/{}/{}/{}" \
.format(BuildUrl.CB_DOWNLOAD_SERVER,
BuildUrl.CB_LATESTBUILDS_URL_PATH,
BuildUrl.CB_VERSION_NAME[main_version],
build_version[1])
build_version = "-".join(build_version)
file_prefix = "{}-{}" \
.format(BuildUrl.CB_BUILD_FILE_PREFIX,
self.node_install_info.edition)
if os_type in install_util.constants.build.X86:
# couchbase-server-enterprise-7.1.5-linux.x86_64.rpm
# couchbase-server-enterprise-debuginfo-7.1.5-linux.x86_64.rpm
if is_debuginfo_build:
file_prefix = "{}-{}".format(file_prefix, "debuginfo")
os_type = "linux"
if float(build_version[:3]) < 7.1:
os_type = self.node_install_info.os_type
file_name = "{}-{}-{}.{}.{}" \
.format(file_prefix,
build_version,
os_type,
node_info.architecture_type,
node_info.deliverable_type)
elif os_type in install_util.constants.build.LINUX_AMD64:
# TODO: Check install_utils.py L1127 redundant code presence
# couchbase-server-enterprise_7.1.5-linux_amd64.deb
# couchbase-server-enterprise-dbg_7.1.5-linux_amd64.deb
if is_debuginfo_build:
file_prefix = "{}-{}".format(file_prefix, "dbg")
os_type = "linux"
if float(build_version[:3]) < 7.1:
os_type = self.node_install_info.os_type
file_name = "{}_{}-{}_{}.{}" \
.format(file_prefix,
build_version,
os_type,
"amd64",
node_info.deliverable_type)
elif os_type in install_util.constants.build.WINDOWS_SERVER:
# couchbase-server-enterprise_6.5.0-4557-windows_amd64.msi
if "windows" in self.node_install_info.os_type:
self.node_install_info.deliverable_type = "msi"
file_name = "{}_{}-{}_{}.{}" \
.format(file_prefix,
build_version,
self.node_install_info.os_type,
"amd64",
node_info.deliverable_type)
elif os_type in install_util.constants.build.MACOS_VERSIONS:
# couchbase-server-enterprise_6.5.0-4557-macos_x86_64.dmg
file_name = "{}_{}-{}_{}-{}.{}" \
.format(file_prefix,
build_version,
"macos",
node_info.architecture_type,
"unnotarized",
node_info.deliverable_type)
else:
self.result = False
self.log.critical("Unsupported os_type '{}' for build_url"
.format(self.node_install_info.os_type))
return "{}/{}".format(url_path, file_name)
|
Constructs the build url for the given node.
This url is used to download the installation package.
|
def configure_log_location(self, new_log_location):
"""
Configure the log location for Couchbase server on remote server
:param new_log_location: path to new location to store logs
:return: None
"""
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)
|
Configure the log location for Couchbase server on remote server
|
|
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
|
|
generate python code for the above
|
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
|
give a code to
|
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 python code for
|
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)
|
Stop membase process on remote server
|
give a code to
|
def is_enterprise(self):
"""
Check if the couchbase installed is enterprise edition or not
Override method for Windows
:return: True if couchbase installed is enterprise edition else False
"""
raise NotImplementedError
|
Check if the couchbase installed is enterprise edition or not
Override method for Windows
|
generate python code for the above
|
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 above:
|
def stop_memcached(self):
"""
Stop memcached process on remote server
:return: None
"""
o, r = self.execute_command("kill -SIGSTOP $(pgrep memcached)")
self.log_command_output(o, r, debug=False)
|
Stop memcached process on remote server
|
generate comment.
|
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)
|
def enable_disk_readonly(self, disk_location):
o, r = self.execute_command("chmod -R 444 {}".format(disk_location))
self.log_command_output(o, r)
|
generate python code for the following
|
def check_directory_exists(self, remote_path):
"""
Check if the directory exists in the remote path
:param remote_path: remote path of the directory to be checked
:return: True if the directory exists else False
"""
sftp = self._ssh_client.open_sftp()
try:
log.info("Checking if the directory {0} exists or not.".format(remote_path))
sftp.stat(remote_path)
except IOError as e:
log.info(f'Directory at {remote_path} DOES NOT exist.')
sftp.close()
return False
log.info("Directory at {0} exist.")
sftp.close()
return True
|
Check if the directory exists in the remote path
|
generate python code for
|
from subprocess import Popen
def remove_directory_recursive(self, remote_path):
"""
Recursively remove directory in remote machine.
:param remote_path: directory path to remove
:return: True if successful else False
"""
if self.remote:
sftp = self._ssh_client.open_sftp()
try:
log.info("removing {0} directory...".format(remote_path))
self.rmtree(sftp, 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)
p.communicate()
except IOError:
return False
return True
|
Recursively remove directory in remote machine.
|
give a code to
|
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 comment.
|
def start_couchbase(self):
"""
Starts couchbase on remote server
:return: None
"""
retry = 0
running = self.is_couchbase_running()
while not running and retry < 3:
log.info("Starting couchbase server")
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
self.sleep(5, "Waiting for 5 secs to start...on " + self.info.ip)
running = self.is_couchbase_running()
retry = retry + 1
if not running and retry >= 3:
sys.exit("Failed to start Couchbase server on " + self.info.ip)
|
def start_couchbase(self):
retry = 0
running = self.is_couchbase_running()
while not running and retry < 3:
log.info("Starting couchbase server")
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
self.sleep(5, "Waiting for 5 secs to start...on " + self.info.ip)
running = self.is_couchbase_running()
retry = retry + 1
if not running and retry >= 3:
sys.exit("Failed to start Couchbase server on " + self.info.ip)
|
generate comment.
|
def enable_diag_eval_on_non_local_hosts(self, state=True):
"""
Enable diag/eval to be run on non-local hosts.
:param state: enable diag/eval on non-local hosts if True
:return: Command output and error if any.
"""
rest_username = self.server.rest_username
rest_password = self.server.rest_password
protocol = "https://" if self.port == "18091" else "http://"
command = "curl --silent --show-error {4}{0}:{1}@localhost:{2}/diag/eval -X POST -d " \
"'ns_config:set(allow_nonlocal_eval, {3}).'"\
.format(rest_username, rest_password, self.port,
state.__str__().lower(), protocol)
output, error = self.execute_command(command)
self.log.info(output)
try:
output = output.decode()
except AttributeError:
pass
return output, error
|
def enable_diag_eval_on_non_local_hosts(self, state=True):
rest_username = self.server.rest_username
rest_password = self.server.rest_password
protocol = "https://" if self.port == "18091" else "http://"
command = "curl --silent --show-error {4}{0}:{1}@localhost:{2}/diag/eval -X POST -d " \
"'ns_config:set(allow_nonlocal_eval, {3}).'"\
.format(rest_username, rest_password, self.port,
state.__str__().lower(), protocol)
output, error = self.execute_command(command)
self.log.info(output)
try:
output = output.decode()
except AttributeError:
pass
return output, error
|
give a code to
|
from subprocess import Popen
def remove_directory_recursive(self, remote_path):
"""
Recursively remove directory in remote machine.
:param remote_path: directory path to remove
:return: True if successful else False
"""
if self.remote:
sftp = self._ssh_client.open_sftp()
try:
log.info("removing {0} directory...".format(remote_path))
self.rmtree(sftp, 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)
p.communicate()
except IOError:
return False
return True
|
Recursively remove directory in remote machine.
|
def file_exists(self, remotepath, filename, pause_time=30):
"""
Check if file exists in remote machine
:param remotepath: path of the file to check
:param filename: filename of the file to check
:param pause_time: time between each command execution in seconds
:return: True if file exists in remote machine else False
"""
sftp = self._ssh_client.open_sftp()
try:
if "Program" in remotepath:
if "Program\\" in remotepath:
remotepath = remotepath.replace("Program\\", "Program")
output, _ = self.execute_command("cat '{0}{1}'".format(remotepath, filename))
if output and output[0]:
return True
else:
return False
filenames = sftp.listdir_attr(remotepath)
for name in filenames:
if filename in name.filename and int(name.st_size) > 0:
sftp.close()
return True
elif filename in name.filename and int(name.st_size) == 0:
if name.filename == NR_INSTALL_LOCATION_FILE:
continue
log.info("File {0} will be deleted".format(filename))
if not remotepath.endswith("/"):
remotepath += "/"
self.execute_command("rm -rf {0}*{1}*".format(remotepath, filename))
self.sleep(pause_time, "** Network or sever may be busy. **"\
"\nWait {0} seconds before executing next instrucion"\
.format(pause_time))
sftp.close()
return False
except IOError:
return False
|
Check if file exists in remote machine
|
|
give a 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 python code for the following
|
def file_exists(self, remotepath, filename, pause_time=30):
"""
Check if file exists in remote machine
:param remotepath: path of the file to check
:param filename: filename of the file to check
:param pause_time: time between each command execution in seconds
:return: True if file exists in remote machine else False
"""
sftp = self._ssh_client.open_sftp()
try:
if "Program" in remotepath:
if "Program\\" in remotepath:
remotepath = remotepath.replace("Program\\", "Program")
output, _ = self.execute_command("cat '{0}{1}'".format(remotepath, filename))
if output and output[0]:
return True
else:
return False
filenames = sftp.listdir_attr(remotepath)
for name in filenames:
if filename in name.filename and int(name.st_size) > 0:
sftp.close()
return True
elif filename in name.filename and int(name.st_size) == 0:
if name.filename == NR_INSTALL_LOCATION_FILE:
continue
log.info("File {0} will be deleted".format(filename))
if not remotepath.endswith("/"):
remotepath += "/"
self.execute_command("rm -rf {0}*{1}*".format(remotepath, filename))
self.sleep(pause_time, "** Network or sever may be busy. **"\
"\nWait {0} seconds before executing next instrucion"\
.format(pause_time))
sftp.close()
return False
except IOError:
return False
|
Check if file exists in remote machine
|
generate comment.
|
def stop_server(self):
"""
Stops the Couchbase server on the remote server.
The method stops the server from non-default location if it's run as nonroot user. Else from default location.
:param os:
:return: None
"""
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
|
def stop_server(self):
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
|
Code the following:
|
def reset_env_variables(self):
"""
Reset environment previously set and restart couchbase server
:return: None
"""
shell = self._ssh_client.invoke_shell()
init_file = "service_start.bat"
file_path = "/cygdrive/c/Program\ Files/Couchbase/Server/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("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()
|
Reset environment previously set and restart couchbase server
|
Code the following:
|
def stop_network(self, stop_time):
"""
Stop the network for given time period and then restart the network
on the machine.
:param stop_time: Time duration for which the network service needs
to be down in the machine
:return: None
"""
command = "nohup service network stop && sleep {} " \
"&& service network start &"
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.
|
generate code for the following
|
from shell_util.remote_connection import RemoteMachineShellConnection
def check_server_state(self, servers):
"""
Checks if the servers are reachable
:param servers: list of servers to check
:return: True if the servers are all reachable else False
"""
result = True
reachable = list()
unreachable = list()
for server in servers:
try:
shell = RemoteMachineShellConnection(server)
shell.disconnect()
reachable.append(server.ip)
except Exception as e:
self.log.error(e)
unreachable.append(server.ip)
if len(unreachable) > 0:
self.log.info("-" * 100)
for server in unreachable:
self.log.error("INSTALL FAILED ON: \t{0}".format(server))
self.log.info("-" * 100)
for server in reachable:
self.log.info("INSTALL COMPLETED ON: \t{0}".format(server))
self.log.info("-" * 100)
result = False
return result
|
Checks if the servers are reachable
|
Code the following:
|
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
|
Get the hostname of the remote server.
|
generate code for the following
|
def enable_packet_loss(self):
"""
Changes network to lose 25% of packets using traffic control
This is used to simulate a network environment where approximately 25% of packets are lost.
:return: None
"""
o, r = self.execute_command("tc qdisc add dev eth0 root netem loss 25%")
self.log_command_output(o, r)
|
Changes network to lose 25% of packets using traffic control
This is used to simulate a network environment where approximately 25% of packets are lost.
|
give a code to
|
def is_couchbase_running(self):
"""
Checks if couchbase is currently running on the remote server
:return: True if couchbase is running else False
"""
o = self.is_process_running('erl.exe')
if o is not None:
return True
return False
|
Checks if couchbase is currently running on the remote server
|
generate comment for above
|
def stop_couchbase(self, num_retries=5, poll_interval=10):
"""
Stop couchbase service on remote server
:param num_retries: Number of times to retry stopping couchbase
:param poll_interval: interval between each retry attempt
:return: None
"""
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
is_server_stopped = False
retries = num_retries
while not is_server_stopped and retries > 0:
self.sleep(poll_interval, "Wait to stop service completely")
is_server_stopped = self.__check_if_cb_service_stopped("couchbaseserver")
retries -= 1
|
def stop_couchbase(self, num_retries=5, poll_interval=10):
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
is_server_stopped = False
retries = num_retries
while not is_server_stopped and retries > 0:
self.sleep(poll_interval, "Wait to stop service completely")
is_server_stopped = self.__check_if_cb_service_stopped("couchbaseserver")
retries -= 1
|
generate comment for following function:
|
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 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.
|
give a code to
|
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.
|
generate comment for above
|
def configure_log_location(self, new_log_location):
"""
Configure the log location for Couchbase server on remote server
:param new_log_location: path to new location to store logs
:return: None
"""
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 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 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
|
|
give python code to
|
def get_bkrs_client_config(config, section, global_properties,
ui_settings):
"""
Get back up restore client configuration
:param config: config
:param section: section to get configuration from
:param global_properties: dict of global properties
:param ui_settings: TestInputMembaseSetting object with membase settings
:return: TestInputServer with backup restore client information
"""
server = TestInputServer()
options = config.options(section)
for option in options:
if option == 'ip':
server.ip = config.get(section, option)
if option == 'password':
server.ssh_password = config.get(section, option)
if option == 'port':
server.port = config.get(section, option)
if 'username' not in options:
server.ssh_username = global_properties['username']
if 'password' not in options:
server.ssh_password = global_properties['password']
if 'port' not in option:
server.port = global_properties['port']
if ui_settings is None:
try:
ui_settings = TestInputParser.get_membase_settings(config, "membase")
except Exception:
raise Exception("Ini file needs 'membase' section")
server.rest_username = ui_settings.rest_username
server.rest_password = ui_settings.rest_password
server.bkrs_client = True
return server
|
Get back up restore client configuration
|
give a code to
|
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 python code for
|
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
|
Code the following:
|
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
|
def read_remote_file(self, remote_path, filename):
"""
Reads the content of a remote file specified by the path.
:param remote_path: Remote path to read the file from
:param filename: Name of the file to read.
:return: string content of the file
"""
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 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
|
|
generate python code for the above
|
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
|
Windows process utility. This adds firewall rules to Windows system.
If a previously suspended process is detected, it continues with the process instead.
|
give python code to
|
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
|
def run(self):
"""
Runs the NodeInstaller thread to run various installation steps in the remote server
:return: None
"""
installer = InstallSteps(self.log, self.node_install_info)
node_installer = installer.get_node_installer(
self.node_install_info)
for step in self.steps:
self.log.info("{} - Running '{}'"
.format(self.node_install_info.server.ip, step))
if step == "populate_build_url":
# To download the main build url
self.node_install_info.state = "construct_build_url"
installer.populate_build_url()
elif step == "populate_debug_build_url":
# To download the debug_info build url for backtraces
self.node_install_info.state = "construct_debug_build_url"
installer.populate_debug_build_url()
elif step == "check_url_status":
self.node_install_info.state = "checking_url_status"
installer.check_url_status(self.node_install_info.build_url)
if self.node_install_info.debug_build_url:
installer.check_url_status(
self.node_install_info.debug_build_url)
elif step == "local_download_build":
self.node_install_info.state = "downloading_build_on_executor"
build_urls = [self.node_install_info.build_url]
if self.node_install_info.debug_build_url:
build_urls.append(self.node_install_info.debug_build_url)
for build_url in build_urls:
f_name, res = installer.download_build_locally(build_url)
self.log.debug("File saved as '{}'".format(f_name))
self.log.debug("File size: {}".format(res["Content-Length"]))
self.log.debug("File create date: {}".format(res["Date"]))
elif step == "copy_local_build_to_server":
self.node_install_info.state = "copying_build_to_remote_server"
build_urls = [self.node_install_info.build_url]
if self.node_install_info.debug_build_url:
build_urls.append(self.node_install_info.build_url)
for build_url in build_urls:
installer.result = installer.result and \
installer.copy_build_to_server(node_installer,
build_url)
elif step == "download_build":
self.node_install_info.state = "downloading_build"
installer.download_build(node_installer,
self.node_install_info.build_url)
if self.node_install_info.debug_build_url:
installer.download_build(node_installer,
self.node_install_info.build_url)
elif step == "uninstall":
self.node_install_info.state = "uninstalling"
node_installer.uninstall()
elif step == "deep_cleanup":
self.node_install_info.state = "deep_cleaning"
elif step == "pre_install":
self.node_install_info.state = "pre_install_procedure"
elif step == "install":
self.node_install_info.state = "installing"
node_installer.install(self.node_install_info.build_url)
node_installer.post_install()
elif step == "init_cluster":
self.node_install_info.state = "init_cluster"
node_installer.init_cluster(self.node_install_info.server)
elif step == "post_install":
self.node_install_info.state = "post_install_procedure"
elif step == "post_install_cleanup":
self.node_install_info.state = "post_install_cleanup"
else:
self.log.critical("Invalid step '{}'".format(step))
installer.result = False
if installer.result is False:
break
node_installer.shell.disconnect()
self.result = installer.result
|
Runs the NodeInstaller thread to run various installation steps in the remote server
|
|
generate comment.
|
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 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 python code for the following
|
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 comment for above
|
def kill_erlang(self, os="unix", 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("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)
o, r = self.execute_command("tasklist | grep erl.exe")
kill_all = False
count = 0
while len(o) >= 1 and not kill_all:
if o and "erl.exe" in o[0]:
self.execute_command("taskkill /F /T /IM erl.exe*")
self.sleep(1)
o, r = self.execute_command("tasklist | grep erl.exe")
if len(o) == 0:
kill_all = True
log.info("all erlang processes were killed")
else:
count += 1
if count == 5:
log.error("erlang process is not killed")
break
|
def kill_erlang(self, os="unix", delay=0):
if delay:
time.sleep(delay)
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)
o, r = self.execute_command("tasklist | grep erl.exe")
kill_all = False
count = 0
while len(o) >= 1 and not kill_all:
if o and "erl.exe" in o[0]:
self.execute_command("taskkill /F /T /IM erl.exe*")
self.sleep(1)
o, r = self.execute_command("tasklist | grep erl.exe")
if len(o) == 0:
kill_all = True
log.info("all erlang processes were killed")
else:
count += 1
if count == 5:
log.error("erlang process is not killed")
break
|
generate python code for
|
def populate_build_url(self):
"""
Populates the build url variable.
:return: None
"""
self.node_install_info.build_url = self.__construct_build_url()
self.log.info("{} - Build url :: {}"
.format(self.node_install_info.server.ip,
self.node_install_info.build_url))
|
Populates the build url variable.
|
generate python code for
|
def get_disk_info(self, win_info=None, mac=False):
"""
Get disk info of the remote server
:param win_info: Windows info in case of windows
:param mac: Get info for macOS if True
:return: Disk info of the remote server if found else None
"""
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 the remote server
|
generate 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.
:param stop_time: Time duration for which the network service needs
to be down in the machine
:return: None
"""
command = "nohup service network stop && sleep {} " \
"&& service network start &"
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.
|
generate python code for the above
|
def get_bkrs_client_config(config, section, global_properties,
ui_settings):
"""
Get back up restore client configuration
:param config: config
:param section: section to get configuration from
:param global_properties: dict of global properties
:param ui_settings: TestInputMembaseSetting object with membase settings
:return: TestInputServer with backup restore client information
"""
server = TestInputServer()
options = config.options(section)
for option in options:
if option == 'ip':
server.ip = config.get(section, option)
if option == 'password':
server.ssh_password = config.get(section, option)
if option == 'port':
server.port = config.get(section, option)
if 'username' not in options:
server.ssh_username = global_properties['username']
if 'password' not in options:
server.ssh_password = global_properties['password']
if 'port' not in option:
server.port = global_properties['port']
if ui_settings is None:
try:
ui_settings = TestInputParser.get_membase_settings(config, "membase")
except Exception:
raise Exception("Ini file needs 'membase' section")
server.rest_username = ui_settings.rest_username
server.rest_password = ui_settings.rest_password
server.bkrs_client = True
return server
|
Get back up restore client configuration
|
Code the following:
|
def enable_disk_readonly(self, disk_location):
"""
Enables read-only mode for the specified disk location.
Override method for Windows
:param disk_location: disk location to enable read-only mode.
:return: None
"""
raise NotImplementedError
|
Enables read-only mode for the specified disk location.
Override method for Windows
|
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.
|
|
def reset_env_variables(self):
"""
Reset environment previously set and restart couchbase server
:return: None
"""
shell = self._ssh_client.invoke_shell()
init_file = "service_start.bat"
file_path = "/cygdrive/c/Program\ Files/Couchbase/Server/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("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()
|
Reset environment previously set and restart couchbase server
|
|
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)
|
def check_build_url_status(self):
self.check_url_status(self.node_install_info.build_url)
|
|
give a code to
|
def start_couchbase(self):
"""
Starts couchbase on remote server
:return: None
"""
retry = 0
running = self.is_couchbase_running()
while not running and retry < 3:
log.info("Starting couchbase server")
o, r = self.execute_command("net start couchbaseserver")
self.log_command_output(o, r)
self.sleep(5, "Waiting for 5 secs to start...on " + self.info.ip)
running = self.is_couchbase_running()
retry = retry + 1
if not running and retry >= 3:
sys.exit("Failed to start Couchbase server on " + self.info.ip)
|
Starts couchbase on remote server
|
generate python code for the above
|
from time import sleep
def sleep(seconds, msg=""):
"""
Sleep for specified number of seconds. Optionally log a message given
:param seconds: number of seconds to sleep for
:param msg: optional message to log
:return: None
"""
if msg:
log.info(msg)
sleep(seconds)
|
Sleep for specified number of seconds. Optionally log a message given
|
def reconnect_if_inactive(self):
"""
If the SSH channel is inactive, retry the connection
"""
tp = self._ssh_client.get_transport()
if tp and not tp.active:
self.log.warning("%s - SSH connection inactive" % self.ip)
self.ssh_connect_with_retries(self.ip, self.username,
self.password, self.ssh_key)
|
def reconnect_if_inactive(self):
tp = self._ssh_client.get_transport()
if tp and not tp.active:
self.log.warning("%s - SSH connection inactive" % self.ip)
self.ssh_connect_with_retries(self.ip, self.username,
self.password, self.ssh_key)
|
|
give python code to
|
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
|
generate code for 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
|
give a code to
|
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 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.
|
give a code to
|
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 code for the following
|
from shell_util.remote_machine import RemoteMachineProcess
def get_running_processes(self):
"""
Get the list of processes currently running in the remote server
if its linux ,then parse each line
26989 ? 00:00:51 pdflush
ps -Ao pid,comm
:return: List of processes currently running. Each process includes information of the pid, process command,
virtual memory size, resident set size, and arguments to the process
"""
processes = []
output, error = self.execute_command('ps -Ao pid,comm,vsz,rss,args',
debug=False)
if output:
for line in output:
# split to words
words = line.strip().split(' ')
words = [_f for _f in words if _f]
if len(words) >= 2:
process = RemoteMachineProcess()
process.pid = words[0]
process.name = words[1]
if words[2].isdigit():
process.vsz = int(words[2])//1024
else:
process.vsz = words[2]
if words[3].isdigit():
process.rss = int(words[3])//1024
else:
process.rss = words[3]
process.args = " ".join(words[4:])
processes.append(process)
return processes
|
Get the list of processes currently running in the remote server
if its linux ,then parse each line
26989 ? 00:00:51 pdflush
ps -Ao pid,comm
|
generate python code for the above
|
def get_process_statistics_parameter(self, parameter,
process_name=None, process_pid=None):
"""
Get the process statistics for given parameter
: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
"""
if not parameter:
self.log.error("parameter cannot be None")
parameters_list = self.get_process_statistics(process_name, process_pid)
if not parameters_list:
self.log.error("no statistics found")
return None
parameters_dic = dict(item.split(' = ') for item in parameters_list)
if parameter in parameters_dic:
return parameters_dic[parameter]
else:
self.log.error("parameter '{0}' is not found".format(parameter))
return None
|
Get the process statistics for given parameter
|
generate python code for
|
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()
|
Change environment variables mentioned in dictionary and restart Couchbase server
|
generate comment for above
|
def stop_membase(self):
"""
Override method
"""
raise NotImplementedError
|
def stop_membase(self):
raise NotImplementedError
|
give a code to
|
def create_new_partition(self, location, size=None):
"""
Create a new partition at the location specified and of
the size specified
:param location: Location to create the new partition at.
:param size: Size of the partition in MB
:return: None
"""
command = "umount -l {0}".format(location)
output, error = self.execute_command(command)
command = "rm -rf {0}".format(location)
output, error = self.execute_command(command)
command = "rm -rf /usr/disk-img/disk-quota.ext3"
output, error = self.execute_command(command)
command = "mkdir -p {0}".format(location)
output, error = self.execute_command(command)
if size:
count = (size * 1024 * 1024) // 512
else:
count = (5 * 1024 * 1024 * 1024) // 512
command = "mkdir -p /usr/disk-img"
output, error = self.execute_command(command)
command = "dd if=/dev/zero of=/usr/disk-img/disk-quota.ext3 count={0}".format(count)
output, error = self.execute_command(command)
command = "/sbin/mkfs -t ext3 -q /usr/disk-img/disk-quota.ext3 -F"
output, error = self.execute_command(command)
command = "mount -o loop,rw,usrquota,grpquota /usr/disk-img/disk-quota.ext3 {0}".format(location)
output, error = self.execute_command(command)
command = "chown 'couchbase' {0}".format(location)
output, error = self.execute_command(command)
command = "chmod 777 {0}".format(location)
output, error = self.execute_command(command)
|
Create a new partition at the location specified and of
the size specified
|
generate comment for following function:
|
def stop_couchbase(self, num_retries=5, poll_interval=10):
"""
Stop couchbase service on remote server
:param num_retries: None
:param poll_interval: None
:return: None
"""
cb_process = '/Applications/Couchbase\ Server.app/Contents/MacOS/Couchbase\ Server'
cmd = "ps aux | grep {0} | awk '{{print $2}}' | xargs kill -9 "\
.format(cb_process)
o, r = self.execute_command(cmd)
self.log_command_output(o, r)
o, r = self.execute_command("killall -9 epmd")
self.log_command_output(o, r)
|
def stop_couchbase(self, num_retries=5, poll_interval=10):
cb_process = '/Applications/Couchbase\ Server.app/Contents/MacOS/Couchbase\ Server'
cmd = "ps aux | grep {0} | awk '{{print $2}}' | xargs kill -9 "\
.format(cb_process)
o, r = self.execute_command(cmd)
self.log_command_output(o, r)
o, r = self.execute_command("killall -9 epmd")
self.log_command_output(o, r)
|
def __init__(self):
"""
Creates an instance of the TestInputBuild class
"""
self.version = ''
self.url = ''
|
def __init__(self):
self.version = ''
self.url = ''
|
|
generate python code for
|
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
|
Code 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
|
give a 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
|
Code the following:
|
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.
|
def download_build(self, node_installer, build_url,
non_root_installer=False):
"""
Download the Couchbase build on the remote server
:param node_installer: node installer object
:param build_url: build url to download the Couchbase build from.
:param non_root_installer: Change the downloaded build to executable if True
:return: None
"""
download_dir = self.get_download_dir(node_installer)
f_name = build_url.split("/")[-1]
# Remove old build (if exists)
cmd = "rm -f {}/couchbase-server*".format(download_dir)
node_installer.shell.execute_command(cmd)
# Download the build
cmd = node_installer.wget_cmd.format(download_dir, build_url)
node_installer.shell.execute_command(cmd)
if non_root_installer:
node_installer.shell.execute_cmd("chmod a+x {}/{}"
.format(download_dir, f_name))
node_installer.shell.disconnect()
|
Download the Couchbase build on the remote server
|
|
generate comment for above
|
def unpause_beam(self):
"""
Unpauses the beam.smp process on remote server
:return:
"""
o, r = self.execute_command("killall -SIGCONT beam.smp")
self.log_command_output(o, r)
|
def unpause_beam(self):
o, r = self.execute_command("killall -SIGCONT beam.smp")
self.log_command_output(o, r)
|
def kill_goxdcr(self):
"""
Kill XDCR process on remote server
:return: None
"""
o, r = self.execute_command("killall -9 goxdcr")
self.log_command_output(o, r)
|
Kill XDCR process on remote server
|
|
generate doc string for following function:
|
def __init__(self):
"""
Creates an instance of the TestInputServer class. This object holds the server information required for
installation, cli and rest api calls.
"""
self.ip = ''
self.internal_ip = ''
self.hostname = ''
self.ssh_username = ''
self.ssh_password = ''
self.ssh_key = ''
self.rest_username = ''
self.rest_password = ''
self.services = ''
self.port = ''
self.cli_path = ''
self.data_path = ''
self.index_path = ''
self.cbas_path = ''
self.n1ql_port = ''
self.index_port = ''
self.fts_port = ''
self.eventing_port = ''
self.es_username = ''
self.es_password = ''
self.upgraded = False
self.collections_map = {}
self.cbbackupmgr = {}
self.hosted_on_cloud = False
self.dummy = False
|
def __init__(self):
self.ip = ''
self.internal_ip = ''
self.hostname = ''
self.ssh_username = ''
self.ssh_password = ''
self.ssh_key = ''
self.rest_username = ''
self.rest_password = ''
self.services = ''
self.port = ''
self.cli_path = ''
self.data_path = ''
self.index_path = ''
self.cbas_path = ''
self.n1ql_port = ''
self.index_port = ''
self.fts_port = ''
self.eventing_port = ''
self.es_username = ''
self.es_password = ''
self.upgraded = False
self.collections_map = {}
self.cbbackupmgr = {}
self.hosted_on_cloud = False
self.dummy = False
|
Code the following:
|
def unpause_memcached(self):
"""
Unpauses the memcached process on remote server
Override method for Windows
:param os: os type of remote server
:return: None
"""
self.log.info("*** unpause memcached process ***")
cmd = "pssuspend -r $(tasklist | grep memcached | gawk '{printf $2}')"
o, r = self.execute_command(cmd)
self.log_command_output(o, [])
|
Unpauses the memcached process on remote server
Override method for Windows
|
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(WIN_CB_PATH_PARA, VERSION_FILE):
output = self.read_remote_file(WIN_CB_PATH_PARA, VERSION_FILE)
if output:
for x in output:
x = x.strip()
if x and x[:5] in CB_RELEASE_BUILDS.keys() and "-" in x:
fv = x
tmp = x.split("-")
sv = tmp[0]
bn = tmp[1]
break
else:
self.log.info("{} - Couchbase Server not found".format(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 stop_server(self):
"""
Stops the Couchbase server on the remote server.
The method stops the server from non-default location if it's run as nonroot user. Else from default location.
:param os:
:return: None
"""
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
|
def stop_server(self):
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
|
generate comment for above
|
def disable_file_limit(self):
"""
Change the file limite to 200000 for indexer process
:return: None
"""
o, r = self.execute_command("prlimit --nofile=200000 --pid $(pgrep indexer)")
self.log_command_output(o, r)
|
def disable_file_limit(self):
o, r = self.execute_command("prlimit --nofile=200000 --pid $(pgrep indexer)")
self.log_command_output(o, r)
|
Code the following:
|
def get_processes_binding_to_ip_family(self, ip_family="ipv4"):
"""
Get all the processes binding to a particular ip family
Override method for Windows
:param ip_family: ip family to get processes binding of
:return: list of processes binding to ip family
"""
if ip_family == "ipv4":
ip_family = "tcp"
else:
ip_family = "tcpv6"
output_win, error = self.execute_command(
"netstat -a -b -p {0} | grep exe | sort | uniq | sed \'s/\[//g; s/\]//g;\'".
format(ip_family), debug=True)
self.log_command_output(output_win, error, debug=True)
output = list()
for op in output_win:
op = op.strip()
if op in WIN_PROCESSES_SPAWNED:
output.append(op)
return output
|
Get all the processes binding to a particular ip family
Override method for Windows
|
generate comment for above
|
def create_file(self, remote_path, file_data):
"""
Create a remote file from input string
:param remote_path: remote path of the file to be created
:param file_data: file data to be written to the file
:return: None
"""
output, error = self.execute_command("echo '{0}' > {1}".format(file_data, remote_path))
|
def create_file(self, remote_path, file_data):
output, error = self.execute_command("echo '{0}' > {1}".format(file_data, remote_path))
|
generate python code for
|
def terminate_process(self, info=None, process_name=None, force=False):
"""
Terminate a list of processes on remote server
:param info: None
:param p_list: List of processes to terminate
:return: None
"""
if not process_name:
log.info("Please specify process name to be terminated.")
return
o, r = self.execute_command("taskkill /F /T /IM {0}*"\
.format(process_name), debug=False)
self.log_command_output(o, r)
|
Terminate a list of processes on remote server
|
generate doc string for following function:
|
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
|
def get_membase_build(config, section):
membase_build = TestInputBuild()
for option in config.options(section):
if option == 'version':
pass
if option == 'url':
pass
return membase_build
|
def get_processes_binding_to_ip_family(self, ip_family="ipv4"):
"""
Get all the processes binding to a particular ip family
Override method for Windows
:param ip_family: ip family to get processes binding of
:return: list of processes binding to ip family
"""
if ip_family == "ipv4":
ip_family = "tcp"
else:
ip_family = "tcpv6"
output_win, error = self.execute_command(
"netstat -a -b -p {0} | grep exe | sort | uniq | sed \'s/\[//g; s/\]//g;\'".
format(ip_family), debug=True)
self.log_command_output(output_win, error, debug=True)
output = list()
for op in output_win:
op = op.strip()
if op in WIN_PROCESSES_SPAWNED:
output.append(op)
return output
|
Get all the processes binding to a particular ip family
Override method for Windows
|
|
generate code for the above:
|
def param(self, name, *args):
"""
Returns the paramater or a default value
:param name: name of the property
:param args: default value for the property. If no default value is given, an exception is raised
:return: the value of the property
:raises Exception: if the default value is None or empty
"""
if name in self.test_params:
return TestInput._parse_param(self.test_params[name])
elif len(args) == 1:
return args[0]
else:
raise Exception("Parameter `{}` must be set "
"in the test configuration".format(name))
|
Returns the paramater or a default value
|
generate doc string for following function:
|
def disable_file_limit_desc(self):
"""
Change the file limit for all processes to 1606494
:return:
"""
o, r = self.execute_command("sysctl -w fs.file-max=1606494;sysctl -p")
self.log_command_output(o, r)
|
def disable_file_limit_desc(self):
o, r = self.execute_command("sysctl -w fs.file-max=1606494;sysctl -p")
self.log_command_output(o, r)
|
generate python code for the following
|
def stop_server(self, os="unix"):
"""
Stops the Couchbase server on the remote server.
The method stops the server from non-default location if it's run as nonroot user. Else from default location.
:param os:
:return: None
"""
if self.is_couchbase_installed():
if self.nonroot:
cmd = "%s%scouchbase-server -k" % (self.nr_home_path,
LINUX_COUCHBASE_BIN_PATH)
else:
cmd = "systemctl stop couchbase-server.service"
o, r = self.execute_command(cmd)
self.log_command_output(o, r)
|
Stops the Couchbase server on the remote server.
The method stops the server from non-default location if it's run as nonroot user. Else from default location.
|
generate code for the following
|
def delete_file(self, remotepath, filename):
"""
Delete a file from the remote path
:param remotepath: remote path of the file to be deleted
:param filename: name of the file to be deleted
:return: True if the file was successfully deleted else False
"""
sftp = self._ssh_client.open_sftp()
delete_file = False
try:
filenames = sftp.listdir_attr(remotepath)
for name in filenames:
if name.filename == filename:
log.info("File {0} will be deleted".format(filename))
sftp.remove(remotepath + filename)
delete_file = True
break
if delete_file:
""" verify file is deleted """
filenames = sftp.listdir_attr(remotepath)
for name in filenames:
if name.filename == filename:
log.error("fail to remove file %s " % filename)
delete_file = False
break
sftp.close()
return delete_file
except IOError:
return False
|
Delete a file from the remote path
|
give a code to
|
import install_util.constants
from install_util.constants.build import BuildUrl
from shell_util.remote_connection import RemoteMachineShellConnection
def __construct_build_url(self, is_debuginfo_build=False):
"""
Constructs the build url for the given node.
This url is used to download the installation package.
:param is_debuginfo_build: gets debug_info build url if True
:return: build url
"""
file_name = None
build_version = self.node_install_info.version.split("-")
os_type = self.node_install_info.os_type
node_info = RemoteMachineShellConnection.get_info_for_server(
self.node_install_info.server)
# Decide between release / regular build URL path
if len(build_version) == 1:
# Release build url
url_path = "http://{}/{}/{}" \
.format(BuildUrl.CB_DOWNLOAD_SERVER,
BuildUrl.CB_RELEASE_URL_PATH,
build_version[0])
else:
# Build_number specific url
main_version = ".".join(build_version[0].split(".")[:2])
# Reference: builds/latestbuilds/couchbase-server/trinity/1000
url_path = "http://{}/{}/{}/{}" \
.format(BuildUrl.CB_DOWNLOAD_SERVER,
BuildUrl.CB_LATESTBUILDS_URL_PATH,
BuildUrl.CB_VERSION_NAME[main_version],
build_version[1])
build_version = "-".join(build_version)
file_prefix = "{}-{}" \
.format(BuildUrl.CB_BUILD_FILE_PREFIX,
self.node_install_info.edition)
if os_type in install_util.constants.build.X86:
# couchbase-server-enterprise-7.1.5-linux.x86_64.rpm
# couchbase-server-enterprise-debuginfo-7.1.5-linux.x86_64.rpm
if is_debuginfo_build:
file_prefix = "{}-{}".format(file_prefix, "debuginfo")
os_type = "linux"
if float(build_version[:3]) < 7.1:
os_type = self.node_install_info.os_type
file_name = "{}-{}-{}.{}.{}" \
.format(file_prefix,
build_version,
os_type,
node_info.architecture_type,
node_info.deliverable_type)
elif os_type in install_util.constants.build.LINUX_AMD64:
# TODO: Check install_utils.py L1127 redundant code presence
# couchbase-server-enterprise_7.1.5-linux_amd64.deb
# couchbase-server-enterprise-dbg_7.1.5-linux_amd64.deb
if is_debuginfo_build:
file_prefix = "{}-{}".format(file_prefix, "dbg")
os_type = "linux"
if float(build_version[:3]) < 7.1:
os_type = self.node_install_info.os_type
file_name = "{}_{}-{}_{}.{}" \
.format(file_prefix,
build_version,
os_type,
"amd64",
node_info.deliverable_type)
elif os_type in install_util.constants.build.WINDOWS_SERVER:
# couchbase-server-enterprise_6.5.0-4557-windows_amd64.msi
if "windows" in self.node_install_info.os_type:
self.node_install_info.deliverable_type = "msi"
file_name = "{}_{}-{}_{}.{}" \
.format(file_prefix,
build_version,
self.node_install_info.os_type,
"amd64",
node_info.deliverable_type)
elif os_type in install_util.constants.build.MACOS_VERSIONS:
# couchbase-server-enterprise_6.5.0-4557-macos_x86_64.dmg
file_name = "{}_{}-{}_{}-{}.{}" \
.format(file_prefix,
build_version,
"macos",
node_info.architecture_type,
"unnotarized",
node_info.deliverable_type)
else:
self.result = False
self.log.critical("Unsupported os_type '{}' for build_url"
.format(self.node_install_info.os_type))
return "{}/{}".format(url_path, file_name)
|
Constructs the build url for the given node.
This url is used to download the installation package.
|
generate doc string for following function:
|
def fill_disk_space(self, location):
"""
Fill up the disk fully at the location specified.
This method creates a junk file of the specified size in the location specified
:param location: Location to fill the disk
:param size: Size of disk space to fill up, in MB
:return: Output and error message from filling up the disk.
"""
command = "dd if=/dev/zero of={0}/disk-quota.ext3 count={1}; df -Thl"\
.format(location, 1024000000)
output, error = self.execute_command(command)
return output, error
|
def fill_disk_space(self, location):
command = "dd if=/dev/zero of={0}/disk-quota.ext3 count={1}; df -Thl"\
.format(location, 1024000000)
output, error = self.execute_command(command)
return output, error
|
generate python code for the above
|
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
|
Windows process utility. This adds firewall rules to Windows system.
If a previously suspended process is detected, it continues with the process instead.
|
give a code to
|
def reboot_node(self):
"""
Reboot the remote server
:return: None
"""
o, r = self.execute_command("reboot")
self.log_command_output(o, r)
|
Reboot the remote server
|
give python code to
|
def unmount_partition(self, location):
"""
Unmount the partition at the specified location.
:param location: Location of the partition which has to be unmounted
:return: Output and error message from the umount command
"""
command = "umount -l {0}; df -Th".format(location)
output, error = self.execute_command(command)
return output, error
|
Unmount the partition at the specified location.
|
generate python code for the following
|
def get_ip_address(self):
"""
Get ip address of a remote server
Override method for Windows
:return: ip address of remote server
"""
raise NotImplementedError
|
Get ip address of a remote server
Override method for Windows
|
generate code for the above:
|
def stop_server(self):
"""
Stops the Couchbase server on the remote server.
The method stops the server from non-default location if it's run as nonroot user. Else from default location.
:param os:
:return: None
"""
o, r = self.execute_command("net stop couchbaseserver")
self.log_command_output(o, r)
|
Stops the Couchbase server on the remote server.
The method stops the server from non-default location if it's run as nonroot user. Else from default location.
|
def terminate_processes(self, info, p_list):
"""
Terminate a list of processes on remote server
Override for Unix systems
:param info: None
:param p_list: List of processes to terminate
:return: None
"""
raise NotImplementedError
|
def terminate_processes(self, info, p_list):
raise NotImplementedError
|
|
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 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 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
|
generate python code for the above
|
import os
def find_file(self, remote_path, file):
"""
Check if file exists in remote path
:param remote_path: remote path of the file to be checked
:param file: filename to be checked
:return: file path of the file if exists, None otherwise
"""
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()
|
Check if file exists in remote path
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.