def load(self, dependencies): api = dependencies['api'] ari = dependencies['ari'] 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 = FaxesNotifier(bus_publisher) fax_service = FaxesService(amid_client, ari.client, confd_client, notifier) bus_event_handler = FaxesBusEventHandler(notifier) bus_event_handler.subscribe(bus_consumer) api.add_resource(FaxesResource, '/faxes', resource_class_args=[fax_service]) api.add_resource(UserFaxesResource, '/users/me/faxes', resource_class_args=[fax_service])
def migrate_tenants(): config = _load_config() auth_client = AuthClient(**config['auth']) token = auth_client.token.new(expiration=5 * 60)['token'] auth_client.set_token(token) confd = ConfdClient(token=token, **config['confd']) body = { 'contexts': [ {"context": context['name'], "tenant_uuid": context['tenant_uuid']} for context in confd.contexts.list(recurse=True)["items"] ] } with _migration_plugin(config['call_logd']): url = 'https://{host}:{port}/{version}/tenant-migration'.format(**config['call_logd']) result = requests.post( url, data=json.dumps(body), headers={'X-Auth-Token': token, 'Content-Type': 'application/json'}, verify=False, ) if result.status_code != 200: print( 'call_logd tenant migration failed, status-code {}:\n' '{}\ncheck /var/log/wazo-call-logd.log for more info' .format(result.status_code, result.text) ) sys.exit(2)
def test_csv_import(): auth_client = AuthClient( constants.HOST, verify_certificate=False, username='******', password='******', ) token_data = auth_client.token.new(expiration=300) token = token_data['token'] auth_client.set_token(token) client = ConfdClient( constants.HOST, verify_certificate=False, token=token, ) start = datetime.now() result = upload_csv(client, token_data['metadata']['tenant_uuid']) stop = datetime.now() assert 'created' in result, 'Result should contains the created users:\n{}'.format(result) assert len(result['created']) == 100, 'Should have created 100 users\n{}'.format(result) assert stop - start <= MAX_TIME, "CSV import exceeded max time ({})".format(MAX_TIME) # NOTE(fblackburn): wait until pjsip reload complete before starting next test time.sleep(5)
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])
def load(self, dependencies): app = dependencies['app'] api = create_blueprint_api(app, 'endpoints', __name__) confd_client = ConfdClient(**dependencies['config']['confd']) token_changed_subscribe = dependencies['token_changed_subscribe'] token_changed_subscribe(confd_client.set_token) service = EndpointService(dependencies['phone_plugins'], confd_client) class_kwargs = { 'service': service, } api.add_resource( EndpointHoldStartResource, '/endpoints/<endpoint_name>/hold/start', endpoint='endpoint_hold_start', resource_class_kwargs=class_kwargs, ) api.add_resource( EndpointHoldStopResource, '/endpoints/<endpoint_name>/hold/stop', endpoint='endpoint_hold_stop', resource_class_kwargs=class_kwargs, ) api.add_resource( EndpointAnswerResource, '/endpoints/<endpoint_name>/answer', endpoint='endpoint_answer', resource_class_kwargs=class_kwargs, )
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']) 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) transfers_stasis = TransfersStasis(amid_client, ari, transfers_service, state_factory, state_persistor, config['uuid']) startup_callback_collector = CallbackCollector() ari.client_initialized_subscribe(startup_callback_collector.new_source()) startup_callback_collector.subscribe(transfers_stasis.initialize) notifier = TransferNotifier(bus_publisher) state_factory.set_dependencies(amid_client, ari.client, notifier, transfers_service, state_persistor, transfer_lock) kwargs = {'resource_class_args': [transfers_service]} api.add_resource(TransfersResource, '/transfers', **kwargs) api.add_resource(TransferResource, '/transfers/<transfer_id>', **kwargs) api.add_resource(TransferCompleteResource, '/transfers/<transfer_id>/complete', **kwargs) api.add_resource(UserTransfersResource, '/users/me/transfers', **kwargs) api.add_resource(UserTransferResource, '/users/me/transfers/<transfer_id>', **kwargs) api.add_resource(UserTransferCompleteResource, '/users/me/transfers/<transfer_id>/complete', **kwargs)
def load(self, dependencies): api = dependencies['api'] ari = dependencies['ari'] 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) conferences_service = ConferencesService(amid_client, ari.client, confd_client) notifier = ConferencesNotifier(bus_publisher) bus_event_handler = ConferencesBusEventHandler(confd_client, notifier, conferences_service) bus_event_handler.subscribe(bus_consumer) kwargs = {'resource_class_args': [conferences_service]} api.add_resource(ParticipantsResource, '/conferences/<int:conference_id>/participants', **kwargs) api.add_resource(ParticipantsUserResource, '/users/me/conferences/<int:conference_id>/participants', **kwargs) api.add_resource(ParticipantResource, '/conferences/<int:conference_id>/participants/<participant_id>', **kwargs) api.add_resource(ParticipantMuteResource, '/conferences/<int:conference_id>/participants/<participant_id>/mute', **kwargs) api.add_resource(ParticipantUnmuteResource, '/conferences/<int:conference_id>/participants/<participant_id>/unmute', **kwargs) api.add_resource(ConferenceRecordResource, '/conferences/<int:conference_id>/record', **kwargs)
def get_wazo_confd_client(): client = g.get('wazo_confd_client') if not client: client = g.wazo_confd_client = ConfdClient(**app.config['confd']) client.set_token(current_user.get_id()) client.set_tenant(current_user.get_tenant_uuid()) add_tenant_to(client) return client
def setup_rtp(self, engine_password, icesupport, stunaddr): if not icesupport and not stunaddr: return token = self.get_engine_token(engine_password) client = ConfdClient(token=token, **self._confd_config) rtp_config = client.rtp_general.get()['options'] rtp_config['stunaddr'] = stunaddr if icesupport: rtp_config['icesupport'] = 'yes' client.rtp_general.update({'options': rtp_config})
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'])
def load(self, dependencies): amid_client = AmidClient(**dependencies['config']['amid']) confd_client = ConfdClient(**dependencies['config']['confd']) token_changed_subscribe = dependencies['token_changed_subscribe'] token_changed_subscribe(amid_client.set_token) token_changed_subscribe(confd_client.set_token) bus_consumer = dependencies['bus_consumer'] service = BlfService(amid_client, confd_client) bus_event_handler = BusEventHandler(service) bus_event_handler.subscribe(bus_consumer)
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])
def main(): if os.path.exists(SENTINEL): sys.exit(0) config = load_config() auth_client = AuthClient(**config['auth']) token_data = auth_client.token.new(expiration=900) confd_client = ConfdClient(**config['confd']) confd_client.set_token(token_data['token']) tenant_configs = confd_client.tenants.list(recurse=True) tenant_templates = {} for config in tenant_configs['items']: if not config['sip_templates_generated']: continue tenant_templates[config['uuid']] = [ # Global is always first config['global_sip_template_uuid'], # Line templates config['webrtc_sip_template_uuid'], config['webrtc_video_sip_template_uuid'], # Trunk templates config['registration_trunk_sip_template_uuid'], ] for tenant_uuid, templates in tenant_templates.items(): endpoints = confd_client.endpoints_sip.list(tenant_uuid=tenant_uuid) for endpoint in endpoints['items']: selected_templates = [ template['uuid'] for template in endpoint['templates'] ] # We need at least 2 templates to have an ordering problem if len(set(selected_templates).intersection(set(templates))) < 2: continue endpoint['templates'] = [{ 'uuid': uuid } for uuid in order_templates(templates, selected_templates)] confd_client.endpoints_sip.update(endpoint) with open(SENTINEL, 'w') as f: f.write('')
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'], }
def main(tenant_uuid): config = load_config() auth_client = AuthClient(**config['auth']) auth_client.set_tenant(tenant_uuid) token_data = auth_client.token.new(expiration=300) confd_client = ConfdClient(token=token_data['token'], **config['confd']) confd_client.set_tenant(tenant_uuid) endpoints_to_update = list_broken_endpoints(confd_client) print('updating', len(endpoints_to_update), 'endpoints') for endpoint_uuid in endpoints_to_update: print('.', end='') fix_endpoint(confd_client, endpoint_uuid) print('done')
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'])
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'] confd_client = ConfdClient(**config['confd']) 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=[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=[switchboards_service], )
def update_db(config, end_date, start_date=None): if start_date is None: try: with session_scope() as dao_sess: start = get_start_time(dao_sess) except RuntimeError: return else: start = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%S%z') end = datetime.datetime.strptime(end_date, '%Y-%m-%dT%H:%M:%S%z') auth_client = AuthClient(**config['auth']) token_data = auth_client.token.new(expiration=300) confd_client = ConfdClient(**config['confd']) confd_client.set_token(token_data['token']) logger.info('Getting objects from wazo-confd...') confd_queues = confd_client.queues.list(recurse=True) confd_agents = confd_client.agents.list(recurse=True) master_tenant = token_data['metadata']['tenant_uuid'] logger.info('Filling cache into DB') logger.info('Start Time: %s, End time: %s', start, end) with session_scope() as dao_sess: insert_missing_queues(dao_sess, start, end, confd_queues['items'], master_tenant) insert_missing_agents(dao_sess, confd_agents['items']) dao_sess.flush() queue.remove_between(dao_sess, start, end) agent.remove_after_start(dao_sess, start) queue.fill_simple_calls(dao_sess, start, end) dao_sess.flush() logger.info('Inserting agent periodic stat') agent.insert_periodic_stat(dao_sess, start, end) logger.info('Inserting queue periodic stat') for period_start in queue_log_dao.hours_with_calls( dao_sess, start, end): period_end = (period_start + datetime.timedelta(hours=1) - datetime.timedelta(microseconds=1)) queue.fill_calls(dao_sess, period_start, period_end) queue.insert_periodic_stat(dao_sess, period_start, period_end)
def load(self, dependencies): app = dependencies['app'] amid_client = AmidClient(**dependencies['config']['amid']) auth_client = AuthClient(**dependencies['config']['auth']) confd_client = ConfdClient(**dependencies['config']['confd']) dird_client = DirdClient(**dependencies['config']['dird']) token_changed_subscribe = dependencies['token_changed_subscribe'] token_changed_subscribe(amid_client.set_token) token_changed_subscribe(auth_client.set_token) token_changed_subscribe(confd_client.set_token) token_changed_subscribe(dird_client.set_token) service = YealinkService(amid_client, confd_client) self.service = service dependencies['phone_plugins'].append(self) bus_consumer = dependencies['bus_consumer'] bus_event_handler = BusEventHandler(service) bus_event_handler.subscribe(bus_consumer) directories_class_kwargs = { 'vendor': self.vendor, 'dird_client': dird_client, 'auth_client': auth_client, } user_service_class_kwargs = { 'service': service, } api = create_blueprint_api(app, '{}_plugin'.format(self.vendor), self.import_name) self.lookup_url = self.lookup_url_fmt.format(vendor=self.vendor) self.directories_lookup_url = self.directories_lookup_url_fmt.format( vendor=self.vendor) self.user_service_dnd_enable_url = self.user_service_dnd_enable_url_fmt.format( vendor=self.vendor) self.user_service_dnd_disable_url = ( self.user_service_dnd_disable_url_fmt.format(vendor=self.vendor)) self._add_resources(api, directories_class_kwargs) self._add_user_service_resources(api, user_service_class_kwargs)
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']) 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) relocates_stasis = RelocatesStasis(ari, relocates) startup_callback_collector = CallbackCollector() ari.client_initialized_subscribe( startup_callback_collector.new_source()) startup_callback_collector.subscribe(relocates_stasis.initialize) kwargs = {'resource_class_args': [relocates_service]} api.add_resource(UserRelocatesResource, '/users/me/relocates', **kwargs) api.add_resource(UserRelocateResource, '/users/me/relocates/<relocate_uuid>', **kwargs) api.add_resource(UserRelocateCompleteResource, '/users/me/relocates/<relocate_uuid>/complete', **kwargs) api.add_resource(UserRelocateCancelResource, '/users/me/relocates/<relocate_uuid>/cancel', **kwargs)
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', 'wazo-provd'])
def load(self, dependencies): api = dependencies['api'] ari = dependencies['ari'] config = dependencies['config'] token_changed_subscribe = dependencies['token_changed_subscribe'] bus_consumer = dependencies['bus_consumer'] bus_publisher = dependencies['bus_publisher'] confd_client = ConfdClient(**config['confd']) token_changed_subscribe(confd_client.set_token) confd_cache = ConfdCache(confd_client) notifier = EndpointStatusNotifier(bus_publisher, confd_cache) status_cache = NotifyingStatusCache(notifier.endpoint_updated, ari.client) endpoints_service = EndpointsService(confd_cache, status_cache) startup_callback_collector = CallbackCollector() ari.client_initialized_subscribe(startup_callback_collector.new_source()) startup_callback_collector.subscribe(status_cache.initialize) event_handler = EventHandler(status_cache, confd_cache) event_handler.subscribe(bus_consumer) api.add_resource( TrunkEndpoints, '/trunks', resource_class_args=[ endpoints_service, ], ) api.add_resource( LineEndpoints, '/lines', resource_class_args=[ endpoints_service, ], )
def main(): config = load_config() args = argument_parser.parse_args() print('Importing', args.filename) if not os.path.exists(args.filename): print('No such file or directory', args.filename) sys.exit(1) auth_client = AuthClient(**config['auth']) token_data = auth_client.token.new(expiration=300) confd_client = ConfdClient(token=token_data['token'], **config['confd']) content = configparser.ConfigParser() content.read(args.filename) if not content.sections(): print('Nothing to import') sys.exit(0) for section in content.sections(): migrate_section(confd_client, section, content[section])
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])
def post_confd_wizard(self, language, password, license_accepted): c = ConfdClient(**self._confd_config) if c.wizard.get()['configured']: logger.info("Wizard already configured...") return discover = c.wizard.discover() if len(discover['nameservers']) > 3: # NOTE(fblackburn): Should parse confd error when it will return json errors raise SetupError( message= 'Too many nameservers configured on host, maximum authorized is three', error_id='setup-nameservers-failed', ) if not discover.get('domain'): discover['domain'] = 'localdomain' wizard = { "admin_password": password, "license": license_accepted, "timezone": discover['timezone'], "language": language, "network": { "hostname": discover['hostname'], "domain": discover['domain'], "interface": discover['interfaces'][0]['interface'], "ip_address": discover['interfaces'][0]['ip_address'], "netmask": discover['interfaces'][0]['netmask'], "gateway": discover['gateways'][0]['gateway'], "nameservers": discover['nameservers'], }, } c.wizard.create(wizard)
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 load(self, dependencies): api = dependencies['api'] config = dependencies['config'] dao = dependencies['dao'] bus_consumer = dependencies['bus_consumer'] bus_publisher = dependencies['bus_publisher'] status_aggregator = dependencies['status_aggregator'] status_validator.set_config(status_aggregator, config) notifier = PresenceNotifier(bus_publisher) service = PresenceService(dao, notifier) initialization = config['initialization'] auth = AuthClient(**config['auth']) amid = AmidClient(**config['amid']) confd = ConfdClient(**config['confd']) initiator = Initiator(dao, auth, amid, confd) status_aggregator.add_provider(initiator.provide_status) if initialization['enabled']: thread_manager = dependencies['thread_manager'] initiator_thread = InitiatorThread(initiator) thread_manager.manage(initiator_thread) bus_event_handler = BusEventHandler(dao, notifier) bus_event_handler.subscribe(bus_consumer) api.add_resource(PresenceListResource, '/users/presences', resource_class_args=[service]) api.add_resource( PresenceItemResource, '/users/<uuid:user_uuid>/presences', resource_class_args=[service], )
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()
def load(self, dependencies): api = dependencies['api'] ari = dependencies['ari'] asyncio = dependencies['asyncio'] bus_publisher = dependencies['bus_publisher'] bus_consumer = dependencies['bus_consumer'] config = dependencies['config'] token_changed_subscribe = dependencies['token_changed_subscribe'] next_token_changed_subscribe = dependencies['next_token_changed_subscribe'] confd_client = ConfdClient(**config['confd']) switchboard_get_cache = ConfdClientGetUUIDCacheDecorator( confd_client.switchboards.get, resource_name='switchboard' ) confd_client.switchboards.get = switchboard_get_cache line_get_cache = ConfdClientGetIDCacheDecorator( confd_client.lines.get, resource_name='line' ) confd_client.lines.get = line_get_cache user_line_get_cache = ConfdClientUserLineGetCacheDecorator( confd_client.users.get, resource_name='user' ) confd_client.users.get = user_line_get_cache token_changed_subscribe(confd_client.set_token) switchboards_notifier = SwitchboardsNotifier(bus_publisher) switchboards_service = SwitchboardsService( ari.client, asyncio, confd_client, switchboards_notifier ) switchboards_stasis = SwitchboardsStasis( ari, confd_client, switchboards_notifier, switchboards_service ) switchboard_get_cache.subscribe( bus_consumer, events=['switchboard_edited', 'switchboard_deleted'] ) # line-endpoint association emits line_edited too line_get_cache.subscribe(bus_consumer, events=['line_edited', 'line_deleted']) user_line_get_cache.subscribe(bus_consumer) startup_callback_collector = CallbackCollector() next_token_changed_subscribe(startup_callback_collector.new_source()) ari.client_initialized_subscribe(startup_callback_collector.new_source()) startup_callback_collector.subscribe(switchboards_stasis.initialize) 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=[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=[switchboards_service], )
def load(self, dependencies): api = dependencies['api'] ari = dependencies['ari'] config = dependencies['config'] bus_consumer = dependencies['bus_consumer'] bus_publisher = dependencies['bus_publisher'] config = dependencies['config'] token_changed_subscribe = dependencies['token_changed_subscribe'] next_token_changed_subscribe = dependencies[ 'next_token_changed_subscribe'] pubsub = dependencies['pubsub'] 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) confd_apps_cache = ConfdApplicationsCache(confd_client) confd_apps_cache.subscribe(bus_consumer) moh_cache = MohCache(confd_client) moh_cache.subscribe(bus_consumer) notifier = ApplicationNotifier(bus_publisher) service = ApplicationService( ari.client, confd_client, amid_client, notifier, confd_apps_cache, moh_cache, ) stasis = ApplicationStasis( ari, service, notifier, confd_apps_cache, moh_cache, ) confd_is_ready_thread = ConfdIsReadyThread(confd_client) startup_callback_collector = CallbackCollector() next_token_changed_subscribe(startup_callback_collector.new_source()) ari.client_initialized_subscribe( startup_callback_collector.new_source()) confd_is_ready_thread.subscribe( startup_callback_collector.new_source()) startup_callback_collector.subscribe(stasis.initialize) confd_apps_cache.created_subscribe(stasis.add_ari_application) confd_apps_cache.updated_subscribe(service.update_destination_node) confd_apps_cache.deleted_subscribe(stasis.remove_ari_application) confd_is_ready_thread.start() pubsub.subscribe('stopping', lambda _: confd_is_ready_thread.stop()) 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( ApplicationCallAnswer, '/applications/<uuid:application_uuid>/calls/<call_id>/answer', resource_class_args=[service], ) api.add_resource( ApplicationCallProgressStart, '/applications/<uuid:application_uuid>/calls/<call_id>/progress/start', resource_class_args=[service], ) api.add_resource( ApplicationCallProgressStop, '/applications/<uuid:application_uuid>/calls/<call_id>/progress/stop', 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( ApplicationNodeCallUserList, '/applications/<uuid:application_uuid>/nodes/<uuid:node_uuid>/calls/user', 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], ) api.add_resource( ApplicationDTMFList, '/applications/<uuid:application_uuid>/calls/<call_id>/dtmf', resource_class_args=[service], )