Example #1
0
def test_notification_ws(http_compute, async_run):
    ws = http_compute.websocket("/notifications/ws")
    answer = async_run(ws.receive())
    answer = json.loads(answer.data)
    assert answer["action"] == "ping"

    NotificationManager.instance().emit("test", {})

    answer = async_run(ws.receive())
    answer = json.loads(answer.data)
    assert answer["action"] == "test"

    async_run(http_compute.close())
def test_queue_json(async_run):
    NotificationManager.reset()
    notifications = NotificationManager.instance()
    with notifications.queue() as queue:
        assert len(notifications._listeners) == 1

        res = async_run(queue.get(5))
        assert "ping" in res

        notifications.emit("test", {"a": 1})
        res = async_run(queue.get_json(5))
        assert res == '{"action": "test", "event": {"a": 1}}'

    assert len(notifications._listeners) == 0
def test_queue(async_run):
    NotificationManager.reset()
    notifications = NotificationManager.instance()
    with notifications.queue() as queue:
        assert len(notifications._listeners) == 1

        res = async_run(queue.get(5))
        assert res[0] == "ping"

        notifications.emit("test", {"a": 1})
        res = async_run(queue.get(5))
        assert res == ('test', {"a": 1}, {})

    assert len(notifications._listeners) == 0
def test_queue_json_meta(async_run):
    NotificationManager.reset()
    project_id = str(uuid.uuid4())
    notifications = NotificationManager.instance()
    with notifications.queue() as queue:
        assert len(notifications._listeners) == 1

        res = async_run(queue.get(5))
        assert "ping" in res

        notifications.emit("test", {"a": 1}, project_id=project_id)
        res = async_run(queue.get_json(5))
        assert res == '{"action": "test", "event": {"a": 1}, "project_id": "' + project_id + '"}'

    assert len(notifications._listeners) == 0
Example #5
0
def test_start(loop, vm, async_run):
    process = MagicMock()
    process.returncode = None

    with NotificationManager.instance().queue() as queue:
        async_run(queue.get(0))  # Ping

        with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True):
            with asyncio_patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec:
                with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"):
                    nio = VPCS.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"})
                    async_run(vm.port_add_nio_binding(0, nio))
                    loop.run_until_complete(asyncio.async(vm.start()))
                    assert mock_exec.call_args[0] == (vm._vpcs_path(),
                                                      '-p',
                                                      str(vm._internal_console_port),
                                                      '-m', '1',
                                                      '-i',
                                                      '1',
                                                      '-F',
                                                      '-R',
                                                      '-s',
                                                      ANY,
                                                      '-c',
                                                      ANY,
                                                      '-t',
                                                      '127.0.0.1')
                assert vm.is_running()
                assert vm.command_line == ' '.join(mock_exec.call_args[0])
        (action, event, kwargs) = async_run(queue.get(0))
        assert action == "node.updated"
        assert event == vm
Example #6
0
def test_start(loop, vm, async_run):
    process = MagicMock()
    process.returncode = None

    with NotificationManager.instance().queue() as queue:
        async_run(queue.get(1))  # Ping

        vm.ip_address = "192.168.1.1"
        with patch("sys.platform", return_value="win"):
            with asyncio_patch("gns3server.compute.traceng.traceng_vm.TraceNGVM._check_requirements", return_value=True):
                with asyncio_patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec:
                    loop.run_until_complete(asyncio.ensure_future(vm.start("192.168.1.2")))
                    assert mock_exec.call_args[0] == (vm._traceng_path(),
                                                      '-u',
                                                      '-c',
                                                      ANY,
                                                      '-v',
                                                      ANY,
                                                      '-b',
                                                      '127.0.0.1',
                                                      '-s',
                                                      'ICMP',
                                                      '-f',
                                                      '192.168.1.1',
                                                      '192.168.1.2')
                    assert vm.is_running()
                    assert vm.command_line == ' '.join(mock_exec.call_args[0])
        (action, event, kwargs) = async_run(queue.get(1))
        assert action == "node.updated"
        assert event == vm
Example #7
0
def test_stop(loop, vm, async_run):
    process = MagicMock()

    # Wait process kill success
    future = asyncio.Future()
    future.set_result(True)
    process.wait.return_value = future
    process.returncode = None

    vm.ip_address = "192.168.1.1"
    with NotificationManager.instance().queue() as queue:
        with patch("sys.platform", return_value="win"):
            with asyncio_patch("gns3server.compute.traceng.traceng_vm.TraceNGVM._check_requirements", return_value=True):
                with asyncio_patch("asyncio.create_subprocess_exec", return_value=process):
                    nio = TraceNG.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1", "filters": {}})
                    async_run(vm.port_add_nio_binding(0, nio))

                    vm._ubridge_send = AsyncioMagicMock()
                    async_run(vm.start("192.168.1.2"))
                    assert vm.is_running()

                    with asyncio_patch("gns3server.utils.asyncio.wait_for_process_termination"):
                        loop.run_until_complete(asyncio.ensure_future(vm.stop()))
                    assert vm.is_running() is False

                    process.terminate.assert_called_with()

                    async_run(queue.get(1))  #  Ping
                    async_run(queue.get(1))  #  Started

                    (action, event, kwargs) = async_run(queue.get(1))
                    assert action == "node.updated"
                    assert event == vm
Example #8
0
def test_stop(loop, vm, async_run):
    process = MagicMock()

    # Wait process kill success
    future = asyncio.Future()
    future.set_result(True)
    process.wait.return_value = future
    process.returncode = None

    with NotificationManager.instance().queue() as queue:
        with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True):
            with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"):
                with asyncio_patch("asyncio.create_subprocess_exec", return_value=process):
                    nio = VPCS.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"})
                    async_run(vm.port_add_nio_binding(0, nio))

                    async_run(vm.start())
                    assert vm.is_running()

                    with asyncio_patch("gns3server.utils.asyncio.wait_for_process_termination"):
                        loop.run_until_complete(asyncio.async(vm.stop()))
                    assert vm.is_running() is False

                    if sys.platform.startswith("win"):
                        process.send_signal.assert_called_with(1)
                    else:
                        process.terminate.assert_called_with()

                    async_run(queue.get(0))  #  Ping
                    async_run(queue.get(0))  #  Started

                    (action, event, kwargs) = async_run(queue.get(0))
                    assert action == "node.updated"
                    assert event == vm
def test_queue_ping(async_run):
    """
    If we don't send a message during a long time (0.5 seconds)
    a ping is send
    """
    NotificationManager.reset()
    notifications = NotificationManager.instance()
    with notifications.queue() as queue:
        assert len(notifications._listeners) == 1

        res = async_run(queue.get(5))
        assert res[0] == "ping"

        res = async_run(queue.get(0.5))
        assert res[0] == "ping"
        assert res[1]["cpu_usage_percent"] is not None
    assert len(notifications._listeners) == 0
Example #10
0
def test_emit(async_run):

    with NotificationManager.instance().queue() as queue:
        (action, event, context) = async_run(queue.get(0.5))  #  Ping

        project = Project(project_id=str(uuid4()))
        project.emit("test", {})
        (action, event, context) = async_run(queue.get(0.5))
        assert action == "test"
        assert context["project_id"] == project.id
Example #11
0
def test_termination_callback(vm, async_run):

    vm.status = "started"

    with NotificationManager.instance().queue() as queue:
        async_run(vm._termination_callback(0))
        assert vm.status == "stopped"

        async_run(queue.get(0))  #  Ping

        (action, event, kwargs) = async_run(queue.get(0))
        assert action == "node.updated"
        assert event == vm
async def test_stop(vm):

    process = MagicMock()
    # Wait process kill success
    future = asyncio.Future()
    future.set_result(True)
    process.wait.return_value = future
    process.returncode = None

    with NotificationManager.instance().queue() as queue:
        with asyncio_patch(
                "gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements",
                return_value=True):
            with asyncio_patch(
                    "gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"
            ):
                with asyncio_patch("asyncio.create_subprocess_exec",
                                   return_value=process):
                    nio = VPCS.instance().create_nio({
                        "type": "nio_udp",
                        "lport": 4242,
                        "rport": 4243,
                        "rhost": "127.0.0.1",
                        "filters": {}
                    })
                    await vm.port_add_nio_binding(0, nio)

                    await vm.start()
                    assert vm.is_running()

                    with asyncio_patch(
                            "gns3server.utils.asyncio.wait_for_process_termination"
                    ):
                        await vm.stop()
                    assert vm.is_running() is False

                    if sys.platform.startswith("win"):
                        process.send_signal.assert_called_with(1)
                    else:
                        process.terminate.assert_called_with()

                    await queue.get(1)  #  Ping
                    await queue.get(1)  #  Started

                    (action, event, kwargs) = await queue.get(1)
                    assert action == "node.updated"
                    assert event == vm
    def notifications(request, response):
        notifications = NotificationManager.instance()
        ws = WebSocketResponse()
        yield from ws.prepare(request)

        asyncio.async(process_websocket(ws))

        with notifications.queue() as queue:
            while True:
                try:
                    notification = yield from queue.get_json(5)
                except asyncio.futures.CancelledError:
                    break
                if ws.closed:
                    break
                ws.send_str(notification)
        return ws
Example #14
0
async def test_stop(vm):

    process = MagicMock()
    # Wait process kill success
    future = asyncio.Future()
    future.set_result(True)
    process.wait.return_value = future
    process.returncode = None

    vm.ip_address = "192.168.1.1"
    with NotificationManager.instance().queue() as queue:
        with patch("sys.platform", return_value="win"):
            with asyncio_patch(
                    "gns3server.compute.traceng.traceng_vm.TraceNGVM._check_requirements",
                    return_value=True):
                with asyncio_patch("asyncio.create_subprocess_exec",
                                   return_value=process):
                    nio = TraceNG.instance().create_nio({
                        "type": "nio_udp",
                        "lport": 4242,
                        "rport": 4243,
                        "rhost": "127.0.0.1",
                        "filters": {}
                    })
                    await vm.port_add_nio_binding(0, nio)

                    vm._ubridge_send = AsyncioMagicMock()
                    await vm.start("192.168.1.2")
                    assert vm.is_running()

                    with asyncio_patch(
                            "gns3server.utils.asyncio.wait_for_process_termination"
                    ):
                        await vm.stop()
                    assert vm.is_running() is False

                    process.terminate.assert_called_with()

                    await queue.get(1)  #  Ping
                    await queue.get(1)  #  Started

                    (action, event, kwargs) = await queue.get(1)
                    assert action == "node.updated"
                    assert event == vm
Example #15
0
async def test_termination_callback_error(vm, tmpdir):

    with open(str(tmpdir / "qemu.log"), "w+") as f:
        f.write("BOOMM")

    vm.status = "started"
    vm._stdout_file = str(tmpdir / "qemu.log")

    with NotificationManager.instance().queue() as queue:
        await vm._termination_callback(1)
        assert vm.status == "stopped"

        await queue.get(1)  # Ping

        (action, event, kwargs) = queue.get_nowait()
        assert action == "node.updated"
        assert event == vm

        (action, event, kwargs) = queue.get_nowait()
        assert action == "log.error"
        assert event["message"] == "QEMU process has stopped, return code: 1\nBOOMM"
Example #16
0
def test_termination_callback_error(vm, tmpdir, async_run):

    with open(str(tmpdir / "qemu.log"), "w+") as f:
        f.write("BOOMM")

    vm.status = "started"
    vm._stdout_file = str(tmpdir / "qemu.log")

    with NotificationManager.instance().queue() as queue:
        async_run(vm._termination_callback(1))
        assert vm.status == "stopped"

        async_run(queue.get(0))  # Ping

        (action, event, kwargs) = queue.get_nowait()
        assert action == "node.updated"
        assert event == vm

        (action, event, kwargs) = queue.get_nowait()
        assert action == "log.error"
        assert event["message"] == "QEMU process has stopped, return code: 1\nBOOMM"
Example #17
0
    async def notifications(request, response):
        notifications = NotificationManager.instance()
        ws = WebSocketResponse()
        await ws.prepare(request)

        request.app['websockets'].add(ws)
        asyncio.ensure_future(process_websocket(ws))
        log.info("New client has connected to compute WebSocket")
        try:
            with notifications.queue() as queue:
                while True:
                    notification = await queue.get_json(1)
                    if ws.closed:
                        break
                    await ws.send_str(notification)
        finally:
            log.info("Client has disconnected from compute WebSocket")
            if not ws.closed:
                await ws.close()
            request.app['websockets'].discard(ws)

        return ws