Exemplo n.º 1
0
    def test_start_controller(*args):
        """Test activate method."""
        (mock_pre_install_napps, mock_load_napps, mock_raw_event_handler,
         mock_msg_in_event_handler, mock_msg_out_event_handler,
         mock_app_event_handler, _) = args

        napp = MagicMock()
        loop = MagicMock()
        options = KytosConfig().options['daemon']
        options.napps_pre_installed = [napp]
        controller = Controller(options, loop=loop)
        controller.log = Mock()

        controller.start_controller()

        controller.server.serve_forever.assert_called()
        calls = [
            call(mock_raw_event_handler.return_value),
            call(mock_msg_in_event_handler.return_value),
            call(mock_msg_out_event_handler.return_value),
            call(mock_app_event_handler.return_value)
        ]
        loop.create_task.assert_has_calls(calls)
        mock_pre_install_napps.assert_called_with([napp])
        mock_load_napps.assert_called()
Exemplo n.º 2
0
    def _get_controller_mock(self):
        """Return a controller mock."""
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)
        options = KytosConfig().options['daemon']
        options.jwt_secret = 'jwt_secret'

        controller = Controller(options, loop=loop)
        controller.log = Mock()

        # Patch event callback trigger.
        controller.buffers.app.put = self._patch_event_trigger

        return controller
Exemplo n.º 3
0
    def __init__(self):
        """Create the GenericEntity object with empty metadata dictionary."""
        options = KytosConfig().options['daemon']
        self.metadata = {}

        self._active: bool = True
        self._enabled: bool = options.enable_entities_by_default
Exemplo n.º 4
0
def main():
    """Start main Kytos Daemon."""
    def stop_controller(signum, frame):  # pylint: disable=unused-argument
        """Stop the controller before quitting."""
        if controller:
            print('Stopping controller...')
            # If stop() hangs, old ctrl+c behaviour will be restored
            signal.signal(signal.SIGINT, kill_handler)
            controller.stop()

    kill_handler = signal.signal(signal.SIGINT, stop_controller)

    config = KytosConfig()
    controller = Controller(config.options['daemon'])

    if controller.options.foreground:
        try:
            controller.start()
        except SystemExit as exc:
            controller.log.error(exc)
            controller.log.info("Kytos start aborted.")
            sys.exit()

        start_shell(controller)

        controller.stop()
    else:
        with daemon.DaemonContext():
            try:
                controller.start()
            except SystemExit as exc:
                controller.log.error(exc)
                controller.log.info("Kytos daemon start aborted.")
                sys.exit()
Exemplo n.º 5
0
 def __init__(self):
     """Create the GenericEntity object with empty metadata dictionary."""
     options = KytosConfig().options['daemon']
     self.metadata = {}
     # operational status with True or False
     self._active = True
     # administrative status with True or False
     self._enabled = options.enable_entities_by_default
Exemplo n.º 6
0
def main():
    config = KytosConfig().options['daemon']

    if config.foreground:
        async_main(config)
    else:
        with daemon.DaemonContext():
            async_main(config)
Exemplo n.º 7
0
def main():
    """Read config and start Kytos in foreground or daemon mode."""
    config = KytosConfig().options['daemon']

    if config.foreground:
        async_main(config)
    else:
        with daemon.DaemonContext():
            async_main(config)
Exemplo n.º 8
0
    def test_start_controller(*args):
        """Test activate method."""
        (mock_pre_install_napps, mock_load_napps, _, _, _, _, _) = args

        napp = MagicMock()
        loop = MagicMock()
        options = KytosConfig().options['daemon']
        options.napps_pre_installed = [napp]
        controller = Controller(options, loop=loop)
        controller.log = Mock()

        controller.start_controller()

        controller.server.serve_forever.assert_called()
        assert loop.create_task.call_count == 5
        assert len(controller._tasks) == 5
        mock_pre_install_napps.assert_called_with([napp])
        mock_load_napps.assert_called()
Exemplo n.º 9
0
    def setUp(self):
        """Instantiate a controller."""

        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

        self.options = KytosConfig().options['daemon']
        self.controller = Controller(self.options, loop=self.loop)
        self.controller.log = Mock()
Exemplo n.º 10
0
def get_config():
    """Exclude unittest args from Config argparser."""
    argv_backup = None
    # If cli command was like "python -m unittest"
    if sys.argv[0].split()[-1] == 'unittest':
        argv_backup = sys.argv
        sys.argv = sys.argv[:1]
    config = KytosConfig()
    if argv_backup:
        # Recover original argv
        sys.argv = argv_backup
    return config
Exemplo n.º 11
0
    def setUp(self):
        """Execute steps before each tests."""
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

        self.options = KytosConfig().options['daemon']
        self.controller = Controller(self.options, loop=self.loop)
        self.controller.log = MagicMock()
        self.controller.load_napp = MagicMock()
        self.controller.unload_napp = MagicMock()

        self.napps_manager = NAppsManager(self.controller)
Exemplo n.º 12
0
def async_main():
    """Start main Kytos Daemon with asyncio loop."""
    def stop_controller(controller):
        """Stop the controller before quitting."""
        loop = asyncio.get_event_loop()

        # If stop() hangs, old ctrl+c behaviour will be restored
        loop.remove_signal_handler(signal.SIGINT)
        loop.remove_signal_handler(signal.SIGTERM)

        # disable_threadpool_exit()

        controller.log.info("Stopping Kytos controller...")
        controller.stop()

    async def start_shell_async():
        """Run the shell inside a thread and stop controller when done."""
        _start_shell = functools.partial(start_shell, controller)
        data = await loop.run_in_executor(executor, _start_shell)
        executor.shutdown()
        stop_controller(controller)
        return data

    config = KytosConfig()
    controller = Controller(config.options['daemon'])

    loop = asyncio.get_event_loop()
    kill_handler = functools.partial(stop_controller, controller)
    loop.add_signal_handler(signal.SIGINT, kill_handler)
    loop.add_signal_handler(signal.SIGTERM, kill_handler)

    if controller.options.debug:
        loop.set_debug(True)

    if controller.options.foreground:
        try:
            controller.start()
        except SystemExit as exc:
            controller.log.error(exc)
            controller.log.info("Kytos start aborted.")
            sys.exit()

        executor = ThreadPoolExecutor(max_workers=1)
        loop.create_task(start_shell_async())
    else:
        with daemon.DaemonContext():
            try:
                controller.start()
            except SystemExit as exc:
                controller.log.error(exc)
                controller.log.info("Kytos daemon start aborted.")
                sys.exit()
Exemplo n.º 13
0
def main():
    """Read config and start Kytos in foreground or daemon mode."""
    # data_files is not enough when installing from PyPI

    _create_pid_dir()

    config = KytosConfig().options['daemon']

    if config.foreground or not config.daemon:
        async_main(config)
    else:
        with daemon.DaemonContext():
            async_main(config)
Exemplo n.º 14
0
 def get_token_expiration():
     """Return token expiration time in minutes defined in kytos conf."""
     options = KytosConfig().options['daemon']
     return options.token_expiration_minutes
Exemplo n.º 15
0
def get_controller_mock():
    """Return a controller mock."""
    options = KytosConfig().options['daemon']
    controller = Controller(options)
    controller.log = Mock()
    return controller
Exemplo n.º 16
0
    def __init__(self, options=None, loop=None):
        """Init method of Controller class takes the parameters below.

        Args:
            options (:attr:`ParseArgs.args`): :attr:`options` attribute from an
                instance of :class:`~kytos.core.config.KytosConfig` class.
        """
        if options is None:
            options = KytosConfig().options['daemon']

        self._loop = loop or asyncio.get_event_loop()
        self._pool = ThreadPoolExecutor(max_workers=1)

        # asyncio tasks
        self._tasks = []

        #: dict: keep the main threads of the controller (buffers and handler)
        self._threads = {}
        #: KytosBuffers: KytosBuffer object with Controller buffers
        self.buffers = KytosBuffers(loop=self._loop)
        #: dict: keep track of the socket connections labeled by ``(ip, port)``
        #:
        #: This dict stores all connections between the controller and the
        #: switches. The key for this dict is a tuple (ip, port). The content
        #: is a Connection
        self.connections = {}
        #: dict: mapping of events and event listeners.
        #:
        #: The key of the dict is a KytosEvent (or a string that represent a
        #: regex to match against KytosEvents) and the value is a list of
        #: methods that will receive the referenced event
        self.events_listeners = {
            'kytos/core.connection.new': [self.new_connection]
        }

        #: dict: Current loaded apps - ``'napp_name'``: ``napp`` (instance)
        #:
        #: The key is the napp name (string), while the value is the napp
        #: instance itself.
        self.napps = {}
        #: Object generated by ParseArgs on config.py file
        self.options = options
        #: KytosServer: Instance of KytosServer that will be listening to TCP
        #: connections.
        self.server = None
        #: dict: Current existing switches.
        #:
        #: The key is the switch dpid, while the value is a Switch object.
        self.switches = {}  # dpid: Switch()
        self._switches_lock = threading.Lock()

        #: datetime.datetime: Time when the controller finished starting.
        self.started_at = None

        #: logging.Logger: Logger instance used by Kytos.
        self.log = None

        #: Observer that handle NApps when they are enabled or disabled.
        self.napp_dir_listener = NAppDirListener(self)

        self.napps_manager = NAppsManager(self)

        #: API Server used to expose rest endpoints.
        self.api_server = APIServer(__name__, self.options.listen,
                                    self.options.api_port, self.napps_manager,
                                    self.options.napps)

        self.auth = Auth(self)
        self.dead_letter = DeadLetter(self)

        self._register_endpoints()
        #: Adding the napps 'enabled' directory into the PATH
        #: Now you can access the enabled napps with:
        #: from napps.<username>.<napp_name> import ?....
        sys.path.append(os.path.join(self.options.napps, os.pardir))
        sys.excepthook = exc_handler
Exemplo n.º 17
0
 def get_authenticate_options():
     """Return configuration options related to authentication."""
     options = KytosConfig().options['daemon']
     return options.authenticate_urls
Exemplo n.º 18
0
def get_thread_pool_max_workers():
    """Get the number of thread pool max workers."""
    return KytosConfig().options["daemon"].thread_pool_max_workers
Exemplo n.º 19
0
def get_apm_name():
    """Get apm backend name."""
    return KytosConfig().options["daemon"].apm
Exemplo n.º 20
0
 def get_jwt_secret(cls):
     """Return JWT secret defined in kytos conf."""
     options = KytosConfig().options['daemon']
     return options.jwt_secret
Exemplo n.º 21
0
 def setUp(self):
     """Instantiate a controller."""
     self.options = KytosConfig().options['daemon']
     self.controller = Controller(self.options)
     self.controller.log = Mock()