%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /opt/imunify360/venv/lib/python3.8/site-packages/defence360agent/utils/
Upload File :
Create Path :
Current File : //opt/imunify360/venv/lib/python3.8/site-packages/defence360agent/utils/serialization.py

"""
This program is free software: you can redistribute it and/or modify it under 
the terms of the GNU General Public License as published by 
the Free Software Foundation, either version 3 of the License, 
or (at your option) any later version.


This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
See the GNU General Public License for more details.


You should have received a copy of the GNU General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/>.

Copyright © 2019 Cloud Linux Software Inc.

This software is also available under ImunifyAV commercial license,
see <https://www.imunify360.com/legal/eula>
"""
import functools
import logging
import pickle
from asyncio import iscoroutinefunction
from typing import Union, Callable

logger = logging.getLogger(__name__)


def _dump(path, obj):
    # separate function to mock in tests
    with open(path, "wb") as w:
        pickle.dump(obj, w)


def serialize_attr(*, path: str, attr: str):
    """
    Make decorator to serialize an object or object's attribute
    :param path: path to file to serialize into
    :param attr: attribute name to serialize
    """

    def decorator(f):
        @functools.wraps(f)
        def wrapper(self, *args, **kwargs):
            result = f(self, *args, **kwargs)
            obj = getattr(self, attr)
            logger.debug("Write %r to %r", obj, path)
            _dump(path, obj)
            return result

        @functools.wraps(f)
        async def async_wrapper(self, *args, **kwargs):
            result = await f(self, *args, **kwargs)
            obj = getattr(self, attr)
            logger.debug("Write %r to %r", obj, path)
            _dump(path, obj)
            return result

        if iscoroutinefunction(f):
            return async_wrapper
        return wrapper

    return decorator


def unserialize(*, path: str, fallback: Union[Callable, object] = None):
    """
    Restore an object from file
    :param path: path to read from
    :param fallback: return or call it if unserialization fails
    :return:
    """
    try:
        with open(path, "rb") as r:
            obj = pickle.load(r)
        logger.debug("Read %r from %r", obj, path)
    except (
        FileNotFoundError,
        EOFError,
        IndexError,
        pickle.UnpicklingError,
    ) as e:
        obj = fallback() if callable(fallback) else fallback
        logger.debug("Unserialize failed with %r. Returning an %r", e, obj)
    return obj

Zerion Mini Shell 1.0