Skip to content

Commit

Permalink
feat(server): started on server side logic
Browse files Browse the repository at this point in the history
  • Loading branch information
shinybrar committed May 3, 2024
1 parent 1806807 commit 620ce77
Show file tree
Hide file tree
Showing 7 changed files with 1,138 additions and 17 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ WORKDIR /voe

SHELL ["/bin/bash", "-c"]

RUN pip install .
RUN pip install --no-cache-dir .

CMD ["/bin/bash"]
73 changes: 69 additions & 4 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
version: "3.7"
version: "3.9"

services:
voe:
build:
context: .
no_cache: true
dockerfile: Dockerfile
command: ["/bin/bash"]
command: ["python", "/voe/frbvoe/server.py"]
environment:
- SANIC_HOSTNAME=localhost
- SANIC_PORT=8001
- SANIC_ACCESS_LOG=true
- SANIC_AUTO_RELOAD=true
- SANIC_DEBUG=true
- SANIC_WORKERS=2
- SANIC_MONGODB_HOSTNAME=localhost
- SANIC_MONGODB_PORT=27017
network_mode: host
ports:
- "8001:8001"
deploy:
replicas: 1
resources:
reservations:
cpus: "0.1"
Expand All @@ -16,4 +28,57 @@ services:
cpus: "0.5"
memory: "256M"
restart_policy:
condition: on-failure
condition: on-failure

comet:
build:
context: .
dockerfile: Dockerfile
command: [
"twistd",
"--nodaemon",
"--pidfile=comet.pid",
"comet",
"--receive",
"--broadcast",
"--receive-port=8098",
"--broadcast-port=8099",
"--print-event",
"--local-ivo=ivo://frbvoe/test",
"--author-whitelist=0.0.0.0/0",
]
environment:
- SUBSCRIBERS_LIST:${SUBSCRIBERS_LIST}
network_mode: host
ports:
- "8098:8098"
- "8099:8099"
deploy:
resources:
reservations:
cpus: "0.1"
memory: "128M"
limits:
cpus: "0.5"
memory: "256M"
restart_policy:
condition: on-failure

mongo:
image: mongo:latest
command: mongod --bind_ip_all --dbpath /data/db
network_mode: host
deploy:
resources:
reservations:
cpus: "0.1"
memory: "128M"
limits:
cpus: "0.5"
memory: "256M"
restart_policy:
condition: on-failure
ports:
- "27017:27017"
volumes:
- ./frbvoe-data:/data/db
8 changes: 8 additions & 0 deletions frbvoe/backend/voe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""VOEvent Server Blueprint."""

# Post at /voe

# Add the validated payload to the MongoDB Database
# Database Name: frbvoe
# Collection Name: voe
# Document -> VOEvent Payload Dict.
19 changes: 19 additions & 0 deletions frbvoe/models/voe.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import picologging as logging
from pydantic import EmailStr, Field, StrictFloat, StrictInt, StrictStr
from pydantic_settings import BaseSettings, SettingsConfigDict
from sanic import Request

logging.basicConfig()
log = logging.getLogger()
Expand Down Expand Up @@ -213,3 +214,21 @@ def payload(self):
"""Return the VOEvent payload."""
log.info("Returning VOEvent payload")
return self.dict()

@staticmethod
async def compile(request: Request):
"""Extracts data from request and returns object.
Parameters
----------
request : Request
Sanic Request.
Returns
-------
ActionData
Object containing dependency data to take actions.
"""
await request.receive_body()
voe = request.json
return VOEvent(**voe)
88 changes: 88 additions & 0 deletions frbvoe/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""Buckets Server."""

from asyncio import AbstractEventLoop
from functools import partial

from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import ConnectionFailure
from sanic import Sanic
from sanic.log import logger
from sanic.worker.loader import AppLoader

from frbvoe.models.voe import VOEvent


async def mongo(app: Sanic, loop: AbstractEventLoop) -> None:
"""Connect to the database.
Args:
app (Sanic): The application.
loop (AbstractEventLoop): The event loop.
"""
# SANIC_MONGODB_HOSTNAME
hostname = str(app.config.get("MONGODB_HOSTNAME", "localhost"))
# SANIC_MONGODB_PORT
port = int(app.config.get("MONGODB_PORT", 27017))
# SANIC_MONGODB_USERNAME
username = app.config.get("MONGODB_USERNAME", "")
# SANIC_MONGODB_PASSWORD
password = app.config.get("MONGODB_PASSWORD", "")
try:
logger.debug(f"Connecting to MongoDB at {hostname}:{port}")
client = AsyncIOMotorClient(
host=hostname, port=port, username=username, password=password, io_loop=loop
)
await client.admin.command("ping")
logger.debug("MongoDB Connection Established")
app.ctx.mongo = client
except ConnectionFailure as error:
logger.error(error)
logger.debug("MongoDB Connection Failed")


async def inject_dependencies(app: Sanic):
"""Adds dependencies for route handlers to the app.
Parameters
----------
app : Sanic
Sanic application.
loop : AbstractEventLoop
Event loop.
"""
logger.info("Injecting dependencies.")
app.ext.add_dependency(VOEvent, VOEvent.compile)


def create(name: str = "frbvoe", debug: bool = False) -> Sanic:
"""Create the buckets server.
Args:
debug (bool, optional): Whether to enable debug mode.
Defaults to False.
Returns:
Sanic: The buckets server.
"""
app = Sanic(name)
logger.propagate = False
app.config.CORS_ORIGINS = "*" # CORS
app.config.HEALTH = True
app.config.HEALTH_ENDPOINT = True
app.ctx.debug = debug
app.config.FALLBACK_ERROR_FORMAT = "json"
app.register_listener(mongo, "before_server_start")
return app


if __name__ == "__main__":
loader = AppLoader(factory=partial(create))
server: Sanic = loader.load()
server.prepare(
host=server.config.get("HOSTNAME", "localhost"), # type: ignore
port=server.config.get("PORT", 8002), # type: ignore
access_log=server.config.get("ACCESS_LOG", False),
auto_reload=server.config.get("AUTO_RELOAD", True),
debug=server.config.get("DEBUG", True),
)
Sanic.serve(primary=server, app_loader=loader)
Loading

0 comments on commit 620ce77

Please sign in to comment.