def test_call_exception_handling(mocker): hooks.register_builtin("bli", lambda: 1.0 / 0.0) hook3_mock = mocker.Mock() hooks.register("bli", hook3_mock) with pytest.raises(ZeroDivisionError, match="float division by zero"): hooks.call("bli") hook3_mock.assert_not_called()
def call_hook_activate_changes(): if hooks.registered("activate-changes"): # TODO: Cleanup this local import import cmk.gui.watolib.hosts_and_folders # pylint: disable=redefined-outer-name hooks.call("activate-changes", cmk.gui.watolib.hosts_and_folders.collect_all_hosts())
def execute(self, request): # type: (PushSnapshotRequest) -> bool with store.lock_checkmk_configuration(): multitar.extract_from_buffer(request.tar_content, cmk.gui.watolib.activate_changes.get_replication_paths()) try: self._save_site_globals_on_slave_site(request.tar_content) # pending changes are lost cmk.gui.watolib.activate_changes.confirm_all_local_changes() hooks.call("snapshot-pushed") # Create rule making this site only monitor our hosts create_distributed_wato_file(request.site_id, is_slave=True) except Exception: raise MKGeneralException( _("Failed to deploy configuration: \"%s\". " "Please note that the site configuration has been synchronized " "partially.") % traceback.format_exc()) cmk.gui.watolib.changes.log_audit( None, "replication", _("Synchronized with master (my site id is %s.)") % request.site_id) return True
def test_request_memoize_request_integration(logged_in_wsgi_app, mocker): mock = mocker.MagicMock() @hooks.request_memoize() def memoized(): return mock() @page_registry.register_page("my_page") class PageClass(Page): # pylint: disable=unused-variable def page(self): mock.return_value = 1 assert memoized() == 1 # Test that it gives the memoized value instead of the new mock value mock.return_value = 2 assert memoized() == 1 # Try a first request. Memoization within this request is tested in page() above. logged_in_wsgi_app.get("/NO_SITE/check_mk/my_page.py", status=200) # After the request has ended we get the new value mock.return_value = 2 assert memoized() == 2 # But there is no reset triggered outside of the request. We do it manually here. hooks.call("request-end") # And now try a second request mock.return_value = 1 logged_in_wsgi_app.get("/NO_SITE/check_mk/my_page.py", status=200) page_registry.unregister("my_page")
def activate(self): if getattr(config, "mkeventd_enabled", False): mkeventd.execute_command("RELOAD", site=config.omd_site()) log_audit(None, "mkeventd-activate", _("Activated changes of event console configuration")) if hooks.registered('mkeventd-activate-changes'): hooks.call("mkeventd-activate-changes")
def activate(self, settings: Optional[SerializedSettings] = None) -> ConfigurationWarnings: if getattr(config, "mkeventd_enabled", False): mkeventd.execute_command("RELOAD", site=omd_site()) log_audit("mkeventd-activate", _("Activated changes of event console configuration")) if hooks.registered("mkeventd-activate-changes"): hooks.call("mkeventd-activate-changes") return []
def general_userdb_job() -> None: """This function registers general stuff, which is independet of the single connectors to each page load. It is exectued AFTER all other connections jobs.""" hooks.call("userdb-job") # Create initial auth.serials file, same issue as auth.php above serials_file = '%s/auth.serials' % os.path.dirname(cmk.utils.paths.htpasswd_file) if not os.path.exists(serials_file) or os.path.getsize(serials_file) == 0: rewrite_users()
def test_request_memoize(): @hooks.request_memoize() def blah(a=[]): # pylint: disable=dangerous-default-value a.append(1) return a assert blah() == [1] assert blah() == [1] hooks.call("request-end") assert blah() == [1, 1]
def _pre_activate_changes(self): # TODO: Cleanup this local import import cmk.gui.watolib.hosts_and_folders # pylint: disable=redefined-outer-name try: if hooks.registered('pre-distribute-changes'): hooks.call("pre-distribute-changes", cmk.gui.watolib.hosts_and_folders.collect_all_hosts()) except Exception as e: logger.exception() if config.debug: raise raise MKUserError(None, _("Can not start activation: %s") % e)
def test_call(mocker): hook1_mock = mocker.Mock() hook2_mock = mocker.Mock() hooks.register("bla", hook1_mock) hooks.register("blub", hook2_mock) hooks.call("bla") hook1_mock.assert_called_once() hook2_mock.assert_not_called() hooks.call("blub") hook1_mock.assert_called_once() hook2_mock.assert_called_once()
def _save_roles(self): # Reflect the data in the roles dict kept in the config module Needed # for instant changes in current page while saving modified roles. # Otherwise the hooks would work with old data when using helper # functions from the config module config.roles.update(self._roles) store.mkdir(watolib.multisite_dir()) store.save_to_mk_file(watolib.multisite_dir() + "roles.mk", "roles", self._roles, pprint_value=config.wato_pprint_config) hooks.call("roles-saved", self._roles)
def _set_group(all_groups, group_type, name, extra_info): # Check if this alias is used elsewhere alias = extra_info.get("alias") if not alias: raise MKUserError("alias", "Alias is missing") unique, info = is_alias_used(group_type, name, alias) if not unique: raise MKUserError("alias", info) all_groups.setdefault(group_type, {}) all_groups[group_type].setdefault(name, {}) all_groups[group_type][name] = extra_info save_group_information(all_groups) if group_type == "contact": hooks.call('contactgroups-saved', all_groups)
def save_sites(cls, sites, activate=True): # TODO: Clean this up from cmk.gui.watolib.hosts_and_folders import Folder store.mkdir(multisite_dir()) store.save_to_mk_file(cls._sites_mk(), "sites", sites) # Do not activate when just the site's global settings have # been edited if activate: config.load_config() # make new site configuration active _update_distributed_wato_file(sites) Folder.invalidate_caches() cmk.gui.watolib.sidebar_reload.need_sidebar_reload() _create_nagvis_backends(sites) # Call the sites saved hook hooks.call("sites-saved", sites)
def test_request_memoize_unregister(): # Make sure request-start hooks are still called, after plugin hooks are # unregistered. In previous versions unregister_plugin_hooks also # unregistered hooks used by memoize. @hooks.request_memoize() def blah(a: List[int] = []) -> List[int]: # pylint: disable=dangerous-default-value a.append(1) return a assert blah() == [1] assert blah() == [1] hooks.call("request-end") assert blah() == [1, 1] hooks.unregister_plugin_hooks() hooks.call("request-end") assert blah() == [1, 1, 1] assert blah() == [1, 1, 1]
def save_users(profiles: Users) -> None: write_contacts_and_users_file(profiles) # Execute user connector save hooks hook_save(profiles) updated_profiles = _add_custom_macro_attributes(profiles) _save_auth_serials(updated_profiles) _save_user_profiles(updated_profiles) _cleanup_old_user_profiles(updated_profiles) # Release the lock to make other threads access possible again asap # This lock is set by load_users() only in the case something is expected # to be written (like during user syncs, wato, ...) release_users_lock() # populate the users cache g.users = updated_profiles # Call the users_saved hook hooks.call("users-saved", updated_profiles)
def __call__(self, environ, start_response): hooks.call("request-start") response = self.app(environ, start_response) hooks.call("request-end") return response
def _call_hook(name: str) -> None: # TODO: cyclical import with hooks -> globals from cmk.gui import hooks hooks.call("request-context-exit")
def _call_hook(name: str) -> None: from cmk.gui import hooks hooks.call(name)