generated from erangel1/generic-template
initial commit. phase 1 complete
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
"""
|
||||
ASGI config for LabGraph.
|
||||
|
||||
Kept for future WebSocket support (Phase 3+ real-time status updates).
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.development")
|
||||
|
||||
application = get_asgi_application()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
Celery application for LabGraph.
|
||||
|
||||
Referenced by docker-compose as: celery -A config.celery <subcommand>
|
||||
|
||||
Queues:
|
||||
discovery — Proxmox API polling, nmap network scans
|
||||
heartbeat — Periodic ICMP/TCP liveness checks
|
||||
default — Maintenance, cleanup, housekeeping
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from celery import Celery
|
||||
from celery.schedules import crontab
|
||||
from kombu import Exchange, Queue
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.development")
|
||||
|
||||
app = Celery("labgraph")
|
||||
|
||||
app.config_from_object("django.conf:settings", namespace="CELERY")
|
||||
|
||||
app.autodiscover_tasks(["tasks"])
|
||||
|
||||
# Explicit queue definitions (mirrors --queues flag in docker-compose worker command)
|
||||
app.conf.task_queues = (
|
||||
Queue("default", Exchange("default"), routing_key="default"),
|
||||
Queue("discovery", Exchange("discovery"), routing_key="discovery"),
|
||||
Queue("heartbeat", Exchange("heartbeat"), routing_key="heartbeat"),
|
||||
)
|
||||
|
||||
app.conf.task_default_queue = "default"
|
||||
app.conf.task_default_exchange = "default"
|
||||
app.conf.task_default_routing_key = "default"
|
||||
|
||||
# Route tasks to queues by module prefix
|
||||
app.conf.task_routes = {
|
||||
"tasks.discovery.*": {"queue": "discovery"},
|
||||
"tasks.heartbeat.*": {"queue": "heartbeat"},
|
||||
"tasks.maintenance.*": {"queue": "default"},
|
||||
}
|
||||
|
||||
app.conf.beat_schedule = {
|
||||
"heartbeat-all-nodes": {
|
||||
"task": "tasks.heartbeat.check_all_nodes",
|
||||
"schedule": 60.0,
|
||||
"queue": "heartbeat",
|
||||
# Drop task if not picked up before the next run fires
|
||||
"options": {"expires": 55},
|
||||
},
|
||||
"discovery-scan-networks": {
|
||||
"task": "tasks.discovery.scan_all_networks",
|
||||
"schedule": crontab(minute="*/15"),
|
||||
"queue": "discovery",
|
||||
},
|
||||
"maintenance-prune-heartbeat-logs": {
|
||||
"task": "tasks.maintenance.prune_old_heartbeat_logs",
|
||||
"schedule": crontab(hour=3, minute=0),
|
||||
"queue": "default",
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
"""
|
||||
Base settings shared across all LabGraph environments.
|
||||
|
||||
Never imported directly — always imported via development.py or production.py.
|
||||
All secrets are read from environment variables; missing required vars raise
|
||||
ImproperlyConfigured immediately on startup.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import environ
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent # backend/
|
||||
|
||||
env = environ.Env(
|
||||
DEBUG=(bool, False),
|
||||
ALLOWED_HOSTS=(list, ["localhost", "127.0.0.1"]),
|
||||
)
|
||||
|
||||
environ.Env.read_env(BASE_DIR.parent / ".env")
|
||||
|
||||
# =============================================================================
|
||||
# Security — no defaults for secrets; missing value raises ImproperlyConfigured
|
||||
# =============================================================================
|
||||
SECRET_KEY = env("SECRET_KEY")
|
||||
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
|
||||
|
||||
# =============================================================================
|
||||
# Application definition
|
||||
# =============================================================================
|
||||
DJANGO_APPS = [
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
]
|
||||
|
||||
THIRD_PARTY_APPS = [
|
||||
"rest_framework",
|
||||
"corsheaders",
|
||||
"django_celery_beat",
|
||||
"django_celery_results",
|
||||
"drf_spectacular",
|
||||
"django_filters",
|
||||
]
|
||||
|
||||
LOCAL_APPS = [
|
||||
"apps.core",
|
||||
"apps.health",
|
||||
]
|
||||
|
||||
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
|
||||
|
||||
# =============================================================================
|
||||
# Middleware — CorsMiddleware must be first
|
||||
# =============================================================================
|
||||
MIDDLEWARE = [
|
||||
"corsheaders.middleware.CorsMiddleware",
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = "config.urls"
|
||||
WSGI_APPLICATION = "config.wsgi.application"
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [BASE_DIR / "templates"],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.debug",
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
# =============================================================================
|
||||
# Database — parsed from DATABASE_URL env var by django-environ
|
||||
# =============================================================================
|
||||
DATABASES = {
|
||||
"default": env.db("DATABASE_URL")
|
||||
}
|
||||
|
||||
# Ensure Django uses UTC-aware datetimes in queries
|
||||
DATABASES["default"]["OPTIONS"] = {"options": "-c timezone=UTC"}
|
||||
|
||||
# =============================================================================
|
||||
# Cache — Redis
|
||||
# =============================================================================
|
||||
CACHES = {
|
||||
"default": {
|
||||
"BACKEND": "django.core.cache.backends.redis.RedisCache",
|
||||
"LOCATION": env("REDIS_URL"),
|
||||
}
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Celery — all CELERY_* prefixed settings are picked up by
|
||||
# app.config_from_object("django.conf:settings", namespace="CELERY")
|
||||
# =============================================================================
|
||||
CELERY_BROKER_URL = env("CELERY_BROKER_URL")
|
||||
CELERY_RESULT_BACKEND = "django-db"
|
||||
CELERY_CACHE_BACKEND = "default"
|
||||
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
|
||||
CELERY_TASK_SERIALIZER = "json"
|
||||
CELERY_RESULT_SERIALIZER = "json"
|
||||
CELERY_ACCEPT_CONTENT = ["json"]
|
||||
CELERY_TIMEZONE = "UTC"
|
||||
CELERY_TASK_TRACK_STARTED = True
|
||||
CELERY_TASK_TIME_LIMIT = 300
|
||||
CELERY_TASK_SOFT_TIME_LIMIT = 270
|
||||
CELERY_WORKER_MAX_TASKS_PER_CHILD = 100
|
||||
|
||||
# =============================================================================
|
||||
# Django REST Framework
|
||||
# =============================================================================
|
||||
REST_FRAMEWORK = {
|
||||
"DEFAULT_AUTHENTICATION_CLASSES": [
|
||||
"rest_framework.authentication.SessionAuthentication",
|
||||
],
|
||||
"DEFAULT_PERMISSION_CLASSES": [
|
||||
"rest_framework.permissions.IsAuthenticated",
|
||||
],
|
||||
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
|
||||
"DEFAULT_FILTER_BACKENDS": [
|
||||
"django_filters.rest_framework.DjangoFilterBackend",
|
||||
"rest_framework.filters.SearchFilter",
|
||||
"rest_framework.filters.OrderingFilter",
|
||||
],
|
||||
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
|
||||
"PAGE_SIZE": 50,
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# drf-spectacular — OpenAPI schema
|
||||
# =============================================================================
|
||||
SPECTACULAR_SETTINGS = {
|
||||
"TITLE": "LabGraph API",
|
||||
"DESCRIPTION": "HomeLab infrastructure documentation engine — graph-based inventory and monitoring.",
|
||||
"VERSION": "1.0.0",
|
||||
"SERVE_INCLUDE_SCHEMA": False,
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# CORS
|
||||
# =============================================================================
|
||||
CORS_ALLOW_CREDENTIALS = True
|
||||
|
||||
# =============================================================================
|
||||
# Static & media files
|
||||
# =============================================================================
|
||||
STATIC_URL = "/static/"
|
||||
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||
MEDIA_URL = "/media/"
|
||||
MEDIA_ROOT = BASE_DIR / "mediafiles"
|
||||
|
||||
# =============================================================================
|
||||
# Internationalisation
|
||||
# =============================================================================
|
||||
LANGUAGE_CODE = "en-us"
|
||||
TIME_ZONE = "UTC"
|
||||
USE_I18N = True
|
||||
USE_TZ = True
|
||||
|
||||
# =============================================================================
|
||||
# Default primary key
|
||||
# =============================================================================
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
|
||||
# =============================================================================
|
||||
# Password validation
|
||||
# =============================================================================
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
Development settings for LabGraph.
|
||||
|
||||
Inherits all base settings and adds:
|
||||
- DEBUG = True
|
||||
- Relaxed CORS (localhost:3000 allowed by default)
|
||||
- Console email backend
|
||||
- Verbose DEBUG-level logging for apps and Celery
|
||||
"""
|
||||
|
||||
from .base import * # noqa: F401, F403
|
||||
from .base import env
|
||||
|
||||
DEBUG = True
|
||||
|
||||
CORS_ALLOWED_ORIGINS = env.list(
|
||||
"CORS_ALLOWED_ORIGINS",
|
||||
default=["http://localhost:3000", "http://127.0.0.1:3000"],
|
||||
)
|
||||
|
||||
INTERNAL_IPS = ["127.0.0.1"]
|
||||
|
||||
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"verbose": {
|
||||
"format": "[{levelname}] {asctime} {name}: {message}",
|
||||
"style": "{",
|
||||
},
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "verbose",
|
||||
},
|
||||
},
|
||||
"root": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO",
|
||||
},
|
||||
"loggers": {
|
||||
"django": {"handlers": ["console"], "level": "INFO", "propagate": False},
|
||||
"celery": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
|
||||
"apps": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
|
||||
"tasks": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
Production settings for LabGraph.
|
||||
|
||||
Inherits all base settings and adds:
|
||||
- DEBUG = False
|
||||
- Strict CORS (origins required from env, no default)
|
||||
- HSTS + secure cookies + SSL redirect
|
||||
- WhiteNoise compressed static files
|
||||
- JSON-formatted structured logging at WARNING level
|
||||
"""
|
||||
|
||||
from .base import * # noqa: F401, F403
|
||||
from .base import env
|
||||
|
||||
DEBUG = False
|
||||
|
||||
# Production CORS must be explicitly set — no default
|
||||
CORS_ALLOWED_ORIGINS = env.list("CORS_ALLOWED_ORIGINS")
|
||||
|
||||
# Security hardening
|
||||
SECURE_HSTS_SECONDS = 31_536_000 # 1 year
|
||||
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
|
||||
SECURE_HSTS_PRELOAD = True
|
||||
SECURE_SSL_REDIRECT = env.bool("SECURE_SSL_REDIRECT", default=True)
|
||||
SESSION_COOKIE_SECURE = True
|
||||
CSRF_COOKIE_SECURE = True
|
||||
SECURE_BROWSER_XSS_FILTER = True
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
X_FRAME_OPTIONS = "DENY"
|
||||
|
||||
# WhiteNoise: compress + fingerprint static files for long-lived caching
|
||||
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"json": {
|
||||
"()": "logging.Formatter",
|
||||
"fmt": '{"time": "%(asctime)s", "level": "%(levelname)s", "name": "%(name)s", "message": "%(message)s"}',
|
||||
},
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "json",
|
||||
},
|
||||
},
|
||||
"root": {
|
||||
"handlers": ["console"],
|
||||
"level": "WARNING",
|
||||
},
|
||||
"loggers": {
|
||||
"django": {"handlers": ["console"], "level": "WARNING", "propagate": False},
|
||||
"celery": {"handlers": ["console"], "level": "WARNING", "propagate": False},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"""
|
||||
Root URL configuration for LabGraph.
|
||||
|
||||
Routes:
|
||||
/admin/ — Django admin interface
|
||||
/api/health/ — Health check (required by docker-compose healthcheck)
|
||||
/api/v1/ — DRF router (viewsets registered in Phase 2)
|
||||
/api/schema/ — OpenAPI schema (drf-spectacular)
|
||||
"""
|
||||
|
||||
from django.contrib import admin
|
||||
from django.urls import include, path
|
||||
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
|
||||
|
||||
urlpatterns = [
|
||||
path("admin/", admin.site.urls),
|
||||
path("api/health/", include("apps.health.urls")),
|
||||
path("api/v1/", include("apps.core.urls")),
|
||||
path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
|
||||
path("api/docs/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"),
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
WSGI config for LabGraph.
|
||||
|
||||
Entry point used by Gunicorn in docker-compose:
|
||||
gunicorn config.wsgi:application
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.development")
|
||||
|
||||
application = get_wsgi_application()
|
||||
Reference in New Issue
Block a user