Ejemplo n.º 1
0
def test_get_peer_status():
    peers = get_peer_status(cache)
    assert isinstance(peers, list)
    for Peer in peers:
        assert isinstance(Peer, dict)
        assert 'role' in Peer
        assert 'address' in Peer
        assert Peer['active'] is True
Ejemplo n.º 2
0
def test_load_moon_state():
    moonStatus = []
    fpn_moons = ['deadd738e6']
    peers = get_peer_status(cache)
    for peer in peers:
        if peer['role'] == 'MOON' and peer['identity'] in fpn_moons:
            moonStatus.append(peer)
            break
    load_cache_by_type(cache, moonStatus, 'mstate')
    assert len(cache) == 11
Ejemplo n.º 3
0
def test_get_peer_status():
    peers = get_peer_status(cache)
    assert isinstance(peers, list)
    for Peer in peers:
        assert isinstance(Peer, dict)
        assert 'role' in Peer
        assert 'address' in Peer
        assert Peer['active'] is True
        addr_obj = ipaddress.ip_address(Peer['address'])
        assert addr_obj.version == 4
Ejemplo n.º 4
0
def test_populate_leaf_list():
    import diskcache as dc
    from node_tools import state_data as st

    node_q = dc.Deque(directory='/tmp/test-nq')
    wait_q = dc.Deque(directory='/tmp/test-wq')
    tmp_q = dc.Deque(directory='/tmp/test-tq')
    node_q.clear()
    wait_q.clear()
    tmp_q.clear()
    node_q.append('beef9f73c6')

    peers = get_peer_status(cache)
    # print(peers)
    for peer in peers:
        if peer['role'] == 'LEAF':
            populate_leaf_list(node_q, wait_q, tmp_q, peer)
            assert len(st.leaf_nodes) == 1
            assert st.leaf_nodes[0]['beef9f73c6'] == '134.47.250.137'

    node_q.clear()
    wait_q.append('beef9f73c6')
    for peer in peers:
        if peer['role'] == 'LEAF':
            populate_leaf_list(node_q, wait_q, tmp_q, peer)
            assert len(st.leaf_nodes) == 1
            assert st.leaf_nodes[0]['beef9f73c6'] == '134.47.250.137'

    res = lookup_node_id('beef9f73c6', tmp_q)
    assert res['beef9f73c6'] == '134.47.250.137'
    assert len(tmp_q) == 1

    node_update = dict({'beef9f73c6': '134.47.250.42'})
    avoid_and_update('beef9f73c6', node_update, tmp_q)

    res = lookup_node_id('beef9f73c6', tmp_q)
    assert res['beef9f73c6'] == '134.47.250.42'
    assert len(tmp_q) == 1

    wait_q.clear()
    tmp_q.clear()
    st.leaf_nodes = []
Ejemplo n.º 5
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)

        try:
            logger.debug('{} node(s) in offline queue: {}'.format(
                len(off_q), list(off_q)))
            if len(off_q) > 0:
                drain_msg_queue(off_q, addr='127.0.0.1', method='offline')

            logger.debug('{} node(s) in wedged queue: {}'.format(
                len(wdg_q), list(wdg_q)))
            if len(wdg_q) > 0:
                drain_msg_queue(wdg_q, addr='127.0.0.1', method='wedged')

            logger.debug('{} node(s) in reg queue: {}'.format(
                len(reg_q), list(reg_q)))
            logger.debug('{} node(s) in wait queue: {}'.format(
                len(wait_q), list(wait_q)))
            manage_incoming_nodes(node_q, reg_q, wait_q)
            if len(reg_q) > 0:
                drain_msg_queue(reg_q, pub_q, addr='127.0.0.1')

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

            # 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')

            num_leaves = 0
            peerStatus = get_peer_status(cache)
            for peer in peerStatus:
                if peer['role'] == 'LEAF':
                    if peer['identity'] not in reg_q:
                        if peer['identity'] not in node_q:
                            node_q.append(peer['identity'])
                            logger.debug('Adding LEAF node id: {}'.format(
                                peer['identity']))
                    populate_leaf_list(node_q, wait_q, tmp_q, peer)
                    num_leaves = num_leaves + 1
            if num_leaves == 0 and st.leaf_nodes != []:
                st.leaf_nodes = []
            if st.leaf_nodes != []:
                logger.debug('Found {} leaf node(s)'.format(num_leaves))
            logger.debug('{} node(s) in node queue: {}'.format(
                len(node_q), list(node_q)))

            logger.debug('{} node(s) in reg queue: {}'.format(
                len(reg_q), list(reg_q)))
            logger.debug('{} node(s) in wait queue: {}'.format(
                len(wait_q), list(wait_q)))
            manage_incoming_nodes(node_q, reg_q, wait_q)
            if len(reg_q) > 0:
                drain_msg_queue(reg_q, pub_q, addr='127.0.0.1')

            logger.debug('{} node(s) in node queue: {}'.format(
                len(node_q), list(node_q)))
            logger.debug('{} node(s) in pub queue: {}'.format(
                len(pub_q), list(pub_q)))
            logger.debug('{} node(s) in active queue: {}'.format(
                len(cfg_q), list(cfg_q)))

        except Exception as exc:
            logger.error('peerstate exception was: {}'.format(exc))
            raise exc
Ejemplo n.º 6
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