Skip to content
Snippets Groups Projects
Verified Commit 357b2987 authored by Tanner Prestegard's avatar Tanner Prestegard
Browse files

Add database routing configuration for production

Non-priority production containers will use the master for
writes and a read-replica database for reads. This commit adds
functionality for getting the replica's information from
environment variables and sets up a database routing scheme.
parent 37dd5c29
No related branches found
No related tags found
No related merge requests found
# Settings for a production GraceDB instance running in a container
import copy
from django.core.exceptions import ImproperlyConfigured
from .base import *
DEBUG = False
......@@ -15,12 +17,46 @@ if (isinstance(is_priority_server, str) and
is_priority_server.lower() in ['true', 't']):
PRIORITY_SERVER = True
# If priority server, add custom permissions for API
# If priority server, do some things
if PRIORITY_SERVER:
# Add custom permissions for API
default_perms = list(REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'])
default_perms = ['api.permissions.IsPriorityUser'] + default_perms
REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'] = tuple(default_perms)
# Don't do anything to databases. Priority servers use the master
# for both read and write operations
else:
# If not a priority server, we use the read-only replica database
# for reads and master for writes.
# Get information from environment variables
replica_db_name = os.environ.get('DJANGO_REPLICA_DB_NAME', None)
if replica_db_name is None:
raise ImproperlyConfigured('Could not get replica database name from '
'envvars.')
replica_db_password = os.environ.get('DJANGO_REPLICA_DB_PASSWORD', None)
if replica_db_password is None:
raise ImproperlyConfigured('Could not get replica database password '
'from envvars.')
# Set up dict and add to DATABASES setting
read_replica = {
'NAME': replica_db_name,
'ENGINE': 'django.db.backends.mysql',
'USER': os.environ.get('DJANGO_REPLICA_DB_USER', 'gracedb'),
'PASSWORD': replica_db_password,
'HOST': os.environ.get('DJANGO_REPLICA_DB_HOST', ''),
'PORT': os.environ.get('DJANGO_REPLICA_DB_PORT', ''),
'OPTIONS': {
'init_command': 'SET storage_engine=MyISAM',
},
}
DATABASES['read_replica'] = read_replica
# Set up database router
DATABASE_ROUTERS = ['core.db.routers.NonPriorityRouter',]
# Safety check on debug mode for production
if (DEBUG == True):
raise RuntimeError("Turn off debug mode for production")
class NonPriorityRouter(object):
"""For non-priority production workers in a swarm container deployment"""
def db_for_read(self, model, **hints):
return 'read_replica'
def db_for_write(self, model, **hints):
return 'default'
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment