Skip to content

Commit

Permalink
Added GCP config settings and commands.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ken Lippold authored and Ken Lippold committed Nov 1, 2024
1 parent 5033c23 commit 8922c75
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 150 deletions.
64 changes: 0 additions & 64 deletions core/management/commands/configure_timescaledb.py

This file was deleted.

78 changes: 0 additions & 78 deletions core/management/commands/deploy_aws.py

This file was deleted.

25 changes: 25 additions & 0 deletions core/management/commands/setup_admin_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from django.core.management.base import BaseCommand
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_model
from django.conf import settings


class Command(BaseCommand):
help = 'Creates a default superuser if no superuser exists'

def handle(self, *args, **kwargs):
user_model = get_user_model()

if not user_model.objects.filter(is_superuser=True).exists():
self.stdout.write(self.style.NOTICE(f'\nCreating default superuser...'))

email = getattr(settings, 'DEFAULT_SUPERUSER_EMAIL', '[email protected]')
password = getattr(settings, 'DEFAULT_SUPERUSER_PASSWORD', 'pass')

try:
user_model.objects.create_superuser(username=email, email=email, password=password)
self.stdout.write(self.style.SUCCESS(f'Superuser created: {email}'))
except ValidationError as e:
self.stdout.write(self.style.ERROR(f'Failed to create default superuser: {e}'))
except Exception as e:
self.stdout.write(self.style.ERROR(f'An unexpected error occurred: {e}'))
74 changes: 74 additions & 0 deletions core/management/commands/setup_observations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import psycopg2
from django.core.management.base import BaseCommand
from django.conf import settings
from psycopg2 import OperationalError, Error


class Command(BaseCommand):
help = "Create or update the Observation table and optionally set it as a TimescaleDB hypertable."

def add_arguments(self, parser):
parser.add_argument(
'--setup-timescaledb',
action='store_true',
help='Create the observations table as a hypertable if using TimescaleDB.'
)

parser.add_argument(
'--partition-interval-days',
default=365,
type=int,
help='Set the observations hypertable partition interval value in days.'
)

def handle(self, *args, **options):
self.stdout.write(self.style.NOTICE("\nChecking Observation table setup..."))
db_settings = settings.DATABASES['default']

try:
with psycopg2.connect(
host=db_settings['HOST'],
user=db_settings['USER'],
password=db_settings['PASSWORD'],
dbname=db_settings['NAME'],
port=db_settings['PORT'],
connect_timeout=3
) as connection:
with connection.cursor() as cursor:
observation_table = """
CREATE TABLE IF NOT EXISTS "Observation" (
"id" uuid NOT NULL,
"datastreamId" uuid NOT NULL,
"featureOfInterestId" uuid NULL,
"phenomenonTime" timestamptz NOT NULL,
"result" float8 NOT NULL,
"resultTime" timestamptz NULL,
"qualityCode" varchar(255) NULL,
"resultQualifiers" uuid[] NULL,
CONSTRAINT "_datastream_uuid_phenomenon_time_uc" UNIQUE ("datastreamId", "phenomenonTime"),
CONSTRAINT observation_pkey PRIMARY KEY ("id", "datastreamId", "phenomenonTime"),
CONSTRAINT observation_datastream_id_fkey FOREIGN KEY ("datastreamId") REFERENCES public."Datastream"(id),
CONSTRAINT observation_feature_of_interest_id_fkey FOREIGN KEY ("featureOfInterestId") REFERENCES public."Datastream"(id)
);
"""
cursor.execute(observation_table)

if options['setup_timescaledb']:
cursor.execute("CREATE EXTENSION IF NOT EXISTS timescaledb;")
cursor.execute(
f"SELECT create_hypertable("
f"'\"Observation\"', "
f"'phenomenonTime', "
f"chunk_time_interval => INTERVAL '{options['partition_interval_days']} day', "
f"if_not_exists => TRUE"
f");"
)

except OperationalError as e:
self.stdout.write(self.style.ERROR(f"Database connection failed: {e}"))
except Error as e:
self.stdout.write(self.style.ERROR(f"An error occurred while executing Observation table setup: {e}"))
except Exception as e:
self.stdout.write(self.style.ERROR(f"An unexpected error occurred setting up Observation table: {e}"))

self.stdout.write(self.style.SUCCESS("Finished checking Observation table setup."))
35 changes: 27 additions & 8 deletions hydroserver/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@
DISABLE_ACCOUNT_CREATION = config('DISABLE_ACCOUNT_CREATION', default=False, cast=bool)

# CORS Settings

CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/.*$'
CORS_ALLOW_HEADERS = list(default_headers)

# Deployment Settings
# Default Superuser Settings
DEFAULT_SUPERUSER_EMAIL = config('DEFAULT_SUPERUSER_EMAIL', default='[email protected]')
DEFAULT_SUPERUSER_PASSWORD = config('DEFAULT_SUPERUSER_PASSWORD', default='pass')

# Deployment Settings
if DEPLOYMENT_BACKEND == 'aws':
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname) # This is necessary for AWS ELB Health Checks to pass.
Expand All @@ -40,6 +42,9 @@
elif DEPLOYMENT_BACKEND == 'vm':
PROXY_BASE_URL = config('PROXY_BASE_URL')
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=PROXY_BASE_URL).split(',')
elif DEPLOYMENT_BACKEND == 'gcp':
PROXY_BASE_URL = config('PROXY_BASE_URL')
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=PROXY_BASE_URL).split(',')
else:
PROXY_BASE_URL = config('PROXY_BASE_URL', 'http://127.0.0.1:3030')
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
Expand Down Expand Up @@ -170,15 +175,29 @@

# Email Settings

SMTP_URL = config('SMTP_URL', default=None)
SMTP_CONNECTION = urlparse(SMTP_URL) if SMTP_URL else None

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = config('EMAIL_HOST', default=None)
EMAIL_PORT = config('EMAIL_PORT', default=None)
EMAIL_HOST_USER = config('EMAIL_HOST_USER', default=None)
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default=None)
DEFAULT_FROM_EMAIL = config('ADMIN_EMAIL', default=None)
DEFAULT_FROM_EMAIL = config('ACCOUNTS_EMAIL', default=None)

EMAIL_HOST = SMTP_CONNECTION.hostname if SMTP_CONNECTION else None
EMAIL_PORT = SMTP_CONNECTION.port if SMTP_CONNECTION else None
EMAIL_HOST_USER = SMTP_CONNECTION.username if SMTP_CONNECTION else None
EMAIL_HOST_PASSWORD = SMTP_CONNECTION.password if SMTP_CONNECTION else None

if SMTP_CONNECTION and SMTP_CONNECTION.scheme == "smtp":
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
elif SMTP_CONNECTION and SMTP_CONNECTION.scheme == "smtps":
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
elif SMTP_CONNECTION:
raise ValueError("Unsupported SMTP URL scheme. Use 'smtp' or 'smtps'.")


# Deployment Settings

if DEPLOYMENT_BACKEND == 'aws':
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID', default=None)
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY', default=None)
Expand Down
5 changes: 5 additions & 0 deletions hydroserver/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
import os

from django.core.wsgi import get_wsgi_application
from django.core.management import call_command

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hydroserver.settings')

application = get_wsgi_application()

call_command('migrate')
call_command('setup_admin_user')
call_command('setup_observations')

0 comments on commit 8922c75

Please sign in to comment.