\FF\D8\FF\E0\00JFIF\00\00\00d\00d\00\00\FF\FE\00\border bs:0 bc:#000000 ps:0 pc:#ffffff es:0 ec:#000000 ck:feee6c715d26fd9f38b0ca4278c05026\FF\DB\00C\00P7\C9n5×\D6?\BDê\9Ds\EBp\9F[`8m\B7)o\B5\E8\E6I\99\FE3]]A2\BA\8Cw\D6E\93\\DEv\C8\009\F2\F1NI?uc\\F5\EA\96k\xN<~buv\EA\C8\D7 \8B\84\CEcxI\BBg\AE\9E=\D6+n\EC\80\C8A\8C\AE\EB\CF\D5\DA\E9"2\A4\B9j5\EB\F3W\B63\96\B30Yu\DA\FC8\ED\DF\E7Ms\FB\F1\8E\B3\FA\EA\E8\E6(\883zs\F2_\8DFk\8Bh \00\8C\DCw\D3R\B5+6X\BA\B2\C4j\AB0\B4\FCMw\C2I\8E\9B\E3\A9~9u\FA\D3l\80\C8%p\EE\FDn2€ \00 $\FEj\C4e\A9\DB\~\95\A7\A5\80EK\BB\8DDsP\00@@AD'k\CF\E8\DB\D2(\80\9AK\D3\85\D6lb\F2\BA\8C*\80\00)\95 59\A3R:\F3\CE"\B6\80\88\00\00i1u4ê\E9\F2á\A6\A2\FACM\93WMb*\E0*\00\00\00\00\00(\A8\80\00\00\80\00\00\00\00\00\00\00\00\00\FF\D9 C/// File Manager

File Manager

Path: /opt/cloudlinux/venv/lib64/python3.11/site-packages/lvestats/plugins/generic/

Viewing File: cleaners.py

# coding=utf-8
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

import logging
import os
import timeit

from sqlalchemy import func
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import sessionmaker

import lvestats.lib.snapshot
from lvestats.core.plugin import LveStatsPlugin, LveStatsPluginTerminated
from lvestats.lib.commons.func import reboot_lock
from lvestats.orm import history, history_gov, history_x60, incident

__author__ = 'shaman'


class HistoryCleaner(LveStatsPlugin):
    def __init__(self):
        self.period = 60 * 60  # 1 hour
        self.batch = 6 * 60 * 60  # 6 hours
        self.execute_timeout = 20
        self.keep_history_days = 30  # 1 months to keep history, by default
        self.db_engine = None
        self.log = logging.getLogger('HistoryCleaner')
        self.db_type = 'sqlite'
        self.server_id = None
        # db_type = mysql
        # db_type = postgresql

    def set_db_engine(self, engine):
        self.db_engine = engine

    def set_config(self, config):
        self.keep_history_days = int(config.get('keep_history_days', self.keep_history_days))
        self.period = int(config.get('period', 60)) * 60
        self.db_type = config.get('db_type', self.db_type)
        self.server_id = config.get('server_id', 'localhost')

    def time_threshold(self):
        return int(self.now - self.keep_history_days * 24 * 60 * 60)

    @staticmethod
    def clean_old_snapshots(ts_to):
        for uid in os.listdir(lvestats.lib.snapshot.SNAPSHOT_PATH):
            if not uid.isdigit():
                continue
            snap = lvestats.lib.snapshot.Snapshot({'uid': int(uid)})
            snap.delete_old(ts_to)

    def execute(self, lve_data):
        t_min = self.time_threshold()
        # tables to clean: history, history_gov, incident, snapshot
        self.log.debug('Records with timestamp less then %d will be erased', t_min)
        if os.path.exists(lvestats.lib.snapshot.SNAPSHOT_PATH):
            self.clean_old_snapshots(t_min)
        self.log.debug('Deleting old records from database')
        with reboot_lock():
            session = sessionmaker(bind=self.db_engine)()
            start_time = timeit.default_timer()
            try:
                self.delete(session, history_x60, history_x60.created, t_min)
                self.delete(session, history_gov, history_gov.ts, t_min)
                self.delete(session, incident, incident.incident_end_time, t_min)
                session.commit()

                first_created = (
                    session.query(func.min(history.created)).filter(history.server_id == self.server_id).one()[0]
                    or t_min
                )
                for iteration, timestamp in enumerate(range(int(first_created) + self.batch, int(t_min), self.batch)):
                    self.delete(session, history, history.created, timestamp)
                    session.commit()
                    if timeit.default_timer() - start_time > self.execute_timeout:
                        self.log.debug(
                            "Iterations: %s. Deleted: %sh", iteration, (timestamp - first_created) / (60 * 60)
                        )
                        break
                else:
                    self.delete(session, history, history.created, t_min)
                    session.commit()
            except OperationalError as e:
                session.rollback()
                self.log.warning(str(e))
            except LveStatsPluginTerminated as e:
                self.log.debug('Cleaner terminated. Trying to rollback')
                session.rollback()
                session.close()
                raise LveStatsPluginTerminated() from e
            finally:
                elapsed = (timeit.default_timer() - start_time) * 1000  # Milliseconds
                self.log.debug('Execution time: %d', elapsed)
                session.close()

    def delete(self, session, table, ts_column, limit):
        session.query(table).filter(ts_column < limit, table.server_id == self.server_id).delete(
            synchronize_session=False
        )