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j '  'P$a ( `D$Na L?u80e J,K˷NI'0eݷ(NI'؀ 2ipIIKp`:O'`ʤxB8Ѥx Ѥx $ $P6 :vRNb 'p,>NB 'P]-->P T+*^h& p '‰a ‰ (ĵt#u33;Nt̵'ޯ; [3W ~]0KH1q@8]O2]3*̧7# *p>us p _6]/}-4|t'|Smx= DoʾM×M_8!)6lq':l7!|4} '\ne t!=hnLn (~Dn\+‰_4k)0e@OhZ`F `.m1} 'vp{F`ON7Srx 'D˸nV`><;yMx!IS钦OM)Ե٥x 'DSD6bS8!" ODz#R >S8!7ّxEh0m$MIPHi$IvS8IN$I p$O8I,sk&I)$IN$Hi$I^Ah.p$MIN$IR8I·N "IF9Ah0m$MIN$IR8IN$I 3jIU;kO$ɳN$+ q.x* tEXtComment

Viewing File: /opt/cloudlinux/venv/lib/python3.11/site-packages/lvestats/lib/notifications_helper.py

#!/usr/bin/python
# 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 pickle
import time
from typing import Dict, Iterable, Union  # NOQA

__author__ = "Aleksandr Shyshatsky"


class NotificationsHelper(object):
    """
    Helper for our StatsNotifier plugin, contains
    logic related to notification periods
    """

    STATSNOTIFIER_LAST_TS = "/var/lve/statsnotifier_last.ts"
    RESELLERS_NOTIFICATIONS_STORAGE = "/var/lve/statsnotifier_timestamps.bin"

    def __init__(self):
        self._users_notification_info = {}  # type: Dict[int, float]
        self._resellers_notification_info = {}  # type: Dict[int, float]
        self._admin_notify_time = -1
        self._log = logging.getLogger(__name__)

        # let's load info after service restart
        self._load_from_persistent_storage()

    def _load_from_persistent_storage(self):
        # type: () -> None
        """
        Load information about periods from persistent storage.
        Admin timestamp contains in separate file,
        in order to make it backwards-compatible with old logic
        """
        self._admin_notify_time = self._read_ts_from_file()

        if not os.path.exists(self.RESELLERS_NOTIFICATIONS_STORAGE):
            return
        try:
            with open(self.RESELLERS_NOTIFICATIONS_STORAGE, 'rb') as f:
                self._users_notification_info, self._resellers_notification_info = pickle.load(f)
        except (IOError, EOFError):
            self._log.exception("Cannot load data from persistent storage")

    def save_to_persistent_storage(self):
        # type: () -> None
        """
        Save information about periods on disk.
        Admin timestamp contains in separate file, plain text.
        Resellers info is pickle'd and saved into other file.
        """
        self._save_ts_to_file(self._admin_notify_time)

        try:
            with open(self.RESELLERS_NOTIFICATIONS_STORAGE, 'wb') as f:
                pickle.dump((self._users_notification_info, self._resellers_notification_info), f, protocol=2)
        except IOError:
            self._log.warning("Unable to save resellers timestamps to file")

    def _save_ts_to_file(self, ts):
        # type: (float) -> None
        try:
            with open(self.STATSNOTIFIER_LAST_TS, 'w', encoding='utf-8') as f:
                f.write(str(ts))
        except IOError:
            self._log.warning("Unable to save admin timestamp to file")

    def _read_ts_from_file(self):
        # type: () -> float
        try:
            with open(self.STATSNOTIFIER_LAST_TS, 'r', encoding='utf-8') as f:
                ts = float(f.readline().rstrip())
                return ts
        except IOError:
            return -1
        except ValueError as e:
            self._log.warning("Unable to read %s (%s)", self.STATSNOTIFIER_LAST_TS, str(e))
            return -1

    @staticmethod
    def _get_current_timestamp():
        # type: () -> float
        """
        Get current timestamp. In future, we may do
        some things here, like "round(time / 60**2)"
        """
        return time.time()

    def mark_resellers_notified(self, resellers_id):
        # type: (Iterable[int]) -> None
        """
        Mark resellers as notified. S
        aves current timestamp in memory.
        """
        ts = self._get_current_timestamp()
        for reseller_id in resellers_id:
            self._log.debug("Reseller marked as notified at %s for %s", ts, reseller_id)
            self._resellers_notification_info[reseller_id] = ts

    def mark_users_notified(self, resellers_id):
        # type: (Iterable[int]) -> None
        """
        Mark users as notified.
        Saves current timestamp in memory.
        """
        ts = self._get_current_timestamp()
        for reseller_id in resellers_id:
            self._log.debug("Users marked as notified at %s for %s", ts, reseller_id)
            self._users_notification_info[reseller_id] = ts

    def mark_admin_notified(self):
        # type: () -> None
        """
        Mark admin as notified.
        Saves current timestamp in memory.
        """
        self._log.debug("Admin marked as notified at %s", time.time())
        self._admin_notify_time = self._get_current_timestamp()

    def users_need_notification(self, reseller_id, notify_period):
        # type: (int, Union[int, float]) -> bool
        """
        Check if reseller's users need to be notified
        (period is more than time elapsed)
        """
        time_since_last_check = self._get_current_timestamp() - self._users_notification_info.get(reseller_id, -1)
        return time_since_last_check > notify_period

    def reseller_need_notification(self, reseller_id, notify_period):
        # type: (int, Union[int, float]) -> bool
        """
        Check if reseller himself needs to be notified
        (period is more than time elapsed)
        """
        time_since_last_check = self._get_current_timestamp() - self._resellers_notification_info.get(reseller_id, -1)
        return time_since_last_check > notify_period

    def admin_need_notification(self, notify_period):
        # type: (Union[int, float]) -> bool
        """
        Check if admin needs to be notified
        (period is more than time elapsed)
        """
        return self._admin_notify_time + notify_period < self._get_current_timestamp()
Back to Directory=ceiIENDB`