示例#1
0
def generator_sdk_ca(agency_dir, sdk_dir, gm=False):
    """[generate sdkcert]
    
    Arguments:
        dir {[path]} -- [agency cert path]
        If operation success, dir will generate sdk dir under the target path, the content is sdk_cert.
    """
    dir = os.path.abspath(agency_dir)
    sdk_dir = os.path.abspath(sdk_dir)
    try:
        if gm:
            (status, result
             ) = utils.getstatusoutput('bash ' + path.get_path() +
                                       '/scripts/ca/gm/cts.sh gen_sdk_cert ' +
                                       dir + ' ' + sdk_dir)
        else:
            (status, result
             ) = utils.getstatusoutput('bash ' + path.get_path() +
                                       '/scripts/ca/cts.sh gen_sdk_cert ' +
                                       dir + ' ' + sdk_dir)
        if not status:
            consoler.info(' Generate sdk cert successful! dir is %s.',
                          sdk_dir + '/sdk')
            logger.info(' Generate sdk cert successful! dir is %s.',
                        sdk_dir + '/sdk')
        else:
            logger.error('  Generate sdk cert failed! Result is %s' % result)
            raise MCError(' Generate sdk cert failed! Result is %s' % result)
    except MCError as me:
        consoler.error(' \033[1;31m %s \033[0m', me)
    except Exception as e:
        consoler.error(
            ' \033[1;31m Generate root cert failed! excepion is %s.\033[0m', e)
        logger.error('  Generate root cert failed! Result is %s' % result)
示例#2
0
def generate_root_ca(_dir):
    """[generate root cert]

    Arguments:
        dir {[path]} -- [root cert path]
    """
    try:
        ca_dir = os.path.abspath(_dir)
        if utils.Status.gm_option:
            os.chdir('{}/scripts/gm/'.format(path.get_path()))
            (status, result) = utils.getstatusoutput('./cts.sh gen_chain_cert {}'
                                                     .format(ca_dir))
            os.chdir('{}'.format(path.get_path()))
        else:
            os.chdir('{}/scripts'.format(path.get_path()))
            (status, result) = utils.getstatusoutput('./cts.sh gen_chain_cert {}'
                                                     .format(ca_dir))
            os.chdir('{}'.format(path.get_path()))
        if bool(status):
            LOGGER.error(
                ' cts.sh failed! status is %d, output is %s, dir is %s.', status, result, ca_dir)
            raise MCError('cts.sh failed! status is %d, output is %s, dir is %s.' % (
                status, result, ca_dir))
        LOGGER.info(
            ' cts.sh success! status is %d, output is %s, dir is %s.', status, result, ca_dir)
        LOGGER.info(' Generate root cert success, dir is %s', ca_dir)
        CONSOLER.info(' Generate root cert success, dir is %s', ca_dir)
    except MCError as cert_exp:
        console_error('  %s ' % cert_exp)
    except Exception as gen_cert_exp:
        console_error(
            '  Generate root cert failed! excepion is %s.' % gen_cert_exp)
        LOGGER.error('  Generate root cert failed! Result is %s', result)
        raise MCError(
            'Generate root agency failed! Result is %s' % gen_cert_exp)
示例#3
0
def generate_root_ca(dir, gm=False):
    """[generate root cert]
    
    Arguments:
        dir {[path]} -- [root cert path]
    """
    try:
        dir = os.path.abspath(dir)
        if gm:
            (status, result) = utils.getstatusoutput(
                'bash ' + path.get_path() +
                '/scripts/ca/gm/cts.sh gen_chain_cert ' + dir)
        else:
            (status, result
             ) = utils.getstatusoutput('bash ' + path.get_path() +
                                       '/scripts/ca/cts.sh gen_chain_cert ' +
                                       dir)
        if status != 0:
            logger.warn(
                ' cts.sh failed! status is %d, output is %s, dir is %s.',
                status, result, dir)
            raise MCError(
                'cts.sh failed! status is %d, output is %s, dir is %s.' %
                (status, result, dir))
        logger.info(' cts.sh success! status is %d, output is %s, dir is %s.',
                    status, result, dir)
        logger.info(' Generate root cert success, dir is %s', dir)
        consoler.info(' Generate root cert success, dir is %s' % dir)
    except MCError as me:
        consoler.error(' \033[1;31m %s \033[0m', me)
    except Exception as e:
        consoler.error(
            ' \033[1;31m Generate root cert failed! excepion is %s.\033[0m', e)
        logger.error('  Generate root cert failed! Result is %s' % result)
示例#4
0
def get_console_file(_file):
    """[get console file]

    Arguments:
        _file {[type]} -- [description]
    """
    data = _file
    utils.file_must_exists(data)
    p2p_ip = mconf.MchainConf.p2p_ip
    channel_listen_port = mconf.MchainConf.channel_listen_port
    channel_addr = []
    group_id = mconf.MchainConf.group_id
    utils.replace(data, '"group1', '"group{}'.format(group_id))
    utils.replace(data, 'name="groupId" value="1"',
                  'name="groupId" value="{}"'.format(group_id))
    for ip_idx, p2p_get in enumerate(p2p_ip):
        channel_addr.append('{}:{}'.format(p2p_get,
                                           channel_listen_port[ip_idx]))
    cmd = "cat {} | grep -n connectionsStr | awk '{{print $1}}'".format(data)
    (status, result) = utils.getstatusoutput(cmd)
    result = result.strip('\n').strip(':')
    if bool(status):
        LOGGER.error(' append console channel_addr failed, result is %s.',
                     result)
        raise MCError(' append console channel_addr failed, result is %s.' %
                      result)
    line_num = int(result) + 1
    for channel in channel_addr:
        (status, result) \
            = utils.getstatusoutput('sed -i "{} a'
                                    '<value>{}</value>" {}'
                                    .format(line_num, channel, data))
        line_num = line_num + 1
    CONSOLER.info('get console file end')
示例#5
0
def generator_node_ca(_dir, agent, node):
    """[generate node cert ]

    Arguments:
        agent {[path]} -- [agency cert path]
        node {[string]} -- [node name]
        dir {[path]} -- [node cert path]
    """
    node_dir = os.path.abspath(_dir)
    agent = os.path.abspath(agent)
    try:
        if utils.Status.gm_option:
            os.chdir('{}/scripts/gm/'.format(path.get_path()))
            (status, result) = utils.getstatusoutput(
                './cts.sh'
                ' gen_node_cert {} {}/{}'.format(agent, node_dir, node))
            os.chdir('{}'.format(path.get_path()))
        else:
            os.chdir('{}/scripts/'.format(path.get_path()))
            (status, result) = utils.getstatusoutput(
                './cts.sh'
                ' gen_node_cert {} {}/{}'.format(agent, node_dir, node))
            os.chdir('{}'.format(path.get_path()))
        if not bool(status):
            LOGGER.info(' Generate %s cert successful! dir is %s/%s.', node,
                        node_dir, node)
            os.chdir('{}'.format(path.get_path()))
            if utils.Status.gm_option:
                (status, result) = utils.getstatusoutput(
                    'cat {}/{}/gmagency.crt '
                    '>> {}/{}/gmnode.crt'.format(_dir, node, _dir, node))
                os.remove('{}/{}/gmagency.crt'.format(_dir, node))
                os.remove('{}/{}/gmnode.serial'.format(_dir, node))
            else:
                (status, result) = utils.getstatusoutput(
                    'cat {}/{}/agency.crt '
                    '>> {}/{}/node.crt'.format(_dir, node, _dir, node))
                os.remove('{}/{}/agency.crt'.format(_dir, node))
                os.remove('{}/{}/node.ca'.format(_dir, node))
                os.remove('{}/{}/node.json'.format(_dir, node))
                os.remove('{}/{}/node.private'.format(_dir, node))
                os.remove('{}/{}/node.serial'.format(_dir, node))
                os.remove('{}/{}/node.param'.format(_dir, node))
                os.remove('{}/{}/node.pubkey'.format(_dir, node))
        else:
            # console_error(
            #     '  Generate node cert failed! Please check your network,'
            #     ' and try to check your opennssl version.')
            LOGGER.error('  Generate %s cert failed! Result is %s', node,
                         result)
            raise MCError(' Generate %s cert failed! Result is %s' %
                          (node, result))
    except MCError as cert_exp:
        console_error('  %s ' % cert_exp)
    except Exception as gen_cert_exp:
        console_error('  Generate node cert failed! excepion is %s.' %
                      gen_cert_exp)
        LOGGER.error('  Generate node cert failed! Result is %s', result)
        raise MCError('Generate node failed! Result is %s' % gen_cert_exp)
示例#6
0
def get_nodeid_str(get_path):
    """[get nodeid string]

    Arguments:
        get_path {[file]} -- [description]

    Raises:
        MCError -- [description]

    Returns:
        [string] -- [nodeid]
    """

    # openssl x509  -text -in ./node.crt |  sed -n '15,20p' |  sed 's/://g' |
    #  tr "\n" " " | sed 's/ //g' | sed 's/pub//g' | cut -c 3-130
    LOGGER.info("get_nodeid start! get path is %s", get_path)
    if not os.path.isfile(get_path):
        LOGGER.error(' node cert doesn\'t existed! Need %s', get_path)
        raise MCError(' node cert doesn\'t existed! Need %s' % get_path)
    try:
        if utils.Status.gm_option:
            (status, result) = utils.getstatusoutput(
                '~/.tassl x509  -text -in {}'
                ' | sed -n "15,20p" |  sed '
                '"s/://g" | sed "s/pub//g" |'
                ' tr "\n" " " | sed "s/ //g"'
                ' | cut -c 3-130'.format(get_path))
            result = result.split('\n')[0]
        else:
            (status, result) = utils.getstatusoutput(
                'openssl x509  -text -in {}'
                ' | sed -n "15,20p" |  sed '
                '"s/://g" | sed "s/pub//g" |'
                ' tr "\n" " " | sed "s/ //g"'
                ' | cut -c 3-130'.format(get_path))

        if status != 0:
            LOGGER.error(
                ' create nodeid failed! status is %d, output is %s, dir is %s.',
                status, result, get_path)
        LOGGER.info(
            ' create nodeid success! status is %d, output is %s, dir is %s.',
            status, result, get_path)
    except Exception as node_id_exp:
        LOGGER.error(
            ' create nodeid failed! status is %d, output is %s, dir is %s.',
            status, result, get_path)
        raise MCError(' create nodeid failed! excepion is %s.' % node_id_exp)
    LOGGER.info("get_nodeid success! get path is %s", get_path)
    return result
示例#7
0
def check_module(ip, dest):
    """Using ansible.sh check_module, check chain status
    
    Arguments:
        ip {string} -- corresponding server host ip
        dest {string} -- corresponding server dir path
    
    Returns:
        bool -- true or false
    """

    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh check ' + ip + ' ' + dest)
    logger.debug('check action , status %s, output %s' % (status, result))
    
    if status:
        logger.warn('check action failed, status %s' % (status))
        consoler.warn(' ansible check failed, host is %s, dst is %s, status is %s, output is %s.', ip, dest, status, result)
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        logger.warn('check action failed, output %s' % (result))
        consoler.warn(' ansible check failed, host is %s, dst is %s, status is %s, output is %s.', ip, dest, status, result)
    else:
        consoler.info(' ansible check success, host is %s, output is %s.', ip, result)
        return True
    
    return False
示例#8
0
def unregister_module(ip, dest, index):
    """Using ansible.sh unregister_module, start nodes
    
    Arguments:
        ip {string} -- corresponding server host ip
        dest {string} -- corresponding server dir path
        index {int} -- node index to be register
    
    Returns:
        bool -- true or false
    """

    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh unregister ' + ip + ' ' + dest + ' ' + str(index))
    logger.debug(' unregister action, status %s, output %s' % (status, result))
    
    if status:
        consoler.warn(' ansible unregister  failed, host is %s, index is %s, dst is %s, status is %s, output is %s.', ip, str(index), dest, status, result)
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        consoler.warn(' ansible unregister failed, host is %s, index is %s, dst is %s, status is %s, output is %s.', ip, str(index), dest, status, result)
    elif not (result.find('success') + 1):
        consoler.warn(' ansible register failed, host is %s, index is %s, dst is %s, status is %s, output is %s.', ip, str(index), dest, status, result)
    else:
        consoler.info(' ansible unregister success, host is %s, index is %s, output is %s.', ip, str(index), result)
        return True
    return False
示例#9
0
    def is_running(self):
        check_command = 'bash ' + self.check_shell_file()
        status, output = utils.getstatusoutput(check_command)
        logger.info('check status, status is %d, output is %s', status, output)

        if (output.find('is running') == -1):
            raise MCError(' temp node is not running, outpus is %s' % output)
示例#10
0
def cmd_module(ip, cmd):
    """Using ansible.sh cmd_module, execute commands on the corresponding server.

    Arguments:
        ip {string} -- server host ip

    Keyword Arguments:
        msg {string} -- execute commands

    Returns:
        [bool] -- true or false
    """
    cmd = '"' + cmd + '"'
    
    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh cmd ' + ip + ' ' + cmd)
    logger.debug(' cmd action , status %s, output %s' % (status, result))
    if status:
        consoler.error(' \033[1;31m  ansible cmd failed, host is %s, output is %s \033[0m', ip, result)
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        consoler.error(' \033[1;31m  ansible cmd failed, host is %s, output is %s \033[0m', ip, result)
    else:
        consoler.info(' ansible cmd success, host is %s, cmd is %s.', ip, cmd)
        return True
    return False
示例#11
0
 def stop(self):
     stop_command = 'bash ' + self.stop_shell_file()
     if not os.path.exists(self.stop_shell_file()):
         logger.debug('stop file not exist, file is %s. ', stop_command)
         return
     status, output = utils.getstatusoutput(stop_command)
     logger.debug('stop status, status is %d, output is %s', status, output)
示例#12
0
def unarchive_module(ip, src, dest):
    """[Using ansible.sh unarchive_module, compress files to the corresponding server and extract it]
    
    Arguments:
        ip {[string]} -- [corresponding server host ip]
        src {[string]} -- [files dir path]
        dest {[string]} -- [corresponding server dir path]
    
    Returns:
        [bool] -- [true or false]
    """


    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh unarchive ' + ip + ' ' + src + ' ' + dest)
    logger.debug('unarchive action , status %s, output %s' % (status, result))
   
    if status:
        logger.warn('unarchive action failed, status %s' % (status))
        consoler.warn(' ansible unarchive  failed, host is %s, src is %s, dst is %s, status is %s, output is %s.', ip, src, dest, status, result)
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        logger.warn('unarchive action failed, output %s' % (result))
        consoler.warn(' ansible unarchive failed, host is %s, src is %s, dst is %s, status is %s, output is %s.', ip, src, dest, status, result)
    else:
        consoler.info(' ansible unarchive success, host is %s, src is %s, dst is %s.', ip, src, dest)
        return True
    return False
示例#13
0
def copy_module(ip, src, dest):
    """[Using ansible.sh copy_module, push package to servers]
    
    Arguments:
        ip {string} -- corresponding server host ip
        src {string} -- files which push
        dest {string} -- corresponding server dir path

    Returns:
        bool -- true or false.
    """

    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh copy ' + ip + ' ' + src + ' ' + dest)
    logger.debug('copy action , status %s, output %s' % (status, result))
   
    if status:
        logger.warn('copy action failed, status %s' % (status))
        consoler.warn(' ansible copy failed, host is %s, src is %s, dst is %s, status is %s, output is %s.', ip, src, dest, status, result)
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        consoler.warn(' ansible copy failed, host is %s, src is %s, dst is %s, status is %s, output is %s.', ip, src, dest, status, result)
        logger.warn('copy action failed, output %s' % (result))
    else:
        consoler.info(' ansible copy success, host is %s, src is %s, dst is %s.', ip, src, dest)
        return True
    return False
def init_ansible(hosts_conf, add_opr=False):
    try:
        if not os.path.exists(hosts_conf):
            raise MCError('hosts_conf not exisits! ')
        if add_opr:
            src = '/etc/ansible/hosts'
            dst = '/etc/ansible/hosts.bak'
            if not os.path.exists(src):
                raise MCError('/etc/ansible/hosts not exisits! ')
            os.rename(src, dst)
            f = open(src, 'w')
            f.close()
        for line in open(hosts_conf):
            line = line.strip()
            host_value = line.split()
            if len(host_value) != 4:
                raise Exception('hosts_conf type error ,host_line -> %s',
                                host_value)
            user = host_value[0]
            ip = host_value[1]
            port = host_value[2]
            passwd = host_value[3]
            if not utils.valid_string(user):
                raise Exception(
                    'user type error ,user -> %s, host_line -> %s' %
                    (user, host_value))
            if not utils.valid_ip(ip):
                raise Exception('ip type error ,ip -> %s, host_line -> %s' %
                                (ip, host_value))
            if not utils.valid_port(int(port)):
                raise Exception(
                    'port type error ,port -> %s, host_line -> %s' %
                    (port, host_value))
            if not utils.valid_string(passwd):
                raise Exception(
                    'passwd type error ,passwd -> %s, host_line -> %s' %
                    (passwd, host_value))
            (status,
             result) = utils.getstatusoutput('bash ' + path.get_path() +
                                             '/scripts/ansible_init.sh' + ' ' +
                                             user + ' ' + ip + ' ' + port +
                                             ' ' + passwd)
            if status != 0:
                logger.warn(
                    ' ansible_init failed! status is %d, output is %s.',
                    status, result)
                raise MCError(
                    'ansible_init failed! status is %d, output is %s.' %
                    (status, result))
            result = []
            result.append(ip)
            opr_tools.telnet_ansible(result)
            logger.info(' ansible_init success! status is %d, output is %s',
                        status, result)
    except MCError as me:
        consoler.error(' \033[1;31m %s \033[0m', me)
    except Exception as e:
        consoler.error(
            ' \033[1;31m ansible_init failed! excepion is %s.\033[0m', e)
示例#15
0
    def check_fisco_version(self):
        # check if fisco-bcos exists
        if not (os.path.exists(self.fisco_path)
                and os.path.isfile(self.fisco_path)):
            logger.error(' fisco-bcos not exist, fisco-bcos is %s',
                         self.fisco_path)
            raise MCError(' fisco-bcos not exist, fisco-bcos is %s' %
                          self.fisco_path)

        cmd = self.fisco_path + ' --version'
        status, output = utils.getstatusoutput(cmd)
        if status != 0:
            logger.error(
                ' fisco-bcos --version failed, fisco-bcos is %s, status is %d, output is %s',
                self.fisco_path, status, output)
            raise MCError('fisco-bcos --version failed , fisco-bcos is %s.' %
                          self.fisco_path)

        logger.debug(' fisco-bcos --version, status is %d, output is %s',
                     status, output)

        version_info = output.split()
        if version_info[0] == 'FISCO-BCOS' and len(version_info) > 2:
            version = version_info[2].split('.')
            if not len(version) == 3:
                logger.error(
                    ' fisco-bcos --version invalid format, 00 status is %d, output is %s',
                    status, output)
                raise MCError(
                    ' fisco-bcos --version invalid format , fisco-bcos is %s, version is %s.'
                    % (self.fisco_path, version_info[2]))

            if version[2].endswith('-gm'):
                self.gm = True
            self.major = str(int(version[0]))
            self.minor = str(int(version[1]))
            if self.gm:
                self.revision = str(int(version[2][:-3]))
            else:
                self.revision = str(int(version[2]))

            logger.info(' fisco-bcos is %s', self)

            # parser fisco-bcos version and check it.
            if not self.is_13_version():
                logger.error(
                    ' fisco-bcos is not 1.3.x version, not support now, %s',
                    fisco)
                raise MCError(
                    ' fisco-bcos is not 1.3.x version, not support now, %s' %
                    fisco)

        else:
            logger.error(
                ' fisco-bcos --version invalid format, fisco-bcos is %s, status is %d, output is %s',
                self.fisco_path, status, output)
            raise MCError(
                ' fisco-bcos --version invalid format , fisco-bcos is %s, status is %d, output is %s.'
                % (self.fisco_path, status, output))
示例#16
0
 def register(self, node_json):
     register_command = 'bash %s NodeAction registerNode file:%s' % (
         self.register_shell_file(), node_json)
     # node_all_command = 'bash %s NodeAction all'
     status, output = utils.getstatusoutput(register_command)
     if status != 0:
         logger.error(
             ' register node failed, node_json is %s,status is %d, output is %s', node_json, status, output)
         raise MCError(' register opr failed, status is %d ' % status)
示例#17
0
def download_tassl():
    """[download_tassl]
    """
    os.chdir('{}/scripts/gm/'.format(path.get_path()))
    (status, result) = utils.getstatusoutput('./cts.sh download_tassl')
    os.chdir('{}'.format(path.get_path()))
    if bool(status):
        raise EOFError(' download tassl failed failed! status is %d, output is %s.' % (
            status, result))
示例#18
0
def generator_agent_ca(_dir, _ca, agent):
    """[generate agency cert]

    Arguments:
        dir {[path]} -- [agency cert path]
        ca {[path]} -- [root cert path]
        agent {[string]} -- [agency name]
    """
    try:
        ca_dir = os.path.abspath(_ca)
        agency_dir = os.path.abspath(_dir)
        if utils.Status.gm_option:
            os.chdir('{}/scripts/gm/'.format(path.get_path()))
            (status, result) = utils.getstatusoutput('./cts.sh'
                                                     ' gen_agency_cert {} {}/{}'
                                                     .format(ca_dir,
                                                             agency_dir, agent))
            os.chdir('{}'.format(path.get_path()))
        else:
            os.chdir('{}/scripts'.format(path.get_path()))
            (status, result) = utils.getstatusoutput('./cts.sh'
                                                     ' gen_agency_cert {} {}/{}'
                                                     .format(ca_dir,
                                                             agency_dir, agent))
            os.chdir('{}'.format(path.get_path()))
        if not bool(status):
            LOGGER.info(' Generate %s cert successful! dir is %s/%s.',
                        agent, agency_dir, agent)
        else:
            # console_error(
            #     '  Generate cert failed! Please check your network,'
            #     ' and try to check your opennssl version.')
            LOGGER.error('  Generate %s cert failed! Result is %s',
                         agent, result)
            raise MCError(' Generate %s cert failed! Result is %s' %
                          (agent, result))
    except MCError as cert_exp:
        console_error('  %s ' % cert_exp)
    except Exception as gen_cert_exp:
        console_error(
            '  Generate agency cert failed! excepion is %s.' % gen_cert_exp)
        LOGGER.error('  Generate agency cert failed! Result is %s', result)
        raise MCError(
            'Generate agency agency failed! Result is %s' % gen_cert_exp)
示例#19
0
def get_nodeid(get_path, send_path):
    """[get nodeid into file]

    Arguments:
        get_path {[file]} -- [description]
        send_path {[file]} -- [description]

    Raises:
        MCError -- [description]
    """

    LOGGER.info("get_nodeid start! get path is %s", get_path)
    LOGGER.info("get_nodeid start! send path is %s", send_path)
    if not os.path.isfile(get_path):
        LOGGER.error(' node cert doesn\'t existed! Need %s', get_path)
        raise MCError(' node cert doesn\'t existed! Need %s' % get_path)
    try:
        if utils.Status.gm_option:
            (status, result) = utils.getstatusoutput('~/.tassl x509  -text -in {}'
                                                     ' | sed -n "15,20p" |  sed '
                                                     '"s/://g" | sed "s/pub//g" |'
                                                     ' tr "\n" " " | sed "s/ //g"'
                                                     ' cut -c 3-130| cat >{}'
                                                     .format(get_path, send_path))
        else:
            (status, result) = utils.getstatusoutput('openssl x509  -text -in {}'
                                                     ' | sed -n "15,20p" |  sed "s/://g"'
                                                     ' | tr "\n" " " | sed "s/ //g" |'
                                                     ' cut -c 3-130| cat >{}'
                                                     .format(get_path, send_path))
        if status != 0:
            LOGGER.error(
                ' create nodeid failed! status is %d, output is %s, dir is %s.',
                status, result, get_path)
        LOGGER.info(
            ' create nodeid success! status is %d, output is %s, dir is %s.',
            status, result, get_path)
    except Exception as node_id_exp:
        LOGGER.error(
            ' create nodeid failed! status is %d, output is %s, dir is %s.',
            status, result, get_path)
        raise MCError(' create nodeid failed! excepion is %s.' % node_id_exp)
    LOGGER.info("get_nodeid success! get path is %s", get_path)
    LOGGER.info("get_nodeid success! send path is %s", send_path)
示例#20
0
 def start(self):
     # check if port temp node will use aleady used by others.
     self.port_check()
     # start temp node.
     start_command = 'bash ' + self.start_shell_file()
     status, output = utils.getstatusoutput(start_command)
     if status != 0:
         raise MCError(
             ' temp node start not success, output is %s ' % output)
     logger.info(' start status, status is %d, output is %s',
                 status, output)
示例#21
0
 def export(self):
     self.stop()
     export_command = 'bash ' + self.export_shell_file() + ' ' + \
         self.chain.data_dir() + '/genesis.json'
     status, output = utils.getstatusoutput(export_command)
     if not os.path.exists(self.dir() + '/../genesis.json'):
         logger.error('export genesis.json failed, output is %s', output)
         raise MCError(
             ' export genesis.json failed, output is %s.' % output)
     else:
         logger.debug(
             'export status, status is %d, output is %s', status, output)
示例#22
0
def generator_node_ca(agent, dir, node, gm=False):
    """[generate node cert ]
    
    Arguments:
        agent {[path]} -- [agency cert path]
        node {[string]} -- [node name]
        dir {[path]} -- [node cert path]
    """
    _dir = os.path.abspath(dir)
    agent = os.path.abspath(agent)
    try:
        if gm:
            (status, result
             ) = utils.getstatusoutput('bash ' + path.get_path() +
                                       '/scripts/ca/gm/cts.sh gen_node_cert ' +
                                       agent + ' ' + _dir + '/ ' + node)
        else:
            (status, result
             ) = utils.getstatusoutput('bash ' + path.get_path() +
                                       '/scripts/ca/cts.sh gen_node_cert ' +
                                       agent + ' ' + _dir + '/ ' + node)
        if not status:
            logger.info(' Generate %s cert successful! dir is %s.', node,
                        _dir + '/' + node)
        else:
            consoler.error(
                ' \033[1;31m Generate node cert failed! Please check your network, and try to check your opennssl version.\033[0m'
            )
            logger.error('  Generate %s cert failed! Result is %s' %
                         (node, result))
            raise MCError(' Generate %s cert failed! Result is %s' %
                          (node, result))
    except MCError as me:
        consoler.error(' \033[1;31m %s \033[0m', me)
    except Exception as e:
        consoler.error(
            ' \033[1;31m Generate root cert failed! excepion is %s.\033[0m', e)
        logger.error('  Generate root cert failed! Result is %s' % result)
示例#23
0
def generator_agent_ca(dir, ca, agent, gm=False):
    """[generate agency cert]
    
    Arguments:
        dir {[path]} -- [agency cert path]
        ca {[path]} -- [root cert path]
        agent {[string]} -- [agency name]
    """
    try:
        ca = os.path.abspath(ca)
        dir = os.path.abspath(dir)
        if gm:
            (status, result) = utils.getstatusoutput(
                'bash ' + path.get_path() +
                '/scripts/ca/gm/cts.sh gen_agency_cert ' + ca + ' ' + dir +
                ' ' + agent)
        else:
            (status, result
             ) = utils.getstatusoutput('bash ' + path.get_path() +
                                       '/scripts/ca/cts.sh gen_agency_cert ' +
                                       ca + ' ' + dir + ' ' + agent)
        if not status:
            logger.info(' Generate %s cert successful! dir is %s.' %
                        (agent, dir + '/' + agent))
        else:
            consoler.error(
                ' \033[1;31m Generate %s cert failed! Please check your network, and try to check your opennssl version.\033[0m'
            )
            logger.error('  Generate %s cert failed! Result is %s' %
                         (agent, result))
            raise MCError(' Generate %s cert failed! Result is %s' %
                          (agent, result))
    except MCError as me:
        consoler.error(' \033[1;31m %s \033[0m', me)
    except Exception as e:
        consoler.error(
            ' \033[1;31m Generate root cert failed! excepion is %s.\033[0m', e)
        logger.error('  Generate root cert failed! Result is %s' % result)
示例#24
0
 def export(self):
     try:
         if self.fisco.is_gm():
             shutil.move(get_gm_god_path() + '/godInfo.txt',
             get_gm_god_path() + '/godInfo.txt.bak')
             cmd = self.fisco.get_fisco_path() + ' --newaccount ' + get_gm_god_path() + '/godInfo.txt'
             status, result = utils.getstatusoutput(cmd)
             logger.debug(' start status, status is %d, output is %s', status, result)
         else:
             shutil.move(get_god_path() + '/godInfo.txt',
             get_god_path() + '/godInfo.txt.bak')
             cmd = self.fisco.get_fisco_path() + ' --newaccount ' + get_god_path() + '/godInfo.txt'
             status, result = utils.getstatusoutput(cmd)
             logger.debug(' start status, status is %d, output is %s', status, result)
         if status != 0:
             logger.warn(' export godInfo.txt failed! status is %d, output is %s.', status, result)
             raise MCError('godInfo.txt failed! status is %d, output is %s.' % (status, result))
         logger.info(' export godInfo.txt status is %d, output is %s.', status, result)
         consoler.info(' export godInfo.txt success')
     except MCError as me:
         consoler.error(' \033[1;31m %s \033[0m', me)
     except Exception as e:
         consoler.error(' \033[1;31m export godInfo.txt failed! excepion is %s.\033[0m', e)
         logger.error('  export godInfo.txt failed!')
示例#25
0
def diagnose_module(ip, dest):
    """Using ansible.sh diagnose_module, call script -> monotor.sh, Check status of nodes
    Arguments:
        ip {string} -- corresponding server host ip
        dest {string} -- corresponding server dir path
    """

    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh diagnose ' + ip + ' ' + dest)
    logger.debug('diagnose action , status %s, output %s' % (status, result))
    if status:
        consoler.error(' \033[1;31m  ansible diagnose failed, host is %s, output is %s \033[0m', ip, result)
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        consoler.error(' \033[1;31m  ansible diagnose failed, host is %s, output is %s \033[0m', ip, result)
    else:
        consoler.info(' ansible diagnose success, host is %s, result is %s.', ip, result)
        return True
    return False
示例#26
0
    def check_java(self):
        """[check java]

        Raises:
            MCError -- [java not install]
        """

        cmd = 'java -version'
        status, output = utils.getstatusoutput(cmd)
        if status != 0:
            LOGGER.error(' java -version failed , status is %d, output is %s',
                         status, output)
            raise MCError(' java -version failed , java not installed.')

        version_str = output.split("\"")
        if not len(version_str) > 1:
            LOGGER.error(
                ' cannot get java version, status is %d, output is %s', status,
                output)
            raise MCError(
                ' cannot get java version, oracle jdk need >=1.8, please try \'java -version\'. '
            )

        version_arr = version_str[1].split('.')
        if not len(version_arr) > 2:
            LOGGER.error(
                ' cannot get java version, status is %d, output is %s', status,
                output)
            raise MCError(
                ' cannot get java version, oracle jdk need >=1.8, please try \'java -version\' '
            )

        self.major = version_arr[0]
        self.minor = version_arr[1]
        self.openjdk = bool(output.lower().find('openjdk') != -1)

        if not self.is_suitable():
            raise MCError(
                ' invalid java version, oracle jdk need >=1.8, now %s ' % self)

        LOGGER.info(' java version is %s ', self)
示例#27
0
    def check_java(self):
        cmd = 'java -version'
        status, output = utils.getstatusoutput(cmd)
        if status != 0:
            logger.error(' java -version failed , status is %d, output is %s',
                         status, output)
            raise MCError(' java -version failed , java not installed.')

        version_str = output.split("\"")
        if not len(version_str) > 1:
            logger.error(
                ' cannot get java version, status is %d, output is %s', status,
                output)
            raise MCError(
                ' cannot get java version, oracle jdk need >=1.8 or openjdk need >= 1.9, please try \'java -version\'. '
            )

        version_arr = version_str[1].split('.')
        if not len(version_arr) > 2:
            logger.error(
                ' cannot get java version, status is %d, output is %s', status,
                output)
            raise MCError(
                ' cannot get java version, oracle jdk need >=1.8 or openjdk need >= 1.9, please try \'java -version\' '
            )

        self.major = version_arr[0]
        self.minor = version_arr[1]
        if output.lower().find('openjdk') != -1:
            self.openjdk = True
        else:
            self.openjdk = False

        if not self.is_suitable():
            raise MCError(
                ' invalid java version, oracle jdk need >=1.8 or openjdk need >= 1.9, now %s '
                % self)

        logger.info(' java version is %s ', self)
示例#28
0
def telnet_module(ip, msg='HelloWorld!'):
    """using ansible.sh telnet module, echo 'HelloWorld' to screen to check ansible is useful.

    Arguments:
        ip {string} -- host ip

    Keyword Arguments:
        msg {string} -- test string (default: {'HelloWorld!'})

    Returns:
        [bool] -- ansible useful echo return True, else False.
    """

    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh telnet ' + ip + ' ' + msg)
    logger.debug('telnet action , status %s, output %s' % (status, result))
    if status:
        consoler.error(' \033[1;31m  ansible telnet failed, host is %s, output is %s \033[0m', ip, result)
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        consoler.error(' \033[1;31m  ansible telnet failed, host is %s, output is %s \033[0m', ip, result)
    else:
        consoler.info(' ansible telnet success, host is %s, output is %s', ip, result)
        return True
    return False
示例#29
0
def mkdir_module(ip, dest):
    """[Using ansible.sh mkdir_module create dictionary ]
    
    Arguments:
        ip {string} -- corresponding server host ip
        dest {string} -- dir path
    
    Returns:
        int -- success return True, else return False.
    """

    (status, result) = utils.getstatusoutput('bash ' + path.get_path() +
                                                '/scripts/ansible.sh mkdir ' + ip + ' ' + dest)
    logger.debug('mkdir action , status %s, output %s' % (status, result))
   
    if status:
        consoler.warn(' ansible mkdir failed, host is %s, dst is %s, status is %s, output is %s.', ip, dest, status, result)
        logger.warn('mkdir action failed, status %s, result %s ' % (status, result))
    elif result.find('SUCCESS') == -1 and result.find('CHANGED') == -1:
        consoler.warn(' ansible mkdir failed, host is %s, dst is %s, status is %s, output is %s.', ip, dest, status, result)
        logger.warn('mkdir action failed, output %s' % (result))
    else:
        return True
    return False
示例#30
0
def create_group_genesis(data_dir='{}/meta'.format(path.get_path())):
    '''
    create group in meta
    '''
    LOGGER.info('create_group_genesis start')
    package_dir = data_dir
    gm_opr = utils.Status.gm_option
    group_id = mgroup.MgroupConf.group_id
    p2p_ip = mgroup.MgroupConf.p2p_ip
    p2p_listen_port = mgroup.MgroupConf.p2p_listen_port
    utils.file_must_not_exists('{}/group.{}.genesis'.format(
        data_dir, group_id))
    if not os.path.exists(package_dir):
        LOGGER.warning(' %s not existed!', package_dir)
        os.mkdir(data_dir)
    shutil.copy('{}/tpl/group.i.genesis'.format(path.get_path()),
                '{}/group.{}.genesis'.format(package_dir, group_id))
    shutil.copy('{}/tpl/group.i.ini'.format(path.get_path()),
                '{}/group.{}.ini'.format(package_dir, group_id))
    # uptes second to ms
    (status, time_stamp) = utils.getstatusoutput('echo $(date +%s"000")')
    if not bool(status):
        CONSOLER.info('generate %s/group.%s.genesis, successful', package_dir,
                      group_id)
    else:
        LOGGER.error(
            ' Generate %s/group.%s.genesis failed! Please check your network.',
            package_dir, group_id)
        raise MCError(
            ' Generate %s/group.%s.genesis failed, timestamp is %s! Please check your network.'
            % (package_dir, group_id, time_stamp))
    # CONSOLER.info('generate %s/group.%s.ini', package_dir, group_id)
    group_cfg = configparser.ConfigParser()
    with open('{}/group.{}.genesis'.format(package_dir, group_id),
              'r') as config_file:
        group_cfg.readfp(config_file)
    for node_idx, _in in enumerate(p2p_ip):
        try:
            if gm_opr:
                node_id = config.get_nodeid_str(
                    '{}/meta/gmcert_{}_{}.crt'.format(
                        path.get_path(), p2p_ip[node_idx],
                        p2p_listen_port[node_idx]))
                node_id.strip('\n').strip(
                    'WARNING: can\'t open config file: /home/asherli/TASSL/ssl/openssl.cnf'
                )
                LOGGER.info('resolve %s/meta/gmcert_%s_%s.crt',
                            path.get_path(), p2p_ip[node_idx],
                            p2p_listen_port[node_idx])
                LOGGER.info("nodeid -> %s", node_id)
                group_cfg.set("consensus", "node.{}".format(node_idx), node_id)
            else:
                node_id = config.get_nodeid_str(
                    '{}/meta/cert_{}_{}.crt'.format(path.get_path(),
                                                    p2p_ip[node_idx],
                                                    p2p_listen_port[node_idx]))
                LOGGER.info('resolve %s/meta/cert_%s_%s.crt', path.get_path(),
                            p2p_ip[node_idx], p2p_listen_port[node_idx])
                LOGGER.info("nodeid -> %s", node_id)
                group_cfg.set("consensus", "node.{}".format(node_idx), node_id)
        except Exception as group_exp:
            LOGGER.error('create group genesis failed! exception is %s',
                         group_exp)
            raise MCError('create group genesis failed! exception is %s' %
                          group_exp)
        group_cfg.set("group", "id", group_id)
        group_cfg.set("group", "timestamp", time_stamp)
    with open('{}/group.{}.genesis'.format(package_dir, group_id),
              'w') as config_file:
        group_cfg.write(config_file)
    shutil.copy('{}/group.{}.genesis'.format(package_dir, group_id),
                '{}/meta/group.{}.genesis'.format(path.get_path(), group_id))

    LOGGER.info('create_group_genesis end')