instruction
stringclasses
14 values
output
stringlengths
105
12.9k
input
stringlengths
0
4.12k
give python code to
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
generate python code for
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
generate code for the above:
def post_install(self): """ Post installation steps on a Unix server :return: True on successful post installation steps run else False """ cmds = self.cmds if self.shell.nonroot: cmds = self.non_root_cmds cmd = cmds["post_install"] retry_cmd = cmds["post_install_retry"] if cmd is None: return True output, err = self.shell.execute_command(cmd) if output[0] == '1': return True self.shell.log.critical("Output: {}, Error: {}".format(output, err)) if retry_cmd is None: return False self.shell.log.critical("Retrying post_install steps") output, err = self.shell.execute_command(retry_cmd) if output[0] == '1': return True self.shell.log.critical("Output: {}, Error: {}".format(output, err)) return False
Post installation steps on a Unix server
generate python code for the following
import re def get_test_input(arguments): """ Parses the test input arguments to type TestInput object :param arguments: arguments to parse :return: TestInput object """ params = dict() if arguments.params: argument_split = [a.strip() for a in re.split("[,]?([^,=]+)=", arguments.params)[1:]] pairs = dict(list(zip(argument_split[::2], argument_split[1::2]))) for pair in list(pairs.items()): if pair[0] == "vbuckets": # takes in a string of the form "1-100,140,150-160" # converts to an array with all those values inclusive vbuckets = set() for v in pair[1].split(","): r = v.split("-") vbuckets.update(list(range(int(r[0]), int(r[-1]) + 1))) params[pair[0]] = sorted(vbuckets) else: argument_list = [a.strip() for a in pair[1].split(",")] if len(argument_list) > 1: params[pair[0]] = argument_list else: params[pair[0]] = argument_list[0] input = TestInputParser.parse_from_file(arguments.ini) input.test_params = params for server in input.servers: if 'run_as_user' in input.test_params and input.test_params['run_as_user'] != server.rest_username: server.rest_username = input.test_params['run_as_user'] if "num_clients" not in list(input.test_params.keys()) and input.clients: # do not override the command line value input.test_params["num_clients"] = len(input.clients) if "num_nodes" not in list(input.test_params.keys()) and input.servers: input.test_params["num_nodes"] = len(input.servers) return input
Parses the test input arguments to type TestInput object
generate comment for above
def reboot_node(self): """ Reboot the remote server :return: None """ o, r = self.execute_command("reboot") self.log_command_output(o, r)
def reboot_node(self): o, r = self.execute_command("reboot") self.log_command_output(o, r)
give python code to
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 doc string for following function:
def __init__(self, test_server): """ Creates an instance of Unix installer class :param test_server: server object of type TestInputServer """ super(Unix, self).__init__() self.shell = RemoteMachineShellConnection(test_server)
def __init__(self, test_server): super(Unix, self).__init__() self.shell = RemoteMachineShellConnection(test_server)
generate comment for following function:
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)
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
generate python code for
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 python code for the above
import os from subprocess import Popen from typing import re def execute_commands_inside(self, main_command, query, queries, bucket1, password, bucket2, source, subcommands=[], min_output_size=0, end_msg='', timeout=250): filename = "/tmp/test2" 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() 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 " + filename + '"' else: main_command = main_command + " -f=" + filename self.log.info("%s - Running command: %s" % (self.ip, main_command)) output = "" if self.remote: (stdin, stdout, stderro) = self._ssh_client.exec_command(main_command) self.sleep(10) count = 0 for line in stdout.readlines(): if (count == 0) and line.lower().find("error") > 0: output = "status:FAIL" break 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) self.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 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)
Reboot the remote server
generate python code for
def cbbackupmgr_param(self, name, *args): """ Returns the config value from the ini whose key matches 'name' and is stored under the 'cbbackupmgr' section heading. :param name: the key under which an expected value is stored. :param args: expects a single parameter which will be used as the default if the requested key is not found. :return: the value parsed from the ini file/default value if the given key is not found. :raises Exception: if the given key does not exist in the ini and no default value is provided. """ if name in self.cbbackupmgr: return TestInput._parse_param(self.cbbackupmgr[name]) if len(args) == 1: return args[0] if self.cbbackupmgr["name"] != "local_bkrs": raise Exception(f"Parameter '{name}' must be set in the test configuration")
Returns the config value from the ini whose key matches 'name' and is stored under the 'cbbackupmgr' section heading.
generate python code for the above
def enable_network_delay(self): """ Changes network to send requests with a delay of 200 ms using traffic control :return: None """ o, r = self.execute_command("tc qdisc add dev eth0 root netem delay 200ms") self.log_command_output(o, r)
Changes network to send requests with a delay of 200 ms using traffic control
generate comment for 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)
def stop_memcached(self): o, r = self.execute_command("taskkill /F /T /IM memcached*") self.log_command_output(o, r, debug=False)
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
generate python code for the following
def disable_firewall(self): """ Clear firewall rules on the remote server :return: None """ output, error = self.execute_command('netsh advfirewall set publicprofile state off') self.log_command_output(output, error) output, error = self.execute_command('netsh advfirewall set privateprofile state off') self.log_command_output(output, error) # for details see RemoteUtilHelper.enable_firewall for windows output, error = self.execute_command('netsh advfirewall firewall delete rule name="block erl.exe in"') self.log_command_output(output, error) output, error = self.execute_command('netsh advfirewall firewall delete rule name="block erl.exe out"') self.log_command_output(output, error)
Clear firewall rules on the remote server
from shell_util.remote_machine import RemoteMachineProcess def get_running_processes(self): """ Retrieves a list of running processes on the system. :return: list of running processes on the system """ # if its linux ,then parse each line # 26989 ? 00:00:51 pdflush # ps -Ao pid,comm processes = [] output, error = self.execute_command('ps -Ao pid,comm,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
Retrieves a list of running processes on the system.
generate code for the following
def __init__(self): """ Creates an instance of the TestInputMembaseSetting class """ self.rest_username = '' self.rest_password = ''
Creates an instance of the TestInputMembaseSetting class
generate python code for the above
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 python code for the above
def cpu_stress(self, stop_time): """ Applies CPU stress for a specified duration on the 20 CPU cores. :param stop_time: duration to apply the CPU stress for. :return: None """ o, r = self.execute_command("stress --cpu 20 --timeout {}".format(stop_time)) self.log_command_output(o, r)
Applies CPU stress for a specified duration on the 20 CPU cores.
generate python 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
generate python code for the following
def start_memcached(self): """ Start 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)
Start memcached process on remote server
generate python code for the following
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 code for the following
import os def get_server_options(servers, membase_settings, global_properties): """ Set the various server properties from membase and global properties :param servers: list of servers to set the values of :param membase_settings: TestInputMembaseSetting object with membase settings :param global_properties: dict of global properties :return: list of servers with values set """ for server in servers: 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'] if server.ssh_key == '' and 'ssh_key' in global_properties: server.ssh_key = os.path.expanduser(global_properties['ssh_key']) if not server.port and 'port' in global_properties: server.port = global_properties['port'] if server.cli_path == '' and 'cli' in global_properties: server.cli_path = global_properties['cli'] if server.rest_username == '' and membase_settings.rest_username != '': server.rest_username = membase_settings.rest_username if server.rest_password == '' and membase_settings.rest_password != '': server.rest_password = membase_settings.rest_password if server.data_path == '' and 'data_path' in global_properties: server.data_path = global_properties['data_path'] if server.index_path == '' and 'index_path' in global_properties: server.index_path = global_properties['index_path'] if server.cbas_path == '' and 'cbas_path' in global_properties: server.cbas_path = global_properties['cbas_path'] if server.services == '' and 'services' in global_properties: server.services = global_properties['services'] if server.n1ql_port == '' and 'n1ql_port' in global_properties: server.n1ql_port = global_properties['n1ql_port'] if server.index_port == '' and 'index_port' in global_properties: server.index_port = global_properties['index_port'] if server.eventing_port == '' and 'eventing_port' in global_properties: server.eventing_port = global_properties['eventing_port'] if server.es_username == '' and 'es_username' in global_properties: server.es_username = global_properties['es_username'] if server.es_password == '' and 'es_password' in global_properties: server.es_password = global_properties['es_password'] return servers
Set the various server properties from membase and global properties
generate comment.
def set_node_name(self, name): """ Edit couchbase-server shell script in place and set custom node name. This is necessary for cloud installations where nodes have both private and public addresses. It only works on Unix-like OS. Reference: http://bit.ly/couchbase-bestpractice-cloud-ip :param name: name to set the couchbase node to :return: None """ # Stop server self.stop_couchbase() # Edit _start function cmd = r"sed -i 's/\(.*\-run ns_bootstrap.*\)/\1\n\t-name ns_1@{0} \\/' \ /opt/couchbase/bin/couchbase-server".format(name) self.execute_command(cmd) # Cleanup for cmd in ('rm -fr /opt/couchbase/var/lib/couchbase/data/*', 'rm -fr /opt/couchbase/var/lib/couchbase/mnesia/*', 'rm -f /opt/couchbase/var/lib/couchbase/config/config.dat'): self.execute_command(cmd) # Start server self.start_couchbase()
def set_node_name(self, name): # Stop server self.stop_couchbase() # Edit _start function cmd = r"sed -i 's/\(.*\-run ns_bootstrap.*\)/\1\n\t-name ns_1@{0} \\/' \ /opt/couchbase/bin/couchbase-server".format(name) self.execute_command(cmd) # Cleanup for cmd in ('rm -fr /opt/couchbase/var/lib/couchbase/data/*', 'rm -fr /opt/couchbase/var/lib/couchbase/mnesia/*', 'rm -f /opt/couchbase/var/lib/couchbase/config/config.dat'): self.execute_command(cmd) # Start server self.start_couchbase()
generate comment for above
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
def get_running_processes(self): 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
generate comment.
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
def file_starts_with(self, remotepath, pattern): sftp = self._ssh_client.open_sftp() files_matched = [] try: file_names = sftp.listdir(remotepath) for name in file_names: if name.startswith(pattern): files_matched.append("{0}/{1}".format(remotepath, name)) except IOError: # ignore this error pass sftp.close() if len(files_matched) > 0: log.info("found these files : {0}".format(files_matched)) return files_matched
generate python code for
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.
generate comment:
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 comment for above
def get_processes_binding_to_ip_family(self, ip_family="ipv4"): """ Get all the processes binding to a particular ip family :param ip_family: ip family to get processes binding of :return: list of processes binding to ip family """ output, error = self.execute_command( "lsof -i -P -n | grep LISTEN | grep couchbase| grep -i {0}" .format(ip_family), debug=True) self.log_command_output(output, error, debug=True) return output
def get_processes_binding_to_ip_family(self, ip_family="ipv4"): output, error = self.execute_command( "lsof -i -P -n | grep LISTEN | grep couchbase| grep -i {0}" .format(ip_family), debug=True) self.log_command_output(output, error, debug=True) return output
def stop_membase(self): """ Override method """ raise NotImplementedError
Override method
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
Code the following:
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
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
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 comment for above
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 __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())
def __init__(self, test_server): 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())
give a 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
give python code to
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 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)
Change the file limite to 200000 for indexer process
generate python code for the above
def install(self, build_url): """ Installs Couchbase server on Unix machine :param build_url: build url to get the Couchbase package from :return: True on successful installation else False """ cmd = self.cmds["install"] if self.shell.nonroot: cmd = self.non_root_cmds["install"] f_name = build_url.split("/")[-1] cmd = cmd.replace("buildpath", "{}/{}" .format(self.download_dir, f_name)) self.shell.execute_command(cmd) output, err = self.shell.execute_command(cmd) if output[0] == '1': return True self.shell.log.critical("Output: {}, Error: {}".format(output, err)) return False
Installs Couchbase server on Unix machine
generate code for the following
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.
generate python code for the above
def start_couchbase(self): """ Starts couchbase on remote server :return: None """ retry = 0 running = self.is_couchbase_running() while not running and retry < 3: self.log.info("Starting couchbase server") o, r = self.execute_command("open /Applications/Couchbase\ Server.app") self.log_command_output(o, r) running = self.is_couchbase_running() retry = retry + 1 if not running and retry >= 3: self.log.critical("%s - Server not started even after 3 retries" % self.info.ip) return False return True
Starts couchbase on remote server
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 comment:
def __init__(self, server, server_info, os_type, version, edition): """ Creats an instance of the NodeInstallInfo class. :param server: server object of type TestInputServer :param server_info: server info with information of the server :param os_type: OS type of the server :param version: version of the couchbase server :param edition: type of Couchbase Server """ self.server = server self.server_info = server_info self.os_type = os_type self.version = version self.edition = edition self.build_url = None self.debug_build_url = None self.non_root_package_mgr = None self.state = "not_started"
def __init__(self, server, server_info, os_type, version, edition): self.server = server self.server_info = server_info self.os_type = os_type self.version = version self.edition = edition self.build_url = None self.debug_build_url = None self.non_root_package_mgr = None self.state = "not_started"
generate python code for the above
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
generate python code for
def start_indexer(self): """ Start indexer process on remote server :return: None """ o, r = self.execute_command("taskkill /F /T /IM indexer*") self.log_command_output(o, r)
Start indexer process on remote server
generate python code for the following
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
Get the process id for the given process Override method for Windows
generate code for the above:
def __init__(self): """ Creates an instance of the TestInputMembaseSetting class """ self.rest_username = '' self.rest_password = ''
Creates an instance of the TestInputMembaseSetting class
generate python code for 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
generate doc string for following function:
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
generate python code for
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.
def wait_till_process_ended(self, process_name, timeout_in_seconds=600): """ Wait until the process is completed or killed or terminated :param process_name: name of the process to be checked :param timeout_in_seconds: wait time in seconds until the process is completed :return: True if the process is completed within timeout else False """ if process_name[-1:] == "-": process_name = process_name[:-1] end_time = time.time() + float(timeout_in_seconds) process_ended = False process_running = False count_process_not_run = 0 while time.time() < end_time and not process_ended: output, error = self.execute_command("tasklist | grep {0}" \ .format(process_name)) self.log_command_output(output, error) if output and process_name in output[0]: self.sleep(8, "wait for process ended!") process_running = True else: if process_running: log.info("{1}: Alright, PROCESS {0} ENDED!" \ .format(process_name, self.ip)) process_ended = True else: if count_process_not_run < 5: log.error("{1}: process {0} may not run" \ .format(process_name, self.ip)) self.sleep(5) count_process_not_run += 1 else: log.error("{1}: process {0} did not run after 25 seconds" .format(process_name, self.ip)) mesg = "kill in/uninstall job due to process was not run" \ .format(process_name, self.ip) self.stop_current_python_running(mesg) if time.time() >= end_time and not process_ended: log.info("Process {0} on node {1} is still running" " after 10 minutes VERSION.txt file was removed" .format(process_name, self.ip)) return process_ended
def wait_till_process_ended(self, process_name, timeout_in_seconds=600): if process_name[-1:] == "-": process_name = process_name[:-1] end_time = time.time() + float(timeout_in_seconds) process_ended = False process_running = False count_process_not_run = 0 while time.time() < end_time and not process_ended: output, error = self.execute_command("tasklist | grep {0}" \ .format(process_name)) self.log_command_output(output, error) if output and process_name in output[0]: self.sleep(8, "wait for process ended!") process_running = True else: if process_running: log.info("{1}: Alright, PROCESS {0} ENDED!" \ .format(process_name, self.ip)) process_ended = True else: if count_process_not_run < 5: log.error("{1}: process {0} may not run" \ .format(process_name, self.ip)) self.sleep(5) count_process_not_run += 1 else: log.error("{1}: process {0} did not run after 25 seconds" .format(process_name, self.ip)) mesg = "kill in/uninstall job due to process was not run" \ .format(process_name, self.ip) self.stop_current_python_running(mesg) if time.time() >= end_time and not process_ended: log.info("Process {0} on node {1} is still running" " after 10 minutes VERSION.txt file was removed" .format(process_name, self.ip)) return process_ended
give python code to
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 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.
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 code for 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.
generate comment:
def execute_command(self, command, info=None, debug=True, use_channel=False, timeout=600, get_exit_code=False): """ Executes a given command on the remote machine. :param command: The command to execute. :param info: Additional information for execution (optional). :param debug: Enables debug output if True. :param use_channel: Use SSH channel if True. :param timeout: Timeout for command execution in seconds :param get_exit_code: Return the exit code of the command if True. :return: Command output and error as a tuple. """ if getattr(self, "info", None) is None and info is not None : self.info = info if self.info.type.lower() == 'windows': self.use_sudo = False if self.use_sudo: command = "sudo " + command return self.execute_command_raw( command, debug=debug, use_channel=use_channel, timeout=timeout, get_exit_code=get_exit_code)
def execute_command(self, command, info=None, debug=True, use_channel=False, timeout=600, get_exit_code=False): if getattr(self, "info", None) is None and info is not None : self.info = info if self.info.type.lower() == 'windows': self.use_sudo = False if self.use_sudo: command = "sudo " + command return self.execute_command_raw( command, debug=debug, use_channel=use_channel, timeout=timeout, get_exit_code=get_exit_code)
generate comment for following function:
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
def get_cbversion(self): 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
generate comment for above
def _check_output(self, word_check, output): """ Check if certain word is present in the output :param word_check: string or list of strings to check :param output: the output to check against :return: True if word is present in the output else False """ found = False if len(output) >= 1: if isinstance(word_check, list): for ele in word_check: for x in output: if ele.lower() in str(x.lower()): log.info("Found '{0} in output".format(ele)) found = True break elif isinstance(word_check, str): for x in output: if word_check.lower() in str(x.lower()): log.info("Found '{0}' in output".format(word_check)) found = True break else: self.log.error("invalid {0}".format(word_check)) return found
def _check_output(self, word_check, output): found = False if len(output) >= 1: if isinstance(word_check, list): for ele in word_check: for x in output: if ele.lower() in str(x.lower()): log.info("Found '{0} in output".format(ele)) found = True break elif isinstance(word_check, str): for x in output: if word_check.lower() in str(x.lower()): log.info("Found '{0}' in output".format(word_check)) found = True break else: self.log.error("invalid {0}".format(word_check)) return found
generate python code for
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: # set debug=False if does not want to show log self.execute_command("taskkill /F /T /IM {0}" .format(process), debug=False)
Terminate a list of processes on remote server
generate python code for
def get_ip_address(self): """ Get ip address of a remote server :return: ip address of remote server """ ip_type = "inet \K[\d.]" ipv6_server = False if "ip6" in self.ip or self.ip.startswith("["): ipv6_server = True ip_type = "inet6 \K[0-9a-zA-Z:]" cmd = "ifconfig | grep -Po '{0}+'".format(ip_type) o, r = self.execute_command_raw(cmd) if ipv6_server: for x in range(len(o)): o[x] = "[{0}]".format(o[x]) return o
Get ip address of a remote server
generate python code for the following
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 comment.
def populate_cb_server_versions(self): """ Update the BuildUrl with all versions of Couchbase Server currently available for testing. \n This method gets the current versions of Couchbase Servers available from the CB server manifest and updates the missing versions in BuildUrl constants accordingly. :return: None """ cb_server_manifests_url = "https://github.com/couchbase" \ "/manifest/tree/master/couchbase-server/" raw_content_url = "https://raw.githubusercontent.com/couchbase" \ "/manifest/master/couchbase-server/" version_pattern = r'<annotation name="VERSION" value="([0-9\.]+)"' version_pattern = re.compile(version_pattern) payload_pattern = r'>({"payload".*})<' payload_pattern = re.compile(payload_pattern) data = urlopen(cb_server_manifests_url).read() data = json.loads(re.findall(payload_pattern, data.decode())[0]) for item in data["payload"]["tree"]["items"]: if item["contentType"] == "file" and item["name"].endswith(".xml"): rel_name = item["name"].replace(".xml", "") data = urlopen(raw_content_url + item["name"]).read() rel_ver = re.findall(version_pattern, data.decode())[0][:3] if rel_ver not in BuildUrl.CB_VERSION_NAME: self.log.info("Adding missing version {}={}" .format(rel_ver, rel_name)) BuildUrl.CB_VERSION_NAME[rel_ver] = rel_name
def populate_cb_server_versions(self): cb_server_manifests_url = "https://github.com/couchbase" \ "/manifest/tree/master/couchbase-server/" raw_content_url = "https://raw.githubusercontent.com/couchbase" \ "/manifest/master/couchbase-server/" version_pattern = r'<annotation name="VERSION" value="([0-9\.]+)"' version_pattern = re.compile(version_pattern) payload_pattern = r'>({"payload".*})<' payload_pattern = re.compile(payload_pattern) data = urlopen(cb_server_manifests_url).read() data = json.loads(re.findall(payload_pattern, data.decode())[0]) for item in data["payload"]["tree"]["items"]: if item["contentType"] == "file" and item["name"].endswith(".xml"): rel_name = item["name"].replace(".xml", "") data = urlopen(raw_content_url + item["name"]).read() rel_ver = re.findall(version_pattern, data.decode())[0][:3] if rel_ver not in BuildUrl.CB_VERSION_NAME: self.log.info("Adding missing version {}={}" .format(rel_ver, rel_name)) BuildUrl.CB_VERSION_NAME[rel_ver] = rel_name
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
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)
def stop_indexer(self): o, r = self.execute_command("kill -SIGSTOP $(pgrep indexer)") self.log_command_output(o, r, debug=False)
give a code to
def execute_batch_command(self, command): """ Execute a batch of commands. This method copies the commands onto a batch file, changes the file type to executable and then executes them on the remote server :param command: commands to execute in a batch :return: output of the batch commands """ remote_command = "echo \"%s\" > /tmp/cmd.bat ; " \ "chmod u=rwx /tmp/cmd.bat; /tmp/cmd.bat" % command o, r = self.execute_command_raw(remote_command) if r and r!=['']: log.error("Command didn't run successfully. Error: {0}".format(r)) return o, r
Execute a batch of commands. This method copies the commands onto a batch file, changes the file type to executable and then executes them on the remote server
give python code to
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
Enable diag/eval to be run on non-local hosts.
give python code to
from shell_util.remote_machine import RemoteMachineProcess def get_running_processes(self): """ Retrieves a list of running processes on the system. :return: list of running processes on the system """ # if its linux ,then parse each line # 26989 ? 00:00:51 pdflush # ps -Ao pid,comm processes = [] output, error = self.execute_command('ps -Ao pid,comm,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
Retrieves a list of running processes on the system.
generate comment:
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
def __init__(self): """ Creates an instance of the TestInputBuild class """ self.version = '' self.url = ''
Creates an instance of the TestInputBuild class
generate python code for
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
Check if the couchbase installed is enterprise edition or not
generate comment for above
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)
def kill_goxdcr(self): o, r = self.execute_command("killall -9 goxdcr") self.log_command_output(o, r)
Code the following:
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 doc string for following function:
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
give python code to
import getopt def parse_from_command_line(argv): """ Parse command line arguments :param argv: command line arguments :return: parsed command line arguments as TestInput """ input = TestInput() try: # -f : won't be parse here anynore # -s will have comma separated list of servers # -t : wont be parsed here anymore # -v : version # -u : url # -b : will have the path to cli # -k : key file # -p : for smtp ( taken care of by jenkins) # -o : taken care of by jenkins servers = [] membase_setting = None (opts, args) = getopt.getopt(argv[1:], 'h:t:c:i:p:', []) #first let's loop over and find out if user has asked for help need_help = False for option, argument in opts: if option == "-h": print('usage...') need_help = True break if need_help: return #first let's populate the server list and the version number for option, argument in opts: if option == "-s": #handle server list servers = TestInputParser.handle_command_line_s(argument) elif option == "-u" or option == "-v": input_build = TestInputParser.handle_command_line_u_or_v(option, argument) #now we can override the username pass and cli_path info for option, argument in opts: if option == "-k": #handle server list for server in servers: if server.ssh_key == '': server.ssh_key = argument elif option == "--username": #handle server list for server in servers: if server.ssh_username == '': server.ssh_username = argument elif option == "--password": #handle server list for server in servers: if server.ssh_password == '': server.ssh_password = argument elif option == "-b": #handle server list for server in servers: if server.cli_path == '': server.cli_path = argument # loop over stuff once again and set the default # value for server in servers: if server.ssh_username == '': server.ssh_username = 'root' if server.ssh_password == '': server.ssh_password = 'northscale!23' if server.cli_path == '': server.cli_path = '/opt/membase/bin/' if not server.port: server.port = 8091 input.servers = servers input.membase_settings = membase_setting return input except Exception: log = logger.Logger.get_logger() log.error("unable to parse input arguments") raise
Parse command line arguments
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
generate code for the above:
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 print_install_status(thread_list, logger): """ Print the installation status of the threads in the thread list. :param thread_list: list of threads to check :param logger: logger object to use :return: None """ status_msg = "\n" for tem_thread in thread_list: node_ip = tem_thread.node_install_info.server.ip t_state = tem_thread.node_install_info.state if tem_thread.result: status_msg += " {}: Complete".format(node_ip) else: status_msg += " {}: Failure during {}".format(node_ip, t_state) status_msg += "\n" logger.info(status_msg)
def print_install_status(thread_list, logger): status_msg = "\n" for tem_thread in thread_list: node_ip = tem_thread.node_install_info.server.ip t_state = tem_thread.node_install_info.state if tem_thread.result: status_msg += " {}: Complete".format(node_ip) else: status_msg += " {}: Failure during {}".format(node_ip, t_state) status_msg += "\n" logger.info(status_msg)
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 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 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
generate doc string for following function:
def _recover_disk_full_failure(self, location): """ Recover the disk full failures on remote server :param location: location of the disk to recover :return: output and error message from recovering disk """ delete_file = "{0}/disk-quota.ext3".format(location) output, error = self.execute_command("rm -f {0}".format(delete_file)) return output, error
def _recover_disk_full_failure(self, location): delete_file = "{0}/disk-quota.ext3".format(location) output, error = self.execute_command("rm -f {0}".format(delete_file)) return output, error
generate python code for the following
def stop_membase(self): """ Override method """ raise NotImplementedError
Override method
generate comment:
def get_download_dir(node_installer): """ Gets the download directory for the given node. Returns non-root download directory in case of nonroot installation. Else returns the default download directory. :param node_installer: node installer object :return: download directory for given node """ if node_installer.shell.nonroot: return node_installer.nonroot_download_dir return node_installer.download_dir
def get_download_dir(node_installer): if node_installer.shell.nonroot: return node_installer.nonroot_download_dir return node_installer.download_dir
generate python code for the following
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
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))
def param(self, name, *args): 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))
generate python 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
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)
Code the following:
def handle_command_line_u_or_v(option, argument): """ Parse command line arguments for -u or -v :param option: option to parse :param argument: argument to check :return: parsed arguments as TestInputBuild """ input_build = TestInputBuild() if option == "-u": # let's check whether this url exists or not # let's extract version from this url pass if option == "-v": allbuilds = BuildQuery().get_all_builds() for build in allbuilds: if build.product_version == argument: input_build.url = build.url input_build.version = argument break return input_build
Parse command line arguments for -u or -v
give a code to
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 comment for above
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)
def kill_goxdcr(self): o, r = self.execute_command("killall -9 goxdcr") self.log_command_output(o, r)
generate python code for the above
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 """ output = "" fv = sv = bn = tmp = "" err_msg = "{} - Couchbase Server not found".format(self.ip) if self.nonroot: if self.file_exists('/home/%s/cb/%s' % (self.username, self.cb_path), self.version_file): output = self.read_remote_file('/home/%s/cb/%s' % (self.username, self.cb_path), self.version_file) else: log.info(err_msg) else: if self.file_exists(self.cb_path, self.version_file): output = self.read_remote_file(self.cb_path, self.version_file) else: log.info(err_msg) 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 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 code for the above:
def ram_stress(self, stop_time): """ Applies memory stress for a specified duration with 3 workers each of size 2.5G. Override method for Windows :param stop_time: duration to apply the memory stress for. :return: None """ raise NotImplementedError
Applies memory stress for a specified duration with 3 workers each of size 2.5G. Override method for Windows
generate doc string for following function:
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)
def cleanup_all_configuration(self, data_path): # 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)
generate python code for the above
def __check_if_cb_service_stopped(self, service_name=None): """ Check if a couchbase service is stopped :param service_name: service name to check :return: True if service is stopped else False """ if service_name: o, r = self.execute_command('sc query {0}'.format(service_name)) for res in o: if "STATE" in res: info = res.split(":") is_stopped = "STOPPED" in str(info[1]) return is_stopped log.error("Cannot identify service state for service {0}. " "Host response is: {1}".format(service_name, str(o))) return True log.error("Service name is not specified!") return False
Check if a couchbase service is stopped
generate doc string for following function:
def __init__(self, test_server, info=None): """ Creates a new shell connection for Linux based platforms :param test_server: test server to create the shell connection for :param info: None """ super(Linux, self).__init__(test_server) self.nonroot = False self.use_sudo = False self.info = info
def __init__(self, test_server, info=None): super(Linux, self).__init__(test_server) self.nonroot = False self.use_sudo = False self.info = info
Code the following:
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
def create_windows_info(self): """ Create info dictionary about the Windows server This method retrieves OS, OS version, and OS architecture of the Windows server. The method also stores the information in the remote server as a text file. :return: windows info dictionary """ systeminfo = self.get_windows_system_info() info = dict() info["os_name"] = "2k8" if "OS Name" in systeminfo: info["os"] = systeminfo["OS Name"].find("indows") and "windows" or "NONE" if systeminfo["OS Name"].find("2008 R2") != -1: info["os_name"] = 2008 elif systeminfo["OS Name"].find("2016") != -1: info["os_name"] = 2016 elif systeminfo["OS Name"].find("2019") != -1: info["os_name"] = 2019 if "System Type" in systeminfo: info["os_arch"] = systeminfo["System Type"].find("64") and "x86_64" or "NONE" info.update(systeminfo) self.execute_batch_command("rm -rf /cygdrive/c/tmp/windows_info.txt") self.execute_batch_command("touch /cygdrive/c/tmp/windows_info.txt") sftp = self._ssh_client.open_sftp() try: f = sftp.open('/cygdrive/c/tmp/windows_info.txt', 'w') content = '' for key in sorted(info.keys()): content += '{0} = {1}\n'.format(key, info[key]) f.write(content) log.info("/cygdrive/c/tmp/windows_info.txt was created with content: {0}".format(content)) except IOError: log.error('Can not write windows_info.txt file') finally: sftp.close() return info
Create info dictionary about the Windows server This method retrieves OS, OS version, and OS architecture of the Windows server. The method also stores the information in the remote server as a text file.