예제 #1
0
    def initialize_app(self, app) -> Optional[Future]:
        if not options.consul_enabled:
            integrations_logger.info('Consul disabled, skipping')
            return None

        host = socket.gethostname()
        self.consul = Consul(host=options.consul_host,
                             port=options.consul_port)
        self.service_name = options.app
        self.service_id = f'{self.service_name}-{options.datacenter}-{host}-{options.port}'

        http_check = Check.http(f'http://{host}:{options.port}/status',
                                options.consul_http_check_interval_sec,
                                timeout=options.consul_http_check_timeout_sec)
        # not supported by version 1.1.0
        meta = {'serviceVersion': version}
        return asyncio.ensure_future(
            self.consul.agent.service.register(
                self.service_name,
                service_id=self.service_id,
                address=host,
                port=options.port,
                check=http_check,
                tags=options.consul_tags,
            ))
예제 #2
0
    async def create_database(cls,
                              config,
                              collection: str,
                              model: Type[BaseModel],
                              create_schema: bool = True) -> IDataBase:
        """
        Creates new instance of Consul KV DB and performs necessary initializations.

        :param DBSettings config: configuration for consul kv server
        :param str collection: collection for storing model onto db
        :param Type[BaseModel] model: model which instances will be stored in DB
        :param bool create_schema: if the flag is true, the collection will be created.
        :return:
        """
        # NOTE: please, be sure that you avoid using this method twice (or more times) for the same
        # model
        if not all((cls.consul_client, cls.thread_pool, cls.loop)):
            cls.loop = asyncio.get_event_loop()
            try:
                cls.consul_client = Consul(host=config.hosts[0],
                                           port=config.port,
                                           loop=cls.loop)
            except ConnectionRefusedError as e:
                raise DataAccessExternalError(f"{e}")
            # needed to perform tree traversal in non-blocking mode
            cls.thread_pool = ThreadPoolExecutor(
                max_workers=multiprocessing.cpu_count())

        consul_db = cls(cls.consul_client, model, collection, cls.thread_pool,
                        cls.loop)

        try:
            if create_schema:
                await consul_db.create_object_root()
        except ClientConnectorError as e:
            raise DataAccessExternalError(f"{e}")
        except Exception as e:
            raise DataAccessError(
                f"Some unknown exception occurred in Consul module: {e}")

        return consul_db