Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Update deployment doc and add zero-downtime info about environment variables (#907)
sarayourfriend6935076649ee
diff --git a/documentation/guides/deploy.md b/documentation/guides/deploy.mddeleted file mode 100644index c52340924..000000000--- a/documentation/guides/deploy.md+++ /dev/null@@ -1,3 +0,0 @@-# Deploy--🚧diff --git a/documentation/guides/deployment.md b/documentation/guides/deployment.mdnew file mode 100644index 000000000..62bb943c3--- /dev/null+++ b/documentation/guides/deployment.md@@ -0,0 +1,220 @@+# Deployments++This document covers API and Frontend deployments. It does not include+information regarding the ingestion server or our Airflow instance.++## Real-time Deployment Information++### Frontend++| Environment | Deployment Log | URL | Version Endpoint |+| ----------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------- |+| Staging | [Deployment Log](https://github.com/WordPress/openverse/actions/workflows/deploy-staging-nuxt.yml) | <https://staging.openverse.org> | [`/version.json`](https://staging.openverse.org/version.json) |+| Production | [Deployment Log](https://github.com/WordPress/openverse/actions/workflows/deploy-production-nuxt.yml) | <https://production.openverse.org> | [`/version.json`](https://production.openverse.org/version.json) |++### API++| Environment | Deployment Log | URL | Version Endpoint |+| ----------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------- | --------------------------------------------------------------- |+| Staging | [Deployment Log](https://github.com/WordPress/openverse/actions/workflows/deploy-staging-api.yml) | <https://api-staging.openverse.engineering> | [`/version`](https://api-staging.openverse.engineering/version) |+| Production | [Deployment Log](https://github.com/WordPress/openverse/actions/workflows/deploy-production-api.yml) | <https://api.openverse.engineering> | [`/version`](https://api.openverse.engineering/version) |++## Overview++The Openverse Nuxt frontend and Django API are deployed using AWS's Elastic+Container Service. Both are encapsulated into single ECS services per+environment. The overall approach of deployments is to generate a new _task+definition_ and to associate that task definition with the ECS Service. This+causes the service to deploy the new task definition as a newly running _task_.+Once the service has determined the new task to be healthy, it will redirect all+traffic to the new task away from the old task. This is called _draining_. Once+the old task is drained, it is spun down and the only task left running is the+new one. The same process is followed when there are multiple tasks and each+task is drained one at a time following our+[zero-downtime approach to deployments](https://docs.openverse.org/guides/zero-downtime-database-management.html).++```{note}+The number of running tasks per active task definition may vary per+environment but has no bearings on the deployment process. The size of the+service is handled entirely on the infrastructure side. The process above is+completely automated and contributors generally do not need to be acutely+aware of the "behind the scenes" stuff going on, but it can be helpful for+understanding what is happening during a deployment.+```++## Deployment Workflow++Deployments for all environments follow the same general workflow. **This+workflow is completely automated and auditable via GitHub Workflows.**++1. Build and publish the docker image(s) for the application and tag+ appropriately for the deployment.+ - This happens inside the+ [`ci_cd.yml` workflow](https://github.com/WordPress/openverse/blob/2646c5ead465603b42c70f58a190f7b50861d698/.github/workflows/ci_cd.yml#L866)+ rather than the deployment workflows.+2. Download the template task definition from AWS for the environment and+ application being deployed. Render a new task definition based on the+ template, changing the following:+ 1. The new image tag(s)+ 2. Remove the `-template` suffix from the family name (essentially removing+ the "template" identifiers present in the template)+3. Register the new rendered task definition to the ECS service.+ - This causes the ECS service to begin deploying the new task definition.+4. Wait for the ECS service to report that it is stable.+ - During this waiting period, the process described in the+ [opening paragraph](#overview) is orchestrated by ECS. This part is _not_+ transparent in the GitHub Workflows and will simply appear as a waiting+ step without any further information.++This process, from start to finish, generally takes less than 15 minutes. If it+takes longer than 15 then something is probably wrong.++### Failures++Failures are automatically handled and the Openverse maintainers are notified.+The GitHub Workflow log is the canonical source of truth of the record of our+deployment attempts. See the table at the top of this document for links to+these logs per environment.++If any of the steps described above fails, including the new task spin up and+switch over, the deployment is deemed a failure. If the failure occurs while+trying to start a new healthy task, the ECS service will automatically rollback+to the previous task definition revision. Remember that the previous task is not+drained and removed until the new task is determined to be healthy, so this+rollback has zero downtime. Automated rollbacks do not create a new task+definition revision, the service just uses the last healthy revision.++If the docker build fails then there is nothing to rollback. The failure needs+to be investigated and the issue fixed for deployments to be possible again.+This is unlikely to happen because we require valid Docker image builds as part+of our CI. Nonetheless, given certain semantic merge conflicts, it is possible+that a PR could pass CI and still cause a build failure when merged, so it is+technically possible for a failure to occur during the first step.++## Staging++Staging is automatically deployed any time code is merged to the `main` branch+of this repository. The frontend and API are deployed only when changes are+merged that pertain to each particular application. Staging deployments follow+the process above. The staging deployment workflows+[tag images with the commit SHA](https://github.com/WordPress/openverse/blob/2646c5ead465603b42c70f58a190f7b50861d698/.github/workflows/ci_cd.yml#L62).++## Production++Maintainers manually dispatch the production deployment via the+[Release app](https://github.com/WordPress/openverse/actions/workflows/release-app.yml)+workflow. The workflow requires the tag of an existing Docker image to tag as+the "released" image. It generates a date-based tag for the specific application+being released, publishes a GitHub Release (which creates a git tag), tags the+Docker image, and then triggers the deployment workflow. The workflow also opens+a PR to add the changelog to the+[documentation site's changelog directory](https://docs.openverse.org/changelogs/index.html).+This needs to be manually approved and merged by maintainers. The person who+triggers the release app workflow is pinged in the PR description to help with+the visibility of the PR.++The same workflow is used to create production release images for the ingestion+server. In that case the production deployment still needs to be handled via+Terraform.++## Rollbacks++Even if the deployment process described above succeeds, sometimes we may+realise that the deployed code is not behaving as we expected. In these cases it+may be necessary to force an environment to be deployed to a specific version,+usually the previous version of the application.++The same staging and production deployment workflows are used directly to+rollback any environment for any service. Only members of the+@WordPress/openverse-maintainers GitHub team are able to dispatch the workflows+to completion. Anyone else who tries to dispatch them will have the workflow+automatically fail.++The workflows require one input: `tag`, which must be a valid tag that exists in+the image repository for that application. The `tag` input is validated against+the available list of tags and the workflow will fail if the tag is determined+not to exist in the image repository. You can find a list of release tags for+specific apps by filtering git tags based on the tag prefix for the app:++```+$ git tag -l '<app slug>-*'+```++Replace `<app slug>` with `api`, `frontend`, or `ingestion_server` as needed.++After validating the tag and that the dispatcher is authorised, the Rollback+workflow follows the [deployment process described above](#deployment-workflow),+without building the Docker image as it reuses the existing image tagged with+the input.++## Environment Variables++When deploying code that depends on a new or updated environment variable, you+must follow the process below _before_ that code is deployed. This is the only+way to make the new or updated variable available for the code the depends on+it. Please see the+[zero-downtime deployments document's section on environment variables for an in-depth explanation of the rationale behind this process](https://docs.openverse.org/guides/zero-downtime-database-management.html#environment-variables).++1. Update the template task definition for the service with the new or updated+ environment variable.++ - Request help from `@WordPress/openverse-maintainers` if you're unable to do+ this yourself (i.e., if you do not have the ability to make changes to our+ Terraform configuration)++2. Deploy the code that depends on the new or updated variable by dispatching+ the appropriate deployment workflow for the application and envionment that+ was updated.+ - If the application only needs to be re-deployed to the already+ running-version, dispatch the workflow with the version present at the+ version endpoint for the application. See the "version endpoint" in the+ [real-time deployment information](#real-time-deployment-information)+ tables above to determine the currently running version.++## Future end-to-end test integration++In the future we hope to integrate end-to-end tests into this workflow and to+tighten the staging to production pipeline. Essentially, we would like the+deployment pipeline to go something like this:++1. Merge PR to `main`.+2. Wait for staging to deploy.+3. Playwright tests automatically run against the new staging environment+ (frontend and live API).+4. While Playwright tests are running, the person who merged the PR should+ manually verify that their change behaves as expected.+5. After the Playwright tests are confirmed to have passed, unlock a "deploy to+ production" button somewhere that pushes the image currently deployed to+ staging into the production task definition.++Following this process would effectively mean that production gets deployed+every time code is merged to `main`. It reduces the turn around for new features+and bug fixes because they don't have to wait for a new release to be manually+created.++We could more or less follow the process as described today just by creating a+new release every time we've merged to staging and verified our changes, but+there are a couple missing pieces that would need to be implemented to make this+process easy to follow, to varying degrees of difficulty:++1. We need a GitHub workflow that runs the Playwright tests against the staging+ deployment automatically after staging is deployed. This will require some+ Playwright configuration tweaks and increased test timeouts due to network+ latency.+2. We would need to create a queue so that new staging deployments do not occur+ until the current staging deployment is live on production. This could be+ implemented by polling the `/version.json` endpoints of both environments and+ only liberating a new staging deployment for new merges once the endpoints+ both report the same `release` property.+3. We would need to update the production deployment workflow to not create a+ new Docker build and instead just pull the current tag from the staging+ `/version.json` endpoint.++Note that this workflow does make the process of merging a PR heavier than it is+today. This comes with some benefits:++1. PRs will likely be more carefully tested as the consequence of merging them+ is higher and more immediate.+2. Bug fixes appear in production earlier.+3. Features can be rolled out with more care using feature flags and likewise+ more quickly.diff --git a/documentation/guides/index.md b/documentation/guides/index.mdindex bad3aff9b..c769910d1 100644--- a/documentation/guides/index.md+++ b/documentation/guides/index.md@@ -13,7 +13,7 @@ quickstart# test# https# publish-# deploy+deploymentloggingzero-downtime-database-management```diff --git a/documentation/guides/zero-downtime-database-management.md b/documentation/guides/zero-downtime-database-management.mdindex 7340280bc..8dee4a42d 100644--- a/documentation/guides/zero-downtime-database-management.md+++ b/documentation/guides/zero-downtime-database-management.md@@ -91,12 +91,14 @@ Other causes are variations on this same pattern: a shared dependency is neitherforward nor backwards compatible between two subsequent versions of theapplication.-> **Note**: This issue of incompatibility only applies to _subsequent_ versions-> of an application because only subsequent versions are ever deployed-> simultaneously with the same underlying support infrastructure. So long as-> there is at least one version between them, application versions may and-> indeed sometimes do have fundamental incompatibilities with each other and-> could not be simultaneously deployed.+```{note}+This issue of incompatibility only applies to _subsequent_ versions+of an application because only subsequent versions are ever deployed+simultaneously with the same underlying support infrastructure. So long as+there is at least one version between them, application versions may and+indeed sometimes do have fundamental incompatibilities with each other and+could not be simultaneously deployed.+```## How to achieve zero-downtime deployments@@ -290,3 +292,149 @@ a[non-atomic migration](https://docs.djangoproject.com/en/4.1/howto/writing-migrations/#non-atomic-migrations)can help make it easier to recover from unexpected errors without causing theentire transformation process to be reversed.++## Environment variables++In addition to careful database management, we must also take care when we+introduce or update environment variables and ensure that it is done in a way+compatible with zero-downtime deployments. While some issues and difficulties+are shared between zero-downtime database schema changes and environment+variable management, environment variables do have their own distinct issues to+be aware of.++### How we configure environment variables++In order to understand the potential issues that can arise in managing+environment variables, it is necessary to first understand the mechanisms used+to management them and how they are propogated to application instances.++Environment variables for applications and their environments are configured and+managed in the _task definition template_. The ECS service for each application+does not run the template. Rather, it runs a _rendered task definition_ derived+from the template. The critical piece here is that services run task definitions+_based_ on the template, but not the template itself. Therefore, to get new or+updated environment variables, it is necessary to render new application task+definitions based on the templates. **Updating the template does not+automatically update the application**.++New rendered task definitions are created during runs of the+[deployment workflow](https://wordpress.github.io/openverse/guides/deployment.html#deployment-workflow).+That means the following situations will render a new task definition:++- New version deployments, including automated staging deployments and manual+ production deployments+- Manual rollbacks where the deployment workflow is newly dispatched+- Redeployments of applications to the same version++New task definitions are _not_ rendered during _automated rollbacks_. That is,+if a deployment process fails, the previous working task definition revision is+used without modification. **Notably, this includes the previous configuration+of environment variables**.++To restate for clarity: provided the task definition template environment+variables have been updated, the only way to get new or updated environment+variables into a running application is by forcing a new deployment which in+turn creates a new task definition revision.++It can be easy to tangle up the concept of the application version and the task+definition revision, but they are separate. If an application is deployed to v1,+then to v2, then rolled back to v1, there are only two application versions.+However, there are now _three_ task definition revisions: one for each+deployment and one for the rollback. To further reiterate the nuance here,+rolling back the application version _does not use previous task definitions_+and will render a new task definition pointing to the rolled back application+version, but using the latest version of the template.++Put yet another way: regardless of the application version being deployed,+whether it is new, existing, or old, a new task definition revision is always+created using the latest task definition template.++This is restated several times in this section because it is a critical nuance+that is easy to lose sight of, in particular in the course of an emergency+rollback where details like this are easy to miss.++### What is distinct from column management++The difference between environment variable and column management comes down to+the fact that with the database, the exact same database is being used by two+different running versions of the application. For environment variables, the+previously running version of the application will continue to use the+environment variable configuration defined in the previous task definition+revision used to run that instance. Environment variables are not automatically+updated for the running application. This means that if a deployment was very+carefully orchestrated, we do not necessarily need to worry about backwards+incompatible changes, and even in the+[worst case described below](#manual-rollbacks-after-removing-an-environment-variable),+it is still possible to recover by following an additional step (re-updating the+template before rolling back).++Generally environment variables require far less care and attention than+database management when it comes to maintaining zero-downtime deployments.+However, maintainers should still understand how this process works so that they+can handle situations where it does come up (particularly with manual rollbacks+and the removal of environment variables).++### When to update environment variables++Because environment variables are updated in the task definition template, they+must be updated _before_ the new version of the application depending on the+variable is deployed. This includes staging, which automatically deploys on+pushes to `main`. If a new environment variable is required and has no+acceptable default behaviour if not configured—i.e., the application will crash+if it is not present or the behaviour when it is not present is incompatible+with the environment—then it must be added to the task definition template for+the application and environment before the application is deployed. For staging,+this means updating the task definition template before merging the PR. For+production, this means updating the task definition template before running the+production deployment workflow.++It is generally best practice to configure acceptable default behaviours for+undefined environment variables, but sometimes it's not possible to do so and in+these cases it is imperative to update the task definition template before+triggering a deployment (whether automated or manual).++If the task definition template is updated _after_ the fact (whether because we+forgot to do it beforehand or for any other reason), then the application will+need to be redeployed so that a new task definition is created using the latest+template revision with the updated variables.++```{warning}+_Any_ redeployment after the template is updated will receive the updated+variables. That means that, for example, if staging is automatically deployed+due to a push to `main` after updating the template, it is not necessary to+further redeploy staging for the application to get the updated variables. If+the timing of each is within seconds, however, it's best not to risk it and+just redeploy staging if you have any doubts.+```++### Manual rollbacks after removing an environment variable or updating its format++This is the primary situation where an environment variable change could cause+an issue if not handled carefully. Imagine a situation where we've developed+changes for one of our applications that removes the need for a previously+required environment variable. For example, imagine we decided to get rid of+Sentry and removed the+[`SENTRY_DSN`](https://github.com/wordpress/openverse/blob/72087873e8383a656842cb6152a8f4391250cbbc/frontend/src/utils/sentry-config.ts#L11)+environment variable from the template task definition in preparation for the+subsequent deployment. Imagine further that for some reason, we needed+immediately to rollback this change and for Sentry to return to working order.+Because the latest task definition template is always used to create the task+definition for every deployment, we would first need to update the template to+add back the environment variable. If we didn't then the manual rollback would+use the same template as the original deployment that didn't include the+environment variable.++**The best way to avoid this complication is to leave unneeded environment+variables in the template until after the application version that does not need+them is confirmed to work as expected**. After that, the template may be safely+updated to remove the environment variable and any subsequent deployments will+not include the variable. This is similar to how we remove columns from the+database schema: deploy the code that doesn't use the variable/column first,+_then_ remove the variable/column.++Note that this same issue applies when making non-backwards compatible changes+to environment variable formats. For this reason, it's best to follow the+zero-downtime column data-type approach in this case and create a new+environment variable name for the new format. This allows both the old and the+new environment variable formats to co-exist and a manual rollback to occur+without the need to re-add the previous variable to the template.diff --git a/frontend/meta_docs/DEPLOYMENT.md b/frontend/meta_docs/DEPLOYMENT.mddeleted file mode 100644index 13e71a4ee..000000000--- a/frontend/meta_docs/DEPLOYMENT.md+++ /dev/null@@ -1,182 +0,0 @@-# Frontend Deployments--| Environment | Deployment Log | URL | Version Endpoint[^versions] |-| ----------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------- |-| Staging | [Staging Deployment Log](https://github.com/WordPress/openverse-frontend/actions/workflows/ghcr.yml?query=branch%3Amain+event%3Apush) | <https://staging.openverse.org> | [Staging version](https://staging.openverse.org/version.json) |-| Production | [Production Deployment Log](https://github.com/WordPress/openverse-frontend/actions/workflows/ghcr.yml?query=event%3Arelease) | <https://production.openverse.org>[^production] | [Production version](https://production.openverse.org/version.json) |--[^versions]:- To determine the currently deployed version for any environment, visit the- `/version.json` of the environment. The `release` property will list the- relevant image tag for the current deployment.--[^production]:- Note that production is accessed via the iframe at- <https://wordpress.org/openverse>, not directly via the `search-production`- subdomain.--The Openverse frontend is deployed using AWS's Elastic Container Service. The-frontend is encapsulated into a single _ECS service_ per environment. The-overall approach of deployments is to generate a new _task definition_ and to-associate that task definition with the ECS Service. This causes the service to-deploy the new task definition as a newly running _task_. Once the service has-determined the new task to be healthy, it will redirect all traffic to the new-task away from the old task. This is called _draining_. Once the old task is-drained, it is spun down and the only task left running is the new one.--> _**Note:**_ The number of running tasks per active task definition may vary-> per environment but has no bearings on the deployment process. The size of the-> service is handle entirely on the infrastructure side. The process above is-> completely automated and contributors generally do not need to be acutely-> aware of the "behind the scenes" stuff going on, but it can be helpful for-> understanding what is happening during a deployment.--## Deployment Workflow--Deployments for all environments follow the same general workflow. This workflow-is completely automated and auditable via GitHub Workflows.--1. Build the ghcr.io/wordpress/openverse-frontend docker image. Tag it- appropriately for the deployment.-2. Download the template task definition from AWS for the environment being- deployed. Update the template with the following:- 1. The new image tag- 2. The reified task definition family name without the `-template` suffix-3. Register the new task definition to the ECS service.-4. Wait for the ECS service to report that it is stable.- - During this waiting period, the process described in the opening paragraph- is orchestrated by ECS. This part is _not_ transparent in the GitHub- Workflows and will simply appear as a waiting step without any further- information.--This process, from start to finish, generally takes less than 15 minutes. If it-takes longer than 15 then something is probably wrong.--### Failures--Failures are automatically handled and the Openverse maintainers are notified.-The GitHub Workflow log is the canonical source of truth of the record of our-deployment attempts. See the table at the top of this document for links to-these logs per environment.--If any of the steps described above fails, including the new task spin up and-switch over, the deployment is deemed a failure. If the failure occurs while-trying to start a new healthy task, the ECS service will automatically rollback-to the previous task definition revision. Remember that the previous task is not-drained and removed until the new task is determined to be healthy, so this-rollback has zero downtime.--If the docker build fails then there is nothing to rollback. The failure needs-to be investigated and the issue fixed for deployments to be possible again.-However, this is unlikely to happen because we require valid Docker image builds-as part of our CI. Nonetheless, given certain semantic merge conflicts, it is-possible that a PR could pass CI and still cause a build failure when merged, so-it is technically possible for a failure to occur during the first step.--## Staging--Staging is automatically deployed any time code is merged to the `main` branch-of this repository. It follows the process above. Staging images are tagged with-the commit SHA, following the pattern `sha-<commit>`. They are also tagged with-`main`[^staging-tag].--[^staging-tag]:- Currently the staging task definition gets rendered with the `main` tag- instead of the commit SHA based one. This may change in the future. If it- does change, there should be no noticeable difference in the deployment- process to contributors.--## Production--Production is automatically deployed any time a new release is created in-GitHub. Release images are tagged with the release tag name, for example-`v3.4.3`. The task definition is rendered using this tag.--## Rollbacks--Even if the deployment process described above succeeds, sometimes we may-realise that the deployed code is not behaving as we expected. In these cases it-may be necessary to force an environment to be deployed to a specific version.--The-[Rollback Frontend](https://github.com/WordPress/openverse-frontend/actions/workflows/rollback.yml)-workflow makes this possible. It is a dispatchable workflow. Only members of the-@WordPress/openverse-maintainers GitHub team are able to dispatch the workflow-to completion. Anyone else who tries to dispatch it will have the workflow-automatically fail.--The workflow requires two inputs: `environment` and `tag`. `environment` must be-either `staging` or `production` and the `tag` must be a valid tag that exists-on the ghcr.io/wordpress/openverse-frontend image. The `tag` input is validated-against the available list of tags and the workflow will fail if the tag is-determined not to exist in the image repository.--After validating the tag and that the dispatcher is authorised, the Rollback-workflow follows the deployment process described above, except that it skips-the Docker image build and goes straight to step 2. Because of this difference,-the rollback workflow generally takes less than 10 minutes.--## Environment Variables--To add new environment variables for a given service, you must first update the-task definition template in Terraform with the new variables and then deploy the-code that depends on it. It is generally good practice to have safe defaults for-environment variables so that this ordering does not matter.--If you're adding a new environment variable, be sure to coordinate with someone-on @WordPress/openverse-maintainers who is able to update the task definition-template for you, if you're unable to do so yourself.--After the template is updated, deploy the new code following the usual-procedures and the new template will be used.--When updating existing environment variable values or adding new variables that-do not have dependent code, update the template for the environment that needs-updating and then redeploy the environment using the rollback workflow described-above.--## Future end-to-end test integration--In the future we hope to integrate end-to-end tests into this workflow and to-tighten the staging to production pipeline. Essentially, we would like the-deployment pipeline to go something like this:--1. Merge PR to `main`.-2. Wait for staging to deploy.-3. Playwright tests automatically run against the new staging environment.-4. While Playwright tests are running, the person who merged the PR should- manually verify that their change behaves as expected.-5. After the Playwright tests are confirmed to have passed, unlock a "deploy to- production" button somewhere that pushes the image currently deployed to- staging into the production task definition.--Following this process would mean that production gets deployed every time code-is merged to `main`. It reduces the turn around for new features and bug fixes-because they don't have to wait for a new release to be manually created.--We could more or less follow the process as described today just by creating a-new release every time we've merged to staging and verified our changes, but-there are a couple missing pieces that would need to be implemented to make this-process easy to follow, to varying degrees of difficulty:--1. We need a GitHub workflow that runs the Playwright tests against the staging- deployment automatically after staging is deployed. This will require some- Playwright configuration tweaks and increased test timeouts due to network- latency.-2. We would need to create a queue so that new staging deployments do not occur- until the current staging deployment is live on production. This could be- implemented by polling the `/version.json` endpoints of both environments and- only liberating a new staging deployment for new merges once the endpoints- both report the same `release` property.-3. We would need to update the production deployment workflow to not create a- new Docker build and instead just pull the current tag from the staging- `/version.json` endpoint.--Note that this workflow does make the process of merging a PR heavier than it is-today. This comes with some benefits:--1. PRs will likely be more carefully tested as the consequence of merging them- is higher and more immediately consequential.-2. Bugs will be fixed in production more quickly.-3. Features can be rolled out with more care using feature flags and likewise- more quickly.