Skip to content

Kubernetes

recruIT's Helm chart is published to the repository's OCI registry at oci://ghcr.io/open-recruit/recruit/charts/recruit. Every release also has it attached as recruit-helm-chart.tgz.

The chart deploys:

  • the screening list (list), together with a Job that migrates its database ahead of every new version
  • the query module (querySqlOnFhir), which is disabled by default since it needs a Trino to query
  • a Job that installs recruIT's FHIR SearchParameters on every install and upgrade

and, unless disabled, the dependencies those need:

  • a HAPI FHIR JPA server with its own PostgreSQL database (fhirserver)
  • a PostgreSQL database for the screening list (postgres)
  • MailDev, a mock mail server that catches notification emails (maildev)

For demos, the chart can also generate Synthea patients and a sample study (syntheticPatients, sampleStudy). The Quickstart uses these to get a demo running with a single command.

Documentation for all available chart options

You can find a complete description of all chart values in the chart's README.

Prerequisites

  • a Kubernetes cluster, version 1.30 or later
  • kubectl and Helm 3.8 or later
  • an ingress controller to make the screening list reachable for your users

Production installation

For production, replace the mock mail server with your own SMTP server and connect the modules to the services listed in Docker Compose: the FHIR server, Trino with a FHIR lakehouse, an OpenID Connect provider, and optionally a Pathling server. That page also explains what each of them needs to provide and how they work together.

You can keep the included HAPI FHIR server and PostgreSQL databases, or replace them with your own. For highly available PostgreSQL clusters run inside Kubernetes, see CloudNativePG for HA databases.

Start from the following values, which connect recruIT to external services only:

values-recruit-production.yaml
# your own FHIR server instead of the included HAPI FHIR server
fhirserver:
  enabled: false
externalFhirServer:
  url: https://fhir.example.com/fhir

# your own SMTP server instead of the included mock mail server, see `list.notifications.email.smtp`
maildev:
  enabled: false

# your own PostgreSQL database instead of the included one, see `list.database`
postgres:
  enabled: false

list:
  replicaCount: 2
  podDisruptionBudget:
    enabled: true
  resources:
    requests:
      cpu: 250m
      memory: 512Mi
    limits:
      memory: 512Mi
  database:
    # without credentials, they're set via `username` and the Secret below
    connectionString: "Host=postgres.example.com;Port=5432;Database=recruit"
    username: recruit
    existingSecret:
      name: recruit-list-db
      key: password
  auth:
    enabled: true
    oidc:
      authority: https://auth.example.com/realms/recruit
      clientId: recruit-list
      existingSecret:
        name: recruit-list-oidc
        key: client-secret
      roleClaimType: role
  notifications:
    email:
      from: recruit@example.com
      smtp:
        host: smtp.example.com
        port: 587
        username: recruit
        # must contain an `smtp-password` key
        existingSecret: recruit-list-smtp
  ingress:
    enabled: true
    hosts:
      # also used as the base URL of the links in notification emails
      - host: recruit.example.com
        paths: ["/"]
    tls:
      - secretName: recruit-list-tls
        hosts:
          - recruit.example.com

querySqlOnFhir:
  enabled: true
  schedule: "@hourly"
  resources:
    requests:
      cpu: 500m
      memory: 1Gi
    limits:
      memory: 1Gi
  trino:
    jdbcUrl: jdbc:trino://trino.example.com:443/fhir/default?SSL=true
    auth:
      username: recruit
      existingSecret:
        name: recruit-query-trino
        key: password
  # optional, for criteria Trino can't run directly
  sqlOnFhir:
    url: ""

The values refer to Secrets instead of containing credentials. Create them before installing the chart:

kubectl create namespace recruit

kubectl create secret generic -n recruit recruit-list-db --from-literal=password=change-me
kubectl create secret generic -n recruit recruit-list-oidc --from-literal=client-secret=change-me
kubectl create secret generic -n recruit recruit-list-smtp --from-literal=smtp-password=change-me
kubectl create secret generic -n recruit recruit-query-trino --from-literal=password=change-me

Then install the chart:

helm upgrade --install -n recruit \
  --version 11.3.0 \
  -f values-recruit-production.yaml \
  --wait \
  recruit oci://ghcr.io/open-recruit/recruit/charts/recruit

Register https://recruit.example.com/signin-oidc as the redirect URI of the recruit-list client with your OpenID Connect provider, see Authentication. Sign-in only works over HTTPS, so the ingress needs a TLS certificate, e.g. issued by cert-manager to the recruit-list-tls Secret.

To make sure the modules started and can reach the FHIR server, run the chart's tests:

helm test -n recruit recruit

On every scheduled run, the query module logs Polling for ResearchStudy resources referencing a Group with SQLQuery Library, followed by the studies it found and processed:

kubectl logs -n recruit deploy/recruit-query-sql-on-fhir --follow

Settings the chart doesn't expose

The chart sets the most important configuration options from its values. Set any other option as an environment variable via list.extraEnv or querySqlOnFhir.extraEnv, e.g. to only recommend patients who meet every criterion:

querySqlOnFhir:
  extraEnv:
    - name: QUERY_SQL_ON_FHIR_REQUIRE_ALL_CRITERIA_MET
      value: "true"

Database migrations

Before a new version of the screening list starts, a Job named recruit-list-migrate-<hash> updates its database schema. The hash is derived from the image tag, so the Job only runs once per version, and is deleted 10 minutes after it finished (list.migrationJob.ttlSecondsAfterFinished). The screening list's pods wait for it in an init container, which asks the Kubernetes API whether the Job has completed. The chart creates a Role that allows just that.

If the migration fails, the screening list's pods don't start. Check the Job's logs:

kubectl logs -n recruit -l app.kubernetes.io/component=list-migrate --tail=-1

Since the Job isn't a Helm hook, this also works when the chart is rendered with helm template by a GitOps tool like Argo CD or Flux.

Example installation using KinD

This walks you through installing recruIT with the demo fixtures on your local machine using KinD, with:

  • a multi-node cluster to demonstrate topology zone aware pod spreading, see High availability
  • the screening list and the FHIR server exposed via the Traefik ingress controller on nip.io domains resolving to localhost
  • the restricted Pod Security Standard enforced, which all components comply with

It needs a machine with around 16 GiB of memory.

First, save the following as kind-config.yaml and create the cluster:

kind-config.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
  - role: control-plane
    # the ingress controller's NodePorts, published on the host's ports 80 and 443
    extraPortMappings:
      - containerPort: 30080
        hostPort: 80
        protocol: TCP
      - containerPort: 30443
        hostPort: 443
        protocol: TCP
    labels:
      topology.kubernetes.io/zone: a
  - role: worker
    labels:
      topology.kubernetes.io/zone: b
  - role: worker
    labels:
      topology.kubernetes.io/zone: c
kind create cluster --config=kind-config.yaml

Install Traefik, with its HTTP and HTTPS ports published on the NodePorts mapped to your host's ports 80 and 443 above:

helm upgrade --install -n traefik --create-namespace \
  --set service.spec.type=NodePort \
  --set ports.web.nodePort=30080 \
  --set ports.websecure.nodePort=30443 \
  --wait \
  traefik oci://ghcr.io/traefik/helm/traefik

Create a namespace for recruIT that enforces the restricted Pod Security Standard:

kubectl create namespace recruit
kubectl label namespace recruit \
  pod-security.kubernetes.io/enforce=restricted \
  pod-security.kubernetes.io/enforce-version=latest

Save the following as values-kind-recruit.yaml. It enables the ingresses of the screening list and the FHIR server:

values-kind-recruit.yaml
# used together with the chart's values-demo.yaml

list:
  ingress:
    enabled: true
    hosts:
      - host: recruit-list.127.0.0.1.nip.io
        paths: ["/"]

fhirserver:
  ingress:
    enabled: true
    hosts:
      - host: recruit-fhir-server.127.0.0.1.nip.io
        pathType: ImplementationSpecific
        paths: ["/"]

And finally, install the chart using these values on top of the chart's values-demo.yaml, which is explained in the Quickstart:

helm upgrade --install -n recruit \
  --render-subchart-notes \
  --version 11.3.0 \
  -f https://raw.githubusercontent.com/open-recruit/recruit/refs/tags/v11.3.0/charts/recruit/values-demo.yaml \
  -f values-kind-recruit.yaml \
  --wait \
  --timeout 30m \
  recruit oci://ghcr.io/open-recruit/recruit/charts/recruit

The install takes several minutes to download the images, generate the synthetic patients, and load them into the FHIR server. Once the command exits, these services are reachable:

Service URL
recruIT Screening List http://recruit-list.127.0.0.1.nip.io/
HAPI FHIR Server http://recruit-fhir-server.127.0.0.1.nip.io/fhir/

The query module checks for studies every minute, so the sample study's screening list shows up about a minute later:

The screening list of the sample study The screening list of the sample study

MailDev doesn't have an ingress. To read the notification emails it caught, forward its port and open http://127.0.0.1:1080:

kubectl port-forward -n recruit svc/recruit-maildev-web 1080:1080

See Notifications for how to subscribe to a study and trigger a notification. To create additional studies, follow Creating your first study.

To remove everything again, delete the cluster:

kind delete cluster

Metrics

All modules expose metrics in Prometheus format (see Observability). The chart makes it easy to scrape these metrics by integrating with the widely used Prometheus Operator:

helm upgrade --install -n monitoring --create-namespace \
  kube-prometheus-stack oci://ghcr.io/prometheus-community/charts/kube-prometheus-stack

You can now update your release by combining the values from above with the following:

values-kind-recruit-enable-servicemonitors.yaml
list:
  metrics:
    serviceMonitor:
      enabled: true
      additionalLabels:
        release: kube-prometheus-stack

querySqlOnFhir:
  metrics:
    serviceMonitor:
      enabled: true
      additionalLabels:
        release: kube-prometheus-stack

# loaded by the Grafana included with kube-prometheus-stack, see below
grafanaDashboard:
  enabled: true
helm upgrade -n recruit \
  --version 11.3.0 \
  -f https://raw.githubusercontent.com/open-recruit/recruit/refs/tags/v11.3.0/charts/recruit/values-demo.yaml \
  -f values-kind-recruit.yaml \
  -f values-kind-recruit-enable-servicemonitors.yaml \
  --wait \
  recruit oci://ghcr.io/open-recruit/recruit/charts/recruit

grafanaDashboard.enabled creates a ConfigMap with recruIT's Grafana dashboard, which the Grafana included with kube-prometheus-stack picks up on its own. To open it, forward Grafana's port:

kubectl port-forward -n monitoring svc/kube-prometheus-stack-grafana 3000:80

Then sign in at http://127.0.0.1:3000 as admin, with the password from kubectl get secret -n monitoring kube-prometheus-stack-grafana -o jsonpath='{.data.admin-password}' | base64 -d, and open recruIT in the dashboard list:

The recruIT dashboard in Grafana

The recruIT dashboard in Grafana

The dashboard finds the screening list's and the query module's metrics by their Prometheus job label, which the ServiceMonitors set to the services' names, so it picks the first job containing list and query. If you scrape them some other way, pick the right jobs in the Screening list job and Query module job selectors at the top.

Grafana's dashboard sidecar only looks for ConfigMaps labeled grafana_dashboard: "1" by default, and in some setups only in its own namespace. Use grafanaDashboard.labels and grafanaDashboard.namespace to match yours. Without the sidecar, import charts/recruit/files/dashboards/recruit.json from the repository in Grafana instead.

High availability

The screening list and the FHIR server support running multiple replicas, so they stay available if a single pod or node fails. The query module should only run as a single replica.

The screening list keeps its data, including its notification job queue and the keys that protect its sign-in cookies, in PostgreSQL. It is a Blazor Server app, though: each open browser tab is connected to one pod, which holds that tab's session in memory. With more than one replica, the ingress controller has to send all of a browser's requests to the same pod, using a sticky-session cookie. Without it, the browser shows errors like WebSocket failed to connect. The connection could not be found on the server and No Connection with that ID: Status code '404', and the page stops responding.

With Traefik, sticky sessions are set with annotations on the list's Service (list.service.annotations), as in the values below. With ingress-nginx, set nginx.ingress.kubernetes.io/affinity: "cookie" in list.ingress.annotations instead. If a pod goes away, the tabs connected to it lose their session and have to be reloaded.

The following values run two replicas of both, pin each browser session to one screening list pod, create PodDisruptionBudgets for them, and use pod topology spread constraints to spread their pods across the cluster's topology zones:

values-kind-recruit-ha.yaml
list:
  replicaCount: 2
  # Blazor Server keeps each browser session's state in the pod that serves it, so Traefik pins every
  # session to one pod with a cookie
  service:
    annotations:
      traefik.ingress.kubernetes.io/service.sticky.cookie: "true"
      traefik.ingress.kubernetes.io/service.sticky.cookie.name: recruit-list-affinity
      traefik.ingress.kubernetes.io/service.sticky.cookie.secure: "true"
      traefik.ingress.kubernetes.io/service.sticky.cookie.httponly: "true"
      traefik.ingress.kubernetes.io/service.sticky.cookie.samesite: lax
  podDisruptionBudget:
    enabled: true
  topologySpreadConstraints:
    - maxSkew: 1
      topologyKey: topology.kubernetes.io/zone
      whenUnsatisfiable: ScheduleAnyway
      labelSelector:
        matchLabels:
          app.kubernetes.io/name: recruit
          # note that this label depends on the name of the chart release
          # this assumes the chart is deployed with a name of `recruit`
          app.kubernetes.io/instance: recruit
          app.kubernetes.io/component: list

fhirserver:
  replicaCount: 2
  podDisruptionBudget:
    enabled: true
  topologySpreadConstraints:
    - maxSkew: 1
      topologyKey: topology.kubernetes.io/zone
      whenUnsatisfiable: ScheduleAnyway
      labelSelector:
        matchLabels:
          app.kubernetes.io/name: fhirserver
          app.kubernetes.io/instance: recruit

The included PostgreSQL databases only run a single instance. For highly available databases, see CloudNativePG for HA databases.

CloudNativePG for HA databases

Install the CloudNativePG operator first:

helm upgrade --install -n cnpg-system --create-namespace \
  --repo https://cloudnative-pg.github.io/charts \
  --wait \
  cnpg cloudnative-pg

Next, create PostgreSQL clusters and users for the HAPI FHIR server and the screening list:

cnpg-clusters.yaml
---
apiVersion: v1
kind: Secret
metadata:
  name: recruit-fhir-server-db-app-user
type: kubernetes.io/basic-auth
stringData:
  username: fhir_server_user
  password: recruit-fhir-server
---
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: recruit-fhir-server-db
spec:
  instances: 3
  primaryUpdateStrategy: unsupervised
  replicationSlots:
    highAvailability:
      enabled: true
  storage:
    size: 64Gi
  bootstrap:
    initdb:
      database: fhir_server
      owner: fhir_server_user
      secret:
        name: recruit-fhir-server-db-app-user
---
apiVersion: v1
kind: Secret
metadata:
  name: recruit-list-db-app-user
type: kubernetes.io/basic-auth
stringData:
  username: list_user
  password: recruit-list
---
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: recruit-list-db
spec:
  instances: 3
  primaryUpdateStrategy: unsupervised
  replicationSlots:
    highAvailability:
      enabled: true
  storage:
    size: 8Gi
  bootstrap:
    initdb:
      database: recruit
      owner: list_user
      secret:
        name: recruit-list-db-app-user
kubectl apply -n recruit -f cnpg-clusters.yaml

Finally, install the recruIT chart with the following values added, which replace the included PostgreSQL databases with the clusters' read-write services:

values-kind-recruit-with-cnpg.yaml
fhirserver:
  postgres:
    enabled: false
  externalDatabase:
    host: "recruit-fhir-server-db-rw"
    port: 5432
    database: "fhir_server"
    user: "fhir_server_user"
    password: ""
    existingSecret: "recruit-fhir-server-db-app-user"
    existingSecretKey: "password"

postgres:
  enabled: false

list:
  database:
    connectionString: "Host=recruit-list-db-rw;Port=5432;Database=recruit"
    username: "list_user"
    existingSecret:
      name: "recruit-list-db-app-user"
      key: "password"

Service mesh integration

The application can be integrated with a service mesh, both for observability and to secure service-to-service communication via mTLS.

Linkerd

The following values add Linkerd's linkerd.io/inject: enabled annotation to the pods of all services. The chart's Jobs have their own podAnnotations and aren't injected, since a sidecar would keep them from completing. The ports of PostgreSQL and SMTP, whose protocols Linkerd can't detect, are marked as opaque:

values-kind-recruit-linkerd.yaml
podAnnotations:
  linkerd.io/inject: "enabled"

postgres:
  service:
    annotations:
      config.linkerd.io/opaque-ports: "5432"

fhirserver:
  postgres:
    service:
      annotations:
        config.linkerd.io/opaque-ports: "5432"
  podAnnotations:
    linkerd.io/inject: "enabled"

maildev:
  podAnnotations:
    linkerd.io/inject: "enabled"
    config.linkerd.io/opaque-ports: "1025"

You can also add the linkerd.io/inject: enabled annotation to the recruit namespace instead, see Automatic proxy injection, but then have to disable it for the chart's Jobs as shown for Istio below.

Istio

Label the namespace to have Istio inject its Envoy sidecar into every pod deployed to it:

kubectl label namespace recruit istio-injection=enabled

and disable the injection for the chart's Jobs:

values-kind-recruit-istio.yaml
# the chart's Jobs exit once done, which an injected Envoy sidecar would otherwise keep from completing
createSearchParameters:
  podAnnotations:
    sidecar.istio.io/inject: "false"

sampleStudy:
  podAnnotations:
    sidecar.istio.io/inject: "false"

syntheticPatients:
  podAnnotations:
    sidecar.istio.io/inject: "false"

list:
  migrationJob:
    podAnnotations:
      sidecar.istio.io/inject: "false"

Zero-trust networking

To limit the communication between the components, you can deploy Kubernetes NetworkPolicy resources. Because the details of a deployment can differ significantly (external databases, dependencies spread across several namespaces, etc.), no NetworkPolicy resources are included in the Helm chart. Instead, the following policies and explanations should provide a starting point for customization.

The policies are based on these assumptions:

  1. recruIT is deployed as a release named recruit in a namespace called recruit, with the included HAPI FHIR server and PostgreSQL databases
  2. Trino is deployed in a namespace called trino
  3. the SMTP server is running on a host outside the cluster at IP 192.0.2.1 and port 587
  4. the Kubernetes API server is reachable at IP 192.0.2.10 and port 6443
  5. the Prometheus monitoring stack from Metrics is deployed in a namespace called monitoring
  6. the ingress controller is Traefik, deployed in a namespace called traefik

Everything not explicitly allowed is denied, including the pods helm test starts. You can use https://editor.networkpolicy.io/ to visualize and edit individual policies.

recruit-network-policies.yaml
---
# deny all traffic to and from the pods in the namespace that isn't explicitly allowed below,
# except for DNS lookups
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-allow-dns
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - port: 53
          protocol: UDP
        - port: 53
          protocol: TCP
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: list-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/instance: recruit
      app.kubernetes.io/component: list
  policyTypes:
    - Ingress
    - Egress
  ingress:
    # users access the screening list via the ingress controller
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: traefik
          podSelector:
            matchLabels:
              app.kubernetes.io/name: traefik
      ports:
        - port: http
    # Prometheus scrapes its metrics
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring
          podSelector:
            matchLabels:
              app.kubernetes.io/name: prometheus
      ports:
        - port: http-metrics
  egress:
    # reads studies, screening lists, and patients, and saves recruitment status changes
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/instance: recruit
              app.kubernetes.io/name: fhirserver
      ports:
        - port: http
    # its own database
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/instance: recruit
              app.kubernetes.io/name: recruit-postgres
      ports:
        - port: postgresql
    # the SMTP server at 192.0.2.1. The `/32` prefix length limits egress to just this one address
    - to:
        - ipBlock:
            cidr: 192.0.2.1/32
      ports:
        - port: 587
          protocol: TCP
    # the wait-for-migration init container asks the Kubernetes API server whether the migration Job completed.
    # Replace with the address of your API server, see `kubectl get endpoints kubernetes -n default`
    - to:
        - ipBlock:
            cidr: 192.0.2.10/32
      ports:
        - port: 6443
          protocol: TCP
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: list-migrate-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/instance: recruit
      app.kubernetes.io/component: list-migrate
  policyTypes:
    - Ingress
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/instance: recruit
              app.kubernetes.io/name: recruit-postgres
      ports:
        - port: postgresql
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: query-sql-on-fhir-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/instance: recruit
      app.kubernetes.io/component: query-sql-on-fhir
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring
          podSelector:
            matchLabels:
              app.kubernetes.io/name: prometheus
      ports:
        - port: http-metrics
  egress:
    # reads the studies and writes their screening lists
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/instance: recruit
              app.kubernetes.io/name: fhirserver
      ports:
        - port: http
    # runs the eligibility criteria on the Trino coordinator in the `trino` namespace
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: trino
          podSelector:
            matchLabels:
              app.kubernetes.io/name: trino
              app.kubernetes.io/component: coordinator
      ports:
        - port: 8080
          protocol: TCP
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: search-parameters-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/instance: recruit
      app.kubernetes.io/component: search-parameters
  policyTypes:
    - Ingress
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/instance: recruit
              app.kubernetes.io/name: fhirserver
      ports:
        - port: http
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: fhir-server-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/instance: recruit
      app.kubernetes.io/name: fhirserver
  policyTypes:
    - Ingress
    - Egress
  ingress:
    # all recruIT modules, as well as the Job installing the SearchParameters
    - from:
        - podSelector:
            matchExpressions:
              - key: app.kubernetes.io/instance
                operator: In
                values: [recruit]
              - key: app.kubernetes.io/component
                operator: In
                values: [list, query-sql-on-fhir, search-parameters]
      ports:
        - port: http
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring
          podSelector:
            matchLabels:
              app.kubernetes.io/name: prometheus
      ports:
        - port: http-metrics
  egress:
    # its own database
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/instance: recruit
              app.kubernetes.io/name: fhir-server-postgres
      ports:
        - port: postgresql
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: fhir-server-postgres-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/instance: recruit
      app.kubernetes.io/name: fhir-server-postgres
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app.kubernetes.io/instance: recruit
              app.kubernetes.io/name: fhirserver
      ports:
        - port: postgresql
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: recruit-postgres-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/instance: recruit
      app.kubernetes.io/name: recruit-postgres
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchExpressions:
              - key: app.kubernetes.io/instance
                operator: In
                values: [recruit]
              - key: app.kubernetes.io/component
                operator: In
                values: [list, list-migrate]
      ports:
        - port: postgresql

Distributed tracing

All modules support distributed tracing based on OpenTelemetry, exporting traces via OTLP.

For testing, you can install an all-in-one Jaeger instance, which keeps the traces in memory:

helm upgrade --install -n observability --create-namespace \
  --repo https://jaegertracing.github.io/helm-charts \
  --wait \
  jaeger jaeger

The following values enable tracing for the screening list, the query module, and the HAPI FHIR server:

values-kind-recruit-tracing.yaml
list:
  extraEnv:
    - name: Tracing__Enabled
      value: "true"
    - name: OTEL_SERVICE_NAME
      value: "recruit-list"
    - name: OTEL_EXPORTER_OTLP_ENDPOINT
      value: "http://jaeger.observability.svc:4318"
    - name: OTEL_EXPORTER_OTLP_PROTOCOL
      value: "http/protobuf"

querySqlOnFhir:
  extraEnv:
    # keeps the attrition funnel set by values-demo.yaml, since lists aren't merged across values files
    - name: QUERY_SQL_ON_FHIR_FUNNEL_ENABLED
      value: "true"
    - name: OTEL_SDK_DISABLED
      value: "false"
    - name: OTEL_TRACES_EXPORTER
      value: "otlp"
    - name: OTEL_SERVICE_NAME
      value: "recruit-query-sql-on-fhir"
    - name: OTEL_EXPORTER_OTLP_ENDPOINT
      value: "http://jaeger.observability.svc:4318"

fhirserver:
  # overrides the chart's default `fhirserver.extraEnv` and the one in values-demo.yaml, so their entries are repeated
  extraEnv:
    - name: HAPI_FHIR_SUBSCRIPTION_RESTHOOK_ENABLED
      value: "true"
    - name: SPRING_FLYWAY_BASELINE_ON_MIGRATE
      value: "true"
    - name: HAPI_FHIR_REUSE_CACHED_SEARCH_RESULTS_MILLIS
      value: "0"
    - name: JAVA_TOOL_OPTIONS
      value: "-XX:MaxRAMPercentage=75 -javaagent:/app/opentelemetry-javaagent.jar"
    - name: OTEL_METRICS_EXPORTER
      value: "none"
    - name: OTEL_LOGS_EXPORTER
      value: "none"
    - name: OTEL_TRACES_EXPORTER
      value: "otlp"
    - name: OTEL_SERVICE_NAME
      value: "recruit-hapi-fhir-server"
    - name: OTEL_EXPORTER_OTLP_ENDPOINT
      value: "http://jaeger.observability.svc:4318"

To view the traces, forward Jaeger's port and open http://127.0.0.1:16686:

kubectl port-forward -n observability svc/jaeger 16686:16686

Running the query module using Argo Workflows

By default, the query module runs on its own schedule. It can also run once and exit, setting QUERY_SQL_ON_FHIR_RUN_MODE=one-shot, which is useful for running it right after the jobs that update the data it queries, e.g. using Airflow or Argo Workflows. It exits with a non-zero code if any study failed, so the workflow step fails too. Set querySqlOnFhir.enabled=false in the chart so it doesn't also run on its schedule.

Below you can find an example for running the query module as part of a larger workflow. Adjust the FHIR server and Trino settings to your installation, see Configuration options:

query-argo-workflow.yaml
# yaml-language-server: $schema=https://raw.githubusercontent.com/argoproj/argo-workflows/v3.7.2/api/jsonschema/schema.json
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: recruit-query-workflow-
spec:
  entrypoint: full-run
  templates:
    # stands in for whatever updates the data the eligibility criteria are queried against
    - name: etl
      container:
        image: docker.io/docker/whalesay@sha256:178598e51a26abbc958b8a2e48825c90bc22e641de3d31e18aaf55f3258ba93b
        command: [cowsay]
        args: ["Running the ETL job that updates the data lakehouse"]
        securityContext:
          readOnlyRootFilesystem: true
          runAsUser: 65532
          runAsGroup: 65532
          seccompProfile:
            type: RuntimeDefault
          allowPrivilegeEscalation: false
          capabilities:
            drop:
              - ALL
          privileged: false
          runAsNonRoot: true

    - name: recruit-query
      # Argo's own metrics for this step, served by the workflow controller's metrics endpoint. Unlike
      # the ones the query module pushes, they also cover runs that failed before it could push anything.
      metrics:
        prometheus:
          - name: recruit_query_step_duration_seconds
            help: How long the last recruIT query step took
            labels:
              - key: status
                value: "{{status}}"
            gauge:
              realtime: false
              value: "{{duration}}"
          - name: recruit_query_step_runs
            help: recruIT query steps run, by status
            labels:
              - key: status
                value: "{{status}}"
            counter:
              value: "1"
      container:
        image: ghcr.io/open-recruit/recruit/query-sql-on-fhir:v11.3.0 # x-release-please-version
        env:
          # one poll cycle, then exit - non-zero if any study failed, which fails the step
          - name: QUERY_SQL_ON_FHIR_RUN_MODE
            value: one-shot
          - name: FHIR_SERVER_BASE_URL
            value: http://recruit-fhirserver:8080/fhir
          - name: SPRING_DATASOURCE_URL
            value: jdbc:trino://trino:8080/fhir/default
          - name: SPRING_DATASOURCE_USERNAME
            value: trino
          # the pod exits before Prometheus could scrape it, so push the metrics to a Pushgateway instead
          - name: MANAGEMENT_PROMETHEUS_METRICS_EXPORT_PUSHGATEWAY_ENABLED
            value: "true"
          - name: MANAGEMENT_PROMETHEUS_METRICS_EXPORT_PUSHGATEWAY_ADDRESS
            value: prometheus-pushgateway.monitoring.svc:9091
          # labels the pushed metrics with the workflow's namespace rather than the Pushgateway's
          - name: MANAGEMENT_PROMETHEUS_METRICS_EXPORT_PUSHGATEWAY_GROUPINGKEY_NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
        securityContext:
          privileged: false
          capabilities:
            drop:
              - ALL
          runAsNonRoot: true
          runAsUser: 65532
          runAsGroup: 65532
          readOnlyRootFilesystem: true
          allowPrivilegeEscalation: false
          seccompProfile:
            type: RuntimeDefault
        volumeMounts:
          - name: tmp-volume
            mountPath: /tmp
      volumes:
        - name: tmp-volume
          emptyDir: {}

    - name: full-run
      dag:
        tasks:
          - name: run-etl
            template: etl
          - name: run-recruit-query
            depends: run-etl
            template: recruit-query
argo submit -n recruit --wait --log query-argo-workflow.yaml

Metrics for one-shot runs

A one-shot run is usually over before Prometheus would scrape its metrics, so the example pushes them to a Prometheus Pushgateway instead: every minute while running, and once more right before exiting. Each run replaces what the previous one pushed. To install a Pushgateway that the kube-prometheus-stack from Metrics scrapes:

helm upgrade --install -n monitoring prometheus-pushgateway \
  oci://ghcr.io/prometheus-community/charts/prometheus-pushgateway \
  --set serviceMonitor.enabled=true \
  --set serviceMonitor.additionalLabels.release=kube-prometheus-stack

Its ServiceMonitor keeps the labels the metrics were pushed with (honorLabels: true). If you scrape the Pushgateway some other way, set honor_labels: true there too, or Prometheus replaces the pushed job and namespace labels with the Pushgateway's own. The pushed namespace label comes from MANAGEMENT_PROMETHEUS_METRICS_EXPORT_PUSHGATEWAY_GROUPINGKEY_NAMESPACE in the example.

The recruIT dashboard's eligibility query panels then work as for the scheduled module. Last successful poll at the top shows how long ago a run last finished without any study failing, which is also a good metric to alert on (recruit_query_poll_last_success_timestamp_seconds): it catches failed runs and runs that never happened. The dashboard's runtime panels only show a one-shot run's last moments, though, so they don't mean much for it.

The metrics section of the example's recruit-query step adds Argo's own metrics for the step: how long it took and whether it succeeded, also for runs that failed before the query module could push anything.