# Path: marvin_python_toolbox/engine_base/stubs/actions_pb2_grpc.py
# class OnlineActionHandlerStub(object):
# class OnlineActionHandlerServicer(object):
# class BatchActionHandlerStub(object):
# class BatchActionHandlerServicer(object):
#   def __init__(self, channel):
#   def _remote_execute(self, request, context):
#   def _remote_reload(self, request, context):
#   def _health_check(self, request, context):
# def add_OnlineActionHandlerServicer_to_server(servicer, server):
#   def __init__(self, channel):
#   def _remote_execute(self, request, context):
#   def _remote_reload(self, request, context):
#   def _health_check(self, request, context):
# def add_BatchActionHandlerServicer_to_server(servicer, server):
# 
# Path: marvin_python_toolbox/_compatibility.py

# 
# Path: marvin_python_toolbox/_logging.py
# def get_logger(name, namespace='marvin_python_toolbox',
#                log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
#     """Build a logger that outputs to a file and to the console,"""
# 
#     log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
#                  os.getenv('LOG_LEVEL', log_level))
#     log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
#                os.getenv('LOG_DIR', log_dir))
# 
#     logger = logging.getLogger('{}.{}'.format(namespace, name))
#     logger.setLevel(log_level)
# 
#     formatter = logging.Formatter(
#         '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 
#     # Create a console stream handler
#     console_handler = logging.StreamHandler()
#     console_handler.setLevel(log_level)
#     console_handler.setFormatter(formatter)
#     logger.addHandler(console_handler)
# 
#     try:
#         log_path = os.path.abspath(log_dir)
#         log_filename = '{name}.{pid}.log'.format(
#             name=namespace, pid=os.getpid())
# 
#         file_path = str(os.path.join(log_path, log_filename))
# 
#         if not os.path.exists(log_path):  # pragma: no cover
#             os.makedirs(log_path, mode=774)
# 
#         # Create a file handler
#         file_handler = logging.FileHandler(file_path)
#         file_handler.setLevel(log_level)
#         file_handler.setFormatter(formatter)
#         logger.addHandler(file_handler)
#     except OSError as e:
#         logger.error('Could not create log file {file}: {error}'.format(
#             file=file_path, error=e.strerror))
# 
#     return logger


import os
import joblib as serializer
import grpc
import json
from abc import ABCMeta, abstractmethod
from concurrent import futures
from .stubs.actions_pb2 import BatchActionResponse, OnlineActionResponse, ReloadResponse, HealthCheckResponse
from .stubs import actions_pb2_grpc
from .._compatibility import six
from .._logging import get_logger
    @abstractmethod
    def execute(self, params, **kwargs):
        pass

    def _pipeline_execute(self, params):
        if self._previous_step:
            self._previous_step._pipeline_execute(params)

        logger.info("Start of the {} execute method!".format(self.action_name))
        self.execute(params)
        logger.info("Finish of the {} execute method!".format(self.action_name))

    def _remote_execute(self, request, context):
        logger.info("Received message from client and sending to engine action...")
        logger.debug("Received Params: {}".format(request.params))

        params = json.loads(request.params) if request.params else self._params

        self._pipeline_execute(params=params)

        self._release_local_saved_objects()

        logger.info("Handling returned message from engine action...")
        response_message = BatchActionResponse(message="Done")

        logger.info("Return final results to the client!")
        return response_message

    def _prepare_remote_server(self, port, workers, rpc_workers):
        server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=workers), maximum_concurrent_rpcs=rpc_workers)

# Path: marvin_python_toolbox/engine_base/stubs/actions_pb2_grpc.py
# class OnlineActionHandlerStub(object):
# class OnlineActionHandlerServicer(object):
# class BatchActionHandlerStub(object):
# class BatchActionHandlerServicer(object):
#   def __init__(self, channel):
#   def _remote_execute(self, request, context):
#   def _remote_reload(self, request, context):
#   def _health_check(self, request, context):
# def add_OnlineActionHandlerServicer_to_server(servicer, server):
#   def __init__(self, channel):
#   def _remote_execute(self, request, context):
#   def _remote_reload(self, request, context):
#   def _health_check(self, request, context):
# def add_BatchActionHandlerServicer_to_server(servicer, server):
# 
# Path: marvin_python_toolbox/_compatibility.py

# 
# Path: marvin_python_toolbox/_logging.py
# def get_logger(name, namespace='marvin_python_toolbox',
#                log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
#     """Build a logger that outputs to a file and to the console,"""
# 
#     log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
#                  os.getenv('LOG_LEVEL', log_level))
#     log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
#                os.getenv('LOG_DIR', log_dir))
# 
#     logger = logging.getLogger('{}.{}'.format(namespace, name))
#     logger.setLevel(log_level)
# 
#     formatter = logging.Formatter(
#         '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 
#     # Create a console stream handler
#     console_handler = logging.StreamHandler()
#     console_handler.setLevel(log_level)
#     console_handler.setFormatter(formatter)
#     logger.addHandler(console_handler)
# 
#     try:
#         log_path = os.path.abspath(log_dir)
#         log_filename = '{name}.{pid}.log'.format(
#             name=namespace, pid=os.getpid())
# 
#         file_path = str(os.path.join(log_path, log_filename))
# 
#         if not os.path.exists(log_path):  # pragma: no cover
#             os.makedirs(log_path, mode=774)
# 
#         # Create a file handler
#         file_handler = logging.FileHandler(file_path)
#         file_handler.setLevel(log_level)
#         file_handler.setFormatter(formatter)
#         logger.addHandler(file_handler)
#     except OSError as e:
#         logger.error('Could not create log file {file}: {error}'.format(
#             file=file_path, error=e.strerror))
# 
#     return logger


# Path: marvin_python_toolbox/engine_base/engine_base_action.py
import os
import joblib as serializer
import grpc
import json
from abc import ABCMeta, abstractmethod
from concurrent import futures
from .stubs.actions_pb2 import BatchActionResponse, OnlineActionResponse, ReloadResponse, HealthCheckResponse
from .stubs import actions_pb2_grpc
from .._compatibility import six
from .._logging import get_logger

    @abstractmethod
    def execute(self, params, **kwargs):
        pass

    def _pipeline_execute(self, params):
        if self._previous_step:
            self._previous_step._pipeline_execute(params)

        logger.info("Start of the {} execute method!".format(self.action_name))
        self.execute(params)
        logger.info("Finish of the {} execute method!".format(self.action_name))

    def _remote_execute(self, request, context):
        logger.info("Received message from client and sending to engine action...")
        logger.debug("Received Params: {}".format(request.params))

        params = json.loads(request.params) if request.params else self._params

        self._pipeline_execute(params=params)

        self._release_local_saved_objects()

        logger.info("Handling returned message from engine action...")
        response_message = BatchActionResponse(message="Done")

        logger.info("Return final results to the client!")
        return response_message

    def _prepare_remote_server(self, port, workers, rpc_workers):
        server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=workers), maximum_concurrent_rpcs=rpc_workers)

        actions_pb2_grpc.add_BatchActionHandlerServicer_to_server(self, server)