Special agent , check plugin fails w "'__name__' not in globals

CMK version:
2.2.0p28
OS version:
Debian 6.1.0-20-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.85-1 (2024-04-11) x86_64 GNU/Linux

Error message:
"‘name’ not in globals

Output of “cmk --debug -vvn hostname”: (If it is a problem with checks or plugins)

Error in plugin file /omd/sites/demo5g/local/share/check_mk/checks/airspan_api.py: "'__name__' not in globals"
Trying to acquire lock on /omd/sites/demo5g/var/check_mk/crashes/base/c6f96b50-4a7f-11ef-860b-000c2977a675/crash.info
Got lock on /omd/sites/demo5g/var/check_mk/crashes/base/c6f96b50-4a7f-11ef-860b-000c2977a675/crash.info
Releasing lock on /omd/sites/demo5g/var/check_mk/crashes/base/c6f96b50-4a7f-11ef-860b-000c2977a675/crash.info
Released lock on /omd/sites/demo5g/var/check_mk/crashes/base/c6f96b50-4a7f-11ef-860b-000c2977a675/crash.info
Traceback (most recent call last):
  File "/omd/sites/demo5g/bin/cmk", line 97, in <module>
    errors = config.load_all_agent_based_plugins(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/config.py", line 1669, in load_all_agent_based_plugins
    errors.extend(load_checks(get_check_api_context, filelist))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/config.py", line 1739, in load_checks
    did_compile |= load_precompiled_plugin(f, check_context)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/config.py", line 2033, in load_precompiled_plugin
    exec(marshal.loads(Path(precompiled_path).read_bytes()[_PYCHeader.SIZE :]), check_context)
  File "/omd/sites/demo5g/local/share/check_mk/checks/airspan_api.py", line 6, in <module>
    from .agent_based_api.v1 import check_levels, Metric, register, Result, Service, State
KeyError: "'__name__' not in globals"

ich habe ein Check Plugin erstellt entspr. https://docs.checkmk.com/latest/en/devel_check_plugins.html:

#!/usr/bin/env python3

from .agent_based_api.v1 import check_levels, Metric, register, Result, Service, State

def parse_airspan_api(string_table):
    parsed = {}
    for line in string_table:
        parsed[line[0]] = {"alarm_counters": line[1]}
    print(parsed)
    return parsed
   
def discover_airspan_api(section):
    for gnb in section:
        yield Service(item=gnb)
        
def check_airspan_api(item,section):
    attr = section.get(item)
    yield Result(state=State.OK, summary=f"alarm counters: {attr['alarm_counters']}")

register.agent_section(
    name = "airspan_api",
    parse_function = parse_airspan_api,
)

register.check_plugin(
    name = "airspan_api",
    sections = ["airspan_api"],
    service_name = "gnb %s",
    discovery_function = discover_airspan_api,
    check_function = check_airspan_api,
)
'''

als check für "other Integrations"->"Individual program call instead of agent access" abgelegt unter "~/local/lib/check_mk/base/plugins/agent_based/" funktioniert es.
Wenn ich den gleichen check für einen special agent benutzen möchte, lege ich ihn entspr.  https://digaround.cloud/check-mk-create-own-special-agent/ unter "~/local/share/check_mk/checks" ab und bekomme den Fehler.
scheinbar muss ich für den import

`from .agent_based_api.v1 import check_levels, Metric, register, Result, Service, State`

was anderes angeben ... aber was?

vielen Dank
Torsten

Hey @tgoehler1 and welcome.

Had the same error, but could resolve it easily.
You need to fix the path to the “agent_based_api.v1” library.

Change it to the complete path:
“cmk.base.plugins.agent_based.agent_based_api.v1”

After that it should work.

Regards Kruzgoth

Look here pls.
https://forum.checkmk.com/t/special-agent-check-plugin-name-not-in-globals/48628/2?u=kruzgoth

And no double Posts please!

with the path changed accordingly I get

Error in plugin file /omd/sites/demo5g/local/share/check_mk/checks/airspan_api.py: do not register from PosixPath('/omd/sites/demo5g/local/share/check_mk/checks/airspan_api.py') 'airspan_api'

sorry, for duplication :flushed:

Move the file to “local/lib/check_mk/base/plugins/agent_based/”.
And check if you have another file trying to register “airspan_api”, that you customized.
If you have, you need to comment out/delete those register attempts.

For the sake of clarity, I merged your answer, @Kruzgoth from the other thread into this one, I hope it is ok :slight_smile: I will close the other one, as the discussion continues here

2 Likes

when I move the check plugin there … the it works with the the agent addresses through “Individual program call instead of agent access”

but when I deactivate that and activate the special agent (which ist the same code but just at ~/local/share/checkmk/agents/special/agent_airspan_api" … I get

Error running automation call service-discovery-preview (exit code 2), error:

'airspan_api'

so, I think the check must be at “~/local/share/checkmk/checks” for the special agent service discovery approach to work correctly. But the I get the import problem :frowning:

Did you re-match the rule-group?

what doe you mean by “re-match the rule-group”
I removed “Individual program call instead of agent access” and deactivated from the host it and activated the special agent explicitetly for the host.
Activated changes and even rebooted the server …

I mean that you need to register the customized check via “register.check_plugin”.
If you registered your customization, but have another customized check with the same “name”, check_mk will print out an error regarding the second “instance” of this check.

I checked, but the its registered only once.

I suppose it’s a general problem with the checkmk version i use and the way special agents support.
I reproduced it wtih another agent/check combination

When I place the check to “~/local/share/checkmk/checks/*.py” with the relative import:
from .agent_based_api.v1 import check_levels, Metric, register, Result, Service, State
then I get

when I use in contrast the asolute import path like:
from cmk.base.plugins.agent_based.agent_based_api.v1 import check_levels, Metric, register, Result, Service, State
then I get

  File "/omd/sites/demo5g/lib/python3/cmk/base/api/agent_based/register/utils.py", line 56, in get_validated_plugin_module_name
    raise ImportError("do not register from %r" % path)
ImportError: do not register from PosixPath('/omd/sites/demo5g/local/share/check_mk/checks/tgtest.py')

so, it looks like “/omd/sites/demo5g/lib/python3/cmk/base/api/agent_based/register/utils.py” denies to import the api from a check located at "~/local/share/check_mk/checks/.

But when I place the check to “~/local/lib/check_mk/base/plugins/agent_based/xxx” it does not work together with a special agent configured by
"~/local/share/check_mk/agents/special/agent_xxxx
“~/local/share/check_mk/checks/agent_xxx.py” and
"~/local/share/check_mk/web/plugins/wato/xxx.py.

and I get:

Traceback (most recent call last):
  File "/omd/sites/demo5g/bin/cmk", line 118, in <module>
    exit_status = modes.call("--check", None, opts, args)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/modes/__init__.py", line 68, in call
    return handler(*handler_args)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/modes/check_mk.py", line 2003, in mode_check
    with error_handler:
  File "/omd/sites/demo5g/lib/python3/cmk/checkers/error_handling.py", line 59, in __exit__
    self._result = _handle_failure(
                   ^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/checkers/error_handling.py", line 95, in _handle_failure
    raise exc
  File "/omd/sites/demo5g/lib/python3/cmk/base/modes/check_mk.py", line 2005, in mode_check
    fetched = fetcher(hostname, ip_address=ipaddress)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/agent_based/confcheckers.py", line 240, in __call__
    return _fetch_all(
           ^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/agent_based/confcheckers.py", line 71, in _fetch_all
    return [
           ^
  File "/omd/sites/demo5g/lib/python3/cmk/base/agent_based/confcheckers.py", line 75, in <listcomp>
    source.fetcher(),
    ^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/_sources.py", line 389, in fetcher
    cmdline=self.config_cache.make_special_agent_cmdline(
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/config.py", line 2780, in make_special_agent_cmdline
    args = _make_source_args(
           ^^^^^^^^^^^^^^^^^^
  File "/omd/sites/demo5g/lib/python3/cmk/base/config.py", line 2773, in _make_source_args
    info_func = special_agent_info[agentname]
                ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^
KeyError: 'tgtest'

What do you mean by “which ist the same code”? The same as the check plugin? At ~/local/share/checkmk/agents/special/ goes the stub file that calls the actual special agent.

so your check plugin (the one you have posted) should go to

~/local/lib/check_mk/base/plugins/agent_based/airspan_api.py

the stub to call the agent

~/local/share/checkmk/agents/special/agent_airspan_api

the actual agent that fetches the api data

~/local/lib/check_mk/special_agents/agent_airspan_api.py

the ruleset for the special agent

~/local/lib/check_mk/gui/wato/agent_airspan_api.py

the cli “generator” for the special agent (stub)

~/local/share/check_mk/checks/agent_airspan_api

for CMK2.3 the paths are a bit different but the setup from CMK 2.2 sill works.

here you will find a complete special agent that you might use as example.

BTW: can you post an output of your specail agent?

1 Like

I thank you very much,
I really appreciate you guys to help me.

instead of putting a stub agent to ~/local/share/checkmk/agents/special/
which calls the real agent at ~/local/lib/check_mk/special_agents/ it should work to put the agent directly to ~/local/share/checkmk/agents/special/ … shouldn’t it?

there’s some thing unclear with the ruleset.
according to the example you refered, the dir ~/local/lib/check_mk/gui/wato doesn’t exists. there’s ~/local/lib/check_mk/gui/plugins/wato/check_parameters/ssllabs_grade.py and `~/local/share/check_mk/web/plugins/agent_ssllabs.py’
What’s the purpose of those two?

I created a small example to to find out/understand the special agent mechanic, but I’m still desperatly failing

agent at ~/local/share/check_mk/agents/special/agent_tgtest

#!/usr/bin/python3
import os
import sys
eingabe = sys.argv[1]
print("<<<tgtest:sep(59)>>>")
print("%s;Eingabe ist: %s" % ("tgservice",eingabe ))

web plugin at ~/local/share/check_mk/web/plugins/wato/tgtest.py

#!/usr/bin/env python3
# -*- mode: Python; encoding: utf-8; indent-offset: 4; autowrap: nil -*-

from cmk.gui.i18n import _
from cmk.gui.valuespec import (
    Dictionary,
    TextAscii,
#    PasswordSpec,
)


from cmk.gui.plugins.wato import (
    IndividualOrStoredPassword,
    RulespecGroup,
    monitoring_macro_help,
    rulespec_group_registry,
    rulespec_registry,
    HostRulespec,
)

from cmk.gui.plugins.wato.datasource_programs import (
    RulespecGroupDatasourcePrograms,
)

def _valuespec_special_agents_tgtest():
    return Dictionary(
        elements=[
            ("eingabe", TextAscii(title=_("eingabe"), allow_empty=False)),
        ],
        optional_keys=False,
        title=_("TG Test  Parameters"),
    )

rulespec_registry.register(
    HostRulespec(
        group=RulespecGroupDatasourcePrograms,
        name="special_agents:tgtest",
        valuespec=_valuespec_special_agents_tgtest,
    ))

cli generator at ~/local/share/check_mk/checks/agent_tgtest

#!/usr/bin/env python3
# -*- encoding: utf-8; py-indent-offset: 4 -*-

# store at ~/local/share/check_mk/checks/agent_airspan_api.py

def agent_tgtest_arguments(params, eingabe):
    args = []
    args.append(params['eingabe'])
    return args

special_agent_info['agent_tgtest'] = agent_tgtest_arguments

and the check at ~/local/lib/check_mk/base/plugins/agent_based/tgtest.py

#!/usr/bin/env python3

from cmk.base.plugins.agent_based.agent_based_api.v1 import check_levels, Metric, register, Result, Service, State

def parse_tgtest(string_table):
    parsed = {}
    for line in string_table:
        parsed[line[0]] = {"eingabe": line[1]}
    print(parsed)
    return parsed
   
def discover_tgtest(section):
    for gnb in section:
        yield Service(item=gnb)
        
def check_tgtest(item,section):
    attr = section.get(item)
    yield Result(state=State.OK, summary=f"eingabe: {attr['eingabe']}")

register.agent_section(
    name = "tgtest",
    parse_function = parse_tgtest,
)

register.check_plugin(
    name = "tgtest",
    sections = ["tgtest"],
    service_name = "tgtest %s",
    discovery_function = discover_tgtest,
    check_function = check_tgtest,
)

So, the check should just return what I configure as “eingabe” to the agent configuration parameters.
Actually, as a result, I get the config page for “TG Test Parameters” under “Other Integrations” … that’s fine.
but configuring a host to use that agent results in

Error running automation call service-discovery-preview (exit code 2), error:
'tgtest'

What’s wrong with that example?

btw. the regarding agent output is

<<<tgtest:sep(59)>>>
tgservice;Eingabe ist: bla

ok, I had a closer look at your code.
→ Special agent → works
→ Check Plugin → Works
→ Agent Ruleset → wrong Imports

# from cmk.gui.plugins.wato import (
from cmk.gui.plugins.wato.utils import (
    # IndividualOrStoredPassword,
    # RulespecGroup,
    # monitoring_macro_help,
    # rulespec_group_registry,
    rulespec_registry,
    HostRulespec,
)

# from cmk.gui.plugins.wato.datasource_programs import (
#     RulespecGroupDatasourcePrograms,
# )

from cmk.gui.plugins.wato.special_agents.common import RulespecGroupDatasourcePrograms

→ CLI generator → wrong params definition, wrong special_agent_info

# def agent_tgtest_arguments(params, eingabe):
def agent_tgtest_arguments(params, hostname, ipaddress):
    args = []
    args.append(params['eingabe'])
    return args

# special_agent_info['agent_tgtest'] = agent_tgtest_arguments
special_agent_info['tgtest'] = agent_tgtest_arguments

and as mkp :wink:
tgtest-0.0.2.mkp (1.7 KB)

Cheers
Thomas

this actually works,
I set up my own special agents successfully
thank you so much
Torsten

Happy to help. Please don’t forget to mark this as a solution if it solves your problem :wink:

Cheers
Thomas