Ejemplo n.º 1
0
def _wait_for_bulk_discovery_job(web):  # noqa: F811 # pylint: disable=redefined-outer-name
    def job_completed():
        status = web.bulk_discovery_status()
        return status["job"]["state"] != "initialized" and status[
            "is_active"] is False

    wait_until(job_completed, timeout=30, interval=1)
Ejemplo n.º 2
0
def _wait_for_bulk_discovery_job(web):
    def job_completed():
        status = web.bulk_discovery_status()
        return status["job"]["state"] != "initialized" and status[
            "is_active"] is False

    wait_until(job_completed, timeout=30, interval=1)
Ejemplo n.º 3
0
def test_start_job(register_builtin_html):
    job = DummyBackgroundJob()
    job.set_function(job.execute_hello)

    status = job.get_status()
    assert status["state"] == background_job.JobStatusStates.INITIALIZED

    job.start()
    testlib.wait_until(job.is_active, timeout=5, interval=0.1)

    with pytest.raises(background_job.BackgroundJobAlreadyRunning):
        job.start()
    assert job.is_active()

    job.finish_hello_event.set()

    testlib.wait_until(lambda: job.get_status()["state"] not in [
        background_job.JobStatusStates.INITIALIZED, background_job.
        JobStatusStates.RUNNING
    ],
                       timeout=5,
                       interval=0.1)

    status = job.get_status()
    assert status["state"] == background_job.JobStatusStates.FINISHED

    output = "\n".join(status["loginfo"]["JobProgressUpdate"])
    assert "Initialized background job" in output
    assert "Hallo :-)" in output
Ejemplo n.º 4
0
def test_start_job():
    job = DummyBackgroundJob()
    job.set_function(job.execute_hello)

    status = job.get_status()
    assert status["state"] == background_job.JobStatus.state_initialized

    job.start()
    testlib.wait_until(job.is_running, timeout=5, interval=0.1)

    with pytest.raises(background_job.BackgroundJobAlreadyRunning):
        job.start()
    assert job.is_running()

    job.finish_hello_event.set()

    testlib.wait_until(lambda: job.get_status()["state"] not in [
        background_job.JobStatus.state_initialized, background_job.JobStatus.
        state_running
    ],
                       timeout=5,
                       interval=0.1)

    status = job.get_status()
    assert status["state"] == background_job.JobStatus.state_finished

    output = "\n".join(status["loginfo"]["JobProgressUpdate"])
    assert "Initialized background job" in output
    assert "Hallo :-)" in output
def initial_state(site, scenario):
    # Before each test: Set to initial state: Both UP
    site.send_host_check_result("notify-test-child", 0, "UP")
    site.send_host_check_result("notify-test-parent", 0, "UP")

    # Before each test: Clear logs
    if scenario.core == "cmc":
        # The command is processed asynchronously -> Wait for completion
        inode_before = os.stat(site.path("var/check_mk/core/history")).st_ino
        site.live.command("[%d] ROTATE_LOGFILE" % time.time())

        def rotated_log():
            try:
                return inode_before != os.stat(
                    site.path("var/check_mk/core/history")).st_ino
            except OSError as e:
                if e.errno == errno.ENOENT:
                    return False
                else:
                    raise e

        wait_until(rotated_log, timeout=10)
    else:
        site.delete_file("var/nagios/nagios.log")

    time.sleep(1)  # TODO: Add check for rotation
Ejemplo n.º 6
0
def _wait_for_waiting_lock():
    """Use /proc/locks to wait until one lock is in waiting state

    https://man7.org/linux/man-pages/man5/proc.5.html
    """
    def has_waiting_lock():
        pid = os.getpid()
        with Path("/proc/locks").open() as f:
            for line in f:
                p = line.strip().split()
                if p[1] == "->" and p[2] == "FLOCK" and p[4] == "WRITE" and p[5] == str(pid):
                    return True
        return False

    wait_until(has_waiting_lock, timeout=1, interval=0.01)
Ejemplo n.º 7
0
def test_stop_job(register_builtin_html):
    job = DummyBackgroundJob()
    job.set_function(job.execute_endless)
    job.start()

    testlib.wait_until(lambda: "Hanging loop" in job.get_status()["loginfo"]["JobProgressUpdate"],
                       timeout=5,
                       interval=0.1)

    status = job.get_status()
    assert status["state"] == background_job.JobStatusStates.RUNNING

    job.stop()

    status = job.get_status()
    assert status["state"] == background_job.JobStatusStates.STOPPED

    output = "\n".join(status["loginfo"]["JobProgressUpdate"])
    assert "Job was stopped" in output
Ejemplo n.º 8
0
def _start(request, client, version=None, is_update=False, **kwargs):
    if version is None:
        version = build_version()

    try:
        if version.version == build_version().version:
            _image, _build_logs = _build(request, client, version)
        else:
            # In case the given version is not the current branch version, don't
            # try to build it. Download it instead!
            _image = _pull(client, version)
    except requests.exceptions.ConnectionError as e:
        raise Exception(
            "Failed to access docker socket (Permission denied). You need to be member of the "
            "docker group to get access to the socket (e.g. use \"make -C docker setup\") to "
            "fix this, then restart your computer and try again.") from e

    c = client.containers.run(image=_image.id, detach=True, **kwargs)

    try:
        site_id = kwargs.get("environment", {}).get("CMK_SITE_ID", "cmk")

        request.addfinalizer(lambda: c.remove(force=True))

        testlib.wait_until(
            lambda: _exec_run(c, ["omd", "status"], user=site_id)[0] == 0,
            timeout=120)
        output = c.logs().decode("utf-8")

        if not is_update:
            assert "Created new site" in output
            assert "cmkadmin with password:"******"Created new site" not in output
            assert "cmkadmin with password:"******"STARTING SITE" in output
        assert "### CONTAINER STARTED" in output
    finally:
        sys.stdout.write("Log so far: %s\n" % c.logs().decode("utf-8"))

    return c
Ejemplo n.º 9
0
def snmpsim_fixture(site, snmp_data_dir, tmp_path_factory):
    tmp_path = tmp_path_factory.getbasetemp()
    log.logger.setLevel(logging.DEBUG)
    debug.enable()

    process_definitions = [
        _define_process(idx, auth, tmp_path, snmp_data_dir)
        for idx, auth in enumerate(_create_auth_list())
    ]

    for process_def in process_definitions:
        wait_until(_create_listening_condition(process_def), timeout=20)

    yield

    log.logger.setLevel(logging.INFO)
    debug.disable()

    logger.debug("Stopping snmpsimd...")
    for process_def in process_definitions:
        process_def.process.terminate()
        process_def.process.wait()
    logger.debug("Stopped snmpsimd.")
Ejemplo n.º 10
0
def _start(request, client, version=None, is_update=False, **kwargs):
    if version is None:
        version = build_version()

    if version.version == build_version().version:
        _image, _build_logs = _build(request, client, version)
    else:
        # In case the given version is not the current branch version, don't
        # try to build it. Download it instead!
        _image = _pull(client, version)

    c = client.containers.run(image=_image.id, detach=True, **kwargs)

    try:
        site_id = kwargs.get("environment", {}).get("CMK_SITE_ID", "cmk")

        request.addfinalizer(lambda: c.remove(force=True))

        testlib.wait_until(
            lambda: c.exec_run(["omd", "status"], user=site_id)[0] == 0,
            timeout=120)
        output = c.logs()

        if not is_update:
            assert "Created new site" in output
            assert "cmkadmin with password:"******"Created new site" not in output
            assert "cmkadmin with password:"******"STARTING SITE" in output
        assert "### CONTAINER STARTED" in output
    finally:
        print "Log so far: %s" % c.logs()

    return c
Ejemplo n.º 11
0
def snmpsim_fixture(site, request, tmp_path_factory):
    tmp_path = tmp_path_factory.getbasetemp()
    source_data_dir = Path(request.fspath.dirname) / "snmp_data"

    log.logger.setLevel(logging.DEBUG)
    debug.enable()
    cmd = [
        "snmpsimd.py",
        #"--log-level=error",
        "--cache-dir",
        str(tmp_path / "snmpsim"),
        "--data-dir",
        str(source_data_dir),
        # TODO: Fix port allocation to prevent problems with parallel tests
        #"--agent-unix-endpoint="
        "--agent-udpv4-endpoint=127.0.0.1:1337",
        "--agent-udpv6-endpoint=[::1]:1337",
        "--v3-user=authOnlyUser",
        "--v3-auth-key=authOnlyUser",
        "--v3-auth-proto=MD5",
    ]

    p = subprocess.Popen(
        cmd,
        close_fds=True,
        # Silence the very noisy output. May be useful to enable this for debugging tests
        #stdout=open(os.devnull, "w"),
        #stderr=subprocess.STDOUT,
    )

    # Ensure that snmpsim is ready for clients before starting with the tests
    def is_listening():
        if p.poll() is not None:
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        num_sockets = 0
        try:
            for e in os.listdir("/proc/%d/fd" % p.pid):
                try:
                    if os.readlink("/proc/%d/fd/%s" % (p.pid, e)).startswith("socket:"):
                        num_sockets += 1
                except OSError:
                    pass
        except OSError:
            if p.poll() is None:
                raise
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        if num_sockets < 2:
            return False

        # Correct module is only available in the site
        import netsnmp  # type: ignore[import] # pylint: disable=import-error,import-outside-toplevel
        var = netsnmp.Varbind("sysDescr.0")
        result = netsnmp.snmpget(var, Version=2, DestHost="127.0.0.1:1337", Community="public")
        if result is None or result[0] is None:
            return False
        return True

    wait_until(is_listening, timeout=20)

    yield

    log.logger.setLevel(logging.INFO)
    debug.disable()

    logger.debug("Stopping snmpsimd...")
    p.terminate()
    p.wait()
    logger.debug("Stopped snmpsimd.")