コード例 #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)
コード例 #2
0
ファイル: plugin.py プロジェクト: sileht/xivo-ctid-ng
    def load(self, dependencies):
        api = dependencies['api']
        ari = dependencies['ari']
        bus_consumer = dependencies['bus_consumer']
        bus_publisher = dependencies['bus_publisher']
        collectd = dependencies['collectd']
        token_changed_subscribe = dependencies['token_changed_subscribe']
        config = dependencies['config']

        amid_client = AmidClient(**config['amid'])
        token_changed_subscribe(amid_client.set_token)

        auth_client = AuthClient(**config['auth'])
        confd_client = ConfdClient(**config['confd'])

        token_changed_subscribe(confd_client.set_token)

        dial_echo_manager = DialEchoManager()

        calls_service = CallsService(amid_client, config['ari']['connection'], ari.client, confd_client, dial_echo_manager)

        ari.register_application(DEFAULT_APPLICATION_NAME)
        calls_stasis = CallsStasis(ari.client, collectd, bus_publisher, calls_service, config['uuid'], amid_client)
        calls_stasis.subscribe()

        calls_bus_event_handler = CallsBusEventHandler(amid_client, ari.client, collectd, bus_publisher, calls_service, config['uuid'], dial_echo_manager)
        calls_bus_event_handler.subscribe(bus_consumer)

        api.add_resource(CallsResource, '/calls', resource_class_args=[calls_service])
        api.add_resource(MyCallsResource, '/users/me/calls', resource_class_args=[auth_client, calls_service])
        api.add_resource(CallResource, '/calls/<call_id>', resource_class_args=[calls_service])
        api.add_resource(MyCallResource, '/users/me/calls/<call_id>', resource_class_args=[auth_client, calls_service])
        api.add_resource(ConnectCallToUserResource, '/calls/<call_id>/user/<user_uuid>', resource_class_args=[calls_service])
コード例 #3
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'])
コード例 #4
0
def get_confd_client():
    client = g.get('confd_client')
    if not client:
        client = g.confd_client = ConfdClient(**app.config['confd'])
        token = current_user.get_id()
        client.set_token(token)
    return client
コード例 #5
0
ファイル: manager.py プロジェクト: wazo-platform/xivo-ctid
 def _async_set_forward(self, user_uuid, auth_token, forward, enabled,
                        destination):
     client = ConfdClient(token=auth_token, **config['confd'])
     self._runner.run(client.users(user_uuid).update_forward,
                      forward_name=forward,
                      forward={
                          'enabled': enabled,
                          'destination': destination
                      })
コード例 #6
0
ファイル: plugin.py プロジェクト: sileht/xivo-ctid-ng
    def load(self, dependencies):
        api = dependencies['api']
        ari = dependencies['ari']
        bus_consumer = dependencies['bus_consumer']
        bus_publisher = dependencies['bus_publisher']
        config = dependencies['config']
        status_aggregator = dependencies['status_aggregator']
        token_changed_subscribe = dependencies['token_changed_subscribe']

        auth_client = AuthClient(**config['auth'])
        confd_client = ConfdClient(**config['confd'])

        token_changed_subscribe(confd_client.set_token)

        voicemail_storage = new_filesystem_storage()
        self._voicemail_cache = new_cache(voicemail_storage)
        try:
            self._voicemail_cache.refresh_cache()
        except Exception:
            logger.exception('fail to refresh voicemail cache')
        voicemails_service = VoicemailsService(ari.client, confd_client,
                                               voicemail_storage)

        voicemails_bus_event_handler = VoicemailsBusEventHandler(
            confd_client, bus_publisher, self._voicemail_cache)
        voicemails_bus_event_handler.subscribe(bus_consumer)

        status_aggregator.add_provider(self._provide_status)

        api.add_resource(VoicemailResource,
                         '/voicemails/<voicemail_id>',
                         resource_class_args=[voicemails_service])
        api.add_resource(VoicemailFolderResource,
                         '/voicemails/<voicemail_id>/folders/<folder_id>',
                         resource_class_args=[voicemails_service])
        api.add_resource(VoicemailMessageResource,
                         '/voicemails/<voicemail_id>/messages/<message_id>',
                         resource_class_args=[voicemails_service])
        api.add_resource(
            VoicemailRecordingResource,
            '/voicemails/<voicemail_id>/messages/<message_id>/recording',
            resource_class_args=[voicemails_service])
        api.add_resource(UserVoicemailResource,
                         '/users/me/voicemails',
                         resource_class_args=[auth_client, voicemails_service])
        api.add_resource(UserVoicemailFolderResource,
                         '/users/me/voicemails/folders/<folder_id>',
                         resource_class_args=[auth_client, voicemails_service])
        api.add_resource(UserVoicemailMessageResource,
                         '/users/me/voicemails/messages/<message_id>',
                         resource_class_args=[auth_client, voicemails_service])
        api.add_resource(
            UserVoicemailRecordingResource,
            '/users/me/voicemails/messages/<message_id>/recording',
            resource_class_args=[auth_client, voicemails_service])
コード例 #7
0
def _auto_create_config():
    config = _load_config()
    auth_client = AuthClient(**config['auth'])
    token = auth_client.token.new('wazo_user', expiration=36000)['token']
    auth_client.set_token(token)
    confd_client = ConfdClient(token=token, **config['confd'])

    tenants = auth_client.tenants.list()['items']

    base_url = 'https://{host}:{port}/{version}'.format(**config['dird'])
    profiles_url = '{}/profiles'.format(base_url)
    conference_url = '{}/backends/conference/sources'.format(base_url)
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Auth-Token': token,
    }
    for tenant in tenants:
        name = tenant['name']
        if name == 'master':
            continue

        headers['Wazo-Tenant'] = tenant['uuid']

        conference_body = dict(name='auto_conference_{}'.format(name),
                               **CONFERENCE_SOURCE_BODY)
        conference = requests.post(
            conference_url,
            headers=headers,
            json=conference_body,
            verify=config['dird']['verify_certificate'],
        ).json()

        response = requests.get(
            profiles_url,
            headers={
                'Accept': 'application/json',
                'X-Auth-Token': token,
                'Wazo-Tenant': tenant['uuid'],
            },
            verify=config['dird']['verify_certificate'],
        ).json()

        for profile in response['items']:
            profile['services']['lookup']['sources'].append(conference)
            profile['services']['favorites']['sources'].append(conference)
            requests.put(
                '{}/{}'.format(profiles_url, profile['uuid']),
                json=profile,
                headers=headers,
                verify=config['dird']['verify_certificate'],
            )
コード例 #8
0
    def load(self, dependencies):
        api = dependencies['api']
        ari = dependencies['ari']
        bus_publisher = dependencies['bus_publisher']
        config = dependencies['config']
        token_changed_subscribe = dependencies['token_changed_subscribe']

        amid_client = AmidClient(**config['amid'])
        auth_client = AuthClient(**config['auth'])
        confd_client = ConfdClient(**config['confd'])

        token_changed_subscribe(amid_client.set_token)
        token_changed_subscribe(confd_client.set_token)

        state_persistor = StatePersistor(ari.client)
        transfer_lock = TransferLock()

        transfers_service = TransfersService(amid_client, ari.client,
                                             confd_client, state_factory,
                                             state_persistor, transfer_lock)

        ari.register_application(DEFAULT_APPLICATION_NAME)
        transfers_stasis = TransfersStasis(amid_client, ari.client,
                                           transfers_service, state_factory,
                                           state_persistor, config['uuid'])
        transfers_stasis.subscribe()

        notifier = TransferNotifier(bus_publisher)

        state_factory.set_dependencies(amid_client, ari.client, notifier,
                                       transfers_service, state_persistor,
                                       transfer_lock)

        api.add_resource(TransfersResource,
                         '/transfers',
                         resource_class_args=[transfers_service])
        api.add_resource(TransferResource,
                         '/transfers/<transfer_id>',
                         resource_class_args=[transfers_service])
        api.add_resource(TransferCompleteResource,
                         '/transfers/<transfer_id>/complete',
                         resource_class_args=[transfers_service])
        api.add_resource(UserTransfersResource,
                         '/users/me/transfers',
                         resource_class_args=[auth_client, transfers_service])
        api.add_resource(UserTransferResource,
                         '/users/me/transfers/<transfer_id>',
                         resource_class_args=[auth_client, transfers_service])
        api.add_resource(UserTransferCompleteResource,
                         '/users/me/transfers/<transfer_id>/complete',
                         resource_class_args=[auth_client, transfers_service])
コード例 #9
0
    def get_acl_metadata(self, **kwargs):
        local_token_renewer = self._config.get('local_token_renewer')
        if not local_token_renewer:
            logger.info('no local token renewer')
            return {}

        token = local_token_renewer.get_token()
        if not token:
            logger.info('cannot create local token')
            return {}

        confd_client = ConfdClient(token=token, **self._confd_config)
        user_uuid = kwargs.get('uuid')
        if not user_uuid:
            return {}

        try:
            user = confd_client.users.get(user_uuid)
        except HTTPError:
            return {}

        voicemail = user.get('voicemail')
        voicemails = [voicemail['id']] if voicemail else []
        lines, sip, sccp, custom, extensions = [], [], [], [], []
        for line in user['lines']:
            lines.append(line['id'])
            endpoint_custom = line.get('endpoint_custom')
            endpoint_sip = line.get('endpoint_sip')
            endpoint_sccp = line.get('endpoint_sccp')
            if endpoint_custom:
                custom.append(endpoint_custom['id'])
            elif endpoint_sip:
                sip.append(endpoint_sip['id'])
            elif endpoint_sccp:
                sccp.append(endpoint_sccp['id'])
            for extension in line['extensions']:
                extensions.append(extension['id'])
        return {
            'id': user['id'],
            'uuid': user['uuid'],
            'tenant_uuid': user['tenant_uuid'],
            'voicemails': voicemails,
            'lines': lines,
            'extensions': extensions,
            'endpoint_sip': sip,
            'endpoint_sccp': sccp,
            'endpoint_custom': custom,
            'agent': user['agent'],
        }
コード例 #10
0
    def load(self, dependencies):
        api = dependencies['api']
        ari = dependencies['ari']
        bus_publisher = dependencies['bus_publisher']
        config = dependencies['config']
        token_changed_subscribe = dependencies['token_changed_subscribe']

        auth_client = AuthClient(**config['auth'])
        confd_client = ConfdClient(**config['confd'])

        token_changed_subscribe(auth_client.set_token)
        token_changed_subscribe(confd_client.set_token)

        switchboards_notifier = SwitchboardsNotifier(bus_publisher)
        switchboards_service = SwitchboardsService(ari.client, confd_client, switchboards_notifier)

        ari.register_application(DEFAULT_APPLICATION_NAME)
        switchboards_stasis = SwitchboardsStasis(ari.client, confd_client, switchboards_notifier, switchboards_service)
        switchboards_stasis.subscribe()

        api.add_resource(
            SwitchboardCallsQueuedResource,
            '/switchboards/<switchboard_uuid>/calls/queued',
            resource_class_args=[switchboards_service],
        )
        api.add_resource(
            SwitchboardCallQueuedAnswerResource,
            '/switchboards/<switchboard_uuid>/calls/queued/<call_id>/answer',
            resource_class_args=[auth_client, switchboards_service],
        )
        api.add_resource(
            SwitchboardCallsHeldResource,
            '/switchboards/<switchboard_uuid>/calls/held',
            resource_class_args=[switchboards_service],
        )
        api.add_resource(
            SwitchboardCallHeldResource,
            '/switchboards/<switchboard_uuid>/calls/held/<call_id>',
            resource_class_args=[switchboards_service],
        )
        api.add_resource(
            SwitchboardCallHeldAnswerResource,
            '/switchboards/<switchboard_uuid>/calls/held/<call_id>/answer',
            resource_class_args=[auth_client, switchboards_service],
        )
コード例 #11
0
    def load(self, dependencies):
        api = dependencies['api']
        bus_consumer = dependencies['bus_consumer']
        bus_publisher = dependencies['bus_publisher']
        config = dependencies['config']
        token_changed_subscribe = dependencies['token_changed_subscribe']

        amid_client = AmidClient(**config['amid'])
        confd_client = ConfdClient(**config['confd'])

        token_changed_subscribe(amid_client.set_token)
        token_changed_subscribe(confd_client.set_token)

        notifier = ConferencesNotifier(bus_publisher)
        bus_event_handler = ConferencesBusEventHandler(notifier)
        bus_event_handler.subscribe(bus_consumer)
        conferences_service = ConferencesService(amid_client, confd_client)

        api.add_resource(ParticipantsResource, '/conferences/<int:conference_id>/participants', resource_class_args=[conferences_service])
コード例 #12
0
def main():
    auth_client = AuthClient(HOST, username=USERNAME, password=PASSWORD, verify_certificate=False)
    token = auth_client.token.new(AUTH_BACKEND, expiration=TOKEN_EXPIRATION)['token']
    confd_client = ConfdClient(HOST, token=token, verify_certificate=False)
    for i in range(N):
        user_data = dict(
            firstname=' '.join([FIRSTNAME_PREFIX, str(i)]),
        )
        exten_data = dict(
            exten=str(FIRST_EXTEN + i),
            context=CONTEXT,
        )

        print('Creating ', user_data, '...')
        user = confd_client.users.create(user_data)
        exten = confd_client.extensions.create(exten_data)
        line = confd_client.lines_sip.create({'context': CONTEXT})

        confd_client.users(user).add_line(line)
        confd_client.lines(line).add_extension(exten)
コード例 #13
0
 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)
コード例 #14
0
def migrate_tenants():
    config = _load_config()
    _wait_for_provd(config['provd'])

    auth_client = AuthClient(**config['auth'])
    token = auth_client.token.new('wazo_user', expiration=5*60)
    auth_client.set_token(token['token'])
    confd = ConfdClient(token=token['token'], **config['confd'])

    master_tenant_uuid = token['metadata']['tenant_uuid']

    # Migrate associated devices
    devices_migrated = []
    lines = confd.lines.list(recurse=True)['items']
    for line in lines:
        device_id = line['device_id']

        if device_id and device_id not in devices_migrated:
            try:
                _migrate_device(device_id, line['tenant_uuid'])
            except json.JSONDecodeError:
                print(device_id, 'is not a valid JSON file. Skipping.')
                continue
            except IOError as e:
                print('Skipping device "{}": {}'.format(device_id, e))
                continue
            devices_migrated.append(device_id)

    # Migrate autoprov devices
    for dir_entry in os.scandir(PROVD_JSONDB_DEVICES_DIR):
        device_id = dir_entry.name
        if device_id not in devices_migrated:
            try:
                _migrate_device(device_id, master_tenant_uuid)
            except json.JSONDecodeError:
                print(device_id, 'is not a valid JSON file. Skipping.')
                continue

    subprocess.run(['systemctl', 'restart', 'xivo-provd'])
コード例 #15
0
ファイル: plugin.py プロジェクト: sileht/xivo-ctid-ng
    def load(self, dependencies):
        api = dependencies['api']
        ari = dependencies['ari']
        bus_publisher = dependencies['bus_publisher']
        config = dependencies['config']
        token_changed_subscribe = dependencies['token_changed_subscribe']

        amid_client = AmidClient(**config['amid'])
        auth_client = AuthClient(**config['auth'])
        confd_client = ConfdClient(**config['confd'])

        token_changed_subscribe(amid_client.set_token)
        token_changed_subscribe(confd_client.set_token)

        relocates = RelocateCollection()
        state_factory = StateFactory(state_index, amid_client, ari.client)

        notifier = RelocatesNotifier(bus_publisher)
        relocates_service = RelocatesService(amid_client, ari.client,
                                             confd_client, notifier, relocates,
                                             state_factory)

        ari.register_application(DEFAULT_APPLICATION_NAME)
        relocates_stasis = RelocatesStasis(ari.client, relocates)
        relocates_stasis.subscribe()

        api.add_resource(UserRelocatesResource,
                         '/users/me/relocates',
                         resource_class_args=[auth_client, relocates_service])
        api.add_resource(UserRelocateResource,
                         '/users/me/relocates/<relocate_uuid>',
                         resource_class_args=[auth_client, relocates_service])
        api.add_resource(UserRelocateCompleteResource,
                         '/users/me/relocates/<relocate_uuid>/complete',
                         resource_class_args=[auth_client, relocates_service])
        api.add_resource(UserRelocateCancelResource,
                         '/users/me/relocates/<relocate_uuid>/cancel',
                         resource_class_args=[auth_client, relocates_service])
コード例 #16
0
ファイル: manager.py プロジェクト: wazo-platform/xivo-ctid
 def _async_set_service(self, user_uuid, auth_token, service, enabled):
     client = ConfdClient(token=auth_token, **config['confd'])
     self._runner.run(client.users(user_uuid).update_service,
                      service_name=service,
                      service={'enabled': enabled})
コード例 #17
0
ファイル: plugin.py プロジェクト: sileht/xivo-ctid-ng
    def load(self, dependencies):
        api = dependencies['api']
        ari = dependencies['ari']
        config = dependencies['config']
        bus_publisher = dependencies['bus_publisher']
        config = dependencies['config']
        token_changed_subscribe = dependencies['token_changed_subscribe']
        next_token_changed_subscribe = dependencies[
            'next_token_changed_subscribe']

        auth_client = AuthClient(**config['auth'])
        confd_client = ConfdClient(**config['confd'])
        amid_client = AmidClient(**config['amid'])

        token_changed_subscribe(amid_client.set_token)
        token_changed_subscribe(auth_client.set_token)
        token_changed_subscribe(confd_client.set_token)

        notifier = ApplicationNotifier(bus_publisher)
        service = ApplicationService(ari.client, confd_client, amid_client,
                                     notifier)

        stasis = ApplicationStasis(ari, confd_client, service, notifier)
        next_token_changed_subscribe(stasis.initialize)

        api.add_resource(
            ApplicationItem,
            '/applications/<uuid:application_uuid>',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallList,
            '/applications/<uuid:application_uuid>/calls',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallItem,
            '/applications/<uuid:application_uuid>/calls/<call_id>',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallHoldStartList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/hold/start',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallHoldStopList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/hold/stop',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallMohStopList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/moh/stop',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallMohStartList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/moh/<uuid:moh_uuid>/start',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallMuteStartList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/mute/start',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallMuteStopList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/mute/stop',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallPlaybackList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/playbacks',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationCallSnoopList,
            '/applications/<uuid:application_uuid>/calls/<call_id>/snoops',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationNodeList,
            '/applications/<uuid:application_uuid>/nodes',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationNodeItem,
            '/applications/<uuid:application_uuid>/nodes/<uuid:node_uuid>',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationNodeCallList,
            '/applications/<uuid:application_uuid>/nodes/<uuid:node_uuid>/calls',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationNodeCallItem,
            '/applications/<uuid:application_uuid>/nodes/<uuid:node_uuid>/calls/<call_id>',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationPlaybackItem,
            '/applications/<uuid:application_uuid>/playbacks/<uuid:playback_uuid>',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationSnoopList,
            '/applications/<uuid:application_uuid>/snoops',
            resource_class_args=[service],
        )
        api.add_resource(
            ApplicationSnoopItem,
            '/applications/<uuid:application_uuid>/snoops/<uuid:snoop_uuid>',
            resource_class_args=[service],
        )
コード例 #18
0
def setup(xivo_uuid):
    auth_client = new_auth_client()

    bus_url = 'amqp://{username}:{password}@{host}:{port}//'.format(**config['bus'])
    bus_connection = Connection(bus_url)
    bus_exchange = Exchange(config['bus']['exchange_name'],
                            type=config['bus']['exchange_type'])
    bus_producer = Producer(bus_connection, exchange=bus_exchange, auto_declare=True)
    bus_marshaler = Marshaler(xivo_uuid)
    bus_publisher = Publisher(bus_producer, bus_marshaler)
    bus_listener = BusListener(bus_connection, bus_exchange)

    same_exchange_arguments_as_collectd = {'arguments': {'auto_delete': True}, 'durable': False}
    collectd_exchange = Exchange('collectd', type=config['bus']['exchange_type'], **same_exchange_arguments_as_collectd)
    collectd_producer = Producer(bus_connection, exchange=collectd_exchange, auto_declare=True)
    collectd_marshaler = CollectdMarshaler(xivo_uuid)
    collectd_publisher = Publisher(collectd_producer, collectd_marshaler)

    remote_service_tracker = RemoteServiceTracker(config['consul'],
                                                  xivo_uuid,
                                                  config['rest_api']['http']['port'])

    thread_pool_executor = futures.ThreadPoolExecutor(max_workers=10)

    context.register('ami_18', AMI_1_8)
    context.register('ami_callback_handler', AMICallbackHandler.get_instance())
    context.register('ami_class', AMIClass)
    context.register('agent_availability_computer', AgentAvailabilityComputer)
    context.register('agent_availability_notifier', AgentAvailabilityNotifier)
    context.register('agent_availability_updater', AgentAvailabilityUpdater)
    context.register('agent_executor', AgentExecutor)
    context.register('agent_service_cti_parser', AgentServiceCTIParser)
    context.register('agent_service_manager', AgentServiceManager)
    context.register('agent_status_adapter', AgentStatusAdapter)
    context.register('agent_status_manager', AgentStatusManager)
    context.register('agent_status_parser', AgentStatusParser)
    context.register('agent_status_router', AgentStatusRouter)
    context.register('async_runner', AsyncRunner)
    context.register('agentd_client', AgentdClient(**config['agentd']))
    context.register('bridge_manager', BridgeManager)
    context.register('bridge_updater', BridgeUpdater)
    context.register('bridge_notifier', BridgeNotifier)
    context.register('bus_connection', bus_connection)
    context.register('bus_exchange', lambda: bus_exchange)
    context.register('bus_listener', bus_listener)
    context.register('bus_publisher', bus_publisher)
    context.register('broadcast_cti_group', new_broadcast_cti_group)
    context.register('cache_updater', CacheUpdater)
    context.register('call_form_dispatch_filter', DispatchFilter)
    context.register('call_form_result_handler', CallFormResultHandler)
    context.register('call_form_variable_aggregator', VariableAggregator)
    context.register('call_pickup_tracker', CallPickupTracker)
    context.register('call_notifier', CallNotifier)
    context.register('call_receiver', CallReceiver)
    context.register('call_storage', CallStorage)
    context.register('call_manager', CallManager)
    context.register('chat_publisher', ChatPublisher)
    context.register('channel_updater', ChannelUpdater)
    context.register('collectd_publisher', collectd_publisher)
    context.register('confd_client', ConfdClient(**config['confd']))
    context.register('cti_group_factory', CTIGroupFactory)
    context.register('cti_msg_codec', CTIMessageCodec)
    context.register('cti_provd_client', CTIProvdClient.new_from_config(config['provd']))
    context.register('cti_server', CTIServer)
    context.register('current_call_formatter', CurrentCallFormatter)
    context.register('current_call_manager', CurrentCallManager)
    context.register('current_call_notifier', CurrentCallNotifier)
    context.register('current_call_parser', CurrentCallParser)
    context.register('delta_computer', DeltaComputer)
    context.register('device_manager', DeviceManager)
    context.register('endpoint_status_notifier', EndpointStatusNotifier)
    context.register('endpoint_status_updater', EndpointStatusUpdater)
    context.register('endpoint_notifier', EndpointNotifier)
    context.register('flusher', Flusher)
    context.register('funckey_manager', FunckeyManager)
    context.register('innerdata', Safe)
    context.register('interface_ami', AMI)
    context.register('main_thread_proxy', MainThreadProxy)
    context.register('meetme_service_manager', MeetmeServiceManager)
    context.register('meetme_service_notifier', MeetmeServiceNotifier)
    context.register('people_cti_adapter', PeopleCTIAdapter)
    context.register('old_protocol_cti_adapter', OldProtocolCTIAdapter)
    context.register('presence_service_executor', PresenceServiceExecutor)
    context.register('presence_service_manager', PresenceServiceManager)
    context.register('pubsub', Pubsub)
    context.register('queue_entry_encoder', QueueEntryEncoder)
    context.register('queue_entry_manager', QueueEntryManager)
    context.register('queue_entry_notifier', QueueEntryNotifier)
    context.register('queue_statistics_manager', QueueStatisticsManager)
    context.register('queue_statistics_producer', QueueStatisticsProducer)
    context.register('queue_member_cti_subscriber', QueueMemberCTISubscriber)
    context.register('queue_member_cti_adapter', QueueMemberCTIAdapter)
    context.register('queue_member_indexer', QueueMemberIndexer)
    context.register('queue_member_manager', QueueMemberManager)
    context.register('queue_member_notifier', QueueMemberNotifier)
    context.register('queue_member_updater', QueueMemberUpdater)
    context.register('remote_service_tracker', remote_service_tracker)
    context.register('statistics_notifier', StatisticsNotifier)
    context.register('statistics_producer_initializer', StatisticsProducerInitializer)
    context.register('status_forwarder', StatusForwarder)
    context.register('task_queue', new_task_queue)
    context.register('task_scheduler', new_task_scheduler)
    context.register('token_renewer', TokenRenewer(auth_client))
    context.register('thread_pool_executor', thread_pool_executor)
    context.register('user_service_manager', UserServiceManager)
    context.register('user_service_notifier', UserServiceNotifier)
    context.register('xivo_uuid', lambda: xivo_uuid)
コード例 #19
0
def _auto_create_config():
    config = _load_config()
    auth_client = AuthClient(**config['auth'])
    token = auth_client.token.new('wazo_user', expiration=36000)['token']
    auth_client.set_token(token)
    confd_client = ConfdClient(token=token, **config['confd'])

    tenants = auth_client.tenants.list()['items']

    base_url = 'https://{host}:{port}/{version}'.format(**config['dird'])
    profiles_url = '{}/profiles'.format(base_url)
    displays_url = '{}/displays'.format(base_url)
    personal_url = '{}/backends/personal/sources'.format(base_url)
    wazo_url = '{}/backends/wazo/sources'.format(base_url)
    office365_url = '{}/backends/office365/sources'.format(base_url)
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Auth-Token': token,
    }
    for tenant in tenants:
        name = tenant['name']
        if name == 'master':
            continue

        headers['Wazo-Tenant'] = tenant['uuid']

        def post(*args, **kwargs):
            return requests.post(*args,
                                 headers=headers,
                                 verify=config['dird']['verify_certificate'],
                                 **kwargs)

        personal_body = PERSONAL_SOURCE_BODY
        personal = post(personal_url, json=personal_body)
        if personal.status_code == 409:
            # Default configuration already exists
            return

        wazo_body = dict(name='auto_wazo_{}'.format(name), **WAZO_SOURCE_BODY)
        wazo = post(wazo_url, json=wazo_body)

        sources = [personal.json(), wazo.json()]

        # add office365 is the plugin is installed
        office365_body = dict(name='auto_office365_{}'.format(name),
                              **OFFICE_365_SOURCE_BODY)
        office365 = post(office365_url, json=office365_body)
        if office365.status_code == 201:
            sources.append(office365)

        display_body = {
            'name': 'auto_{}'.format(name),
            'columns': DEFAULT_DISPLAY_COLUMNS,
        }
        display = post(displays_url, json=display_body).json()

        contexts = confd_client.contexts.list(
            tenant_uuid=tenant['uuid'])['items']
        for context in contexts:
            if context['type'] != 'internal':
                continue

            profile_body = {
                'name': context['name'],
                'display': display,
                'services': {
                    'lookup': {
                        'sources': sources
                    },
                    'favorites': {
                        'sources': sources
                    },
                    'reverse': {
                        'sources': sources,
                        'timeout': 0.5
                    },
                },
            }
            post(profiles_url, json=profile_body)