Пример #1
0
def check_if_ctdb_file_exists(servers=None):
    '''Checks if /etc/sysconfig/ctdb file exists
    Kwargs:
        servers (list): The list of servers on which we need
            to check if /etc/sysconfig/ctdb file exists.
            Defaults to ctdb_servers as specified in the config file.
    Returns:
        bool: True if successful, False otherwise
    Example:
        check_if_ctdb_file_exists()
    '''
    if servers is None:
        servers = (tc.global_config['gluster']['cluster_config']
                   ['smb']['ctdb_servers'])
    file_path = "/etc/sysconfig/ctdb"
    if not isinstance(servers, list):
        servers = [servers]
    _rc = True
    for server in servers:
        conn = tc.get_connection(server, "root")
        if not conn.modules.os.path.isfile(file_path):
            tc.logger.error("%s file not found on %s" % (file_path, server))
            _rc = False
        conn.close()

    return _rc
Пример #2
0
def remove_file(filename, server=''):
    """
    This module removes the given file
    @paramater:
        * filename - <str> absolute path name of the file to be created
        * server   - <str> (optional) name of the server to write the
                     file. If not given, the function takes the
                     first node from config file
    @Returns: True, on success
              False, on failure
    """
    if server == '':
        server = tc.servers[0]
    try:
        conn = tc.get_connection(server, 'root')
        if conn == -1:
            tc.logger.error("Unable to get connection to 'root' of node %s" \
                            % server)
            return False
        if conn.modules.os.path.exists(filename):
            conn.modules.os.remove(filename)
    except:
        tc.logger.error("Exception occured while removing file %s" % filename)
        return False

    finally:
        conn.close()

    return True
Пример #3
0
def append_string_to_file(mnode, filename, str_to_add_in_file):
    """Appends the given string in the file.

    Example:
        append_string_to_file("abc.def.com", "/var/log/messages",
                           "test_1_string")

    Args:
        mnode (str): Node on which cmd has to be executed.
        filename (str): absolute file path to append the string
        str_to_add_in_file (str): string to be added in the file,
            which is used as a start and stop string for parsing
            the file in search_pattern_in_file().

    Returns:
        True, on success, False otherwise
    """
    try:
        conn = tc.get_connection(mnode, 'root')
        if conn == -1:
            tc.logger.error("Unable to get connection to 'root' of node %s"
                            " in append_string_to_file()" % mnode)
            return False

        with conn.builtin.open(filename, 'a') as _filehandle:
            _filehandle.write(str_to_add_in_file)

        return True
    except:
        tc.logger.error("Exception occured while adding string to "
                        "file %s in append_string_to_file()" % filename)
        return False
    finally:
        conn.close()
Пример #4
0
def append_string_to_file(mnode, filename, str_to_add_in_file):
    """Appends the given string in the file.

    Example:
        append_string_to_file("abc.def.com", "/var/log/messages",
                           "test_1_string")

    Args:
        mnode (str): Node on which cmd has to be executed.
        filename (str): absolute file path to append the string
        str_to_add_in_file (str): string to be added in the file,
            which is used as a start and stop string for parsing
            the file in search_pattern_in_file().

    Returns:
        True, on success, False otherwise
    """
    try:
        conn = tc.get_connection(mnode, 'root')
        if conn == -1:
            tc.logger.error("Unable to get connection to 'root' of node %s"
                            " in append_string_to_file()" % mnode)
            return False

        with conn.builtin.open(filename, 'a') as _filehandle:
            _filehandle.write(str_to_add_in_file)

        return True
    except:
        tc.logger.error("Exception occured while adding string to "
                        "file %s in append_string_to_file()" % filename)
        return False
    finally:
        conn.close()
Пример #5
0
def remove_file(filename, server=""):
    """
    This module removes the given file
    @paramater:
        * filename - <str> absolute path name of the file to be created
        * server   - <str> (optional) name of the server to write the
                     file. If not given, the function takes the
                     first node from config file
    @Returns: True, on success
              False, on failure
    """
    if server == "":
        server = tc.servers[0]
    try:
        conn = tc.get_connection(server, "root")
        if conn == -1:
            tc.logger.error("Unable to get connection to 'root' of node %s" % server)
            return False
        if conn.modules.os.path.exists(filename):
            conn.modules.os.remove(filename)
    except:
        tc.logger.error("Exception occured while removing file %s" % filename)
        return False

    finally:
        conn.close()

    return True
Пример #6
0
def check_if_ctdb_file_exists(servers=None):
    '''Checks if /etc/sysconfig/ctdb file exists
    Kwargs:
        servers (list): The list of servers on which we need
            to check if /etc/sysconfig/ctdb file exists.
            Defaults to ctdb_servers as specified in the config file.
    Returns:
        bool: True if successful, False otherwise
    Example:
        check_if_ctdb_file_exists()
    '''
    if servers is None:
        servers = (tc.global_config['gluster']['cluster_config']['smb']
                   ['ctdb_servers'])
        server_host_list = []
        for server in servers:
            server_host_list.append(server['host'])
        servers = server_host_list
    file_path = "/etc/sysconfig/ctdb"
    if not isinstance(servers, list):
        servers = [servers]
    _rc = True
    for server in servers:
        conn = tc.get_connection(server, "root")
        if not conn.modules.os.path.isfile(file_path):
            tc.logger.error("%s file not found on %s" % (file_path, server))
            _rc = False
        conn.close()

    return _rc
Пример #7
0
def create_geo_passwordless_ssh(mnode, snode, gsuser=''):
    """
        Sets up the password less ssh between two specified nodes

        Returns True if successfull and False on failure
    """
    if gsuser == '':
        gsuser = '******'
    loc = "/var/lib/glusterd/geo-replication/"
    mconn = tc.get_connection(mnode, user='******')
    sconn = tc.get_connection(snode, user=gsuser)
    tc.run(mnode, "ssh-keyscan %s >> /root/.ssh/known_hosts" % snode)
    if not mconn.modules.os.path.isfile('/root/.ssh/id_rsa'):
        if not mconn.modules.os.path.isfile('%s/secret.pem' % loc):
            tc.logger.debug("id_rsa not present. Generating with gsec_create")
            ret = tc.run(mnode, "gluster system:: execute gsec_create")
            if ret[0] != 0:
                tc.logger.error("Unable to generate the secret pem file")
                return False
        tc.logger.debug("Copying the secret.pem to id_rsa")
        mconn.modules.shutil.copyfile("%s/secret.pem" % loc, \
                "/root/.ssh/id_rsa")
        mconn.modules.os.chmod("/root/.ssh/id_rsa", 0600)
        tc.logger.debug("Copying the secret.pem.pub to id_rsa.pub")
        mconn.modules.shutil.copyfile("%s/secret.pem.pub" % loc, \
                "/root/.ssh/id_rsa.pub")
    try:
        slocal = sconn.modules.os.path.expanduser('~')
        sfh = sconn.builtin.open("%s/.ssh/authorized_keys" % slocal, "a")
        with mconn.builtin.open("/root/.ssh/id_rsa.pub", 'r') as f:
            for line in f:
                sfh.write(line)
    except:
        tc.logger.error("Unable to establish passwordless ssh %s@%s to %s@%s" \
                % ('root', mnode, gsuser, snode))
        return False
    finally:
        sfh.close()
        mconn.close()
        sconn.close()
    tc.logger.debug("Password less ssh setup from %s@%s to %s@%s is %s" \
            % ('root', mnode, gsuser, snode, 'successfull'))
    return True
Пример #8
0
def list_files(dir_path, parse_str="", mnode=None):
    """This module list files from the given file path

    Example:
        list_files("/root/dir1/")

    Args:
        dir_path (str): directory path name

    Kwargs:
        parse_str (str): sub string of the filename to be fetched
        mnode (str): Node on which cmd has to be executed.

    Returns:
        NoneType: None if command execution fails, parse errors.
        list: files with absolute name
    """
    if mnode is None:
        mnode = tc.clients[0]

    try:
        conn = tc.get_connection(mnode, 'root')
        if conn == -1:
            tc.logger.error("Unable to get connection to 'root' of node %s"
                            % mnode)
            return None

        filepaths = []
        for root, directories, files in conn.modules.os.walk(dir_path):
            for filename in files:
                if parse_str != "":
                    if parse_str in filename:
                        filepath = conn.modules.os.path.join(root, filename)
                        filepaths.append(filepath)
                else:
                    filepath = conn.modules.os.path.join(root, filename)
                    filepaths.append(filepath)
        return filepaths
    except:
        tc.logger.error("Exception occured in list_files()")
        return None

    finally:
        conn.close()
Пример #9
0
def list_files(dir_path, parse_str="", mnode=None):
    """This module list files from the given file path

    Example:
        list_files("/root/dir1/")

    Args:
        dir_path (str): directory path name

    Kwargs:
        parse_str (str): sub string of the filename to be fetched
        mnode (str): Node on which cmd has to be executed.

    Returns:
        NoneType: None if command execution fails, parse errors.
        list: files with absolute name
    """
    if mnode is None:
        mnode = tc.clients[0]

    try:
        conn = tc.get_connection(mnode, 'root')
        if conn == -1:
            tc.logger.error("Unable to get connection to 'root' of node %s" %
                            mnode)
            return None

        filepaths = []
        for root, directories, files in conn.modules.os.walk(dir_path):
            for filename in files:
                if parse_str != "":
                    if parse_str in filename:
                        filepath = conn.modules.os.path.join(root, filename)
                        filepaths.append(filepath)
                else:
                    filepath = conn.modules.os.path.join(root, filename)
                    filepaths.append(filepath)
        return filepaths
    except:
        tc.logger.error("Exception occured in list_files()")
        return None

    finally:
        conn.close()
Пример #10
0
def create_ctdb_public_addresses(servers=None):
    '''Creates the /etc/ctdb/public_addresses file.
       This file will have a list of vips, routing-prefix and interface,
       in the following format - vip/routing-prefix interface.
    Kwargs:
        servers (list): The list of servers on which we need
            to create the /etc/ctdb/public_addresses file.
            Defaults to ctdb_servers as specified in the config file.
    Returns:
        bool: True if successful, False otherwise
    Example:
        create_ctdb_public_addresses()
    '''
    if servers is None:
        servers = (tc.global_config['gluster']['cluster_config']['smb']
                   ['ctdb_servers'])
        server_host_list = []
        for server in servers:
            server_host_list.append(server['host'])
        servers = server_host_list
    ctdb_vips = (
        tc.global_config['gluster']['cluster_config']['smb']['ctdb_vips'])
    if not isinstance(servers, list):
        servers = [servers]
    _rc = True
    data_to_write = ""
    file_path = "/etc/ctdb/public_addresses"
    for each_vip in ctdb_vips:
        data_to_write = (data_to_write + each_vip['vip'] + "/" +
                         str(each_vip['routing_prefix']) + " " +
                         each_vip['interface'] + "\n")
    for server in servers:
        conn = tc.get_connection(server, "root")
        try:
            FH = conn.builtin.open(file_path, "w")
            FH.write(data_to_write)
        except IOError as e:
            tc.logger.error(e)
            _rc = False
        finally:
            FH.close()

    return _rc
Пример #11
0
def create_ctdb_public_addresses(servers=None):
    '''Creates the /etc/ctdb/public_addresses file.
       This file will have a list of vips, routing-prefix and interface,
       in the following format - vip/routing-prefix interface.
    Kwargs:
        servers (list): The list of servers on which we need
            to create the /etc/ctdb/public_addresses file.
            Defaults to ctdb_servers as specified in the config file.
    Returns:
        bool: True if successful, False otherwise
    Example:
        create_ctdb_public_addresses()
    '''
    if servers is None:
        servers = (tc.global_config['gluster']['cluster_config']
                   ['smb']['ctdb_servers'])
        server_host_list = []
        for server in servers:
            server_host_list.append(server['host'])
        servers = server_host_list
    ctdb_vips = (tc.global_config['gluster']['cluster_config']
                 ['smb']['ctdb_vips'])
    if not isinstance(servers, list):
        servers = [servers]
    _rc = True
    data_to_write = ""
    file_path = "/etc/ctdb/public_addresses"
    for each_vip in ctdb_vips:
        data_to_write = (data_to_write + each_vip['vip'] + "/" +
                         str(each_vip['routing_prefix']) + " " +
                         each_vip['interface'] + "\n")
    for server in servers:
        conn = tc.get_connection(server, "root")
        try:
            FH = conn.builtin.open(file_path, "w")
            FH.write(data_to_write)
        except IOError as e:
            tc.logger.error(e)
            _rc = False
        finally:
            FH.close()

    return _rc
Пример #12
0
def create_ctdb_nodes_file(servers=None):
    '''Creates the /etc/ctdb/nodes file.
       This file will have a list of IPs of all the servers.
    Kwargs:
        servers (list): The list of servers on which we need
            to update the /etc/ctdb/nodes file.
            Defaults to ctdb_servers as specified in the config file.
    Returns:
        bool: True if successful, False otherwise
    Example:
        create_ctdb_nodes_file()
    '''
    if servers is None:
        servers = (tc.global_config['gluster']['cluster_config']['smb']
                   ['ctdb_servers'])
        server_host_list = []
        for server in servers:
            server_host_list.append(server['host'])
        servers = server_host_list
    file_path = "/etc/ctdb/nodes"
    _rc = True
    ctdb_ips_list = []
    if not isinstance(servers, list):
        servers = [servers]
    for server in servers:
        ret, out, _ = tc.run(server, "hostname -i")
        if ret != 0:
            tc.logger.error("failed to get ip of %s" % server)
            _rc = False
        ctdb_ips_list.append(out)
    for server in servers:
        conn = tc.get_connection(server, "root")
        try:
            FH = conn.builtin.open(file_path, "w")
            FH.write("".join(ctdb_ips_list))
        except IOError as e:
            tc.logger.error(e)
            _rc = False
        finally:
            FH.close()

    return _rc
Пример #13
0
def create_ctdb_nodes_file(servers=None):
    '''Creates the /etc/ctdb/nodes file.
       This file will have a list of IPs of all the servers.
    Kwargs:
        servers (list): The list of servers on which we need
            to update the /etc/ctdb/nodes file.
            Defaults to ctdb_servers as specified in the config file.
    Returns:
        bool: True if successful, False otherwise
    Example:
        create_ctdb_nodes_file()
    '''
    if servers is None:
        servers = (tc.global_config['gluster']['cluster_config']
                   ['smb']['ctdb_servers'])
        server_host_list = []
        for server in servers:
            server_host_list.append(server['host'])
        servers = server_host_list
    file_path = "/etc/ctdb/nodes"
    _rc = True
    ctdb_ips_list = []
    if not isinstance(servers, list):
        servers = [servers]
    for server in servers:
        ret, out, _ = tc.run(server, "hostname -i")
        if ret != 0:
            tc.logger.error("failed to get ip of %s" % server)
            _rc = False
        ctdb_ips_list.append(out)
    for server in servers:
        conn = tc.get_connection(server, "root")
        try:
            FH = conn.builtin.open(file_path, "w")
            FH.write("".join(ctdb_ips_list))
        except IOError as e:
            tc.logger.error(e)
            _rc = False
        finally:
            FH.close()

    return _rc
Пример #14
0
def update_ganesha_ha_conf(no_of_servers=None):
    '''Updates the ganesha-ha.conf file, with VIPs and hostnames.
    Kwargs:
        no_of_servers (Optional[int]): The number of nodes on which we have
            to modify the ganesha-ha.conf file. Default it takes
            the number of servers from the pool list.
    Returns:
        bool: True if successfull, False otherwise.
    '''
    if no_of_servers is None:
        servers = nodes_from_pool_list()
        no_of_servers = len(servers)
    else:
        servers = tc.servers[0:no_of_servers]
    server_hostname_dict = get_host_by_name(servers)
    hostnames = server_hostname_dict.values()
    hosts = ','.join(hostnames)
    file_src_path = "/etc/ganesha/ganesha-ha.conf.sample"
    file_dest_path = "/etc/ganesha/ganesha-ha.conf"
    ha_server = tc.run(tc.servers[0], "hostname")
    conn = tc.get_connection(tc.servers[0], "root")
    if conn.modules.os.path.isfile(file_src_path) == True:
        tc.logger.info("%s file available and should be updated as "
                       "ganesha-ha.conf" % file_src_path)
        try:
            conn.modules.shutil.copy(file_src_path, file_dest_path)
            FH = conn.builtin.open(file_dest_path, "r+")
        except IOError as e:
            tc.logger.error(e)
            return False
    lines = FH.readlines()
    FH.seek(0)
    FH.truncate()
    for i in range(len(lines)):
        if re.search("HA_NAME", lines[i]) != None:
            lines[i] = re.sub(r'^HA_NAME.*',
                              "HA_NAME=\"G" + str(time.time()) + "\"",
                              lines[i])
        if re.search("HA_VOL_SERVER", lines[i]) != None:
            lines[i] = re.sub(r'^HA_VOL_SERVER.*',
                              "HA_VOL_SERVER=\"" + ha_server[1].strip() + "\"",
                              lines[i])
        if re.search("HA_CLUSTER_NODES", lines[i]) != None:
            lines[i] = re.sub(r'^HA_CLUSTER_NODES.*',
                              "HA_CLUSTER_NODES=\"" + hosts + "\"", lines[i])
        if re.search("VIP_", lines[i]) != None:
            lines[i] = re.sub(r'.*VIP_.*\n', "", lines[i])
    vips = (
        tc.global_config["gluster"]["cluster_config"]["nfs_ganesha"]["vips"])
    for i in range(no_of_servers):
        lines += "VIP_%s=\"%s\"\n" % (hostnames[i], vips[i])
    FH.write(''.join(lines))
    # create a local copy of this ha.conf file
    f = open("/tmp/ganesha-ha.conf", "w")
    f.write(''.join(lines))
    f.close()
    FH.close()
    conn.close()
    # copy this ha.conf file to all the other nodes
    for node in tc.servers[1:no_of_servers]:
        ret = tc.upload(node, "/tmp/ganesha-ha.conf", file_dest_path)

    return True
Пример #15
0
def update_ganesha_ha_conf(no_of_servers=None):
    '''Updates the ganesha-ha.conf file, with VIPs and hostnames.
    Kwargs:
        no_of_servers (Optional[int]): The number of nodes on which we have
            to modify the ganesha-ha.conf file. Default it takes
            the number of servers from the pool list.
    Returns:
        bool: True if successfull, False otherwise.
    '''
    if no_of_servers is None:
        servers = nodes_from_pool_list()
        no_of_servers = len(servers)
    else:
        servers = tc.servers[0:no_of_servers]
    server_hostname_dict = get_host_by_name(servers)
    hostnames = server_hostname_dict.values()
    hosts = ','.join(hostnames)
    file_src_path = "/etc/ganesha/ganesha-ha.conf.sample"
    file_dest_path = "/etc/ganesha/ganesha-ha.conf"
    ha_server = tc.run(tc.servers[0], "hostname")
    conn = tc.get_connection(tc.servers[0], "root")
    if conn.modules.os.path.isfile(file_src_path) == True:
        tc.logger.info("%s file available and should be updated as "
                       "ganesha-ha.conf" % file_src_path)
        try:
            conn.modules.shutil.copy(file_src_path, file_dest_path)
            FH = conn.builtin.open(file_dest_path, "r+")
        except IOError as e:
            tc.logger.error(e)
            return False
    lines = FH.readlines()
    FH.seek(0)
    FH.truncate()
    for i in range(len(lines)):
        if re.search("HA_NAME", lines[i]) != None:
            lines[i] = re.sub(r'^HA_NAME.*', "HA_NAME=\"G"+str(time.time()) +
                              "\"", lines[i])
        if re.search("HA_VOL_SERVER", lines[i]) != None:
            lines[i] = re.sub(r'^HA_VOL_SERVER.*', "HA_VOL_SERVER=\"" +
                              ha_server[1].strip()+"\"", lines[i])
        if re.search("HA_CLUSTER_NODES", lines[i]) != None:
            lines[i] = re.sub(r'^HA_CLUSTER_NODES.*', "HA_CLUSTER_NODES=\"" +
                              hosts+"\"", lines[i])
        if re.search("VIP_", lines[i]) != None:
            lines[i] = re.sub(r'.*VIP_.*\n', "", lines[i])
    vips = (tc.global_config["gluster"]["cluster_config"]
            ["nfs_ganesha"]["vips"])
    for i in range(no_of_servers):
        lines += "VIP_%s=\"%s\"\n" % (hostnames[i], vips[i])
    FH.write(''.join(lines))
    # create a local copy of this ha.conf file
    f = open("/tmp/ganesha-ha.conf", "w")
    f.write(''.join(lines))
    f.close()
    FH.close()
    conn.close()
    # copy this ha.conf file to all the other nodes
    for node in tc.servers[1:no_of_servers]:
        ret = tc.upload(node, "/tmp/ganesha-ha.conf", file_dest_path)

    return True
Пример #16
0
def create_nfs_passwordless_ssh(snodes=[], guser=None, mnode=None):
    '''Sets up the passwordless ssh between mnode and all other snodes.
    Args:
        snodes (list): List of nodes for which we require passwordless
            ssh from mnode.
    Kwargs:
        guser (Optional[str]): Username . Default value is root.
        mnode (Optional[str]): Node from which we require passwordless
            ssh to snodes. Default value is tc.servers[0].
    Returns:
        bool: True if successfull, False otherwise
    '''
    if guser is None:
        guser = '******'
    if mnode is None:
        mnode = tc.servers[0]
    if not isinstance(snodes, list):
        snodes = [snodes]
    loc = "/var/lib/glusterd/nfs/"
    mconn = tc.get_connection(mnode, user='******')
    if not mconn.modules.os.path.isfile('/root/.ssh/id_rsa'):
        if not mconn.modules.os.path.isfile('%s/secret.pem' % loc):
            ret, _, _ = tc.run(mnode, "ssh-keygen -f /var/lib/glusterd/nfs/"
                               "secret.pem -q -N ''")
            if ret != 0:
                tc.logger.error("Unable to generate the secret pem file")
                return False
        mconn.modules.os.chmod("%s/secret.pem" % loc, 0600)
        mconn.modules.shutil.copyfile("%s/secret.pem" % loc,
                                      "/root/.ssh/id_rsa")
        mconn.modules.os.chmod("/root/.ssh/id_rsa", 0600)
        tc.logger.debug("Copying the secret.pem.pub to id_rsa.pub")
        mconn.modules.shutil.copyfile("%s/secret.pem.pub" % loc,
                                      "/root/.ssh/id_rsa.pub")
    else:
        mconn.modules.shutil.copyfile("/root/.ssh/id_rsa",
                                      "%s/secret.pem" % loc)
        mconn.modules.os.chmod("%s/secret.pem" % loc, 0600)
        tc.logger.debug("Copying the id_rsa.pub to secret.pem.pub")
        mconn.modules.shutil.copyfile("/root/.ssh/id_rsa.pub",
                                      "%s/secret.pem.pub" % loc)
    if not isinstance(snodes, list):
        snodes = [snodes]
    for snode in snodes:
        sconn = tc.get_connection(snode, user=guser)
        try:
            slocal = sconn.modules.os.path.expanduser('~')
            sfh = sconn.builtin.open("%s/.ssh/authorized_keys" % slocal, "a")
            with mconn.builtin.open("/root/.ssh/id_rsa.pub", 'r') as f:
                for line in f:
                    sfh.write(line)
        except:
            tc.logger.error("Unable to establish passwordless ssh %s@%s to "
                            "%s@%s" % ('root', mnode, guser, snode))
            return False
        finally:
            sfh.close()
            sconn.close()
    mconn.close()
    time.sleep(30)
    for snode in snodes:
        ret, _, _ = tc.run(mnode, "ssh-keyscan -H %s  >> ~/.ssh/known_hosts"
                           % snode)
        if snode != mnode:
            ret, _, _ = tc.run(mnode, "scp /var/lib/glusterd/nfs/secret.*  "
                               "%s:/var/lib/glusterd/nfs/" % snode)
            if ret != 0:
                return False

    return True
Пример #17
0
def create_nfs_passwordless_ssh(snodes=[], guser=None, mnode=None):
    '''Sets up the passwordless ssh between mnode and all other snodes.
    Args:
        snodes (list): List of nodes for which we require passwordless
            ssh from mnode.
    Kwargs:
        guser (Optional[str]): Username . Default value is root.
        mnode (Optional[str]): Node from which we require passwordless
            ssh to snodes. Default value is tc.servers[0].
    Returns:
        bool: True if successfull, False otherwise
    '''
    if guser is None:
        guser = '******'
    if mnode is None:
        mnode = tc.servers[0]
    if not isinstance(snodes, list):
        snodes = [snodes]
    loc = "/var/lib/glusterd/nfs/"
    mconn = tc.get_connection(mnode, user='******')
    if not mconn.modules.os.path.isfile('/root/.ssh/id_rsa'):
        if not mconn.modules.os.path.isfile('%s/secret.pem' % loc):
            ret, _, _ = tc.run(
                mnode, "ssh-keygen -f /var/lib/glusterd/nfs/"
                "secret.pem -q -N ''")
            if ret != 0:
                tc.logger.error("Unable to generate the secret pem file")
                return False
        mconn.modules.os.chmod("%s/secret.pem" % loc, 0600)
        mconn.modules.shutil.copyfile("%s/secret.pem" % loc,
                                      "/root/.ssh/id_rsa")
        mconn.modules.os.chmod("/root/.ssh/id_rsa", 0600)
        tc.logger.debug("Copying the secret.pem.pub to id_rsa.pub")
        mconn.modules.shutil.copyfile("%s/secret.pem.pub" % loc,
                                      "/root/.ssh/id_rsa.pub")
    else:
        mconn.modules.shutil.copyfile("/root/.ssh/id_rsa",
                                      "%s/secret.pem" % loc)
        mconn.modules.os.chmod("%s/secret.pem" % loc, 0600)
        tc.logger.debug("Copying the id_rsa.pub to secret.pem.pub")
        mconn.modules.shutil.copyfile("/root/.ssh/id_rsa.pub",
                                      "%s/secret.pem.pub" % loc)
    if not isinstance(snodes, list):
        snodes = [snodes]
    for snode in snodes:
        sconn = tc.get_connection(snode, user=guser)
        try:
            slocal = sconn.modules.os.path.expanduser('~')
            sfh = sconn.builtin.open("%s/.ssh/authorized_keys" % slocal, "a")
            with mconn.builtin.open("/root/.ssh/id_rsa.pub", 'r') as f:
                for line in f:
                    sfh.write(line)
        except:
            tc.logger.error("Unable to establish passwordless ssh %s@%s to "
                            "%s@%s" % ('root', mnode, guser, snode))
            return False
        finally:
            sfh.close()
            sconn.close()
    mconn.close()
    time.sleep(30)
    for snode in snodes:
        ret, _, _ = tc.run(mnode,
                           "ssh-keyscan -H %s  >> ~/.ssh/known_hosts" % snode)
        if snode != mnode:
            ret, _, _ = tc.run(
                mnode, "scp /var/lib/glusterd/nfs/secret.*  "
                "%s:/var/lib/glusterd/nfs/" % snode)
            if ret != 0:
                return False

    return True
Пример #18
0
def write_file(filename, file_contents=" ", create_mode='', filesize='', \
        server=''):
    """
    This module writes the file along with file contents
    @paramater:
        * filename - <str> absolute path name of the file to be created
        * file_contents - <str> (optional) file content
        * create_mode - <str> (optional) mode to create the file
        * filesize - <str> (optional) filesize
        * server   - <str> (optional) name of the server to write the
                     file. If not given, the function takes the
                     first node from config file
    @Returns: True, on success
              False, on failure
    """
    if server == '':
        server = tc.servers[0]

    if create_mode == '':
        create_mode = 'open'

    if create_mode != 'open':
        try:
            conn = tc.get_connection(server, 'root')
            if conn == -1:
                tc.logger.error("Unable to get connection to 'root' of "
                                "node %s" % server)
                return False
            if not conn.modules.os.path.exists(conn.modules.os.path.\
                    dirname(filename)):
                conn.modules.os.makedirs(conn.modules.os.path.\
                        dirname(filename))
        except:
            tc.logger.error("Exception occured while creating directory  for "
                            "file %s" % filename)
            return False
        finally:
            conn.close()

    if create_mode == 'open':
        try:
            conn = tc.get_connection(server, 'root')
            if conn == -1:
                tc.logger.error("Unable to get connection to 'root' of node "
                                "%s" % server)
                return False

            if not conn.modules.os.path.exists(conn.modules.os.path.\
                    dirname(filename)):
                conn.modules.os.makedirs(conn.modules.os.path.\
                        dirname(filename))

            with conn.builtin.open(filename, 'w') as _filehandle:
                _filehandle.write(file_contents)
        except:
            tc.logger.error("Exception occured while writing file %s" \
                    % filename)
            return False

        finally:
            conn.close()
    elif create_mode == 'echo':
        cmd = "echo " + file_contents + " > " + filename
        ret, _, _ = tc.run(server, cmd)
        if ret != 0:
            return False
    elif create_mode == 'touch':
        cmd = "touch " + filename
        ret, _, _ = tc.run(server, cmd)
        if ret != 0:
            return False
    elif create_mode == 'dd':
        if filesize == '':
            tc.logger.error("Invalid argument for dd cmd. Pass correct \
                             number of parameters")
            return False

        cmd = "dd if=/dev/zero of=%s bs=%s count=1" % (filename, filesize)
        ret, _, _ = tc.run(server, cmd)
        if ret != 0:
            return False

    return True
Пример #19
0
def write_file(filename, file_contents=" ", create_mode="", filesize="", server=""):
    """
    This module writes the file along with file contents
    @paramater:
        * filename - <str> absolute path name of the file to be created
        * file_contents - <str> (optional) file content
        * create_mode - <str> (optional) mode to create the file
        * filesize - <str> (optional) filesize
        * server   - <str> (optional) name of the server to write the
                     file. If not given, the function takes the
                     first node from config file
    @Returns: True, on success
              False, on failure
    """
    if server == "":
        server = tc.servers[0]

    if create_mode == "":
        create_mode = "open"

    if create_mode != "open":
        try:
            conn = tc.get_connection(server, "root")
            if conn == -1:
                tc.logger.error("Unable to get connection to 'root' of " "node %s" % server)
                return False
            if not conn.modules.os.path.exists(conn.modules.os.path.dirname(filename)):
                conn.modules.os.makedirs(conn.modules.os.path.dirname(filename))
        except:
            tc.logger.error("Exception occured while creating directory  for " "file %s" % filename)
            return False
        finally:
            conn.close()

    if create_mode == "open":
        try:
            conn = tc.get_connection(server, "root")
            if conn == -1:
                tc.logger.error("Unable to get connection to 'root' of node " "%s" % server)
                return False

            if not conn.modules.os.path.exists(conn.modules.os.path.dirname(filename)):
                conn.modules.os.makedirs(conn.modules.os.path.dirname(filename))

            with conn.builtin.open(filename, "w") as _filehandle:
                _filehandle.write(file_contents)
        except:
            tc.logger.error("Exception occured while writing file %s" % filename)
            return False

        finally:
            conn.close()
    elif create_mode == "echo":
        cmd = "echo " + file_contents + " > " + filename
        ret, _, _ = tc.run(server, cmd)
        if ret != 0:
            return False
    elif create_mode == "touch":
        cmd = "touch " + filename
        ret, _, _ = tc.run(server, cmd)
        if ret != 0:
            return False
    elif create_mode == "dd":
        if filesize == "":
            tc.logger.error(
                "Invalid argument for dd cmd. Pass correct \
                             number of parameters"
            )
            return False

        cmd = "dd if=/dev/zero of=%s bs=%s count=1" % (filename, filesize)
        ret, _, _ = tc.run(server, cmd)
        if ret != 0:
            return False

    return True