Sindbad~EG File Manager

Current Path : /opt/alt/python37/lib/python3.7/site-packages/lvestats/plugins/generic/
Upload File :
Current File : //opt/alt/python37/lib/python3.7/site-packages/lvestats/plugins/generic/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
from __future__ import absolute_import
from __future__ import division
from builtins import range
import os
import logging
import timeit
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import OperationalError
from sqlalchemy import func

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

__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):
            snap = lvestats.lib.snapshot.Snapshot({'uid': 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:
                self.log.debug('Cleaner terminated. Trying to rollback')
                session.rollback()
                session.close()
                raise LveStatsPluginTerminated()
            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)

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists