Example #1
0
def evaluate_time_series_expression(expression, rrd_data):
    if rrd_data:
        num_points = len(list(rrd_data.values())[0])
    else:
        num_points = 1

    if expression[0] == "operator":
        operator_id, operands = expression[1:]
        operands_evaluated = [
            evaluate_time_series_expression(a, rrd_data) for a in operands
        ]
        return time_series_math(operator_id, operands_evaluated)

    if expression[0] == "transformation":
        (transform, conf), operands = expression[1:]
        operands_evaluated = evaluate_time_series_expression(
            operands[0], rrd_data)
        if transform == 'percentile':
            return time_series_operator_perc(operands_evaluated, conf)
        if transform == 'forecast':
            if cmk_version.is_raw_edition():
                raise MKGeneralException(
                    _("Forecast calculations are only available with the "
                      "Checkmk Enterprise Editions"))
            # Suppression is needed to silence pylint in CRE environment
            from cmk.gui.cee.plugins.metrics.forecasts import time_series_transform_forecast  # pylint: disable=no-name-in-module
            return time_series_transform_forecast(
                TimeSeries(operands_evaluated, rrd_data['__range']), conf)

    if expression[0] == "rrd":
        key = tuple(expression[1:])
        if key in rrd_data:
            return rrd_data[key]
        return [None] * num_points

    if expression[0] == "constant":
        return [expression[1]] * num_points

    raise NotImplementedError()
Example #2
0
def test_refresh_snapins():
    expected_refresh_snapins = [
        "admin_mini",
        "performance",
        "master_control",
        "mkeventd_performance",
        "sitestatus",
        "tactical_overview",
        "tag_tree",
        "time",
    ]

    if not cmk_version.is_raw_edition():
        expected_refresh_snapins += [
            "cmc_stats",
        ]

    refresh_snapins = [
        s.type_name() for s in snapin_registry.values()
        if s.refresh_regularly()
    ]
    assert sorted(refresh_snapins) == sorted(expected_refresh_snapins)
Example #3
0
def test_check_crash_report_from_exception(monkeypatch):
    Scenario().apply(monkeypatch)
    try:
        raise Exception("DING")
    except Exception:
        crash = crash_reporting.CheckCrashReport.from_exception_and_context(
            hostname="testhost",
            check_plugin_name="uptime",
            check_plugin_kwargs={
                "item": None,
                "params": None
            },
            is_manual_check=False,
            description=u"Uptime",
            text=u"Output",
        )

    _check_generic_crash_info(crash)
    assert crash.type() == "check"
    assert crash.crash_info["exc_type"] == "Exception"
    assert crash.crash_info["exc_value"] == "DING"

    for key, (ty, value) in {
            "check_output": (str, "Output"),
            "host": (str, "testhost"),
            "is_cluster": (bool, False),
            "description": (str, "Uptime"),
            "check_type": (str, "uptime"),
            "item": (type(None), None),
            "params": (type(None), None),
            "inline_snmp": (bool, not cmk_version.is_raw_edition()),
            "manual_check": (bool, False),
    }.items():
        assert key in crash.crash_info["details"]
        assert isinstance(crash.crash_info["details"][key], ty), (  # pylint: disable=isinstance-second-argument-not-valid-type
            "Key %r has wrong type: %r" %
            (key, type(crash.crash_info["details"][key])))
        assert crash.crash_info["details"][
            key] == value, "%r has invalid value" % key
Example #4
0
def _expected_intervals():
    expected = [
        ("hoststats", False),
        ("mk_logo", False),
        ("nodata", False),
        ("notify_failed_notifications", 60),
        ("user_messages", False),
        ("overview", False),
        ("pnpgraph", 60),
        ("servicestats", False),
        ("snapin", 30),
        ("url", False),
        ("view", False),
        ("linked_view", False),
    ]

    if not cmk_version.is_raw_edition():
        expected += [
            ("custom_graph", 60),
        ]

    return expected
Example #5
0
def get_replication_paths():
    paths = [
        ("dir", "check_mk", cmk.gui.watolib.utils.wato_root_dir(),
         ["sitespecific.mk"]),
        ("dir", "multisite", cmk.gui.watolib.utils.multisite_dir(),
         ["sitespecific.mk"]),
        ("file", "htpasswd", cmk.utils.paths.htpasswd_file),
        ("file", "auth.secret",
         '%s/auth.secret' % os.path.dirname(cmk.utils.paths.htpasswd_file)),
        ("file", "auth.serials",
         '%s/auth.serials' % os.path.dirname(cmk.utils.paths.htpasswd_file)),
        # Also replicate the user-settings of Multisite? While the replication
        # as such works pretty well, the count of pending changes will not
        # know.
        ("dir", "usersettings", cmk.utils.paths.var_dir + "/web",
         ["*/report-thumbnails"]),
        ("dir", "mkps", cmk.utils.paths.var_dir + "/packages"),
        ("dir", "local", cmk.utils.paths.omd_root + "/local"),
    ]  # type: List[ReplicationPath]

    # TODO: Move this to CEE specific code again
    if not cmk_version.is_raw_edition():
        paths += [
            ("dir", "liveproxyd",
             cmk.gui.watolib.utils.liveproxyd_config_dir(),
             ["sitespecific.mk"]),
        ]

    # Include rule configuration into backup/restore/replication. Current
    # status is not backed up.
    if config.mkeventd_enabled:
        _rule_pack_dir = str(ec.rule_pack_dir())
        paths.append(("dir", "mkeventd", _rule_pack_dir, ["sitespecific.mk"]))

        _mkp_rule_pack_dir = str(ec.mkp_rule_pack_dir())
        paths.append(("dir", "mkeventd_mkp", _mkp_rule_pack_dir))

    return paths + _replication_paths
Example #6
0
def test_registered_permission_sections():
    expected_sections = [
        ("bookmark_list", (50, "Bookmark lists", True)),
        ("custom_snapin", (50, "Custom sidebar elements", True)),
        ("sidesnap", (50, "Sidebar elements", True)),
        ("notification_plugin", (50, "Notification plugins", True)),
        ("wato", (50, "Setup", False)),
        ("background_jobs", (50, "Background jobs", False)),
        ("bi", (50, "BI - Checkmk Business Intelligence", False)),
        ("general", (10, "General Permissions", False)),
        ("mkeventd", (50, "Event Console", False)),
        ("action", (50, "Commands on host and services", True)),
        ("dashboard", (50, "Dashboards", True)),
        ("nagvis", (50, "NagVis", False)),
        ("view", (50, "Views", True)),
        ("icons_and_actions", (50, "Icons", True)),
        ("pagetype_topic", (50, "Topics", True)),
    ]

    if not cmk_version.is_raw_edition():
        expected_sections += [
            ("agent_registration", (50, "Agent registration", False)),
            ("custom_graph", (50, "Custom graphs", True)),
            ("forecast_graph", (50, "Forecast graphs", True)),
            ("graph_collection", (50, "Graph collections", True)),
            ("graph_tuning", (50, "Graph tunings", True)),
            ("sla_configuration", (50, "Service Level Agreements", True)),
            ("report", (50, "Reports", True)),
        ]

    section_names = permission_section_registry.keys()
    assert sorted([s[0] for s in expected_sections]) == sorted(section_names)

    for name, (sort_index, title, do_sort) in expected_sections:
        section = permission_section_registry[name]()
        assert section.title == title
        assert section.sort_index == sort_index
        assert section.do_sort == do_sort
def test_registered_ac_tests():
    expected_ac_tests = [
        'ACTestAlertHandlerEventTypes',
        'ACTestApacheNumberOfProcesses',
        'ACTestApacheProcessUsage',
        'ACTestBackupConfigured',
        'ACTestBackupNotEncryptedConfigured',
        'ACTestBrokenGUIExtension',
        'ACTestCheckMKHelperUsage',
        'ACTestCheckMKFetcherUsage',
        'ACTestCheckMKCheckerNumber',
        'ACTestCheckMKCheckerUsage',
        'ACTestConnectivity',
        'ACTestESXDatasources',
        'ACTestEscapeHTMLDisabled',
        'ACTestGenericCheckHelperUsage',
        'ACTestHTTPSecured',
        'ACTestLDAPSecured',
        'ACTestLiveproxyd',
        'ACTestLivestatusUsage',
        'ACTestLivestatusSecured',
        'ACTestNumberOfUsers',
        'ACTestOldDefaultCredentials',
        'ACTestPersistentConnections',
        'ACTestRulebasedNotifications',
        'ACTestSizeOfExtensions',
        'ACTestTmpfs',
        'ACTestUnexpectedAllowedIPRanges',
    ]

    if not cmk_version.is_raw_edition():
        expected_ac_tests += [
            'ACTestSecureAgentUpdaterTransport',
            'ACTestSecureNotificationSpoolerMessages',
        ]

    registered_plugins = sorted(watolib.ac_test_registry.keys())
    assert registered_plugins == sorted(expected_ac_tests)
Example #8
0
def test_dashlet_registry_plugins():
    expected_plugins = [
        'hoststats',
        'notify_failed_notifications',
        'mk_logo',
        'servicestats',
        'url',
        'overview',
        'pnpgraph',
        'view',
        'linked_view',
        'notify_users',
        'nodata',
        'snapin',
    ]

    if not cmk_version.is_raw_edition():
        expected_plugins += [
            'alerts_bar_chart',
            'alert_statistics',
            'average_scatterplot',
            'barplot',
            'gauge',
            'notifications_bar_chart',
            'problem_graph',
            'single_metric',
            'site_overview',
            'custom_graph',
            'combined_graph',
            'ntop_alerts',
            'ntop_flows',
            'ntop_top_talkers',
            'single_timeseries',
        ]

    dashboard._transform_old_dict_based_dashlets()
    assert sorted(
        dashboard.dashlet_registry.keys()) == sorted(expected_plugins)
Example #9
0
def test_registered_jobs():

    expected = [
        "cmk.gui.inventory.run",
        "cmk.gui.plugins.cron.gui_background_job.housekeeping",
        "cmk.gui.plugins.cron.wato_folder_lookup_cache.rebuild_folder_lookup_cache",
        "cmk.gui.userdb.execute_userdb_job",
        "cmk.gui.userdb.execute_user_profile_cleanup_job",
        "cmk.gui.watolib.network_scan.execute_network_scan_job",
        "cmk.gui.watolib.activate_changes.execute_activation_cleanup_background_job",
    ]

    if not cmk_version.is_raw_edition():
        expected += [
            "cmk.gui.cee.plugins.wato.agent_registration.background_jobs.execute_host_registration_background_job",
            "cmk.gui.cee.reporting.cleanup_stored_reports",
            "cmk.gui.cee.reporting.do_scheduled_reports",
            "cmk.gui.cee.ntop.connector.ntop_instance_check",
            "cmk.gui.watolib.host_label_sync.execute_host_label_sync_job",
        ]

    found_jobs = sorted(["%s.%s" % (f.__module__, f.__name__) for f in cron.multisite_cronjobs])
    assert found_jobs == sorted(expected)
Example #10
0
def test_registered_background_jobs():
    expected_jobs = [
        'ParentScanBackgroundJob',
        'DummyBackgroundJob',
        'RenameHostsBackgroundJob',
        'RenameHostBackgroundJob',
        'FetchAgentOutputBackgroundJob',
        'BulkDiscoveryBackgroundJob',
        'UserSyncBackgroundJob',
        'ServiceDiscoveryBackgroundJob',
        'ActivationCleanupBackgroundJob',
        'CheckmkAutomationBackgroundJob',
        'DiagnosticsDumpBackgroundJob',
    ]

    if not cmk_version.is_raw_edition():
        expected_jobs += [
            'BakeAgentsBackgroundJob',
            'ReportingBackgroundJob',
        ]

    assert sorted(
        gui_background_job.job_registry.keys()) == sorted(expected_jobs)
Example #11
0
def _expected_intervals():
    expected = [
        ('hoststats', 60),
        ('mk_logo', False),
        ('network_topology', False),
        ('nodata', False),
        ('notify_failed_notifications', 60),
        ('notify_users', False),
        ('overview', False),
        ('pnpgraph', 60),
        ('servicestats', 60),
        ('snapin', 30),
        ('url', False),
        ('view', False),
        ('linked_view', False),
    ]

    if not cmk_version.is_raw_edition():
        expected += [
            ('custom_graph', 60),
        ]

    return expected
Example #12
0
def test_registered_snapins():
    expected_snapins = [
        "admin",
        "admin_mini",
        "biaggr_groups",
        "biaggr_groups_tree",
        "bookmarks",
        "dashboards",
        "hostgroups",
        "master_control",
        "mkeventd_performance",
        "nagvis_maps",
        "performance",
        "search",
        "servicegroups",
        "sitestatus",
        "speedometer",
        "tactical_overview",
        "tag_tree",
        "time",
        "views",
        "wato_folders",
        "wato_foldertree",
    ]

    if not cmk_version.is_raw_edition():
        expected_snapins += [
            "cmc_stats",
            "reports",
        ]

    if cmk_version.is_managed_edition():
        expected_snapins += [
            "customers",
        ]

    assert sorted(snapin_registry.keys()) == sorted(expected_snapins)
Example #13
0
def test_registered_permission_sections():
    expected_sections = [
        ('bookmark_list', (50, u'Bookmark lists', True)),
        ('custom_snapin', (50, u'Custom sidebar elements', True)),
        ('sidesnap', (50, u'Sidebar elements', True)),
        ('notification_plugin', (50, u'Notification plugins', True)),
        ('wato', (50, u"WATO - Checkmk's Web Administration Tool", False)),
        ('background_jobs', (50, u'Background jobs', False)),
        ('bi', (50, u'BI - Checkmk Business Intelligence', False)),
        ('general', (10, u'General Permissions', False)),
        ('mkeventd', (50, u'Event Console', False)),
        ('action', (50, u'Commands on host and services', True)),
        ('dashboard', (50, u'Dashboards', True)),
        ('nagvis', (50, u'NagVis', False)),
        ('view', (50, u'Views', True)),
        ('icons_and_actions', (50, u'Icons', True)),
        ('pagetype_topic', (50, u'Topics', True)),
    ]

    if not cmk_version.is_raw_edition():
        expected_sections += [
            ('custom_graph', (50, u'Custom graphs', True)),
            ('forecast_graph', (50, u'Forecast graphs', True)),
            ('graph_collection', (50, u'Graph collections', True)),
            ('graph_tuning', (50, u'Graph tunings', True)),
            ('sla_configuration', (50, u'Service Level Agreements', True)),
            ('report', (50, u'Reports', True)),
        ]

    section_names = permission_section_registry.keys()
    assert sorted([s[0] for s in expected_sections]) == sorted(section_names)

    for name, (sort_index, title, do_sort) in expected_sections:
        section = permission_section_registry[name]()
        assert section.title == title
        assert section.sort_index == sort_index
        assert section.do_sort == do_sort
Example #14
0
def test_filters_filter_table(request_context, test, monkeypatch):
    # Needed for DeploymentTristateFilter test
    def deployment_states(host_name):
        return {
            "abc": {
                "target_aghash": "abc",
            },
            "zzz": {},
        }[host_name]

    if not cmk_version.is_raw_edition():
        import cmk.gui.cee.agent_bakery as agent_bakery  # pylint: disable=redefined-outer-name,import-outside-toplevel,no-name-in-module

        monkeypatch.setattr(agent_bakery, "get_cached_deployment_status",
                            deployment_states)

    # Needed for FilterInvFloat test
    monkeypatch.setattr(cmk.gui.inventory, "get_inventory_table",
                        get_inventory_table_patch)
    monkeypatch.setattr(cmk.gui.inventory, "get_inventory_attribute",
                        get_inventory_table_patch)

    # Needed for FilterAggrServiceUsed test
    def is_part_of_aggregation_patch(host, service):
        return {("h", "srv1"): True}.get((host, service), False)

    monkeypatch.setattr(cmk.gui.bi, "is_part_of_aggregation",
                        is_part_of_aggregation_patch)

    with on_time("2018-04-15 16:50", "CET"):
        context: VisualContext = {test.ident: dict(test.request_vars)}

        # TODO: Fix this for real...
        if not cmk_version.is_raw_edition or test.ident != "deployment_has_agent":
            filt = cmk.gui.plugins.visuals.utils.filter_registry[test.ident]
            assert filt.filter_table(context, test.rows) == test.expected_rows
Example #15
0
def test_refresh_snapins():
    expected_refresh_snapins = [
        'admin',
        'admin_mini',
        'performance',
        'hostmatrix',
        'mkeventd_performance',
        'problem_hosts',
        'sitestatus',
        'tactical_overview',
        'tag_tree',
        'time',
    ]

    if not cmk_version.is_raw_edition():
        expected_refresh_snapins += [
            'cmc_stats',
        ]

    refresh_snapins = [
        s.type_name() for s in snapin_registry.values()
        if s.refresh_regularly()
    ]
    assert sorted(refresh_snapins) == sorted(expected_refresh_snapins)
Example #16
0
def test_registered_automation_commands():

    expected_automation_commands = [
        'activate-changes',
        'push-profiles',
        'check-analyze-config',
        'fetch-agent-output-get-file',
        'fetch-agent-output-get-status',
        'fetch-agent-output-start',
        'network-scan',
        'ping',
        'push-snapshot',
        'service-discovery-job',
        'checkmk-remote-automation-start',
        'checkmk-remote-automation-get-status',
    ]

    if not cmk_version.is_raw_edition():
        expected_automation_commands += [
            'execute-dcd-command',
        ]

    registered = sorted(watolib.automation_command_registry.keys())
    assert registered == sorted(expected_automation_commands)
Example #17
0
def test_registered_automations():
    needed_automations = [
        'active-check',
        'analyse-host',
        'analyse-service',
        'create-diagnostics-dump',
        'delete-hosts',
        'diag-host',
        'get-agent-output',
        'get-check-information',
        'get-configuration',
        'get-labels-of',
        'get-real-time-checks',
        'get-section-information',
        'get-service-configurations',
        'inventory',
        'notification-analyse',
        'notification-get-bulks',
        'notification-replay',
        'reload',
        'rename-hosts',
        'restart',
        'scan-parents',
        'set-autochecks',
        'try-inventory',
        'update-dns-cache',
        'update-host-labels',
    ]

    if not cmk_version.is_raw_edition():
        needed_automations += [
            'bake-agents',
        ]

    assert sorted(needed_automations) == sorted(
        cmk.base.automations.automations._automations.keys())
Example #18
0
def test_registered_automations():
    needed_automations = [
        "active-check",
        "analyse-host",
        "analyse-service",
        "create-diagnostics-dump",
        "delete-hosts",
        "delete-hosts-known-remote",
        "diag-host",
        "get-agent-output",
        "get-check-information",
        "get-configuration",
        "get-labels-of",
        "get-section-information",
        "get-service-configurations",
        "inventory",
        "notification-analyse",
        "notification-get-bulks",
        "notification-replay",
        "reload",
        "rename-hosts",
        "restart",
        "scan-parents",
        "set-autochecks",
        "try-inventory",
        "update-dns-cache",
        "update-host-labels",
    ]

    if not cmk_version.is_raw_edition():
        needed_automations += [
            "bake-agents",
        ]

    assert sorted(needed_automations) == sorted(
        cmk.base.automations.automations._automations.keys())
Example #19
0
def test_registered_modules():
    expected_modules = [
        'folder',
        'tags',
        'globalvars',
        'host_attrs',
        'wato.py?mode=rulesets&group=static',
        'check_plugins',
        'read_only',
        'predefined_conditions',
        'host_groups',
        'service_groups',
        'users',
        'user_attrs',
        'roles',
        'contact_groups',
        'notifications',
        'timeperiods',
        'mkeventd_rule_packs',
        'bi_packs',
        'sites',
        'backup',
        'passwords',
        'analyze_config',
        'auditlog',
        'icons',
        'background_jobs_overview',
        'ldap_config',
        'diagnostics',
        'download_agents',
        'version.py',
        'rule_search',
        'wato.py?mode=rulesets&group=activechecks',
        'wato.py?mode=rulesets&group=agent',
        'wato.py?mode=rulesets&group=checkparams',
        'wato.py?mode=rulesets&group=custom_checks',
        'wato.py?mode=rulesets&group=custom_integrations',
        'wato.py?mode=rulesets&group=datasource_programs',
        'wato.py?mode=rulesets&group=inventory',
        'wato.py?mode=rulesets&group=monconf',
        'wato.py?mode=rulesets&group=host_monconf',
        'wato.py?mode=rulesets&group=snmp',
        'wato.py?mode=rulesets&group=vm_cloud_container',
    ]

    if cmk_version.is_raw_edition():
        expected_modules += [
            'download_agents_linux',
            'download_agents_windows',
        ]

    if not cmk_version.is_raw_edition():
        expected_modules += [
            'agents',
            'alert_handlers',
            'mkps',
            'license_usage',
            'dcd_connections',
        ]

    if cmk_version.is_managed_edition():
        expected_modules += [
            "customer_management",
        ]

    module_names = [m.mode_or_url for m in main_menu.get_modules()]
    assert sorted(module_names) == sorted(expected_modules)
Example #20
0
def test_registered_configvars():
    expected_vars = [
        'actions',
        'adhoc_downtime',
        'agent_simulator',
        'apache_process_tuning',
        'archive_orphans',
        'auth_by_http_header',
        'builtin_icon_visibility',
        'bulk_discovery_default_settings',
        'check_mk_perfdata_with_times',
        'cluster_max_cachefile_age',
        'crash_report_target',
        'crash_report_url',
        'custom_service_attributes',
        'debug',
        'debug_livestatus_queries',
        'debug_rules',
        'default_user_profile',
        'default_bi_layout',
        'delay_precompile',
        'diskspace_cleanup',
        'enable_rulebased_notifications',
        'enable_sounds',
        'escape_plugin_output',
        'event_limit',
        'eventsocket_queue_len',
        'failed_notification_horizon',
        'hard_query_limit',
        'history_lifetime',
        'history_rotation',
        'hostname_translation',
        'housekeeping_interval',
        'http_proxies',
        'inventory_check_autotrigger',
        'inventory_check_do_scan',
        'inventory_check_interval',
        'inventory_check_severity',
        'lock_on_logon_failures',
        'log_level',
        'log_levels',
        'log_messages',
        'log_rulehits',
        'login_screen',
        'mkeventd_connect_timeout',
        'mkeventd_notify_contactgroup',
        'mkeventd_notify_facility',
        'mkeventd_notify_remotehost',
        'mkeventd_pprint_rules',
        'mkeventd_service_levels',
        'multisite_draw_ruleicon',
        'notification_backlog',
        'notification_bulk_interval',
        'notification_fallback_email',
        'notification_logging',
        'notification_plugin_timeout',
        'page_heading',
        'pagetitle_date_format',
        'password_policy',
        'piggyback_max_cachefile_age',
        'profile',
        'quicksearch_dropdown_limit',
        'quicksearch_search_order',
        'remote_status',
        'replication',
        'reschedule_timeout',
        'restart_locking',
        'retention_interval',
        'rrdcached_tuning',
        'rule_optimizer',
        'selection_livetime',
        'service_view_grouping',
        'show_livestatus_errors',
        'sidebar_notify_interval',
        'sidebar_show_version_in_sidebar',
        'sidebar_update_interval',
        'simulation_mode',
        'single_user_session',
        'site_autostart',
        'site_core',
        'site_livestatus_tcp',
        'site_mkeventd',
        'site_nsca',
        'snmp_credentials',
        'socket_queue_len',
        'soft_query_limit',
        'staleness_threshold',
        'start_url',
        'statistics_interval',
        'support_credentials',
        'table_row_limit',
        'tcp_connect_timeout',
        'topology_default_filter_group',
        'translate_snmptraps',
        'trusted_certificate_authorities',
        'ui_theme',
        'use_dns_cache',
        'snmp_backend_default',
        'use_inline_snmp',
        'use_new_descriptions_for',
        'user_downtime_timeranges',
        'user_icons_and_actions',
        'user_idle_timeout',
        'user_localizations',
        'view_action_defaults',
        'virtual_host_trees',
        'wato_activation_method',
        'wato_activate_changes_concurrency',
        'wato_activate_changes_comment_mode',
        'wato_hide_filenames',
        'wato_hide_folders_without_read_permissions',
        'wato_hide_help_in_lists',
        'wato_hide_hosttags',
        'wato_hide_varnames',
        'wato_icon_categories',
        'wato_legacy_eval',
        'wato_max_snapshots',
        'wato_pprint_config',
        'wato_upload_insecure_snapshots',
        'wato_use_git',
        'graph_timeranges',
    ]

    if not cmk_version.is_raw_edition():
        expected_vars += [
            'agent_deployment_enabled',
            'agent_deployment_host_selection',
            'agent_deployment_central',
            'agent_deployment_remote',
            'alert_handler_event_types',
            'alert_handler_timeout',
            'alert_logging',
            'bake_agents_on_restart',
            'cmc_authorization',
            'cmc_check_helpers',
            'cmc_check_timeout',
            'cmc_cmk_helpers',
            'cmc_config_multiprocessing',
            'cmc_debug_notifications',
            'cmc_dump_core',
            "cmc_enable_fetchers",
            "cmc_fetcher_helpers",
            "cmc_checker_helpers",
            'cmc_flap_settings',
            'cmc_graphite',
            'cmc_import_nagios_state',
            'cmc_initial_scheduling',
            'cmc_livestatus_lines_per_file',
            'cmc_livestatus_logcache_size',
            'cmc_livestatus_threads',
            'cmc_log_cmk_helpers',
            'cmc_log_levels',
            'cmc_log_limit',
            'cmc_log_microtime',
            'cmc_log_rotation_method',
            'cmc_log_rrdcreation',
            'cmc_pnp_update_delay',
            'cmc_pnp_update_on_restart',
            'cmc_real_time_checks',
            'cmc_real_time_helpers',
            'cmc_smartping_tuning',
            'cmc_state_retention_interval',
            'cmc_statehist_cache',
            'cmc_timeperiod_horizon',
            'config',
            'dcd_log_levels',
            'dcd_web_api_connection',
            'liveproxyd_default_connection_params',
            'liveproxyd_log_levels',
            'mknotifyd_insecure_message_format',
            'notification_spooling',
            'reporting_date_format',
            'reporting_email_options',
            'reporting_filename',
            'reporting_font_family',
            'reporting_font_size',
            'reporting_graph_layout',
            'reporting_lineheight',
            'reporting_margins',
            'reporting_mirror_margins',
            'reporting_pagesize',
            'reporting_rangespec',
            'reporting_table_layout',
            'reporting_time_format',
            'reporting_use',
            'reporting_view_limit',
            'site_liveproxyd',
            'ntop_connection',
        ]

    registered = sorted(config_variable_registry.keys())
    assert registered == sorted(expected_vars)
Example #21
0
    def _show_login_page(self) -> None:
        html.set_render_headfoot(False)
        html.add_body_css_class("login")
        html.header(config.get_page_heading(), Breadcrumb(), javascripts=[])

        default_origtarget = ("index.py" if html.myfile in ["login", "logout"]
                              else makeuri(global_request, []))
        origtarget = html.get_url_input("_origtarget", default_origtarget)

        # Never allow the login page to be opened in the iframe. Redirect top page to login page.
        # This will result in a full screen login page.
        html.javascript('''if(top != self) {
    window.top.location.href = location;
}''')

        # When someone calls the login page directly and is already authed redirect to main page
        if html.myfile == 'login' and _check_auth(html.request):
            raise HTTPRedirect(origtarget)

        html.open_div(id_="login")

        html.open_div(id_="login_window")

        html.div("" if "hide_version" in config.login_screen else
                 cmk_version.__version__,
                 id_="version")

        html.begin_form("login",
                        method='POST',
                        add_transid=False,
                        action='login.py')
        html.hidden_field('_login', '1')
        html.hidden_field('_origtarget', origtarget)
        html.label("%s:" % _('Username'),
                   id_="label_user",
                   class_=["legend"],
                   for_="_username")
        html.br()
        html.text_input("_username", id_="input_user")
        html.label("%s:" % _('Password'),
                   id_="label_pass",
                   class_=["legend"],
                   for_="_password")
        html.br()
        html.password_input("_password", id_="input_pass", size=None)

        if html.has_user_errors():
            html.open_div(id_="login_error")
            html.show_user_errors()
            html.close_div()

        html.open_div(id_="button_text")
        html.button("_login", _('Login'))
        html.close_div()
        html.close_div()

        html.open_div(id_="foot")

        if config.login_screen.get("login_message"):
            html.open_div(id_="login_message")
            html.show_message(config.login_screen["login_message"])
            html.close_div()

        footer: List[Union[HTML, str]] = []
        for title, url, target in config.login_screen.get("footer_links", []):
            footer.append(html.render_a(title, href=url, target=target))

        if "hide_version" not in config.login_screen:
            footer.append("Version: %s" % cmk_version.__version__)

        footer.append("© %s" % html.render_a(
            "tribe29 GmbH", href="https://checkmk.com", target="_blank"))

        html.write(HTML(" - ").join(footer))

        if cmk_version.is_raw_edition():
            html.br()
            html.br()
            html.write(
                _('You can use, modify and distribute Check_MK under the terms of the <a href="%s" target="_blank">'
                  'GNU GPL Version 2</a>.') % "https://checkmk.com/gpl.html")

        html.close_div()

        html.set_focus('_username')
        html.hidden_fields()
        html.end_form()
        html.close_div()

        html.footer()
Example #22
0
def test_registered_pages():
    expected_pages = [
        'add_bookmark',
        'ajax_cascading_render_painer_parameters',
        'ajax_activation_state',
        'ajax_add_visual',
        'ajax_autocomplete_labels',
        'ajax_backup_job_state',
        'ajax_dashlet_pos',
        'ajax_delete_user_notification',
        'ajax_dict_host_tag_condition_get_choice',
        'ajax_inv_render_tree',
        'ajax_nagvis_maps_snapin',
        'ajax_popup_action_menu',
        'ajax_popup_add_visual',
        'ajax_popup_icon_selector',
        'ajax_popup_move_to_folder',
        'ajax_reschedule',
        'ajax_search',
        'ajax_service_discovery',
        'ajax_set_foldertree',
        'ajax_set_rowselection',
        'ajax_set_viewoption',
        'ajax_start_activation',
        'ajax_switch_help',
        'ajax_userdb_sync',
        'ajax_visual_filter_list_get_choice',
        'ajax_vs_autocomplete',
        'ajax_fetch_aggregation_data',
        'ajax_save_bi_template_layout',
        'ajax_save_bi_aggregation_layout',
        'ajax_load_bi_template_layout',
        'ajax_load_bi_aggregation_layout',
        'ajax_delete_bi_template_layout',
        'ajax_delete_bi_aggregation_layout',
        'ajax_fetch_topology',
        'ajax_get_all_bi_template_layouts',
        'automation_login',
        'bi',
        'bi_map',
        'bi_debug',
        'bi_render_tree',
        'bi_save_treestate',
        'bi_set_assumption',
        'bookmark_lists',
        'clear_failed_notifications',
        'count_context_button',
        'create_dashboard',
        'create_view',
        'create_view_dashlet',
        'create_view_dashlet_infos',
        'create_link_view_dashlet',
        'create_view_infos',
        'custom_snapins',
        'dashboard',
        'dashboard_dashlet',
        'delete_dashlet',
        'download_agent_output',
        'download_crash_report',
        'download_diagnostics_dump',
        'edit_bookmark_list',
        'edit_custom_snapin',
        'edit_dashboard',
        'edit_dashboards',
        'edit_dashlet',
        'clone_dashlet',
        'edit_view',
        'edit_views',
        'export_views',
        'fetch_agent_output',
        'graph_dashlet',
        'crash',
        'host_inv_api',
        'host_service_graph_popup',
        'index',
        'login',
        'logout',
        'logwatch',
        'mobile',
        'mobile_view',
        'noauth:automation',
        'noauth:run_cron',
        'notify',
        'prediction_graph',
        'parent_child_topology',
        'search_open',
        'side',
        'sidebar_add_snapin',
        'sidebar_ajax_add_snapin',
        'sidebar_ajax_set_snapin_site',
        'sidebar_ajax_speedometer',
        'sidebar_ajax_tag_tree',
        'sidebar_ajax_tag_tree_enter',
        'sidebar_fold',
        'sidebar_get_messages',
        'sidebar_message_read',
        'sidebar_move_snapin',
        'sidebar_openclose',
        'sidebar_snapin',
        'switch_master_state',
        'switch_site',
        'tree_openclose',
        'user_change_pw',
        'user_profile',
        'version',
        'view',
        'wato',
        'wato_ajax_diag_host',
        'wato_ajax_execute_check',
        'wato_ajax_fetch_site_status',
        'wato_ajax_profile_repl',
        'webapi',
        'werk',
        'ajax_graph',
        'ajax_graph_hover',
        'ajax_render_graph_content',
    ]

    if not cmk_version.is_raw_edition():
        expected_pages += [
            'ajax_metric_choice',
            'ajax_pagetype_add_element',
            'ajax_popup_add_metric_to_graph',
            'ajax_scalar_choice',
            'combined_graphs',
            'create_report',
            'custom_graph',
            'custom_graph_design',
            'custom_graphs',
            'download_agent',
            'download_mkp',
            'download_stored_report',
            'edit_custom_graph',
            'edit_forecast_graph',
            'edit_graph_collection',
            'edit_graph_tuning',
            'edit_report',
            'edit_report_content',
            'edit_report_element',
            'edit_report_fixel',
            'edit_reports',
            'edit_sla_configuration',
            'forecast_editor',
            'forecast_graph',
            'forecast_graphs',
            'graph_collection',
            'graph_collections',
            'graph_export',
            'graph_image',
            'graph_tunings',
            'noauth:ajax_graph_images',
            'noauth:deploy_agent',
            'register_agent',
            'report',
            'report_download_preview',
            'report_instant',
            'report_instant_graph_collection',
            'report_scheduler',
            'report_scheduler_edit',
            'report_scheduler_preview',
            'report_store',
            'report_thumbnail',
            'sla_configurations',
            'sla_details',
        ]

    assert sorted(cmk.gui.pages.page_registry.keys()) == sorted(expected_pages)
Example #23
0
                },
            },
            2,
            id="invalid configuration",
        ),
        pytest.param(
            {
                "logwatch_rules": {
                    "reclassify_patterns": [
                        ("C", "\\\\x\\\\y\\\\z", "some comment"),
                    ]
                },
                "checkgroup_parameters:ntp_time": {
                    "ntp_levels": (10, 200.0, 500.0),
                },
                **({} if is_raw_edition() else {
                       "extra_service_conf:_sla_config": "i am skipped"
                   }),
            },
            0,
            id="valid configuration",
        ),
    ],
)
@pytest.mark.usefixtures("request_context")
def test_validate_rule_values(
    mocker: MockerFixture,
    uc: update_config.UpdateConfig,
    rulesets: Mapping[RulesetName, RuleValue],
    n_expected_warnings: int,
) -> None:
Example #24
0
# 10 -> full dump of all variables and command
notification_logging = 15
notification_backlog = 10  # keep the last 10 notification contexts for reference

# Settings for new rule based notifications
enable_rulebased_notifications = False
notification_fallback_email = ""
notification_rules = []  # type: _List[_Dict[str, _Any]]
# Check every 10 seconds for ripe bulks
notification_bulk_interval = 10
notification_plugin_timeout = 60

# Notification Spooling.

# Possible values for notification_spooling
# "off"    - Direct local delivery without spooling
# "local"  - Asynchronous local delivery by notification spooler
# "remote" - Forward to remote site by notification spooler
# "both"   - Asynchronous local delivery plus remote forwarding
# False    - legacy: sync delivery  (and notification_spool_to)
# True     - legacy: async delivery (and notification_spool_to)
if cmk_version.is_raw_edition():
    notification_spooling = "off"  # type: _Union[bool, str]
else:
    notification_spooling = "local"

# Legacy setting. The spool target is now specified in the
# configuration of the spooler. notification_spool_to has
# the tuple format (remote_host, tcp_port, also_local)
notification_spool_to = None
Example #25
0
def show_annotations(annotations, av_rawdata, what, avoptions, omit_service):
    annos_to_render = get_relevant_annotations(annotations, av_rawdata, what,
                                               avoptions)
    render_date = get_annotation_date_render_function(annos_to_render,
                                                      avoptions)

    with table_element(title=_("Annotations"), omit_if_empty=True) as table:
        for (site_id, host, service), annotation in annos_to_render:
            table.row()
            table.cell("", css="buttons")
            anno_vars = [
                ("anno_site", site_id),
                ("anno_host", host),
                ("anno_service", service or ""),
                ("anno_from", int(annotation["from"])),
                ("anno_until", int(annotation["until"])),
            ]
            edit_url = html.makeuri(anno_vars)
            html.icon_button(edit_url, _("Edit this annotation"), "edit")
            del_anno = [("_delete_annotation", "1")]  # type: HTTPVariables
            delete_url = html.makeactionuri(del_anno + anno_vars)
            html.icon_button(delete_url, _("Delete this annotation"), "delete")

            if not omit_service:
                if "omit_host" not in avoptions["labelling"]:
                    host_url = "view.py?" + html.urlencode_vars(
                        [("view_name", "hoststatus"), ("site", site_id),
                         ("host", host)])
                    table.cell(_("Host"), html.render_a(host, host_url))

                if what == "service":
                    if service:
                        service_url = "view.py?" + html.urlencode_vars(
                            [("view_name", "service"), ("site", site_id),
                             ("host", host), ("service", service)])
                        # TODO: honor use_display_name. But we have no display names here...
                        service_name = service
                        table.cell(_("Service"),
                                   html.render_a(service_name, service_url))
                    else:
                        table.cell(_("Service"),
                                   "")  # Host annotation in service table

            table.cell(_("From"),
                       render_date(annotation["from"]),
                       css="nobr narrow")
            table.cell(_("Until"),
                       render_date(annotation["until"]),
                       css="nobr narrow")
            table.cell("", css="buttons")
            if annotation.get("downtime") is True:
                html.icon(
                    _("This period has been reclassified as a scheduled downtime"
                      ), "downtime")
            elif annotation.get("downtime") is False:
                html.icon(
                    _("This period has been reclassified as a not being a scheduled downtime"
                      ), "nodowntime")
            table.cell(_("Annotation"), html.render_text(annotation["text"]))
            table.cell(_("Author"), annotation["author"])
            table.cell(_("Entry"),
                       render_date(annotation["date"]),
                       css="nobr narrow")
            if not cmk_version.is_raw_edition():
                table.cell(
                    _("Hide in report"),
                    _("Yes")
                    if annotation.get("hide_from_report") else _("No"))
Example #26
0
    def _get_optional_information_elements(
            self) -> List[Tuple[str, ValueSpec]]:
        elements: List[Tuple[str, ValueSpec]] = [
            (
                OPT_LOCAL_FILES,
                FixedValue(
                    True,
                    totext="",
                    title=_("Local Files"),
                    help=
                    _("List of installed, unpacked, optional files below OMD_ROOT/local. "
                      "This also includes information about installed MKPs."),
                ),
            ),
            (
                OPT_OMD_CONFIG,
                FixedValue(
                    True,
                    totext="",
                    title=_("OMD Config"),
                    help=_("Apache mode and TCP address and port, Core, "
                           "Liveproxy daemon and livestatus TCP mode, "
                           "Event daemon config, Multiste authorisation, "
                           "NSCA mode, TMP filesystem mode"),
                ),
            ),
            (
                OPT_CHECKMK_OVERVIEW,
                FixedValue(
                    True,
                    totext="",
                    title=_("Checkmk Overview"),
                    help=
                    _("Checkmk Agent, Number, version and edition of sites, Cluster host; "
                      "Number of hosts, services, CMK Helper, Live Helper, "
                      "Helper usage; State of daemons: Apache, Core, Crontag, "
                      "DCD, Liveproxyd, MKEventd, MKNotifyd, RRDCached "
                      "(Agent plugin mk_inventory needs to be installed)"),
                ),
            ),
            (
                OPT_CHECKMK_CONFIG_FILES,
                self._get_component_specific_checkmk_files_choices(
                    _("Checkmk Configuration files"),
                    [(f, get_checkmk_file_info(f))
                     for f in self._checkmk_config_files_map],
                ),
            ),
        ]

        if not cmk_version.is_raw_edition():
            elements.append((
                OPT_PERFORMANCE_GRAPHS,
                FixedValue(
                    True,
                    totext="",
                    title=_("Performance Graphs of Checkmk Server"),
                    help=
                    _("CPU load and utilization, Number of threads, Kernel Performance, "
                      "OMD, Filesystem, Apache Status, TCP Connections of the time ranges "
                      "25 hours and 35 days"),
                ),
            ))
        return elements
Example #27
0
def test_generate_pre_17_site_snapshot(edition_short, monkeypatch, tmp_path,
                                       with_user_login, remote_site):
    snapshot_data_collector_class = ("CMESnapshotDataCollector"
                                     if edition_short == "cme" else
                                     "CRESnapshotDataCollector")

    is_pre_17_site = True
    monkeypatch.setattr(cmk_version, "edition_short", lambda: edition_short)
    monkeypatch.setattr(utils, "is_pre_17_remote_site",
                        lambda s: is_pre_17_site)

    activation_manager = _get_activation_manager(monkeypatch, remote_site)
    snapshot_settings = _create_sync_snapshot(
        activation_manager,
        snapshot_data_collector_class,
        monkeypatch,
        tmp_path,
        is_pre_17_site,
        remote_site,
    )

    # And now check the resulting snapshot contents
    unpack_dir = tmp_path / "snapshot_unpack"
    if unpack_dir.exists():
        shutil.rmtree(str(unpack_dir))

    with tarfile.open(snapshot_settings.snapshot_path, "r") as t:
        t.extractall(str(unpack_dir))

    expected_subtars = [
        "auth.secret.tar",
        "auth.serials.tar",
        "check_mk.tar",
        "diskspace.tar",
        "htpasswd.tar",
        "mkeventd_mkp.tar",
        "mkeventd.tar",
        "multisite.tar",
        "sitespecific.tar",
        "usersettings.tar",
    ]

    if is_enterprise_repo():
        expected_subtars += [
            "dcd.tar",
            "mknotify.tar",
        ]

    if config.sites[remote_site].get("replicate_mkps", False):
        expected_subtars += [
            "local.tar",
            "mkps.tar",
        ]

    if not cmk_version.is_raw_edition():
        expected_subtars.append("liveproxyd.tar")

    if cmk_version.is_managed_edition():
        expected_subtars += [
            "customer_check_mk.tar",
            "customer_gui_design.tar",
            "customer_multisite.tar",
            "gui_logo.tar",
            "gui_logo_dark.tar",
            "gui_logo_facelift.tar",
        ]

    assert sorted(f.name
                  for f in unpack_dir.iterdir()) == sorted(expected_subtars)

    expected_files: Dict[str, List[str]] = {
        "mkeventd_mkp.tar": [],
        "multisite.tar": ["global.mk", "users.mk"],
        "usersettings.tar": [with_user_login],
        "mkeventd.tar": [],
        "check_mk.tar": ["hosts.mk", "contacts.mk"],
        "htpasswd.tar": ["htpasswd"],
        "liveproxyd.tar": [],
        "sitespecific.tar": ["sitespecific.mk"],
        "auth.secret.tar": [],
        "dcd.tar": [],
        "auth.serials.tar": ["auth.serials"],
        "mknotify.tar": [],
        "diskspace.tar": [],
    }

    if config.sites[remote_site].get("replicate_mkps", False):
        expected_files.update({"local.tar": [], "mkps.tar": []})

    if cmk_version.is_managed_edition():
        expected_files.update({
            "customer_check_mk.tar": ["customer.mk"],
            "customer_gui_design.tar": [],
            "customer_multisite.tar": ["customer.mk"],
            "gui_logo.tar": [],
            "gui_logo_dark.tar": [],
            "gui_logo_facelift.tar": [],
            # TODO: Shouldn't we clean up these subtle differences?
            "mkeventd.tar": ["rules.mk"],
            "check_mk.tar": ["groups.mk", "contacts.mk"],
            "multisite.tar": [
                "bi.mk",
                "customers.mk",
                "global.mk",
                "groups.mk",
                "user_connections.mk",
                "users.mk",
            ],
        })

    if not cmk_version.is_raw_edition():
        expected_files["liveproxyd.tar"] = []

    # And now check the subtar contents
    for subtar in unpack_dir.iterdir():
        subtar_unpack_dir = unpack_dir / subtar.stem
        subtar_unpack_dir.mkdir(parents=True, exist_ok=True)

        with tarfile.open(str(subtar), "r") as s:
            s.extractall(str(subtar_unpack_dir))

        files = sorted(
            str(f.relative_to(subtar_unpack_dir))
            for f in subtar_unpack_dir.iterdir())

        assert sorted(expected_files[subtar.name]) == files, (
            "Subtar %s has wrong files" % subtar.name)