- Docker
- Docker Compose (does not need to be installed separately if using Docker Desktop)
- uv for Python project management
- Node.js >= 20
- Optional: nvm for managing Node.js versions
- Yarn 1.x
- Recommended: install via
corepack:corepack enable corepack install --global yarn@1
- Recommended: install via
- A local clone of the
nmdc-serverrepository
Start by copying the example environment configuration file.
cp .env.example .envSee nmdc_server/config.py for all configuration variables. Variable names in .env should be all uppercase and prefixed with NMDC_.
Follow the steps below to configure the necessary settings.
- If necessary, create an ORCID account at orcid.org.
- Once logged in to ORCID, create an Application via the ORCID developer tools page.
- In the "Application details" section:
- Set the Application name to
NMDC Portal - Set the Application URL to
https://microbiomedata.org/ - Set the Application description to
NMDC Portal
- Set the Application name to
- In the "Redirect URIs" section:
- Add an entry for
http://127.0.0.1:8000
Note: Our production Redirect URIs are listed here.
- Add an entry for
- You will use the resulting Client ID and Client Secret in the next step.
- In the "Application details" section:
- Populate the following variables in
.env.NMDC_ORCID_CLIENT_ID=changeme NMDC_ORCID_CLIENT_SECRET=changeme
- Populate the below variables in
.env. Values for these should be generated by runningopenssl rand -hex 32. You will have to run the command once for each variable (i.e. twice total).NMDC_SESSION_SECRET_KEY=changeme NMDC_API_JWT_SECRET=changeme
To load production data or to run an ingest locally, you will need NERSC credentials.
- If necessary, create a new account by following the instructions at https://docs.nersc.gov/accounts.
- Populate the following variable in
.env.NERSC_USER=changeme
- Install the
sshproxytool by following the instructions at https://docs.nersc.gov/connect/mfa/#sshproxy.
In order to connect to the dev or prod MongoDB instances for ingest, you will need credentials to connect to them. If you do not have credentials, ask a team member to either create accounts for you or to provide you with the generic org.microbiomedata.data_reader credentials. Then add the credentials to your .env file.
NMDC_MONGO_USER=changeme
NMDC_MONGO_PASSWORD=changemeGoogle Cloud Storage (GCS) is used to store images associated with Submission Portal submissions. By default, local development uses a local mock GCS server. This is controlled by the NMDC_GCS_USE_FAKE variable in .env. If you want to use the real GCS server, set this variable to false.
Whether you use the real or fake GCS server, you will need to set up authentication. The recommended way to do this is to use Application Default Credentials (ADC) with service account impersonation. Service account impersonation is required for generating signed URLs for uploading/downloading images directly to/from GCS.
-
Ask a team member with the necessary GCS permissions to associate your Google Cloud account with the NMDC Google Cloud project and service account.
Show/hide instructions for team member
These instructions are for the team member that has necessary GCS permissions to associate your (i.e. the "developer's") Google Cloud account with the NMDC Google Cloud project and service account.
- In a web browser, sign into the Google Cloud console and go to the "
NMDC" project (if not already there) in the "lbl.gov" organization. - Go to the "IAM & Admin" > "IAM" section of the Google Cloud console.
- On the "Allow" tab, go to the "View by principals" sub-tab.
- If the developer is already listed as a principal, perform the following sub-steps to confirm they have sufficient roles; then skip step 5 below.
- Click the pencil icon next to their name.
- In the "Assign roles" section of the form, select the following two roles:
Service Account Token CreatorView Service Accounts
- Click the "Save" button.
- If the developer is not already listed as a principal, perform the following sub-steps to add the developer as a principal having sufficient roles.
- Click the "Grant access" button.
- In the "New principals" field, enter the email address of the developer's Google account.
- In the "Assign roles" section of the form, select the following two roles:
Service Account Token CreatorView Service Accounts
- Click the "Save" button.
- Send the service account email address to the developer.
- Back on the "View by principals" sub-tab, locate the row whose "Name" value says "
Mister Bucket". - On that row, copy the email address in the "Principal" column. It's the same email address every time—we have just opted not to include it in these public docs.
- Send that email address to the developer. You can include the following introduction for context if you want (optional):
Here is the service account email address you can use when setting up Application Default Credentials (ADC):
- Back on the "View by principals" sub-tab, locate the row whose "Name" value says "
- In a web browser, sign into the Google Cloud console and go to the "
-
Install the Google Cloud Command Line Interface (CLI) by following the instructions at https://cloud.google.com/sdk/docs/install.
-
Run the following command to set up Application Default Credentials (ADC):
gcloud auth application-default login --impersonate-service-account <service account email will be provided by team member>
You also must generate a local object name prefix. This prefix is used to differentiate which system uploaded to the shared GCS bucket. Local development systems should use the prefix local_<random_suffix>.
-
Generate a random suffix using the following command:
openssl rand -hex 4
-
Set the
NMDC_GCS_OBJECT_NAME_PREFIXvariable in.envtolocal_<random_suffix>.NMDC_GCS_OBJECT_NAME_PREFIX=local_1234abcd # replace 1234abcd with your random suffix
To test LLM features locally, you will need to get the nmdc-llm GCP service account credential file from an NMDC team member. The file should be copied into the nmdc-server/auth/ directory of this project. Then add the following variable in .env:
NMDC_LLM_SERVICE_ACCOUNT_CREDENTIALS_FILE=/auth/name-of-your-file.jsonThis path is used by nmdc-metadata-suggestor-ai-tool on the backend
For Langfuse access, contact Olivia Hess
To enable Langfuse, set the following variables in .env:
- LANGFUSE_PUBLIC_KEY=changeme
- LANGFUSE_SECRET_KEY=changeme
- LANGFUSE_BASE_URL=https://us.cloud.langfuse.com
- LANGFUSE_TRACING_ENVIRONMENT=dev/local/prod
Setting these values will enable traces to be sent to our Langfuse instance.
The nmdc-server CLI has a load-db subcommand which populates your local database using a backup file. These backups are produced nightly for both dev and prod and stored in Google Cloud Storage buckets. Typically, you will want to load from a recent production backup.
- Obtain a recent dev or production backup.
- If you have Google Cloud Storage access and the
gcloudCLI installed, you can list recent backups with:Then download a recent backup with:gcloud storage ls gs://nmdc-portal-prod-postgres-dump # for production backups gcloud storage ls gs://nmdc-portal-test-postgres-dump # for dev backups
Note: the nightly backup process makes backups of both thegcloud storage cp gs://nmdc-portal-prod-postgres-dump/<backup-filename>.dump /tmp/backup.dump
nmdc_aandnmdc_bdatabases. Make sure you download the one which was the primary database (i.e. not the ingest database) at the time. - If you do not have Google Cloud Storage access, ask a team member with access to download a recent production backup for you. This will come in the form of a
.dumpfile. Save the file locally (e.g. to/tmp/backup.dump).
- If you have Google Cloud Storage access and the
- Run the
load-dbsubcommand from abackendcontainer, mounting the backup file to load.
docker compose run \
--rm \
-v <local/path/to/backup.dump>:/tmp/backup.dump \
backend \
nmdc-server load-db -f /tmp/backup.dumpTo see all CLI options run:
nmdc-server load-db --helpNote: if you already have a local database set up, the first time you attempt to load from a production backup you may see an error about a missing nmdc_data_reader or nmdc_reader role. If you see this error, run the following command to remove existing docker volumes:
docker compose down -vThis should only need to be done once. When the db service starts up again (including via running the load-db command), the necessary roles and databases will be created automatically.
Although the project is designed to be run in Docker, having the dependencies installed locally can be useful for development (e.g. providing code completion in your editor, running tests, etc.).
- Install the backend dependencies using
uv. This will create a new virtual environment in the.venvdirectory if one does not already exist.uv sync --all-groups
- Install the frontend dependencies.
cd web yarn
Run the full stack via Docker Compose:
docker compose up -dThe
-dis short for--detachand makes it so the container logs (i.e. STDOUT and STDERR streams) don't take over your shell, causing you to have to open up a new shell in order to run more commands.
Troubleshooting: If the building of one of the services fails with an error citing networking timeouts, but the building of other services completes successfully, we recommend you retry building only the service that failed, by itself. Our thinking is that there will be less demand on your network that way. You can do that via $ docker compose build {service_name} (e.g. $ docker compose build web).
View the main application at http://127.0.0.1:8080/ and the API documentation page at http://127.0.0.1:8080/api/docs.
Changing Python files in the nmdc_server directory will automatically reload the server.
To stop the server:
docker compose downIf you add or modify project dependencies, you may need to rebuild the containers:
docker compose up --build -dYou will need Node version 22 or greater to install and run the web app locally. You can find installation instructions here: https://nodejs.org/en/download. If you're on a Mac, it is recommended to use nvm to install and manage your node versions.
If you have nvm installed, you can run the following command at the root of the web directory to use the Node version specified in our .nvmrc file:
nvm useIf you are modifying files in the web directory, additionally run the frontend development server to enable hot reloading in your browser:
cd web
yarn install
yarn devView the main application at http://127.0.0.1:8081/. Changes to files in the web directory will automatically trigger a reload in your browser.
Note: An instance of the frontend application will continue to be served via Docker Compose on port
8080, but that instance will not pick up changes to thewebdirectory automatically. Be aware of which port you are accessing when doing frontend development.
It is recommended to use 127.0.0.1 instead of localhost for local development. This is because localhost is not allowed as a redirect URI for an ORCID client. The workaround is to register 127.0.0.1 as a redirect URI with ORCID and to use subsequently visit 127.0.0.1 for local testing.
Note: This is not generally required unless you are specifically working on the ingest code. If you are working on the web application, simply loading from a recent production backup is sufficient.
-
Ensure that you have completed the sections above about configuring your NERSC credentials and MongoDB credentials.
-
Obtain a new SSH key from NERSC if you haven't done so in the last 24 hours.
sshproxy.sh -u $NERSC_USER -
Set up an active SSH tunnel to the dev and production MongoDB instances if you do not already have one established.
ssh \ -L 37018:mongo-loadbalancer.nmdc-dev.production.svc.spin.nersc.org:27017 \ -L 37019:mongo-loadbalancer.nmdc.production.svc.spin.nersc.org:27017 \ -o ServerAliveInterval=60 \ -f \ -N \ -l $NERSC_USER \ -i ~/.ssh/nersc \ dtn01.nersc.gov
That command will set up SSH port forwarding such that your computer can access the dev MongoDB server at
localhost:37018and the prod MongoDB server atlocalhost:37019.From within a Docker container
host.docker.internalcan be used to access thelocalhostof your computer. When ingesting from the dev or prod MongoDB instances, be sure to setNMDC_MONGO_HOST=host.docker.internalin your.envfile.See https://github.com/microbiomedata/infra-admin/blob/main/mongodb/connection-guide.md (internal) for more information on connecting to the MongoDB instances.
-
Create a local copy of ingest support files:
mkdir -p data && scp \ -r \ -i ~/.ssh/nersc \ "$NERSC_USER@dtn01.nersc.gov:/global/cfs/cdirs/m3408/ingest" \ data
-
Run the ingest command:
docker compose run backend nmdc-server ingest -vv --function-limit 100
Note: The
--function-limitflag is optional. It is used to reduce the time that the ingest takes by limiting the number of certain types of objects loaded. This can be useful for testing purposes. For more information on options runnmdc-server ingest --help.
See this documentation for information about ingesting from a local mongo database.
toxIn order for the py312 test suite to run properly, it needs to be able to communicate with a running postgres
server and the fake GCS service. You can use the docker configuration to get these services up and running:
docker compose up db storageYou'll also need to set environment variables so the tests know where these resources can be found. If you're
running the services via docker compose, then you can use the following values:
export NMDC_TESTING_DATABASE_URI=postgresql://postgres:postgres@localhost:5432/nmdc_testing
export NMDC_GCS_FAKE_API_ENDPOINT=http://localhost:4443# Autogenerate a migration diff from the current HEAD
docker compose run backend alembic -c nmdc_server/alembic.ini revision --autogenerateIn order to generate a migration, your database state should match HEAD. If you started the server from a totally empty database, then the default behavior is to ignore migration scripts and set up the database to match models.py. Before you can generate a migration, you need to reset your database to match HEAD.
# Destroy everything. You'll lose your data!
docker compose down -v
docker compose up -d db
# Create the database
docker compose run backend psql -c "create database nmdc_a;" -d postgres
# Run migrations to HEAD
docker compose run backend alembic -c nmdc_server/alembic.ini upgrade head
# Autogenerate a migration diff from the current HEAD
docker compose run backend alembic -c nmdc_server/alembic.ini revision --autogenerateHere are some commands we find helpful when writing new migrations. We typically run these once we have filled out the function bodies of both the upgrade and downgrade functions.
# Migrate the database forward by 1 migration.
# This can be used to invoke a migration's `upgrade` function.
docker compose run --rm backend alembic -c nmdc_server/alembic.ini upgrade +1
# Migrate the database backward by 1 migration.
# This can be used to invoke a migration's `downgrade` function.
docker compose run --rm backend alembic -c nmdc_server/alembic.ini downgrade -1A handy IPython shell is provided with some commonly used symbols automatically
imported, and autoreload 2 enabled. To run it:
docker compose run --rm backend nmdc-server shellYou can also pass --print-sql to output all SQL queries. Note that if you have SQL logging enabled via the NMDC_PRINT_SQL environment variable, you will not need to pass --print-sql to the command.
The shell can be very helpful for gaining an understanding of how the data model and query/filter classes work. Here are some prompts you can start with to explore the system.
You'll need a SQLAlchemy session object to perform queries. The functions needed to create a session (either for the "active" database or the "ingest" database) are included in the auto-import statements. To create a session that can talk to the "active" database, you can run:
db = SessionLocal()To create a basic SQLAlchemy select object (which can be executed against the session), run:
select_statement = select(Biosample)To actually execute the statement, you'll need to run:
result = db.execute(select_statement)
one_biosample = result.scalars().first()Note that result.scalars() returns an instance of ScalarResult. This can be used to get ORM objects. The above snippet uses the first method to retrieve a single biosample, which is an instace of nmdc_server.models.Biosample. For more details on using SQLAlchemy to explore results, see the official documentation.
To see an example of how relationships work in SQLAlchemy, use the Biosample retrieved abolve and run:
one_biosample.omics_processingYou can analyze the SQL output to better understand how this relationship works in SQLAlchemy, and what the engine needs to do to get from one entity (in this case, Biosample) to another (OmicsProcssing). This query in particular also reveals the association table between those two.
Using the shell like this is a great way to explore SQLAlchemy ideas and concepts. Having this tool is important for analyzing performance and optimizing queries during search. Here is an example that illustrates how SQLAlchemy's selectinload can reduce the number of queries the system needs to run.
from sqlalchem.orm import selectinload
db = SessionLocal()
biosample_query = db.query(Biosample).options(selectinload(Biosample.omics_processing))
one_biosample = biosample_query[0]
one_biosample.omics_processingExecuting the above line by line with SQL logging turned on will reveal that selectinload will query for the biosample's omics processing data before the property is accessed. The final line, one_biosample.omics_processing does not emit a SQL statement. That related information has already been retrieved, thanks to selectinload.
The following example illustrates how the QuerySchema and ConditionSchema classes are used to generate queries for searches from the data portal. QuerySchema classes contain important methods like execute, query, and facet. ConditionSchema classes model individual conditions (usually chosen by the user in the Data Portal's search sidebar). This example uses the SimpleConditionSchema class, which has the following properties:
op: The operation (equals, greater than, etc.) to use. Expects a value from theOperationenum inquery.pytable: The table that contains the value we're searching onfield: The column (or JSONb property within theannotationscolumn) to search onvalue: The value used to search against.
This structure mirrors the individual conditions sent to the API's search/ endpoints.
You can use these classes to run searches just like the API does, follow these steps in your shell to walk through a simple example.
filter_conditions = [SimpleConditionSchema(table='biosample', field='latitude', value='45', op=Operation.greater)]The QuerySchema classes expect an list of conditions, which is why we're wrapping our SimpleConditionSchema object in a list here.
study_query_schema = StudyQuerySchema(conditions=conditions)Instantiate the StudyQuerySchema class with our condition. We're going to use this class to query the database for all studies that have related biosamples in the latitude range specified by the condition above.
db = SessionLocal()
result = study_query_schema.execute(db)
one_study = result[0]The execute method will construct the query based on the conditions and execute it against the given SQLAlchemy session (in this case, the "active" database). Evaluating the result (in this case, retrieving the study at index 0) will cause the SQL to run and be logged.
As an exercise, try running the same search with an instance of the BiosampleQuerySchema class. Compare the SQL generated in both cases. It is quite different.
Child classes of the BaseQuerySchema can override the default behavior. For example, study results need to inject counts of data types into the results.
For more on how Conditions are tranformed into Filters, see the BaseQuerySchema class, and the filters.py module.
The frontend Vue app is configured to work with Google Analytics. There are two Google Analytics "properties" for the NMDC Data Portal. One is for the production site. One is for the dev site as well as local development. Each GA property has its own GA ID associated with it. This ID gets pulled into the Vue app from an environment variable called VITE_APP_NMDC_GOOGLE_ANALYTICS_ID. You can set this inside a .env file inside the web directory (note this is separate from the .env file at the root of the project).