Skip to content
Snippets Groups Projects
MockP4RuntimeService.py 1.69 KiB
Newer Older
import grpc, logging
from concurrent import futures
from p4.v1 import p4runtime_pb2_grpc

from .Device_P4 import(
    DEVICE_P4_ADDRESS, DEVICE_P4_PORT,
    DEVICE_P4_WORKERS, DEVICE_P4_GRACE_PERIOD)
from .MockP4RuntimeServicerImpl import MockP4RuntimeServicerImpl

LOGGER = logging.getLogger(__name__)


class MockP4RuntimeService:
    def __init__(
            self, address=DEVICE_P4_ADDRESS, port=DEVICE_P4_PORT,
            max_workers=DEVICE_P4_WORKERS,
            grace_period=DEVICE_P4_GRACE_PERIOD):
        self.address = address
        self.port = port
        self.endpoint = '{:s}:{:s}'.format(str(self.address), str(self.port))
        self.max_workers = max_workers
        self.grace_period = grace_period
        self.pool = None
        self.server = None
        self.servicer = None

    def start(self):
        LOGGER.info(
            'Starting P4Runtime service on {:s} with max_workers: {:s})'.format(
                str(self.endpoint), str(self.max_workers)))

        self.pool = futures.ThreadPoolExecutor(max_workers=self.max_workers)
        self.server = grpc.server(self.pool)

        self.servicer = MockP4RuntimeServicerImpl()
        p4runtime_pb2_grpc.add_P4RuntimeServicer_to_server(
            self.servicer, self.server)

        _ = self.server.add_insecure_port(self.endpoint)
        LOGGER.info('Listening on {:s}...'.format(str(self.endpoint)))

        self.server.start()
        LOGGER.debug('P4Runtime service started')

    def stop(self):
        LOGGER.debug(
            'Stopping P4Runtime service (grace period {:s} seconds)...'.format(
                str(self.grace_period)))
        self.server.stop(self.grace_period)
        LOGGER.debug('P4Runtime service stopped')