From c288fc19fd7430bf5fc403b0d51fc5dda758f033 Mon Sep 17 00:00:00 2001 From: Justin Slay Date: Sat, 24 Sep 2022 06:07:51 -0600 Subject: [PATCH] Alpine, Gunicorn, and Helm --- .dockerignore | 14 ++ Dockerfile | 48 ++++++ ccdb5_api/settings.py | 24 ++- docker-entrypoint.sh | 51 +++++++ gunicorn.conf.py | 48 ++++++ helm/.gitignore | 1 + helm/ccdb5-api/.helmignore | 23 +++ helm/ccdb5-api/Chart.lock | 12 ++ helm/ccdb5-api/Chart.yaml | 39 +++++ helm/ccdb5-api/templates/NOTES.txt | 22 +++ helm/ccdb5-api/templates/_helpers.tpl | 138 ++++++++++++++++++ helm/ccdb5-api/templates/deployment.yaml | 94 ++++++++++++ helm/ccdb5-api/templates/hpa.yaml | 28 ++++ helm/ccdb5-api/templates/ingress.yaml | 61 ++++++++ helm/ccdb5-api/templates/service.yaml | 15 ++ helm/ccdb5-api/templates/serviceaccount.yaml | 12 ++ .../templates/tests/test-connection.yaml | 15 ++ helm/ccdb5-api/values.yaml | 126 ++++++++++++++++ initial-data.sh | 20 +++ refresh-data.sh | 87 +++++++++++ setup.py | 10 +- 21 files changed, 880 insertions(+), 8 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100755 docker-entrypoint.sh create mode 100644 gunicorn.conf.py create mode 100644 helm/.gitignore create mode 100644 helm/ccdb5-api/.helmignore create mode 100644 helm/ccdb5-api/Chart.lock create mode 100644 helm/ccdb5-api/Chart.yaml create mode 100644 helm/ccdb5-api/templates/NOTES.txt create mode 100644 helm/ccdb5-api/templates/_helpers.tpl create mode 100644 helm/ccdb5-api/templates/deployment.yaml create mode 100644 helm/ccdb5-api/templates/hpa.yaml create mode 100644 helm/ccdb5-api/templates/ingress.yaml create mode 100644 helm/ccdb5-api/templates/service.yaml create mode 100644 helm/ccdb5-api/templates/serviceaccount.yaml create mode 100644 helm/ccdb5-api/templates/tests/test-connection.yaml create mode 100644 helm/ccdb5-api/values.yaml create mode 100755 initial-data.sh create mode 100755 refresh-data.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..8ccbdfe5 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +# Ignore all +** + +# ...except these directories +!ccdb5_api +!complaint_search + +# ...and these files +!docker-entrypoint.sh +!manage.py +!initial-data.sh +!refresh-data.sh +!setup.py +!gunicorn.conf.py diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..04bba921 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,48 @@ +FROM python:3.8-alpine as base + +# Hard labels +LABEL maintainer="tech@cfpb.gov" + +# Ensure that the environment uses UTF-8 encoding by default +ENV LANG en_US.UTF-8 +ENV ENV /etc/profile +ENV PIP_NO_CACHE_DIR true +# Stops Python default buffering to stdout, improving logging to the console. +ENV PYTHONUNBUFFERED 1 +ENV APP_HOME /src/app +ENV ALLOWED_HOSTS '["*"]' + +WORKDIR ${APP_HOME} + +RUN apk update --no-cache && apk upgrade --no-cache && \ + pip install --upgrade pip setuptools + +FROM base as builder + +RUN apk add --no-cache --virtual .build-deps gcc git libffi-dev musl-dev postgresql-dev + +COPY setup.py setup.py +RUN mkdir /build && pip install --prefix=/build . + +FROM base as dev + +RUN apk add --no-cahce --virtual .backend-deps curl postgresql + +COPY --from=builder /build /usr/local +COPY setup.py setup.py +RUN pip install '.[testing]' + +EXPOSE 8000 + +ENTRYPOINT ["./docker-entrypoint.sh"] +CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] + +FROM base as final + +COPY --from=builder /build /usr/local +RUN pip install gunicorn +RUN apk add --no-cache --virtual .deps postgresql-client + +COPY . . + +CMD ["gunicorn", "-c", "gunicorn.conf.py"] diff --git a/ccdb5_api/settings.py b/ccdb5_api/settings.py index 3ed67c00..62b2d570 100644 --- a/ccdb5_api/settings.py +++ b/ccdb5_api/settings.py @@ -29,7 +29,7 @@ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS = [] +ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", []) # Application definition @@ -98,12 +98,24 @@ # Database # https://docs.djangoproject.com/en/stable/ref/settings/#databases -DATABASES = { - "default": { - "ENGINE": "django.db.backends.sqlite3", - "NAME": os.path.join(BASE_DIR, "db.sqlite3"), +if os.getenv("PGUSER"): + DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": os.getenv("PGDATABASE", "ccdb"), + "USER": os.getenv("PGUSER", "cfpb"), + "PASSWORD": os.getenv("PGPASSWORD", "cfpb"), + "HOST": os.getenv("PGHOST", "localhost"), + "PORT": os.getenv("PGPORT", "5432"), + } + } +else: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": os.path.join(BASE_DIR, "db.sqlite3"), + } } -} # Internationalization diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100755 index 00000000..abcbb08f --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,51 @@ +#!/bin/sh + +set -e + +if [ -f '.env' ]; then + . '.env' +fi + +echo "Using $(python3 --version 2>&1) located at $(which python3)" + +# Do first-time set up of the database if necessary +if [ ! -z "$RUN_MIGRATIONS" ]; then + # Wait for the database to be ready for initialization tasks + if [ ! -z "$PGHOST" ]; then + until pg_isready --host="${PGHOST:-localhost}" --port="${PGPORT:-5432}" + do + echo "Waiting for postgres at: ${PGHOST:-localhost}:${PGPORT:-5432}" + sleep 1; + done + + # Check the DB if it needs refresh or migrations (initial-data.sh) + if ! psql "postgres://${PGUSER:-cfpb}:${PGPASSWORD:-cfpb}@${PGHOST:-localhost}:${PGPORT:-5432}/${PGDATABASE:-ccdb}" -c 'SELECT COUNT(*) FROM auth_user' >/dev/null 2>&1 || [ ! -z $FORCE_DB_REBUILD ]; then + echo "Doing first-time database and search index setup..." + if [ -n "$DB_DUMP_FILE" ] || [ -n "$DB_DUMP_URL" ]; then + echo "Running refresh-data.sh... $DB_DUMP_FILE" + ./refresh-data.sh "$DB_DUMP_FILE" + echo "Create the cache table..." + ./manage.py createcachetable + + # refresh-data.sh runs migrations, + # unset vars to prevent further action + unset RUN_MIGRATIONS + else + # Detected the database is empty, or force rebuild was requested, + # but we have no valid data sources to load data. + echo "WARNING: Database rebuild request detected, but missing DB_DUMP_FILE/DB_DUMP_URL variable. Unable to load data!!" + fi + else + echo "Data detected, FORCE_DB_REBUILD not requested. Skipping data load!" + fi + fi + + # Check if we still need to run migrations, if so, run them + if [ ! -z $RUN_MIGRATIONS ]; then + echo "Running initial-data.sh (migrations)..." + ./initial-data.sh + fi +fi + +# Execute the Docker CMD +exec "$@" diff --git a/gunicorn.conf.py b/gunicorn.conf.py new file mode 100644 index 00000000..5baa6f3d --- /dev/null +++ b/gunicorn.conf.py @@ -0,0 +1,48 @@ +import json +import multiprocessing +import os + +from __future__ import print_function # noqa: F404 + + +# Django WSGI application path in pattern MODULE_NAME:VARIABLE_NAME +wsgi_app = "ccdb5_api.wsgi:application" + +workers_per_core_str = os.getenv("WORKERS_PER_CORE", "2") +web_concurrency_str = os.getenv("WEB_CONCURRENCY", None) +host = os.getenv("HOST", "0.0.0.0") +port = os.getenv("PORT", "8000") +bind_env = os.getenv("BIND", None) +use_loglevel = os.getenv("LOG_LEVEL", "info").lower() +if bind_env: + use_bind = bind_env +else: + use_bind = "{host}:{port}".format(host=host, port=port) + +cores = multiprocessing.cpu_count() +workers_per_core = float(workers_per_core_str) +default_web_concurrency = workers_per_core * cores +if web_concurrency_str: + web_concurrency = int(web_concurrency_str) + assert web_concurrency > 0 +else: + web_concurrency = int(default_web_concurrency) + +# Gunicorn config variables +loglevel = use_loglevel +workers = web_concurrency +bind = use_bind +keepalive = 120 +errorlog = "-" + +# For debugging and testing +log_data = { + "loglevel": loglevel, + "workers": workers, + "bind": bind, + # Additional, non-gunicorn variables + "workers_per_core": workers_per_core, + "host": host, + "port": port, +} +print(json.dumps(log_data)) diff --git a/helm/.gitignore b/helm/.gitignore new file mode 100644 index 00000000..ee3892e8 --- /dev/null +++ b/helm/.gitignore @@ -0,0 +1 @@ +charts/ diff --git a/helm/ccdb5-api/.helmignore b/helm/ccdb5-api/.helmignore new file mode 100644 index 00000000..0e8a0eb3 --- /dev/null +++ b/helm/ccdb5-api/.helmignore @@ -0,0 +1,23 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*.orig +*~ +# Various IDEs +.project +.idea/ +*.tmproj +.vscode/ diff --git a/helm/ccdb5-api/Chart.lock b/helm/ccdb5-api/Chart.lock new file mode 100644 index 00000000..99f0731a --- /dev/null +++ b/helm/ccdb5-api/Chart.lock @@ -0,0 +1,12 @@ +dependencies: +- name: postgresql + repository: https://charts.bitnami.com/bitnami + version: 11.6.19 +- name: opensearch + repository: https://opensearch-project.github.io/helm-charts/ + version: 2.0.0 +- name: opensearch-dashboards + repository: https://opensearch-project.github.io/helm-charts/ + version: 2.0.0 +digest: sha256:7726e430c78cab54ca25b6032b9267d6b2e4a3d5576822d44697a80d81d2073a +generated: "2022-09-24T05:19:15.252965-06:00" diff --git a/helm/ccdb5-api/Chart.yaml b/helm/ccdb5-api/Chart.yaml new file mode 100644 index 00000000..af558004 --- /dev/null +++ b/helm/ccdb5-api/Chart.yaml @@ -0,0 +1,39 @@ +apiVersion: v2 +name: ccdb5-api +description: A Helm chart for Kubernetes + +# A chart can be either an 'application' or a 'library' chart. +# +# Application charts are a collection of templates that can be packaged into versioned archives +# to be deployed. +# +# Library charts provide useful utilities or functions for the chart developer. They're included as +# a dependency of application charts to inject those utilities and functions into the rendering +# pipeline. Library charts do not define any templates and therefore cannot be deployed. +type: application + +# This is the chart version. This version number should be incremented each time you make changes +# to the chart and its templates, including the app version. +# Versions are expected to follow Semantic Versioning (https://semver.org/) +version: 0.1.0 + +# This is the version number of the application being deployed. This version number should be +# incremented each time you make changes to the application. Versions are not expected to +# follow Semantic Versioning. They should reflect the version the application is using. +# It is recommended to use it with quotes. +appVersion: "1.16.0" + +# Dependency Charts +dependencies: + - name: postgresql + version: "11.6.19" + repository: "https://charts.bitnami.com/bitnami" + condition: postgresql.enabled + - name: opensearch + version: "1.14.1" + repository: "https://opensearch-project.github.io/helm-charts/" + condition: opensearch.enabled + - name: opensearch-dashboards + version: "1.8.3" + repository: "https://opensearch-project.github.io/helm-charts/" + condition: opensearch-dashboards.enabled diff --git a/helm/ccdb5-api/templates/NOTES.txt b/helm/ccdb5-api/templates/NOTES.txt new file mode 100644 index 00000000..edac6dde --- /dev/null +++ b/helm/ccdb5-api/templates/NOTES.txt @@ -0,0 +1,22 @@ +1. Get the application URL by running these commands: +{{- if .Values.ingress.enabled }} +{{- range $host := .Values.ingress.hosts }} + {{- range .paths }} + http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }} + {{- end }} +{{- end }} +{{- else if contains "NodePort" .Values.service.type }} + export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "ccdb5-api.fullname" . }}) + export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") + echo http://$NODE_IP:$NODE_PORT +{{- else if contains "LoadBalancer" .Values.service.type }} + NOTE: It may take a few minutes for the LoadBalancer IP to be available. + You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "ccdb5-api.fullname" . }}' + export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "ccdb5-api.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}") + echo http://$SERVICE_IP:{{ .Values.service.port }} +{{- else if contains "ClusterIP" .Values.service.type }} + export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "ccdb5-api.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") + export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") + echo "Visit http://127.0.0.1:8080 to use your application" + kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT +{{- end }} diff --git a/helm/ccdb5-api/templates/_helpers.tpl b/helm/ccdb5-api/templates/_helpers.tpl new file mode 100644 index 00000000..0bebfa5b --- /dev/null +++ b/helm/ccdb5-api/templates/_helpers.tpl @@ -0,0 +1,138 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "ccdb5-api.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "ccdb5-api.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "ccdb5-api.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "ccdb5-api.labels" -}} +helm.sh/chart: {{ include "ccdb5-api.chart" . }} +{{ include "ccdb5-api.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "ccdb5-api.selectorLabels" -}} +app.kubernetes.io/name: {{ include "ccdb5-api.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "ccdb5-api.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "ccdb5-api.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} + + +{{/* +Postgres Environment Vars +*/}} +{{- define "ccdb5-api.postgresEnv" -}} +{{- if .Values.postgresql.enabled -}} +- name: PGUSER + value: "{{ include "postgresql.username" .Subcharts.postgresql | default "postgres" }}" +- name: PGPASSWORD + valueFrom: + secretKeyRef: + name: {{ include "postgresql.secretName" .Subcharts.postgresql }} + key: {{ include "postgresql.userPasswordKey" .Subcharts.postgresql }} +- name: PGHOST + value: "{{ include "postgresql.primary.fullname" .Subcharts.postgresql | trunc 63 | trimSuffix "-" }}" +- name: PGDATABASE + value: "{{ include "postgresql.database" .Subcharts.postgresql | default "postgres" }}" +- name: PGPORT + value: "{{ include "postgresql.service.port" .Subcharts.postgresql }}" +{{- else }} +{{- if .Values.postgresql.auth.createSecret -}} +- name: PGUSER + valueFrom: + secretKeyRef: + name: {{ include "ccdb5-api.fullname" . }}-postgres + key: username +- name: PGPASSWORD + valueFrom: + secretKeyRef: + name: {{ include "ccdb5-api.fullname" . }}-postgres + key: password +- name: PGDATABASE + valueFrom: + secretKeyRef: + name: {{ include "ccdb5-api.fullname" . }}-postgres + key: database +{{- else }} +- name: PGUSER + value: "{{ .Values.postgresql.auth.username | default "postgres" }}" +- name: PGPASSWORD + value: {{ .Values.postgresql.auth.password | quote }} +- name: PGDATABASE + value: "{{ .Values.postgresql.auth.database | default "postgres" }}" +{{- end }} +- name: PGHOST + value: {{ .Values.postgresql.external.host | quote }} +- name: PGPORT + value: "{{ .Values.postgresql.external.port | default "5432" }}" +{{- end }} +{{- end }} + +{{/* +Opensearch Environment Vars +*/}} +{{- define "ccdb5-api.opensearchEnv" -}} +- name: ES_SCHEME + value: "{{ default "https" .Values.opensearch.protocol }}" +- name: ES_HOST +{{- if .Values.opensearch.enabled }} + value: "{{ include "opensearch.serviceName" .Subcharts.opensearch }}" +{{- else }} + value: {{ .Values.opensearch.hostname | quote }} +{{- end }} +- name: ES_PORT + value: {{ .Values.opensearch.httpPort | quote }} +{{- end }} + + +{{/* +Main container Environment Vars +*/}} +{{- define "ccdb5-api.env" -}} +{{ include "ccdb5-api.postgresEnv" . }} +{{ include "ccdb5-api.opensearchEnv" . }} +{{- end }} diff --git a/helm/ccdb5-api/templates/deployment.yaml b/helm/ccdb5-api/templates/deployment.yaml new file mode 100644 index 00000000..d10ddbd6 --- /dev/null +++ b/helm/ccdb5-api/templates/deployment.yaml @@ -0,0 +1,94 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "ccdb5-api.fullname" . }} + labels: + {{- include "ccdb5-api.labels" . | nindent 4 }} +spec: + {{- if not .Values.autoscaling.enabled }} + replicas: {{ .Values.replicaCount }} + {{- end }} + selector: + matchLabels: + {{- include "ccdb5-api.selectorLabels" . | nindent 6 }} + template: + metadata: + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + labels: + {{- include "ccdb5-api.selectorLabels" . | nindent 8 }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + serviceAccountName: {{ include "ccdb5-api.serviceAccountName" . }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + initContainers: + - name: {{ .Chart.Name }}-migrations + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: + {{- toYaml .Values.initContainer.command | nindent 12 }} + args: + {{- toYaml .Values.initContainer.args | nindent 12 }} + volumeMounts: + {{- range .Values.volumes }} + - mountPath: {{ .mountPath }} + name: {{ .name }} + {{- end }} + env: + {{ include "ccdb5-api.env" . | nindent 12 }} + - name: RUN_MIGRATIONS + value: "true" + resources: + {{- toYaml .Values.resources | nindent 12 }} + containers: + - name: {{ .Chart.Name }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + volumeMounts: + {{- range .Values.volumes }} + - mountPath: {{ .mountPath }} + name: {{ .name }} + {{- end }} + env: + {{ include "ccdb5-api.env" . | nindent 12 }} + ports: + - name: http + containerPort: 8000 + protocol: TCP + livenessProbe: + httpGet: + path: / + port: http + readinessProbe: + httpGet: + path: / + port: http + resources: + {{- toYaml .Values.resources | nindent 12 }} + volumes: + {{- range .Values.volumes }} + - name: {{ .name }} + {{- toYaml .volume | nindent 10 }} + {{- end }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/helm/ccdb5-api/templates/hpa.yaml b/helm/ccdb5-api/templates/hpa.yaml new file mode 100644 index 00000000..c8a67da0 --- /dev/null +++ b/helm/ccdb5-api/templates/hpa.yaml @@ -0,0 +1,28 @@ +{{- if .Values.autoscaling.enabled }} +apiVersion: autoscaling/v2beta1 +kind: HorizontalPodAutoscaler +metadata: + name: {{ include "ccdb5-api.fullname" . }} + labels: + {{- include "ccdb5-api.labels" . | nindent 4 }} +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{ include "ccdb5-api.fullname" . }} + minReplicas: {{ .Values.autoscaling.minReplicas }} + maxReplicas: {{ .Values.autoscaling.maxReplicas }} + metrics: + {{- if .Values.autoscaling.targetCPUUtilizationPercentage }} + - type: Resource + resource: + name: cpu + targetAverageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} + {{- end }} + {{- if .Values.autoscaling.targetMemoryUtilizationPercentage }} + - type: Resource + resource: + name: memory + targetAverageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }} + {{- end }} +{{- end }} diff --git a/helm/ccdb5-api/templates/ingress.yaml b/helm/ccdb5-api/templates/ingress.yaml new file mode 100644 index 00000000..4ba2fe3d --- /dev/null +++ b/helm/ccdb5-api/templates/ingress.yaml @@ -0,0 +1,61 @@ +{{- if .Values.ingress.enabled -}} +{{- $fullName := include "ccdb5-api.fullname" . -}} +{{- $svcPort := .Values.service.port -}} +{{- if and .Values.ingress.className (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) }} + {{- if not (hasKey .Values.ingress.annotations "kubernetes.io/ingress.class") }} + {{- $_ := set .Values.ingress.annotations "kubernetes.io/ingress.class" .Values.ingress.className}} + {{- end }} +{{- end }} +{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}} +apiVersion: networking.k8s.io/v1 +{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}} +apiVersion: networking.k8s.io/v1beta1 +{{- else -}} +apiVersion: extensions/v1beta1 +{{- end }} +kind: Ingress +metadata: + name: {{ $fullName }} + labels: + {{- include "ccdb5-api.labels" . | nindent 4 }} + {{- with .Values.ingress.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- if and .Values.ingress.className (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) }} + ingressClassName: {{ .Values.ingress.className }} + {{- end }} + {{- if .Values.ingress.tls }} + tls: + {{- range .Values.ingress.tls }} + - hosts: + {{- range .hosts }} + - {{ . | quote }} + {{- end }} + secretName: {{ .secretName }} + {{- end }} + {{- end }} + rules: + {{- range .Values.ingress.hosts }} + - host: {{ .host | quote }} + http: + paths: + {{- range .paths }} + - path: {{ .path }} + {{- if and .pathType (semverCompare ">=1.18-0" $.Capabilities.KubeVersion.GitVersion) }} + pathType: {{ .pathType }} + {{- end }} + backend: + {{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }} + service: + name: {{ $fullName }} + port: + number: {{ $svcPort }} + {{- else }} + serviceName: {{ $fullName }} + servicePort: {{ $svcPort }} + {{- end }} + {{- end }} + {{- end }} +{{- end }} diff --git a/helm/ccdb5-api/templates/service.yaml b/helm/ccdb5-api/templates/service.yaml new file mode 100644 index 00000000..ded049f0 --- /dev/null +++ b/helm/ccdb5-api/templates/service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "ccdb5-api.fullname" . }} + labels: + {{- include "ccdb5-api.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + name: http + selector: + {{- include "ccdb5-api.selectorLabels" . | nindent 4 }} diff --git a/helm/ccdb5-api/templates/serviceaccount.yaml b/helm/ccdb5-api/templates/serviceaccount.yaml new file mode 100644 index 00000000..2204126c --- /dev/null +++ b/helm/ccdb5-api/templates/serviceaccount.yaml @@ -0,0 +1,12 @@ +{{- if .Values.serviceAccount.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "ccdb5-api.serviceAccountName" . }} + labels: + {{- include "ccdb5-api.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/helm/ccdb5-api/templates/tests/test-connection.yaml b/helm/ccdb5-api/templates/tests/test-connection.yaml new file mode 100644 index 00000000..1efd2d47 --- /dev/null +++ b/helm/ccdb5-api/templates/tests/test-connection.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Pod +metadata: + name: "{{ include "ccdb5-api.fullname" . }}-test-connection" + labels: + {{- include "ccdb5-api.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": test +spec: + containers: + - name: wget + image: busybox + command: ['wget'] + args: ['{{ include "ccdb5-api.fullname" . }}:{{ .Values.service.port }}'] + restartPolicy: Never diff --git a/helm/ccdb5-api/values.yaml b/helm/ccdb5-api/values.yaml new file mode 100644 index 00000000..35ba8cf2 --- /dev/null +++ b/helm/ccdb5-api/values.yaml @@ -0,0 +1,126 @@ +# Default values for ccdb5-api. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +replicaCount: 1 + +image: + repository: ccdb5-api + pullPolicy: IfNotPresent + # Overrides the image tag whose default is the chart appVersion. + tag: local + +imagePullSecrets: [] + +initContainer: + command: + - "./docker-entrypoint.sh" + args: [] + +nameOverride: "" +fullnameOverride: "" + +serviceAccount: + # Specifies whether a service account should be created + create: true + # Annotations to add to the service account + annotations: {} + # The name of the service account to use. + # If not set and create is true, a name is generated using the fullname template + name: "" + +podAnnotations: {} + +podSecurityContext: {} + # fsGroup: 2000 + +securityContext: {} + # capabilities: + # drop: + # - ALL + # readOnlyRootFilesystem: true + # runAsNonRoot: true + # runAsUser: 1000 + +service: + type: ClusterIP + port: 80 + +ingress: + enabled: false + className: "" + annotations: {} + # kubernetes.io/ingress.class: nginx + # kubernetes.io/tls-acme: "true" + hosts: + - host: chart-example.local + paths: + - path: / + pathType: ImplementationSpecific + tls: [] + # - secretName: chart-example-tls + # hosts: + # - chart-example.local + +resources: {} + # We usually recommend not to specify default resources and to leave this as a conscious + # choice for the user. This also increases chances charts run on environments with little + # resources, such as Minikube. If you do want to specify resources, uncomment the following + # lines, adjust them as necessary, and remove the curly braces after 'resources:'. + # limits: + # cpu: 100m + # memory: 128Mi + # requests: + # cpu: 100m + # memory: 128Mi + +autoscaling: + enabled: false + minReplicas: 1 + maxReplicas: 100 + targetCPUUtilizationPercentage: 80 + # targetMemoryUtilizationPercentage: 80 + +nodeSelector: {} + +tolerations: [] + +affinity: {} + +volumes: [] + +### SERVICES ### +# Postgres Values +postgresql: + enabled: true # Deploy child chart, if false, uses external host and port + auth: + # username: "" # Used for both chart and external db's + # password: "" # Used for both chart and external db's + # database: "" # Used for both chart and external db's + createSecret: true # Only valid when using external database + external: + host: "" + port: "" + primary: + persistence: + enabled: false + service: + type: ClusterIP + +# Opensearch Values +opensearch: + enabled: true + protocol: https + httpPort: 9200 + hostname: "" # Only used when not using child chart + service: + type: ClusterIP + persistence: + enabled: false # Disable persistence for local by default + replicas: 2 + +# Opensearch Dashboard Values +opensearch-dashboards: + enabled: false + service: + type: ClusterIP diff --git a/initial-data.sh b/initial-data.sh new file mode 100755 index 00000000..b3c94bed --- /dev/null +++ b/initial-data.sh @@ -0,0 +1,20 @@ +#!/bin/sh + +# ========================================================================== +# Initialization script for a wagtail user and imported data. +# NOTE: Run this script while in the project root directory. +# It will not run correctly when run from another directory. +# ========================================================================== + +# Set script to exit on any errors. +set -e + +# Import Data +import_data(){ + echo 'Running Django migrations...' + ./manage.py migrate + echo 'Creating any necessary Django database cache tables...' + ./manage.py createcachetable +} + +import_data diff --git a/refresh-data.sh b/refresh-data.sh new file mode 100755 index 00000000..ff45a806 --- /dev/null +++ b/refresh-data.sh @@ -0,0 +1,87 @@ +#!/bin/sh + +# ========================================================================== +# Import data from a gzipped dump. Provide the filename as the first arg. +# NOTE: Run this script while in the project root directory. +# It will not run correctly when run from another directory. +# ========================================================================== + +set -e + +usage() { + cat << EOF +Please download a recent database dump before running this script: + + ./refresh-data.sh production_django.sql.gz + +Or you can define the location of a dump and this script will +download it for you: + + export DB_DUMP_URL=https://example.com/production_django.sql.gz + ./refresh-data.sh + +EOF + exit 1; +} + +download_data() { + echo 'Downloading database dump...' + skip_download=0 + + # If the file already exists, check its timestamp, and skip the download + # if it matches the timestamp of the remote file. + if [ -f "$refresh_dump_name" ]; then + timestamp_check=$(curl -s -I -R -L -z "$refresh_dump_name" "${DB_DUMP_URL}") + if [ -z "${$timestamp_check##*'304 Not Modified'*}" ]; then + echo 'Skipping download as local timestamp matches remote timestamp' + skip_download=1 + fi + fi + + if [ "$skip_download" = "0" ]; then + curl -RL -o "$refresh_dump_name" "${DB_DUMP_URL}" + fi +} + +check_data() { + echo 'Validating local dump file' + gunzip -t "$refresh_dump_name" +} + +refresh_data() { + echo 'Importing refresh db' + gunzip < "$refresh_dump_name" | cfgov/manage.py dbshell > /dev/null + SCHEMA="$(gunzip -c $refresh_dump_name | grep -m 1 'CREATE SCHEMA' | sed 's/CREATE SCHEMA \(.*\);$/\1/')" + PGUSER="${PGUSER:-cfpb}" + if [ "${PGUSER}" != "${SCHEMA}" ]; then + echo "Adjusting schema name to match username..." + echo "DROP SCHEMA IF EXISTS \"${PGUSER}\" CASCADE; \ + ALTER SCHEMA \"${SCHEMA}\" RENAME TO \"${PGUSER}\"" | psql > /dev/null 2>&1 + fi + echo 'Running any necessary migrations' + ./cfgov/manage.py migrate --noinput --fake-initial + echo 'Setting up initial data' + ./cfgov/manage.py runscript initial_data +} + +get_data() { + if [ -z "$refresh_dump_name" ]; then + if [ -z "$DB_DUMP_URL" ]; then + usage + fi + # Split URL, and get the file name. + refresh_dump_name="$(echo $DB_DUMP_URL | tr '/' '\n' | tail -1)" + download_data + else + if [ $refresh_dump_name != *.sql.gz ]; then + echo "Input dump '$refresh_dump_name' expected to end with .sql.gz." + exit 2 + fi + fi +} + +refresh_dump_name=$@ + +get_data +check_data +refresh_data diff --git a/setup.py b/setup.py index ef81c495..a8fc900f 100644 --- a/setup.py +++ b/setup.py @@ -33,6 +33,8 @@ def format_version(version, fmt=fmt): def get_git_version(): + if not os.path.isdir(".git"): + return "container" git_version = check_output(command.split()).decode("utf-8").strip() return format_version(version=git_version) @@ -43,8 +45,11 @@ def get_git_version(): here = os.path.abspath(os.path.dirname(__file__)) -with open(os.path.join(here, "README.md"), encoding="utf-8") as f: - long_description = f.read() +if os.path.isfile(os.path.join(here, "README.md")): + with open(os.path.join(here, "README.md"), encoding="utf-8") as f: + long_description = f.read() +else: + long_description = "CCDB API" install_requires = [ @@ -56,6 +61,7 @@ def get_git_version(): "django-localflavor>=1.1,<3.1", "django-flags>=4.0.1,<5.1", "requests-aws4auth", + "psycopg2-binary==2.8.6", ] testing_extras = [