Example #1
0
    def rename_host_in_folder_rules(folder):
        rulesets = watolib.FolderRulesets(folder)
        rulesets.load()

        changed_folder_rulesets = []
        for varname, ruleset in rulesets.get_rulesets().items():
            for _rule_folder, _rulenr, rule in ruleset.get_rules():
                orig_rule = rule.clone(preserve_id=True)
                if rule.replace_explicit_host_condition(oldname, newname):
                    changed_folder_rulesets.append(varname)

                    log_audit(
                        "edit-rule",
                        _('Renamed host condition from "%s" to "%s"') % (oldname, newname),
                        diff_text=make_diff_text(orig_rule.to_log(), rule.to_log()),
                        object_ref=rule.object_ref(),
                    )

        if changed_folder_rulesets:
            add_change(
                "edit-ruleset",
                _("Renamed host in %d rulesets of folder %s")
                % (len(changed_folder_rulesets), folder.title()),
                object_ref=folder.object_ref(),
                sites=folder.all_site_ids(),
            )
            rulesets.save()

        changed_rulesets.extend(changed_folder_rulesets)

        for subfolder in folder.subfolders():
            rename_host_in_folder_rules(subfolder)
Example #2
0
    def _create_snapshots(self):
        with cmk.gui.watolib.utils.exclusive_lock():
            if not self._changes:
                raise MKUserError(None, _("Currently there are no changes to activate."))

            if self._get_last_change_id() != self._activate_until:
                raise MKUserError(
                    None,
                    _("Another change has been made in the meantime. Please review it "
                      "to ensure you also want to activate it now and start the "
                      "activation again."))

            # Create (legacy) WATO config snapshot
            start = time.time()
            logger.debug("Snapshot creation started")
            # TODO: Remove/Refactor once new changes mechanism has been implemented
            #       This single function is responsible for the slow activate changes (python tar packaging..)
            snapshot_name = cmk.gui.watolib.snapshots.create_snapshot(self._comment)
            log_audit(None, "snapshot-created", _("Created snapshot %s") % snapshot_name)

            work_dir = os.path.join(self.activation_tmp_base_dir, self._activation_id)
            if cmk.is_managed_edition():
                import cmk.gui.cme.managed_snapshots as managed_snapshots
                managed_snapshots.CMESnapshotManager(
                    work_dir, self._get_site_configurations()).generate_snapshots()
            else:
                self._generate_snapshots(work_dir)

            logger.debug("Snapshot creation took %.4f" % (time.time() - start))
Example #3
0
    def activate(self):
        log_audit(None, "liveproxyd-activate",
                  _("Activating changes of Livestatus Proxy configuration"))

        try:
            pidfile = cmk.utils.paths.livestatus_unix_socket + "proxyd.pid"
            try:
                pid = int(file(pidfile).read().strip())
                os.kill(pid, signal.SIGUSR1)
            except IOError as e:
                if e.errno == 2:  # No such file or directory
                    pass
                else:
                    raise
            except ValueError:
                # ignore empty pid file (may happen during locking in
                # cmk.utils.daemon.lock_with_pid_file().  We are in the
                # situation where the livstatus proxy is in early phase of the
                # startup. The configuration is loaded later -> no reload needed
                pass

        except Exception as e:
            logger.exception()
            raise MKGeneralException(
                _("Could not reload Livestatus Proxy: %s. See web.log and liveproxyd.log "
                  "for further information.") % e)
Example #4
0
 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")
Example #5
0
    def activate(
        self,
        settings: Optional[SerializedSettings] = None
    ) -> ConfigurationWarnings:
        log_audit("liveproxyd-activate",
                  _("Activating changes of Livestatus Proxy configuration"))

        try:
            pidfile = Path(cmk.utils.paths.livestatus_unix_socket).with_name(
                "liveproxyd.pid")
            try:
                with pidfile.open(encoding="utf-8") as f:
                    pid = int(f.read().strip())

                os.kill(pid, signal.SIGHUP)
            except OSError as e:
                # ENOENT: No liveproxyd running: No reload needed.
                # ESRCH: PID in pidfiles does not exist: No reload needed.
                if e.errno not in (errno.ENOENT, errno.ESRCH):
                    raise
            except ValueError:
                # ignore empty pid file (may happen during locking in
                # cmk.utils.daemon.lock_with_pid_file().  We are in the
                # situation where the livstatus proxy is in early phase of the
                # startup. The configuration is loaded later -> no reload needed
                pass

        except Exception as e:
            logger.exception("error reloading liveproxyd")
            raise MKGeneralException(
                _("Could not reload Livestatus Proxy: %s. See web.log and liveproxyd.log "
                  "for further information.") % e)
        return []
Example #6
0
    def activate(self):
        log_audit(None, "liveproxyd-activate",
                  _("Activating changes of Livestatus Proxy configuration"))

        try:
            pidfile = cmk.utils.paths.livestatus_unix_socket + "proxyd.pid"
            try:
                pid = int(open(pidfile).read().strip())
                os.kill(pid, signal.SIGUSR1)
            except IOError as e:
                # No liveproxyd running: No reload needed.
                if e.errno != errno.ENOENT:
                    raise
            except OSError as e:
                # PID in pidfiles does not exist: No reload needed.
                if e.errno != errno.ESRCH:  # [Errno 3] No such process
                    raise
            except ValueError:
                # ignore empty pid file (may happen during locking in
                # cmk.utils.daemon.lock_with_pid_file().  We are in the
                # situation where the livstatus proxy is in early phase of the
                # startup. The configuration is loaded later -> no reload needed
                pass

        except Exception as e:
            logger.exception("error reloading liveproxyd")
            raise MKGeneralException(
                _("Could not reload Livestatus Proxy: %s. See web.log and liveproxyd.log "
                  "for further information.") % e)
Example #7
0
def test_log_audit_with_object_diff(request_context):
    old = {
        "a": "b",
        "b": "c",
    }
    new = {
        "b": "c",
    }

    with on_time("2018-04-15 16:50", "CET"):
        log_audit(
            object_ref=None,
            action="bla",
            message="Message",
            user_id=UserId("calvin"),
            diff_text=make_diff_text(old, new),
        )

    store = AuditLogStore(AuditLogStore.make_path())
    assert store.read() == [
        AuditLogStore.Entry(
            time=1523811000,
            object_ref=None,
            user_id="calvin",
            action="bla",
            text="Message",
            diff_text='Attribute "a" with value "b" removed.',
        ),
    ]
Example #8
0
    def _log_activation(self):
        log_msg = _("Starting activation (Sites: %s)") % ",".join(self._sites)
        log_audit(None, "activate-changes", log_msg)

        if self._comment:
            log_audit(None, "activate-changes",
                      "%s: %s" % (_("Comment"), self._comment))
Example #9
0
 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 []
Example #10
0
def edit_users(changed_users):
    all_users = userdb.load_users(lock=True)
    new_users_info = []
    modified_users_info = []
    for user_id, settings in changed_users.items():
        user_attrs = settings.get("attributes")
        is_new_user = settings.get("is_new_user", True)
        _validate_user_attributes(all_users, user_id, user_attrs, is_new_user=is_new_user)
        if is_new_user:
            new_users_info.append(user_id)
        else:
            modified_users_info.append(user_id)

        if is_new_user:
            add_internal_attributes(user_attrs)

        old_object = make_user_audit_log_object(all_users.get(user_id, {}))
        log_audit(action="edit-user",
                  message=(_("Created new user: %s") %
                           user_id if is_new_user else _("Modified user: %s") % user_id),
                  diff_text=make_diff_text(old_object, make_user_audit_log_object(user_attrs)),
                  object_ref=make_user_object_ref(user_id))

        all_users[user_id] = user_attrs

    if new_users_info:
        add_change("edit-users", _("Created new users: %s") % ", ".join(new_users_info))
    if modified_users_info:
        add_change("edit-users", _("Modified users: %s") % ", ".join(modified_users_info))

    userdb.save_users(all_users)
Example #11
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)
Example #12
0
def test_log_audit_with_html_message(request_context):
    with on_time("2018-04-15 16:50", "CET"):
        log_audit(
            object_ref=None,
            user_id=UserId("calvin"),
            action="bla",
            message=HTML("Message <b>bla</b>"),
        )

    store = AuditLogStore(AuditLogStore.make_path())
    assert store.read() == [
        AuditLogStore.Entry(
            time=1523811000,
            object_ref=None,
            user_id="calvin",
            action="bla",
            text=HTML("Message <b>bla</b>"),
            diff_text=None,
        ),
    ]
Example #13
0
def test_log_audit_with_html_message(register_builtin_html):
    with on_time('2018-04-15 16:50', 'CET'):
        log_audit(
            object_ref=None,
            user_id=UserId('calvin'),
            action="bla",
            message=HTML("Message <b>bla</b>"),
        )

    store = AuditLogStore(AuditLogStore.make_path())
    assert store.read() == [
        AuditLogStore.Entry(
            time=1523811000,
            object_ref=None,
            user_id='calvin',
            action='bla',
            text=HTML("Message <b>bla</b>"),
            diff_text=None,
        ),
    ]
Example #14
0
def delete_users(users_to_delete):
    if user.id in users_to_delete:
        raise MKUserError(None, _("You cannot delete your own account!"))

    all_users = userdb.load_users(lock=True)

    deleted_users = []
    for entry in users_to_delete:
        if entry in all_users:  # Silently ignore not existing users
            deleted_users.append(entry)
            del all_users[entry]
        else:
            raise MKUserError(None, _("Unknown user: %s") % entry)

    if deleted_users:
        for user_id in deleted_users:
            log_audit("edit-user",
                      _("Deleted user: %s") % user_id,
                      object_ref=make_user_object_ref(user_id))
        add_change("edit-users", _("Deleted user: %s") % ", ".join(deleted_users))
        userdb.save_users(all_users)
Example #15
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)
Example #16
0
 def _log_site_activation(self, site_id):
     log_audit(None, "activate-changes", _("Started activation of site %s") % site_id)