Esempio n. 1
0
    def _add_client(self, source_config):
        logger.debug('Instanciating a new confd client for %s',
                     source_config['uuid'])
        auth_config = dict(source_config['auth'])
        if auth_config.get('key_file'):
            # File must be readable by wazo-dird
            key_file = parse_config_file(auth_config.pop('key_file'))
            if not key_file:
                logger.info('failed to load key file for source %s',
                            source_config['name'])
                return
            auth_config['username'] = key_file['service_id']
            auth_config['password'] = key_file['service_key']
        auth_client = AuthClient(**auth_config)
        token_renewer = TokenRenewer(auth_client)

        confd_config = source_config['confd']
        logger.debug('confd config %s', confd_config)
        client = ConfdClient(**confd_config)
        client.set_tenant(source_config['tenant_uuid'])

        token_renewer.subscribe_to_token_change(client.set_token)
        token_renewer.start()

        self._clients[source_config['uuid']] = RegisteredClient(
            client, token_renewer)
Esempio n. 2
0
def _generate_call_logs():
    parser = argparse.ArgumentParser(description='Call logs generator')
    options = parse_args(parser)
    key_config = load_key_file(DEFAULT_CONFIG)
    config = ChainMap(key_config, DEFAULT_CONFIG)

    auth_client = AuthClient(**config['auth'])
    confd_client = ConfdClient(**config['confd'])
    token_renewer = TokenRenewer(auth_client)
    token_renewer.subscribe_to_token_change(confd_client.set_token)

    cel_fetcher = CELFetcher()
    generator = CallLogsGenerator([
        LocalOriginateCELInterpretor(confd_client),
        DispatchCELInterpretor(CallerCELInterpretor(confd_client),
                               CalleeCELInterpretor(confd_client))
    ])
    writer = CallLogsWriter()
    publisher = BusPublisher(config)
    manager = CallLogsManager(cel_fetcher, generator, writer, publisher)

    options = vars(options)
    with token_renewer:
        if options.get('action') == 'delete':
            if options.get('all'):
                manager.delete_all()
            elif options.get('days'):
                manager.delete_from_days(options['days'])
        else:
            if options.get('days'):
                manager.generate_from_days(days=options['days'])
            else:
                manager.generate_from_count(cel_count=options['cel_count'])
Esempio n. 3
0
class Controller:
    def __init__(self, config):
        self.config = config
        set_xivo_uuid(config, logger)
        self.bus_consumer = CoreBusConsumer(config)
        self.status_aggregator = StatusAggregator()
        self.http_server = HTTPServer(self.config)
        self.http_server.app.config['authorized_subnets'] = self.config[
            'rest_api']['authorized_subnets']
        auth_client = AuthClient(**config['auth'])
        auth_verifier.set_client(auth_client)
        self.token_renewer = TokenRenewer(auth_client)
        self.token_renewer.subscribe_to_token_change(self._on_token_change)

        self.token_status = TokenStatus()
        self.token_renewer.subscribe_to_token_change(
            self.token_status.token_change_callback)

        self.phone_plugins = []
        self.plugin_manager = plugin_helpers.load(
            namespace='wazo_phoned.plugins',
            names=config['enabled_plugins'],
            dependencies={
                'config': config,
                'app': self.http_server.app,
                'token_changed_subscribe':
                self.token_renewer.subscribe_to_token_change,
                'bus_consumer': self.bus_consumer,
                'status_aggregator': self.status_aggregator,
                'phone_plugins': self.phone_plugins,
            },
        )

    def run(self):
        logger.debug('wazo-phoned starting...')
        self.status_aggregator.add_provider(self.bus_consumer.provide_status)
        self.status_aggregator.add_provider(self.token_status.provide_status)
        bus_consumer_thread = Thread(target=self.bus_consumer.run,
                                     name='bus_consumer_thread')
        bus_consumer_thread.start()
        try:
            with self.token_renewer:
                self.http_server.run()
        finally:
            logger.info('wazo-phoned stopping...')
            self.bus_consumer.should_stop = True
            logger.debug('joining rest api thread...')
            self.http_server.join()
            logger.debug('joining bus consumer thread...')
            bus_consumer_thread.join()
            logger.debug('done joining.')

    def stop(self, reason):
        logger.warning('Stopping wazo-phoned: %s', reason)
        self.http_server.stop()

    def _on_token_change(self, token_id):
        self.http_server.app.config['token'] = token_id
Esempio n. 4
0
class Controller:
    def __init__(self, config):
        self.config = config
        init_db(config['db_uri'])
        self.rest_api = CoreRestApi(self.config)
        self.bus = Bus(config)
        auth.set_auth_config(self.config['auth'])
        self.auth_client = AuthClient(**self.config['auth'])
        self.token_renewer = TokenRenewer(self.auth_client)
        self.token_renewer.subscribe_to_token_change(
            self.auth_client.set_token)
        self.status_aggregator = StatusAggregator()
        self._service_registration_params = [
            'wazo-dird',
            self.config.get('uuid'),
            self.config.get('consul'),
            self.config.get('service_discovery'),
            self.config.get('bus'),
            partial(self_check, self.config['rest_api']['https']['port']),
        ]
        self._source_manager = SourceManager(
            self.config['enabled_plugins']['backends'],
            self.config,
            self.auth_client,
            self.token_renewer,
        )

    def run(self):
        self.services = plugin_manager.load_services(
            self.config,
            self.config['enabled_plugins']['services'],
            self._source_manager,
            self.bus,
            self,
        )
        plugin_manager.load_views(
            self.config,
            self.config['enabled_plugins']['views'],
            self.services,
            self.auth_client,
            self.status_aggregator,
        )
        self._source_manager.set_source_service(self.services['source'])
        self.status_aggregator.add_provider(self.bus.provide_status)

        signal.signal(signal.SIGTERM, _signal_handler)
        with self.token_renewer:
            with ServiceCatalogRegistration(
                    *self._service_registration_params):
                self.bus.start()
                try:
                    self.rest_api.run()
                finally:
                    plugin_manager.unload_views()
                    plugin_manager.unload_services()
                    self._source_manager.unload_sources()
                    self.bus.stop()
Esempio n. 5
0
class Controller(object):
    def __init__(self, config):
        auth_config = dict(config['auth'])
        auth_config.pop('key_file', None)
        auth_client = AuthClient(**auth_config)
        cel_fetcher = CELFetcher()
        confd_client = ConfdClient(**config['confd'])
        generator = CallLogsGenerator([
            LocalOriginateCELInterpretor(confd_client),
            DispatchCELInterpretor(CallerCELInterpretor(confd_client),
                                   CalleeCELInterpretor(confd_client))
        ])
        writer = CallLogsWriter()
        self._publisher = BusPublisher(config)
        self.manager = CallLogsManager(cel_fetcher, generator, writer,
                                       self._publisher)
        self.bus_client = BusClient(config)
        self.rest_api = CoreRestApi(config)
        self.token_renewer = TokenRenewer(auth_client)
        self.token_renewer.subscribe_to_token_change(confd_client.set_token)
        self._load_plugins(config)

    def run(self):
        logger.info('Starting wazo-call-logd')
        bus_publisher_thread = Thread(target=self._publisher.run)
        bus_publisher_thread.start()
        bus_consumer_thread = Thread(target=self.bus_client.run,
                                     args=[self.manager],
                                     name='bus_consumer_thread')
        bus_consumer_thread.start()

        try:
            with self.token_renewer:
                self.rest_api.run()
        finally:
            logger.info('Stopping wazo-call-logd')
            self.bus_client.stop()
            self._publisher.stop()
            bus_consumer_thread.join()
            bus_publisher_thread.join()

    def stop(self, reason):
        logger.warning('Stopping wazo-call-logd: %s', reason)
        self.rest_api.stop()

    def _load_plugins(self, global_config):
        load_args = [{
            'api': api,
            'config': global_config,
        }]
        plugin_manager.load_plugins(global_config['enabled_plugins'],
                                    load_args)
Esempio n. 6
0
def _generate_call_logs():
    parser = argparse.ArgumentParser(description='Call logs generator')
    options = parse_args(parser)

    file_config = {
        key: value
        for key, value in read_config_file_hierarchy(DEFAULT_CONFIG).items()
        if key in ('confd', 'bus', 'auth', 'db_uri', 'cel_db_uri')
    }
    key_config = {}
    auth_username = file_config['auth'].get('username')
    auth_password = file_config['auth'].get('password')
    if not (auth_username and auth_password):
        key_config = load_key_file(ChainMap(file_config, DEFAULT_CONFIG))
    config = ChainMap(key_config, file_config, DEFAULT_CONFIG)
    set_xivo_uuid(config, logger)
    init_db_from_config({'db_uri': config['cel_db_uri']})
    DBSession = new_db_session(config['db_uri'])
    CELDBSession = new_db_session(config['cel_db_uri'])
    dao = DAO(DBSession, CELDBSession)

    auth_client = AuthClient(**config['auth'])
    confd_client = ConfdClient(**config['confd'])
    token_renewer = TokenRenewer(auth_client)
    token_renewer.subscribe_to_token_change(confd_client.set_token)

    generator = CallLogsGenerator(
        confd_client,
        [
            LocalOriginateCELInterpretor(),
            DispatchCELInterpretor(CallerCELInterpretor(),
                                   CalleeCELInterpretor()),
        ],
    )
    token_renewer.subscribe_to_next_token_details_change(
        generator.set_default_tenant_uuid)
    writer = CallLogsWriter(dao)
    publisher = BusPublisher(service_uuid=config['uuid'], **config['bus'])
    manager = CallLogsManager(dao, generator, writer, publisher)

    options = vars(options)
    with token_renewer:
        if options.get('action') == 'delete':
            if options.get('all'):
                manager.delete_all()
            elif options.get('days'):
                manager.delete_from_days(options['days'])
        else:
            if options.get('days'):
                manager.generate_from_days(days=options['days'])
            else:
                manager.generate_from_count(cel_count=options['cel_count'])
Esempio n. 7
0
def _generate_call_logs():
    parser = argparse.ArgumentParser(description='Call logs generator')
    options = parse_args(parser)

    file_config = {
        key: value
        for key, value in read_config_file_hierarchy(DEFAULT_CONFIG).items()
        if key in ('confd', 'bus', 'auth', 'db_uri')
    }
    key_config = load_key_file(ChainMap(file_config, DEFAULT_CONFIG))
    config = ChainMap(key_config, file_config, DEFAULT_CONFIG)
    init_db_from_config(config)

    auth_client = AuthClient(**config['auth'])
    confd_client = ConfdClient(**config['confd'])
    token_renewer = TokenRenewer(auth_client)
    token_renewer.subscribe_to_token_change(confd_client.set_token)

    cel_fetcher = CELFetcher()
    generator = CallLogsGenerator(
        confd_client,
        [
            LocalOriginateCELInterpretor(confd_client),
            DispatchCELInterpretor(
                CallerCELInterpretor(confd_client), CalleeCELInterpretor(confd_client)
            ),
        ],
    )
    token_renewer.subscribe_to_next_token_details_change(
        generator.set_default_tenant_uuid
    )
    writer = CallLogsWriter()
    publisher = BusPublisher(config)
    manager = CallLogsManager(cel_fetcher, generator, writer, publisher)

    options = vars(options)
    with token_renewer:
        if options.get('action') == 'delete':
            if options.get('all'):
                manager.delete_all()
            elif options.get('days'):
                manager.delete_from_days(options['days'])
        else:
            if options.get('days'):
                manager.generate_from_days(days=options['days'])
            else:
                manager.generate_from_count(cel_count=options['cel_count'])
Esempio n. 8
0
class TokenRenewerService(Service):
    def __init__(self, prov_service, config):
        self._config = config
        self._prov_service = prov_service

    def startService(self):
        app = self._prov_service.app
        auth_client = auth.get_auth_client(**self._config['auth'])
        amid_client = provd.synchronize.get_AMID_client(**self._config['amid'])
        self._token_renewer = TokenRenewer(auth_client)
        self._token_renewer.subscribe_to_token_change(app.set_token)
        self._token_renewer.subscribe_to_token_change(auth_client.set_token)
        self._token_renewer.subscribe_to_token_change(amid_client.set_token)
        self._token_renewer.start()
        Service.startService(self)

    def stopService(self):
        self._token_renewer.stop()
        Service.stopService(self)
Esempio n. 9
0
class WazoVersionFinder:
    def __init__(self, config):
        self._token = None
        self._config = config
        self._token_renewer = TokenRenewer(AuthClient(**config['auth']))
        self._token_renewer.subscribe_to_token_change(self.set_token)
        self._version = None

    def get_version(self):
        if not self._version:
            self._version = os.getenv(
                'WAZO_VERSION') or self._query_for_version()
        return self._version

    def set_token(self, token):
        self._token = token

    def _query_for_version(self):
        logger.debug('Using the current version from confd')
        with self._token_renewer:
            client = ConfdClient(token=self._token, **self._config['confd'])
            return client.infos()['wazo_version']
Esempio n. 10
0
def main():
    config = _read_config()

    setup_logging(config['log_filename'], debug=config['debug'])

    if 'host' not in config['prov_server']:
        logger.error('error: no provd host specified. Exiting.')
        sys.exit(1)

    user = config['user']
    if user:
        change_user(user)

    auth_client = AuthClient(**config['auth'])
    provd_client = ProvdClient(**config['prov_server'])
    token_renewer = TokenRenewer(auth_client)
    token_renewer.subscribe_to_token_change(provd_client.set_token)
    sink = ProvServerDHCPInfoSink(provd_client)

    with token_renewer:
        try:
            pidfile = PidFile(config['pid_filename'])
            try:
                source = UnixSocketDHCPInfoSource(config['unix_server_addr'], True)
                try:
                    signum = signal.SIGTERM
                    old_handler = signal.signal(signum, _sig_handler)
                    try:
                        agent = Agent(source, sink)
                        agent.run()
                    finally:
                        signal.signal(signum, old_handler)
                finally:
                    source.close()
            finally:
                pidfile.close()
        finally:
            sink.close()
Esempio n. 11
0
def main():
    config = load_config(sys.argv[1:])

    token_renewer = TokenRenewer(_new_auth_client(config), expiration=600)
    agent_client = _new_agent_client(config)

    interpreter = Interpreter(prompt='wazo-agentd-cli> ',
                              history_file='~/.wazo_agentd_cli_history')
    interpreter.add_command('add', AddAgentToQueueCommand(agent_client))
    interpreter.add_command('remove', RemoveAgentFromQueueCommand(agent_client))
    interpreter.add_command('login', LoginCommand(agent_client))
    interpreter.add_command('logoff', LogoffCommand(agent_client))
    interpreter.add_command('relog all', RelogAllCommand(agent_client))
    interpreter.add_command('pause', PauseCommand(agent_client))
    interpreter.add_command('unpause', UnpauseCommand(agent_client))
    interpreter.add_command('status', StatusCommand(agent_client))

    token_renewer.subscribe_to_token_change(agent_client.set_token)
    with token_renewer:
        if config.get('command'):
            interpreter.execute_command_line(config['command'])
        else:
            interpreter.loop()
Esempio n. 12
0
def main():
    cli_config = _parse_args()
    file_config = read_config_file_hierarchy(
        ChainMap(cli_config, _DEFAULT_CONFIG))
    key_config = _load_key_file(
        ChainMap(cli_config, file_config, _DEFAULT_CONFIG))
    config = ChainMap(cli_config, key_config, file_config, _DEFAULT_CONFIG)

    setup_logging(config['logfile'], debug=config['debug'])
    silence_loggers(['urllib3'], logging.WARNING)

    user = config.get('user')
    if user:
        change_user(user)

    xivo_dao.init_db_from_config(config)

    token_renewer = TokenRenewer(AuthClient(**config['auth']))
    config['agentd']['client'] = AgentdClient(**config['agentd'])
    config['calld']['client'] = CalldClient(**config['calld'])
    config['confd']['client'] = ConfdClient(**config['confd'])
    config['dird']['client'] = DirdClient(**config['dird'])
    config['auth']['client'] = AuthClient(**config['auth'])

    def on_token_change(token_id):
        config['agentd']['client'].set_token(token_id)
        config['calld']['client'].set_token(token_id)
        config['confd']['client'].set_token(token_id)
        config['dird']['client'].set_token(token_id)
        config['auth']['client'].set_token(token_id)

    token_renewer.subscribe_to_token_change(on_token_change)

    agid.init(config)
    with token_renewer:
        agid.run()
Esempio n. 13
0
class Controller:
    def __init__(self, config):
        xivo_uuid = get_xivo_uuid(logger)
        auth_config = dict(config['auth'])
        auth_config.pop('key_file', None)
        auth_client = AuthClient(**auth_config)
        self.ari = CoreARI(config['ari'])
        self.bus_publisher = CoreBusPublisher(config)
        self.bus_consumer = CoreBusConsumer(config)
        self.collectd = CoreCollectd(config)
        self.rest_api = CoreRestApi(config)
        self.status_aggregator = StatusAggregator()
        self.token_renewer = TokenRenewer(auth_client)
        self.token_status = TokenStatus()
        self._service_registration_params = [
            'xivo-ctid-ng', xivo_uuid, config['consul'],
            config['service_discovery'], config['bus'],
            partial(self_check, config['rest_api']['port'])
        ]
        plugin_helpers.load(
            namespace='xivo_ctid_ng.plugins',
            names=config['enabled_plugins'],
            dependencies={
                'api':
                api,
                'adapter_api':
                adapter_api,
                'ari':
                self.ari,
                'bus_publisher':
                self.bus_publisher,
                'bus_consumer':
                self.bus_consumer,
                'collectd':
                self.collectd,
                'config':
                config,
                'status_aggregator':
                self.status_aggregator,
                'token_changed_subscribe':
                self.token_renewer.subscribe_to_token_change,
                'next_token_changed_subscribe':
                self.token_renewer.subscribe_to_next_token_change,
            })

    def run(self):
        logger.info('xivo-ctid-ng starting...')
        self.token_renewer.subscribe_to_token_change(
            self.token_status.token_change_callback)
        self.status_aggregator.add_provider(self.ari.provide_status)
        self.status_aggregator.add_provider(self.bus_consumer.provide_status)
        self.status_aggregator.add_provider(self.token_status.provide_status)
        bus_producer_thread = Thread(target=self.bus_publisher.run,
                                     name='bus_producer_thread')
        bus_producer_thread.start()
        collectd_thread = Thread(target=self.collectd.run,
                                 name='collectd_thread')
        collectd_thread.start()
        bus_consumer_thread = Thread(target=self.bus_consumer.run,
                                     name='bus_consumer_thread')
        bus_consumer_thread.start()
        ari_thread = Thread(target=self.ari.run, name='ari_thread')
        ari_thread.start()
        try:
            with self.token_renewer:
                with ServiceCatalogRegistration(
                        *self._service_registration_params):
                    self.rest_api.run()
        finally:
            logger.info('xivo-ctid-ng stopping...')
            self.ari.stop()
            self.bus_consumer.should_stop = True
            self.collectd.stop()
            self.bus_publisher.stop()
            logger.debug('joining ari thread')
            ari_thread.join()
            logger.debug('joining bus consumer thread')
            bus_consumer_thread.join()
            logger.debug('joining collectd thread')
            collectd_thread.join()
            logger.debug('joining bus producer thread')
            bus_producer_thread.join()
            logger.debug('joining rest api threads')
            self.rest_api.join()
            logger.debug('done joining')

    def stop(self, reason):
        logger.warning('Stopping xivo-ctid-ng: %s', reason)
        self.rest_api.stop()
Esempio n. 14
0
class Controller(object):
    def __init__(self, config):
        auth_client = AuthClient(**config['auth'])
        cel_fetcher = CELFetcher()
        confd_client = ConfdClient(**config['confd'])
        generator = CallLogsGenerator(
            confd_client,
            [
                LocalOriginateCELInterpretor(confd_client),
                DispatchCELInterpretor(
                    CallerCELInterpretor(confd_client),
                    CalleeCELInterpretor(confd_client),
                ),
            ],
        )
        writer = CallLogsWriter()
        self.token_renewer = TokenRenewer(auth_client)
        self.token_renewer.subscribe_to_token_change(confd_client.set_token)
        self.token_renewer.subscribe_to_next_token_details_change(
            generator.set_default_tenant_uuid)
        self._publisher = BusPublisher(config)
        self.manager = CallLogsManager(cel_fetcher, generator, writer,
                                       self._publisher)
        self.bus_client = BusClient(config)
        self.rest_api = CoreRestApi(config)
        self.status_aggregator = StatusAggregator()
        self.token_status = TokenStatus()
        plugin_helpers.load(
            namespace='wazo_call_logd.plugins',
            names=config['enabled_plugins'],
            dependencies={
                'api': api,
                'config': config,
                'token_renewer': self.token_renewer,
                'status_aggregator': self.status_aggregator,
            },
        )

    def run(self):
        logger.info('Starting wazo-call-logd')
        self.token_renewer.subscribe_to_token_change(
            self.token_status.token_change_callback)
        self.status_aggregator.add_provider(self.bus_client.provide_status)
        self.status_aggregator.add_provider(self.token_status.provide_status)
        bus_publisher_thread = Thread(target=self._publisher.run)
        bus_publisher_thread.start()
        bus_consumer_thread = Thread(target=self.bus_client.run,
                                     args=[self.manager],
                                     name='bus_consumer_thread')
        bus_consumer_thread.start()

        try:
            with self.token_renewer:
                self.rest_api.run()
        finally:
            logger.info('Stopping wazo-call-logd')
            self.bus_client.stop()
            self._publisher.stop()
            bus_consumer_thread.join()
            bus_publisher_thread.join()

    def stop(self, reason):
        logger.warning('Stopping wazo-call-logd: %s', reason)
        self.rest_api.stop()
Esempio n. 15
0
def _run(config):
    _init_signal()
    xivo_uuid = config['uuid']
    agent_dao = AgentDAOAdapter(orig_agent_dao)
    queue_dao = QueueDAOAdapter(orig_queue_dao)
    exten_features_dao = ExtenFeaturesDAOAdapter(asterisk_conf_dao)
    amid_client = AmidClient(**config['amid'])
    auth_client = AuthClient(**config['auth'])
    token_renewer = TokenRenewer(auth_client)
    token_renewer.subscribe_to_token_change(amid_client.set_token)
    token_renewer.subscribe_to_token_change(auth_client.set_token)

    bus_consumer = BusConsumer(**config['bus'])
    bus_publisher = BusPublisherWithQueue(**config['bus'], service_uuid=xivo_uuid)

    blf_manager = BLFManager(amid_client, exten_features_dao)
    queue_log_manager = QueueLogManager(queue_log_dao)

    add_to_queue_action = AddToQueueAction(amid_client, agent_status_dao)
    login_action = LoginAction(
        amid_client,
        queue_log_manager,
        blf_manager,
        agent_status_dao,
        line_dao,
        user_dao,
        agent_dao,
        bus_publisher,
    )
    pause_action = PauseAction(amid_client)
    pause_manager = PauseManager(pause_action, agent_dao)
    logoff_action = LogoffAction(
        amid_client,
        queue_log_manager,
        blf_manager,
        pause_manager,
        agent_status_dao,
        user_dao,
        agent_dao,
        bus_publisher,
    )
    remove_from_queue_action = RemoveFromQueueAction(amid_client, agent_status_dao)
    update_penalty_action = UpdatePenaltyAction(amid_client, agent_status_dao)

    add_member_manager = AddMemberManager(
        add_to_queue_action, amid_client, agent_status_dao, queue_member_dao
    )
    login_manager = LoginManager(login_action, agent_status_dao, context_dao, line_dao)
    logoff_manager = LogoffManager(logoff_action, agent_dao, agent_status_dao)
    on_agent_deleted_manager = OnAgentDeletedManager(logoff_manager, agent_status_dao)
    on_agent_updated_manager = OnAgentUpdatedManager(
        add_to_queue_action,
        remove_from_queue_action,
        update_penalty_action,
        agent_status_dao,
    )
    on_queue_added_manager = OnQueueAddedManager(add_to_queue_action, agent_status_dao)
    on_queue_deleted_manager = OnQueueDeletedManager(agent_status_dao)
    on_queue_updated_manager = OnQueueUpdatedManager(
        add_to_queue_action, remove_from_queue_action, agent_status_dao
    )
    on_queue_agent_paused_manager = OnQueueAgentPausedManager(
        agent_status_dao, user_dao, agent_dao, bus_publisher
    )
    relog_manager = RelogManager(
        login_action, logoff_action, agent_dao, agent_status_dao
    )
    remove_member_manager = RemoveMemberManager(
        remove_from_queue_action, amid_client, agent_status_dao, queue_member_dao
    )

    service_proxy = ServiceProxy()
    service_proxy.login_handler = LoginHandler(login_manager, agent_dao)
    service_proxy.logoff_handler = LogoffHandler(logoff_manager, agent_status_dao)
    service_proxy.membership_handler = MembershipHandler(
        add_member_manager, remove_member_manager, agent_dao, queue_dao
    )
    service_proxy.on_agent_handler = OnAgentHandler(
        on_agent_deleted_manager, on_agent_updated_manager, agent_dao
    )
    service_proxy.on_queue_handler = OnQueueHandler(
        on_queue_added_manager,
        on_queue_updated_manager,
        on_queue_deleted_manager,
        on_queue_agent_paused_manager,
        queue_dao,
        agent_dao,
    )
    service_proxy.pause_handler = PauseHandler(pause_manager, agent_status_dao)
    service_proxy.relog_handler = RelogHandler(relog_manager)
    service_proxy.status_handler = StatusHandler(agent_dao, agent_status_dao, xivo_uuid)

    _init_bus_consume(bus_consumer, service_proxy)

    http_iface = http.HTTPInterface(config, service_proxy, auth_client)

    service_discovery_args = [
        'wazo-agentd',
        xivo_uuid,
        config['consul'],
        config['service_discovery'],
        config['bus'],
        partial(self_check, config['rest_api']),
    ]
    try:
        with token_renewer:
            with bus_consumer, bus_publisher:
                with ServiceCatalogRegistration(*service_discovery_args):
                    http_iface.run()
    finally:
        logger.info('wazo-agentd stopping...')
Esempio n. 16
0
class Controller:

    def __init__(self, config):
        xivo_uuid = get_xivo_uuid(logger)
        auth_client = AuthClient(**config['auth'])
        self.ari = CoreARI(config['ari'])
        self.asyncio = CoreAsyncio()
        self.bus_consumer = CoreBusConsumer(**config['bus'])
        self.bus_publisher = CoreBusPublisher(service_uuid=config['uuid'], **config['bus'])
        self.collectd = CoreCollectd(config)
        self.http_server = HTTPServer(config)
        self.status_aggregator = StatusAggregator()
        self.token_renewer = TokenRenewer(auth_client)
        self.token_status = TokenStatus()
        self._service_registration_params = ['wazo-calld',
                                             xivo_uuid,
                                             config['consul'],
                                             config['service_discovery'],
                                             config['bus'],
                                             partial(self_check, config)]

        self._pubsub = pubsub.Pubsub()
        plugin_helpers.load(
            namespace='wazo_calld.plugins',
            names=config['enabled_plugins'],
            dependencies={
                'api': api,
                'ari': self.ari,
                'asyncio': self.asyncio,
                'bus_publisher': self.bus_publisher,
                'bus_consumer': self.bus_consumer,
                'collectd': self.collectd,
                'config': config,
                'status_aggregator': self.status_aggregator,
                'pubsub': self._pubsub,
                'token_changed_subscribe': self.token_renewer.subscribe_to_token_change,
                'next_token_changed_subscribe': self.token_renewer.subscribe_to_next_token_change,
            }
        )

        if not config['auth'].get('master_tenant_uuid'):
            self.token_renewer.subscribe_to_next_token_details_change(
                init_master_tenant
            )

    def run(self):
        logger.info('wazo-calld starting...')
        self.token_renewer.subscribe_to_token_change(self.token_status.token_change_callback)
        self.status_aggregator.add_provider(self.ari.provide_status)
        self.status_aggregator.add_provider(self.bus_consumer.provide_status)
        self.status_aggregator.add_provider(self.token_status.provide_status)
        collectd_thread = Thread(target=self.collectd.run, name='collectd_thread')
        collectd_thread.start()
        ari_thread = Thread(target=self.ari.run, name='ari_thread')
        ari_thread.start()
        asyncio_thread = Thread(target=self.asyncio.run, name='asyncio_thread')
        asyncio_thread.start()
        try:
            with self.token_renewer:
                with self.bus_consumer:
                    with ServiceCatalogRegistration(*self._service_registration_params):
                        self.http_server.run()
        finally:
            logger.info('wazo-calld stopping...')
            self._pubsub.publish('stopping', None)
            self.asyncio.stop()
            self.ari.stop()
            self.collectd.stop()
            logger.debug('joining asyncio thread')
            asyncio_thread.join()
            logger.debug('joining ari thread')
            ari_thread.join()
            logger.debug('joining collectd thread')
            collectd_thread.join()
            logger.debug('done joining')

    def stop(self, reason):
        logger.warning('Stopping wazo-calld: %s', reason)
        self.http_server.stop()
Esempio n. 17
0
def _run(config):
    _init_signal()
    xivo_uuid = config['uuid']
    agent_dao = AgentDAOAdapter(orig_agent_dao)
    queue_dao = QueueDAOAdapter(orig_queue_dao)
    auth_client = AuthClient(**config['auth'])
    token_renewer = TokenRenewer(auth_client)
    token_renewer.subscribe_to_token_change(auth_client.set_token)

    with _new_ami_client(config) as ami_client:
        with _new_bus_connection(config) as producer_conn, _new_bus_connection(
                config) as consumer_conn:
            bus_exchange = Exchange(config['bus']['exchange_name'],
                                    type=config['bus']['exchange_type'])
            bus_producer = Producer(producer_conn,
                                    exchange=bus_exchange,
                                    auto_declare=True)
            bus_marshaler = Marshaler(xivo_uuid)
            bus_publisher = Publisher(bus_producer, bus_marshaler)

            queue_log_manager = QueueLogManager(queue_log_dao)

            add_to_queue_action = AddToQueueAction(ami_client,
                                                   agent_status_dao)
            login_action = LoginAction(ami_client, queue_log_manager,
                                       agent_status_dao, line_dao, user_dao,
                                       bus_publisher)
            logoff_action = LogoffAction(ami_client, queue_log_manager,
                                         agent_status_dao, user_dao,
                                         bus_publisher)
            pause_action = PauseAction(ami_client)
            remove_from_queue_action = RemoveFromQueueAction(
                ami_client, agent_status_dao)
            update_penalty_action = UpdatePenaltyAction(
                ami_client, agent_status_dao)

            add_member_manager = AddMemberManager(add_to_queue_action,
                                                  ami_client, agent_status_dao,
                                                  queue_member_dao)
            login_manager = LoginManager(login_action, agent_status_dao,
                                         context_dao)
            logoff_manager = LogoffManager(logoff_action, agent_status_dao)
            on_agent_deleted_manager = OnAgentDeletedManager(
                logoff_manager, agent_status_dao)
            on_agent_updated_manager = OnAgentUpdatedManager(
                add_to_queue_action, remove_from_queue_action,
                update_penalty_action, agent_status_dao)
            on_queue_added_manager = OnQueueAddedManager(
                add_to_queue_action, agent_status_dao)
            on_queue_deleted_manager = OnQueueDeletedManager(agent_status_dao)
            on_queue_updated_manager = OnQueueUpdatedManager(
                add_to_queue_action, remove_from_queue_action,
                agent_status_dao)
            on_queue_agent_paused_manager = OnQueueAgentPausedManager(
                agent_status_dao, user_dao, bus_publisher)
            pause_manager = PauseManager(pause_action)
            relog_manager = RelogManager(login_action, logoff_action,
                                         agent_dao, agent_status_dao)
            remove_member_manager = RemoveMemberManager(
                remove_from_queue_action, ami_client, agent_status_dao,
                queue_member_dao)

            service_proxy = ServiceProxy()
            service_proxy.login_handler = LoginHandler(login_manager,
                                                       agent_dao)
            service_proxy.logoff_handler = LogoffHandler(
                logoff_manager, agent_status_dao)
            service_proxy.membership_handler = MembershipHandler(
                add_member_manager, remove_member_manager, agent_dao,
                queue_dao)
            service_proxy.on_agent_handler = OnAgentHandler(
                on_agent_deleted_manager, on_agent_updated_manager, agent_dao)
            service_proxy.on_queue_handler = OnQueueHandler(
                on_queue_added_manager, on_queue_updated_manager,
                on_queue_deleted_manager, on_queue_agent_paused_manager,
                queue_dao, agent_dao)
            service_proxy.pause_handler = PauseHandler(pause_manager,
                                                       agent_status_dao)
            service_proxy.relog_handler = RelogHandler(relog_manager)
            service_proxy.status_handler = StatusHandler(
                agent_dao, agent_status_dao, xivo_uuid)

            amqp_iface = amqp.AMQPInterface(consumer_conn, bus_exchange,
                                            service_proxy)
            http_iface = http.HTTPInterface(config, service_proxy, auth_client)

            amqp_iface.start()
            try:
                with token_renewer:
                    with ServiceCatalogRegistration(
                            'xivo-agentd', xivo_uuid, config['consul'],
                            config['service_discovery'], config['bus'],
                            partial(self_check,
                                    config['rest_api']['https']['port'])):
                        http_iface.run()
            finally:
                amqp_iface.stop()
Esempio n. 18
0
class Controller:
    def __init__(self, config):
        self.config = config
        DBSession = new_db_session(config['db_uri'])
        CELDBSession = new_db_session(config['cel_db_uri'])
        self.dao = DAO(DBSession, CELDBSession)
        writer = CallLogsWriter(self.dao)

        # NOTE(afournier): it is important to load the tasks before configuring the Celery app
        self.celery_task_manager = plugin_helpers.load(
            namespace='wazo_call_logd.celery_tasks',
            names=config['enabled_celery_tasks'],
            dependencies={
                'config': self.config,
                'dao': self.dao,
                'app': celery.app,
            },
        )
        celery.configure(config)
        self._celery_process = celery.spawn_workers(config)

        auth_client = AuthClient(**config['auth'])
        confd_client = ConfdClient(**config['confd'])
        generator = CallLogsGenerator(
            confd_client,
            [
                LocalOriginateCELInterpretor(),
                DispatchCELInterpretor(
                    CallerCELInterpretor(),
                    CalleeCELInterpretor(),
                ),
            ],
        )
        self.token_renewer = TokenRenewer(auth_client)
        self.token_renewer.subscribe_to_token_change(confd_client.set_token)
        self.token_renewer.subscribe_to_next_token_details_change(
            generator.set_default_tenant_uuid)

        self.bus_publisher = BusPublisher(service_uuid=config['uuid'],
                                          **config['bus'])
        self.bus_consumer = BusConsumer(**config['bus'])
        self.manager = CallLogsManager(self.dao, generator, writer,
                                       self.bus_publisher)

        self._bus_subscribe()

        self.http_server = HTTPServer(config)
        if not app.config['auth'].get('master_tenant_uuid'):
            self.token_renewer.subscribe_to_next_token_details_change(
                init_master_tenant)

        self.status_aggregator = StatusAggregator()
        self.token_status = TokenStatus()
        plugin_helpers.load(
            namespace='wazo_call_logd.plugins',
            names=config['enabled_plugins'],
            dependencies={
                'api': api,
                'config': config,
                'dao': self.dao,
                'token_renewer': self.token_renewer,
                'status_aggregator': self.status_aggregator,
                'bus_publisher': self.bus_publisher,
            },
        )

    def run(self):
        logger.info('Starting wazo-call-logd')
        self.token_renewer.subscribe_to_token_change(
            self.token_status.token_change_callback)
        self.status_aggregator.add_provider(self.bus_consumer.provide_status)
        self.status_aggregator.add_provider(self.token_status.provide_status)
        self.status_aggregator.add_provider(celery.provide_status)
        signal.signal(signal.SIGTERM, partial(_sigterm_handler, self))

        self._update_db_from_config_file()

        try:
            with self.bus_consumer:
                with self.token_renewer:
                    self.http_server.run()
        finally:
            logger.info('Stopping wazo-call-logd')
            self._celery_process.terminate()
            self._celery_process.join()

    def stop(self, reason):
        logger.warning('Stopping wazo-call-logd: %s', reason)
        self.http_server.stop()

    def _update_db_from_config_file(self):
        with self.dao.helper.db_ready():
            config = self.dao.config.find_or_create()
            cdr_days = self.config['retention']['cdr_days']
            if cdr_days is not None:
                config.retention_cdr_days = cdr_days
                config.retention_cdr_days_from_file = True
            else:
                config.retention_cdr_days_from_file = False
            export_days = self.config['retention']['export_days']
            if export_days is not None:
                config.retention_export_days = export_days
                config.retention_export_days_from_file = True
            else:
                config.retention_export_days_from_file = False
            recording_days = self.config['retention']['recording_days']
            if recording_days is not None:
                config.retention_recording_days = recording_days
                config.retention_recording_days_from_file = True
            else:
                config.retention_recording_days_from_file = False
            self.dao.config.update(config)

    def _bus_subscribe(self):
        self.bus_consumer.subscribe('CEL', self._handle_linked_id_end)

    def _handle_linked_id_end(self, payload):
        if payload['EventName'] != 'LINKEDID_END':
            return

        linked_id = payload['LinkedID']
        try:
            self.manager.generate_from_linked_id(linked_id)
        except Exception:
            logger.exception(
                'Failed to genereate call log for linked id=\"%s\"', linked_id)
Esempio n. 19
0
    _CONFIG['provd']['port'] = int(opts.port)
if opts.prefix is not None:
    _CONFIG['provd']['prefix'] = int(opts.prefix)
if opts.https is not None:
    _CONFIG['provd']['https'] = _bool(opts.https)
if opts.verify is not None:
    _CONFIG['provd']['verify_certificate'] = _bool(opts.verify)

# # create client object
client = cli_client.new_cli_provisioning_client(_CONFIG['provd'])

# read key from key file and setup token renewer
key_file = parse_config_file(_CONFIG['auth'].pop('key_file'))
auth_client = AuthClient(username=key_file['service_id'], password=key_file['service_key'], **_CONFIG['auth'])
token_renewer = TokenRenewer(auth_client, expiration=600)
token_renewer.subscribe_to_token_change(client.prov_client.set_token)


configs = client.configs()
devices = client.devices()
plugins = client.plugins()
parameters = client.parameters()


# create help
RAW_HELP_MAP = {
    None: """\
\x1b[1mDescription\x1b[0m
    You can interact with the provd server through 3 top-level objects:
        configs
        devices
Esempio n. 20
0
class Controller:
    def __init__(self, config):
        self.config = config
        init_db(config['db_uri'])
        self.rest_api = CoreRestApi(self.config)
        self.bus = CoreBus(service_uuid=self.config.get('uuid'),
                           **self.config['bus'])
        auth.set_auth_config(self.config['auth'])
        self.auth_client = AuthClient(**self.config['auth'])
        self.token_renewer = TokenRenewer(self.auth_client)
        if not self.config['auth'].get('master_tenant_uuid'):
            self.token_renewer.subscribe_to_next_token_details_change(
                auth.init_master_tenant)
        self.token_renewer.subscribe_to_token_change(
            self.auth_client.set_token)
        self.status_aggregator = StatusAggregator()
        self.status_aggregator.add_provider(auth.provide_status)
        self._service_registration_params = [
            'wazo-dird',
            self.config.get('uuid'),
            self.config.get('consul'),
            self.config.get('service_discovery'),
            self.config.get('bus'),
            partial(self_check, self.config['rest_api']['port']),
        ]
        self._source_manager = SourceManager(
            self.config['enabled_plugins']['backends'],
            self.config,
            self.auth_client,
            self.token_renewer,
        )

    def run(self):
        signal.signal(signal.SIGTERM, partial(_sigterm_handler, self))
        self.services = plugin_manager.load_services(
            self.config,
            self.config['enabled_plugins']['services'],
            self._source_manager,
            self.bus,
            self,
        )
        plugin_manager.load_views(
            self.config,
            self.config['enabled_plugins']['views'],
            self.services,
            self.auth_client,
            self.status_aggregator,
            self.rest_api,
        )
        self._source_manager.set_source_service(self.services['source'])
        self.status_aggregator.add_provider(self.bus.provide_status)

        with self.token_renewer:
            with self.bus:
                with ServiceCatalogRegistration(
                        *self._service_registration_params):
                    try:
                        self.rest_api.run()
                    finally:
                        plugin_manager.unload_views()
                        plugin_manager.unload_services()
                        self._source_manager.unload_sources()

    def stop(self, reason):
        logger.warning('Stopping wazo-dird: %s', reason)
        self.rest_api.stop()