Exemple #1
0
 def resolve(self, request, handler):
     reply = request.reply()
     qname = request.q.qname
     qtype = QTYPE[request.q.qtype]
     for name, rtype, rr in self.get_split_records():
         # Check if label & type match
         if getattr(qname,
                    self.eq)(name) and (qtype == rtype or qtype == "ANY"
                                        or rtype == "CNAME"):
             logger.debug(
                 "record matched - name: {} | rtype: {} | rr: {} | qname: {}"
                 .format(str(name), str(rtype), str(rr), str(qname)))
             # If we have a glob match fix reply label
             if self.glob:
                 a = copy.copy(rr)
                 a.rname = qname
                 reply.add_answer(a)
             else:
                 reply.add_answer(rr)
             # Check for A/AAAA records associated with reply and
             # add in additional section
             if rtype in ["CNAME", "NS", "MX", "PTR"]:
                 for a_name, a_rtype, a_rr in self.get_split_records():
                     if a_name == rr.rdata.label and a_rtype in [
                             "A", "AAAA"
                     ]:
                         reply.add_ar(a_rr)
         else:
             logger.debug("record not matched: {} for {}".format(
                 str(name), str(qname)))
     if not reply.rr:
         reply.header.rcode = RCODE.NXDOMAIN
     return reply
Exemple #2
0
 async def on_after_insert(mapper, connection, target):
     logger.debug("on_after_insert@DnsRequest: Publishing message")
     try:
         publisher = await make_redis()
         res = await publisher.publish_json(
             "channel:auth",
             {
                 "type": "MESSAGE",
                 "name": "DNS_REQUEST_CREATED",
                 "payload": ""
             },
         )
     except Exception as e:
         logger.warning(f"on_after_insert error: {str(e)}")
Exemple #3
0
    def make(cls, zone, rr):
        if not getattr(rr, "rtype", None):
            logger.critical(
                f"No rtype found for rr: {str(rr)} - {str(rr.__class__)}")

        # RR's don't have knowledge of domiain so replace "." with zone domain
        if rr.rname == ".":
            zone_rname = zone.domain + "."
        else:
            zone_rname = "." + zone.domain + "."
        new_label_name = str(rr.rname).replace(".", zone_rname)
        logger.debug(
            f"Replacing RR's rname {str(rr.rname)} with {new_label_name}")
        rr.set_rname(new_label_name)
        return cls(zone, rr)
Exemple #4
0
async def is_broadcast_up():
    seconds = 0
    while True:
        if seconds > 60:
            logger.critical("could not start api. broadcast (queue) not up")
            return False
        logger.debug("checking for broadcast (queue) status")
        try:
            redis = await make_redis()
            await redis.set("up-key", "value")
            val = await redis.get("up-key")
            val = await redis.delete("up-key")
            return True
        except Exception as e:
            logger.critical(
                "broadcast (queue) check not ready after {} seconds: {}".
                format(str(seconds), str(e.__class__.__name__)))
        seconds = seconds + 2
        sleep(2)
Exemple #5
0
def is_db_up():
    seconds = 0
    while True:
        if seconds > 60:
            logger.critical("could not start api. database not up")
            return False
        logger.debug("checking for db status")
        try:
            session().execute("SELECT 1")
            return True
        except KeyError as e:
            logger.critical(
                "database has not be registered. please call db_register(db_url)"
            )
            return False
        except Exception as e:
            logger.critical(
                "database check not ready after {} seconds: {}".format(
                    str(seconds), str(e.__class__.__name__)))
        seconds = seconds + 1
        sleep(1)
Exemple #6
0
def is_db_setup():
    seconds = 0
    while True:
        if seconds > 60:
            logger.critical("could not start api. database not setup")
            return False
        logger.debug("checking for db migrations")
        try:
            session().execute("SELECT * from alembic_version")
            return True
        except KeyError as e:
            logger.critical(
                "database has not be registered. please call db_register(db_url)"
            )
            return False
        except Exception as e:
            logger.critical(
                "database has not been migrated. please run: bdnsctl.py db-setup"
            )
            return False
        seconds = seconds + 1
        sleep(1)
Exemple #7
0
 def log_request(self, handler, request, request_uuid):
     logger.debug(f"log_request: {handler}, {request}, {request_uuid}")
     self.api.create_dns_request(handler, request, request_uuid)
     super().log_request(handler, request)
Exemple #8
0
    async def run(self):
        app = "boucanpy.api.main:api"
        kwargs = self.get_kwargs()

        if self.should_import_check():
            logger.info("run@api_server.py - Performing import check")
            from boucanpy.api.main import api

        logger.critical(
            "run@api_server.py - Starting api server with options: {}".format(
                str(kwargs)))
        from boucanpy.db.checks import is_db_up, is_db_setup

        # alembic just destroys the loggers, it's annoying
        if self.should_db_check():
            logger.info(
                "run@api_server.py - Waiting for database service to be up")
            db_wait_options = self._args_to_dict(self.options)
            await DbWait(db_wait_options).run()

        if self.option("db_setup"):
            logger.critical("run@api_server.py - Running database migration")
            db_setup_options = self._args_to_dict(self.options)
            if self.option("db_seed"):
                db_setup_options["seed"] = True
            await DbSetup(db_setup_options).run()

        if self.should_db_check():
            logger.info(
                "run@api_server.py - Checking if application database is setup and configured"
            )

            db_setup = is_db_setup()
            if not db_setup:
                logger.critical(
                    "run@api_server.py - Database not setup error. please check logs"
                )
                return self.exit(1)

        from boucanpy.broadcast import is_broadcast_up

        if self.should_bcast_check():
            bcast_up = await is_broadcast_up()
            if not bcast_up:
                logger.critical(
                    "run@api_server.py - Broadcast (queue) not up error. please check logs"
                )
                return self.exit(1)

        if self.option("db_seed_env", False):
            self.seed_from_env()

        # taken from uvicorn/main.py:run

        logger.debug("run@api_server.py - Building Uvicorn Config and Server")
        config = UvicornConfig(app,
                               log_config=self.get_uvicorn_logging(),
                               **kwargs)
        server = UvicornServer(config=config)
        if self.option("force_exit"):
            server.force_exit = True

        if isinstance(app, str) and (config.debug or config.reload):
            logger.warning(
                f"run@api_server.py - Running boucanpy api in dev mode...")
            sock = config.bind_socket()
            supervisor = StatReload(config)
            return supervisor.run(server.run, sockets=[sock])
        elif config.workers > 1:
            sock = config.bind_socket()
            supervisor = Multiprocess(config)
            logger.warning(
                f"run@api_server.py - Running boucanpy api in worker mode...")
            return supervisor.run(server.run, sockets=[sock])
        else:
            sockets = None
            logger.warning(
                f"run@api_server.py - Running boucanpy api in standard mode..."
            )
            return await server.serve(sockets=sockets)
Exemple #9
0
        origins.append(use_origin)

    logger.info(f"[email protected] - Registering cors origins {origins}")

    api.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    ),

main_router = APIRouter()

for r, ropts in routers:
    logger.debug(f"[email protected] - Registering router {str(r)} {str(ropts)}")
    main_router.include_router(r, **ropts)

logger.debug(f"[email protected] - Registering main router {str(r)} {str(ropts)}")

api.include_router(main_router, prefix=config.API_V1_STR)

from starlette.websockets import WebSocket

# public broadcast

if int(environ.get("BROADCAST_ENABLED", 0)) == 1:
    logger.info("[email protected] - Registering broadcast routers")
    api.add_websocket_route("/broadcast",
                            broadcast_index,
                            name="broadcast.index")
Exemple #10
0
 def debug(self, msg):
     # pass
     if int(environ.get("API_REPO_DEBUG", 0)) == 1:
         logger.debug(msg)