Exemple #1
0
def save_timeperiods(timeperiods: TimeperiodSpecs) -> None:
    store.mkdir(wato_root_dir())
    store.save_to_mk_file(wato_root_dir() + "timeperiods.mk",
                          "timeperiods",
                          _filter_builtin_timeperiods(timeperiods),
                          pprint_value=config.wato_pprint_config)
    g.timeperiod_information = timeperiods
Exemple #2
0
def log_entry(linkinfo, action, message, user_id=None):
    # Using attrencode here is against our regular rule to do the escaping
    # at the last possible time: When rendering. But this here is the last
    # place where we can distinguish between HTML() encapsulated (already)
    # escaped / allowed HTML and strings to be escaped.
    message = cmk.utils.make_utf8(html.attrencode(message)).strip()

    # TODO: Create a more generic referencing
    # linkinfo identifies the object operated on. It can be a Host or a Folder
    # or a text.
    # linkinfo is either a Folder, or a Host or a hostname or None
    if hasattr(linkinfo, "linkinfo"):
        link = linkinfo.linkinfo()
    elif linkinfo is None:
        link = "-"
    else:
        link = linkinfo

    if user_id is None and config.user.id is not None:
        user_id = config.user.id
    elif user_id == '':
        user_id = '-'

    if user_id:
        user_id = user_id.encode("utf-8")

    store.mkdir(os.path.dirname(audit_log_path))
    with open(audit_log_path, "ab") as f:
        os.chmod(f.name, 0660)
        f.write("%d %s %s %s %s\n" % (int(time.time()), link, user_id, action,
                                      message.replace("\n", "\\n")))
Exemple #3
0
def _confdir_for_user_id(user_id: Optional[UserId]) -> Optional[str]:
    if user_id is None:
        return None

    confdir = config_dir + "/" + ensure_str(user_id)
    store.mkdir(confdir)
    return confdir
Exemple #4
0
def save_notification_rules(rules):
    store.mkdir(wato_root_dir())
    store.save_to_mk_file(
        wato_root_dir() + "notifications.mk",
        "notification_rules",
        rules,
        pprint_value=config.wato_pprint_config)
Exemple #5
0
def _confdir_for_user_id(user_id: Optional[UserId]) -> Optional[str]:
    if user_id is None:
        return None

    confdir = cmk.utils.paths.profile_dir / user_id
    store.mkdir(confdir)
    return str(confdir)
Exemple #6
0
def save_notification_rules(rules):
    # type: (List[Dict]) -> None
    store.mkdir(wato_root_dir())
    store.save_to_mk_file(wato_root_dir() + "notifications.mk",
                          "notification_rules",
                          rules,
                          pprint_value=config.wato_pprint_config)
Exemple #7
0
    def _save_folder(self, folder):
        store.mkdir(folder.get_root_dir())

        has_content = False
        content = ""
        for varname, ruleset in sorted(self._rulesets.items(), key=lambda x: x[0]):
            if varname not in rulespec_registry:
                continue  # don't save unknown rulesets

            if ruleset.is_empty_in_folder(folder):
                continue  # don't save empty rule sets

            has_content = True
            content += ruleset.to_config(folder)

        rules_file_path = folder.rules_file_path()
        # Remove rules files if it has no content. This prevents needless reads
        if not has_content:
            if os.path.exists(rules_file_path):
                os.unlink(rules_file_path)  # Do not keep empty rules.mk files
            return

        # Adding this instead of the full path makes it easy to move config
        # files around. The real FOLDER_PATH will be added dynamically while
        # loading the file in cmk.base.config
        content = content.replace("'%s'" % _FOLDER_PATH_MACRO, "'/%s/' % FOLDER_PATH")

        store.save_mk_file(rules_file_path, content, add_header=not config.wato_use_git)
Exemple #8
0
def save_user_file(name: str, data: Any, user_id: Optional[UserId]) -> None:
    if user_id is None:
        raise TypeError("The profiles of LoggedInSuperUser and LoggedInNobody cannot be saved")

    path = config_dir + "/" + ensure_str(user_id) + "/" + name + ".mk"
    store.mkdir(os.path.dirname(path))
    store.save_object_to_file(path, data)
Exemple #9
0
def _save_user_profiles(updated_profiles: Users) -> None:
    non_contact_keys = _non_contact_keys()
    multisite_keys = _multisite_keys()

    for user_id, user in updated_profiles.items():
        user_dir = cmk.utils.paths.var_dir + "/web/" + ensure_str(user_id)
        store.mkdir(user_dir)

        # authentication secret for local processes
        auth_file = user_dir + "/automation.secret"
        if "automation_secret" in user:
            store.save_file(auth_file, "%s\n" % user["automation_secret"])
        elif os.path.exists(auth_file):
            os.unlink(auth_file)

        # Write out user attributes which are written to dedicated files in the user
        # profile directory. The primary reason to have separate files, is to reduce
        # the amount of data to be loaded during regular page processing
        save_custom_attr(user_id, 'serial', str(user.get('serial', 0)))
        save_custom_attr(user_id, 'num_failed_logins', str(user.get('num_failed_logins', 0)))
        save_custom_attr(user_id, 'enforce_pw_change', str(int(user.get('enforce_pw_change',
                                                                        False))))
        save_custom_attr(user_id, 'last_pw_change', str(user.get('last_pw_change',
                                                                 int(time.time()))))

        if "idle_timeout" in user:
            save_custom_attr(user_id, "idle_timeout", user["idle_timeout"])
        else:
            remove_custom_attr(user_id, "idle_timeout")

        _save_cached_profile(user_id, user, multisite_keys, non_contact_keys)
Exemple #10
0
def create_snapshot(comment):
    logger.debug("Start creating backup snapshot")
    start = time.time()
    store.mkdir(snapshot_dir)

    snapshot_name = "wato-snapshot-%s.tar" % time.strftime(
        "%Y-%m-%d-%H-%M-%S", time.localtime(time.time())
    )

    data: Dict[str, Any] = {}
    data["comment"] = _("Activated changes by %s.") % user.id

    if comment:
        data["comment"] += _("Comment: %s") % comment

    # with SuperUserContext the user.id is None; later this value will be encoded for tar
    data["created_by"] = "" if user.id is None else user.id
    data["type"] = "automatic"
    data["snapshot_name"] = snapshot_name

    _do_create_snapshot(data)
    _do_snapshot_maintenance()

    log_audit("snapshot-created", _("Created snapshot %s") % snapshot_name)
    logger.debug("Backup snapshot creation took %.4f", time.time() - start)
Exemple #11
0
def save_timeperiods(timeperiods):
    # type: (TimeperiodSpecs) -> None
    store.mkdir(wato_root_dir())
    store.save_to_mk_file(wato_root_dir() + "timeperiods.mk",
                          "timeperiods",
                          _filter_builtin_timeperiods(timeperiods),
                          pprint_value=config.wato_pprint_config)
Exemple #12
0
def _confdir_for_user_id(user_id):
    # type: (Optional[UserId]) -> Optional[str]
    if user_id is None:
        return None

    confdir = config_dir + "/" + user_id.encode("utf-8")
    store.mkdir(confdir)
    return confdir
Exemple #13
0
def save_notification_rules(rules: list[EventRule]) -> None:
    store.mkdir(wato_root_dir())
    store.save_to_mk_file(
        wato_root_dir() + "notifications.mk",
        "notification_rules",
        rules,
        pprint_value=active_config.wato_pprint_config,
    )
Exemple #14
0
def save_user_file(name, data, user_id):
    # type: (str, Any, Optional[UserId]) -> None
    if user_id is None:
        raise TypeError("The profiles of LoggedInSuperUser and LoggedInNobody cannot be saved")

    path = config_dir + "/" + user_id.encode("utf-8") + "/" + name + ".mk"
    store.mkdir(os.path.dirname(path))
    store.save_object_to_file(path, data)
Exemple #15
0
def save_timeperiods(timeperiods: TimeperiodSpecs) -> None:
    store.mkdir(wato_root_dir())
    store.save_to_mk_file(
        wato_root_dir() + "timeperiods.mk",
        "timeperiods",
        _filter_builtin_timeperiods(timeperiods),
        pprint_value=active_config.wato_pprint_config,
    )
    load_timeperiods.cache_clear()
def save_custom_attrs_to_mk_file(attrs):
    output = watolib.wato_fileheader()
    for what in ["user", "host"]:
        if what in attrs and len(attrs[what]) > 0:
            output += "if type(wato_%s_attrs) != list:\n    wato_%s_attrs = []\n" % (what, what)
            output += "wato_%s_attrs += %s\n\n" % (what, pprint.pformat(attrs[what]))

    store.mkdir(watolib.multisite_dir())
    store.save_text_to_file(watolib.multisite_dir() + "custom_attrs.mk", output)
Exemple #17
0
def save_connection_config(connections, base_dir=None):
    # type: (List[UserConnectionSpec], str) -> None
    if not base_dir:
        base_dir = _multisite_dir()
    store.mkdir(base_dir)
    store.save_to_mk_file(os.path.join(base_dir, "user_connections.mk"),
                          "user_connections", connections)

    for connector_class in user_connector_registry.values():
        connector_class.config_changed()
Exemple #18
0
def _update_replication_status(site_id, vars_):
    """Updates one or more dict elements of a site in an atomic way."""
    store.mkdir(var_dir)

    repl_status = _load_site_replication_status(site_id, lock=True)
    try:
        repl_status.setdefault("times", {})
        repl_status.update(vars_)
    finally:
        _save_site_replication_status(site_id, repl_status)
Exemple #19
0
    def _save_site_globals_on_slave_site(self, tarcontent):
        tmp_dir = cmk.utils.paths.tmp_dir + "/sitespecific-%s" % id(html)
        try:
            if not os.path.exists(tmp_dir):
                store.mkdir(tmp_dir)

            multitar.extract_from_buffer(tarcontent, [("dir", "sitespecific", tmp_dir)])

            site_globals = store.load_object_from_file(tmp_dir + "/sitespecific.mk", default={})
            save_site_global_settings(site_globals)
        finally:
            shutil.rmtree(tmp_dir)
Exemple #20
0
def save_connection_config(connections: List[UserConnectionSpec],
                           base_dir: Optional[str] = None) -> None:
    if not base_dir:
        base_dir = _multisite_dir()
    store.mkdir(base_dir)
    store.save_to_mk_file(os.path.join(base_dir, "user_connections.mk"),
                          "user_connections", connections)

    for connector_class in user_connector_registry.values():
        connector_class.config_changed()

    clear_user_connection_cache()
Exemple #21
0
def _create_auth_file(callee, users=None):
    if users is None:
        users = userdb.load_users()

    store.mkdir(_auth_base_dir)

    contactgroups = load_contact_group_information()
    groups = {}
    for gid, group in contactgroups.items():
        if 'nagvis_maps' in group and group['nagvis_maps']:
            groups[gid] = group['nagvis_maps']

    _create_php_file(callee, users, config.get_role_permissions(), groups)
Exemple #22
0
    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)
Exemple #23
0
def create_auth_file(callee, users=None):
    from cmk.gui.watolib.groups import load_contact_group_information
    import cmk.gui.userdb as userdb  # TODO: Cleanup
    if users is None:
        users = userdb.load_users()

    store.mkdir(g_auth_base_dir)

    contactgroups = load_contact_group_information()
    groups = {}
    for gid, group in contactgroups.items():
        if 'nagvis_maps' in group and group['nagvis_maps']:
            groups[gid] = group['nagvis_maps']

    create_php_file(callee, users, config.get_role_permissions(), groups)
Exemple #24
0
    def _save_folder(self, folder):
        store.mkdir(folder.get_root_dir())

        content = ""
        for varname, ruleset in sorted(self._rulesets.items(),
                                       key=lambda x: x[0]):
            if varname not in rulespec_registry:
                continue  # don't save unknown rulesets

            if ruleset.is_empty_in_folder(folder):
                continue  # don't save empty rule sets

            content += ruleset.to_config(folder)

        store.save_mk_file(folder.rules_file_path(),
                           content,
                           add_header=not config.wato_use_git)
Exemple #25
0
    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)
Exemple #26
0
def create_snapshot(comment):
    store.mkdir(snapshot_dir)

    snapshot_name = "wato-snapshot-%s.tar" % time.strftime(
        "%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))

    data = {}
    data["comment"] = _("Activated changes by %s.") % config.user.id

    if comment:
        data["comment"] += _("Comment: %s") % comment

    data["created_by"] = config.user.id
    data["type"] = "automatic"
    data["snapshot_name"] = snapshot_name

    _do_create_snapshot(data)
    _do_snapshot_maintenance()

    return snapshot_name
Exemple #27
0
    def _save_folder(self, folder):
        store.mkdir(folder.get_root_dir())

        content = ""
        for varname, ruleset in sorted(self._rulesets.items(),
                                       key=lambda x: x[0]):
            if varname not in rulespec_registry:
                continue  # don't save unknown rulesets

            if ruleset.is_empty_in_folder(folder):
                continue  # don't save empty rule sets

            content += ruleset.to_config(folder)

        # Adding this instead of the full path makes it easy to move config
        # files around. The real FOLDER_PATH will be added dynamically while
        # loading the file in cmk_base.config
        content = content.replace("'%s'" % _FOLDER_PATH_MACRO,
                                  "'/' + FOLDER_PATH")

        store.save_mk_file(folder.rules_file_path(),
                           content,
                           add_header=not config.wato_use_git)
Exemple #28
0
def create_snapshot(comment):
    logger.debug("Start creating backup snapshot")
    start = time.time()
    store.mkdir(snapshot_dir)

    snapshot_name = "wato-snapshot-%s.tar" % time.strftime("%Y-%m-%d-%H-%M-%S",
                                                           time.localtime(time.time()))

    data = {}  # type: Dict[str, Any]
    data["comment"] = _("Activated changes by %s.") % config.user.id

    if comment:
        data["comment"] += _("Comment: %s") % comment

    data["created_by"] = config.user.id
    data["type"] = "automatic"
    data["snapshot_name"] = snapshot_name

    _do_create_snapshot(data)
    _do_snapshot_maintenance()

    log_audit(None, "snapshot-created", _("Created snapshot %s") % snapshot_name)
    logger.debug("Backup snapshot creation took %.4f", time.time() - start)
Exemple #29
0
def save_user_file(name: str, data: Any, user_id: UserId) -> None:
    path = cmk.utils.paths.profile_dir.joinpath(user_id, name + ".mk")
    store.mkdir(path.parent)
    store.save_object_to_file(path, data)
Exemple #30
0
def save_gui_messages(messages, user_id=None):
    if user_id is None:
        user_id = config.user.id
    path = config.config_dir + "/" + six.ensure_str(user_id) + '/messages.mk'
    store.mkdir(os.path.dirname(path))
    store.save_object_to_file(path, messages)