instruction
stringclasses
14 values
output
stringlengths
105
12.9k
input
stringlengths
0
4.12k
generate python code for the above
def cluster_ip(self): """ Returns the ip address of the server. Returns internal ip is available, else the ip address. :return: ip address of the server """ return self.internal_ip or self.ip
Returns the ip address of the server. Returns internal ip is available, else the ip address.
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 doc string for following function:
def _parse_param(value): """ Parses the parameter to integers, floats, booleans and strings. The method tries to fit the value to integer, float, boolean in sequence. If the value fits, return the corresponding type of value, else return the string value as is. :param value: value to parse. :return: parsed value """ try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass if value.lower() == "false": return False if value.lower() == "true": return True return value
def _parse_param(value): try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass if value.lower() == "false": return False if value.lower() == "true": return True return value
generate comment for above
def unpause_memcached(self, os="linux"): """ Unpauses the memcached process on remote server :param os: os type of remote server :return: None """ log.info("*** unpause memcached process ***") if self.nonroot: o, r = self.execute_command("killall -SIGCONT memcached.bin") else: o, r = self.execute_command("killall -SIGCONT memcached") self.log_command_output(o, r)
def unpause_memcached(self, os="linux"): log.info("*** unpause memcached process ***") if self.nonroot: o, r = self.execute_command("killall -SIGCONT memcached.bin") else: o, r = self.execute_command("killall -SIGCONT memcached") self.log_command_output(o, r)
generate python code for 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('beam.smp') if o is not None: return True return False
Checks if couchbase is currently running on the remote server
generate python code for the following
def __init__(self, logger): """ Creates an instance of InstallHelper object :param logger: logger object """ self.log = logger
Creates an instance of InstallHelper object
Code the following:
def init_cluster(self, node): """ Initializes Couchbase cluster Override method for Unix :param node: server object :return: True on success """ return True
Initializes Couchbase cluster Override method for Unix
def __find_windows_info(self): """ Get information about a Windows server :return: Windows info about the server """ if self.remote: found = self.find_file("/cygdrive/c/tmp", "windows_info.txt") if isinstance(found, str): if self.remote: sftp = self._ssh_client.open_sftp() try: f = sftp.open(found) log.info("get windows information") info = {} for line in f: (key, value) = line.split('=') key = key.strip(' \t\n\r') value = value.strip(' \t\n\r') info[key] = value return info except IOError: log.error("can not find windows info file") sftp.close() else: return self.create_windows_info() else: try: txt = open( "{0}/{1}".format("/cygdrive/c/tmp", "windows_info.txt")) log.info("get windows information") info = {} for line in txt.read(): (key, value) = line.split('=') key = key.strip(' \t\n\r') value = value.strip(' \t\n\r') info[key] = value return info except IOError: log.error("can not find windows info file")
Get information about a Windows server
generate python code for
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
Gets the download directory for the given node. Returns non-root download directory in case of nonroot installation. Else returns the default download directory.
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('beam.smp') if o is not None: return True return False
def is_couchbase_running(self): o = self.is_process_running('beam.smp') if o is not None: return True return False
generate python code for the following
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 python code for the following
def connect_with_user(self, user="root"): """ Connect to the remote server with given user Override method since this is not required for Unix :param user: user to connect to remote server with :return: None """ return
Connect to the remote server with given user Override method since this is not required for Unix
Code the following:
def remove_folders(self, list): """ Remove folders from list provided :param list: paths of folders to be removed :return: None """ for folder in list: output, error = self.execute_command( "rm -rf {0}".format(folder), debug=False) self.log_command_output(output, error)
Remove folders from list provided
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 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
give python code to
def init_cluster(self, node): """ Initializes Couchbase cluster Override method for Unix :param node: server object :return: True on success """ return True
Initializes Couchbase cluster Override method for Unix
generate comment.
def parse_from_file(file): """ Parse the test inputs from file :param file: path to file to parse :return: TestInput object """ count = 0 start = 0 end = 0 servers = list() ips = list() input = TestInput() config = configparser.ConfigParser(interpolation=None) config.read(file) sections = config.sections() global_properties = dict() cluster_ips = list() clusters = dict() client_ips = list() input.cbbackupmgr = dict() for section in sections: result = re.search('^cluster', section) if section == 'servers': ips = TestInputParser.get_server_ips(config, section) elif section == 'clients': client_ips = TestInputParser.get_server_ips(config, section) elif section == 'membase': input.membase_settings = TestInputParser.get_membase_settings(config, section) elif section == 'global': #get global stuff and override for those unset for option in config.options(section): global_properties[option] = config.get(section, option) elif section == 'elastic': input.elastic = TestInputParser.get_elastic_config(config, section, global_properties) elif section == 'bkrs_client': input.bkrs_client = TestInputParser.get_bkrs_client_config(config, section, global_properties, input.membase_settings) elif section == 'cbbackupmgr': input.cbbackupmgr = TestInputParser.get_cbbackupmgr_config(config, section) elif result is not None: cluster_list = TestInputParser.get_server_ips(config, section) cluster_ips.extend(cluster_list) clusters[count] = len(cluster_list) count += 1 # Setup 'cluster#' tag as dict # input.clusters -> {0: [ip:10.1.6.210 ssh_username:root, ip:10.1.6.211 ssh_username:root]} for cluster_ip in cluster_ips: servers.append(TestInputParser.get_server(cluster_ip, config)) servers = TestInputParser.get_server_options(servers, input.membase_settings, global_properties) for key, value in list(clusters.items()): end += value input.clusters[key] = servers[start:end] start += value # Setting up 'servers' tag servers = [] for ip in ips: servers.append(TestInputParser.get_server(ip, config)) input.servers = TestInputParser.get_server_options(servers, input.membase_settings, global_properties) if 'cbbackupmgr' not in sections: input.cbbackupmgr["name"] = "local_bkrs" if 'bkrs_client' not in sections: input.bkrs_client = None # Setting up 'clients' tag input.clients = client_ips return input
def parse_from_file(file): count = 0 start = 0 end = 0 servers = list() ips = list() input = TestInput() config = configparser.ConfigParser(interpolation=None) config.read(file) sections = config.sections() global_properties = dict() cluster_ips = list() clusters = dict() client_ips = list() input.cbbackupmgr = dict() for section in sections: result = re.search('^cluster', section) if section == 'servers': ips = TestInputParser.get_server_ips(config, section) elif section == 'clients': client_ips = TestInputParser.get_server_ips(config, section) elif section == 'membase': input.membase_settings = TestInputParser.get_membase_settings(config, section) elif section == 'global': #get global stuff and override for those unset for option in config.options(section): global_properties[option] = config.get(section, option) elif section == 'elastic': input.elastic = TestInputParser.get_elastic_config(config, section, global_properties) elif section == 'bkrs_client': input.bkrs_client = TestInputParser.get_bkrs_client_config(config, section, global_properties, input.membase_settings) elif section == 'cbbackupmgr': input.cbbackupmgr = TestInputParser.get_cbbackupmgr_config(config, section) elif result is not None: cluster_list = TestInputParser.get_server_ips(config, section) cluster_ips.extend(cluster_list) clusters[count] = len(cluster_list) count += 1 # Setup 'cluster#' tag as dict # input.clusters -> {0: [ip:10.1.6.210 ssh_username:root, ip:10.1.6.211 ssh_username:root]} for cluster_ip in cluster_ips: servers.append(TestInputParser.get_server(cluster_ip, config)) servers = TestInputParser.get_server_options(servers, input.membase_settings, global_properties) for key, value in list(clusters.items()): end += value input.clusters[key] = servers[start:end] start += value # Setting up 'servers' tag servers = [] for ip in ips: servers.append(TestInputParser.get_server(ip, config)) input.servers = TestInputParser.get_server_options(servers, input.membase_settings, global_properties) if 'cbbackupmgr' not in sections: input.cbbackupmgr["name"] = "local_bkrs" if 'bkrs_client' not in sections: input.bkrs_client = None # Setting up 'clients' tag input.clients = client_ips return input
def log_command_output(self, output, error, track_words=(), debug=True): """ Check for errors and tracked words in the output success means that there are no track_words in the output and there are no errors at all, if track_words is not empty if track_words=(), the result is not important, and we return True :param output: output to check in :param error: errors to check in the output :param track_words: words to track in the output :param debug: whether to log the errors and track words if found :return: True if all error and track words were not found in output else False """ success = True for line in error: if debug: self.log.error(line) if track_words: if "Warning" in line and "hugepages" in line: self.log.info( "There is a warning about transparent_hugepage " "may be in used when install cb server.\ So we will disable transparent_hugepage in this vm") output, error = self.execute_command( "echo never > " "/sys/kernel/mm/transparent_hugepage/enabled") self.log_command_output(output, error) success = True elif "Warning" in line and "systemctl daemon-reload" in line: self.log.info( "Unit file of couchbase-server.service changed on " "disk, we will run 'systemctl daemon-reload'") output, error = self.execute_command("systemctl daemon-reload") self.log_command_output(output, error) success = True elif "Warning" in line and "RPMDB altered outside of yum" in line: self.log.info("Warming: RPMDB altered outside of yum") success = True elif "dirname" in line: self.log.warning( "Ignore dirname error message during couchbase " "startup/stop/restart for CentOS 6.6 (MB-12536)") success = True elif "Created symlink from /etc/systemd/system" in line: self.log.info( "This error is due to fix_failed_install.py script " "that only happens in centos 7") success = True elif "Created symlink /etc/systemd/system/multi-user.target.wants/couchbase-server.service" in line: self.log.info(line) self.log.info( "This message comes only in debian8 and debian9 " "during installation. This can be ignored.") success = True else: self.log.info( "If couchbase server is running with this error. Go to" " log_command_output to add error mesg to bypass it.") success = False if self._check_output(list(track_words), output): success = False install_ok = False if self._check_output("hugepages", output): self.log.info( "There is a warning about transparent_hugepage may be " "in used when install cb server. So we will" "So we will disable transparent_hugepage in this vm") output, error = self.execute_command( "echo never > /sys/kernel/mm/transparent_hugepage/enabled") success = True install_ok = True if self._check_output("successfully installed couchbase server", output): success = True install_ok = True if not install_ok: self.log.error( 'something wrong happened on {0}!!! output:{1}, ' 'error:{2}, track_words:{3}' .format(self.ip, output, error, track_words)) elif debug and output: for line in output: self.log.info(line) return success
def log_command_output(self, output, error, track_words=(), debug=True): success = True for line in error: if debug: self.log.error(line) if track_words: if "Warning" in line and "hugepages" in line: self.log.info( "There is a warning about transparent_hugepage " "may be in used when install cb server.\ So we will disable transparent_hugepage in this vm") output, error = self.execute_command( "echo never > " "/sys/kernel/mm/transparent_hugepage/enabled") self.log_command_output(output, error) success = True elif "Warning" in line and "systemctl daemon-reload" in line: self.log.info( "Unit file of couchbase-server.service changed on " "disk, we will run 'systemctl daemon-reload'") output, error = self.execute_command("systemctl daemon-reload") self.log_command_output(output, error) success = True elif "Warning" in line and "RPMDB altered outside of yum" in line: self.log.info("Warming: RPMDB altered outside of yum") success = True elif "dirname" in line: self.log.warning( "Ignore dirname error message during couchbase " "startup/stop/restart for CentOS 6.6 (MB-12536)") success = True elif "Created symlink from /etc/systemd/system" in line: self.log.info( "This error is due to fix_failed_install.py script " "that only happens in centos 7") success = True elif "Created symlink /etc/systemd/system/multi-user.target.wants/couchbase-server.service" in line: self.log.info(line) self.log.info( "This message comes only in debian8 and debian9 " "during installation. This can be ignored.") success = True else: self.log.info( "If couchbase server is running with this error. Go to" " log_command_output to add error mesg to bypass it.") success = False if self._check_output(list(track_words), output): success = False install_ok = False if self._check_output("hugepages", output): self.log.info( "There is a warning about transparent_hugepage may be " "in used when install cb server. So we will" "So we will disable transparent_hugepage in this vm") output, error = self.execute_command( "echo never > /sys/kernel/mm/transparent_hugepage/enabled") success = True install_ok = True if self._check_output("successfully installed couchbase server", output): success = True install_ok = True if not install_ok: self.log.error( 'something wrong happened on {0}!!! output:{1}, ' 'error:{2}, track_words:{3}' .format(self.ip, output, error, track_words)) elif debug and output: for line in output: self.log.info(line) return success
def post_install(self): """ Post installation steps on a Windows server :return: True on successful post installation steps run else False """ cmds = self.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 Windows server
generate code for the above:
from shell_util.shell_conn import ShellConnection def delete_info_for_server(server, ipaddr=None): """ Delete the info associated with the given server or ipaddr :param server: server to delete the info for :param ipaddr: ipaddr to delete the info for :return: None """ ipaddr = ipaddr or server.ip if ipaddr in RemoteMachineShellConnection.__info_dict: del RemoteMachineShellConnection.__info_dict[ipaddr] RemoteMachineShellConnection.__info_dict.pop(ipaddr, None)
Delete the info associated with the given server or ipaddr
generate doc string for following function:
def get_file(self, remotepath, filename, todir): """ Downloads a file from a remote location to a local path. :param remotepath: Remote path to download the file from. :param filename: Name of the file to download. :param todir: Directory to save the file to. :return: True if the file was successfully downloaded else False """ if self.file_exists(remotepath, filename): if self.remote: sftp = self._ssh_client.open_sftp() try: filenames = sftp.listdir(remotepath) for name in filenames: if filename in name: log.info("found the file {0}/{1}".format(remotepath, name)) sftp.get('{0}/{1}'.format(remotepath, name), todir) sftp.close() return True sftp.close() return False except IOError: return False else: os.system("cp {0} {1}".format('{0}/{1}'.format(remotepath, filename), todir))
def get_file(self, remotepath, filename, todir): if self.file_exists(remotepath, filename): if self.remote: sftp = self._ssh_client.open_sftp() try: filenames = sftp.listdir(remotepath) for name in filenames: if filename in name: log.info("found the file {0}/{1}".format(remotepath, name)) sftp.get('{0}/{1}'.format(remotepath, name), todir) sftp.close() return True sftp.close() return False except IOError: return False else: os.system("cp {0} {1}".format('{0}/{1}'.format(remotepath, filename), todir))
generate comment for following function:
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)
def start_server(self): 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)
generate python code for
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
Code the following:
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)
Stop couchbase service on remote server
generate python code for
def get_instances(cls): """ Returns a list of instances of the class :return: generator that yields instances of the class """ for ins in cls.__refs__: yield ins
Returns a list of instances of the class
give a code to
def diag_eval(self, diag_eval_command): """ Executes a diag eval command on remote server :param diag_eval_command: diag eval command to execute e.g. "gen_server:cast(ns_cluster, leave)." :return: None """ self.execute_command( "curl -X POST localhost:%s/diag/eval -d \"%s\" -u %s:%s" % (self.port, diag_eval_command, self.server.rest_username, self.server.rest_password))
Executes a diag eval command on remote server
generate python code for the above
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 comment:
def remove_folders(self, list): """ Remove folders from list provided :param list: paths of folders to be removed :return: None """ for folder in list: output, error = self.execute_command( "rm -rf {0}".format(folder), debug=False) self.log_command_output(output, error)
def remove_folders(self, list): for folder in list: output, error = self.execute_command( "rm -rf {0}".format(folder), debug=False) self.log_command_output(output, error)
generate comment:
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
def get_process_statistics(self, process_name=None, process_pid=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
generate python code for
def disable_disk_readonly(self, disk_location): """ Disables read-only mode for the specified disk location. Override method for Windows :param disk_location: disk location to disable read-only mode. :return: None """ raise NotImplementedError
Disables read-only mode for the specified disk location. Override method for Windows
generate doc string for following function:
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
def __check_if_cb_service_stopped(self, service_name=None): 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
generate code for the following
def is_couchbase_installed(self): """ Check if Couchbase is installed on the remote server. This checks if the couchbase is installed in default or non default path. :return: True if Couchbase is installed on the remote server else False """ if self.nonroot: if self.file_exists("/home/%s/" % self.username, NR_INSTALL_LOCATION_FILE): output, error = self.execute_command("cat %s" % NR_INSTALL_LOCATION_FILE) if output and output[0]: log.info("Couchbase Server was installed in non default path %s" % output[0]) self.nr_home_path = output[0] file_path = self.nr_home_path + self.cb_path if self.file_exists(file_path, self.version_file): log.info("non root couchbase installed at %s " % self.ip) return True else: if self.file_exists(self.cb_path, self.version_file): log.info("{0} **** The linux version file {1} {2} exists" .format(self.ip, self.cb_path, self.version_file)) return True return False
Check if Couchbase is installed on the remote server. This checks if the couchbase is installed in default or non default path.
generate python code for the following
def start_memcached(self): """ Start memcached process on remote server :return: None """ o, r = self.execute_command("kill -SIGCONT $(pgrep memcached)") self.log_command_output(o, r, debug=False)
Start memcached process on remote server
Code the following:
def get_instances(cls): """ Returns a list of instances of the class :return: generator that yields instances of the class """ for ins in cls.__refs__: yield ins
Returns a list of instances of the class
generate python code for the above
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 enable_file_limit(self): """ Change the file limit to 100 for indexer process :return: None """ o, r = self.execute_command("prlimit --nofile=100 --pid $(pgrep indexer)") self.log_command_output(o, r)
Change the file limit to 100 for indexer process
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 python code for the above
def restart_couchbase(self): """ Restarts the Couchbase server on the remote server :return: None """ o, r = self.execute_command("service couchbase-server restart") self.log_command_output(o, r)
Restarts the Couchbase server on the remote server
def disable_firewall(self): """ Clear firewall rules on the remote server :return: None """ command_1 = "/sbin/iptables -F" command_2 = "/sbin/iptables -t nat -F" if self.nonroot: log.info("Non root user has no right to disable firewall, " "switching over to root") self.connect_with_user(user="root") output, error = self.execute_command(command_1) self.log_command_output(output, error) output, error = self.execute_command(command_2) self.log_command_output(output, error) self.connect_with_user(user=self.username) return output, error = self.execute_command(command_1) self.log_command_output(output, error, debug=False) output, error = self.execute_command(command_2) self.log_command_output(output, error, debug=False) self.connect_with_user(user=self.username)
def disable_firewall(self): command_1 = "/sbin/iptables -F" command_2 = "/sbin/iptables -t nat -F" if self.nonroot: log.info("Non root user has no right to disable firewall, " "switching over to root") self.connect_with_user(user="root") output, error = self.execute_command(command_1) self.log_command_output(output, error) output, error = self.execute_command(command_2) self.log_command_output(output, error) self.connect_with_user(user=self.username) return output, error = self.execute_command(command_1) self.log_command_output(output, error, debug=False) output, error = self.execute_command(command_2) self.log_command_output(output, error, debug=False) self.connect_with_user(user=self.username)
generate code for the above:
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
give a code to
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
give python code to
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
give python code to
import os def copy_files_local_to_remote(self, src_path, des_path): """ Copy multi files from local to remote server :param src_path: source path of the files to be copied :param des_path: destination path of the files to be copied :return: None """ files = os.listdir(src_path) self.log.info("copy files from {0} to {1}".format(src_path, des_path)) # self.execute_batch_command("cp -r {0}/* {1}".format(src_path, des_path)) for file in files: if file.find("wget") != 1: a = "" full_src_path = os.path.join(src_path, file) full_des_path = os.path.join(des_path, file) self.copy_file_local_to_remote(full_src_path, full_des_path)
Copy multi files from local to remote server
generate comment:
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
def __check_if_cb_service_stopped(self, service_name=None): 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
generate code for the above:
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
Code the following:
def post_install(self): """ Post installation steps on a Windows server :return: True on successful post installation steps run else False """ cmds = self.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 Windows server
Code the following:
def start_memcached(self): """ Start memcached process on remote server :return: None """ o, r = self.execute_command("kill -SIGCONT $(pgrep memcached)") self.log_command_output(o, r, debug=False)
Start memcached process on remote server
generate code for the above:
import time from time import sleep def monitor_process(self, process_name, duration_in_seconds=120): """ Monitor the given process till the given duration to check if it crashed or restarted :param process_name: the name of the process to monitor :param duration_in_seconds: the duration to monitor the process till, in seconds :return: True if the process didn't restart or crash else False """ end_time = time.time() + float(duration_in_seconds) last_reported_pid = None while time.time() < end_time: process = self.is_process_running(process_name) if process: if not last_reported_pid: last_reported_pid = process.pid elif not last_reported_pid == process.pid: message = 'Process {0} restarted. PID Old: {1}, New: {2}' log.info(message.format(process_name, last_reported_pid, process.pid)) return False # check if its equal else: # we should have an option to wait for the process # to start during the timeout # process might have crashed log.info( "{0}:process {1} is not running or it might have crashed!" .format(self.ip, process_name)) return False time.sleep(1) # log.info('process {0} is running'.format(process_name)) return True
Monitor the given process till the given duration to check if it crashed or restarted
generate comment:
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
def get_test_input(arguments): 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
generate comment for following function:
def kill_cbft_process(self): """ Kill the full text search process on remote server :return: output and error of command killing FTS process """ o, r = self.execute_command("killall -9 cbft") self.log_command_output(o, r) if r and r[0] and "command not found" in r[0]: o, r = self.execute_command("pkill cbft") self.log_command_output(o, r) return o, r
def kill_cbft_process(self): o, r = self.execute_command("killall -9 cbft") self.log_command_output(o, r) if r and r[0] and "command not found" in r[0]: o, r = self.execute_command("pkill cbft") self.log_command_output(o, r) return o, r
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.
give a code to
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
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 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
generate comment for above
def stop_schedule_tasks(self): """ Stop the scheduled tasks. Stops installme, removeme and upgrademe processes on remote server :return: None """ self.log.info("STOP SCHEDULE TASKS: installme, removeme & upgrademe") for task in ["installme", "removeme", "upgrademe"]: output, error = self.execute_command("cmd /c schtasks /end /tn %s" % task) self.log_command_output(output, error)
def stop_schedule_tasks(self): self.log.info("STOP SCHEDULE TASKS: installme, removeme & upgrademe") for task in ["installme", "removeme", "upgrademe"]: output, error = self.execute_command("cmd /c schtasks /end /tn %s" % task) self.log_command_output(output, error)
generate python code for the above
def start_couchbase(self): """ Starts couchbase on remote server :return: None """ running = self.is_couchbase_running() retry = 0 while not running and retry < 3: log.info("Starting couchbase server") if self.nonroot: log.info("Start Couchbase Server with non root method") o, r = self.execute_command( '%s%scouchbase-server \-- -noinput -detached' % (self.nr_home_path, LINUX_COUCHBASE_BIN_PATH)) self.log_command_output(o, r) else: log.info("Running systemd command on this server") o, r = self.execute_command("systemctl start couchbase-server.service") self.log_command_output(o, r) self.sleep(5,"waiting for couchbase server to come up") o, r = self.execute_command("systemctl status couchbase-server.service | grep ExecStop=/opt/couchbase/bin/couchbase-server") log.info("Couchbase server status: {}".format(o)) 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
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
give python code to
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
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 comment.
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
def post_install(self): 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
generate comment for following function:
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
def run(self): 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
generate python code for the above
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 code for the above:
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 comment:
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)
def restart_couchbase(self): o, r = self.execute_command("open /Applications/Couchbase\ Server.app") self.log_command_output(o, r)
generate comment.
def kill_goxdcr(self): """ Kill XDCR process on remote server :return: None """ o, r = self.execute_command("taskkill /F /T /IM goxdcr*") self.log_command_output(o, r)
def kill_goxdcr(self): o, r = self.execute_command("taskkill /F /T /IM goxdcr*") self.log_command_output(o, r)
generate comment.
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
def main(logger): 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
generate python code for the following
def start_server(self): """ Starts the Couchbase server on the remote server. The method runs the sever from non-default location if it's run as nonroot user. Else from default location. :return: None """ o, r = self.execute_command("open /Applications/Couchbase\ Server.app") self.log_command_output(o, r)
Starts the Couchbase server on the remote server. The method runs the sever from non-default location if it's run as nonroot user. Else from default location.
generate comment:
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)
generate python code for
def populate_debug_build_url(self): """ Populates the debug_info build url variable. :return: None """ self.node_install_info.debug_build_url = self.__construct_build_url( is_debuginfo_build=True) self.log.info("{} - Debug build url :: {}" .format(self.node_install_info.server.ip, self.node_install_info.debug_build_url))
Populates the debug_info build url variable.
generate comment.
def disconnect(self): """ Disconnect the ssh connection to remote machine. :return: None """ ShellConnection.disconnections += 1 self._ssh_client.close()
def disconnect(self): ShellConnection.disconnections += 1 self._ssh_client.close()
def __str__(self): """ Returns a string representation of the TestInputServer object with ip, port and ssh_username :return: A string representation of the TestInputServer object """ #ip_str = "ip:{0}".format(self.ip) ip_str = "ip:{0} port:{1}".format(self.ip, self.port) ssh_username_str = "ssh_username:{0}".format(self.ssh_username) return "{0} {1}".format(ip_str, ssh_username_str)
def __str__(self): #ip_str = "ip:{0}".format(self.ip) ip_str = "ip:{0} port:{1}".format(self.ip, self.port) ssh_username_str = "ssh_username:{0}".format(self.ssh_username) return "{0} {1}".format(ip_str, ssh_username_str)
generate python code for the following
def flush_os_caches(self): """ Flush OS caches on remote server :return: None """ o, r = self.execute_command("sync") self.log_command_output(o, r) o, r = self.execute_command("/sbin/sysctl vm.drop_caches=3") self.log_command_output(o, r)
Flush OS caches on remote server
generate python code for the following
def wait_for_couchbase_started(self, num_retries=5, poll_interval=5, message="Waiting for couchbase startup finish."): """ Waits for Couchbase server to start within the specified timeout period. :param num_retries: Number of times to wait for the Couchbase server to be online. :param poll_interval: interval in seconds between each retry attempt. :param message: Message to display while waiting for Couchbase server to be online. :return: None """ while num_retries > 0: if self.is_couchbase_running(): break self.sleep(timeout=poll_interval, message=message) num_retries -= 1 else: log.error("Couchbase server is failed to start!")
Waits for Couchbase server to start within the specified timeout period.
generate comment for following function:
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
def remove_directory_recursive(self, remote_path): 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
generate doc string for following function:
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 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
give a code to
def get_memcache_pid(self): """ Get the pid of memcached process :return: pid of memcached process """ raise NotImplementedError
Get the pid of memcached process
generate comment:
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)
def stop_network(self, stop_time): command = "net stop Netman && timeout {} && net start Netman" output, error = self.execute_command(command.format(stop_time)) self.log_command_output(output, error)
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)
def stop_network(self, stop_time): command = "nohup service network stop && sleep {} " \ "&& service network start &" output, error = self.execute_command(command.format(stop_time)) self.log_command_output(output, error)
generate 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 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
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.
generate code for the above:
def uninstall(self): """ Uninstalls Couchbase server on Linux machine :return: True on success """ self.shell.stop_couchbase() cmd = self.cmds if self.shell.nonroot: cmd = self.non_root_cmds cmd = cmd[self.shell.info.deliverable_type]["uninstall"] self.shell.execute_command(cmd) return True
Uninstalls Couchbase server on Linux machine
generate comment.
def unpause_memcached(self, os="linux"): """ Unpauses the memcached process on remote server :param os: os type of remote server :return: None """ log.info("*** unpause memcached process ***") if self.nonroot: o, r = self.execute_command("killall -SIGCONT memcached.bin") else: o, r = self.execute_command("killall -SIGCONT memcached") self.log_command_output(o, r)
def unpause_memcached(self, os="linux"): log.info("*** unpause memcached process ***") if self.nonroot: o, r = self.execute_command("killall -SIGCONT memcached.bin") else: o, r = self.execute_command("killall -SIGCONT memcached") self.log_command_output(o, r)
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: 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
def start_couchbase(self): 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
generate python code for the following
def enable_disk_readonly(self, disk_location): """ Enables read-only mode for the specified disk location. :param disk_location: disk location to enable read-only mode. :return: None """ o, r = self.execute_command("chmod -R 444 {}".format(disk_location)) self.log_command_output(o, r)
Enables read-only mode for the specified disk location.
def get_membase_settings(config, section): """ Get the membase settings information from the config :param config: config :param section: section to get information from :return: membase settings information """ membase_settings = TestInputMembaseSetting() for option in config.options(section): if option == 'rest_username': membase_settings.rest_username = config.get(section, option) if option == 'rest_password': membase_settings.rest_password = config.get(section, option) return membase_settings
Get the membase settings information from the config
generate code for the following
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
Check if certain word is present in the output
generate python code for
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
Check if certain word is present in the output
def copy_file_remote_to_local(self, rem_path, des_path): """ Copy file from remote server to local :param rem_path: remote path of the file to be copied :param des_path: destination path of the file to be copied :return: True if the file was successfully copied else False """ result = True sftp = self._ssh_client.open_sftp() try: sftp.get(rem_path, des_path) except IOError as e: self.log.error('Can not copy file', e) result = False finally: sftp.close() return result
def copy_file_remote_to_local(self, rem_path, des_path): result = True sftp = self._ssh_client.open_sftp() try: sftp.get(rem_path, des_path) except IOError as e: self.log.error('Can not copy file', e) result = False finally: sftp.close() return result
generate python code for the following
from shell_util.remote_machine import RemoteMachineProcess def is_process_running(self, process_name): """ Check if a process is running currently Override method for Windows :param process_name: name of the process to check :return: True if process is running else False """ self.log.info("%s - Checking for process %s" % (self.ip, process_name)) output, error = self.execute_command( 'tasklist | grep {0}'.format(process_name), debug=False) if error or output == [""] or output == []: return None words = output[0].split(" ") words = [x for x in words if x != ""] process = RemoteMachineProcess() process.pid = words[1] process.name = words[0] self.log.debug("Process is running: %s" % words) return process
Check if a process is running currently Override method for Windows
generate comment for above
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
def get_disk_info(self, win_info=None, mac=False): 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
generate doc string for following function:
def list_files(self, remote_path): """ List files in remote machine for a given directory :param remote_path: path of the directory to list :return: List of file paths found in remote machine and directory """ if self.remote: sftp = self._ssh_client.open_sftp() files = [] try: file_names = sftp.listdir(remote_path) for name in file_names: files.append({'path': remote_path, 'file': name}) sftp.close() except IOError: return [] return files else: p = Popen("ls {0}".format(remote_path), shell=True, stdout=PIPE, stderr=PIPE) files, stderro = p.communicate() return files
def list_files(self, remote_path): if self.remote: sftp = self._ssh_client.open_sftp() files = [] try: file_names = sftp.listdir(remote_path) for name in file_names: files.append({'path': remote_path, 'file': name}) sftp.close() except IOError: return [] return files else: p = Popen("ls {0}".format(remote_path), shell=True, stdout=PIPE, stderr=PIPE) files, stderro = p.communicate() return files
generate comment for above
def uninstall(self): """ Uninstalls Couchbase server on Windows machine :return: True on success """ self.shell.stop_couchbase() cmd = self.cmds["uninstall"] self.shell.execute_command(cmd) return True
def uninstall(self): self.shell.stop_couchbase() cmd = self.cmds["uninstall"] self.shell.execute_command(cmd) return True
generate python code for the above
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 comment:
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)
def restart_couchbase(self): 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)
generate code for 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
Code the following:
def kill_cbft_process(self): """ Kill the full text search process on remote server :return: output and error of command killing FTS process """ o, r = self.execute_command("killall -9 cbft") self.log_command_output(o, r) if r and r[0] and "command not found" in r[0]: o, r = self.execute_command("pkill cbft") self.log_command_output(o, r) return o, r
Kill the full text search process on remote server
give a code to
def delete_network_rule(self): """ Delete all traffic control rules set for eth0 :return: None """ o, r = self.execute_command("tc qdisc del dev eth0 root") self.log_command_output(o, r)
Delete all traffic control rules set for eth0
generate comment:
def reboot_node(self): """ Reboot the remote server :return: None """ o, r = self.execute_command("shutdown -r -f -t 0") self.log_command_output(o, r)
def reboot_node(self): o, r = self.execute_command("shutdown -r -f -t 0") self.log_command_output(o, r)