Exemplo n.º 1
0
def echo_client(fpn_id, addr, send_cfg=False):
    import json
    from node_tools import state_data as st
    from node_tools.msg_queues import make_version_msg
    from node_tools.node_funcs import do_shutdown
    from node_tools.node_funcs import node_state_check
    from node_tools.node_funcs import run_ztcli_cmd

    if NODE_SETTINGS['use_localhost'] or not addr:
        addr = '127.0.0.1'

    cfg = st.cfg_msgs
    compatible = True
    node_data = st.fpnState
    reply_list = []
    reciept = False

    try:
        if send_cfg:
            reply_list = send_req_msg(addr, 'node_cfg', fpn_id)
            logger.debug('CFG: send_cfg reply is {}'.format(reply_list))
            if 'result' not in reply_list[0]:
                logger.warning('CFG: malformed reply {}'.format(reply_list))
            else:
                node_data['cfg_ref'] = reply_list[0]['ref']
                cfg = json.loads(reply_list[0]['result'])
                logger.debug('CFG: state has payload {}'.format(cfg))
                for net in cfg['networks']:
                    res = run_ztcli_cmd(action='join', extra=net)
                    logger.debug('run_ztcli_cmd join result: {}'.format(res))
        else:
            ver_msg = make_version_msg(fpn_id)
            reply_list = send_req_msg(addr, 'echo', ver_msg)
            logger.debug('ECHO: ver_msg reply is {}'.format(reply_list))
            if 'result' not in reply_list[0]:
                logger.warning('ECHO: malformed reply {}'.format(reply_list))
            else:
                node_data['msg_ref'] = reply_list[0]['ref']
                msg = json.loads(reply_list[0]['result'])
                logger.debug('ECHO: got msg reply {}'.format(msg))
                if 'UPGRADE' in msg['version']:
                    put_state_msg('UPGRADE')
                    compatible = False
        reciept = True
        logger.debug('Send result is {}'.format(reply_list))
        if not compatible:
            logger.error(
                'Shutting down due to incompatible version: {}'.format(
                    ver_msg))
            do_shutdown()
        if not send_cfg and not node_data['cfg_ref']:
            res = node_state_check(deorbit=True)
            logger.debug('node_state_check returned {}'.format(res))
    except Exception as exc:
        # success wrapper needs a warning to catch
        logger.warning('Send error is {}'.format(exc))
        raise exc

    return reply_list, reciept
Exemplo n.º 2
0
def network_cruft_cleaner():
    """
    This is (sort of) the companion to net_id_handler() for checking
    the net_q on startup and sending a ztcli command to leave any
    stale networks found (and clear the queue).
    """
    import diskcache as dc
    from node_tools.node_funcs import run_ztcli_cmd

    if NODE_SETTINGS['node_role'] is None:
        net_q = dc.Deque(directory=get_cachedir('net_queue'))

        for nwid in list(net_q):
            res = run_ztcli_cmd(action='leave', extra=nwid)
            logger.debug('run_ztcli_cmd leave result: {}'.format(res))

        net_q.clear()
Exemplo n.º 3
0
def echo_client(fpn_id, addr, send_cfg=False):
    import json
    from node_tools import state_data as st
    from node_tools.node_funcs import node_state_check
    from node_tools.node_funcs import run_ztcli_cmd

    if NODE_SETTINGS['use_localhost'] or not addr:
        addr = '127.0.0.1'

    cfg = st.cfg_msgs
    node_data = st.fpnState
    reply_list = []
    reciept = False

    try:
        if send_cfg:
            reply_list = send_req_msg(addr, 'node_cfg', fpn_id)
            logger.debug('CFG: send_cfg reply is {}'.format(reply_list))
            if 'result' not in reply_list[0]:
                logger.warning('CFG: malformed reply {}'.format(reply_list))
            else:
                node_data['cfg_ref'] = reply_list[0]['ref']
                cfg = json.loads(reply_list[0]['result'])
                logger.debug('CFG: state has payload {}'.format(cfg))
                for net in cfg['networks']:
                    res = run_ztcli_cmd(action='join', extra=net)
                    logger.debug('run_ztcli_cmd join result: {}'.format(res))
        else:
            reply_list = send_req_msg(addr, 'echo', fpn_id)
            node_data['msg_ref'] = reply_list[0]['ref']
        reciept = True
        logger.debug('Send result is {}'.format(reply_list))
        if not send_cfg and not node_data['cfg_ref']:
            res = node_state_check(deorbit=True)
            logger.debug('node_state_check returned {}'.format(res))
    except Exception as exc:
        # success wrapper needs a warning to catch
        logger.warning('Send error is {}'.format(exc))
        raise exc

    return reply_list, reciept
Exemplo n.º 4
0
def set_initial_role():
    """
    Set initial node role from node ID if ID is a known infra node.
    """
    from node_tools.node_funcs import run_ztcli_cmd

    try:
        res = run_ztcli_cmd(action='info')
        if res:
            node_data = res.split()
            logger.debug('INITNODE: node data is {}'.format(node_data))

            if NODE_SETTINGS['mode'] == 'peer':
                node_id = node_data[2]
                if node_id in NODE_SETTINGS['moon_list']:
                    NODE_SETTINGS['node_role'] = 'moon'
                elif node_id in NODE_SETTINGS['ctlr_list']:
                    NODE_SETTINGS['node_role'] = 'controller'
            logger.debug('INITROLE: role is {}'.format(NODE_SETTINGS['node_role']))
            logger.debug('INITMODE: mode is {}'.format(NODE_SETTINGS['mode']))

    except Exception as exc:
        logger.warning('run_ztcli_cmd exception: {}'.format(exc))
Exemplo n.º 5
0
def test_get_node_info():
    res = run_ztcli_cmd(action='info')
    assert res is None or 'failed' in res
Exemplo n.º 6
0
def test_get_moon_data():
    res = run_ztcli_cmd(action='listmoons')
    assert isinstance(res, list)
Exemplo n.º 7
0
def test_join_args():
    res = run_ztcli_cmd(action='join', extra='b6079f73ca8129ad')
    assert res is None or 'failed' in res
    res = cycle_adhoc_net('b6079f73ca8129ad', nap=1)
    assert res is None
Exemplo n.º 8
0
async def main():
    """State cache updater to retrieve data from a local ZeroTier node."""
    async with aiohttp.ClientSession() as session:
        ZT_API = get_token()
        client = ZeroTier(ZT_API, loop, session)
        nsState = AttrDict.from_nested_dict(st.fpnState)
        net_wait = st.wait_cache

        try:
            # get status details of the local node and update state
            await client.get_data('status')
            node_id = handle_node_status(client.data, cache)

            if NODE_SETTINGS['mode'] == 'peer':
                # get status details of the node peers
                await client.get_data('peer')
                peer_data = client.data
                logger.info('Found {} peers'.format(len(peer_data)))
                peer_keys = find_keys(cache, 'peer')
                logger.debug('Returned peer keys: {}'.format(peer_keys))
                load_cache_by_type(cache, peer_data, 'peer')

                # check for moon data (only exists for moons we orbit)
                if not nsState.moon_id0:
                    moon_data = run_ztcli_cmd(action='listmoons')
                    if moon_data:
                        load_cache_by_type(cache, moon_data, 'moon')

                    moonStatus = []
                    fpn_moons = NODE_SETTINGS['moon_list']
                    peerStatus = get_peer_status(cache)
                    for peer in peerStatus:
                        if peer['role'] == 'MOON' and peer['identity'] in fpn_moons:
                            moonStatus.append(peer)
                            break
                    logger.debug('Got moon state: {}'.format(moonStatus))
                    load_cache_by_type(cache, moonStatus, 'mstate')

            # get all available network data
            await client.get_data('network')
            net_data = client.data
            logger.info('Found {} networks'.format(len(net_data)))

            if NODE_SETTINGS['mode'] == 'peer':
                wait_for_nets = net_wait.get('offline_wait')
                if len(net_data) == 0 and not nsState.cfg_ref:
                    send_cfg_handler()
                    put_state_msg('WAITING')
                elif len(net_data) == 0 and nsState.cfg_ref and not wait_for_nets:
                    put_state_msg('ERROR')

            net_keys = find_keys(cache, 'net')
            logger.debug('Returned network keys: {}'.format(net_keys))
            load_cache_by_type(cache, net_data, 'net')

            netStatus = get_net_status(cache)
            logger.debug('Got net state: {}'.format(netStatus))
            load_cache_by_type(cache, netStatus, 'istate')

            if NODE_SETTINGS['mode'] == 'peer':
                # check for reconfiguration events
                for net in netStatus:
                    if net['status'] == 'NOT_FOUND' or net['status'] == 'ACCESS_DENIED':
                        # if net['ztaddress'] != net['gateway']:
                        #     do_net_cmd(get_net_cmds(NODE_SETTINGS['home_dir'], 'fpn0'))
                        run_ztcli_cmd(action='leave', extra=net['identity'])
                        net_id_handler(None, net['identity'], old=True)
                        st.fpnState['cfg_ref'] = None
                        net_wait.set('offline_wait', True, 75)
                if len(net_data) < 2 and not nsState.cfg_ref:
                    send_cfg_handler()
                    put_state_msg('WAITING')

                # check the state of exit network/route
                exit_id = get_ztnwid('fpn0', 'fpn_id0', nsState)
                if exit_id is not None:
                    for net in netStatus:
                        if net['identity'] == exit_id:
                            ztaddr = net['ztaddress']
                            break
                    exit_state, _, _ = do_peer_check(ztaddr)
                    logger.debug('HEALTH: peer state is {}'.format(exit_state))

                    wait_for_nets = net_wait.get('offline_wait')
                    logger.debug('HEALTH: network route state is {}'.format(nsState.route))
                    if nsState.route is False:
                        if not st.fpnState['wdg_ref'] and not wait_for_nets:
                            # logger.error('HEALTH: net_health state is {}'.format(nsState.route))
                            reply = send_wedged_msg()
                            if 'result' in reply[0]:
                                st.fpnState['wdg_ref'] = True
                            logger.error('HEALTH: network is unreachable!!')
                            put_state_msg('ERROR')
                    else:
                        logger.debug('HEALTH: wait_for_nets is {}'.format(wait_for_nets))

            elif NODE_SETTINGS['mode'] == 'adhoc':
                if not NODE_SETTINGS['nwid']:
                    logger.warning('ADHOC: network ID not set {}'.format(NODE_SETTINGS['nwid']))
                else:
                    logger.debug('ADHOC: found network ID {}'.format(NODE_SETTINGS['nwid']))
                if netStatus != []:
                    nwid = netStatus[0]['identity']
                    addr = netStatus[0]['ztaddress']
                    nwstat = netStatus[0]['status']
                    logger.debug('ADHOC: found network with ID {}'.format(nwid))
                    logger.debug('ADHOC: network status is {}'.format(nwstat))
                    if addr:
                        res = do_peer_check(addr)

                # elif NODE_SETTINGS['nwid']:
                #     run_ztcli_cmd(action='join', extra=NODE_SETTINGS['nwid'])

        except Exception as exc:
            logger.error('nodestate exception was: {}'.format(exc))
            raise exc