diff --git a/.github/scripts/smoke_nifi_login.sh b/.github/scripts/smoke_nifi_login.sh new file mode 100644 index 00000000..4ea4f303 --- /dev/null +++ b/.github/scripts/smoke_nifi_login.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail + +api="${1%/}/nifi-api" +request=(curl -fsS --noproxy '*' --cacert "$SECURITY_DIR/certificates/root/root-ca.pem" --max-time 10) +token=$("${request[@]}" --retry 30 --retry-all-errors --retry-delay 10 --retry-max-time 300 \ + --data-urlencode "username=$SINGLE_USER_CREDENTIALS_USERNAME" \ + --data-urlencode "password=$SINGLE_USER_CREDENTIALS_PASSWORD" "$api/access/token") +[[ -n "$token" ]] +"${request[@]}" --header "Authorization: Bearer $token" "$api/flow/current-user" | + jq -e --arg user "$SINGLE_USER_CREDENTIALS_USERNAME" '.identity == $user and .anonymous == false' diff --git a/.github/workflows/build_helm_charts.yml b/.github/workflows/build_helm_charts.yml index 2b515fb9..f165e5e5 100644 --- a/.github/workflows/build_helm_charts.yml +++ b/.github/workflows/build_helm_charts.yml @@ -21,10 +21,12 @@ on: - "helm-charts/*-v*.*.*" # e.g., helm-charts/medcat-trainer-helm-v0.1.2 paths: - "deployment/charts/**" + - "apps/opensearch/config/opensearch.yml" - ".github/workflows/build_helm_charts.yml" pull_request: paths: - "deployment/charts/**" + - "apps/opensearch/config/opensearch.yml" - ".github/workflows/build_helm_charts.yml" defaults: diff --git a/.github/workflows/docker_smoke_nifi.yml b/.github/workflows/docker_smoke_nifi.yml new file mode 100644 index 00000000..89a37322 --- /dev/null +++ b/.github/workflows/docker_smoke_nifi.yml @@ -0,0 +1,88 @@ +name: docker_smoke_nifi + +on: + push: + branches: ['**'] + paths: &paths + - 'apps/nifi/**' + - 'apps/nginx/**' + - 'deployment/Makefile' + - 'deployment/scripts/security/**' + - 'deployment/security/templates/**' + - '.github/scripts/smoke_nifi_login.sh' + - '.github/workflows/docker_smoke_nifi.yml' + - '!**/*.md' + - '!**/README*' + pull_request: + paths: *paths + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +defaults: + run: + shell: bash + working-directory: apps/nifi/docker + +jobs: + smoke: + name: Smoke-test NiFi services + runs-on: ubuntu-24.04 + timeout-minutes: 45 + env: + COMPOSE_PROJECT_NAME: nifi-smoke-${{ github.run_id }}-${{ github.run_attempt }} + COGSTACK_GENERAL_ENV_FILE: /dev/null + COGSTACK_NIFI_ENV_FILE: /dev/null + NIFI_DOCKER_CPU_MIN: '1' + NIFI_DOCKER_CPU_MAX: '2' + NIFI_DOCKER_RAM: 4g + SINGLE_USER_CREDENTIALS_USERNAME: smoke + + steps: + - uses: actions/checkout@v7 + + - name: Set up Java + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + + - name: Start NiFi and verify login + run: | + SECURITY_DIR=$(mktemp -d "$RUNNER_TEMP/nifi-smoke.XXXXXX") + printf 'SECURITY_DIR=%s\n' "$SECURITY_DIR" >> "$GITHUB_ENV" + password="$(openssl rand -hex 16)" + NIFI_SENSITIVE_PROPS_KEY=$(openssl rand -hex 16) + export SECURITY_DIR NIFI_SENSITIVE_PROPS_KEY + export KEYSTORE_PASSWORD="$password" TRUSTSTORE_PASSWORD="$password" SINGLE_USER_CREDENTIALS_PASSWORD="$password" + ROOT_CERTIFICATE_KEYSTORE_PASSWORD="$password" make -C ../../../deployment certs + # The published containers run as UID/GID 1000. + sudo chown 1000:1000 "$SECURITY_DIR"/certificates/{nifi/nifi-keystore.jks,nginx/tls.key} + + docker compose -f docker-compose.yml -f - up -d <<'YAML' + services: + nifi: + environment: + NIFI_HEALTHCHECK_HOST: nifi + NIFI_WEB_PROXY_HOST: 127.0.0.1:8443 + NIFI_SENSITIVE_PROPS_KEY: ${NIFI_SENSITIVE_PROPS_KEY} + YAML + bash ../../../.github/scripts/smoke_nifi_login.sh https://127.0.0.1:8443 + + - name: Dump container logs + if: failure() + run: | + [[ -n "${SECURITY_DIR:-}" ]] || exit 0 + docker compose ps + docker compose logs --no-color nifi nifi-nginx + + - name: Shutdown stack + if: always() + run: | + [[ -n "${SECURITY_DIR:-}" ]] || exit 0 + docker compose down -v diff --git a/.github/workflows/docker_smoke_opensearch.yml b/.github/workflows/docker_smoke_opensearch.yml new file mode 100644 index 00000000..ac225062 --- /dev/null +++ b/.github/workflows/docker_smoke_opensearch.yml @@ -0,0 +1,81 @@ +name: docker_smoke_opensearch + +on: + push: + branches: ['**'] + paths: &paths + - 'apps/opensearch/**' + - 'apps/opensearch-dashboards/**' + - 'deployment/Makefile' + - 'deployment/scripts/security/**' + - 'deployment/security/templates/**' + - '.github/workflows/docker_smoke_opensearch.yml' + pull_request: + paths: *paths + workflow_dispatch: + +permissions: + contents: read + +jobs: + smoke: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + env: + SMOKE_PROJECT_SUFFIX: smoke-${{ github.run_id }}-${{ github.run_attempt }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + + - name: Start the default stack and verify access + shell: bash + run: | + SECURITY_DIR=$(mktemp -d "$RUNNER_TEMP/opensearch-smoke.XXXXXX") + KIBANA_PASSWORD=$(openssl rand -hex 16) + OS_NIFI_PASSWORD=$(openssl rand -hex 16) + OS_ANALYST_PASSWORD=$(openssl rand -hex 16) + export SECURITY_DIR KIBANA_PASSWORD OS_NIFI_PASSWORD OS_ANALYST_PASSWORD + printf '::add-mask::%s\n' "$KIBANA_PASSWORD" + printf 'SECURITY_DIR=%s\nKIBANA_PASSWORD=%s\n' "$SECURITY_DIR" "$KIBANA_PASSWORD" >> "$GITHUB_ENV" + password=$(openssl rand -hex 16) + export ROOT_CERTIFICATE_KEYSTORE_PASSWORD="$password" OS_CERTIFICATE_PASSWORD="$password" + make -C deployment certs-root certs-opensearch + OPENSEARCH_DASHBOARDS_DNS_NAMES=localhost ./deployment/scripts/security/create_opensearch_client_admin_certs.sh --dashboards-only + certs="$SECURITY_DIR/certificates/opensearch" + sudo chown 1000:1000 "$certs"/{opensearch-shared.key,es_kibana_client.key} + request=(curl -sS --noproxy '*' --cacert "$SECURITY_DIR/certificates/root/root-ca.pem" --max-time 10) + + search=(docker compose -p "opensearch-$SMOKE_PROJECT_SUFFIX" -f apps/opensearch/docker/docker-compose.yml) + "${search[@]}" up -d + bash apps/opensearch/security/bootstrap.sh "${search[@]}" exec -T opensearch + + printf '%s\n' '{"index":{"_id":"smoke"}}' '{"ok":true}' | + "${request[@]}" -f -u "nifi:$OS_NIFI_PASSWORD" -H 'Content-Type: application/x-ndjson' \ + --data-binary @- https://localhost:9200/nifi_smoke/_bulk | jq -e '.errors == false' + "${request[@]}" -f -u "cogstack_user:$OS_ANALYST_PASSWORD" \ + https://localhost:9200/nifi_smoke/_doc/smoke | jq -e '._source.ok == true' + status=$("${request[@]}" -u "cogstack_user:$OS_ANALYST_PASSWORD" -o /dev/null -w '%{http_code}' \ + -X PUT --json '{"ok":false}' https://localhost:9200/nifi_smoke/_doc/smoke) + [[ "$status" == 403 ]] + + docker compose -p "opensearch-dashboards-$SMOKE_PROJECT_SUFFIX" -f apps/opensearch-dashboards/docker/docker-compose.yml up -d + "${request[@]}" -f --retry 30 --retry-all-errors --retry-delay 3 -H 'osd-xsrf: smoke' \ + --json "{\"username\":\"cogstack_user\",\"password\":\"$OS_ANALYST_PASSWORD\"}" \ + https://localhost:5601/auth/login | jq -e '.username == "cogstack_user"' + + - name: Cleanup + if: always() + env: + SMOKE_JOB_STATUS: ${{ job.status }} + run: | + [[ -n "${SECURITY_DIR:-}" ]] || exit 0 + for app in opensearch-dashboards opensearch; do + compose=(docker compose -p "$app-$SMOKE_PROJECT_SUFFIX" -f "apps/$app/docker/docker-compose.yml") + if [[ "$SMOKE_JOB_STATUS" == failure ]]; then + "${compose[@]}" logs --tail 50 || true + fi + "${compose[@]}" down -v + done diff --git a/.github/workflows/helm_smoke_logins.yml b/.github/workflows/helm_smoke_logins.yml new file mode 100644 index 00000000..2dcf03e2 --- /dev/null +++ b/.github/workflows/helm_smoke_logins.yml @@ -0,0 +1,126 @@ +name: kubernetes_smoke_logins + +on: + push: + branches: ['**'] + paths: &paths + - 'deployment/charts/nifi/**' + - 'deployment/charts/nginx/**' + - 'deployment/charts/opensearch/**' + - 'deployment/charts/opensearch-dashboards/**' + - 'deployment/Makefile' + - 'deployment/env/authentication.env' + - 'deployment/env/certificates.env' + - 'deployment/env/general.env' + - 'deployment/scripts/security/**' + - 'deployment/security/templates/**' + - 'apps/opensearch/**' + - '.github/scripts/smoke_nifi_login.sh' + - '.github/workflows/helm_smoke_logins.yml' + pull_request: + paths: *paths + workflow_dispatch: + workflow_call: + inputs: + stacks: + type: string + required: true + +permissions: + contents: read + +defaults: + run: + shell: bash + +jobs: + smoke: + name: Kubernetes smoke (${{ matrix.stack }}) + runs-on: ubuntu-24.04 + timeout-minutes: 35 + strategy: + fail-fast: false + matrix: + stack: ${{ fromJSON(inputs.stacks || '["nifi","opensearch"]') }} + env: + SINGLE_USER_CREDENTIALS_USERNAME: smoke + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + - uses: helm/kind-action@v1.15.2 + + - name: Generate and load certificates + run: | + source deployment/env/general.env + SECURITY_DIR=$(mktemp -d "$RUNNER_TEMP/k3s-smoke.XXXXXX") + password=$(openssl rand -hex 16) + printf '::add-mask::%s\n' "$password" + printf 'SECURITY_DIR=%s\nSMOKE_PASSWORD=%s\n' "$SECURITY_DIR" "$password" >> "$GITHUB_ENV" + export SECURITY_DIR ROOT_CERTIFICATE_KEYSTORE_PASSWORD="$password" OS_CERTIFICATE_PASSWORD="$password" + export KEYSTORE_PASSWORD="$password" TRUSTSTORE_PASSWORD="$password" + make -C deployment -j1 setup-k3s-namespace certs-all k3s-load-certs-all + kubectl config set-context --current --namespace="$KUBE_NAMESPACE" + + - name: Install NiFi + if: matrix.stack == 'nifi' || matrix.stack == 'nginx' + run: | + NIFI_SINGLE_USER_CREDENTIALS_USERNAME="$SINGLE_USER_CREDENTIALS_USERNAME" \ + NIFI_SINGLE_USER_CREDENTIALS_PASSWORD="$SMOKE_PASSWORD" \ + NIFI_SENSITIVE_PROPS_KEY="$(openssl rand -hex 16)" \ + KEYSTORE_PASSWORD="$SMOKE_PASSWORD" TRUSTSTORE_PASSWORD="$SMOKE_PASSWORD" \ + make -C deployment k3s-load-auth-nifi + NIFI_WEB_PROXY_HOST=127.0.0.1:8443 make -C deployment k3s-install-nifi K3S_TIMEOUT=15m + + - name: NiFi login + if: matrix.stack == 'nifi' + run: | + kubectl port-forward svc/cogstack-nifi 8443:8443 & + trap 'kill "$!"' EXIT + SINGLE_USER_CREDENTIALS_PASSWORD="$SMOKE_PASSWORD" bash .github/scripts/smoke_nifi_login.sh https://127.0.0.1:8443 + + - name: NGINX proxy login + if: matrix.stack == 'nifi' || matrix.stack == 'nginx' + run: | + make -C deployment k3s-install-nginx K3S_TIMEOUT=5m + kubectl port-forward svc/cogstack-nginx 8443:8443 & + trap 'kill "$!"' EXIT + SINGLE_USER_CREDENTIALS_PASSWORD="$SMOKE_PASSWORD" bash .github/scripts/smoke_nifi_login.sh https://127.0.0.1:8443 + + - name: OpenSearch authentication + if: matrix.stack == 'opensearch' + run: | + sudo sysctl -w vm.max_map_count=262144 + OPENSEARCH_KIBANA_PASSWORD="$SMOKE_PASSWORD" make -C deployment k3s-load-auth-opensearch-dashboards + make -C deployment k3s-install-opensearch + OPENSEARCH_ANALYST_PASSWORD="$SMOKE_PASSWORD" \ + make -C deployment k3s-bootstrap-opensearch + kubectl port-forward svc/opensearch-cluster-master 9200:9200 & + trap 'kill "$!"' EXIT + curl -fsS --noproxy '*' --cacert "$SECURITY_DIR/certificates/root/root-ca.pem" \ + --retry 10 --retry-all-errors --retry-delay 2 --max-time 10 \ + -u "cogstack_user:$SMOKE_PASSWORD" https://localhost:9200/_plugins/_security/authinfo | + jq -e '.user_name == "cogstack_user"' + + - name: OpenSearch Dashboards login + if: matrix.stack == 'opensearch' + run: | + certs="$SECURITY_DIR/certificates" + make -C deployment k3s-load-certs-opensearch-dashboards + make -C deployment k3s-install-opensearch-dashboards K3S_TIMEOUT=5m + kubectl port-forward svc/opensearch-dashboards 5601:5601 & + trap 'kill "$!"' EXIT + curl -fsS --noproxy '*' --cacert "$certs/root/root-ca.pem" --max-time 10 \ + --retry 30 --retry-all-errors --retry-delay 3 -H 'osd-xsrf: smoke' \ + --json "{\"username\":\"cogstack_user\",\"password\":\"$SMOKE_PASSWORD\"}" \ + https://localhost:5601/auth/login | jq -e '.username == "cogstack_user"' + + - name: Show pod logs on failure + if: failure() + run: | + kubectl get pods,svc,pvc + for pod in $(kubectl get pods -o name); do + kubectl logs "$pod" --all-containers --tail=100 || true + done diff --git a/.github/workflows/helm_smoke_nginx.yml b/.github/workflows/helm_smoke_nginx.yml new file mode 100644 index 00000000..39fd5f69 --- /dev/null +++ b/.github/workflows/helm_smoke_nginx.yml @@ -0,0 +1,12 @@ +name: helm_smoke_nginx + +on: workflow_dispatch + +permissions: + contents: read + +jobs: + smoke: + uses: ./.github/workflows/helm_smoke_logins.yml + with: + stacks: '["nginx"]' diff --git a/.github/workflows/helm_smoke_opensearch.yml b/.github/workflows/helm_smoke_opensearch.yml new file mode 100644 index 00000000..93e28f87 --- /dev/null +++ b/.github/workflows/helm_smoke_opensearch.yml @@ -0,0 +1,12 @@ +name: helm_smoke_opensearch + +on: workflow_dispatch + +permissions: + contents: read + +jobs: + smoke: + uses: ./.github/workflows/helm_smoke_logins.yml + with: + stacks: '["opensearch"]' diff --git a/.github/workflows/smoke_nifi_services.yml b/.github/workflows/smoke_nifi_services.yml deleted file mode 100644 index 8271642a..00000000 --- a/.github/workflows/smoke_nifi_services.yml +++ /dev/null @@ -1,163 +0,0 @@ -name: smoke-nifi-services - -on: - push: - branches: ['**'] - paths: &paths - - 'apps/nifi/**' - - 'apps/nginx/**' - - '.github/workflows/smoke_nifi_services.yml' - - '!**/*.md' - - '!**/README*' - pull_request: - paths: *paths - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -defaults: - run: - shell: bash - working-directory: apps/nifi/docker - -jobs: - smoke: - name: Build and smoke-test NiFi services - runs-on: ubuntu-24.04 - timeout-minutes: 45 - env: - COMPOSE_FILE: docker-compose.base.yml:docker-compose.dev.yml - COMPOSE_PROJECT_NAME: nifi-smoke - CERT_DIR: ../../../deployment/security/certificates - - steps: - - uses: actions/checkout@v7 - - - name: Set up Java - uses: actions/setup-java@v6 - with: - distribution: temurin - java-version: '21' - - - name: Generate smoke fixtures - run: | - scratch_dir="$(mktemp -d)" - trap 'rm -rf "$scratch_dir"' EXIT - mkdir -p "$CERT_DIR"/{root,nifi,nginx} ../env - ca_cert="$CERT_DIR/root/root-ca.pem" - password="$(openssl rand -hex 16)" - - openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj '/CN=NiFi smoke CA' \ - -addext 'basicConstraints=critical,CA:TRUE' \ - -addext 'keyUsage=critical,keyCertSign,cRLSign' \ - -keyout "$scratch_dir/ca.key" -out "$ca_cert" - - issue_cert() { - local subject="$1" san="$2" key="$3" cert="$4" - openssl req -new -newkey rsa:2048 -nodes -subj "/CN=$subject" \ - -keyout "$key" -out "$scratch_dir/leaf.csr" - openssl x509 -req -days 1 -in "$scratch_dir/leaf.csr" \ - -CA "$ca_cert" -CAkey "$scratch_dir/ca.key" \ - -CAserial "$scratch_dir/ca.srl" -CAcreateserial \ - -extfile <(printf 'subjectAltName=%s\nextendedKeyUsage=serverAuth\n' "$san") -out "$cert" - } - issue_cert nifi DNS:nifi "$scratch_dir/nifi.key" "$scratch_dir/nifi.pem" - issue_cert 127.0.0.1 IP:127.0.0.1 "$CERT_DIR/nginx/tls.key" "$CERT_DIR/nginx/tls.crt" - - openssl pkcs12 -export -name nifi -inkey "$scratch_dir/nifi.key" \ - -in "$scratch_dir/nifi.pem" -certfile "$ca_cert" \ - -out "$scratch_dir/nifi.p12" -passout "pass:$password" - keytool -importkeystore -noprompt \ - -srckeystore "$scratch_dir/nifi.p12" -srcstoretype PKCS12 -srcstorepass "$password" \ - -destkeystore "$CERT_DIR/nifi/nifi-keystore.jks" -deststoretype JKS -deststorepass "$password" - keytool -importcert -noprompt -alias root-ca -file "$ca_cert" \ - -keystore "$CERT_DIR/nifi/nifi-truststore.jks" -storetype JKS -storepass "$password" - - touch ../env/general.env - cat > ../env/nifi.env <&2; exit 1 ;; - esac - done - - for service in nifi nifi-nginx; do - docker compose exec -T "$service" sh -ec 'test "$(id -u)" -ne 0' - done - docker compose exec -T nifi /opt/nifi/scripts/cogstack-healthcheck.sh live - docker compose exec -T nifi /opt/nifi/scripts/cogstack-healthcheck.sh ready - for probe in live ready; do - docker compose exec -T nifi-nginx curl -fsS --output /dev/null "http://127.0.0.1:8080/healthz/$probe" - done - - response="$("${request[@]}" --data-urlencode "username=$SINGLE_USER_CREDENTIALS_USERNAME" \ - --data-urlencode "password=$SINGLE_USER_CREDENTIALS_PASSWORD" \ - --write-out $'\n%{http_code}' "$url/nifi-api/access/token")" - code="${response##*$'\n'}" - token="${response%$'\n'*}" - if [[ "$code" != 201 || -z "$token" ]]; then - echo "NiFi token request returned HTTP $code or an empty token" >&2 - exit 1 - fi - - code="$("${request[@]}" --header "Authorization: Bearer $token" --output /dev/null \ - --write-out '%{http_code}' "$url/nifi-api/flow/about")" - if [[ "$code" != 200 ]]; then - echo "Authenticated NiFi API returned HTTP $code" >&2 - exit 1 - fi - echo 'OK: authenticated NiFi API returned HTTP 200' - - - name: Dump container logs - if: failure() - run: | - [[ -f ../env/nifi.env ]] || exit 0 - source ./export_env_vars.sh - docker compose ps - docker compose logs --no-color nifi nifi-nginx - - - name: Shutdown stack - if: always() - run: | - [[ -f ../env/nifi.env ]] || exit 0 - source ./export_env_vars.sh - docker compose down -v - docker compose -p nifi-smoke-published -f docker-compose.yml down diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f2d49cd6..d0244981 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -5,9 +5,6 @@ "deployment/charts/cohorter": "0.5.0", "deployment/charts/observability": "0.4.1", "deployment/charts/jupyter-hub": "0.5.0", - "deployment/charts/ocr-service": "0.1.0", - "deployment/charts/nifi": "0.0.0", - "deployment/charts/nginx": "0.0.0", "deployment/terraform/openstack-kubernetes-k3s": "0.1.4", "apps/ocr-service": "1.1.4", "apps/jupyter-hub": "2.3.12" diff --git a/apps/nifi/README.md b/apps/nifi/README.md index a84f9d3a..01341893 100644 --- a/apps/nifi/README.md +++ b/apps/nifi/README.md @@ -13,56 +13,40 @@ production configurations use `cogstacksystems/nifi` and `cogstacksystems/nginx` From the repository root, create `apps/nifi/env/` and add `general.env` and `nifi.env`. Both files are Git-ignored. `general.env` can be empty if you have -no shared settings. Use the following as a starting point for `nifi.env` and -replace the example credentials and passwords before starting NiFi. +no shared settings. Use the following as a starting point for `nifi.env`. ```dotenv NIFI_DOCKER_CPU_MIN=1 NIFI_DOCKER_CPU_MAX=2 NIFI_DOCKER_RAM=4g -SINGLE_USER_CREDENTIALS_USERNAME=admin -SINGLE_USER_CREDENTIALS_PASSWORD='replace-with-a-unique-password' -NIFI_SENSITIVE_PROPS_KEY='replace-with-a-stable-encryption-key' - -KEYSTORE_PATH=/security/certificates/nifi/nifi-keystore.jks -KEYSTORE_TYPE=JKS -KEYSTORE_PASSWORD='replace-with-the-keystore-password' -TRUSTSTORE_PATH=/security/certificates/nifi/nifi-truststore.jks -TRUSTSTORE_TYPE=JKS -TRUSTSTORE_PASSWORD='replace-with-the-truststore-password' - NIFI_WEB_PROXY_HOST=localhost:8443 NIFI_HEALTHCHECK_HOST=nifi ``` -Use at least 12 characters for the single-user password. Preserve -`NIFI_SENSITIVE_PROPS_KEY` with the flow configuration so NiFi can decrypt -saved sensitive properties. For a non-local deployment, set `NIFI_WEB_PROXY_HOST` -to the browser-facing host and port. If you change `NIFI_EXTERNAL_PORT_NGINX`, -update that allowlist entry as well. See [Apache's startup script](https://github.com/apache/nifi/blob/rel/nifi-2.12.0/nifi-docker/dockerhub/sh/start.sh) +Set `KEYSTORE_PASSWORD` and `TRUSTSTORE_PASSWORD` to match the mounted stores. +Set `SINGLE_USER_CREDENTIALS_USERNAME` and `SINGLE_USER_CREDENTIALS_PASSWORD` +for the NiFi login. Use at least 12 characters for the single-user password. +Use `COGSTACK_NIFI_ENV_FILE` to select another deployment's `nifi.env`. + +The dev Make targets take their sample store passwords and login from +[`certificates.env`](../../deployment/env/certificates.env) and +[`authentication.env`](../../deployment/env/authentication.env). +Set your own values in `nifi.env` to override the samples. + +Preserve `NIFI_SENSITIVE_PROPS_KEY` with the flow configuration so NiFi can +decrypt saved sensitive properties. For a non-local deployment, set +`NIFI_WEB_PROXY_HOST` to the browser-facing host and port. If you change +`NIFI_EXTERNAL_PORT_NGINX`, update that allowlist entry as well. See +[Apache's startup script](https://github.com/apache/nifi/blob/rel/nifi-2.12.0/nifi-docker/dockerhub/sh/start.sh) and [Docker setup guide](https://github.com/apache/nifi/blob/rel/nifi-2.12.0/nifi-docker/dockerhub/README.md) for additional settings. ### TLS certificates -For local development, keep TLS and demo login settings in -`deployment/env/cert_auth_settings_dev.env`. Set an absolute `SECURITY_DIR`, -`ROOT_CERTIFICATE_KEYSTORE_PASSWORD`, `KEYSTORE_PASSWORD`, `TRUSTSTORE_PASSWORD`, -`SINGLE_USER_CREDENTIALS_USERNAME`, and `SINGLE_USER_CREDENTIALS_PASSWORD`. -Prepare or reuse the TLS bundle from the repository root. - -```bash -make -C apps/nifi/docker setup-nifi-dev-tls -``` - -Keep this Git-ignored file at mode `0600`. It can also hold store paths, types, -and TLS names. `start-nifi-dev` and `start-nifi-dev-build` load it automatically -when present and mount the bundle's runtime TLS files. The CA signing key and -its store password stay on the host. - -To supply certificates manually, place the following under -`deployment/security/certificates/`. +Use the existing certificate generators or supply a TLS bundle. Place the files +under `deployment/security/certificates/`, or set `SECURITY_DIR` in `nifi.env` +to the parent of your deployment’s `certificates/` directory. | Files | Purpose | | --- | --- | @@ -72,10 +56,9 @@ To supply certificates manually, place the following under Compose mounts the service certificate directories and `root/root-ca.pem` read-only. The CA signing key and private bundles stay on the host. Make the mounted files -readable by their container users. The start targets run `make check-tls`, which -checks for readable, nonempty regular files. If `root-ca.pem` is a directory from an -earlier bind mount, replace it with the actual PEM file. Certificate validation -occurs when the services connect over TLS. +readable by their container users. The start targets check for readable, +nonempty files before launching. Certificate validation occurs when the services +connect over TLS. ### Start and verify @@ -85,6 +68,7 @@ Run these commands from `apps/nifi/docker/`: | --- | --- | | `make check-config` | Resolve and validate all three Compose configurations using the env files. | | `make start-nifi` | Use `docker-compose.yml` to start published images with a Compose-managed `cogstack-net`. | +| `make start-nifi-dev` | Start NiFi and NGINX with the dev settings. | | `make start-nifi-dev-build` | Apply `docker-compose.dev.yml` over the base, build both images locally, mount editable NiFi resources and dev data, and use `nifi-dev-net`. | | `make start-nifi-prod` | Apply `docker-compose.prod.yml` over the base and start published images on an existing `cogstack-net`. | @@ -186,9 +170,8 @@ with external service, credential, or sample data requirements. ## Kubernetes -The [NiFi chart](../../deployment/charts/nifi/README.md) and -[NGINX chart](../../deployment/charts/nginx/README.md) document their ConfigMaps, -TLS Secrets, and storage. Use those instructions for Helm deployments. +The [NiFi and NGINX deployment instructions](../../deployment/charts/README.md#nifi-and-nginx) +cover the manifests, ConfigMaps, TLS Secrets, and persistent storage. ## Dependency auditing diff --git a/apps/nifi/docker/Makefile b/apps/nifi/docker/Makefile index 037f080b..b347f961 100644 --- a/apps/nifi/docker/Makefile +++ b/apps/nifi/docker/Makefile @@ -3,36 +3,27 @@ SHELL := /usr/bin/env bash DC_START_CMD := up -d DC_STOP_CMD := stop -COMPOSE_DEV := docker compose -f docker-compose.base.yml -f docker-compose.dev.yml +COMPOSE_DEV := docker compose --env-file ../../../deployment/env/certificates.env \ + --env-file ../../../deployment/env/authentication.env \ + $(if $(wildcard .env),--env-file .env) \ + -f docker-compose.base.yml -f docker-compose.dev.yml COMPOSE_PROD := docker compose -f docker-compose.base.yml -f docker-compose.prod.yml -DEV_CERT_ENV := $(abspath ../../../deployment/env/cert_auth_settings_dev.env) define WITH_ENV source ./export_env_vars.sh || exit $$?; endef -define WITH_DEV_CERTS -$(WITH_ENV) \ -cert_dir=../../../deployment/security/certificates; \ -dev_certs=(); \ -if [[ -f "$(DEV_CERT_ENV)" ]]; then \ - set -a; source "$(DEV_CERT_ENV)" || exit $$?; set +a; \ - : "$${SECURITY_DIR:?Set SECURITY_DIR in the dev settings file}"; \ - : "$${KEYSTORE_PASSWORD:?Set KEYSTORE_PASSWORD in the dev settings file}" "$${TRUSTSTORE_PASSWORD:?Set TRUSTSTORE_PASSWORD in the dev settings file}"; \ - cert_dir="$$SECURITY_DIR/certificates"; \ - dev_certs=(-f docker-compose.dev-tls.yml); \ -fi; -endef - define CHECK_TLS_FILES -for cert in root/root-ca.pem nifi/nifi-keystore.jks nifi/nifi-truststore.jks nginx/tls.crt nginx/tls.key; do \ - file="$$cert_dir/$$cert"; \ +for cert in root/root-ca.pem nifi/nifi-{keystore,truststore}.jks nginx/tls.{crt,key}; do \ + file="$${SECURITY_DIR:-../../../deployment/security}/certificates/$$cert"; \ if [ ! -f "$$file" ] || [ ! -r "$$file" ] || [ ! -s "$$file" ]; then \ printf 'TLS file missing, empty, or unreadable: %s\n' "$$file" >&2; exit 1; \ fi; \ done; endef +WITH_START = $(WITH_ENV) $(CHECK_TLS_FILES) + help: ## List available targets with descriptions @echo "Available targets:" @awk '\ @@ -73,26 +64,22 @@ show-env: ## Print sorted environment variables after loading export_env_vars.sh ${WITH_ENV} >/dev/null 2>&1; printenv | sort check-config: ## Validate the default, dev and prod Compose configurations - @$(WITH_ENV) docker compose config --quiet && $(COMPOSE_PROD) config --quiet - @$(WITH_DEV_CERTS) $(COMPOSE_DEV) "$${dev_certs[@]}" config --quiet + @$(WITH_ENV) docker compose config --quiet && $(COMPOSE_DEV) config --quiet && $(COMPOSE_PROD) config --quiet check-tls: ## Check the TLS files required by NiFi and NGINX - @cert_dir=../../../deployment/security/certificates; $(CHECK_TLS_FILES) - -start-nifi: check-tls ## Start the default NiFi and NGINX stack - $(WITH_ENV) docker compose $(DC_START_CMD) + @$(WITH_ENV) $(CHECK_TLS_FILES) -setup-nifi-dev-tls: ## Generate or validate the local dev certificates using cert_auth_settings_dev.env - @./setup_dev_tls.sh "$(DEV_CERT_ENV)" +start-nifi: ## Start the default NiFi and NGINX stack + $(WITH_START) docker compose $(DC_START_CMD) start-nifi-dev: ## Start NiFi and NGINX with local builds - $(WITH_DEV_CERTS) $(CHECK_TLS_FILES) $(COMPOSE_DEV) "$${dev_certs[@]}" $(DC_START_CMD) nifi nifi-nginx + $(WITH_START) $(COMPOSE_DEV) $(DC_START_CMD) nifi nifi-nginx start-nifi-dev-build: ## Build and start NiFi dev services - $(WITH_DEV_CERTS) $(CHECK_TLS_FILES) $(COMPOSE_DEV) "$${dev_certs[@]}" up -d --build nifi nifi-nginx + $(WITH_START) $(COMPOSE_DEV) up -d --build nifi nifi-nginx -start-nifi-prod: check-tls ## Start the published NiFi and NGINX images on cogstack-net - $(WITH_ENV) $(COMPOSE_PROD) $(DC_START_CMD) +start-nifi-prod: ## Start the published NiFi and NGINX images on cogstack-net + $(WITH_START) $(COMPOSE_PROD) $(DC_START_CMD) build-nifi-image: ## Build the local NiFi image without starting services $(WITH_ENV) docker build \ @@ -128,4 +115,4 @@ delete-nifi-dev-images: ## Delete the NiFi dev images echo "No NiFi dev images found."; \ fi -.PHONY: help load-env show-env check-config check-tls start-nifi setup-nifi-dev-tls start-nifi-dev start-nifi-dev-build start-nifi-prod build-nifi-image stop-nifi-dev stop-nifi-prod delete-nifi delete-nifi-dev-containers delete-nifi-dev-volumes delete-nifi-dev-images +.PHONY: help load-env show-env check-config check-tls start-nifi start-nifi-dev start-nifi-dev-build start-nifi-prod build-nifi-image stop-nifi-dev stop-nifi-prod delete-nifi delete-nifi-dev-containers delete-nifi-dev-volumes delete-nifi-dev-images diff --git a/apps/nifi/docker/docker-compose.base.yml b/apps/nifi/docker/docker-compose.base.yml index 55763034..f1f1890c 100644 --- a/apps/nifi/docker/docker-compose.base.yml +++ b/apps/nifi/docker/docker-compose.base.yml @@ -19,14 +19,14 @@ x-env: AUTH: ${AUTH:-tls} NIFI_SECURITY_USER_AUTHORIZER: ${NIFI_SECURITY_USER_AUTHORIZER:-single-user-authorizer} NIFI_SECURITY_USER_LOGIN_IDENTITY_PROVIDER: ${NIFI_SECURITY_USER_LOGIN_IDENTITY_PROVIDER:-single-user-provider} - SINGLE_USER_CREDENTIALS_USERNAME: ${SINGLE_USER_CREDENTIALS_USERNAME:-${NIFI_SINGLE_USER_CREDENTIALS_USERNAME}} - SINGLE_USER_CREDENTIALS_PASSWORD: ${SINGLE_USER_CREDENTIALS_PASSWORD:-${NIFI_SINGLE_USER_CREDENTIALS_PASSWORD}} - KEYSTORE_PATH: ${KEYSTORE_PATH:-${NIFI_KEYSTORE_PATH}} - KEYSTORE_TYPE: ${KEYSTORE_TYPE:-${NIFI_KEYSTORE_TYPE}} - KEYSTORE_PASSWORD: ${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD}} - TRUSTSTORE_PATH: ${TRUSTSTORE_PATH:-${NIFI_TRUSTSTORE_PATH}} - TRUSTSTORE_TYPE: ${TRUSTSTORE_TYPE:-${NIFI_TRUSTSTORE_TYPE}} - TRUSTSTORE_PASSWORD: ${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD}} + SINGLE_USER_CREDENTIALS_USERNAME: ${SINGLE_USER_CREDENTIALS_USERNAME:-${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:-}} + SINGLE_USER_CREDENTIALS_PASSWORD: ${SINGLE_USER_CREDENTIALS_PASSWORD:-${NIFI_SINGLE_USER_CREDENTIALS_PASSWORD:-}} + KEYSTORE_PATH: ${KEYSTORE_PATH:-${NIFI_KEYSTORE_PATH:-/security/certificates/nifi/nifi-keystore.jks}} + KEYSTORE_TYPE: ${KEYSTORE_TYPE:-${NIFI_KEYSTORE_TYPE:-JKS}} + KEYSTORE_PASSWORD: ${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD:-}} + TRUSTSTORE_PATH: ${TRUSTSTORE_PATH:-${NIFI_TRUSTSTORE_PATH:-/security/certificates/nifi/nifi-truststore.jks}} + TRUSTSTORE_TYPE: ${TRUSTSTORE_TYPE:-${NIFI_TRUSTSTORE_TYPE:-JKS}} + TRUSTSTORE_PASSWORD: ${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD:-}} NIFI_WEB_HTTPS_PORT: ${NIFI_WEB_HTTPS_PORT:-${NIFI_INTERNAL_PORT:-8443}} NIFI_REMOTE_INPUT_SOCKET_PORT: ${NIFI_REMOTE_INPUT_SOCKET_PORT:-${NIFI_INPUT_SOCKET_PORT:-10000}} PYTHONPATH: ${NIFI_PYTHONPATH:-/opt/nifi/nifi-current/python/framework} @@ -45,9 +45,9 @@ x-env: x-mounts: nifi: &nifi-volumes # Security certificates - - ../../../deployment/security/certificates/nifi:/security/certificates/nifi:ro + - ${SECURITY_DIR:-../../../deployment/security}/certificates/nifi:/security/certificates/nifi:ro - type: bind - source: ../../../deployment/security/certificates/root/root-ca.pem + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem target: /security/certificates/root/root-ca.pem read_only: true bind: @@ -67,9 +67,9 @@ x-mounts: - /tmp:mode=1777 nifi-nginx: &nifi-nginx-volumes - - ../../../deployment/security/certificates/nginx:/certificates/nginx:ro + - ${SECURITY_DIR:-../../../deployment/security}/certificates/nginx:/certificates/nginx:ro - type: bind - source: ../../../deployment/security/certificates/root/root-ca.pem + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem target: /certificates/root/root-ca.pem read_only: true bind: diff --git a/apps/ocr-service/Dockerfile b/apps/ocr-service/Dockerfile index eec0cfb4..7c02451d 100644 --- a/apps/ocr-service/Dockerfile +++ b/apps/ocr-service/Dockerfile @@ -156,7 +156,7 @@ RUN python${APP_PYTHON_VERSION} -m venv "$VIRTUAL_ENV" && \ # Byte-compile using venv python RUN "$VIRTUAL_ENV/bin/python" -m compileall /ocr_service -# Run as non-root by default for Kubernetes restricted policies. +# Run as a non-root user by default. ARG OCR_SERVICE_UID=10001 ARG OCR_SERVICE_GID=10001 RUN groupadd --system --gid "$OCR_SERVICE_GID" ocrsvc && \ diff --git a/apps/ocr-service/Makefile b/apps/ocr-service/Makefile deleted file mode 100644 index cd0e5ae3..00000000 --- a/apps/ocr-service/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -SHELL := /usr/bin/env bash -.SHELLFLAGS := -o pipefail -c - -HELM_RELEASE ?= ocr-service -HELM_CHART ?= ../../deployment/charts/ocr-service -HELM_TEXT_ONLY_VALUES ?= $(HELM_CHART)/values-text-only.yaml -HELM_ARGS ?= - -.PHONY: helm-install helm-install-text-only helm-template helm-lint helm-uninstall - -helm-install: - helm upgrade --install $(HELM_RELEASE) $(HELM_CHART) $(HELM_ARGS) - -helm-install-text-only: - helm upgrade --install $(HELM_RELEASE) $(HELM_CHART) -f $(HELM_TEXT_ONLY_VALUES) $(HELM_ARGS) - -helm-template: - helm template $(HELM_RELEASE) $(HELM_CHART) $(HELM_ARGS) - -helm-lint: - helm lint $(HELM_CHART) - -helm-uninstall: - helm uninstall $(HELM_RELEASE) $(HELM_ARGS) diff --git a/apps/openbao/.gitignore b/apps/openbao/.gitignore new file mode 100644 index 00000000..1a56d0d2 --- /dev/null +++ b/apps/openbao/.gitignore @@ -0,0 +1,3 @@ +!/env/ +/env/* +!/env/openbao.env diff --git a/apps/openbao/Makefile b/apps/openbao/Makefile new file mode 100644 index 00000000..1ba58979 --- /dev/null +++ b/apps/openbao/Makefile @@ -0,0 +1,12 @@ +OPENBAO_HOST_PORT ?= 8201 +OPENBAO_TLS_DIR ?= $(CURDIR)/local-server/tls + +.PHONY: start-openbao start-openbao-dev + +start-openbao: ## Start the persistent OpenBao server + OPENBAO_HOST_PORT="$(OPENBAO_HOST_PORT)" OPENBAO_TLS_DIR="$(OPENBAO_TLS_DIR)" \ + docker compose --project-name openbao-server --env-file env/openbao.env \ + -f docker/docker-compose.base.yml -f docker/docker-compose.server.yml up -d + +start-openbao-dev: ## Start the in-memory OpenBao server + docker compose -f docker/docker-compose.yml up -d diff --git a/apps/openbao/docker/docker-compose.base.yml b/apps/openbao/docker/docker-compose.base.yml new file mode 100644 index 00000000..bfc36c4a --- /dev/null +++ b/apps/openbao/docker/docker-compose.base.yml @@ -0,0 +1,3 @@ +services: + openbao: + image: ${OPENBAO_DOCKER_IMAGE:?Set OPENBAO_DOCKER_IMAGE} diff --git a/apps/openbao/docker/docker-compose.dev.yml b/apps/openbao/docker/docker-compose.dev.yml new file mode 100644 index 00000000..59688003 --- /dev/null +++ b/apps/openbao/docker/docker-compose.dev.yml @@ -0,0 +1,8 @@ +services: + openbao: + # The upstream image starts an in-memory dev server by default. + environment: + BAO_ADDR: ${OPENBAO_ADDR:?Set OPENBAO_ADDR} + BAO_DEV_ROOT_TOKEN_ID: + ports: + - "127.0.0.1:${OPENBAO_HOST_PORT:?Set OPENBAO_HOST_PORT}:8200" diff --git a/apps/openbao/docker/docker-compose.server.yml b/apps/openbao/docker/docker-compose.server.yml new file mode 100644 index 00000000..324cb785 --- /dev/null +++ b/apps/openbao/docker/docker-compose.server.yml @@ -0,0 +1,21 @@ +name: openbao-server + +services: + openbao: + command: [server] + environment: + BAO_API_ADDR: ${OPENBAO_API_ADDR:-https://127.0.0.1:${OPENBAO_HOST_PORT}} + ports: + - "127.0.0.1:${OPENBAO_HOST_PORT}:8200" + volumes: + - openbao-data:/openbao/file + - ./openbao.hcl:/openbao/config/openbao.hcl:ro + - type: bind + source: ${OPENBAO_TLS_DIR:?Set OPENBAO_TLS_DIR} + target: /openbao/tls + read_only: true + bind: + create_host_path: false + +volumes: + openbao-data: diff --git a/apps/openbao/docker/docker-compose.yml b/apps/openbao/docker/docker-compose.yml new file mode 100644 index 00000000..f54551f7 --- /dev/null +++ b/apps/openbao/docker/docker-compose.yml @@ -0,0 +1,7 @@ +name: openbao + +include: + - path: + - docker-compose.base.yml + - docker-compose.dev.yml + env_file: ../env/openbao.env diff --git a/apps/openbao/docker/openbao.hcl b/apps/openbao/docker/openbao.hcl new file mode 100644 index 00000000..44b6fac1 --- /dev/null +++ b/apps/openbao/docker/openbao.hcl @@ -0,0 +1,12 @@ +ui = true +cluster_addr = "https://openbao:8201" + +storage "raft" { + path = "/openbao/file" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/openbao/tls/tls.crt" + tls_key_file = "/openbao/tls/tls.key" +} diff --git a/apps/openbao/env/openbao.env b/apps/openbao/env/openbao.env new file mode 100644 index 00000000..d98b1de1 --- /dev/null +++ b/apps/openbao/env/openbao.env @@ -0,0 +1,7 @@ +OPENBAO_DOCKER_IMAGE=openbao/openbao:2.7.3 +OPENBAO_HOST_PORT=8200 + +# Address for the bao CLI inside the container. +OPENBAO_ADDR=http://127.0.0.1:8200 + +# Export BAO_DEV_ROOT_TOKEN_ID in your shell if a demo script needs a known token. diff --git a/apps/opensearch-dashboards/.gitignore b/apps/opensearch-dashboards/.gitignore new file mode 100644 index 00000000..a05566ac --- /dev/null +++ b/apps/opensearch-dashboards/.gitignore @@ -0,0 +1,3 @@ +!/env/ +/env/* +!/env/opensearch-dashboards.env diff --git a/apps/opensearch-dashboards/config/opensearch.yml b/apps/opensearch-dashboards/config/opensearch.yml new file mode 100644 index 00000000..a24ca360 --- /dev/null +++ b/apps/opensearch-dashboards/config/opensearch.yml @@ -0,0 +1,151 @@ +# OpenSearch Dashboards is served by a back end server. This setting specifies the port to use. +server.port: 5601 + +# Specifies the address to which the OpenSearch Dashboards server will bind. IP addresses and host names are both valid values. +# The default is 'localhost', which usually means remote machines will not be able to connect. +# To allow connections from remote users, set this parameter to a non-loopback address. +server.host: "0.0.0.0" + +# Enables you to specify a path to mount OpenSearch Dashboards at if you are running behind a proxy. +# Use the `server.rewriteBasePath` setting to tell OpenSearch Dashboards if it should remove the basePath +# from requests it receives, and to prevent a deprecation warning at startup. +# This setting cannot end in a slash. +#server.basePath: "" + +# Specifies whether OpenSearch Dashboards should rewrite requests that are prefixed with +# `server.basePath` or require that they are rewritten by your reverse proxy. +#server.rewriteBasePath: false + +# The maximum payload size in bytes for incoming server requests. +#server.maxPayloadBytes: 1048576 + +# The OpenSearch Dashboards server's name. This is used for display purposes. +server.name: ${OPENSEARCH_DASHBOARDS_SERVER_NAME} + +# The URLs of the OpenSearch instances to use for all your queries. +opensearch.hosts: ${OPENSEARCH_HOSTS} + +opensearch_security.multitenancy.enabled: true +opensearch_security.multitenancy.tenants.enable_global: true +opensearch_security.multitenancy.tenants.enable_private: true +opensearch_security.multitenancy.tenants.preferred: ["Global"] +opensearch_security.readonly_mode.roles: ["kibana_read_only"] +opensearch_security.multitenancy.enable_filter: true +opensearch_security.cookie.secure: true + +# OpenSearch Dashboards uses an index in OpenSearch to store saved searches, visualizations and +# dashboards. OpenSearch Dashboards creates a new index if the index doesn't already exist. + +# We changed this from .opensearch_dashboards to .kibana because of a permission bug in OpenSearch Dashboards 2.19.x and 3.0.0 +# report: https://github.com/opensearch-project/security/issues/5360 +opensearchDashboards.index: ".opensearch_dashboards" + +# The default application to load. +#opensearchDashboards.defaultAppId: "home" + +# Setting for an optimized healthcheck that only uses the local OpenSearch node to do Dashboards healthcheck. +# This settings should be used for large clusters or for clusters with ingest heavy nodes. +# It allows Dashboards to only healthcheck using the local OpenSearch node rather than fan out requests across all nodes. +# +# It requires the user to create an OpenSearch node attribute with the same name as the value used in the setting +# This node attribute should assign all nodes of the same cluster an integer value that increments with each new cluster that is spun up +# e.g. in opensearch.yml file you would set the value to a setting using node.attr.cluster_id: +# Should only be enabled if there is a corresponding node attribute created in your OpenSearch config that matches the value here +#opensearch.optimizedHealthcheckId: "cluster_id" + +# If your OpenSearch is protected with basic authentication, these settings provide +# the username and password that the OpenSearch Dashboards server uses to perform maintenance on the OpenSearch Dashboards +# index at startup. Your OpenSearch Dashboards users still need to authenticate with OpenSearch, which +# is proxied through the OpenSearch Dashboards server. +opensearch.username: ${KIBANA_USER} +opensearch.password: ${KIBANA_PASSWORD} + +# Enables SSL and paths to the PEM-format SSL certificate and SSL key files, respectively. +# These settings enable SSL for outgoing requests from the OpenSearch Dashboards server to the browser. +server.ssl.enabled: true +server.ssl.certificate: "/certificates/elastic/opensearch/es_kibana_client.pem" +server.ssl.key: "/certificates/elastic/opensearch/es_kibana_client.key" + +# Outgoing requests use KIBANA_USER/KIBANA_PASSWORD and verify the server CA. +# Do not send an admin client certificate: that would bypass the service account. + +# Optional setting that enables you to specify a path to the PEM file for the certificate +# authority for your OpenSearch instance. +opensearch.ssl.certificateAuthorities: ["/certificates/elastic/opensearch/elastic-stack-ca.crt.pem"] + +# To disregard the validity of SSL certificates, change this setting's value to 'none'. +opensearch.ssl.verificationMode: full + +# Time in milliseconds to wait for OpenSearch to respond to pings. Defaults to the value of +# the opensearch.requestTimeout setting. +opensearch.pingTimeout: 10000 + +# Time in milliseconds to wait for responses from the back end or OpenSearch. This value +# must be a positive integer. +opensearch.requestTimeout: 420000 + +# List of OpenSearch Dashboards client-side headers to send to OpenSearch. To send *no* client-side +# headers, set this value to [] (an empty list). +opensearch.requestHeadersAllowlist: ["securitytenant", "Authorization"] + +# Header names and values that are sent to OpenSearch. Any custom headers cannot be overwritten +# by client-side headers, regardless of the opensearch.requestHeadersAllowlist configuration. +# opensearch.customHeaders: {} + +# Time in milliseconds for OpenSearch to wait for responses from shards. Set to 0 to disable. +# opensearch.shardTimeout: 30000 + +# Logs queries sent to OpenSearch. Requires logging.verbose set to true. +# opensearch.logQueries: false + +# Specifies the path where OpenSearch Dashboards creates the process ID file. +# pid.file: /var/run/opensearchDashboards.pid + +# Enables you to specify a file where OpenSearch Dashboards stores log output. +# logging.dest: stdout + +# Set the value of this setting to true to suppress all logging output. +# logging.silent: false + +# Set the value of this setting to true to suppress all logging output other than error messages. +# logging.quiet: false + +# Set the value of this setting to true to log all events, including system usage information +# and all requests. +# logging.verbose: false + +# Set the interval in milliseconds to sample system and process performance +# metrics. Minimum is 100ms. Defaults to 5000. +# ops.interval: 5000 + +# Specifies locale to be used for all localizable strings, dates and number formats. +# Supported languages are the following: English - en , by default , Chinese - zh-CN . +# i18n.locale: "en" + +# Set the allowlist to check input graphite Url. Allowlist is the default check list. +#vis_type_timeline.graphiteAllowedUrls: ['https://www.hostedgraphite.com/UID/ACCESS_KEY/graphite'] + +# Set the value of this setting to true to capture region blocked warnings and errors +# for your map rendering services. +# map.showRegionBlockedWarning: false + +# Enable ML Commons model monitoring and management. Model registration and +# deployment are performed through the REST API or the Dashboards Dev Tools UI. +ml_commons_dashboards.enabled: true +assistant.chat.enabled: true +assistant.incontextInsight.enabled: true +assistant.next.enabled: true +assistant.text2viz.enabled: true +observability.query_assist.enabled: true + +savedObjects.permission.enabled: true + +# Set the value to true to enable multiple data source feature +data_source.enabled: false +# Set the value to true to enable workspace feature +workspace.enabled: true +# Set the value to true to enable explore feature +explore.enabled: true + +opensearchDashboards.dashboardAdmin.users: ["admin"] +opensearchDashboards.dashboardAdmin.groups: ["admin","all_access"] diff --git a/apps/opensearch-dashboards/docker/docker-compose.base.yml b/apps/opensearch-dashboards/docker/docker-compose.base.yml new file mode 100644 index 00000000..3118484a --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.base.yml @@ -0,0 +1,34 @@ +services: + opensearch-dashboards: + image: ${OPENSEARCH_DASHBOARDS_DOCKER_IMAGE:?Load ../env/opensearch-dashboards.env} + restart: unless-stopped + mem_limit: ${OPENSEARCH_DASHBOARDS_DOCKER_RAM:-1g} + environment: + OPENSEARCH_DASHBOARDS_SERVER_NAME: ${OPENSEARCH_DASHBOARDS_SERVER_NAME:-cogstack-opensearch-dashboards} + OPENSEARCH_HOSTS: '${OPENSEARCH_HOSTS:-["https://opensearch-shared:9200"]}' + OPENSEARCHDASHBOARDS_INDEX: ${OPENSEARCHDASHBOARDS_INDEX:-.kibana} + KIBANA_USER: ${KIBANA_USER:-kibanaserver} + ports: + - '127.0.0.1:${OPENSEARCH_DASHBOARDS_SERVER_OUTPUT_PORT:-5601}:5601' + volumes: + - &bind + type: bind + source: ../config/opensearch.yml + target: /usr/share/opensearch-dashboards/config/opensearch_dashboards.yml + read_only: true + bind: + create_host_path: false + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/es_kibana_client.pem + target: /certificates/elastic/opensearch/es_kibana_client.pem + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/es_kibana_client.key + target: /certificates/elastic/opensearch/es_kibana_client.key + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem + target: /certificates/elastic/opensearch/elastic-stack-ca.crt.pem + networks: [cognet] + +networks: + cognet: + external: true diff --git a/apps/opensearch-dashboards/docker/docker-compose.dev.yml b/apps/opensearch-dashboards/docker/docker-compose.dev.yml new file mode 100644 index 00000000..90ccfb30 --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.dev.yml @@ -0,0 +1,10 @@ +name: opensearch-dashboards-dev + +services: + opensearch-dashboards: + environment: + KIBANA_PASSWORD: ${KIBANA_PASSWORD:-kibanaserver} + +networks: + cognet: + name: opensearch-dev-net diff --git a/apps/opensearch-dashboards/docker/docker-compose.prod.yml b/apps/opensearch-dashboards/docker/docker-compose.prod.yml new file mode 100644 index 00000000..07c83e34 --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.prod.yml @@ -0,0 +1,10 @@ +name: opensearch-dashboards + +services: + opensearch-dashboards: + environment: + KIBANA_PASSWORD: ${KIBANA_PASSWORD:?Set the Dashboards service account password} + +networks: + cognet: + name: cogstack-net diff --git a/apps/opensearch-dashboards/docker/docker-compose.yml b/apps/opensearch-dashboards/docker/docker-compose.yml new file mode 100644 index 00000000..4af24138 --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.yml @@ -0,0 +1,5 @@ +name: opensearch-dashboards + +include: + - path: [docker-compose.base.yml, docker-compose.prod.yml] + env_file: ../env/opensearch-dashboards.env diff --git a/apps/opensearch-dashboards/env/opensearch-dashboards.env b/apps/opensearch-dashboards/env/opensearch-dashboards.env new file mode 100644 index 00000000..03d23fee --- /dev/null +++ b/apps/opensearch-dashboards/env/opensearch-dashboards.env @@ -0,0 +1,20 @@ +########################################################################## OpenSearch Dashboards Env vars ########################################################################### + +OPENSEARCH_DASHBOARDS_HOST="https://kibana:5601" + +# possible values: +# - opensearch : opensearchproject/opensearch-dashboards:3.9.0 +# the custom cogstack image is always based on the last image of ES native + +OPENSEARCH_DASHBOARDS_DOCKER_IMAGE=opensearchproject/opensearch-dashboards:3.9.0@sha256:256d4cea5928868ac09bca642a0ac8285a2b7e4b7fdd45c4ec06e75a5cf3184c + +OPENSEARCH_DASHBOARDS_SERVER_NAME="cogstack-opensearch-dashboards" +OPENSEARCH_DASHBOARDS_PUBLIC_BASE_URL="https://elasticsearch-1:5601" + +OPENSEARCH_DASHBOARDS_SERVER_HOST="0.0.0.0" +OPENSEARCH_DASHBOARDS_SERVER_OUTPUT_PORT=5601 + +OPENSEARCH_DASHBOARDS_DOCKER_SHM_SIZE=512m +OPENSEARCH_DASHBOARDS_DOCKER_CPU_MIN=1 +OPENSEARCH_DASHBOARDS_DOCKER_CPU_MAX=1 +OPENSEARCH_DASHBOARDS_DOCKER_RAM=1g diff --git a/apps/opensearch/.gitignore b/apps/opensearch/.gitignore new file mode 100644 index 00000000..641f226a --- /dev/null +++ b/apps/opensearch/.gitignore @@ -0,0 +1,3 @@ +!/env/ +/env/* +!/env/opensearch.env diff --git a/apps/opensearch/README.md b/apps/opensearch/README.md new file mode 100644 index 00000000..9bd40f4c --- /dev/null +++ b/apps/opensearch/README.md @@ -0,0 +1,47 @@ +# OpenSearch and Dashboards in Docker + +From the repository root, run the commands for any missing TLS files. + +```bash +make -C deployment certs-root +make -C deployment certs-opensearch +OPENSEARCH_DASHBOARDS_DNS_NAMES=localhost \ + ./deployment/scripts/security/create_opensearch_client_admin_certs.sh --dashboards-only +``` + +Set an absolute `SECURITY_DIR` to use a different certificate bundle. Each +container runs as UID 1000 and needs read access to its own private key. The +Dashboards certificate must cover the browser hostname. + +Export `KIBANA_PASSWORD` from your deployment secrets for the `kibanaserver` +account. Set `OS_NIFI_PASSWORD`, `OS_PIPELINE_PASSWORD`, or `OS_ANALYST_PASSWORD` +to create `nifi`, `cogstack_pipeline`, or `cogstack_user`, respectively. +Run from the repository root on a fresh deployment. + +```bash +docker compose -f apps/opensearch/docker/docker-compose.yml up -d +bash apps/opensearch/security/bootstrap.sh \ + docker compose -f apps/opensearch/docker/docker-compose.yml exec -T opensearch +docker compose -f apps/opensearch-dashboards/docker/docker-compose.yml up -d +``` + +The bootstrap hashes the supplied passwords and applies the shared policy in +[`security/`](security/). Apply changes to existing clusters through the +[Security REST API](https://docs.opensearch.org/latest/security/api/roles/). +Dashboards listens at `https://localhost:5601`. + +Compose uses `.kibana` for saved objects to match the bundled Security role. +Set `OPENSEARCHDASHBOARDS_INDEX` when your Security configuration uses another index. + +For dev, run this from each app's `docker/` directory, starting with OpenSearch. +Use `opensearch-dashboards.env` for Dashboards. + +```bash +docker compose --env-file ../env/opensearch.env \ + -f docker-compose.base.yml -f docker-compose.dev.yml up -d +``` + +Dev uses the bundled Security users and a separate network. The corresponding +`docker-compose.prod.yml` overlay joins an existing `cogstack-net`. OpenSearch +stores indexes and Security state in `opensearch_data` or `opensearch-dev_data`, +which survive `docker compose down`. diff --git a/apps/opensearch/config/opensearch.yml b/apps/opensearch/config/opensearch.yml new file mode 100644 index 00000000..1966adbd --- /dev/null +++ b/apps/opensearch/config/opensearch.yml @@ -0,0 +1,222 @@ +network.host: '${OPENSEARCH_NETWORK_HOST:0.0.0.0}' +network.publish_host: '${OPENSEARCH_NETWORK_PUBLISH_HOST:}' +logger.level: '${OPENSEARCH_LOG_LEVEL:INFO}' + +###### CLUSTER CONFIGURATION ###### + +bootstrap.system_call_filter: '${OPENSEARCH_SYSTEM_CALL_FILTER:true}' + +# Docker supplies these settings through its environment. Helm supplies the +# Kubernetes discovery settings through the StatefulSet. +discovery.seed_hosts: '${OPENSEARCH_SEED_HOSTS:}' +cluster.initial_cluster_manager_nodes: '${OPENSEARCH_INITIAL_CLUSTER_MANAGER_NODES:}' +discovery.type: zen + +plugins.security.ssl.transport.pemcert_filepath: tls/node.crt +plugins.security.ssl.transport.pemkey_filepath: tls/node.key +plugins.security.ssl.transport.pemtrustedcas_filepath: tls/ca.crt +transport.ssl.enforce_hostname_verification: false +plugins.security.ssl.http.enabled: true +plugins.security.ssl.transport.enabled: true +plugins.security.ssl.http.pemcert_filepath: tls/node.crt +plugins.security.ssl.http.pemkey_filepath: tls/node.key +plugins.security.ssl.http.pemtrustedcas_filepath: tls/ca.crt +plugins.security.allow_unsafe_democertificates: false +plugins.security.allow_default_init_securityindex: '${OPENSEARCH_ALLOW_DEFAULT_INIT_SECURITYINDEX:false}' + +plugins.security.authcz.admin_dn: + - "CN=admin,OU=cogstack,O=cogstack,L=UK,ST=London,C=UK" + +plugins.security.nodes_dn: + - "CN=opensearch-shared,OU=cogstack,O=cogstack,L=UK,ST=London,C=UK" + +plugins.security.enable_snapshot_restore_privilege: true +plugins.security.check_snapshot_restore_write_privileges: true +cluster.routing.allocation.disk.threshold_enabled: true + +plugins.security.ssl.http.clientauth_mode : OPTIONAL + +plugins.security.roles_mapping_resolution: MAPPING_ONLY + +# Supply deployment-specific values on every node when using these features. +plugins.security.compliance.salt: '${OPENSEARCH_COMPLIANCE_SALT:}' +plugins.query.datasources.encryption.masterkey: '${OPENSEARCH_DATASOURCE_MASTER_KEY:}' + +############## REST Management API configuration settings ############## +# Enable or disable role based access to the REST management API +# Default is that no role is allowed to access the REST management API. +plugins.security.restapi.roles_enabled: ["all_access", "security_rest_api_access"] + +# Disable particular endpoints and their HTTP methods for roles. +# By default all endpoints/methods are allowed. +#plugins.security.restapi.endpoints_disabled..: +# Example: +#plugins.security.restapi.endpoints_disabled.all_access.ACTIONGROUPS: ["PUT","POST","DELETE"] +#plugins.security.restapi.endpoints_disabled.xyz_role.LICENSE: ["DELETE"] + +# The following endpoints exist: +# ACTIONGROUPS +# CACHE +# CONFIG +# ROLES +# ROLESMAPPING +# INTERNALUSERS +# SYSTEMINFO +# PERMISSIONSINFO + +############## Auditlog configuration settings ############## + +# Destination of the auditlog events +plugins.security.audit.type: internal_opensearch +plugins.security.audit.config.http_endpoints: '${OPENSEARCH_HOSTS:}' +plugins.security.audit.config.enable_ssl_client_auth: true + +#plugins.security.audit.enable_rest: false +#plugins.security.audit.enable_transport: false +#plugins.security.audit.config.disabled_rest_categories: NONE +#plugins.security.audit.config.disabled_transport_categories: NONE +#plugins.security.audit.config.index: auditlog6 # make sure you secure this index properly +#plugins.security.audit.config.index: "'auditlog6-'YYYY.MM.dd" #rotates index daily - make sure you secure this index properly +#plugins.security.audit.config.type: auditlog +#plugins.security.audit.config.username: auditloguser +#plugins.security.audit.config.password: auditlogpassword +#plugins.security.audit.config.enable_ssl: false +#plugins.security.audit.config.verify_hostnames: false +#plugins.security.audit.config.cert_alias: mycert +#plugins.security.audit.config.pemkey_filepath: key.pem +#plugins.security.audit.config.pemkey_content: <...pem base 64 content> +#plugins.security.audit.config.pemkey_password: secret +#plugins.security.audit.config.pemcert_filepath: cert.pem +#plugins.security.audit.config.pemcert_content: <...pem base 64 content> +#plugins.security.audit.config.pemtrustedcas_filepath: ca.pem +#plugins.security.audit.config.pemtrustedcas_content: <...pem base 64 content> + +# webhook settings +#plugins.security.audit.config.webhook.url: "http://mywebhook/endpoint" +# One of URL_PARAMETER_GET,URL_PARAMETER_POST,TEXT,JSON,SLACK +#plugins.security.audit.config.webhook.format: JSON +#plugins.security.audit.config.webhook.ssl.verify: false +#plugins.security.audit.config.webhook.ssl.pemtrustedcas_filepath: ca.pem +#plugins.security.audit.config.webhook.ssl.pemtrustedcas_content: <...pem base 64 content> + +# log4j settings +#plugins.security.audit.config.log4j.logger_name: auditlogger +#plugins.security.audit.config.log4j.level: INFO + +############## Kerberos configuration settings ############## +# If Kerberos authentication should be used you have to configure: + +# The Path to the krb5.conf file +# Can be absolute or relative to the OpenSearch config directory +#plugins.security.kerberos.krb5_filepath: '/etc/krb5.conf' + +# The Path to the keytab where the acceptor_principal credentials are stored. +# Must be relative to the OpenSearch config directory +#plugins.security.kerberos.acceptor_keytab_filepath: 'eskeytab.tab' + +# Acceptor (Server) Principal name, must be present in acceptor_keytab_path file +#plugins.security.kerberos.acceptor_principal: 'HTTP/localhost' + + +############## Expert settings ############## +# WARNING: Expert settings, do only use if you know what you are doing +# If you set wrong values here this this could be a security risk +# or make OpenSearch Security stop working + +# Name of the index where .opendistro_security stores its configuration. + +#plugins.security.config_index_name: .opendistro_security + +# This defines the OID of server node certificates +#plugins.security.cert.oid: '1.2.3.4.5.5' + +# This specifies the implementation of org.opensearch.security.transport.InterClusterRequestEvaluator +# that is used to determine inter-cluster request. +# Instances of org.opensearch.security.transport.InterClusterRequestEvaluator must implement a single argument +# constructor that takes an org.opensearch.common.settings.Settings +#plugins.security.cert.intercluster_request_evaluator_class: org.opensearch.security.transport.DefaultInterClusterRequestEvaluator + +# By default, normal users can restore snapshots if they have the priviliges 'cluster:admin/snapshot/restore', +# 'indices:admin/create', and 'indices:data/write/index' for the indices to be restored. +# To disable snapshot restore for normal users set 'plugins.security.enable_snapshot_restore_privilege: false'. +# This makes it so that only snapshot restore requests signed by an admin TLS certificate are accepted. +# A snapshot can only be restored when it does not contain global state and does not restore the '.opendistro_security' index +# If 'plugins.security.check_snapshot_restore_write_privileges: false' is set then the additional indices checks are omitted. +#plugins.security.enable_snapshot_restore_privilege: true +#plugins.security.check_snapshot_restore_write_privileges: true + +# Authentication cache timeout in minutes (A value of 0 disables caching, default is 60) +#plugins.security.cache.ttl_minutes: 60 + +# Disable OpenSearch Security +# WARNING: This can expose your configuration (including passwords) to the public. +#plugins.security.disabled: false + +# Protected indices are even more secure than normal indices. These indices require a role to access like any other index, but they require an additional role +# to be visible, listed in the plugins.security.protected_indices.roles setting. +# Enable protected indices +# plugins.security.protected_indices.enabled: true +# Specify a list of roles a user must be member of to touch any protected index. +# plugins.security.protected_indices.roles: ['all_access'] + +# Bundled plugins register their system indices with OpenSearch. Protect those +# registered indices without the deprecated plugins.security.system_indices.indices list. +# Allow explicit system:admin/system_index role permissions as well as super-admin access. +plugins.security.system_indices.enabled: true +plugins.security.system_indices.permission.enabled: true + +# ================= ML Commons ================= + +plugins.ml_commons.local_model.enabled: true +plugins.ml_commons.remote_inference.enabled: true +plugins.ml_commons.only_run_on_ml_node: false +plugins.ml_commons.allow_registering_model_via_url: true +plugins.ml_commons.allow_registering_model_via_local_file: true +# Permit HTTPS model repositories and only the dedicated read-only local model +# directory; do not allow arbitrary HTTP, FTP, or file-system paths. +plugins.ml_commons.trusted_url_regex: '^https://.*$|^file:///usr/share/opensearch/models/[^?#]+\.zip$' +# Permit ML Commons connectors to call only the Ollama service on the private +# CogStack Docker network. Docker resolves this stable service name to a +# private container IP, so both the general and private endpoint allowlists +# are required by OpenSearch 3.7 and later. +plugins.ml_commons.connector.private_ip_enabled: true +plugins.ml_commons.trusted_connector_endpoints_regex: + - '^http://ollama:11434/.*$' + - '^http://ollama-openai-proxy:11435/.*$' +plugins.ml_commons.trusted_connector_private_endpoints_regex: + - '^http://ollama:11434/.*$' + - '^http://ollama-openai-proxy:11435/.*$' +plugins.ml_commons.model_access_control_enabled: true +plugins.ml_commons.connector_access_control_enabled: true +plugins.ml_commons.safe_delete_model: true +plugins.ml_commons.agent_framework_enabled: true +plugins.ml_commons.rag_pipeline_feature_enabled: true +# Upper bound for asynchronous ML Commons tasks. Remote connector connection +# and response timeouts are configured per connector by opensearch-ai-init.sh. +plugins.ml_commons.ml_task_timeout_in_seconds: 600 + +# This cluster has no dedicated ML nodes, so allow both local and remote models +# to execute on data nodes. +plugins.ml_commons.task_dispatcher.eligible_node_role.local_model: + - data +plugins.ml_commons.task_dispatcher.eligible_node_role.remote_model: + - data + + +# Enable SQL-like queries, allows you to join across indices etc. +plugins.sql.enabled: true +plugins.ppl.enabled: true + +# Calcite (SQL v3 engine) +plugins.calcite.enabled: true +# WARNING: exists only in OpenSearch > 3.4, please DISABLE if you are not on this version as this setting doesn't exist. +plugins.calcite.all_join_types.allowed: true + +# coordinator-level kill switch for searches +search.cancel_after_time_interval: 5m + +# shard-level default timeout (can be overridden per request via "timeout") +search.default_search_timeout: 5m + +# relevant if SQL is paging via PIT +search.default_keep_alive: 10m diff --git a/apps/opensearch/docker/docker-compose.base.yml b/apps/opensearch/docker/docker-compose.base.yml new file mode 100644 index 00000000..515c2dc8 --- /dev/null +++ b/apps/opensearch/docker/docker-compose.base.yml @@ -0,0 +1,40 @@ +services: + opensearch: + image: ${OPENSEARCH_DOCKER_IMAGE:?Load ../env/opensearch.env} + restart: unless-stopped + mem_limit: ${OPENSEARCH_DOCKER_RAM:-2g} + shm_size: ${OPENSEARCH_DOCKER_SHM_SIZE:-512m} + environment: + discovery.type: single-node + DISABLE_INSTALL_DEMO_CONFIG: 'true' + OPENSEARCH_JAVA_OPTS: ${OPENSEARCH_JAVA_OPTS:--Xms512m -Xmx512m} + ports: + - '127.0.0.1:${OPENSEARCH_NODE_1_OUTPUT_PORT:-9200}:9200' + volumes: + - data:/usr/share/opensearch/data + - &bind + type: bind + source: ../config/opensearch.yml + target: /usr/share/opensearch/config/opensearch.yml + read_only: true + bind: + create_host_path: false + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/opensearch-shared.crt + target: /usr/share/opensearch/config/tls/node.crt + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/opensearch-shared.key + target: /usr/share/opensearch/config/tls/node.key + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem + target: /usr/share/opensearch/config/tls/ca.crt + networks: + cognet: + aliases: [opensearch-shared] + +volumes: + data: + +networks: + cognet: + name: cogstack-net diff --git a/apps/opensearch/docker/docker-compose.dev.yml b/apps/opensearch/docker/docker-compose.dev.yml new file mode 100644 index 00000000..412878fd --- /dev/null +++ b/apps/opensearch/docker/docker-compose.dev.yml @@ -0,0 +1,10 @@ +name: opensearch-dev + +services: + opensearch: + environment: + OPENSEARCH_ALLOW_DEFAULT_INIT_SECURITYINDEX: 'true' + +networks: + cognet: + name: opensearch-dev-net diff --git a/apps/opensearch/docker/docker-compose.prod.yml b/apps/opensearch/docker/docker-compose.prod.yml new file mode 100644 index 00000000..ac008b13 --- /dev/null +++ b/apps/opensearch/docker/docker-compose.prod.yml @@ -0,0 +1,5 @@ +name: opensearch + +networks: + cognet: + external: true diff --git a/apps/opensearch/docker/docker-compose.yml b/apps/opensearch/docker/docker-compose.yml new file mode 100644 index 00000000..30218390 --- /dev/null +++ b/apps/opensearch/docker/docker-compose.yml @@ -0,0 +1,5 @@ +name: opensearch + +include: + - path: docker-compose.base.yml + env_file: ../env/opensearch.env diff --git a/apps/opensearch/env/opensearch.env b/apps/opensearch/env/opensearch.env new file mode 100644 index 00000000..a348afe0 --- /dev/null +++ b/apps/opensearch/env/opensearch.env @@ -0,0 +1,206 @@ +# Based on CogStack-NiFi deploy/elasticsearch.env. +# Supply credentials and encryption keys through your private deployment settings. +####################################################################### OpenSearch Env vars ####################################################################### + +# possible values : +# - elasticsearch : docker.elastic.co/elasticsearch/elasticsearch:9.5.2 +# - elasticsearch (custom cogstack image) : cogstacksystems/cogstack-elasticsearch:latest +# - opensearch : opensearchproject/opensearch:3.9.0 +# the custom cogstack image is always based on the last image of ES native + +OPENSEARCH_DOCKER_IMAGE=opensearchproject/opensearch:3.9.0@sha256:3b55f6b6249cfdb92b52ee59adc8a266203ba9ef9f5d82544fad6f1af2f3609e + +# Each K3s replica runs on a separate Kubernetes node. +OPENSEARCH_K3S_REPLICA_COUNT=1 +# Comma-separated Kubernetes node names to exclude. +OPENSEARCH_K3S_BLACKLIST= + +OPENSEARCH_LOG_LEVEL=INFO + +OPENSEARCH_SEED_HOSTS=localhost,elasticsearch-2,elasticsearch-1 +OPENSEARCH_INITIAL_CLUSTER_MANAGER_NODES=es01 + + +OPENSEARCH_NETWORK_HOST="0.0.0.0" +OPENSEARCH_NETWORK_PUBLISH_HOST="0.0.0.0" + +OPENSEARCH_NODE_1_OUTPUT_PORT=9200 +OPENSEARCH_NODE_2_OUTPUT_PORT=9201 +OPENSEARCH_NODE_3_OUTPUT_PORT=9202 + +# cluster communication port +OPENSEARCH_NODE_1_COMM_OUTPUT_PORT=9300 +OPENSEARCH_NODE_2_COMM_OUTPUT_PORT=9301 +OPENSEARCH_NODE_3_COMM_OUTPUT_PORT=9302 + +# cluster analyzer port +OPENSEARCH_NODE_1_ANALYZER_OUTPUT_PORT=9600 +OPENSEARCH_NODE_2_ANALYZER_OUTPUT_PORT=9601 +OPENSEARCH_NODE_3_ANALYZER_OUTPUT_PORT=9602 + +# do not change these values unless you want to create new volumes manually in services.yml +# or you have a special case where you need to switch volumes +OPENSEARCH_NODE_1_DATA_VOL_NAME=elasticsearch-vol-1 +OPENSEARCH_NODE_2_DATA_VOL_NAME=elasticsearch-vol-2 +OPENSEARCH_NODE_3_DATA_VOL_NAME=elasticsearch-vol-3 + +# log volumes shared between filebeat and elasticsearch +OPENSEARCH_NODE_1_LOG_VOL_NAME=elasticsearch-vol-log-1 +OPENSEARCH_NODE_2_LOG_VOL_NAME=elasticsearch-vol-log-2 +OPENSEARCH_NODE_3_LOG_VOL_NAME=elasticsearch-vol-log-3 + +# Performance Analyzer volumes (OpenSearch) +OPENSEARCH_NODE_1_PA_VOL_NAME=elasticsearch-vol-performance-analyzer-1 +OPENSEARCH_NODE_2_PA_VOL_NAME=elasticsearch-vol-performance-analyzer-2 +OPENSEARCH_NODE_3_PA_VOL_NAME=elasticsearch-vol-performance-analyzer-3 + +# this is for native ES +# possible values: +# - trial # 30 day trial +# - basic + +OPENSEARCH_LICENSE_TYPE="trial" + +OPENSEARCH_SSL_ENABLED=true +OPENSEARCH_ALLOW_DEFAULT_INIT_SECURITYINDEX=true + +OPENSEARCH_CLUSTER_NAME="elasticsearch-cogstack-cluster" + +# Match the node names to the hostnames passed to the certificate generator. +OPENSEARCH_NODE_1_NAME=es01 +OPENSEARCH_NODE_2_NAME=es02 +OPENSEARCH_NODE_3_NAME=es03 + +# corresponds to "node.attr.rack=" +OPENSEARCH_NODE_ATTR="elastic" + +OPENSEARCH_CORS_ENABLED="true" + +OPENSEARCH_HTTP_PORT=9200 + +# this setting represents the number of CPUS allocated to each cluster. +OPENSEARCH_NODE_PROCESSORS="2" + +OPENSEARCH_BACKUPS_PATH_REPO=["/mnt/es_data_backups","/mnt/es_config_backups"] + +# used for full snapshot backup +# this is the path on the physical drive, not inside the container +OPENSEARCH_BACKUP_PARTITION_FULL=/data/es_snapshot_backups/full_backup + +# this is the path on the physical drive, not inside the container +# used for snapshot backups of configs +OPENSEARCH_BACKUP_PARTITION_CONFIG=/data/es_snapshot_backups/config_backup + +# Security certificates +OPENSEARCH_SECURITY_DIR=../security/certificates/elastic/ + +# MEMORY CONFIG +OPENSEARCH_JAVA_OPTS="-Xms512m -Xmx512m -Des.failure_store_feature_flag_enabled=true --enable-native-access=ALL-UNNAMED" +OS_JAVA_OPTS=$OPENSEARCH_JAVA_OPTS + +OPENSEARCH_DOCKER_CPU_MIN=1 +OPENSEARCH_DOCKER_CPU_MAX=1 +# Leave room beyond the Java heap for direct buffers, native code, and plugins. +# OpenSearch 3.9 exceeds a 1 GiB container limit during plugin initialization. +OPENSEARCH_DOCKER_RAM=2g + +OPENSEARCH_DOCKER_SHM_SIZE=512m + +OPENSEARCH_DOCKER_LOG_SIZE_PER_FILE="1000m" +OPENSEARCH_DOCKER_LOG_NUM_FILES=10 + +# OpenSearch ML Commons bootstrap settings. Connector timeouts are seconds; +# the Dashboards opensearch.requestTimeout setting is milliseconds. +OPENSEARCH_AI_OPENSEARCH_CONTAINER=elasticsearch-1 +# Local development credentials; update these when the OpenSearch admin login +# is rotated or override them when invoking the bootstrap script. +OPENSEARCH_AI_OPENSEARCH_USER=admin +# OPENSEARCH_AI_OPENSEARCH_PASSWORD= +OPENSEARCH_AI_CONNECTION_TIMEOUT_SECONDS=720 +OPENSEARCH_AI_READ_TIMEOUT_SECONDS=1440 +OPENSEARCH_AI_DEPLOY_TIMEOUT_SECONDS=360 +OPENSEARCH_AI_MAX_TOKENS=16384 +OPENSEARCH_AI_UTILITY_MAX_TOKENS=16384 +OPENSEARCH_AI_REASONING_EFFORT=none +# Leave room for discovery, one bounded retry, and result summarization. +OPENSEARCH_AI_CHAT_MAX_ITERATIONS=8 +# Hard cap on rows returned by the chat assistant's executing PPL tool. +OPENSEARCH_AI_PPL_RESULT_LIMIT=100 + +# Stable resource names let scripts/opensearch-ai-init.sh safely find and +# update resources instead of creating duplicates on every run. +OPENSEARCH_AI_CHAT_CONNECTOR_NAME="Ollama Qwen Agent Connector" +OPENSEARCH_AI_CHAT_MODEL_NAME="Qwen 3.5 Ollama Agent Model" +OPENSEARCH_AI_CHAT_AGENT_NAME="Qwen 3.5 Conversational Agent v2" +OPENSEARCH_AI_ROOT_AGENT_NAME="Qwen Dashboards Root Agent" +OPENSEARCH_AI_PPL_CONNECTOR_NAME="Ollama Qwen PPL Connector" +OPENSEARCH_AI_PPL_MODEL_NAME="Qwen 3.5 Ollama PPL Model" +OPENSEARCH_AI_PPL_AGENT_NAME="Qwen PPL Query Assist Agent" +OPENSEARCH_AI_TIME_RANGE_CONNECTOR_NAME="Ollama Qwen Time Range Connector" +OPENSEARCH_AI_TIME_RANGE_MODEL_NAME="Qwen 3.5 Ollama Time Range Model" +OPENSEARCH_AI_TIME_RANGE_AGENT_NAME="Qwen Query Time Range Parser Agent" +OPENSEARCH_AI_UTILITY_CONNECTOR_NAME="Ollama Qwen Dashboards Utility Connector" +OPENSEARCH_AI_UTILITY_MODEL_NAME="Qwen 3.5 Dashboards Utility Model" +OPENSEARCH_AI_AD_CONNECTOR_NAME="Ollama Qwen Anomaly Suggestion Connector" +OPENSEARCH_AI_AD_MODEL_NAME="Qwen 3.5 Anomaly Suggestion Model" +OPENSEARCH_AI_VISUAL_CONNECTOR_NAME="Ollama Qwen Visualization Connector" +OPENSEARCH_AI_VISUAL_MODEL_NAME="Qwen 3.5 Visualization Model" + +# disables swapping, imporving r/w performance (at the expense of RAM) +OPENSEARCH_BOOTSTRAP_MEMORY_LOCK=true + +# system_call_filter | https://en.wikipedia.org/wiki/Seccomp +OPENSEARCH_SYSTEM_CALL_FILTER=false + +####### OpenID Connect (OpenSearch Security) ####### +# Values used by: security/es_roles/opensearch/config.yml (openid_auth_domain) +OPENSEARCH_OPENID_CONNECT_URL="https://keycloak.example.com:8080/auth/realms/master/.well-known/openid-configuration" +OPENSEARCH_OPENID_REQUIRED_AUDIENCE="your-openid-client-id" +OPENSEARCH_OPENID_SUBJECT_KEY="preferred_username" +OPENSEARCH_OPENID_ROLES_KEY="roles" + +####### This section is for AD user authentication ####### + +# example: network.xyz.uk +OPENSEARCH_AD_DOMAIN_NAME="network.xyz.uk" + +# example: "ldap://server1.xyz.uk:389,ldap://server2.xyz.uk:389" +OPENSEARCH_AD_URL="ldap://server1.xyz.uk:389,ldap://server2.xyz.uk:389" + +OPENSEARCH_AD_UNMAPPED_GROUPS_AS_ROLES=true +OPENSEARCH_AD_FOLLOW_REFERRALS=false + +OPENSEARCH_AD_TIMEOUT=60s + + +####### SMTP EMAIL section + +# example Watcher_Email +OPENSEARCH_EMAIL_ACCOUNT_PROFILE="Watcher_Email" + +OPENSEARCH_EMAIL_ACCOUNT_EMAIL_DEFAULTS=info@notifications.cogstack.net + +# example: smtpserver.xyz.uk +OPENSEARCH_EMAIL_SMTP_HOST="smtpserver.xyz.uk" +OPENSEARCH_EMAIL_SMTP_PORT=25 + + +# Other elasticsearch settings, important for indexing etc +OPENSEARCH_QUERY_BOOL_MAX_CLAUSE_COUNT=4096 +OPENSEARCH_INDICES_MEMORY_INDEX_BUFFER_SIZE="25%" + + +########################################################## + +############################################################ Shared Env vars for MetricBeats/Kibana etc ############################################################## + +# please respect the double quotes "" on each address or you may get type errors from Kibana +OPENSEARCH_HOSTS='["https://elasticsearch-1:9200","https://elasticsearch-2:9200"]' + +# You can generate values for the below strings by using openssl rand +# example, in bash: openssl rand -base64 32 +# the keys must be at least 32 characters long + +# xpack.security.encryptionKey: "something_at_least_32_characters" +# OPENSEARCH_XPACK_SECURITY_ENCRYPTION_KEY= + diff --git a/apps/opensearch/security/bootstrap.sh b/apps/opensearch/security/bootstrap.sh new file mode 100644 index 00000000..9eb75d26 --- /dev/null +++ b/apps/opensearch/security/bootstrap.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +if (( $# == 0 )); then + printf 'Usage: bash %s \n' "$0" >&2 + exit 2 +fi +OPENSEARCH_KIBANA_PASSWORD=${OPENSEARCH_KIBANA_PASSWORD:-${KIBANA_PASSWORD:-}} +: "${OPENSEARCH_KIBANA_PASSWORD:?Set the Dashboards service account password}" + +policy_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +certs=$(cd -- "${SECURITY_DIR:-$policy_dir/../../../deployment/security}/certificates/opensearch" && pwd -P) +scratch=$(mktemp -d) +trap 'rm -rf -- "$scratch"' EXIT +printf '%s\0' kibanaserver "$OPENSEARCH_KIBANA_PASSWORD" \ + nifi "${OPENSEARCH_NIFI_PASSWORD:-${OS_NIFI_PASSWORD:-}}" \ + cogstack_pipeline "${OPENSEARCH_PIPELINE_PASSWORD:-${OS_PIPELINE_PASSWORD:-}}" \ + cogstack_user "${OPENSEARCH_ANALYST_PASSWORD:-${OS_ANALYST_PASSWORD:-}}" > "$scratch/passwords" + +bootstrap=$(cat <<'BASH' +set -euo pipefail +umask 077 +work=$(mktemp -d) +trap 'rm -rf -- "$work"' EXIT +tar -xf - -C "$work" + +opensearch_home=${OPENSEARCH_HOME:-/usr/share/opensearch} +tools="$opensearch_home/plugins/opensearch-security/tools" +ca="$opensearch_home/config/tls/ca.crt" +status=$(curl -sS --noproxy '*' --retry 30 --retry-all-errors --retry-delay 3 --max-time 10 \ + --cacert "$ca" --cert "$work/admin.crt" --key "$work/admin.key.pem" \ + --head --output /dev/null --write-out '%{http_code}' https://localhost:9200/.opendistro_security) +if [[ "$status" != 404 ]]; then + printf 'Bootstrap requires an empty Security index (index check returned HTTP %s).\n' "$status" >&2 + exit 1 +fi + +cp "$opensearch_home/config/opensearch-security"/{action_groups,allowlist,audit,config,nodes_dn}.yml "$work/" +{ + printf '_meta:\n type: internalusers\n config_version: 2\n' + while IFS= read -r -d '' user && IFS= read -r -d '' password; do + [[ -n "$password" ]] || continue + hash=$("$tools/hash.sh" -p "$password") + printf '%s:\n hash: "%s"\n' "$user" "$hash" + done < "$work/passwords" +} > "$work/internal_users.yml" +rm -- "$work/passwords" + +"$tools/securityadmin.sh" -icl -cd "$work" -cacert "$ca" \ + -cert "$work/admin.crt" -key "$work/admin.key.pem" +BASH +) + +tar -cf - -C "$scratch" passwords -C "$certs" admin.crt admin.key.pem \ + -C "$policy_dir" roles.yml roles_mapping.yml tenants.yml | + "$@" bash -c "$bootstrap" diff --git a/apps/opensearch/security/roles.yml b/apps/opensearch/security/roles.yml new file mode 100644 index 00000000..eb1eb737 --- /dev/null +++ b/apps/opensearch/security/roles.yml @@ -0,0 +1,18 @@ +_meta: + type: roles + config_version: 2 + +cogstack_ingest: + cluster_permissions: ['indices:data/write/bulk'] + index_permissions: + - index_patterns: ['nifi_*', 'cogstack_*'] + allowed_actions: [create_index, index] + +cogstack_access: + cluster_permissions: [cluster_composite_ops_ro] + index_permissions: + - index_patterns: ['nifi_*', 'cogstack_*'] + allowed_actions: [read] + tenant_permissions: + - tenant_patterns: [cogstack_tenant] + allowed_actions: [kibana_all_read] diff --git a/apps/opensearch/security/roles_mapping.yml b/apps/opensearch/security/roles_mapping.yml new file mode 100644 index 00000000..9eb7b9c0 --- /dev/null +++ b/apps/opensearch/security/roles_mapping.yml @@ -0,0 +1,19 @@ +_meta: + type: rolesmapping + config_version: 2 + +cogstack_ingest: + backend_roles: [cogstack_ingest] + users: [nifi, cogstack_pipeline] + +cogstack_access: + backend_roles: [cogstack_access] + users: [cogstack_user] + +kibana_user: + backend_roles: [cogstack_access] + users: [cogstack_user] + +kibana_server: + reserved: true + users: [kibanaserver] diff --git a/apps/opensearch/security/tenants.yml b/apps/opensearch/security/tenants.yml new file mode 100644 index 00000000..b538c77a --- /dev/null +++ b/apps/opensearch/security/tenants.yml @@ -0,0 +1,6 @@ +_meta: + type: tenants + config_version: 2 + +cogstack_tenant: + description: CogStack dashboards diff --git a/deployment/.gitignore b/deployment/.gitignore index 45a9af48..241c1ce0 100644 --- a/deployment/.gitignore +++ b/deployment/.gitignore @@ -2,7 +2,10 @@ !/env/ /env/* !/env/certificates.env +!/env/authentication.env !/env/cohorter.env !/env/jupyter.env +!/env/opensearch.env +!/env/opensearch-dashboards.env !/env/ocr_service.env !/env/ocr_service_text_only.env diff --git a/deployment/Makefile b/deployment/Makefile index 26b16018..b9103337 100644 --- a/deployment/Makefile +++ b/deployment/Makefile @@ -1,18 +1,241 @@ SHELL := /usr/bin/env bash .SHELLFLAGS := -o pipefail -c -.PHONY: setup-install-pre-requisites setup-k3s-cluster-init setup-verify setup-k3s-cluster-remote +.PHONY: setup-install-pre-requisites setup-k3s-cluster-init setup-verify setup-k3s-cluster-remote setup-k3s-namespace help -setup-install-pre-requisites: +setup-install-pre-requisites: ## Install host tools, Docker, K3s, and Helm locally by default bash scripts/installation_utils/install_os_tools_and_software.sh -setup-k3s-cluster-init: +setup-k3s-cluster-init: ## Initialize the first K3s server on this machine bash scripts/installation_utils/setup_kubernetes_cluster.sh k3s server --cluster-init -setup-k3s-cluster-remote: +setup-k3s-cluster-remote: ## Install prerequisites, initialize the first server, and join the rest over SSH bash scripts/installation_utils/setup_k3s_cluster.sh $(NODES) -setup-verify: +setup-k3s-namespace: ## Create the namespace configured in env/general.env + @set -eo pipefail; \ + . ./env/general.env; \ + kubectl create namespace "$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}" --dry-run=client -o yaml | \ + kubectl apply --server-side --field-manager=cogstack-namespace -f - + +setup-verify: ## Check local Docker, Docker Compose, and K3s access without sudo bash scripts/installation_utils/verify_docker.sh bash scripts/installation_utils/verify_k3s.sh +# ====================================================================================================================================================== + +.PHONY: certs certs-all certs-root certs-nifi certs-nginx certs-opensearch certs-opensearch-nodes delete-certs-all + +load_certificates_env = set -e; set -a; if [ -f ./env/certificates.env ]; then . ./env/certificates.env; fi; set +a + +certs: certs-root ## Generate the root CA and NiFi and NGINX certificates + $(MAKE) certs-nifi certs-nginx + +certs-all: ## Generate the root CA and NiFi, NGINX, OpenSearch, and Dashboards certificates + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + export CLUSTER_DOMAIN; \ + $(MAKE) certs KUBE_NAMESPACE="$$namespace"; \ + $(MAKE) certs-opensearch KUBE_NAMESPACE="$$namespace" + @$(load_certificates_env); \ + OPENSEARCH_DASHBOARDS_DNS_NAMES="$${OPENSEARCH_DASHBOARDS_DNS_NAMES:-localhost}" \ + bash scripts/security/create_opensearch_client_admin_certs.sh --dashboards-only + +certs-root: ## Generate the root CA bundle + @$(load_certificates_env); \ + bash scripts/security/create_root_ca_cert.sh + +certs-nifi: ## Generate the NiFi certificate and stores with the existing CA + bash scripts/security/create_nifi_certs.sh + +certs-nginx: ## Generate the NGINX certificate with the existing CA + @$(load_certificates_env); \ + bash scripts/security/create_nginx_certs.sh + +certs-opensearch: ## Generate the shared OpenSearch node and admin client certificates + @$(load_certificates_env); \ + service=opensearch-cluster-master; \ + service_dns="$$service.$${KUBE_NAMESPACE:-search}.svc"; \ + $(MAKE) certs-opensearch-nodes NODES=opensearch-shared \ + OPENSEARCH_NODE_DNS_NAMES="$${OPENSEARCH_NODE_DNS_NAMES:-localhost,$$service,$$service_dns,$$service_dns.$${CLUSTER_DOMAIN:-cluster.local}}" + @$(load_certificates_env); \ + bash scripts/security/create_opensearch_client_admin_certs.sh --admin-only + +certs-opensearch-nodes: ## Generate OpenSearch node certificates for NODES="node1 node2 ..." + @$(load_certificates_env); \ + read -r -a nodes <<< "$$NODES"; \ + bash scripts/security/create_opensearch_node_cert.sh "$${nodes[@]}" + +delete-certs-all: ## Delete generated local TLS certificates, keys, and stores + @set -e; \ + certs="$${SECURITY_DIR:-security}/certificates"; \ + if [ -L "$$certs" ]; then printf 'Certificate directory is a symlink: %s\n' "$$certs" >&2; exit 1; fi; \ + [ -d "$$certs" ] || exit 0; \ + CDPATH= cd -- "$$certs"; \ + find -P . -maxdepth 2 \( -type f -o -type l \) \ + \( -path './root/*' -o -path './nifi/*' -o -path './nginx/*' -o -path './opensearch/*' \) \ + \( -name '*.crt' -o -name '*.pem' -o -name '*.key' -o -name '*.csr' -o -name '*.p12' -o -name '*.jks' \) -delete + +# ====================================================================================================================================================== + +.PHONY: k3s-load-certs k3s-load-certs-all k3s-load-certs-root-ca k3s-load-certs-nifi k3s-load-certs-nginx k3s-load-certs-opensearch +.PHONY: k3s-load-certs-opensearch-dashboards + +k3s-load-certs: k3s-load-certs-all ## Alias for k3s-load-certs-all +k3s-load-certs-all: ## Load NiFi, NGINX, and OpenSearch node TLS Secrets +k3s-load-certs-root-ca: ## Load the public CA and NiFi truststore into cogstack-root-ca +k3s-load-certs-nifi: ## Load the NiFi keystore into nifi-tls +k3s-load-certs-nginx: ## Load the NGINX certificate and key into nginx-tls +k3s-load-certs-opensearch: ## Load the shared node certificate into opensearch-node-tls +k3s-load-certs-opensearch-dashboards: ## Load the browser-facing certificate into dashboards-tls + +k3s-load-certs-all k3s-load-certs-root-ca k3s-load-certs-nifi k3s-load-certs-nginx k3s-load-certs-opensearch k3s-load-certs-opensearch-dashboards: + @set -eo pipefail; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + certs="$${SECURITY_DIR:-security}/certificates"; \ + services=$(@:k3s-load-certs-%=%); \ + if [ "$$services" = all ]; then services="root-ca nifi nginx opensearch"; fi; \ + manifests=(); \ + for service in $$services; do \ + case "$$service" in \ + root-ca) secret=(generic cogstack-root-ca \ + --from-file="ca.crt=$$certs/root/root-ca.pem" \ + --from-file="truststore.jks=$$certs/nifi/nifi-truststore.jks");; \ + nifi) secret=(generic nifi-tls \ + --from-file="nifi-keystore.jks=$$certs/nifi/nifi-keystore.jks");; \ + nginx) secret=(tls nginx-tls \ + --cert="$$certs/nginx/tls.crt" --key="$$certs/nginx/tls.key");; \ + opensearch) secret=(generic opensearch-node-tls \ + --from-file="node.crt=$$certs/opensearch/opensearch-shared.crt" \ + --from-file="node.key=$$certs/opensearch/opensearch-shared.key" \ + --from-file="ca.crt=$$certs/opensearch/elastic-stack-ca.crt.pem");; \ + opensearch-dashboards) secret=(tls dashboards-tls \ + --cert="$$certs/opensearch/es_kibana_client.pem" --key="$$certs/opensearch/es_kibana_client.key");; \ + esac; \ + manifest=$$(kubectl -n "$$namespace" create secret "$${secret[@]}" --dry-run=client -o yaml); \ + manifests+=("$$manifest"); \ + done; \ + printf -- '---\n%s\n' "$${manifests[@]}" | \ + kubectl -n "$$namespace" apply --server-side --field-manager=cogstack-certificates -f - + +.PHONY: k3s-load-auth-nifi k3s-load-auth-opensearch k3s-load-auth-opensearch-dashboards + +# Uses env/authentication.env. Set NIFI_AUTH_FILE to choose another auth file. +k3s-load-auth-nifi: ## Prompt for missing credentials and load the NiFi auth Secret + @bash scripts/security/load_nifi_auth.sh + +# Both targets use env/authentication.env unless OPENSEARCH_AUTH_FILE is set. +k3s-load-auth-opensearch: ## Load configured users into a fresh OpenSearch cluster +k3s-load-auth-opensearch-dashboards: ## Load the OpenSearch Dashboards auth Secret + +k3s-load-auth-opensearch k3s-load-auth-opensearch-dashboards: + @bash scripts/security/load_opensearch_auth.sh $(@:k3s-load-auth-%=%) + +.PHONY: k3s-load-env-all k3s-load-env-nifi k3s-load-env-nginx k3s-load-env-opensearch + +k3s-load-env-all: k3s-load-env-nifi k3s-load-env-nginx k3s-load-env-opensearch ## Load all runtime environment ConfigMaps +k3s-load-env-nifi: ## Load the NiFi proxy hosts into the nifi-env ConfigMap +k3s-load-env-nginx: ## Load the NGINX runtime settings into the nginx-env ConfigMap +k3s-load-env-opensearch: ## Load the OpenSearch log level into the opensearch-env ConfigMap + +k3s-load-env-nifi k3s-load-env-nginx k3s-load-env-opensearch: + @set -eo pipefail; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + service=$(@:k3s-load-env-%=%); \ + env_file="./env/$$service.env"; \ + if [[ "$$service" == opensearch || -f "$$env_file" ]]; then . "$$env_file"; fi; \ + args=(); \ + case "$$service" in \ + nifi) args+=("--from-literal=NIFI_WEB_PROXY_HOST=$${NIFI_WEB_PROXY_HOST-}");; \ + nginx) \ + for name in NGINX_NIFI_SERVER_NAME NGINX_PROXY_CONTEXT_PATH NGINX_PROXY_SCHEME; do \ + if [[ -n $${!name+x} ]]; then args+=("--from-literal=$$name=$${!name}"); fi; \ + done;; \ + opensearch) args+=("--from-literal=OPENSEARCH_LOG_LEVEL=$${OPENSEARCH_LOG_LEVEL:-INFO}");; \ + esac; \ + kubectl -n "$$namespace" create configmap "$$service-env" "$${args[@]}" --dry-run=client -o yaml | \ + kubectl -n "$$namespace" apply --server-side --field-manager=cogstack-env -f - + +# ====================================================================================================================================================== + +.PHONY: k3s-install-nifi k3s-install-nginx k3s-install-ocr-service k3s-install-nifi-stack +.PHONY: k3s-uninstall-nifi k3s-uninstall-nginx k3s-uninstall-ocr-service k3s-uninstall-nifi-stack +.PHONY: k3s-install-opensearch k3s-install-opensearch-dashboards k3s-install-opensearch-stack k3s-bootstrap-opensearch +.PHONY: k3s-uninstall-opensearch k3s-uninstall-opensearch-dashboards k3s-uninstall-opensearch-stack + +# Install static manifests in the namespace from env/general.env. +k3s-install-nifi: k3s-load-env-nifi ## Apply the NiFi manifest and wait for readiness +k3s-install-nginx: k3s-load-env-nginx ## Apply the NGINX manifest and wait for readiness +k3s-install-ocr-service: ## Apply the OCR Service manifest and wait for readiness +k3s-install-opensearch: k3s-load-env-opensearch ## Apply the OpenSearch manifest and wait for readiness +k3s-install-opensearch-dashboards: ## Apply the Dashboards manifest and wait for readiness + +k3s-install-nifi k3s-install-nginx k3s-install-ocr-service k3s-install-opensearch k3s-install-opensearch-dashboards: + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + service=$(@:k3s-install-%=%); \ + case "$$service" in \ + nifi) workload=statefulset/cogstack-nifi;; \ + nginx) workload=deployment/cogstack-nginx;; \ + ocr-service) workload=deployment/ocr-service;; \ + opensearch) workload=statefulset/opensearch-cluster-master;; \ + opensearch-dashboards) workload=deployment/opensearch-dashboards;; \ + esac; \ + kubectl -n "$$namespace" apply -f "charts/$$service/rendered.yaml"; \ + kubectl -n "$$namespace" rollout status "$$workload" --timeout="$${K3S_TIMEOUT:-10m}" + +k3s-install-nifi-stack: k3s-install-nifi ## Install NiFi and then NGINX from their manifests + $(MAKE) k3s-install-nginx + +k3s-bootstrap-opensearch: k3s-load-auth-opensearch ## Initialize OpenSearch Security + +k3s-install-opensearch-stack: k3s-install-opensearch ## Install OpenSearch and then Dashboards from their manifests + @if [ "$${BOOTSTRAP_OPENSEARCH_SECURITY:-1}" = 1 ]; then $(MAKE) k3s-bootstrap-opensearch; fi + $(MAKE) k3s-install-opensearch-dashboards + +k3s-uninstall-nifi: ## Delete the NiFi workloads and retain their PVCs +k3s-uninstall-nginx: ## Delete the NGINX workloads +k3s-uninstall-ocr-service: ## Delete the OCR Service workloads +k3s-uninstall-opensearch: ## Delete the OpenSearch workloads and retain their PVCs +k3s-uninstall-opensearch-dashboards: ## Delete the Dashboards workloads + +k3s-uninstall-nifi k3s-uninstall-nginx k3s-uninstall-ocr-service k3s-uninstall-opensearch k3s-uninstall-opensearch-dashboards: + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + service=$(@:k3s-uninstall-%=%); \ + kubectl -n "$$namespace" delete -f "charts/$$service/rendered.yaml" \ + --ignore-not-found --cascade=foreground --wait --timeout="$${K3S_TIMEOUT:-10m}" + +k3s-uninstall-nifi-stack: k3s-uninstall-nginx ## Uninstall NGINX, then NiFi, and retain PVCs + $(MAKE) k3s-uninstall-nifi + +k3s-uninstall-opensearch-stack: k3s-uninstall-opensearch-dashboards ## Uninstall Dashboards, then OpenSearch, and retain PVCs + $(MAKE) k3s-uninstall-opensearch + +# ====================================================================================================================================================== + +.PHONY: helm-install + +helm-install: ## Install or upgrade CHART with optional HELM_VALUES and HELM_TIMEOUT + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + chart="charts/$${CHART:?Set CHART to a directory under deployment/charts}"; \ + release="$$CHART"; \ + args=(); \ + if [ -n "$${HELM_VALUES:-}" ]; then args+=(-f "$$HELM_VALUES"); fi; \ + helm upgrade --install "$$release" "$$chart" -n "$$namespace" \ + --wait --timeout "$${HELM_TIMEOUT:-10m}" "$${args[@]}" + +# ====================================================================================================================================================== + +help: ## Show deployment commands + @printf '%s\n' 'Deployment commands' + @awk -F ':.*## ' 'NF == 2 && $$1 ~ /^[[:alnum:]_-]+$$/ { printf " %-30s %s\n", $$1, $$2 }' "$(lastword $(MAKEFILE_LIST))" + @printf '\n%s\n %s\n' 'Remote setup example' \ + 'make setup-k3s-cluster-remote NODES="admin@server1 admin@server2 admin@server3"' diff --git a/deployment/charts/README.md b/deployment/charts/README.md index 2d87edec..1aa910f4 100644 --- a/deployment/charts/README.md +++ b/deployment/charts/README.md @@ -1,49 +1,63 @@ -# Helm charts +# Kubernetes deployments -Reusable deployment charts for CogStack. Each chart sits directly under this -directory and declares its package name in `Chart.yaml`. -Folder names use component names, such as `medcat-service` and `jupyter-hub`. +## NiFi and NGINX -## NiFi charts - -These charts were migrated from `cogstack_nifi/deploy/kubernetes/charts/`: - -| Chart | Purpose | -| --- | --- | -| [`nifi/`](nifi/README.md) | NiFi StatefulSet, Services, TLS settings and persistent storage. | -| [`nginx/`](nginx/README.md) | TLS reverse proxy for the NiFi web Service, with optional Ingress. | - -The `nifi/` directory declares `name: nifi` in `Chart.yaml`, so Helm -packages it as `nifi-.tgz`. - -Run from the repository root: +Set `KUBE_NAMESPACE` in `deployment/env/general.env`. For a new TLS bundle, +run `make -C deployment certs` from the repository root. Load the certificates +and NiFi credentials before applying the manifests. ```bash -helm lint deployment/charts/nifi deployment/charts/nginx -helm template cogstack-nifi deployment/charts/nifi --namespace cogstack -helm template cogstack-nginx deployment/charts/nginx --namespace cogstack +make -C deployment setup-k3s-namespace +make -C deployment k3s-load-certs-root-ca k3s-load-certs-nifi k3s-load-certs-nginx +make -C deployment k3s-load-auth-nifi +make -C deployment k3s-install-nifi-stack ``` -See each chart's README for the ConfigMaps, Secrets and storage needed before -installation. `values.env.yaml` files are optional `envsubst` inputs; render -their environment placeholders before supplying them to Helm. +The install target loads `nifi-env` and `nginx-env`, applies the +[NiFi](nifi/rendered.yaml) and [NGINX](nginx/rendered.yaml) manifests, and waits +for rollout. Set `NIFI_WEB_PROXY_HOST` in `deployment/env/nifi.env` or in the +shell when the file is absent. Use `K3S_TIMEOUT` to change the rollout timeout. -## Validation and releases +NiFi needs a StorageClass or suitable pre-provisioned volumes. Its configuration +and repository PVCs are retained when using `make -C deployment k3s-uninstall-nifi-stack`. +An existing Helm release still tracks its workloads after `kubectl apply`. +Treat Helm uninstall on those releases as workload deletion. -The shared chart workflow discovers `deployment/charts/*/Chart.yaml` for -validation and packaging. Release-please registers each chart by its directory -and uses its configured component for release tags, such as -`helm-charts/nifi-v0.1.0`. The migrated charts start at `0.1.0` for their -first platform release. +## OCR Service + +Run `make -C deployment k3s-install-ocr-service` to apply the +[OCR Service manifest](ocr-service/rendered.yaml) and wait for rollout. Set +`OCR_SERVICE_OPERATION_MODE` to `NO_OCR` in the manifest for text extraction only. -The NiFi charts include `ci/ci-values.yaml` with zero replicas so chart-testing -can validate Kubernetes resource installation without deployment-owned -ConfigMaps and Secrets. Application startup and TLS checks require a separate -runtime test with those inputs supplied. +## OpenSearch and Dashboards -To package locally, keep generated archives outside the source tree: +Set `KUBE_NAMESPACE` in `deployment/env/general.env` and +`OPENSEARCH_KIBANA_PASSWORD` in the shell or `deployment/env/authentication.env`. +For a new certificate bundle, run `make -C deployment certs-all` from the +repository root. ```bash -helm package deployment/charts/nifi --destination /tmp -helm package deployment/charts/nginx --destination /tmp +make -C deployment setup-k3s-namespace +make -C deployment k3s-load-certs-opensearch k3s-load-certs-opensearch-dashboards +make -C deployment k3s-load-auth-opensearch-dashboards +make -C deployment k3s-install-opensearch-stack ``` + +Load the `dashboards-auth` Secret before the first bootstrap so OpenSearch and +Dashboards share the `kibanaserver` password. Set the optional +`OPENSEARCH_NIFI_PASSWORD`, `OPENSEARCH_PIPELINE_PASSWORD`, and +`OPENSEARCH_ANALYST_PASSWORD` to create those accounts during bootstrap. Set +`BOOTSTRAP_OPENSEARCH_SECURITY=0` to skip bootstrap. + +The stack applies the [OpenSearch](opensearch/rendered.yaml) and +[Dashboards](opensearch-dashboards/rendered.yaml) manifests. Set replica counts +and resources in those files, and choose the OpenSearch claim size and storage +class before the first install. Restart the workload after changing its mounted +ConfigMap. OpenSearch and Dashboards serve HTTPS on ports `9200` and `5601`. +`make -C deployment k3s-uninstall-opensearch-stack` deletes the workloads and +retains the OpenSearch PVCs. + +## Helm charts + +The shared chart workflow discovers `deployment/charts/*/Chart.yaml` for +validation and packaging. Release-please registers published charts by directory. diff --git a/deployment/charts/jupyter-hub/rendered.yaml b/deployment/charts/jupyter-hub/rendered.yaml new file mode 100644 index 00000000..0d28d76f --- /dev/null +++ b/deployment/charts/jupyter-hub/rendered.yaml @@ -0,0 +1,3306 @@ +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/netpol.yaml +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + podSelector: + matchLabels: + component: hub + app: "jupyterhub" + release: "jupyterhub" + policyTypes: + - Ingress + - Egress + + # IMPORTANT: + # NetworkPolicy's ingress "from" and egress "to" rule specifications require + # great attention to detail. A quick summary is: + # + # 1. You can provide "from"/"to" rules that provide access either ports or a + # subset of ports. + # 2. You can for each "from"/"to" rule provide any number of + # "sources"/"destinations" of four different kinds. + # - podSelector - targets pods with a certain label in the same namespace as the NetworkPolicy + # - namespaceSelector - targets all pods running in namespaces with a certain label + # - namespaceSelector and podSelector - targets pods with a certain label running in namespaces with a certain label + # - ipBlock - targets network traffic from/to a set of IP address ranges + # + # Read more at: https://kubernetes.io/docs/concepts/services-networking/network-policies/#behavior-of-to-and-from-selectors + # + ingress: + + # allowed pods (hub.jupyter.org/network-access-hub) --> hub + - ports: + - port: http + from: + # source 1 - labeled pods + - podSelector: + matchLabels: + hub.jupyter.org/network-access-hub: "true" + # depends, but default is nothing --> hub + - from: + - podSelector: + matchLabels: + app.kubernetes.io/name: prometheus + ports: + - port: http + protocol: TCP + + egress: + # hub --> proxy + - to: + - podSelector: + matchLabels: + component: proxy + app: "jupyterhub" + release: "jupyterhub" + ports: + - port: 8001 + + # hub --> singleuser-server + - to: + - podSelector: + matchLabels: + component: singleuser-server + app: "jupyterhub" + release: "jupyterhub" + ports: + - port: 8888 + + - ports: + - port: 53 + protocol: UDP + - port: 53 + protocol: TCP + to: + # Allow outbound connections to DNS ports on the cloud metadata server + - ipBlock: + cidr: 169.254.169.254/32 + # Allow outbound connections to DNS ports on pods in the kube-system + # namespace + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + # Allow outbound connections to DNS ports on destinations in the private IP + # ranges + - ipBlock: + cidr: 10.0.0.0/8 + - ipBlock: + cidr: 172.16.0.0/12 + - ipBlock: + cidr: 192.168.0.0/16 + # Allow outbound connections to non-private IP ranges + - to: + - ipBlock: + cidr: 0.0.0.0/0 + except: + # As part of this rule: + # - don't allow outbound connections to private IPs + - 10.0.0.0/8 + - 172.16.0.0/12 + - 192.168.0.0/16 + # - don't allow outbound connections to the cloud metadata server + - 169.254.169.254/32 + # Allow outbound connections to private IP ranges + - to: + - ipBlock: + cidr: 10.0.0.0/8 + - ipBlock: + cidr: 172.16.0.0/12 + - ipBlock: + cidr: 192.168.0.0/16 + # Allow outbound connections to the cloud metadata server + - to: + - ipBlock: + cidr: 169.254.169.254/32 + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/proxy/netpol.yaml +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: proxy + labels: + component: proxy + app.kubernetes.io/component: proxy + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + podSelector: + matchLabels: + component: proxy + app: "jupyterhub" + release: "jupyterhub" + policyTypes: + - Ingress + - Egress + + # IMPORTANT: + # NetworkPolicy's ingress "from" and egress "to" rule specifications require + # great attention to detail. A quick summary is: + # + # 1. You can provide "from"/"to" rules that provide access either ports or a + # subset of ports. + # 2. You can for each "from"/"to" rule provide any number of + # "sources"/"destinations" of four different kinds. + # - podSelector - targets pods with a certain label in the same namespace as the NetworkPolicy + # - namespaceSelector - targets all pods running in namespaces with a certain label + # - namespaceSelector and podSelector - targets pods with a certain label running in namespaces with a certain label + # - ipBlock - targets network traffic from/to a set of IP address ranges + # + # Read more at: https://kubernetes.io/docs/concepts/services-networking/network-policies/#behavior-of-to-and-from-selectors + # + ingress: + # allow incoming traffic to these ports independent of source + - ports: + - port: http + - port: https + + # allowed pods (hub.jupyter.org/network-access-proxy-http) --> proxy (http/https port) + - ports: + - port: http + from: + # source 1 - labeled pods + - podSelector: + matchLabels: + hub.jupyter.org/network-access-proxy-http: "true" + + # allowed pods (hub.jupyter.org/network-access-proxy-api) --> proxy (api port) + - ports: + - port: api + from: + # source 1 - labeled pods + - podSelector: + matchLabels: + hub.jupyter.org/network-access-proxy-api: "true" + + egress: + # proxy --> hub + - to: + - podSelector: + matchLabels: + component: hub + app: "jupyterhub" + release: "jupyterhub" + ports: + - port: 8081 + + # proxy --> singleuser-server + - to: + - podSelector: + matchLabels: + component: singleuser-server + app: "jupyterhub" + release: "jupyterhub" + ports: + - port: 8888 + + - ports: + - port: 53 + protocol: UDP + - port: 53 + protocol: TCP + to: + # Allow outbound connections to DNS ports on the cloud metadata server + - ipBlock: + cidr: 169.254.169.254/32 + # Allow outbound connections to DNS ports on pods in the kube-system + # namespace + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + # Allow outbound connections to DNS ports on destinations in the private IP + # ranges + - ipBlock: + cidr: 10.0.0.0/8 + - ipBlock: + cidr: 172.16.0.0/12 + - ipBlock: + cidr: 192.168.0.0/16 + # Allow outbound connections to non-private IP ranges + - to: + - ipBlock: + cidr: 0.0.0.0/0 + except: + # As part of this rule: + # - don't allow outbound connections to private IPs + - 10.0.0.0/8 + - 172.16.0.0/12 + - 192.168.0.0/16 + # - don't allow outbound connections to the cloud metadata server + - 169.254.169.254/32 + # Allow outbound connections to private IP ranges + - to: + - ipBlock: + cidr: 10.0.0.0/8 + - ipBlock: + cidr: 172.16.0.0/12 + - ipBlock: + cidr: 192.168.0.0/16 + # Allow outbound connections to the cloud metadata server + - to: + - ipBlock: + cidr: 169.254.169.254/32 + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-placeholder/pdb.yaml +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: user-placeholder + labels: + component: user-placeholder + app.kubernetes.io/component: user-placeholder + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + minAvailable: 0 + selector: + matchLabels: + component: user-placeholder + app: "jupyterhub" + release: "jupyterhub" + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-scheduler/pdb.yaml +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: user-scheduler + labels: + component: user-scheduler + app.kubernetes.io/component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + maxUnavailable: 1 + selector: + matchLabels: + component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/serviceaccount.yaml +apiVersion: v1 +kind: ServiceAccount +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-scheduler/serviceaccount.yaml +apiVersion: v1 +kind: ServiceAccount +metadata: + name: user-scheduler + labels: + component: user-scheduler + app.kubernetes.io/component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/secret.yaml +kind: Secret +apiVersion: v1 +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +type: Opaque +data: + values.yaml: "Q2hhcnQ6CiAgQXBwVmVyc2lvbjogNS40LjMKICBOYW1lOiBqdXB5dGVyaHViCiAgVmVyc2lvbjogNC4zLjIKUmVsZWFzZToKICBOYW1lOiBqdXB5dGVyaHViCiAgTmFtZXNwYWNlOiBkZWZhdWx0CiAgU2VydmljZTogSGVsbQpjdWxsOgogIGFkbWluVXNlcnM6IHRydWUKICBjb25jdXJyZW5jeTogMTAKICBlbmFibGVkOiBmYWxzZQogIGV2ZXJ5OiA2MDAKICBtYXhBZ2U6IDAKICByZW1vdmVOYW1lZFNlcnZlcnM6IGZhbHNlCiAgdGltZW91dDogMzYwMAogIHVzZXJzOiBmYWxzZQpjdXN0b206IHt9CmRlYnVnOgogIGVuYWJsZWQ6IGZhbHNlCmZ1bGxuYW1lT3ZlcnJpZGU6ICIiCmdsb2JhbDoKICBzYWZlVG9TaG93VmFsdWVzOiBmYWxzZQpodHRwUm91dGU6CiAgYW5ub3RhdGlvbnM6IHt9CiAgZW5hYmxlZDogZmFsc2UKICBnYXRld2F5OgogICAgbmFtZTogeW91ci1nYXRld2F5CiAgICBuYW1lc3BhY2U6ICIiCiAgaG9zdG5hbWVzOiBbXQpodWI6CiAgYWxsb3dOYW1lZFNlcnZlcnM6IGZhbHNlCiAgYW5ub3RhdGlvbnM6IHt9CiAgYXJnczogW10KICBiYXNlVXJsOiAvCiAgY29tbWFuZDogW10KICBjb25jdXJyZW50U3Bhd25MaW1pdDogNjQKICBjb25maWc6CiAgICBBdXRoZW50aWNhdG9yOgogICAgICBhZG1pbl91c2VyczoKICAgICAgLSBhZG1pbgogICAgRHVtbXlBdXRoZW50aWNhdG9yOgogICAgICBwYXNzd29yZDogU3VwZXJTZWNyZXQKICAgIEp1cHl0ZXJIdWI6CiAgICAgIGFkbWluX2FjY2VzczogdHJ1ZQogICAgICBhdXRoZW50aWNhdG9yX2NsYXNzOiBkdW1teQogICAgS3ViZVNwYXduZXI6CiAgICAgIGZzX2dpZDogMAogICAgICBodHRwX3RpbWVvdXQ6IDEyMAogICAgICBub3RlYm9va19kaXI6IC9ob21lL2pvdnlhbi93b3JrCiAgICAgIHN0YXJ0X3RpbWVvdXQ6IDMwMAogICAgICB1aWQ6IDAKICAgIFNwYXduZXI6CiAgICAgIGRlZmF1bHRfdXJsOiAvbGFiLwogICAgICBub3RlYm9va19kaXI6IC9ob21lL2pvdnlhbi93b3JrCiAgY29uc2VjdXRpdmVGYWlsdXJlTGltaXQ6IDUKICBjb250YWluZXJTZWN1cml0eUNvbnRleHQ6CiAgICBhbGxvd1ByaXZpbGVnZUVzY2FsYXRpb246IGZhbHNlCiAgICBjYXBhYmlsaXRpZXM6CiAgICAgIGRyb3A6CiAgICAgIC0gQUxMCiAgICBydW5Bc0dyb3VwOiAxMDAwCiAgICBydW5Bc1VzZXI6IDEwMDAKICBkYjoKICAgIHB2YzoKICAgICAgYWNjZXNzTW9kZXM6CiAgICAgIC0gUmVhZFdyaXRlT25jZQogICAgICBhbm5vdGF0aW9uczoge30KICAgICAgc2VsZWN0b3I6IHt9CiAgICAgIHN0b3JhZ2U6IDFHaQogICAgdHlwZTogc3FsaXRlLXB2YwogIGRlcGxveW1lbnRTdHJhdGVneToKICAgIHR5cGU6IFJlY3JlYXRlCiAgZXh0cmFDb25maWc6CiAgICAwMC1jdXN0b20tc3Bhd25lcjogfAogICAgICAjIEN1c3RvbSBlbnZpcm9ubWVudCB2YXJpYWJsZXMgZm9yIHVzZXIgcG9kcwogICAgICBjLkt1YmVTcGF3bmVyLmVudmlyb25tZW50ID0gYy5LdWJlU3Bhd25lci5lbnZpcm9ubWVudCBvciB7fQogICAgICBjLkt1YmVTcGF3bmVyLmVudmlyb25tZW50LnVwZGF0ZSh7CiAgICAgICAgJ0dSQU5UX1NVRE8nOiAnMScsCiAgICAgICAgJ0NIT1dOX0hPTUUnOiAneWVzJywKICAgICAgICAnQ0hPV05fSE9NRV9PUFRTJzogJy1SJywKICAgICAgfSkKICAgICAgIyBBbGxvdyByb290IGluIG5vdGVib29rcwogICAgICBjLkt1YmVTcGF3bmVyLmFyZ3MgPSBbJy0tYWxsb3ctcm9vdCddCiAgICAwMC1sb2ctbGV2ZWw6IHwKICAgICAgYy5BcHBsaWNhdGlvbi5sb2dfbGV2ZWwgPSAnREVCVUcnCiAgICAwMS1wcm9tZXRoZXVzLWF1dGhlbnRpY2F0aW9uOiB8CiAgICAgIGMuSnVweXRlckh1Yi5hdXRoZW50aWNhdGVfcHJvbWV0aGV1cyA9IEZhbHNlCiAgZXh0cmFDb250YWluZXJzOiBbXQogIGV4dHJhRW52OiB7fQogIGV4dHJhRmlsZXM6IHt9CiAgZXh0cmFQb2RTcGVjOiB7fQogIGV4dHJhVm9sdW1lTW91bnRzOiBbXQogIGV4dHJhVm9sdW1lczogW10KICBpbWFnZToKICAgIG5hbWU6IGNvZ3N0YWNrc3lzdGVtcy9qdXB5dGVyLWh1YgogICAgcHVsbFBvbGljeTogSWZOb3RQcmVzZW50CiAgICBwdWxsU2VjcmV0czogW10KICAgIHRhZzogMi4zLjYKICBpbml0Q29udGFpbmVyczogW10KICBsYWJlbHM6IHt9CiAgbGlmZWN5Y2xlOiB7fQogIGxpdmVuZXNzUHJvYmU6CiAgICBlbmFibGVkOiB0cnVlCiAgICBmYWlsdXJlVGhyZXNob2xkOiAzMAogICAgaW5pdGlhbERlbGF5U2Vjb25kczogMzAwCiAgICBwZXJpb2RTZWNvbmRzOiAxMAogICAgdGltZW91dFNlY29uZHM6IDMKICBsb2FkUm9sZXM6IHt9CiAgbmV0d29ya1BvbGljeToKICAgIGFsbG93ZWRJbmdyZXNzUG9ydHM6IFtdCiAgICBlZ3Jlc3M6IFtdCiAgICBlZ3Jlc3NBbGxvd1J1bGVzOgogICAgICBjbG91ZE1ldGFkYXRhU2VydmVyOiB0cnVlCiAgICAgIGRuc1BvcnRzQ2xvdWRNZXRhZGF0YVNlcnZlcjogdHJ1ZQogICAgICBkbnNQb3J0c0t1YmVTeXN0ZW1OYW1lc3BhY2U6IHRydWUKICAgICAgZG5zUG9ydHNQcml2YXRlSVBzOiB0cnVlCiAgICAgIG5vblByaXZhdGVJUHM6IHRydWUKICAgICAgcHJpdmF0ZUlQczogdHJ1ZQogICAgZW5hYmxlZDogdHJ1ZQogICAgaW5ncmVzczoKICAgIC0gZnJvbToKICAgICAgLSBwb2RTZWxlY3RvcjoKICAgICAgICAgIG1hdGNoTGFiZWxzOgogICAgICAgICAgICBhcHAua3ViZXJuZXRlcy5pby9uYW1lOiBwcm9tZXRoZXVzCiAgICAgIHBvcnRzOgogICAgICAtIHBvcnQ6IGh0dHAKICAgICAgICBwcm90b2NvbDogVENQCiAgICBpbnRlck5hbWVzcGFjZUFjY2Vzc0xhYmVsczogaWdub3JlCiAgbm9kZVNlbGVjdG9yOiB7fQogIHBkYjoKICAgIGVuYWJsZWQ6IGZhbHNlCiAgICBtaW5BdmFpbGFibGU6IDEKICBwb2RTZWN1cml0eUNvbnRleHQ6CiAgICBmc0dyb3VwOiAxMDAwCiAgICBydW5Bc05vblJvb3Q6IHRydWUKICAgIHNlY2NvbXBQcm9maWxlOgogICAgICB0eXBlOiBSdW50aW1lRGVmYXVsdAogIHJlYWRpbmVzc1Byb2JlOgogICAgZW5hYmxlZDogdHJ1ZQogICAgZmFpbHVyZVRocmVzaG9sZDogMTAwMAogICAgaW5pdGlhbERlbGF5U2Vjb25kczogMAogICAgcGVyaW9kU2Vjb25kczogMgogICAgdGltZW91dFNlY29uZHM6IDEKICByZXNvdXJjZXM6IHt9CiAgc2VydmljZToKICAgIGFubm90YXRpb25zOiB7fQogICAgZXh0cmFQb3J0czogW10KICAgIGlwRmFtaWxpZXM6IFtdCiAgICBpcEZhbWlseVBvbGljeTogUHJlZmVyRHVhbFN0YWNrCiAgICBwb3J0czoge30KICAgIHR5cGU6IENsdXN0ZXJJUAogIHNlcnZpY2VBY2NvdW50OgogICAgYW5ub3RhdGlvbnM6IHt9CiAgICBjcmVhdGU6IHRydWUKICBzZXJ2aWNlczoge30KICB0ZW1wbGF0ZVBhdGhzOiBbXQogIHRlbXBsYXRlVmFyczoge30KICB0b2xlcmF0aW9uczogW10KaW1hZ2VQdWxsU2VjcmV0OgogIGF1dG9tYXRpY1JlZmVyZW5jZUluamVjdGlvbjogdHJ1ZQogIGNyZWF0ZTogZmFsc2UKaW1hZ2VQdWxsU2VjcmV0czogW10KaW5ncmVzczoKICBhbm5vdGF0aW9uczoge30KICBlbmFibGVkOiBmYWxzZQogIGV4dHJhUGF0aHM6IFtdCiAgaG9zdHM6IFtdCiAgcGF0aFR5cGU6IFByZWZpeAogIHRsczogW10KcHJlUHVsbGVyOgogIGFubm90YXRpb25zOiB7fQogIGNvbnRhaW5lclNlY3VyaXR5Q29udGV4dDoKICAgIGFsbG93UHJpdmlsZWdlRXNjYWxhdGlvbjogZmFsc2UKICAgIGNhcGFiaWxpdGllczoKICAgICAgZHJvcDoKICAgICAgLSBBTEwKICAgIHJ1bkFzR3JvdXA6IDY1NTM0CiAgICBydW5Bc05vblJvb3Q6IHRydWUKICAgIHJ1bkFzVXNlcjogNjU1MzQKICAgIHNlY2NvbXBQcm9maWxlOgogICAgICB0eXBlOiBSdW50aW1lRGVmYXVsdAogIGNvbnRpbnVvdXM6CiAgICBkYWVtb25zZXRBbm5vdGF0aW9uczoge30KICAgIGVuYWJsZWQ6IGZhbHNlCiAgICBzZXJ2aWNlQWNjb3VudDoKICAgICAgYW5ub3RhdGlvbnM6IHt9CiAgICAgIGNyZWF0ZTogdHJ1ZQogIGV4dHJhSW1hZ2VzOiB7fQogIGV4dHJhVG9sZXJhdGlvbnM6IFtdCiAgaG9vazoKICAgIGNvbnRhaW5lclNlY3VyaXR5Q29udGV4dDoKICAgICAgYWxsb3dQcml2aWxlZ2VFc2NhbGF0aW9uOiBmYWxzZQogICAgICBjYXBhYmlsaXRpZXM6CiAgICAgICAgZHJvcDoKICAgICAgICAtIEFMTAogICAgICBydW5Bc0dyb3VwOiA2NTUzNAogICAgICBydW5Bc05vblJvb3Q6IHRydWUKICAgICAgcnVuQXNVc2VyOiA2NTUzNAogICAgICBzZWNjb21wUHJvZmlsZToKICAgICAgICB0eXBlOiBSdW50aW1lRGVmYXVsdAogICAgZGFlbW9uc2V0QW5ub3RhdGlvbnM6IHt9CiAgICBlbmFibGVkOiBmYWxzZQogICAgaW1hZ2U6CiAgICAgIG5hbWU6IHF1YXkuaW8vanVweXRlcmh1Yi9rOHMtaW1hZ2UtYXdhaXRlcgogICAgICBwdWxsU2VjcmV0czogW10KICAgICAgdGFnOiA0LjMuMgogICAgbm9kZVNlbGVjdG9yOiB7fQogICAgcG9kU2NoZWR1bGluZ1dhaXREdXJhdGlvbjogMTAKICAgIHB1bGxPbmx5T25DaGFuZ2VzOiB0cnVlCiAgICByZXNvdXJjZXM6IHt9CiAgICBzZXJ2aWNlQWNjb3VudDoKICAgICAgYW5ub3RhdGlvbnM6IHt9CiAgICAgIGNyZWF0ZTogdHJ1ZQogICAgc2VydmljZUFjY291bnRJbWFnZVB1bGxlcjoKICAgICAgYW5ub3RhdGlvbnM6IHt9CiAgICAgIGNyZWF0ZTogdHJ1ZQogICAgdG9sZXJhdGlvbnM6IFtdCiAgbGFiZWxzOiB7fQogIHBhdXNlOgogICAgY29udGFpbmVyU2VjdXJpdHlDb250ZXh0OgogICAgICBhbGxvd1ByaXZpbGVnZUVzY2FsYXRpb246IGZhbHNlCiAgICAgIGNhcGFiaWxpdGllczoKICAgICAgICBkcm9wOgogICAgICAgIC0gQUxMCiAgICAgIHJ1bkFzR3JvdXA6IDY1NTM0CiAgICAgIHJ1bkFzTm9uUm9vdDogdHJ1ZQogICAgICBydW5Bc1VzZXI6IDY1NTM0CiAgICAgIHNlY2NvbXBQcm9maWxlOgogICAgICAgIHR5cGU6IFJ1bnRpbWVEZWZhdWx0CiAgICBpbWFnZToKICAgICAgbmFtZTogcmVnaXN0cnkuazhzLmlvL3BhdXNlCiAgICAgIHB1bGxTZWNyZXRzOiBbXQogICAgICB0YWc6IDMuMTAuMQogIHB1bGxQcm9maWxlTGlzdEltYWdlczogdHJ1ZQogIHJlc291cmNlczoge30KcHJveHk6CiAgYW5ub3RhdGlvbnM6IHt9CiAgY2hwOgogICAgY29udGFpbmVyU2VjdXJpdHlDb250ZXh0OgogICAgICBhbGxvd1ByaXZpbGVnZUVzY2FsYXRpb246IGZhbHNlCiAgICAgIGNhcGFiaWxpdGllczoKICAgICAgICBkcm9wOgogICAgICAgIC0gQUxMCiAgICAgIHJ1bkFzR3JvdXA6IDY1NTM0CiAgICAgIHJ1bkFzTm9uUm9vdDogdHJ1ZQogICAgICBydW5Bc1VzZXI6IDY1NTM0CiAgICAgIHNlY2NvbXBQcm9maWxlOgogICAgICAgIHR5cGU6IFJ1bnRpbWVEZWZhdWx0CiAgICBleHRyYUNvbW1hbmRMaW5lRmxhZ3M6IFtdCiAgICBleHRyYUVudjoge30KICAgIGV4dHJhUG9kU3BlYzoge30KICAgIGltYWdlOgogICAgICBuYW1lOiBxdWF5LmlvL2p1cHl0ZXJodWIvY29uZmlndXJhYmxlLWh0dHAtcHJveHkKICAgICAgcHVsbFNlY3JldHM6IFtdCiAgICAgIHRhZzogNS4xLjAKICAgIGxpdmVuZXNzUHJvYmU6CiAgICAgIGVuYWJsZWQ6IHRydWUKICAgICAgZmFpbHVyZVRocmVzaG9sZDogMzAKICAgICAgaW5pdGlhbERlbGF5U2Vjb25kczogNjAKICAgICAgcGVyaW9kU2Vjb25kczogMTAKICAgICAgdGltZW91dFNlY29uZHM6IDMKICAgIG5ldHdvcmtQb2xpY3k6CiAgICAgIGFsbG93ZWRJbmdyZXNzUG9ydHM6CiAgICAgIC0gaHR0cAogICAgICAtIGh0dHBzCiAgICAgIGVncmVzczogW10KICAgICAgZWdyZXNzQWxsb3dSdWxlczoKICAgICAgICBjbG91ZE1ldGFkYXRhU2VydmVyOiB0cnVlCiAgICAgICAgZG5zUG9ydHNDbG91ZE1ldGFkYXRhU2VydmVyOiB0cnVlCiAgICAgICAgZG5zUG9ydHNLdWJlU3lzdGVtTmFtZXNwYWNlOiB0cnVlCiAgICAgICAgZG5zUG9ydHNQcml2YXRlSVBzOiB0cnVlCiAgICAgICAgbm9uUHJpdmF0ZUlQczogdHJ1ZQogICAgICAgIHByaXZhdGVJUHM6IHRydWUKICAgICAgZW5hYmxlZDogdHJ1ZQogICAgICBpbmdyZXNzOiBbXQogICAgICBpbnRlck5hbWVzcGFjZUFjY2Vzc0xhYmVsczogaWdub3JlCiAgICBub2RlU2VsZWN0b3I6IHt9CiAgICBwZGI6CiAgICAgIGVuYWJsZWQ6IGZhbHNlCiAgICAgIG1pbkF2YWlsYWJsZTogMQogICAgcmVhZGluZXNzUHJvYmU6CiAgICAgIGVuYWJsZWQ6IHRydWUKICAgICAgZmFpbHVyZVRocmVzaG9sZDogMTAwMAogICAgICBpbml0aWFsRGVsYXlTZWNvbmRzOiAwCiAgICAgIHBlcmlvZFNlY29uZHM6IDIKICAgICAgdGltZW91dFNlY29uZHM6IDEKICAgIHJlc291cmNlczoge30KICAgIHRvbGVyYXRpb25zOiBbXQogIGRlcGxveW1lbnRTdHJhdGVneToKICAgIHR5cGU6IFJlY3JlYXRlCiAgaHR0cHM6CiAgICBlbmFibGVkOiBmYWxzZQogICAgaG9zdHM6IFtdCiAgICBsZXRzZW5jcnlwdDoKICAgICAgYWNtZVNlcnZlcjogaHR0cHM6Ly9hY21lLXYwMi5hcGkubGV0c2VuY3J5cHQub3JnL2RpcmVjdG9yeQogICAgbWFudWFsOiB7fQogICAgc2VjcmV0OgogICAgICBjcnQ6IHRscy5jcnQKICAgICAga2V5OiB0bHMua2V5CiAgICB0eXBlOiBsZXRzZW5jcnlwdAogIGxhYmVsczoge30KICBzZWNyZXRTeW5jOgogICAgY29udGFpbmVyU2VjdXJpdHlDb250ZXh0OgogICAgICBhbGxvd1ByaXZpbGVnZUVzY2FsYXRpb246IGZhbHNlCiAgICAgIGNhcGFiaWxpdGllczoKICAgICAgICBkcm9wOgogICAgICAgIC0gQUxMCiAgICAgIHJ1bkFzR3JvdXA6IDY1NTM0CiAgICAgIHJ1bkFzTm9uUm9vdDogdHJ1ZQogICAgICBydW5Bc1VzZXI6IDY1NTM0CiAgICAgIHNlY2NvbXBQcm9maWxlOgogICAgICAgIHR5cGU6IFJ1bnRpbWVEZWZhdWx0CiAgICBpbWFnZToKICAgICAgbmFtZTogcXVheS5pby9qdXB5dGVyaHViL2s4cy1zZWNyZXQtc3luYwogICAgICBwdWxsU2VjcmV0czogW10KICAgICAgdGFnOiA0LjMuMgogICAgcmVzb3VyY2VzOiB7fQogIHNlcnZpY2U6CiAgICBhbm5vdGF0aW9uczoge30KICAgIGRpc2FibGVIdHRwUG9ydDogZmFsc2UKICAgIGV4dGVybmFsSVBzOiBbXQogICAgZXh0cmFQb3J0czogW10KICAgIGlwRmFtaWxpZXM6IFtdCiAgICBpcEZhbWlseVBvbGljeTogUHJlZmVyRHVhbFN0YWNrCiAgICBsYWJlbHM6IHt9CiAgICBsb2FkQmFsYW5jZXJTb3VyY2VSYW5nZXM6IFtdCiAgICBub2RlUG9ydHM6IHt9CiAgICB0eXBlOiBDbHVzdGVySVAKICB0cmFlZmlrOgogICAgY29udGFpbmVyU2VjdXJpdHlDb250ZXh0OgogICAgICBhbGxvd1ByaXZpbGVnZUVzY2FsYXRpb246IGZhbHNlCiAgICAgIGNhcGFiaWxpdGllczoKICAgICAgICBkcm9wOgogICAgICAgIC0gQUxMCiAgICAgIHJ1bkFzR3JvdXA6IDY1NTM0CiAgICAgIHJ1bkFzTm9uUm9vdDogdHJ1ZQogICAgICBydW5Bc1VzZXI6IDY1NTM0CiAgICAgIHNlY2NvbXBQcm9maWxlOgogICAgICAgIHR5cGU6IFJ1bnRpbWVEZWZhdWx0CiAgICBleHRyYUR5bmFtaWNDb25maWc6IHt9CiAgICBleHRyYUVudjoge30KICAgIGV4dHJhSW5pdENvbnRhaW5lcnM6IFtdCiAgICBleHRyYVBvZFNwZWM6IHt9CiAgICBleHRyYVBvcnRzOiBbXQogICAgZXh0cmFTdGF0aWNDb25maWc6IHt9CiAgICBleHRyYVZvbHVtZU1vdW50czogW10KICAgIGV4dHJhVm9sdW1lczogW10KICAgIGhzdHM6CiAgICAgIGluY2x1ZGVTdWJkb21haW5zOiBmYWxzZQogICAgICBtYXhBZ2U6IDE1NzI0ODAwCiAgICAgIHByZWxvYWQ6IGZhbHNlCiAgICBpbWFnZToKICAgICAgbmFtZTogdHJhZWZpawogICAgICBwdWxsU2VjcmV0czogW10KICAgICAgdGFnOiB2My42LjQKICAgIGxhYmVsczoge30KICAgIG5ldHdvcmtQb2xpY3k6CiAgICAgIGFsbG93ZWRJbmdyZXNzUG9ydHM6CiAgICAgIC0gaHR0cAogICAgICAtIGh0dHBzCiAgICAgIGVncmVzczogW10KICAgICAgZWdyZXNzQWxsb3dSdWxlczoKICAgICAgICBjbG91ZE1ldGFkYXRhU2VydmVyOiB0cnVlCiAgICAgICAgZG5zUG9ydHNDbG91ZE1ldGFkYXRhU2VydmVyOiB0cnVlCiAgICAgICAgZG5zUG9ydHNLdWJlU3lzdGVtTmFtZXNwYWNlOiB0cnVlCiAgICAgICAgZG5zUG9ydHNQcml2YXRlSVBzOiB0cnVlCiAgICAgICAgbm9uUHJpdmF0ZUlQczogdHJ1ZQogICAgICAgIHByaXZhdGVJUHM6IHRydWUKICAgICAgZW5hYmxlZDogdHJ1ZQogICAgICBpbmdyZXNzOiBbXQogICAgICBpbnRlck5hbWVzcGFjZUFjY2Vzc0xhYmVsczogaWdub3JlCiAgICBub2RlU2VsZWN0b3I6IHt9CiAgICBwZGI6CiAgICAgIGVuYWJsZWQ6IGZhbHNlCiAgICAgIG1pbkF2YWlsYWJsZTogMQogICAgcmVzb3VyY2VzOiB7fQogICAgc2VydmljZUFjY291bnQ6CiAgICAgIGFubm90YXRpb25zOiB7fQogICAgICBjcmVhdGU6IHRydWUKICAgIHRvbGVyYXRpb25zOiBbXQpyYmFjOgogIGNyZWF0ZTogdHJ1ZQpzY2hlZHVsaW5nOgogIGNvcmVQb2RzOgogICAgbm9kZUFmZmluaXR5OgogICAgICBtYXRjaE5vZGVQdXJwb3NlOiBwcmVmZXIKICAgIHRvbGVyYXRpb25zOgogICAgLSBlZmZlY3Q6IE5vU2NoZWR1bGUKICAgICAga2V5OiBodWIuanVweXRlci5vcmcvZGVkaWNhdGVkCiAgICAgIG9wZXJhdG9yOiBFcXVhbAogICAgICB2YWx1ZTogY29yZQogICAgLSBlZmZlY3Q6IE5vU2NoZWR1bGUKICAgICAga2V5OiBodWIuanVweXRlci5vcmdfZGVkaWNhdGVkCiAgICAgIG9wZXJhdG9yOiBFcXVhbAogICAgICB2YWx1ZTogY29yZQogIHBvZFByaW9yaXR5OgogICAgZGVmYXVsdFByaW9yaXR5OiAwCiAgICBlbmFibGVkOiBmYWxzZQogICAgZ2xvYmFsRGVmYXVsdDogZmFsc2UKICAgIGltYWdlUHVsbGVyUHJpb3JpdHk6IC01CiAgICB1c2VyUGxhY2Vob2xkZXJQcmlvcml0eTogLTEwCiAgdXNlclBsYWNlaG9sZGVyOgogICAgYW5ub3RhdGlvbnM6IHt9CiAgICBjb250YWluZXJTZWN1cml0eUNvbnRleHQ6CiAgICAgIGFsbG93UHJpdmlsZWdlRXNjYWxhdGlvbjogZmFsc2UKICAgICAgY2FwYWJpbGl0aWVzOgogICAgICAgIGRyb3A6CiAgICAgICAgLSBBTEwKICAgICAgcnVuQXNHcm91cDogNjU1MzQKICAgICAgcnVuQXNOb25Sb290OiB0cnVlCiAgICAgIHJ1bkFzVXNlcjogNjU1MzQKICAgICAgc2VjY29tcFByb2ZpbGU6CiAgICAgICAgdHlwZTogUnVudGltZURlZmF1bHQKICAgIGVuYWJsZWQ6IHRydWUKICAgIGV4dHJhUG9kU3BlYzoge30KICAgIGltYWdlOgogICAgICBuYW1lOiByZWdpc3RyeS5rOHMuaW8vcGF1c2UKICAgICAgcHVsbFNlY3JldHM6IFtdCiAgICAgIHRhZzogMy4xMC4xCiAgICBsYWJlbHM6IHt9CiAgICByZXBsaWNhczogMAogICAgcmVzb3VyY2VzOiB7fQogIHVzZXJQb2RzOgogICAgbm9kZUFmZmluaXR5OgogICAgICBtYXRjaE5vZGVQdXJwb3NlOiBwcmVmZXIKICAgIHRvbGVyYXRpb25zOgogICAgLSBlZmZlY3Q6IE5vU2NoZWR1bGUKICAgICAga2V5OiBodWIuanVweXRlci5vcmcvZGVkaWNhdGVkCiAgICAgIG9wZXJhdG9yOiBFcXVhbAogICAgICB2YWx1ZTogdXNlcgogICAgLSBlZmZlY3Q6IE5vU2NoZWR1bGUKICAgICAga2V5OiBodWIuanVweXRlci5vcmdfZGVkaWNhdGVkCiAgICAgIG9wZXJhdG9yOiBFcXVhbAogICAgICB2YWx1ZTogdXNlcgogIHVzZXJTY2hlZHVsZXI6CiAgICBhbm5vdGF0aW9uczoge30KICAgIGNvbnRhaW5lclNlY3VyaXR5Q29udGV4dDoKICAgICAgYWxsb3dQcml2aWxlZ2VFc2NhbGF0aW9uOiBmYWxzZQogICAgICBjYXBhYmlsaXRpZXM6CiAgICAgICAgZHJvcDoKICAgICAgICAtIEFMTAogICAgICBydW5Bc0dyb3VwOiA2NTUzNAogICAgICBydW5Bc05vblJvb3Q6IHRydWUKICAgICAgcnVuQXNVc2VyOiA2NTUzNAogICAgICBzZWNjb21wUHJvZmlsZToKICAgICAgICB0eXBlOiBSdW50aW1lRGVmYXVsdAogICAgZW5hYmxlZDogdHJ1ZQogICAgZXh0cmFQb2RTcGVjOiB7fQogICAgaW1hZ2U6CiAgICAgIG5hbWU6IHJlZ2lzdHJ5Lms4cy5pby9rdWJlLXNjaGVkdWxlcgogICAgICBwdWxsU2VjcmV0czogW10KICAgICAgdGFnOiB2MS4zMC4xNAogICAgbGFiZWxzOiB7fQogICAgbG9nTGV2ZWw6IDQKICAgIG5vZGVTZWxlY3Rvcjoge30KICAgIHBkYjoKICAgICAgZW5hYmxlZDogdHJ1ZQogICAgICBtYXhVbmF2YWlsYWJsZTogMQogICAgcGx1Z2luQ29uZmlnOgogICAgLSBhcmdzOgogICAgICAgIHNjb3JpbmdTdHJhdGVneToKICAgICAgICAgIHJlc291cmNlczoKICAgICAgICAgIC0gbmFtZTogY3B1CiAgICAgICAgICAgIHdlaWdodDogMQogICAgICAgICAgLSBuYW1lOiBtZW1vcnkKICAgICAgICAgICAgd2VpZ2h0OiAxCiAgICAgICAgICB0eXBlOiBNb3N0QWxsb2NhdGVkCiAgICAgIG5hbWU6IE5vZGVSZXNvdXJjZXNGaXQKICAgIHBsdWdpbnM6CiAgICAgIHNjb3JlOgogICAgICAgIGRpc2FibGVkOgogICAgICAgIC0gbmFtZTogTm9kZVJlc291cmNlc0JhbGFuY2VkQWxsb2NhdGlvbgogICAgICAgIC0gbmFtZTogTm9kZUFmZmluaXR5CiAgICAgICAgLSBuYW1lOiBJbnRlclBvZEFmZmluaXR5CiAgICAgICAgLSBuYW1lOiBOb2RlUmVzb3VyY2VzRml0CiAgICAgICAgLSBuYW1lOiBJbWFnZUxvY2FsaXR5CiAgICAgICAgZW5hYmxlZDoKICAgICAgICAtIG5hbWU6IE5vZGVBZmZpbml0eQogICAgICAgICAgd2VpZ2h0OiAxNDYzMQogICAgICAgIC0gbmFtZTogSW50ZXJQb2RBZmZpbml0eQogICAgICAgICAgd2VpZ2h0OiAxMzMxCiAgICAgICAgLSBuYW1lOiBOb2RlUmVzb3VyY2VzRml0CiAgICAgICAgICB3ZWlnaHQ6IDEyMQogICAgICAgIC0gbmFtZTogSW1hZ2VMb2NhbGl0eQogICAgICAgICAgd2VpZ2h0OiAxMQogICAgcmVwbGljYXM6IDEKICAgIHJlc291cmNlczoge30KICAgIHNlcnZpY2VBY2NvdW50OgogICAgICBhbm5vdGF0aW9uczoge30KICAgICAgY3JlYXRlOiB0cnVlCiAgICB0b2xlcmF0aW9uczogW10Kc2luZ2xldXNlcjoKICBhbGxvd1ByaXZpbGVnZUVzY2FsYXRpb246IGZhbHNlCiAgY2xvdWRNZXRhZGF0YToKICAgIGJsb2NrV2l0aElwdGFibGVzOiB0cnVlCiAgICBpcDogMTY5LjI1NC4xNjkuMjU0CiAgY21kOgogIC0ganVweXRlcmh1Yi1zaW5nbGV1c2VyCiAgY3B1OiB7fQogIGV2ZW50czogdHJ1ZQogIGV4dHJhQW5ub3RhdGlvbnM6IHt9CiAgZXh0cmFDb250YWluZXJzOiBbXQogIGV4dHJhRW52OiB7fQogIGV4dHJhRmlsZXM6IHt9CiAgZXh0cmFMYWJlbHM6CiAgICBodWIuanVweXRlci5vcmcvbmV0d29yay1hY2Nlc3MtaHViOiAidHJ1ZSIKICBleHRyYU5vZGVBZmZpbml0eToKICAgIHByZWZlcnJlZDogW10KICAgIHJlcXVpcmVkOiBbXQogIGV4dHJhUG9kQWZmaW5pdHk6CiAgICBwcmVmZXJyZWQ6IFtdCiAgICByZXF1aXJlZDogW10KICBleHRyYVBvZEFudGlBZmZpbml0eToKICAgIHByZWZlcnJlZDogW10KICAgIHJlcXVpcmVkOiBbXQogIGV4dHJhUG9kQ29uZmlnOgogICAgc2VjdXJpdHlDb250ZXh0OgogICAgICBydW5Bc0dyb3VwOiAwCiAgICAgIHJ1bkFzVXNlcjogMAogIGV4dHJhUmVzb3VyY2U6CiAgICBndWFyYW50ZWVzOiB7fQogICAgbGltaXRzOiB7fQogIGV4dHJhVG9sZXJhdGlvbnM6IFtdCiAgZnNHaWQ6IDAKICBpbWFnZToKICAgIG5hbWU6IGNvZ3N0YWNrc3lzdGVtcy9qdXB5dGVyLXNpbmdsZXVzZXIKICAgIHB1bGxQb2xpY3k6IElmTm90UHJlc2VudAogICAgcHVsbFNlY3JldHM6IFtdCiAgICB0YWc6IDIuMy42CiAgaW5pdENvbnRhaW5lcnM6IFtdCiAgbGlmZWN5Y2xlSG9va3M6CiAgICBwb3N0U3RhcnQ6CiAgICAgIGV4ZWM6CiAgICAgICAgY29tbWFuZDoKICAgICAgICAtIHNoCiAgICAgICAgLSAtYwogICAgICAgIC0gfAogICAgICAgICAgaWYgWyAhIC1mIC9ob21lL2pvdnlhbi93b3JrLy5ub3RlYm9va3NfaW5pdGlhbGl6ZWQgXTsgdGhlbgogICAgICAgICAgICBlY2hvICJGaXJzdCBydW4gLSBjb3B5aW5nIG5vdGVib29rcyBhbmQgbWVkY2F0LXNjcmlwdHMuLi4iOwogICAgICAgICAgICBjcCAtciAvc3J2L2p1cHl0ZXJodWIvbm90ZWJvb2tzLyogL2hvbWUvam92eWFuL3dvcmsvOwogICAgICAgICAgICBjcCAtciAvc3J2L2p1cHl0ZXJodWIvbWVkY2F0LXNjcmlwdHMgL2hvbWUvam92eWFuL3dvcmsvOwogICAgICAgICAgICB0b3VjaCAvaG9tZS9qb3Z5YW4vd29yay8ubm90ZWJvb2tzX2luaXRpYWxpemVkOwogICAgICAgICAgICBlY2hvICJOb3RlYm9va3MgaW5pdGlhbGl6ZWQgc3VjY2Vzc2Z1bGx5IjsKICAgICAgICAgIGVsc2UKICAgICAgICAgICAgZWNobyAiTm90ZWJvb2tzIGFscmVhZHkgaW5pdGlhbGl6ZWQgLSBza2lwcGluZyI7CiAgICAgICAgICBmaQogIG1lbW9yeToKICAgIGd1YXJhbnRlZTogMUcKICBuZXR3b3JrUG9saWN5OgogICAgYWxsb3dlZEluZ3Jlc3NQb3J0czogW10KICAgIGVncmVzczogW10KICAgIGVncmVzc0FsbG93UnVsZXM6CiAgICAgIGNsb3VkTWV0YWRhdGFTZXJ2ZXI6IGZhbHNlCiAgICAgIGRuc1BvcnRzQ2xvdWRNZXRhZGF0YVNlcnZlcjogdHJ1ZQogICAgICBkbnNQb3J0c0t1YmVTeXN0ZW1OYW1lc3BhY2U6IHRydWUKICAgICAgZG5zUG9ydHNQcml2YXRlSVBzOiB0cnVlCiAgICAgIG5vblByaXZhdGVJUHM6IHRydWUKICAgICAgcHJpdmF0ZUlQczogZmFsc2UKICAgIGVuYWJsZWQ6IGZhbHNlCiAgICBpbmdyZXNzOiBbXQogICAgaW50ZXJOYW1lc3BhY2VBY2Nlc3NMYWJlbHM6IGlnbm9yZQogIG5ldHdvcmtUb29sczoKICAgIGltYWdlOgogICAgICBuYW1lOiBxdWF5LmlvL2p1cHl0ZXJodWIvazhzLW5ldHdvcmstdG9vbHMKICAgICAgcHVsbFNlY3JldHM6IFtdCiAgICAgIHRhZzogNC4zLjIKICAgIHJlc291cmNlczoge30KICBub2RlU2VsZWN0b3I6IHt9CiAgcHJvZmlsZUxpc3Q6IFtdCiAgc3RhcnRUaW1lb3V0OiA2MDAKICBzdG9yYWdlOgogICAgY2FwYWNpdHk6IDVHaQogICAgZHluYW1pYzoKICAgICAgc3RvcmFnZUFjY2Vzc01vZGVzOgogICAgICAtIFJlYWRXcml0ZU9uY2UKICAgICAgdm9sdW1lTmFtZVRlbXBsYXRlOiB2b2x1bWUte3VzZXJfc2VydmVyfQogICAgZXh0cmFMYWJlbHM6IHt9CiAgICBleHRyYVZvbHVtZU1vdW50czoKICAgICAganVweXRlci1leGFtcGxlczoKICAgICAgICBtb3VudFBhdGg6IC9ob21lL2pvdnlhbi93b3JrL2V4YW1wbGVzCiAgICAgICAgbmFtZToganVweXRlci1leGFtcGxlcwogICAgICAgIHJlYWRPbmx5OiB0cnVlCiAgICBleHRyYVZvbHVtZXM6CiAgICAgIGp1cHl0ZXItZXhhbXBsZXM6CiAgICAgICAgY29uZmlnTWFwOgogICAgICAgICAgbmFtZToganVweXRlci1leGFtcGxlcwogICAgICAgIG5hbWU6IGp1cHl0ZXItZXhhbXBsZXMKICAgIGhvbWVNb3VudFBhdGg6IC9ob21lL2pvdnlhbgogICAgc3RhdGljOgogICAgICBzdWJQYXRoOiAne3VzZXJuYW1lfScKICAgIHR5cGU6IGR5bmFtaWMKICB1aWQ6IDA=" + + # Any JupyterHub Services api_tokens are exposed in this k8s Secret as a + # convinience for external services running in the k8s cluster that could + # mount them directly from this k8s Secret. + + # During Helm template rendering, these values that can be autogenerated for + # users are set using the following logic: + # + # 1. Use chart configuration's value + # 2. Use k8s Secret's value + # 3. Use a new autogenerated value + # + # hub.config.ConfigurableHTTPProxy.auth_token: for hub to proxy-api authorization (JupyterHub.proxy_auth_token is deprecated) + # hub.config.JupyterHub.cookie_secret: for cookie encryption + # hub.config.CryptKeeper.keys: for auth state encryption + # + hub.config.ConfigurableHTTPProxy.auth_token: "U3BSZUdMQWhaUnR3MG8yejlHcVcxU3hGbkJNWkpwaXFTcFJLSzVCOGkyeUwzZFJqSXVwZjlHd2U5ZjlBeWRMUg==" + hub.config.JupyterHub.cookie_secret: "ZDUwMjYzZTQyMTYzOWU2MGQ5MmU1N2RiZTk4ODA0NGI2YTVjZDRiMjZiZTIwNGE0YWE3YmRiMGFmZjAwYTYzMQ==" + hub.config.CryptKeeper.keys: "Mzg3NzkyMzA2YWE4NmNhZjdlNzJjNzAwYmU2NjlkNWE2NmNlODYzYWZhNzY2YjBmNDdkYzM4OTYyYmE4YzE0Ng==" + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/configmap.yaml +kind: ConfigMap +apiVersion: v1 +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +data: + fullname: "" + fullname-dash: "" + hub: "hub" + hub-serviceaccount: "hub" + hub-existing-secret: "" + hub-existing-secret-or-default: "hub" + hub-pvc: "hub-db-dir" + proxy: "proxy" + proxy-api: "proxy-api" + proxy-http: "proxy-http" + proxy-public: "proxy-public" + proxy-public-tls: "proxy-public-tls-acme" + proxy-public-manual-tls: "proxy-public-manual-tls" + autohttps: "autohttps" + autohttps-serviceaccount: "autohttps" + user-scheduler-deploy: "user-scheduler" + user-scheduler-serviceaccount: "user-scheduler" + user-scheduler-lock: "user-scheduler-lock" + user-placeholder: "user-placeholder" + image-puller-priority: "jupyterhub-image-puller-priority" + hook-image-awaiter: "hook-image-awaiter" + hook-image-awaiter-serviceaccount: "hook-image-awaiter" + hook-image-puller: "hook-image-puller" + hook-image-puller-serviceaccount: "hook-image-puller" + continuous-image-puller: "continuous-image-puller" + continuous-image-puller-serviceaccount: "continuous-image-puller" + singleuser: "singleuser" + image-pull-secret: "image-pull-secret" + ingress: "jupyterhub" + priority: "jupyterhub-default-priority" + user-placeholder-priority: "jupyterhub-user-placeholder-priority" + user-scheduler: "jupyterhub-user-scheduler" + jupyterhub_config.py: | + # load the config object (satisfies linters) + c = get_config() # noqa + + import glob + import os + import re + import sys + + from jupyterhub.utils import url_path_join + from kubernetes_asyncio import client + from tornado.httpclient import AsyncHTTPClient + + # Make sure that modules placed in the same directory as the jupyterhub config are added to the pythonpath + configuration_directory = os.path.dirname(os.path.realpath(__file__)) + sys.path.insert(0, configuration_directory) + + from z2jh import ( + get_config, + get_name, + get_name_env, + get_secret_value, + set_config_if_not_none, + ) + + + def camelCaseify(s): + """convert snake_case to camelCase + + For the common case where some_value is set from someValue + so we don't have to specify the name twice. + """ + return re.sub(r"_([a-z])", lambda m: m.group(1).upper(), s) + + + # Configure JupyterHub to use the curl backend for making HTTP requests, + # rather than the pure-python implementations. The default one starts + # being too slow to make a large number of requests to the proxy API + # at the rate required. + AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") + + c.JupyterHub.spawner_class = "kubespawner.KubeSpawner" + + # Connect to a proxy running in a different pod. Note that *_SERVICE_* + # environment variables are set by Kubernetes for Services + c.ConfigurableHTTPProxy.api_url = ( + f'http://{get_name("proxy-api")}:{get_name_env("proxy-api", "_SERVICE_PORT")}' + ) + c.ConfigurableHTTPProxy.should_start = False + + # Do not shut down user pods when hub is restarted + c.JupyterHub.cleanup_servers = False + + # Check that the proxy has routes appropriately setup + c.JupyterHub.last_activity_interval = 60 + + # Don't wait at all before redirecting a spawning user to the progress page + c.JupyterHub.tornado_settings = { + "slow_spawn_timeout": 0, + } + + + # configure the hub db connection + db_type = get_config("hub.db.type") + if db_type == "sqlite-pvc": + c.JupyterHub.db_url = "sqlite:///jupyterhub.sqlite" + elif db_type == "sqlite-memory": + c.JupyterHub.db_url = "sqlite://" + else: + set_config_if_not_none(c.JupyterHub, "db_url", "hub.db.url") + db_password = get_secret_value("hub.db.password", None) + if db_password is not None: + if db_type == "mysql": + os.environ["MYSQL_PWD"] = db_password + elif db_type == "postgres": + os.environ["PGPASSWORD"] = db_password + else: + print(f"Warning: hub.db.password is ignored for hub.db.type={db_type}") + + + # c.JupyterHub configuration from Helm chart's configmap + for trait, cfg_key in ( + ("concurrent_spawn_limit", None), + ("active_server_limit", None), + ("base_url", None), + ("allow_named_servers", None), + ("named_server_limit_per_user", None), + ("authenticate_prometheus", None), + ("redirect_to_server", None), + ("shutdown_on_logout", None), + ("template_paths", None), + ("template_vars", None), + ): + if cfg_key is None: + cfg_key = camelCaseify(trait) + set_config_if_not_none(c.JupyterHub, trait, "hub." + cfg_key) + + # hub_bind_url configures what the JupyterHub process within the hub pod's + # container should listen to. + hub_container_port = 8081 + c.JupyterHub.hub_bind_url = f"http://:{hub_container_port}" + + # hub_connect_url is the URL for connecting to the hub for use by external + # JupyterHub services such as the proxy. Note that *_SERVICE_* environment + # variables are set by Kubernetes for Services. + c.JupyterHub.hub_connect_url = ( + f'http://{get_name("hub")}:{get_name_env("hub", "_SERVICE_PORT")}' + ) + + # implement common labels + # This mimics the jupyterhub.commonLabels helper, but declares managed-by to + # kubespawner instead of helm. + # + # The labels app and release are old labels enabled to be deleted in z2jh 5, but + # for now retained to avoid a breaking change in z2jh 4 that would force user + # server restarts. Restarts would be required because NetworkPolicy resources + # must select old/new pods with labels that then needs to be seen on both + # old/new pods, and we want these resources to keep functioning for old/new user + # server pods during an upgrade. + # + common_labels = c.KubeSpawner.common_labels = {} + common_labels["app.kubernetes.io/name"] = common_labels["app"] = get_config( + "nameOverride", + default=get_config("Chart.Name", "jupyterhub"), + ) + release = get_config("Release.Name") + if release: + common_labels["app.kubernetes.io/instance"] = common_labels["release"] = release + chart_name = get_config("Chart.Name") + chart_version = get_config("Chart.Version") + if chart_name and chart_version: + common_labels["helm.sh/chart"] = common_labels["chart"] = ( + f"{chart_name}-{chart_version.replace('+', '_')}" + ) + common_labels["app.kubernetes.io/managed-by"] = "kubespawner" + + c.KubeSpawner.namespace = os.environ.get("POD_NAMESPACE", "default") + + # Max number of consecutive failures before the Hub restarts itself + set_config_if_not_none( + c.Spawner, + "consecutive_failure_limit", + "hub.consecutiveFailureLimit", + ) + + for trait, cfg_key in ( + ("pod_name_template", None), + ("start_timeout", None), + ("image_pull_policy", "image.pullPolicy"), + # ('image_pull_secrets', 'image.pullSecrets'), # Managed manually below + ("events_enabled", "events"), + ("extra_labels", None), + ("extra_annotations", None), + # ("allow_privilege_escalation", None), # Managed manually below + ("uid", None), + ("fs_gid", None), + ("service_account", "serviceAccountName"), + ("storage_extra_labels", "storage.extraLabels"), + # ("tolerations", "extraTolerations"), # Managed manually below + ("node_selector", None), + ("node_affinity_required", "extraNodeAffinity.required"), + ("node_affinity_preferred", "extraNodeAffinity.preferred"), + ("pod_affinity_required", "extraPodAffinity.required"), + ("pod_affinity_preferred", "extraPodAffinity.preferred"), + ("pod_anti_affinity_required", "extraPodAntiAffinity.required"), + ("pod_anti_affinity_preferred", "extraPodAntiAffinity.preferred"), + ("lifecycle_hooks", None), + ("init_containers", None), + ("extra_containers", None), + ("mem_limit", "memory.limit"), + ("mem_guarantee", "memory.guarantee"), + ("cpu_limit", "cpu.limit"), + ("cpu_guarantee", "cpu.guarantee"), + ("extra_resource_limits", "extraResource.limits"), + ("extra_resource_guarantees", "extraResource.guarantees"), + ("environment", "extraEnv"), + ("profile_list", None), + ("extra_pod_config", None), + ): + if cfg_key is None: + cfg_key = camelCaseify(trait) + set_config_if_not_none(c.KubeSpawner, trait, "singleuser." + cfg_key) + + image = get_config("singleuser.image.name") + if image: + tag = get_config("singleuser.image.tag") + if tag: + image = f"{image}:{tag}" + + c.KubeSpawner.image = image + + # allow_privilege_escalation defaults to False in KubeSpawner 2+. Since its a + # property where None, False, and True all are valid values that users of the + # Helm chart may want to set, we can't use the set_config_if_not_none helper + # function as someone may want to override the default False value to None. + # + c.KubeSpawner.allow_privilege_escalation = get_config( + "singleuser.allowPrivilegeEscalation" + ) + + # Combine imagePullSecret.create (single), imagePullSecrets (list), and + # singleuser.image.pullSecrets (list). + image_pull_secrets = [] + if get_config("imagePullSecret.automaticReferenceInjection") and get_config( + "imagePullSecret.create" + ): + image_pull_secrets.append(get_name("image-pull-secret")) + if get_config("imagePullSecrets"): + image_pull_secrets.extend(get_config("imagePullSecrets")) + if get_config("singleuser.image.pullSecrets"): + image_pull_secrets.extend(get_config("singleuser.image.pullSecrets")) + if image_pull_secrets: + c.KubeSpawner.image_pull_secrets = image_pull_secrets + + # scheduling: + if get_config("scheduling.userScheduler.enabled"): + c.KubeSpawner.scheduler_name = get_name("user-scheduler") + if get_config("scheduling.podPriority.enabled"): + c.KubeSpawner.priority_class_name = get_name("priority") + + # add node-purpose affinity + match_node_purpose = get_config("scheduling.userPods.nodeAffinity.matchNodePurpose") + if match_node_purpose: + node_selector = dict( + matchExpressions=[ + dict( + key="hub.jupyter.org/node-purpose", + operator="In", + values=["user"], + ) + ], + ) + if match_node_purpose == "prefer": + c.KubeSpawner.node_affinity_preferred.append( + dict( + weight=100, + preference=node_selector, + ), + ) + elif match_node_purpose == "require": + c.KubeSpawner.node_affinity_required.append(node_selector) + elif match_node_purpose == "ignore": + pass + else: + raise ValueError( + f"Unrecognized value for matchNodePurpose: {match_node_purpose}" + ) + + # Combine the common tolerations for user pods with singleuser tolerations + scheduling_user_pods_tolerations = get_config("scheduling.userPods.tolerations", []) + singleuser_extra_tolerations = get_config("singleuser.extraTolerations", []) + tolerations = scheduling_user_pods_tolerations + singleuser_extra_tolerations + if tolerations: + c.KubeSpawner.tolerations = tolerations + + volumes = {} + volume_mounts = {} + + # Configure dynamically provisioning pvc + storage_type = get_config("singleuser.storage.type") + if storage_type == "dynamic": + pvc_name_template = get_config("singleuser.storage.dynamic.pvcNameTemplate") + if pvc_name_template: + c.KubeSpawner.pvc_name_template = pvc_name_template + volume_name_template = get_config("singleuser.storage.dynamic.volumeNameTemplate") + c.KubeSpawner.storage_pvc_ensure = True + set_config_if_not_none( + c.KubeSpawner, "storage_class", "singleuser.storage.dynamic.storageClass" + ) + set_config_if_not_none( + c.KubeSpawner, + "storage_access_modes", + "singleuser.storage.dynamic.storageAccessModes", + ) + set_config_if_not_none( + c.KubeSpawner, "storage_capacity", "singleuser.storage.capacity" + ) + + # Add volumes to singleuser pods + volumes = { + volume_name_template: { + "name": volume_name_template, + "persistentVolumeClaim": {"claimName": "{pvc_name}"}, + } + } + volume_mounts = { + volume_name_template: { + "mountPath": get_config("singleuser.storage.homeMountPath"), + "name": volume_name_template, + "subPath": get_config("singleuser.storage.dynamic.subPath"), + } + } + elif storage_type == "static": + pvc_claim_name = get_config("singleuser.storage.static.pvcName") + volumes = { + "home": { + "name": "home", + "persistentVolumeClaim": {"claimName": pvc_claim_name}, + } + } + + volume_mounts = { + "home": { + "mountPath": get_config("singleuser.storage.homeMountPath"), + "name": "home", + "subPath": get_config("singleuser.storage.static.subPath"), + } + } + + # Inject singleuser.extraFiles as volumes and volumeMounts with data loaded from + # the dedicated k8s Secret prepared to hold the extraFiles actual content. + extra_files = get_config("singleuser.extraFiles", {}) + if extra_files: + volume = { + "name": "files", + } + items = [] + for file_key, file_details in extra_files.items(): + # Each item is a mapping of a key in the k8s Secret to a path in this + # abstract volume, the goal is to enable us to set the mode / + # permissions only though so we don't change the mapping. + item = { + "key": file_key, + "path": file_key, + } + if "mode" in file_details: + item["mode"] = file_details["mode"] + items.append(item) + volume["secret"] = { + "secretName": get_name("singleuser"), + "items": items, + } + volumes[volume["name"]] = volume + + for idx, (file_key, file_details) in enumerate(extra_files.items()): + volume_mount = { + "mountPath": file_details["mountPath"], + "subPath": file_key, + "name": "files", + } + volume_mounts[f"{idx}-files"] = volume_mount + + # Inject extraVolumes / extraVolumeMounts + extra_volumes = get_config("singleuser.storage.extraVolumes", default={}) + if isinstance(extra_volumes, dict): + volumes.update(extra_volumes) + elif isinstance(extra_volumes, list): + for volume in extra_volumes: + volumes[volume["name"]] = volume + + extra_volume_mounts = get_config("singleuser.storage.extraVolumeMounts", default={}) + if isinstance(extra_volume_mounts, dict): + volume_mounts.update(extra_volume_mounts) + elif isinstance(extra_volume_mounts, list): + # If extraVolumeMounts is a list, we need to add them to the volume_mounts + # dictionary with a unique key. + # Since volume mount's name is not guaranteed to be unique, we use the index + # as part of the key. + for idx, volume_mount in enumerate(extra_volume_mounts): + volume_mounts[f"{idx}-{volume_mount['name']}"] = volume_mount + + c.KubeSpawner.volumes = volumes + c.KubeSpawner.volume_mounts = volume_mounts + + c.JupyterHub.services = [] + c.JupyterHub.load_roles = [] + + # jupyterhub-idle-culler's permissions are scoped to what it needs only, see + # https://github.com/jupyterhub/jupyterhub-idle-culler#permissions. + # + if get_config("cull.enabled", False): + jupyterhub_idle_culler_role = { + "name": "jupyterhub-idle-culler", + "scopes": [ + "list:users", + "read:users:activity", + "read:servers", + "delete:servers", + # "admin:users", # dynamically added if --cull-users is passed + ], + # assign the role to a jupyterhub service, so it gains these permissions + "services": ["jupyterhub-idle-culler"], + } + + cull_cmd = ["python3", "-m", "jupyterhub_idle_culler"] + base_url = c.JupyterHub.get("base_url", "/") + cull_cmd.append("--url=http://localhost:8081" + url_path_join(base_url, "hub/api")) + + cull_timeout = get_config("cull.timeout") + if cull_timeout: + cull_cmd.append(f"--timeout={cull_timeout}") + + cull_every = get_config("cull.every") + if cull_every: + cull_cmd.append(f"--cull-every={cull_every}") + + cull_concurrency = get_config("cull.concurrency") + if cull_concurrency: + cull_cmd.append(f"--concurrency={cull_concurrency}") + + if get_config("cull.users"): + cull_cmd.append("--cull-users") + jupyterhub_idle_culler_role["scopes"].append("admin:users") + + if not get_config("cull.adminUsers"): + cull_cmd.append("--cull-admin-users=false") + + if get_config("cull.removeNamedServers"): + cull_cmd.append("--remove-named-servers") + + cull_max_age = get_config("cull.maxAge") + if cull_max_age: + cull_cmd.append(f"--max-age={cull_max_age}") + + c.JupyterHub.services.append( + { + "name": "jupyterhub-idle-culler", + "command": cull_cmd, + } + ) + c.JupyterHub.load_roles.append(jupyterhub_idle_culler_role) + + for key, service in get_config("hub.services", {}).items(): + # c.JupyterHub.services is a list of dicts, but + # hub.services is a dict of dicts to make the config mergable + service.setdefault("name", key) + + # As the api_token could be exposed in hub.existingSecret, we need to read + # it it from there or fall back to the chart managed k8s Secret's value. + service.pop("apiToken", None) + service["api_token"] = get_secret_value(f"hub.services.{key}.apiToken") + + c.JupyterHub.services.append(service) + + for key, role in get_config("hub.loadRoles", {}).items(): + # c.JupyterHub.load_roles is a list of dicts, but + # hub.loadRoles is a dict of dicts to make the config mergable + role.setdefault("name", key) + + c.JupyterHub.load_roles.append(role) + + # respect explicit null command (distinct from unspecified) + # this avoids relying on KubeSpawner.cmd's default being None + _unspecified = object() + specified_cmd = get_config("singleuser.cmd", _unspecified) + if specified_cmd is not _unspecified: + c.Spawner.cmd = specified_cmd + + set_config_if_not_none(c.Spawner, "default_url", "singleuser.defaultUrl") + + cloud_metadata = get_config("singleuser.cloudMetadata") + + if cloud_metadata.get("blockWithIptables") == True: + # Use iptables to block access to cloud metadata by default + network_tools_image_name = get_config("singleuser.networkTools.image.name") + network_tools_image_tag = get_config("singleuser.networkTools.image.tag") + network_tools_resources = get_config("singleuser.networkTools.resources") + ip = cloud_metadata["ip"] + ip_block_container = client.V1Container( + name="block-cloud-metadata", + image=f"{network_tools_image_name}:{network_tools_image_tag}", + command=[ + "iptables", + "--append", + "OUTPUT", + "--protocol", + "tcp", + "--destination", + ip, + "--destination-port", + "80", + "--jump", + "DROP", + ], + security_context=client.V1SecurityContext( + privileged=True, + run_as_user=0, + capabilities=client.V1Capabilities(add=["NET_ADMIN"]), + ), + resources=network_tools_resources, + ) + + c.KubeSpawner.init_containers.append(ip_block_container) + + + if get_config("debug.enabled", False): + c.JupyterHub.log_level = "DEBUG" + c.Spawner.debug = True + + # load potentially seeded secrets + # + # NOTE: ConfigurableHTTPProxy.auth_token is set through an environment variable + # that is set using the chart managed secret. + c.JupyterHub.cookie_secret = get_secret_value("hub.config.JupyterHub.cookie_secret") + # NOTE: CryptKeeper.keys should be a list of strings, but we have encoded as a + # single string joined with ; in the k8s Secret. + # + c.CryptKeeper.keys = get_secret_value("hub.config.CryptKeeper.keys").split(";") + + # load hub.config values, except potentially seeded secrets already loaded + for section, cfg in get_config("hub.config", {}).items(): + if section == "JupyterHub": + cfg.pop("proxy_auth_token", None) + cfg.pop("cookie_secret", None) + cfg.pop("services", None) + elif section == "ConfigurableHTTPProxy": + cfg.pop("auth_token", None) + elif section == "CryptKeeper": + cfg.pop("keys", None) + + if not section[:1].isupper(): + # traitlets config sections are Configurable class names + # that MUST start with upper-case + # if it starts with lowercase, it must be a mistake + # (e.g. putting `hub.loadRoles` under `hub.config.loadRoles`), + # and will have no effect, so warn or raise here + print( + f"FATAL: Invalid hub.config section name: {section}." + " hub.config sections must be Configurable class names (e.g. JupyterHub)." + " Maybe misplaced or misspelled config?", + file=sys.stderr, + ) + # make this fatal: + sys.exit(1) + + print(f"Loading pass-through config section hub.config.{section}") + c[section].update(cfg) + + # load /usr/local/etc/jupyterhub/jupyterhub_config.d config files + config_dir = "/usr/local/etc/jupyterhub/jupyterhub_config.d" + if os.path.isdir(config_dir): + for file_path in sorted(glob.glob(f"{config_dir}/*.py")): + file_name = os.path.basename(file_path) + print(f"Loading {config_dir} config: {file_name}") + with open(file_path) as f: + file_content = f.read() + # compiling makes debugging easier: https://stackoverflow.com/a/437857 + exec(compile(source=file_content, filename=file_name, mode="exec")) + + # execute hub.extraConfig entries + for key, config_py in sorted(get_config("hub.extraConfig", {}).items()): + print(f"Loading extra config: {key}") + exec(config_py) + z2jh.py: | + """ + Utility methods for use in jupyterhub_config.py and dynamic subconfigs. + + Methods here can be imported by extraConfig in values.yaml + """ + + import os + from collections.abc import Mapping + from functools import lru_cache + + import yaml + + + # memoize so we only load config once + @lru_cache + def _load_config(): + """Load the Helm chart configuration used to render the Helm templates of + the chart from a mounted k8s Secret, and merge in values from an optionally + mounted secret (hub.existingSecret).""" + + cfg = {} + for source in ("secret/values.yaml", "existing-secret/values.yaml"): + path = f"/usr/local/etc/jupyterhub/{source}" + if os.path.exists(path): + print(f"Loading {path}") + with open(path) as f: + values = yaml.safe_load(f) + cfg = _merge_dictionaries(cfg, values) + else: + print(f"No config at {path}") + return cfg + + + @lru_cache + def _get_config_value(key): + """Load value from the k8s ConfigMap given a key.""" + + path = f"/usr/local/etc/jupyterhub/config/{key}" + if os.path.exists(path): + with open(path) as f: + return f.read() + else: + raise Exception(f"{path} not found!") + + + @lru_cache + def get_secret_value(key, default="never-explicitly-set"): + """Load value from the user managed k8s Secret or the default k8s Secret + given a key.""" + + for source in ("existing-secret", "secret"): + path = f"/usr/local/etc/jupyterhub/{source}/{key}" + if os.path.exists(path): + with open(path) as f: + return f.read() + if default != "never-explicitly-set": + return default + raise Exception(f"{key} not found in either k8s Secret!") + + + def get_name(name): + """Returns the fullname of a resource given its short name""" + return _get_config_value(name) + + + def get_name_env(name, suffix=""): + """Returns the fullname of a resource given its short name along with a + suffix, converted to uppercase with dashes replaced with underscores. This + is useful to reference named services associated environment variables, such + as PROXY_PUBLIC_SERVICE_PORT.""" + env_key = _get_config_value(name) + suffix + env_key = env_key.upper().replace("-", "_") + return os.environ[env_key] + + + def _merge_dictionaries(a, b): + """Merge two dictionaries recursively. + + Simplified From https://stackoverflow.com/a/7205107 + """ + merged = a.copy() + for key in b: + if key in a: + if isinstance(a[key], Mapping) and isinstance(b[key], Mapping): + merged[key] = _merge_dictionaries(a[key], b[key]) + else: + merged[key] = b[key] + else: + merged[key] = b[key] + return merged + + + def get_config(key, default=None): + """ + Find a config item of a given name & return it + + Parses everything as YAML, so lists and dicts are available too + + get_config("a.b.c") returns config['a']['b']['c'] + """ + value = _load_config() + # resolve path in yaml + for level in key.split("."): + if not isinstance(value, dict): + # a parent is a scalar or null, + # can't resolve full path + return default + if level not in value: + return default + else: + value = value[level] + return value + + + def set_config_if_not_none(cparent, name, key): + """ + Find a config item of a given name, set the corresponding Jupyter + configuration item if not None + """ + data = get_config(key) + if data is not None: + setattr(cparent, name, data) + checksum_hook-image-puller: "3a29462d49c0efbd3eb438d883e8f495a408680e5a08aede22fdc6cf229f77b4" + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-scheduler/configmap.yaml +kind: ConfigMap +apiVersion: v1 +metadata: + name: user-scheduler + labels: + component: user-scheduler + app.kubernetes.io/component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +data: + config.yaml: | + apiVersion: kubescheduler.config.k8s.io/v1 + kind: KubeSchedulerConfiguration + leaderElection: + resourceLock: leases + resourceName: user-scheduler-lock + resourceNamespace: "default" + profiles: + - schedulerName: jupyterhub-user-scheduler + plugins: + score: + disabled: + - name: NodeResourcesBalancedAllocation + - name: NodeAffinity + - name: InterPodAffinity + - name: NodeResourcesFit + - name: ImageLocality + enabled: + - name: NodeAffinity + weight: 14631 + - name: InterPodAffinity + weight: 1331 + - name: NodeResourcesFit + weight: 121 + - name: ImageLocality + weight: 11 + pluginConfig: + - args: + scoringStrategy: + resources: + - name: cpu + weight: 1 + - name: memory + weight: 1 + type: MostAllocated + name: NodeResourcesFit + +--- +# Source: jupyterhub-helm/templates/examples-configmap.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: jupyter-examples +data: + medcat-opensearch-e2e.ipynb: | + { + "cells": [ + { + "cell_type": "markdown", + "id": "a7844791", + "metadata": {}, + "source": [ + "# MedCAT + OpenSearch End-to-End Demo\n", + "\n", + "This is a short, practical walkthrough showing how to turn one clinical note into searchable concepts.\n", + "\n", + "It is an end to end example of how you can use CogStack to unlock the power of your healthcare data.\n", + "\n", + "## Overview\n", + "\n", + "### Who this is for\n", + "This is for developers, data engineers, and analysts who want to see a practical example of how CogStack, MedCAT and Opensearch can be integrated to let you perform advanced search on your notes. \n", + "\n", + "### What this notebook does\n", + "1. Index one sample note into `discharge`\n", + "2. Search that note back using free text\n", + "3. Search that note back even when we have typos\n", + "4. Perform Named Entity Resolution (NER) by calling MedCAT Service and index them\n", + "5. Search notes by concept\n", + "\n", + "The goal is to show that this process is straightforward: call one API, index results, and query them.\n", + "\n", + "### Prerequisites\n", + "The best way to run this notebook interactively is to run the CogStack Community Edition with Helm. Look at https://docs.cogstack.org/ to get started." + ] + }, + { + "cell_type": "markdown", + "id": "875a64db", + "metadata": {}, + "source": [ + "## Initialisation: Define the inputs and services\n", + "\n", + "### Input Data\n", + "We define a short input for this tutorial. This represents your free text patient data, for example a discharge summary or long doctors note.\n", + "\n", + "The sample sentence contains concepts that the example demo packs used by medcat service have been trained for. \n", + "\n", + "### Service definitions\n", + "We will setup a client for OpenSearch, and define the HTTP endpoint for medcat service.\n", + "\n", + "If using the cogstack community edition helm chart, these should all be setup for you automatically using kubernetes services and env vars. Otherwise change these accordingly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "17deaa5c", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/opt/conda/envs/py311/lib/python3.11/site-packages/opensearchpy/connection/http_urllib3.py:214: UserWarning: Connecting to https://opensearch-cluster-master:9200 using SSL with verify_certs=False is insecure.\n", + " warnings.warn(\n" + ] + } + ], + "source": [ + "import os\n", + "from datetime import datetime, timezone\n", + "from urllib.parse import urlparse\n", + "\n", + "import pandas as pd\n", + "import requests\n", + "import urllib3\n", + "from IPython.display import display\n", + "from opensearchpy import OpenSearch\n", + "\n", + "# The sample note that we will work with\n", + "sample_text = \"John was diagnosed with Kidney Failure\"\n", + "\n", + "# Service URLs from environment variables\n", + "medcat_base_url = os.getenv(\"MEDCAT_SERVICE_URL\", \"http://cogstack-medcat-service:5000\").rstrip(\"/\")\n", + "medcat_url = medcat_base_url + \"/api/process\"\n", + "\n", + "opensearch_url = os.getenv(\"OPENSEARCH_URL\", \"https://opensearch-cluster-master:9200\")\n", + "opensearch_username = os.getenv(\"OPENSEARCH_USERNAME\", \"admin\")\n", + "opensearch_password = os.getenv(\"OPENSEARCH_PASSWORD\", \"opensearch-312$A\")\n", + "\n", + "parsed = urlparse(opensearch_url)\n", + "\n", + "urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n", + "\n", + "host_cfg = {\n", + " \"host\": parsed.hostname,\n", + " \"port\": parsed.port or (443 if parsed.scheme == \"https\" else 80),\n", + "}\n", + "if parsed.path and parsed.path != \"/\":\n", + " host_cfg[\"url_prefix\"] = parsed.path.lstrip(\"/\")\n", + "\n", + "client = OpenSearch(\n", + " hosts=[host_cfg],\n", + " http_auth=(opensearch_username, opensearch_password),\n", + " use_ssl=(parsed.scheme == \"https\"),\n", + " verify_certs=False,\n", + ")\n", + "\n", + "# Hardcoded demo indices\n", + "discharge_index = \"discharge\"\n", + "annotations_index = \"discharge_annotations\"\n", + "\n", + "# Static demo note id used across all steps\n", + "note_id = \"demo-note-kidney-failure-001\"\n", + "subject_id = 1" + ] + }, + { + "cell_type": "markdown", + "id": "19340174", + "metadata": {}, + "source": [ + "## 1) Index the note into OpenSearch\n", + "\n", + "We write the note into `discharge`, then immediately run a free-text query (`kidney failure`) to prove it is searchable." + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "id": "3eb85731", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'_index': 'discharge',\n", + " '_id': 'demo-note-kidney-failure-001',\n", + " '_version': 10,\n", + " 'result': 'updated',\n", + " 'forced_refresh': True,\n", + " '_shards': {'total': 2, 'successful': 1, 'failed': 0},\n", + " '_seq_no': 1009,\n", + " '_primary_term': 1}" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "note_doc = {\n", + " \"note_id\": note_id,\n", + " \"subject_id\": subject_id,\n", + " \"text\": sample_text,\n", + " \"storetime\": datetime.now(timezone.utc).strftime(\"%Y-%m-%d %H:%M:%S\"),\n", + "}\n", + "\n", + "client.index(index=discharge_index, id=note_id, body=note_doc, refresh=True)\n" + ] + }, + { + "cell_type": "markdown", + "id": "edad8661", + "metadata": {}, + "source": [ + "## 2) Search that note back using free text\n", + "\n", + "This query uses `match` search, so we can find notes by important words (for example `John kidney`) without requiring an exact full-string match.\n", + "\n", + "In a traditional relational query, you would usually rely on exact equality or simple wildcard `LIKE` patterns. Here, OpenSearch handles tokenized full-text search for us." + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "id": "25613475", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Free-text query used: John kidney\n", + "This still returns the note even though it is not an exact full sentence match.\n", + "Results from OpenSearch free-text search:\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
note_idsubject_idtextstoretime
0demo-note-kidney-failure-0011John was diagnosed with Kidney Failure2026-03-26 17:49:59
\n", + "
" + ], + "text/plain": [ + " note_id subject_id \\\n", + "0 demo-note-kidney-failure-001 1 \n", + "\n", + " text storetime \n", + "0 John was diagnosed with Kidney Failure 2026-03-26 17:49:59 " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "query_text = \"John kidney\"\n", + "free_text_resp = client.search(\n", + " index=discharge_index,\n", + " body={\"query\": {\"match\": {\"text\": query_text}}},\n", + ")\n", + "hits = free_text_resp[\"hits\"][\"hits\"]\n", + "print(f\"Free-text query used: {query_text}\")\n", + "print(\"This still returns the note even though it is not an exact full sentence match.\")\n", + "print(\"Results from OpenSearch free-text search:\")\n", + "display(pd.DataFrame([hits[0][\"_source\"]]))" + ] + }, + { + "cell_type": "markdown", + "id": "c8aaa960", + "metadata": {}, + "source": [ + "## 3) Fuzzy full-text search (not exact matching)\n", + "\n", + "Now we intentionally misspell the query (`kidny falur`) and still retrieve results.\n", + "\n", + "This demonstrates why OpenSearch is useful for user-entered text and typo-tolerant retrieval." + ] + }, + { + "cell_type": "code", + "execution_count": 70, + "id": "595a313e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Fuzzy query: kidny falur\n", + "fuzzy_hits=1\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
note_idsubject_idtextstoretime
0demo-note-kidney-failure-0011John was diagnosed with Kidney Failure2026-03-26 17:49:59
\n", + "
" + ], + "text/plain": [ + " note_id subject_id \\\n", + "0 demo-note-kidney-failure-001 1 \n", + "\n", + " text storetime \n", + "0 John was diagnosed with Kidney Failure 2026-03-26 17:49:59 " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "fuzzy_query = \"kidny falur\"\n", + "fuzzy_resp = client.search(\n", + " index=discharge_index,\n", + " body={\n", + " \"query\": {\n", + " \"match\": {\n", + " \"text\": {\n", + " \"query\": fuzzy_query,\n", + " \"fuzziness\": \"AUTO\"\n", + " }\n", + " }\n", + " }\n", + " },\n", + ")\n", + "\n", + "fuzzy_hits = fuzzy_resp[\"hits\"][\"hits\"]\n", + "print(f\"Fuzzy query: {fuzzy_query}\")\n", + "print(f\"fuzzy_hits={len(fuzzy_hits)}\")\n", + "display(pd.DataFrame(pd.DataFrame([hits[0][\"_source\"]])))" + ] + }, + { + "cell_type": "markdown", + "id": "690cd9a2", + "metadata": {}, + "source": [ + "## 4) Perform Named Entity Resolution with MedCAT\n", + "\n", + "We can see that we are able to search with free text, and fuzzy match. However, what happens if we want to search accross notes using common terminology?\n", + "\n", + "We can solve this by using named entity resolution (NER) and NLP.\n", + "\n", + "To do this we will call MedCAT at `/api/process` with the same note text.\n", + "\n", + "MedCAT returns structured entities (for example CUI and concept name). This is named entity resolution in one API call." + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "id": "f1428daf", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "annotations_found=1\n", + "Results from MedCAT named entity extraction:\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
pretty_namecuitype_idssource_valuedetected_nameacccontext_similaritystartendidmeta_annscontext_leftcontext_centercontext_right
0Kidney Failure1[T047]Kidney Failurekidney~failure1124380{}[][][]
\n", + "
" + ], + "text/plain": [ + " pretty_name cui type_ids source_value detected_name acc \\\n", + "0 Kidney Failure 1 [T047] Kidney Failure kidney~failure 1 \n", + "\n", + " context_similarity start end id meta_anns context_left context_center \\\n", + "0 1 24 38 0 {} [] [] \n", + "\n", + " context_right \n", + "0 [] " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "medcat_payload = {\"content\": {\"text\": sample_text}}\n", + "medcat_result = requests.post(medcat_url, json=medcat_payload, timeout=30).json()\n", + "raw_annotations = medcat_result.get(\"result\", {}).get(\"annotations\", [])\n", + "\n", + "annotations = [\n", + " next(iter(ann.values())) if isinstance(ann, dict) and len(ann) == 1 else ann\n", + " for ann in raw_annotations\n", + " if isinstance(ann, dict)\n", + "]\n", + "\n", + "print(f\"annotations_found={len(annotations)}\")\n", + "print(\"Results from MedCAT named entity extraction:\")\n", + "display(pd.DataFrame(annotations))" + ] + }, + { + "cell_type": "markdown", + "id": "1dc6dbf6", + "metadata": {}, + "source": [ + "### 4.1) Index MedCAT entities into OpenSearch\n", + "\n", + "Here we take each MedCAT entity and store it in OpenSearch in the `discharge_annotations` index\n", + "\n", + "We prefix MedCAT fields with `nlp.` and add `meta.note_id` / `meta.subject_id` so each entity stays linked to its source note." + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "id": "86152c7b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "indexed_annotations=1\n" + ] + } + ], + "source": [ + "indexed = 0\n", + "now_ts = datetime.now(timezone.utc).isoformat()\n", + "\n", + "for i, ann in enumerate(annotations):\n", + " nlp_fields = {f\"nlp.{k}\": v for k, v in ann.items()}\n", + "\n", + " ann_doc = {\n", + " **nlp_fields,\n", + " \"meta.note_id\": note_id,\n", + " \"meta.subject_id\": subject_id,\n", + " \"timestamp\": now_ts,\n", + " }\n", + "\n", + " client.index(\n", + " index=annotations_index,\n", + " id=f\"{note_id}-ann-{i}\",\n", + " body=ann_doc,\n", + " refresh=False,\n", + " )\n", + " indexed += 1\n", + "\n", + "client.indices.refresh(index=annotations_index)\n", + "print(f\"indexed_annotations={indexed}\")" + ] + }, + { + "cell_type": "markdown", + "id": "f0067cc1", + "metadata": {}, + "source": [ + "## 5) Search by concept\n", + "\n", + "Finally, we query `discharge_annotations` using the extracted concept (`nlp.cui` / `nlp.pretty_name`).\n", + "\n", + "This is the main value: instead of searching raw strings, we can retrieve notes by normalized clinical concepts." + ] + }, + { + "cell_type": "code", + "execution_count": 73, + "id": "3a6edeb8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Concept CUI search used: 1\n", + "concept_hits=1\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
nlp.pretty_namenlp.cuinlp.type_idsnlp.source_valuenlp.detected_namenlp.accnlp.context_similaritynlp.startnlp.endnlp.idnlp.meta_annsnlp.context_leftnlp.context_centernlp.context_rightmeta.note_idmeta.subject_idtimestamp
0Kidney Failure1[T047]Kidney Failurekidney~failure1124380{}[][][]demo-note-kidney-failure-00112026-03-26T17:50:17.140165+00:00
\n", + "
" + ], + "text/plain": [ + " nlp.pretty_name nlp.cui nlp.type_ids nlp.source_value nlp.detected_name \\\n", + "0 Kidney Failure 1 [T047] Kidney Failure kidney~failure \n", + "\n", + " nlp.acc nlp.context_similarity nlp.start nlp.end nlp.id nlp.meta_anns \\\n", + "0 1 1 24 38 0 {} \n", + "\n", + " nlp.context_left nlp.context_center nlp.context_right \\\n", + "0 [] [] [] \n", + "\n", + " meta.note_id meta.subject_id \\\n", + "0 demo-note-kidney-failure-001 1 \n", + "\n", + " timestamp \n", + "0 2026-03-26T17:50:17.140165+00:00 " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "concept_cui = str(annotations[0].get(\"cui\", \"\"))\n", + "\n", + "concept_query = {\n", + " \"query\": {\n", + " \"term\": {\n", + " \"nlp.cui.keyword\": concept_cui\n", + " }\n", + " }\n", + "}\n", + "\n", + "concept_resp = client.search(index=annotations_index, body=concept_query)\n", + "concept_hits = concept_resp[\"hits\"][\"hits\"]\n", + "\n", + "print(f\"Concept CUI search used: {concept_cui}\")\n", + "print(f\"concept_hits={len(concept_hits)}\")\n", + "\n", + "display(pd.DataFrame([h.get(\"_source\", {}) for h in concept_hits]))" + ] + }, + { + "cell_type": "markdown", + "id": "28cf3ed2", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "You have now seen the full end-to-end CogStack flow in a few simple steps:\n", + "- index notes into OpenSearch\n", + "- run free-text and fuzzy search over clinical text\n", + "- call MedCAT to perform named entity resolution\n", + "- index entity outputs\n", + "- retrieve notes by normalized concept (CUI)\n", + "\n", + "This is the core building block for turning unstructured clinical text into searchable, analysable, and operational data.\n", + "\n", + "## What to do next\n", + "- **Visualise the data with OpenSearch Dashboards** \n", + " If you've setup with the CogStack Community Edition and are running on localhost, visit http://localhost:5601/ to now see reports and drill down on this data with the UI\n", + "\n", + "- **Scale this into production ETL** \n", + " Use these exact blocks in your pipelines: ingest note text -> index to OpenSearch -> call MedCAT -> index annotations -> query/serve downstream applications.\n", + "\n", + "- **Use a real MedCAT model** \n", + " Replace the demo model with a domain-appropriate model pack and configuration: [MedCAT v2 README](https://github.com/CogStack/cogstack-nlp/blob/main/medcat-v2/README.md).\n", + "\n", + "- **Explore the platform docs and examples** \n", + " See full docs at [docs.cogstack.org](https://docs.cogstack.org/) and repositories/examples at [github.com/CogStack](https://github.com/CogStack).\n", + "\n", + "- **Add supervised learning with MedCAT Trainer (MLOps)** \n", + " Set up a training and feedback loop to improve extraction quality over time using MedCAT Trainer (annotation -> train -> evaluate -> redeploy)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 + } + medcat-service-tutorial.ipynb: | + { + "cells": [ + { + "cell_type": "markdown", + "id": "3dd024b0-46cb-4410-8e33-89dbf2557b3f", + "metadata": {}, + "source": [ + "# Cogstack Services Tutorial\n", + "\n", + "This is a step-by-step walkthrough that shows how to call two CogStack services over HTTP:\n", + "MedCAT (entity extraction) and AnonCAT (de-identification).\n", + "\n", + "## Overview\n", + "\n", + "### Who it is for:\n", + "This is for developers, data engineers, and analysts who want a quick, practical example of how\n", + "to integrate MedCAT/AnonCAT into a Python workflow (and later into a notebook-based analysis).\n", + "\n", + "### What it will do:\n", + "1) Define a sample clinical sentence and the service URLs.\n", + "2) Extract Entities, by calling the medcat-service API\n", + "3) Print the extracted entity annotations from the MedCAT response.\n", + "4) Deidentify text by calling the anoncat-service API\n", + "5) Print the de-identified text (and show the full JSON response for inspection).\n", + "\n", + "### Prerequisites\n", + "The best way to run this notebook interactively is to run the CogStack Community Edition with Helm. Look at https://docs.cogstack.org/ to get started." + ] + }, + { + "cell_type": "markdown", + "id": "de9fd984-d6bd-4717-a5a0-4a34b233f594", + "metadata": {}, + "source": [ + "## Initialisation: Define the inputs and services\n", + "We pick a single sample sentence and the two HTTP endpoints we will call.\n", + "\n", + "The sample sentence contains concepts that the example demo packs used by medcat service have been trained for. \n", + "\n", + "For the service URLs, if using the cogstack community edition helm chart, these should all be setup for you automatically using kubernetes services and env vars. Otherwise change these accordingly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a5f15845-5a0f-414e-9db7-f414d12bde48", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import os\n", + "import requests\n", + "\n", + "sample_text = \"John was diagnosed with Kidney Failure\"\n", + "\n", + "medcat_base_url = os.getenv(\n", + " \"MEDCAT_SERVICE_URL\", \"http://cogstack-medcat-service:5000\"\n", + ").rstrip(\"/\")\n", + "\n", + "anoncat_base_url = os.getenv(\n", + " \"ANONCAT_SERVICE_URL\", \"http://cogstack-ce-anoncat-service:5000\"\n", + ").rstrip(\"/\")\n", + "\n", + "medcat_url = medcat_base_url + \"/api/process\"\n", + "anoncat_url = anoncat_base_url + \"/api/process\"" + ] + }, + { + "cell_type": "markdown", + "id": "b9b954ee-66e4-424b-b0f8-5602fe86ffa7", + "metadata": {}, + "source": [ + "## Perform Named Entity Resolution by calling MedCAT service\n", + "We can now use medcat service to extract entities from our note. \n", + "\n", + "We will send `sample_text` to MedCAT’s `/api/process` route where the payload is shaped as: `{\"content\": {\"text\": sample_text}}`\n", + "\n", + "We can then parse the JSON response and pull out: `medcat_result.get(\"result\").get(\"annotations\")`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "13a2405f-502d-4fff-9c0c-11fb7341ca3a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "=== MedCAT: entities ===\n", + "[\n", + " {\n", + " \"0\": {\n", + " \"pretty_name\": \"Kidney Failure\",\n", + " \"cui\": \"1\",\n", + " \"type_ids\": [\n", + " \"T047\"\n", + " ],\n", + " \"source_value\": \"Kidney Failure\",\n", + " \"detected_name\": \"kidney~failure\",\n", + " \"acc\": 1,\n", + " \"context_similarity\": 1,\n", + " \"start\": 24,\n", + " \"end\": 38,\n", + " \"id\": 0,\n", + " \"meta_anns\": {},\n", + " \"context_left\": [],\n", + " \"context_center\": [],\n", + " \"context_right\": []\n", + " }\n", + " }\n", + "]\n" + ] + } + ], + "source": [ + "medcat_payload = {\"content\": {\"text\": sample_text}}\n", + "\n", + "medcat_result = requests.post(medcat_url, json=medcat_payload).json()\n", + "medcat_annotations = medcat_result.get(\"result\").get(\"annotations\")\n", + "\n", + "print(\"=== MedCAT: entities ===\")\n", + "print(json.dumps(medcat_annotations, indent=2))" + ] + }, + { + "cell_type": "markdown", + "id": "95a2f603-f107-4266-9bd8-ae64fd6e7692", + "metadata": {}, + "source": [ + "From the above results, we can see that the service has detected \"Kidney Failure\" in the text with a cui of \"1\".\n", + "\n", + "We can see the raw JSON response from medcat by printing it" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "aad682db-df27-4520-b18d-58007594053f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "=== MedCAT Service: Raw results ===\n", + "{\n", + " \"medcat_info\": {\n", + " \"service_app_name\": \"MedCAT\",\n", + " \"service_language\": \"en\",\n", + " \"service_version\": \"2.4.0.dev0\",\n", + " \"service_model\": \"unknown\",\n", + " \"model_card_info\": {\n", + " \"ontologies\": \"None\",\n", + " \"meta_cat_model_names\": [],\n", + " \"rel_cat_model_names\": [],\n", + " \"model_last_modified_on\": \"2025-07-14T12:36:10.286051\"\n", + " }\n", + " },\n", + " \"result\": {\n", + " \"text\": \"John was diagnosed with Kidney Failure\",\n", + " \"annotations\": [\n", + " {\n", + " \"0\": {\n", + " \"pretty_name\": \"Kidney Failure\",\n", + " \"cui\": \"1\",\n", + " \"type_ids\": [\n", + " \"T047\"\n", + " ],\n", + " \"source_value\": \"Kidney Failure\",\n", + " \"detected_name\": \"kidney~failure\",\n", + " \"acc\": 1,\n", + " \"context_similarity\": 1,\n", + " \"start\": 24,\n", + " \"end\": 38,\n", + " \"id\": 0,\n", + " \"meta_anns\": {},\n", + " \"context_left\": [],\n", + " \"context_center\": [],\n", + " \"context_right\": []\n", + " }\n", + " }\n", + " ],\n", + " \"success\": true,\n", + " \"timestamp\": \"2026-03-18T16:08:44.595+00:00\",\n", + " \"elapsed_time\": 0.003085773,\n", + " \"footer\": null\n", + " }\n", + "}\n" + ] + } + ], + "source": [ + "print(\"=== MedCAT Service: Raw results ===\")\n", + "print(json.dumps(medcat_result, indent=2))" + ] + }, + { + "cell_type": "markdown", + "id": "c4a7dfdb-730f-4390-94eb-31055ecae914", + "metadata": {}, + "source": [ + "## Perform deidentificaition by using AnonCAT sercice\n", + "\n", + "We can also use AnonCat service to deidentify our notes.\n", + "\n", + "The process for this is the same as medcat, the only difference is we are will call a different endpoint. We will send `sample_text` to MedCAT’s `/api/process` route where the payload is shaped as: `{\"content\": {\"text\": sample_text}}`.\n", + "\n", + "We can then parse the JSON response and pull out the text which should be anonymised" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "e2e0cba5-3c08-4c1f-869f-f8012b0a9282", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "=== AnonCAT: Deidentification result ===\n", + "The input was 'John was diagnosed with Kidney Failure'. The output was '[PATIENT] diagnosed with Kidney Failure'\n" + ] + } + ], + "source": [ + "anoncat_payload = {\"content\": {\"text\": sample_text}}\n", + "anoncat_result = requests.post(anoncat_url, json=anoncat_payload).json()\n", + "\n", + "deidentified_text = anoncat_result.get(\"result\").get(\"text\")\n", + "\n", + "print(\"=== AnonCAT: Deidentification result ===\")\n", + "print(f\"The input was '{sample_text}'. The output was '{deidentified_text}'\")" + ] + }, + { + "cell_type": "markdown", + "id": "e4a9c7ce-4255-4ddc-a704-34663298a8a0", + "metadata": {}, + "source": [ + "From the above result, we can see that it has found that the note had the name \"John\", which it's replaced with the placeholder `[PATIENT]`. This has anonymised the note. Note we could alternatively change the service to redact the text, and return `[***]`, which we can do by configuring the service values and redeploying. \n", + "\n", + "We can see the raw JSON response from medcat by printing it. Note that it is the same format as medcat, just instead of finding medical concepts, it has found the patient name." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "e792e179-fc8a-4e76-aa19-efb0a3e01241", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "=== AnonCAT: Deidentification result ===\n", + "{\n", + " \"medcat_info\": {\n", + " \"service_app_name\": \"MedCAT\",\n", + " \"service_language\": \"en\",\n", + " \"service_version\": \"2.4.0.dev0\",\n", + " \"service_model\": \"unknown\",\n", + " \"model_card_info\": {\n", + " \"ontologies\": [],\n", + " \"meta_cat_model_names\": [],\n", + " \"rel_cat_model_names\": [],\n", + " \"model_last_modified_on\": \"2025-08-15T15:14:34.047031\"\n", + " }\n", + " },\n", + " \"result\": {\n", + " \"text\": \"[PATIENT] diagnosed with Kidney Failure\",\n", + " \"annotations\": [\n", + " {\n", + " \"0\": {\n", + " \"pretty_name\": \"PATIENT\",\n", + " \"cui\": \"PATIENT\",\n", + " \"type_ids\": [],\n", + " \"source_value\": \"John was\",\n", + " \"detected_name\": \"\",\n", + " \"acc\": 0.9922866225242615,\n", + " \"context_similarity\": 0.9922866225242615,\n", + " \"start\": 0,\n", + " \"end\": 8,\n", + " \"id\": 0,\n", + " \"meta_anns\": {},\n", + " \"context_left\": [],\n", + " \"context_center\": [],\n", + " \"context_right\": []\n", + " }\n", + " }\n", + " ],\n", + " \"success\": true,\n", + " \"timestamp\": \"2026-03-18T16:09:41.266+00:00\",\n", + " \"elapsed_time\": 0.011446122,\n", + " \"footer\": null\n", + " }\n", + "}\n" + ] + } + ], + "source": [ + "print(\"=== AnonCAT: Deidentification result ===\")\n", + "print(json.dumps(anoncat_result, indent=2))\n" + ] + }, + { + "cell_type": "markdown", + "id": "aed034c8-7630-48f8-b382-f220f4eddfa8", + "metadata": {}, + "source": [ + "## Summary\n", + "This is the end of this tutorial.\n", + "\n", + "We can see by calling the model services, we are able to get entities and deidentify text just by calling two http APIs. \n", + "\n", + "## What next?\n", + "There's two options of where to go next:\n", + "1. Setup a data pipeline, that can call these services and write results into OpenSearch\n", + "2. Use MedCAT Trainer and setup a MLOps flow for training a model, and redeploying the services with the new model." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 + } + ocr-service-tutorial.ipynb: | + { + "cells": [ + { + "cell_type": "markdown", + "id": "a1c4e8f2-1b3d-4c9a-9e2f-ocr-tutorial-intro", + "metadata": {}, + "source": [ + "# OCR Service Tutorial\n", + "\n", + "This is a step-by-step walkthrough that shows how to call the CogStack OCR service over HTTP:\n", + "OCR of scanned files, and text extraction from a Word document.\n", + "\n", + "OCR is optical character recognition. Use this when you have images or scanned in documents containing text. The OCR service is also able to work with machine readable documents that do not need OCR, like word documents or pdfs containing text. This tutorial will show how it can parse both in the same way.\n", + "\n", + "## Overview\n", + "\n", + "### Who is this tutorial for:\n", + "This is for developers, data engineers, and analysts who want a quick, practical example of how\n", + "to integrate OCR Service into a Python workflow (and later into a notebook-based analysis).\n", + "\n", + "### What will the tutorial do:\n", + "1) Define sample files and the service URL.\n", + "2) OCR a PNG of a scanned document, by calling the ocr-service API\n", + "3) Extract text from a Word document\n", + "4) OCR a scanned PDF\n", + "\n", + "### Prerequisites\n", + "The best way to run this notebook interactively is to run the CogStack Community Edition with Helm. Look at https://docs.cogstack.org/ to get started." + ] + }, + { + "cell_type": "markdown", + "id": "b2d5f9a3-2c4e-4d0b-8f31-ocr-tutorial-init-md", + "metadata": {}, + "source": [ + "## Initialisation: Define the inputs and services\n", + "We pick three sample files and the HTTP endpoint we will call.\n", + "\n", + "The samples are a PNG of a scanned document, a Word document that already contains text, and a scanned PDF:\n", + "- [pat_id_1.png](https://github.com/CogStack/cogstack-platform/blob/ocr-service-v1.1.3/apps/ocr-service/ocr_service/tests/resources/docs/generic/pat_id_1.png)\n", + "- [pat_id_1.docx](https://github.com/CogStack/cogstack-platform/blob/ocr-service-v1.1.3/apps/ocr-service/ocr_service/tests/resources/docs/generic/pat_id_1.docx)\n", + "- [pat_id_1.pdf](https://github.com/CogStack/cogstack-platform/blob/ocr-service-v1.1.3/apps/ocr-service/ocr_service/tests/resources/docs/generic/pat_id_1.pdf)\n", + "\n", + "For the service URL, if using the cogstack community edition helm chart, this should be setup for you automatically using kubernetes services and env vars. Otherwise change it accordingly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c3e6a0b4-3d5f-4e1c-9a42-ocr-tutorial-init-code", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import os\n", + "\n", + "import requests\n", + "\n", + "ocr_base_url = os.getenv(\n", + " \"OCR_SERVICE_URL\", \"http://cogstack-ocr-service:8090\"\n", + ").rstrip(\"/\")\n", + "\n", + "ocr_url = ocr_base_url + \"/api/process\"\n", + "\n", + "base_url = \"https://raw.githubusercontent.com/CogStack/cogstack-platform/ocr-service-v1.1.3/apps/ocr-service/ocr_service/tests/resources/docs\"\n", + "os.makedirs(\"data/ocr-service-tutorial\", exist_ok=True)\n", + "\n", + "open(\"data/ocr-service-tutorial/pat_id_1.png\", \"wb\").write(requests.get(f\"{base_url}/generic/pat_id_1.png\").content)\n", + "open(\"data/ocr-service-tutorial/pat_id_1.docx\", \"wb\").write(requests.get(f\"{base_url}/generic/pat_id_1.docx\").content)\n", + "open(\"data/ocr-service-tutorial/pat_id_1.pdf\", \"wb\").write(requests.get(f\"{base_url}/generic/pat_id_1.pdf\").content)" + ] + }, + { + "cell_type": "markdown", + "id": "a7c0e4f8-7b93-4250-de86-ocr-tutorial-png-md", + "metadata": {}, + "source": [ + "## OCR a scanned document\n", + "We can now use ocr service to read text from an image of a page.\n", + "\n", + "We have a PNG file that represents a scanned document. It does not already contain text, so the service will need to OCR it." + ] + }, + { + "cell_type": "markdown", + "id": "b8d1f5a9-8c04-4361-ef97-ocr-tutorial-png-display", + "metadata": {}, + "source": [ + "The scanned document is a PNG file, that looks like this:\n", + "\n", + "![Scanned document](https://raw.githubusercontent.com/CogStack/cogstack-platform/ocr-service-v1.1.3/apps/ocr-service/ocr_service/tests/resources/docs/generic/pat_id_1.png)" + ] + }, + { + "cell_type": "markdown", + "id": "c9e2a6b0-9d15-4472-fa08-ocr-tutorial-png-ocr-md", + "metadata": {}, + "source": [ + "We will send this image to the ocr service and print the text it recovers." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d0f3b7c1-0e26-4583-ab19-ocr-tutorial-png-ocr-code", + "metadata": {}, + "outputs": [], + "source": [ + "with open(\"data/ocr-service-tutorial/pat_id_1.png\", \"rb\") as f:\n", + " png_result = requests.post(ocr_url, files={\"file\": (\"pat_id_1.png\", f)}).json()\n", + "\n", + "print(\"=== OCR Service: PNG ===\")\n", + "print(png_result.get(\"result\").get(\"text\"))" + ] + }, + { + "cell_type": "markdown", + "id": "e1a4c8d2-1f37-4694-bc20-ocr-tutorial-png-commentary", + "metadata": {}, + "source": [ + "From the above result, we can see that the service has recovered the clinical note from the scanned image. The wording can differ slightly, because the service is reading an image of the page.\n", + "\n", + "We can see the raw JSON response from ocr service by printing it" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f2b5d9e3-2a48-4705-cd31-ocr-tutorial-raw-json", + "metadata": {}, + "outputs": [], + "source": [ + "print(\"=== OCR Service: Raw results ===\")\n", + "print(json.dumps(png_result, indent=2))" + ] + }, + { + "cell_type": "markdown", + "id": "d4f7b1c5-4e60-4f2d-ab53-ocr-tutorial-docx-md", + "metadata": {}, + "source": [ + "## Extract text from a Word document\n", + "We can also use ocr service to extract text from a Word file.\n", + "\n", + "This document already contains text, so the service can read it without OCR." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e5a8c2d6-5f71-403e-bc64-ocr-tutorial-docx-code", + "metadata": {}, + "outputs": [], + "source": [ + "with open(\"data/ocr-service-tutorial/pat_id_1.docx\", \"rb\") as f:\n", + " docx_result = requests.post(ocr_url, files={\"file\": (\"pat_id_1.docx\", f)}).json()\n", + "\n", + "print(\"=== OCR Service: Word document ===\")\n", + "print(docx_result.get(\"result\").get(\"text\"))" + ] + }, + { + "cell_type": "markdown", + "id": "f6b9d3e7-6a82-414f-cd75-ocr-tutorial-docx-commentary", + "metadata": {}, + "source": [ + "From the above result, we can see that the service has extracted the clinical note from the Word document." + ] + }, + { + "cell_type": "markdown", + "id": "a3c7e8f4-7b93-4250-de86-ocr-tutorial-pdf-md", + "metadata": {}, + "source": [ + "## OCR a scanned PDF\n", + "A scanned PDF is the same idea as the PNG: the pages are images, so the service uses OCR to recover the text." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b4d8f9a5-8c04-4361-ef97-ocr-tutorial-pdf-code", + "metadata": {}, + "outputs": [], + "source": [ + "with open(\"data/ocr-service-tutorial/pat_id_1.pdf\", \"rb\") as f:\n", + " pdf_result = requests.post(ocr_url, files={\"file\": (\"pat_id_1.pdf\", f)}).json()\n", + "\n", + "print(\"=== OCR Service: scanned PDF ===\")\n", + "print(pdf_result.get(\"result\").get(\"text\"))" + ] + }, + { + "cell_type": "markdown", + "id": "c5e0a6b6-9d15-4472-fa08-ocr-tutorial-pdf-commentary", + "metadata": {}, + "source": [ + "From the above result, we can see that the service has recovered text from the scanned PDF." + ] + }, + { + "cell_type": "markdown", + "id": "e1a4c8d2-1f37-4694-bc21-ocr-tutorial-summary", + "metadata": {}, + "source": [ + "## Summary\n", + "This is the end of this tutorial.\n", + "\n", + "We can see by calling the OCR service, we are able to extract text from images, Word files, and scanned PDFs just by calling one HTTP API.\n", + "\n", + "## What next?\n", + "Take the extracted text and follow the MedCAT + OpenSearch end-to-end tutorial (`medcat-opensearch-e2e.ipynb`). That shows how to ingest the text into OpenSearch and run MedCAT on top." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 + } + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/pvc.yaml +kind: PersistentVolumeClaim +apiVersion: v1 +metadata: + name: hub-db-dir + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: "1Gi" + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-scheduler/rbac.yaml +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: jupyterhub-user-scheduler + labels: + component: user-scheduler + app.kubernetes.io/component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +rules: + # Copied from the system:kube-scheduler ClusterRole of the k8s version + # matching the kube-scheduler binary we use. A modification has been made to + # resourceName fields to remain relevant for how we have named our resources + # in this Helm chart. + # + # NOTE: These rules have been: + # - unchanged between 1.12 and 1.15 + # - changed in 1.16 + # - changed in 1.17 + # - unchanged between 1.18 and 1.20 + # - changed in 1.21: get/list/watch permission for namespace, + # csidrivers, csistoragecapacities was added. + # - unchanged between 1.22 and 1.27 + # - changed in 1.28: permissions to get/update lock endpoint resource + # removed + # - unchanged between 1.28 and 1.30 + # - (1.31 is known to bring some changes below) + # + # ref: https://github.com/kubernetes/kubernetes/blob/v1.30.0/plugin/pkg/auth/authorizer/rbac/bootstrappolicy/testdata/cluster-roles.yaml#L721-L862 + - apiGroups: + - "" + - events.k8s.io + resources: + - events + verbs: + - create + - patch + - update + - apiGroups: + - coordination.k8s.io + resources: + - leases + verbs: + - create + - apiGroups: + - coordination.k8s.io + resourceNames: + - user-scheduler-lock + resources: + - leases + verbs: + - get + - update + - apiGroups: + - "" + resources: + - nodes + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - pods + verbs: + - delete + - get + - list + - watch + - apiGroups: + - "" + resources: + - bindings + - pods/binding + verbs: + - create + - apiGroups: + - "" + resources: + - pods/status + verbs: + - patch + - update + - apiGroups: + - "" + resources: + - replicationcontrollers + - services + verbs: + - get + - list + - watch + - apiGroups: + - apps + - extensions + resources: + - replicasets + verbs: + - get + - list + - watch + - apiGroups: + - apps + resources: + - statefulsets + verbs: + - get + - list + - watch + - apiGroups: + - policy + resources: + - poddisruptionbudgets + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - persistentvolumeclaims + - persistentvolumes + verbs: + - get + - list + - watch + - apiGroups: + - authentication.k8s.io + resources: + - tokenreviews + verbs: + - create + - apiGroups: + - authorization.k8s.io + resources: + - subjectaccessreviews + verbs: + - create + - apiGroups: + - storage.k8s.io + resources: + - csinodes + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - namespaces + verbs: + - get + - list + - watch + - apiGroups: + - storage.k8s.io + resources: + - csidrivers + verbs: + - get + - list + - watch + - apiGroups: + - storage.k8s.io + resources: + - csistoragecapacities + verbs: + - get + - list + - watch + + # Copied from the system:volume-scheduler ClusterRole of the k8s version + # matching the kube-scheduler binary we use. + # + # NOTE: These rules have not changed between 1.12 and 1.29. + # + # ref: https://github.com/kubernetes/kubernetes/blob/v1.29.0/plugin/pkg/auth/authorizer/rbac/bootstrappolicy/testdata/cluster-roles.yaml#L1283-L1310 + - apiGroups: + - "" + resources: + - persistentvolumes + verbs: + - get + - list + - patch + - update + - watch + - apiGroups: + - storage.k8s.io + resources: + - storageclasses + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - persistentvolumeclaims + verbs: + - get + - list + - patch + - update + - watch + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-scheduler/rbac.yaml +kind: ClusterRoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: jupyterhub-user-scheduler + labels: + component: user-scheduler + app.kubernetes.io/component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +subjects: + - kind: ServiceAccount + name: user-scheduler + namespace: "default" +roleRef: + kind: ClusterRole + name: jupyterhub-user-scheduler + apiGroup: rbac.authorization.k8s.io + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/rbac.yaml +kind: Role +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +rules: + - apiGroups: [""] # "" indicates the core API group + resources: ["pods", "persistentvolumeclaims", "secrets", "services"] + verbs: ["get", "watch", "list", "create", "delete"] + - apiGroups: [""] # "" indicates the core API group + resources: ["events"] + verbs: ["get", "watch", "list"] + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/rbac.yaml +kind: RoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +subjects: + - kind: ServiceAccount + name: hub + namespace: "default" +roleRef: + kind: Role + name: hub + apiGroup: rbac.authorization.k8s.io + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm + annotations: + prometheus.io/scrape: "true" + prometheus.io/path: /hub/metrics + prometheus.io/port: "8081" +spec: + type: ClusterIP + selector: + component: hub + app: "jupyterhub" + release: "jupyterhub" + ports: + - name: hub + port: 8081 + targetPort: http + ipFamilyPolicy: PreferDualStack + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/proxy/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: proxy-api + labels: + component: proxy-api + app.kubernetes.io/component: proxy-api + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + selector: + component: proxy + app: "jupyterhub" + release: "jupyterhub" + ports: + - port: 8001 + targetPort: api + ipFamilyPolicy: PreferDualStack + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/proxy/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: proxy-public + labels: + component: proxy-public + app.kubernetes.io/component: proxy-public + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + selector: + # This service will target the autohttps pod if autohttps is configured, and + # the proxy pod if not. When autohttps is configured, the service proxy-http + # will be around to target the proxy pod directly. + component: proxy + app: "jupyterhub" + release: "jupyterhub" + ports: + - name: http + port: 80 + targetPort: http + type: ClusterIP + ipFamilyPolicy: PreferDualStack + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/hub/deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: hub + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + replicas: 1 + selector: + matchLabels: + component: hub + app: "jupyterhub" + release: "jupyterhub" + strategy: + type: Recreate + template: + metadata: + labels: + component: hub + app.kubernetes.io/component: hub + app: "jupyterhub" + release: "jupyterhub" + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + hub.jupyter.org/network-access-proxy-api: "true" + hub.jupyter.org/network-access-proxy-http: "true" + hub.jupyter.org/network-access-singleuser: "true" + annotations: + checksum/config-map: 81b48c55a7b330eda771120f454a582848e700fefb6dafe778f600cfd08e78d2 + checksum/secret: e38444a4cdbdd3330865dedc43a0ce114136c686d432eeb88922baa44d9e282b + spec: + tolerations: + - effect: NoSchedule + key: hub.jupyter.org/dedicated + operator: Equal + value: core + - effect: NoSchedule + key: hub.jupyter.org_dedicated + operator: Equal + value: core + affinity: + nodeAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + preference: + matchExpressions: + - key: hub.jupyter.org/node-purpose + operator: In + values: [core] + volumes: + - name: config + configMap: + name: hub + - name: secret + secret: + secretName: hub + - name: pvc + persistentVolumeClaim: + claimName: hub-db-dir + serviceAccountName: hub + securityContext: + fsGroup: 1000 + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + containers: + - name: hub + image: cogstacksystems/jupyter-hub:2.3.6 + args: + - jupyterhub + - --config + - /usr/local/etc/jupyterhub/jupyterhub_config.py + - --upgrade-db + volumeMounts: + - mountPath: /usr/local/etc/jupyterhub/jupyterhub_config.py + subPath: jupyterhub_config.py + name: config + - mountPath: /usr/local/etc/jupyterhub/z2jh.py + subPath: z2jh.py + name: config + - mountPath: /usr/local/etc/jupyterhub/config/ + name: config + - mountPath: /usr/local/etc/jupyterhub/secret/ + name: secret + - mountPath: /srv/jupyterhub + name: pvc + imagePullPolicy: IfNotPresent + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + runAsGroup: 1000 + runAsUser: 1000 + env: + - name: PYTHONUNBUFFERED + value: "1" + - name: HELM_RELEASE_NAME + value: "jupyterhub" + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: CONFIGPROXY_AUTH_TOKEN + valueFrom: + secretKeyRef: + name: hub + key: hub.config.ConfigurableHTTPProxy.auth_token + ports: + - name: http + containerPort: 8081 + livenessProbe: + initialDelaySeconds: 300 + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 30 + httpGet: + path: /hub/health + port: http + readinessProbe: + initialDelaySeconds: 0 + periodSeconds: 2 + timeoutSeconds: 1 + failureThreshold: 1000 + httpGet: + path: /hub/health + port: http + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/proxy/deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: proxy + labels: + component: proxy + app.kubernetes.io/component: proxy + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + replicas: 1 + selector: + matchLabels: + component: proxy + app: "jupyterhub" + release: "jupyterhub" + strategy: + type: Recreate + template: + metadata: + labels: + component: proxy + app.kubernetes.io/component: proxy + app: "jupyterhub" + release: "jupyterhub" + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + hub.jupyter.org/network-access-hub: "true" + hub.jupyter.org/network-access-singleuser: "true" + annotations: + # We want to restart proxy only if the auth token changes + # Other changes to the hub config should not restart. + # We truncate to 4 chars to avoid leaking auth token info, + # since someone could brute force the hash to obtain the token + # + # Note that if auth_token has to be generated at random, it will be + # generated at random here separately from being generated at random in + # the k8s Secret template. This will cause this annotation to change to + # match the k8s Secret during the first upgrade following an auth_token + # was generated. + checksum/auth-token: "f487" + checksum/proxy-secret: "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b" + spec: + terminationGracePeriodSeconds: 60 + tolerations: + - effect: NoSchedule + key: hub.jupyter.org/dedicated + operator: Equal + value: core + - effect: NoSchedule + key: hub.jupyter.org_dedicated + operator: Equal + value: core + affinity: + nodeAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + preference: + matchExpressions: + - key: hub.jupyter.org/node-purpose + operator: In + values: [core] + containers: + - name: chp + image: quay.io/jupyterhub/configurable-http-proxy:5.1.0 + command: + - configurable-http-proxy + - "--ip=" + - "--api-ip=" + - --api-port=8001 + - --default-target=http://hub:$(HUB_SERVICE_PORT) + - --error-target=http://hub:$(HUB_SERVICE_PORT)/hub/error + - --port=8000 + env: + - name: CONFIGPROXY_AUTH_TOKEN + valueFrom: + secretKeyRef: + # NOTE: References the chart managed k8s Secret even if + # hub.existingSecret is specified to avoid using the + # lookup function on the user managed k8s Secret. + name: hub + key: hub.config.ConfigurableHTTPProxy.auth_token + ports: + - name: http + containerPort: 8000 + - name: api + containerPort: 8001 + livenessProbe: + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 30 + httpGet: + path: /_chp_healthz + port: http + scheme: HTTP + readinessProbe: + initialDelaySeconds: 0 + periodSeconds: 2 + timeoutSeconds: 1 + failureThreshold: 1000 + httpGet: + path: /_chp_healthz + port: http + scheme: HTTP + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + runAsGroup: 65534 + runAsNonRoot: true + runAsUser: 65534 + seccompProfile: + type: RuntimeDefault + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-scheduler/deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: user-scheduler + labels: + component: user-scheduler + app.kubernetes.io/component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + replicas: 1 + selector: + matchLabels: + component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + template: + metadata: + labels: + component: user-scheduler + app.kubernetes.io/component: user-scheduler + app: "jupyterhub" + release: "jupyterhub" + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + annotations: + checksum/config-map: 36c25274eed5aef39282e1b50932c2231c61179a94c08d13ad9ad01017c60c6c + spec: + + serviceAccountName: user-scheduler + tolerations: + - effect: NoSchedule + key: hub.jupyter.org/dedicated + operator: Equal + value: core + - effect: NoSchedule + key: hub.jupyter.org_dedicated + operator: Equal + value: core + affinity: + nodeAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + preference: + matchExpressions: + - key: hub.jupyter.org/node-purpose + operator: In + values: [core] + volumes: + - name: config + configMap: + name: user-scheduler + containers: + - name: kube-scheduler + image: registry.k8s.io/kube-scheduler:v1.30.14 + command: + - /usr/local/bin/kube-scheduler + # NOTE: --authentication-skip-lookup=true is used to avoid a + # seemingly harmless error, if we need to not skip + # "authentication lookup" in the future, see the linked issue. + # + # ref: https://github.com/jupyterhub/zero-to-jupyterhub-k8s/issues/1894 + - --config=/etc/user-scheduler/config.yaml + - --authentication-skip-lookup=true + - --v=4 + volumeMounts: + - mountPath: /etc/user-scheduler + name: config + livenessProbe: + httpGet: + path: /healthz + scheme: HTTPS + port: 10259 + initialDelaySeconds: 15 + readinessProbe: + httpGet: + path: /healthz + scheme: HTTPS + port: 10259 + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + runAsGroup: 65534 + runAsNonRoot: true + runAsUser: 65534 + seccompProfile: + type: RuntimeDefault + +--- +# Source: jupyterhub-helm/charts/jupyterhub/templates/scheduling/user-placeholder/statefulset.yaml +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: user-placeholder + labels: + component: user-placeholder + app.kubernetes.io/component: user-placeholder + app: "jupyterhub" + release: "jupyterhub" + chart: jupyterhub-4.3.2 + heritage: Helm + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + helm.sh/chart: jupyterhub-4.3.2 + app.kubernetes.io/managed-by: Helm +spec: + podManagementPolicy: Parallel + replicas: 0 + selector: + matchLabels: + component: user-placeholder + app: "jupyterhub" + release: "jupyterhub" + serviceName: user-placeholder + template: + metadata: + labels: + component: user-placeholder + app.kubernetes.io/component: user-placeholder + app: "jupyterhub" + release: "jupyterhub" + app.kubernetes.io/name: "jupyterhub" + app.kubernetes.io/instance: "jupyterhub" + spec: + schedulerName: jupyterhub-user-scheduler + tolerations: + - effect: NoSchedule + key: hub.jupyter.org/dedicated + operator: Equal + value: user + - effect: NoSchedule + key: hub.jupyter.org_dedicated + operator: Equal + value: user + affinity: + nodeAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + preference: + matchExpressions: + - key: hub.jupyter.org/node-purpose + operator: In + values: [user] + terminationGracePeriodSeconds: 0 + automountServiceAccountToken: false + containers: + - name: pause + image: registry.k8s.io/pause:3.10.1 + resources: + requests: + memory: 1G + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + runAsGroup: 65534 + runAsNonRoot: true + runAsUser: 65534 + seccompProfile: + type: RuntimeDefault diff --git a/deployment/charts/nginx/.helmignore b/deployment/charts/nginx/.helmignore deleted file mode 100644 index 5bdaa3eb..00000000 --- a/deployment/charts/nginx/.helmignore +++ /dev/null @@ -1,24 +0,0 @@ -# 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/ -ci/ diff --git a/deployment/charts/nginx/Chart.yaml b/deployment/charts/nginx/Chart.yaml deleted file mode 100644 index c47eff23..00000000 --- a/deployment/charts/nginx/Chart.yaml +++ /dev/null @@ -1,32 +0,0 @@ -apiVersion: v2 -name: nginx -description: TLS reverse proxy for CogStack Apache NiFi - -# 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: "latest" - -home: https://docs.cogstack.org/ -sources: - - https://github.com/CogStack/cogstack-platform -maintainers: - - name: vladd-bit - email: 62345326+vladd-bit@users.noreply.github.com -icon: "https://avatars.githubusercontent.com/u/28688163" diff --git a/deployment/charts/nginx/README.md b/deployment/charts/nginx/README.md deleted file mode 100644 index 3f9b9e2e..00000000 --- a/deployment/charts/nginx/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# NiFi NGINX Helm chart - -Deploys `cogstacksystems/nifi-nginx` as the TLS reverse proxy for the NiFi web -Service. It creates a Deployment, a Service, an upstream-settings ConfigMap and -an optional Ingress. - -## Prerequisites - -Prepare these resources in the release namespace before installing: - -| Resource | Default name | Required contents | -| --- | --- | --- | -| ConfigMap | `nginx-env` | Deployment-specific NGINX environment settings. | -| ConfigMap | `nifi-env` | Shared NiFi environment settings. | -| Secret | `cogstack-root-ca` | `ca.crt`, the public CA for upstream TLS verification. | -| TLS Secret | `nginx-tls` | `tls.crt` and `tls.key` for the proxy certificate. | - -The environment ConfigMap names are currently fixed in the template. Override -certificate Secret names with `tls.rootCASecret` and `tls.existingSecret`. -The chart references these inputs rather than creating them from host files. - -By default, the proxy connects to -`cogstack-nifi-web..svc.cluster.local:8443`, which matches the -Service from `deployment/charts/nifi`. Set `nifi.host` and `nifi.port` -for another upstream. `nifi.tlsName` must match the upstream certificate's TLS -name; it defaults to `nifi`. - -## Render and install - -Run from the platform repository root: - -```bash -helm lint ./deployment/charts/nginx -helm template cogstack-nginx ./deployment/charts/nginx --namespace cogstack -helm upgrade --install cogstack-nginx ./deployment/charts/nginx \ - --namespace cogstack --create-namespace -``` - -Pass deployment overrides with `-f /path/to/nginx-values.yaml`. Set `image.tag` -to the image release required by the deployment. - -## Optional Ingress - -Ingress is disabled by default. Example deployment values: - -```yaml -ingress: - enabled: true - className: nginx - annotations: - nginx.ingress.kubernetes.io/backend-protocol: HTTPS - hosts: - - host: nifi.example.org - paths: - - path: / - pathType: Prefix - tls: - - secretName: nifi-ingress-tls - hosts: - - nifi.example.org -``` - -Configure annotations for the selected Ingress controller and provide any -referenced TLS Secret in the namespace. The chart's Service uses HTTPS on -`nginx.internalPort`, which defaults to `8443`. - -## Environment-based values - -`values.yaml` contains reusable defaults. `values.env.yaml` is an optional -`envsubst` input for deployment ports, upstream TLS name and resource limits. -Populate all referenced variables and render it to a separate values file before -passing it to Helm; Helm does not expand `${VARIABLE}` placeholders. - -The chart currently uses fixed `cogstack-nginx` resource names. Use separate -namespaces for independent deployments. diff --git a/deployment/charts/nginx/ci/ci-values.yaml b/deployment/charts/nginx/ci/ci-values.yaml deleted file mode 100644 index bcd196df..00000000 --- a/deployment/charts/nginx/ci/ci-values.yaml +++ /dev/null @@ -1,3 +0,0 @@ -# CI validates resource installation without deployment-owned ConfigMaps and Secrets. -# Runtime startup requires those inputs and a separate application smoke test. -replicaCount: 0 diff --git a/deployment/charts/nginx/templates/deployment.yaml b/deployment/charts/nginx/rendered.yaml similarity index 50% rename from deployment/charts/nginx/templates/deployment.yaml rename to deployment/charts/nginx/rendered.yaml index c69833c9..22d3dfd5 100644 --- a/deployment/charts/nginx/templates/deployment.yaml +++ b/deployment/charts/nginx/rendered.yaml @@ -1,10 +1,40 @@ +--- +# Source: nginx/templates/configmap.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: cogstack-nginx-env +data: + NIFI_UPSTREAM_PORT: "8443" + NIFI_UPSTREAM_TLS_NAME: "nifi" + NIFI_INTERNAL_PORT_NGINX: "8443" + NIFI_WEB_PROXY_PORT: "8443" + +--- +# Source: nginx/templates/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: cogstack-nginx +spec: + type: ClusterIP + selector: + app: cogstack-nginx + ports: + - name: https + port: 8443 + targetPort: 8443 + protocol: TCP + +--- +# Source: nginx/templates/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: cogstack-nginx spec: - replicas: {{ .Values.replicaCount }} + replicas: 1 selector: matchLabels: app: cogstack-nginx @@ -13,17 +43,22 @@ spec: metadata: labels: app: cogstack-nginx - annotations: - checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} - spec: containers: - name: nginx - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" - imagePullPolicy: {{ .Values.image.pullPolicy }} + image: "cogstacksystems/nifi-nginx:latest" + imagePullPolicy: Always ports: - - containerPort: {{ .Values.nginx.internalPort }} + - containerPort: 8443 + + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: NIFI_UPSTREAM_HOST + value: "cogstack-nifi.$(POD_NAMESPACE).svc.cluster.local" envFrom: - configMapRef: @@ -44,19 +79,24 @@ spec: timeoutSeconds: 10 resources: - {{- toYaml .Values.resources | nindent 12 }} + limits: + cpu: 1 + memory: 512M + requests: + cpu: 1 + memory: 128M volumes: - name: tls projected: sources: - secret: - name: {{ .Values.tls.rootCASecret }} + name: cogstack-root-ca items: - key: ca.crt path: root/root-ca.pem - secret: - name: {{ .Values.tls.existingSecret }} + name: nginx-tls items: - key: tls.crt path: nifi/nifi.pem diff --git a/deployment/charts/nginx/templates/configmap.yaml b/deployment/charts/nginx/templates/configmap.yaml deleted file mode 100644 index eeddd90f..00000000 --- a/deployment/charts/nginx/templates/configmap.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: cogstack-nginx-env -data: - NIFI_UPSTREAM_HOST: {{ default (printf "cogstack-nifi-web.%s.svc.cluster.local" .Release.Namespace) .Values.nifi.host | quote }} - NIFI_UPSTREAM_PORT: {{ .Values.nifi.port | quote }} - NIFI_UPSTREAM_TLS_NAME: {{ .Values.nifi.tlsName | quote }} - NIFI_INTERNAL_PORT_NGINX: {{ .Values.nginx.internalPort | quote }} - NIFI_WEB_PROXY_PORT: {{ .Values.nginx.internalPort | quote }} diff --git a/deployment/charts/nginx/templates/ingress.yaml b/deployment/charts/nginx/templates/ingress.yaml deleted file mode 100644 index e18130c2..00000000 --- a/deployment/charts/nginx/templates/ingress.yaml +++ /dev/null @@ -1,41 +0,0 @@ -{{- if .Values.ingress.enabled -}} -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: cogstack-nginx - labels: - app: cogstack-nginx - {{- with .Values.ingress.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -spec: - {{- with .Values.ingress.className }} - ingressClassName: {{ . }} - {{- 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 }} - pathType: {{ .pathType | default "Prefix" }} - backend: - service: - name: cogstack-nginx - port: - number: {{ $.Values.nginx.internalPort }} - {{- end }} - {{- end }} -{{- end }} diff --git a/deployment/charts/nginx/templates/service.yaml b/deployment/charts/nginx/templates/service.yaml deleted file mode 100644 index 1c01190d..00000000 --- a/deployment/charts/nginx/templates/service.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: cogstack-nginx -spec: - type: {{ .Values.service.type }} - selector: - app: cogstack-nginx - ports: - - name: https - port: {{ .Values.nginx.internalPort }} - targetPort: {{ .Values.nginx.internalPort }} - protocol: TCP diff --git a/deployment/charts/nginx/values.env.yaml b/deployment/charts/nginx/values.env.yaml deleted file mode 100644 index 7b1227fa..00000000 --- a/deployment/charts/nginx/values.env.yaml +++ /dev/null @@ -1,34 +0,0 @@ -replicaCount: 1 - -image: - repository: cogstacksystems/nifi-nginx - tag: "latest" - pullPolicy: Always - -nginx: - internalPort: ${NIFI_INTERNAL_PORT_NGINX} - -nifi: - # Empty uses cogstack-nifi-web..svc.cluster.local; override with a full DNS name. - host: "" - port: ${NIFI_INTERNAL_PORT} - tlsName: ${NIFI_UPSTREAM_TLS_NAME} - -tls: - rootCASecret: cogstack-root-ca - # NGINX's own tls.crt/tls.key retain the image's existing /certificates/nifi paths. - existingSecret: nginx-tls - -service: - type: ClusterIP - -ingress: - enabled: false - -resources: - requests: - cpu: ${NGINX_DOCKER_CPU_MIN} - memory: 128M - limits: - cpu: ${NGINX_DOCKER_CPU_MAX} - memory: ${NGINX_DOCKER_RAM} diff --git a/deployment/charts/nginx/values.yaml b/deployment/charts/nginx/values.yaml deleted file mode 100644 index 7fc8e7df..00000000 --- a/deployment/charts/nginx/values.yaml +++ /dev/null @@ -1,34 +0,0 @@ -replicaCount: 1 - -image: - repository: cogstacksystems/nifi-nginx - tag: "latest" - pullPolicy: Always - -nginx: - internalPort: 8443 - -nifi: - # Empty uses cogstack-nifi-web..svc.cluster.local; override with a full DNS name. - host: "" - port: 8443 - tlsName: nifi - -tls: - rootCASecret: cogstack-root-ca - # NGINX's own tls.crt/tls.key retain the image's existing /certificates/nifi paths. - existingSecret: nginx-tls - -service: - type: ClusterIP - -ingress: - enabled: false - -resources: - requests: - cpu: 1 - memory: 128M - limits: - cpu: 1 - memory: 512M diff --git a/deployment/charts/nifi/.helmignore b/deployment/charts/nifi/.helmignore deleted file mode 100644 index 0bbc476f..00000000 --- a/deployment/charts/nifi/.helmignore +++ /dev/null @@ -1,19 +0,0 @@ -# Local state and editor files do not belong in chart packages. -.DS_Store -.git/ -.gitignore -.bzr/ -.bzrignore -.hg/ -.hgignore -.svn/ -*.swp -*.bak -*.tmp -*.orig -*~ -.project -.idea/ -*.tmproj -.vscode/ -ci/ diff --git a/deployment/charts/nifi/Chart.yaml b/deployment/charts/nifi/Chart.yaml deleted file mode 100644 index 6eff45a0..00000000 --- a/deployment/charts/nifi/Chart.yaml +++ /dev/null @@ -1,14 +0,0 @@ -apiVersion: v2 -name: nifi -description: Helm chart for deploying CogStack Apache NiFi -type: application -version: 0.1.0 -appVersion: "latest" - -home: https://docs.cogstack.org/ -sources: - - https://github.com/CogStack/cogstack-platform -maintainers: - - name: vladd-bit - email: 62345326+vladd-bit@users.noreply.github.com -icon: "https://avatars.githubusercontent.com/u/28688163" diff --git a/deployment/charts/nifi/README.md b/deployment/charts/nifi/README.md deleted file mode 100644 index ba4c074e..00000000 --- a/deployment/charts/nifi/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# CogStack NiFi Helm chart - -Deploys the CogStack Apache NiFi image with a StatefulSet, headless and web -Services, a TLS configuration ConfigMap, and persistent storage for configuration -and NiFi repositories. Application sources and the Dockerfile live in -`apps/nifi/`. - -## Prerequisites - -Prepare these resources in the release namespace before installing: - -| Resource | Default name | Required contents | -| --- | --- | --- | -| ConfigMap | `nifi-env` | NiFi runtime environment settings for the deployment. | -| Secret | `nifi-auth` | Apache startup environment variables for login credentials, TLS passwords, the sensitive-properties key and the matching initial admin identity. | -| Secret | `cogstack-root-ca` | `ca.crt` and `truststore.jks`; the public CA and shared truststore. | -| Secret | `nifi-tls` | `nifi-keystore.jks`; the NiFi node certificate and private key. | - -Set `certificates.rootCASecret` and `certificates.existingSecret` to use different -certificate Secret names. The environment ConfigMap and authentication Secret -names are currently fixed in the workload template. - -The chart references these resources; it does not read host environment files or -create authentication or certificate Secrets. Keep private CA signing material -outside the pod. The namespace also needs a StorageClass or suitable -pre-provisioned persistent volumes for the six per-replica claims. - -## Render and install - -Run from the platform repository root: - -```bash -helm lint ./deployment/charts/nifi -helm template cogstack-nifi ./deployment/charts/nifi --namespace cogstack -helm upgrade --install cogstack-nifi ./deployment/charts/nifi \ - --namespace cogstack --create-namespace -``` - -Pass deployment overrides with `-f /path/to/nifi-values.yaml`. The default image -is `cogstacksystems/nifi:latest`; set `image.tag` to the image release -required by the deployment. - -For local access: - -```bash -kubectl -n cogstack port-forward svc/cogstack-nifi-web 8443:8443 -``` - -Open `https://localhost:8443/nifi/` using the deployment's trusted CA and -credentials. - -## Persistent configuration and data - -The chart creates one claim per replica for each of: - -- `flowfile_repository` -- `content_repository` -- `provenance_repository` -- `database_repository` -- `state` -- `conf` - -The initialization container seeds an empty configuration claim from -`$NIFI_HOME/conf` in the image, validates the required files and records a -`.nifi-bootstrap-complete` marker. Existing verified configuration is preserved -on upgrades. An interrupted initialization or an unverified non-empty claim -requires operator recovery before NiFi starts. - -Claims are retained when the StatefulSet is deleted or scaled down. Configure -storage with `persistence.storageClassName`, `persistence.accessModes` and -`persistence.volumes.`. A `null` StorageClass uses the cluster default; -an empty string selects no StorageClass. Each claim can override the global -StorageClass and access modes. Existing StatefulSet claim templates have -Kubernetes immutability constraints; plan storage changes and backups separately. - -Drivers, schemas and Python processors are bundled by the NiFi image. Startup -and readiness probes call its `/opt/nifi/scripts/cogstack-healthcheck.sh` -with the projected public CA. - -## Environment-based values - -`values.yaml` contains reusable defaults. `values.env.yaml` is an optional -`envsubst` input for deployment-specific UID/GID, ports and resource limits. -Populate all referenced variables and render it to a separate values file before -passing it to Helm; Helm does not expand `${VARIABLE}` placeholders. - -## Resource names - -The chart currently uses fixed `cogstack-nifi` workload and headless Service names -and a `cogstack-nifi-web` web Service. Use separate namespaces for independent -deployments. Increasing `replicaCount` also requires appropriate NiFi cluster -configuration, node identities and certificates in the supplied runtime inputs. diff --git a/deployment/charts/nifi/ci/ci-values.yaml b/deployment/charts/nifi/ci/ci-values.yaml deleted file mode 100644 index bcd196df..00000000 --- a/deployment/charts/nifi/ci/ci-values.yaml +++ /dev/null @@ -1,3 +0,0 @@ -# CI validates resource installation without deployment-owned ConfigMaps and Secrets. -# Runtime startup requires those inputs and a separate application smoke test. -replicaCount: 0 diff --git a/deployment/charts/nifi/rendered.yaml b/deployment/charts/nifi/rendered.yaml new file mode 100644 index 00000000..512f6a9e --- /dev/null +++ b/deployment/charts/nifi/rendered.yaml @@ -0,0 +1,250 @@ +--- +# Source: nifi/templates/tls-configmap.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: cogstack-nifi-tls-env +data: + AUTH: tls + NIFI_SECURITY_USER_AUTHORIZER: managed-authorizer + NIFI_SECURITY_USER_LOGIN_IDENTITY_PROVIDER: single-user-provider + NIFI_WEB_HTTPS_PORT: "8443" + # Kubernetes uses /certificates; Compose retains /security/certificates. + NIFI_KEYSTORE_PATH: /certificates/nifi/nifi-keystore.jks + NIFI_TRUSTSTORE_PATH: /certificates/nifi/nifi-truststore.jks + NIFI_HEALTHCHECK_CA_FILE: /certificates/root/root-ca.pem + KEYSTORE_PATH: /certificates/nifi/nifi-keystore.jks + TRUSTSTORE_PATH: /certificates/nifi/nifi-truststore.jks + KEYSTORE_TYPE: JKS + TRUSTSTORE_TYPE: JKS + +--- +# Source: nifi/templates/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: cogstack-nifi-headless +spec: + type: ClusterIP + clusterIP: None + selector: + app: cogstack-nifi + ports: + - name: https + port: 8443 + +--- +# Source: nifi/templates/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: cogstack-nifi +spec: + type: ClusterIP + selector: + app: cogstack-nifi + ports: + - name: https + port: 8443 + targetPort: 8443 + +--- +# Source: nifi/templates/statefulset.yaml +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: cogstack-nifi + +spec: + serviceName: cogstack-nifi-headless + replicas: 1 + persistentVolumeClaimRetentionPolicy: + whenDeleted: Retain + whenScaled: Retain + selector: + matchLabels: + app: cogstack-nifi + template: + metadata: + labels: + app: cogstack-nifi + annotations: + checksum/tls-config: 732afaede6adefc82e876f12b7f82e17d6fd4ecf10cc7a820b811e63bc62db43 + spec: + securityContext: + fsGroup: 1000 + fsGroupChangePolicy: OnRootMismatch + runAsGroup: 1000 + runAsNonRoot: true + runAsUser: 1000 + terminationGracePeriodSeconds: 120 + initContainers: + - name: initialize-conf + image: "cogstacksystems/nifi:latest" + imagePullPolicy: Always + securityContext: + allowPrivilegeEscalation: false + resources: + limits: + cpu: "1" + memory: 2G + requests: + cpu: "1" + memory: 2G + command: ["/bin/sh", "-ec"] + args: + - | + marker=/mnt/conf/.nifi-bootstrap-incomplete + complete=/mnt/conf/.nifi-bootstrap-complete + if [ -e "$marker" ]; then + echo "Interrupted conf initialization; restore the conf PVC before starting NiFi." >&2 + exit 1 + fi + test -w /mnt/conf || { echo "The conf PVC is not writable by the configured NiFi UID/GID." >&2; exit 1; } + if [ ! -f "$complete" ]; then + if [ -n "$(find /mnt/conf -mindepth 1 -maxdepth 1 ! -name lost+found -print -quit)" ]; then + echo "Unverified non-empty conf PVC; verify or restore its configuration before creating .nifi-bootstrap-complete." >&2 + exit 1 + fi + touch "$marker" + sync -f /mnt/conf + find "$NIFI_HOME/conf" -mindepth 1 -maxdepth 1 \ + -exec cp -R --preserve=mode,timestamps -t /mnt/conf -- {} + + fi + for file in nifi.properties bootstrap.conf state-management.xml authorizers.xml login-identity-providers.xml logback.xml; do + if [ ! -s "/mnt/conf/$file" ] || [ ! -r "/mnt/conf/$file" ] || [ ! -w "/mnt/conf/$file" ]; then + echo "Missing, empty or inaccessible NiFi configuration file: $file" >&2 + exit 1 + fi + done + if [ -e "$marker" ]; then + sync -f /mnt/conf + mv "$marker" "$complete" + sync -f /mnt/conf + fi + volumeMounts: + - name: conf + mountPath: /mnt/conf + containers: + - name: nifi + securityContext: + allowPrivilegeEscalation: false + envFrom: + - configMapRef: + name: nifi-env + - configMapRef: + name: cogstack-nifi-tls-env + # Login/password variables and matching INITIAL_ADMIN_IDENTITY only; no certificate files. + - secretRef: + name: nifi-auth + + volumeMounts: + - name: tls + mountPath: /certificates + readOnly: true + - name: flowfile-repository + mountPath: /opt/nifi/nifi-current/flowfile_repository + - name: content-repository + mountPath: /opt/nifi/nifi-current/content_repository + - name: provenance-repository + mountPath: /opt/nifi/nifi-current/provenance_repository + - name: database-repository + mountPath: /opt/nifi/nifi-current/database_repository + - name: state + mountPath: /opt/nifi/nifi-current/state + - name: conf + mountPath: /opt/nifi/nifi-current/conf + + image: "cogstacksystems/nifi:latest" + imagePullPolicy: Always + ports: + - containerPort: 8443 + startupProbe: + exec: + command: ["/opt/nifi/scripts/cogstack-healthcheck.sh", "startup"] + timeoutSeconds: 10 + failureThreshold: 30 + readinessProbe: + exec: + command: ["/opt/nifi/scripts/cogstack-healthcheck.sh", "ready"] + timeoutSeconds: 10 + resources: + limits: + cpu: "1" + memory: 2G + requests: + cpu: "1" + memory: 2G + + volumes: + - name: tls + projected: + sources: + - secret: + name: cogstack-root-ca + items: + - key: ca.crt + path: root/root-ca.pem + - key: truststore.jks + path: nifi/nifi-truststore.jks + - secret: + name: nifi-tls + items: + - key: nifi-keystore.jks + path: nifi/nifi-keystore.jks + + volumeClaimTemplates: + - metadata: + name: flowfile-repository + spec: + accessModes: + - ReadWriteOnce + volumeMode: Filesystem + resources: + requests: + storage: "20Gi" + - metadata: + name: content-repository + spec: + accessModes: + - ReadWriteOnce + volumeMode: Filesystem + resources: + requests: + storage: "100Gi" + - metadata: + name: provenance-repository + spec: + accessModes: + - ReadWriteOnce + volumeMode: Filesystem + resources: + requests: + storage: "50Gi" + - metadata: + name: database-repository + spec: + accessModes: + - ReadWriteOnce + volumeMode: Filesystem + resources: + requests: + storage: "5Gi" + - metadata: + name: state + spec: + accessModes: + - ReadWriteOnce + volumeMode: Filesystem + resources: + requests: + storage: "5Gi" + - metadata: + name: conf + spec: + accessModes: + - ReadWriteOnce + volumeMode: Filesystem + resources: + requests: + storage: "5Gi" diff --git a/deployment/charts/nifi/templates/service.yaml b/deployment/charts/nifi/templates/service.yaml deleted file mode 100644 index 387a45db..00000000 --- a/deployment/charts/nifi/templates/service.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: cogstack-nifi -spec: - clusterIP: None - selector: - app: cogstack-nifi - ports: - - name: https - port: {{ .Values.nifi.internalPort }} ---- -apiVersion: v1 -kind: Service -metadata: - name: cogstack-nifi-web -spec: - type: ClusterIP - selector: - app: cogstack-nifi - ports: - - name: https - port: {{ .Values.nifi.internalPort }} - targetPort: {{ .Values.nifi.internalPort }} diff --git a/deployment/charts/nifi/templates/statefulset.yaml b/deployment/charts/nifi/templates/statefulset.yaml deleted file mode 100644 index 815c814d..00000000 --- a/deployment/charts/nifi/templates/statefulset.yaml +++ /dev/null @@ -1,142 +0,0 @@ -{{- $directories := list "flowfile_repository" "content_repository" "provenance_repository" "database_repository" "state" "conf" -}} -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: cogstack-nifi - -spec: - serviceName: cogstack-nifi - replicas: {{ .Values.replicaCount }} - persistentVolumeClaimRetentionPolicy: - whenDeleted: Retain - whenScaled: Retain - selector: - matchLabels: - app: cogstack-nifi - template: - metadata: - labels: - app: cogstack-nifi - annotations: - checksum/tls-config: {{ include (print $.Template.BasePath "/tls-configmap.yaml") . | sha256sum }} - spec: - securityContext: - {{- toYaml .Values.podSecurityContext | nindent 8 }} - terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }} - initContainers: - - name: initialize-conf - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" - imagePullPolicy: {{ .Values.image.pullPolicy }} - securityContext: - {{- toYaml .Values.securityContext | nindent 12 }} - resources: - {{- toYaml .Values.resources | nindent 12 }} - command: ["/bin/sh", "-ec"] - args: - - | - marker=/mnt/conf/.nifi-bootstrap-incomplete - complete=/mnt/conf/.nifi-bootstrap-complete - if [ -e "$marker" ]; then - echo "Interrupted conf initialization; restore the conf PVC before starting NiFi." >&2 - exit 1 - fi - test -w /mnt/conf || { echo "The conf PVC is not writable by the configured NiFi UID/GID." >&2; exit 1; } - if [ ! -f "$complete" ]; then - if [ -n "$(find /mnt/conf -mindepth 1 -maxdepth 1 ! -name lost+found -print -quit)" ]; then - echo "Unverified non-empty conf PVC; verify or restore its configuration before creating .nifi-bootstrap-complete." >&2 - exit 1 - fi - touch "$marker" - sync -f /mnt/conf - find "$NIFI_HOME/conf" -mindepth 1 -maxdepth 1 \ - -exec cp -R --preserve=mode,timestamps -t /mnt/conf -- {} + - fi - for file in nifi.properties bootstrap.conf state-management.xml authorizers.xml login-identity-providers.xml logback.xml; do - if [ ! -s "/mnt/conf/$file" ] || [ ! -r "/mnt/conf/$file" ] || [ ! -w "/mnt/conf/$file" ]; then - echo "Missing, empty or inaccessible NiFi configuration file: $file" >&2 - exit 1 - fi - done - if [ -e "$marker" ]; then - sync -f /mnt/conf - mv "$marker" "$complete" - sync -f /mnt/conf - fi - volumeMounts: - - name: conf - mountPath: /mnt/conf - containers: - - name: nifi - securityContext: - {{- toYaml .Values.securityContext | nindent 12 }} - envFrom: - - configMapRef: - name: nifi-env - - configMapRef: - name: cogstack-nifi-tls-env - # Login/password variables and matching INITIAL_ADMIN_IDENTITY only; no certificate files. - - secretRef: - name: nifi-auth - - volumeMounts: - - name: tls - mountPath: /certificates - readOnly: true - {{- range $directory := $directories }} - - name: {{ $directory | replace "_" "-" }} - mountPath: /opt/nifi/nifi-current/{{ $directory }} - {{- end }} - - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" - imagePullPolicy: {{ .Values.image.pullPolicy }} - ports: - - containerPort: {{ .Values.nifi.internalPort | int }} - startupProbe: - exec: - command: ["/opt/nifi/scripts/cogstack-healthcheck.sh", "startup"] - timeoutSeconds: 10 - failureThreshold: 30 - readinessProbe: - exec: - command: ["/opt/nifi/scripts/cogstack-healthcheck.sh", "ready"] - timeoutSeconds: 10 - resources: - {{- toYaml .Values.resources | nindent 12 }} - - volumes: - - name: tls - projected: - sources: - - secret: - name: {{ .Values.certificates.rootCASecret }} - items: - - key: ca.crt - path: root/root-ca.pem - - key: truststore.jks - path: nifi/nifi-truststore.jks - - secret: - name: {{ .Values.certificates.existingSecret }} - items: - - key: nifi-keystore.jks - path: nifi/nifi-keystore.jks - - volumeClaimTemplates: - {{- range $directory := $directories }} - {{- $claim := required (printf "persistence.volumes.%s is required" $directory) (index $.Values.persistence.volumes $directory) }} - {{- $storageClass := $.Values.persistence.storageClassName }} - {{- if hasKey $claim "storageClassName" }} - {{- $storageClass = $claim.storageClassName }} - {{- end }} - - metadata: - name: {{ $directory | replace "_" "-" }} - spec: - accessModes: - {{- toYaml (default $.Values.persistence.accessModes $claim.accessModes) | nindent 10 }} - {{- if ne $storageClass nil }} - storageClassName: {{ $storageClass | quote }} - {{- end }} - volumeMode: Filesystem - resources: - requests: - storage: {{ required (printf "persistence.volumes.%s.size is required" $directory) $claim.size | quote }} - {{- end }} diff --git a/deployment/charts/nifi/templates/tls-configmap.yaml b/deployment/charts/nifi/templates/tls-configmap.yaml deleted file mode 100644 index 89669cff..00000000 --- a/deployment/charts/nifi/templates/tls-configmap.yaml +++ /dev/null @@ -1,17 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: cogstack-nifi-tls-env -data: - AUTH: tls - NIFI_SECURITY_USER_AUTHORIZER: managed-authorizer - NIFI_SECURITY_USER_LOGIN_IDENTITY_PROVIDER: single-user-provider - NIFI_WEB_HTTPS_PORT: {{ .Values.nifi.internalPort | quote }} - # Kubernetes uses /certificates; Compose retains /security/certificates. - NIFI_KEYSTORE_PATH: /certificates/nifi/nifi-keystore.jks - NIFI_TRUSTSTORE_PATH: /certificates/nifi/nifi-truststore.jks - NIFI_HEALTHCHECK_CA_FILE: /certificates/root/root-ca.pem - KEYSTORE_PATH: /certificates/nifi/nifi-keystore.jks - TRUSTSTORE_PATH: /certificates/nifi/nifi-truststore.jks - KEYSTORE_TYPE: JKS - TRUSTSTORE_TYPE: JKS diff --git a/deployment/charts/nifi/values.env.yaml b/deployment/charts/nifi/values.env.yaml deleted file mode 100644 index cf3b53f5..00000000 --- a/deployment/charts/nifi/values.env.yaml +++ /dev/null @@ -1,67 +0,0 @@ -nameOverride: "" -fullnameOverride: "" - -replicaCount: 1 - -image: - repository: cogstacksystems/nifi - tag: "latest" - pullPolicy: Always - - -podAnnotations: {} -podLabels: {} - -securityContext: - allowPrivilegeEscalation: false - -podSecurityContext: - runAsNonRoot: true - runAsUser: ${NIFI_UID} - runAsGroup: ${NIFI_GID} - fsGroup: ${NIFI_GID} - fsGroupChangePolicy: OnRootMismatch - -nifi: - internalPort: ${NIFI_INTERNAL_PORT} - outputPort: ${NIFI_OUTPUT_PORT} - -certificates: - # Shared CA only: ca.crt and truststore.jks; never the root private-key keystore. - rootCASecret: cogstack-root-ca - # NiFi's JKS contains its certificate and private key; the CA truststore is shared. - existingSecret: nifi-tls - -persistence: - # null uses the cluster default; "" selects no StorageClass (pre-provisioned PVs). - # Select a durable production backend; Retain does not replace backups. - storageClassName: null - accessModes: [ReadWriteOnce] - # Every volume is a separate PVC per replica. Each can override storageClassName/accessModes. - # Existing data must be restored while NiFi is stopped; no automatic migration or resizing. - # Claim templates are immutable on existing StatefulSets; plan replacement/expansion explicitly. - volumes: - flowfile_repository: - size: 20Gi - content_repository: - size: 100Gi - provenance_repository: - size: 50Gi - database_repository: - size: 5Gi - state: - size: 5Gi - conf: - # Seeded only when empty; image upgrades never overwrite persisted configuration. - # Existing PVCs without .nifi-bootstrap-complete require verification and explicit marking. - size: 5Gi - -resources: - requests: - cpu: "${NIFI_DOCKER_CPU_MIN}" - memory: "${NIFI_DOCKER_RAM}" - limits: - cpu: "${NIFI_DOCKER_CPU_MAX}" - memory: "${NIFI_DOCKER_RAM}" - -terminationGracePeriodSeconds: 120 diff --git a/deployment/charts/nifi/values.yaml b/deployment/charts/nifi/values.yaml deleted file mode 100644 index 9afa52be..00000000 --- a/deployment/charts/nifi/values.yaml +++ /dev/null @@ -1,67 +0,0 @@ -nameOverride: "" -fullnameOverride: "" - -replicaCount: 1 - -image: - repository: cogstacksystems/nifi - tag: "latest" - pullPolicy: Always - - -podAnnotations: {} -podLabels: {} - -securityContext: - allowPrivilegeEscalation: false - -podSecurityContext: - runAsNonRoot: true - runAsUser: 1000 - runAsGroup: 1000 - fsGroup: 1000 - fsGroupChangePolicy: OnRootMismatch - -nifi: - internalPort: 8443 - outputPort: 8082 - -certificates: - # Shared CA only: ca.crt and truststore.jks; never the root private-key keystore. - rootCASecret: cogstack-root-ca - # NiFi's JKS contains its certificate and private key; the CA truststore is shared. - existingSecret: nifi-tls - -persistence: - # null uses the cluster default; "" selects no StorageClass (pre-provisioned PVs). - # Select a durable production backend; Retain does not replace backups. - storageClassName: null - accessModes: [ReadWriteOnce] - # Every volume is a separate PVC per replica. Each can override storageClassName/accessModes. - # Existing data must be restored while NiFi is stopped; no automatic migration or resizing. - # Claim templates are immutable on existing StatefulSets; plan replacement/expansion explicitly. - volumes: - flowfile_repository: - size: 20Gi - content_repository: - size: 100Gi - provenance_repository: - size: 50Gi - database_repository: - size: 5Gi - state: - size: 5Gi - conf: - # Seeded only when empty; image upgrades never overwrite persisted configuration. - # Existing PVCs without .nifi-bootstrap-complete require verification and explicit marking. - size: 5Gi - -resources: - requests: - cpu: "1" - memory: "2G" - limits: - cpu: "1" - memory: "2G" - -terminationGracePeriodSeconds: 120 diff --git a/deployment/charts/ocr-service/.helmignore b/deployment/charts/ocr-service/.helmignore deleted file mode 100644 index 0e8a0eb3..00000000 --- a/deployment/charts/ocr-service/.helmignore +++ /dev/null @@ -1,23 +0,0 @@ -# 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/deployment/charts/ocr-service/CHANGELOG.md b/deployment/charts/ocr-service/CHANGELOG.md deleted file mode 100644 index b0ea49ca..00000000 --- a/deployment/charts/ocr-service/CHANGELOG.md +++ /dev/null @@ -1,8 +0,0 @@ -# Changelog - -## 0.1.0 (2026-09-24) - - -### Features - -* **helm:** Add OCR Service helm chart ([#127](https://github.com/CogStack/cogstack-platform/issues/127)) ([00b0cac](https://github.com/CogStack/cogstack-platform/commit/00b0cac1dab73fb0a95d3aec243ccacc4999cac1)) diff --git a/deployment/charts/ocr-service/Chart.yaml b/deployment/charts/ocr-service/Chart.yaml deleted file mode 100644 index fbcd1e41..00000000 --- a/deployment/charts/ocr-service/Chart.yaml +++ /dev/null @@ -1,41 +0,0 @@ -apiVersion: v2 -name: ocr-service-helm -description: A Helm chart to deploy CogStack OCR Service - -# 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.1.1" - -keywords: - - cogstack - - ocr - - rest-api - -home: https://docs.cogstack.org/ -sources: - - https://github.com/CogStack/cogstack-platform - - https://github.com/CogStack/cogstack-ocr-service - -maintainers: - - name: vladd-bit - email: 62345326+vladd-bit@users.noreply.github.com - url: https://github.com/CogStack - -icon: "https://avatars.githubusercontent.com/u/28688163" diff --git a/deployment/charts/ocr-service/README.md b/deployment/charts/ocr-service/README.md deleted file mode 100644 index 1473795e..00000000 --- a/deployment/charts/ocr-service/README.md +++ /dev/null @@ -1,123 +0,0 @@ -# ocr-service Helm Chart - -A Helm chart to deploy CogStack OCR Service - -**Homepage:** - -## Installation - -```sh -helm install ocr-service oci://registry-1.docker.io/cogstacksystems/ocr-service-helm -``` - -## Usage -For local testing, by default you can port forward the service using this command: - -```sh -kubectl port-forward svc/ocr-service 8090:8090 -``` - -Then navigate to http://localhost:8090 to try the service. You can also use http://localhost:8090/docs to view the REST APIs - -## Configuration - -To configure the service, create a values.yaml file and install with helm. - -## Values - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| affinity | object | `{}` | | -| autoscaling.enabled | bool | `false` | | -| autoscaling.maxReplicas | int | `100` | | -| autoscaling.minReplicas | int | `1` | | -| autoscaling.targetCPUUtilizationPercentage | int | `80` | | -| env.OCR_SERVICE_CONVERTER_THREADS | string | `"1"` | | -| env.OCR_SERVICE_CPU_THREADS | string | `"1"` | | -| env.OCR_SERVICE_DEBUG_MODE | string | `"false"` | | -| env.OCR_SERVICE_GUNICORN_GRACEFUL_TIMEOUT | string | `"30"` | | -| env.OCR_SERVICE_GUNICORN_LOG_FILE_PATH | string | `"-"` | | -| env.OCR_SERVICE_GUNICORN_LOG_LEVEL | string | `"info"` | | -| env.OCR_SERVICE_GUNICORN_MAX_REQUESTS | string | `"50000"` | | -| env.OCR_SERVICE_GUNICORN_MAX_REQUESTS_JITTER | string | `"5000"` | | -| env.OCR_SERVICE_GUNICORN_TIMEOUT | string | `"300"` | | -| env.OCR_SERVICE_HOST | string | `"0.0.0.0"` | | -| env.OCR_SERVICE_IMAGE_DPI | string | `"200"` | | -| env.OCR_SERVICE_LIBRE_OFFICE_PROCESS_TIMEOUT | string | `"20"` | | -| env.OCR_SERVICE_LOG_LEVEL | string | `"20"` | | -| env.OCR_SERVICE_OPERATION_MODE | string | `"OCR"` | | -| env.OCR_SERVICE_PORT | string | `"8090"` | | -| env.OCR_SERVICE_TESSERACT_CUSTOM_CONFIG_FLAGS | string | `""` | | -| env.OCR_SERVICE_TESSERACT_LANG | string | `"eng"` | | -| env.OCR_SERVICE_TESSERACT_NICE | string | `"-18"` | | -| env.OCR_SERVICE_TESSERACT_TIMEOUT | string | `"30"` | | -| env.OCR_SERVICE_WORKER_CLASS | string | `"sync"` | | -| env.OCR_TMP_DIR | string | `"/ocr_service/tmp"` | | -| env.OCR_WEB_SERVICE_WORKERS | string | `"1"` | | -| envValueFrom | object | `{"K8S_NODE_NAME":{"fieldRef":{"fieldPath":"spec.nodeName"}},"K8S_POD_NAME":{"fieldRef":{"fieldPath":"metadata.name"}},"K8S_POD_NAMESPACE":{"fieldRef":{"fieldPath":"metadata.namespace"}},"K8S_POD_UID":{"fieldRef":{"fieldPath":"metadata.uid"}}}` | Allow setting env values from field/configmap/secret references. Defaults to include k8s details for observability. | -| extraInitContainers | list | `[]` | Additional init containers to run before the main container. Can be templated | -| extraManifests | list | `[]` | Additional manifests to deploy to kubernetes. Can be templated | -| fullnameOverride | string | `""` | | -| hostAliases | list | `[]` | Host aliases for the pod | -| httpRoute | object | `{"annotations":{},"enabled":false,"hostnames":["chart-example.local"],"parentRefs":[{"name":"gateway","sectionName":"http"}],"rules":[{"matches":[{"path":{"type":"PathPrefix","value":"/headers"}}]}]}` | Expose the service via gateway-api HTTPRoute Requires Gateway API resources and suitable controller installed within the cluster (see: https://gateway-api.sigs.k8s.io/guides/) | -| image | object | `{"pullPolicy":"IfNotPresent","repository":"cogstacksystems/ocr-service"}` | This sets the container image more information can be found here: https://kubernetes.io/docs/concepts/containers/images/ | -| image.pullPolicy | string | `"IfNotPresent"` | This sets the pull policy for images. | -| image.repository | string | `"cogstacksystems/ocr-service"` | Image repository for the MedCAT service container | -| imagePullSecrets | list | `[]` | This is for the secrets for pulling an image from a private repository more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ | -| ingress.annotations | object | `{}` | | -| ingress.className | string | `""` | | -| ingress.enabled | bool | `false` | | -| ingress.hosts[0].host | string | `"chart-example.local"` | | -| ingress.hosts[0].paths[0].path | string | `"/"` | | -| ingress.hosts[0].paths[0].pathType | string | `"ImplementationSpecific"` | | -| ingress.tls | list | `[]` | | -| livenessProbe.failureThreshold | int | `3` | | -| livenessProbe.httpGet.path | string | `"/api/health"` | | -| livenessProbe.httpGet.port | string | `"http"` | | -| livenessProbe.initialDelaySeconds | int | `30` | | -| livenessProbe.periodSeconds | int | `30` | | -| livenessProbe.timeoutSeconds | int | `5` | | -| nameOverride | string | `""` | This is to override the chart name. | -| nodeSelector | object | `{}` | | -| podAnnotations | object | `{}` | This is for setting Kubernetes Annotations to a Pod. For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ | -| podLabels | object | `{}` | This is for setting Kubernetes Labels to a Pod. For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ | -| podSecurityContext.fsGroup | int | `10001` | | -| podSecurityContext.fsGroupChangePolicy | string | `"OnRootMismatch"` | | -| readinessProbe.failureThreshold | int | `6` | | -| readinessProbe.httpGet.path | string | `"/api/ready"` | | -| readinessProbe.httpGet.port | string | `"http"` | | -| readinessProbe.initialDelaySeconds | int | `20` | | -| readinessProbe.periodSeconds | int | `10` | | -| readinessProbe.timeoutSeconds | int | `5` | | -| replicaCount | int | `1` | This will set the replicaset count more information can be found here: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/ | -| resources | object | `{}` | Configure resources for the pod. More information can be found here: https://kubernetes.io/docs/concepts/containers/ Recommendation for a default production model is { requests: { cpu: 500m, memory: 512Mi }, limits: { cpu: null , memory: 1Gi } } | -| runtimeClassName | string | `""` | Runtime class name for the pod (e.g., "nvidia" for GPU workloads) More information: https://kubernetes.io/docs/concepts/containers/runtime-class/ | -| securityContext.allowPrivilegeEscalation | bool | `false` | | -| securityContext.capabilities.drop[0] | string | `"ALL"` | | -| securityContext.readOnlyRootFilesystem | bool | `false` | | -| securityContext.runAsGroup | int | `10001` | | -| securityContext.runAsNonRoot | bool | `true` | | -| securityContext.runAsUser | int | `10001` | | -| service.port | int | `8090` | This sets the ports more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#field-spec-ports | -| service.type | string | `"ClusterIP"` | This sets the service type more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types | -| serviceAccount.annotations | object | `{}` | Annotations to add to the service account | -| serviceAccount.automount | bool | `true` | Automatically mount a ServiceAccount's API credentials? | -| serviceAccount.create | bool | `true` | Specifies whether a service account should be created | -| serviceAccount.name | string | `""` | The name of the service account to use. If not set and create is true, a name is generated using the fullname template | -| startupProbe.failureThreshold | int | `90` | | -| startupProbe.httpGet.path | string | `"/api/ready"` | | -| startupProbe.httpGet.port | string | `"http"` | | -| startupProbe.initialDelaySeconds | int | `2` | | -| startupProbe.periodSeconds | int | `10` | | -| startupProbe.timeoutSeconds | int | `5` | | -| tmp.emptyDir.medium | string | `""` | | -| tmp.emptyDir.sizeLimit | string | `"1Gi"` | | -| tmp.enabled | bool | `true` | | -| tmp.mountPath | string | `"/ocr_service/tmp"` | | -| tolerations | list | `[]` | | -| updateStrategy.type | string | `"RollingUpdate"` | Used for Kubernetes deployment .spec.strategy.type. Allowed values are "Recreate" or "RollingUpdate". | -| volumeMounts | list | `[]` | Additional volumeMounts on the output Deployment definition. | -| volumes | list | `[]` | Additional volumes on the output Deployment definition. | - ----------------------------------------------- -Autogenerated from chart metadata using [helm-docs v1.14.2](https://github.com/norwoodj/helm-docs/releases/v1.14.2) \ No newline at end of file diff --git a/deployment/charts/ocr-service/README.md.gotmpl b/deployment/charts/ocr-service/README.md.gotmpl deleted file mode 100644 index 6d098252..00000000 --- a/deployment/charts/ocr-service/README.md.gotmpl +++ /dev/null @@ -1,33 +0,0 @@ -# ocr-service Helm Chart - -{{ template "chart.description" . }} - -{{ template "chart.homepageLine" . }} - -## Installation - -```sh -helm install ocr-service oci://registry-1.docker.io/cogstacksystems/ocr-service-helm -``` - -## Usage -For local testing, by default you can port forward the service using this command: - -```sh -kubectl port-forward svc/ocr-service 8090:8090 -``` - -Then navigate to http://localhost:8090 to try the service. You can also use http://localhost:8090/docs to view the REST APIs - - -## Configuration - -To configure the service, create a values.yaml file and install with helm. - - - -{{ template "chart.requirementsSection" . }} - -{{ template "chart.valuesSection" . }} - -{{ template "helm-docs.versionFooter" . }} \ No newline at end of file diff --git a/deployment/charts/ocr-service/rendered.yaml b/deployment/charts/ocr-service/rendered.yaml new file mode 100644 index 00000000..323d8fba --- /dev/null +++ b/deployment/charts/ocr-service/rendered.yaml @@ -0,0 +1,157 @@ +--- +# Source: ocr-service-helm/templates/serviceaccount.yaml +apiVersion: v1 +kind: ServiceAccount +metadata: + name: ocr-service + labels: + app.kubernetes.io/name: ocr-service-helm + app.kubernetes.io/instance: ocr-service +automountServiceAccountToken: true + +--- +# Source: ocr-service-helm/templates/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: ocr-service + labels: + app.kubernetes.io/name: ocr-service-helm + app.kubernetes.io/instance: ocr-service +spec: + type: ClusterIP + ports: + - port: 8090 + targetPort: http + protocol: TCP + name: http + selector: + app.kubernetes.io/name: ocr-service-helm + app.kubernetes.io/instance: ocr-service + +--- +# Source: ocr-service-helm/templates/deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ocr-service + labels: + app.kubernetes.io/name: ocr-service-helm + app.kubernetes.io/instance: ocr-service +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: ocr-service-helm + app.kubernetes.io/instance: ocr-service + template: + metadata: + labels: + app.kubernetes.io/name: ocr-service-helm + app.kubernetes.io/instance: ocr-service + spec: + serviceAccountName: ocr-service + securityContext: + fsGroup: 10001 + fsGroupChangePolicy: OnRootMismatch + containers: + - name: ocr-service-helm + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + readOnlyRootFilesystem: false + runAsGroup: 10001 + runAsNonRoot: true + runAsUser: 10001 + image: "cogstacksystems/ocr-service:1.1.1" + imagePullPolicy: IfNotPresent + env: + - name: "K8S_NODE_NAME" + valueFrom: + fieldRef: + fieldPath: spec.nodeName + - name: "K8S_POD_NAME" + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: "K8S_POD_NAMESPACE" + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: "K8S_POD_UID" + valueFrom: + fieldRef: + fieldPath: metadata.uid + - name: "OCR_SERVICE_CONVERTER_THREADS" + value: "1" + - name: "OCR_SERVICE_CPU_THREADS" + value: "1" + - name: "OCR_SERVICE_DEBUG_MODE" + value: "false" + - name: "OCR_SERVICE_GUNICORN_GRACEFUL_TIMEOUT" + value: "30" + - name: "OCR_SERVICE_GUNICORN_LOG_FILE_PATH" + value: "-" + - name: "OCR_SERVICE_GUNICORN_LOG_LEVEL" + value: "info" + - name: "OCR_SERVICE_GUNICORN_MAX_REQUESTS" + value: "50000" + - name: "OCR_SERVICE_GUNICORN_MAX_REQUESTS_JITTER" + value: "5000" + - name: "OCR_SERVICE_GUNICORN_TIMEOUT" + value: "300" + - name: "OCR_SERVICE_HOST" + value: "0.0.0.0" + - name: "OCR_SERVICE_IMAGE_DPI" + value: "200" + - name: "OCR_SERVICE_LIBRE_OFFICE_PROCESS_TIMEOUT" + value: "20" + - name: "OCR_SERVICE_LOG_LEVEL" + value: "20" + - name: "OCR_SERVICE_OPERATION_MODE" + value: "OCR" + - name: "OCR_SERVICE_PORT" + value: "8090" + - name: "OCR_SERVICE_TESSERACT_CUSTOM_CONFIG_FLAGS" + value: "" + - name: "OCR_SERVICE_TESSERACT_LANG" + value: "eng" + - name: "OCR_SERVICE_TESSERACT_NICE" + value: "-18" + - name: "OCR_SERVICE_TESSERACT_TIMEOUT" + value: "30" + - name: "OCR_SERVICE_WORKER_CLASS" + value: "sync" + - name: "OCR_TMP_DIR" + value: "/ocr_service/tmp" + - name: "OCR_WEB_SERVICE_WORKERS" + value: "1" + ports: + - name: http + containerPort: 8090 + protocol: TCP + livenessProbe: + failureThreshold: 3 + httpGet: + path: /api/health + port: http + initialDelaySeconds: 30 + periodSeconds: 30 + timeoutSeconds: 5 + readinessProbe: + failureThreshold: 6 + httpGet: + path: /api/ready + port: http + initialDelaySeconds: 20 + periodSeconds: 10 + timeoutSeconds: 5 + volumeMounts: + - name: ocr-tmp + mountPath: "/ocr_service/tmp" + volumes: + - name: ocr-tmp + emptyDir: + sizeLimit: "1Gi" diff --git a/deployment/charts/ocr-service/templates/NOTES.txt b/deployment/charts/ocr-service/templates/NOTES.txt deleted file mode 100644 index df1d5dcb..00000000 --- a/deployment/charts/ocr-service/templates/NOTES.txt +++ /dev/null @@ -1,35 +0,0 @@ -1. Get the application URL by running these commands: -{{- if .Values.httpRoute.enabled }} -{{- if .Values.httpRoute.hostnames }} - export APP_HOSTNAME={{ .Values.httpRoute.hostnames | first }} -{{- else }} - export APP_HOSTNAME=$(kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o jsonpath="{.spec.listeners[0].hostname}") - {{- end }} -{{- if and .Values.httpRoute.rules (first .Values.httpRoute.rules).matches (first (first .Values.httpRoute.rules).matches).path.value }} - echo "Visit http://$APP_HOSTNAME{{ (first (first .Values.httpRoute.rules).matches).path.value }} to use your application" - - NOTE: Your HTTPRoute depends on the listener configuration of your gateway and your HTTPRoute rules. - The rules can be set for path, method, header and query parameters. - You can check the gateway configuration with 'kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o yaml' -{{- end }} -{{- else 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 "ocr-service-helm.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 its status by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "ocr-service-helm.fullname" . }}' - export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "ocr-service-helm.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 "ocr-service-helm.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/deployment/charts/ocr-service/templates/_helpers.tpl b/deployment/charts/ocr-service/templates/_helpers.tpl deleted file mode 100644 index 1a9d1467..00000000 --- a/deployment/charts/ocr-service/templates/_helpers.tpl +++ /dev/null @@ -1,63 +0,0 @@ -{{/* -Expand the name of the chart. -*/}} -{{- define "ocr-service-helm.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 "ocr-service-helm.fullname" -}} -{{- if .Values.fullnameOverride }} -{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} -{{- else }} -{{- $name := default .Chart.Name .Values.nameOverride }} -{{- $basename := $name | trimSuffix "-helm" }} -{{- if or (contains $name .Release.Name) (eq .Release.Name $basename) }} -{{- .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 "ocr-service-helm.chart" -}} -{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} -{{- end }} - -{{/* -Common labels -*/}} -{{- define "ocr-service-helm.labels" -}} -helm.sh/chart: {{ include "ocr-service-helm.chart" . }} -{{ include "ocr-service-helm.selectorLabels" . }} -{{- if .Chart.AppVersion }} -app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} -{{- end }} -app.kubernetes.io/managed-by: {{ .Release.Service }} -{{- end }} - -{{/* -Selector labels -*/}} -{{- define "ocr-service-helm.selectorLabels" -}} -app.kubernetes.io/name: {{ include "ocr-service-helm.name" . }} -app.kubernetes.io/instance: {{ .Release.Name }} -{{- end }} - -{{/* -Create the name of the service account to use -*/}} -{{- define "ocr-service-helm.serviceAccountName" -}} -{{- if .Values.serviceAccount.create }} -{{- default (include "ocr-service-helm.fullname" .) .Values.serviceAccount.name }} -{{- else }} -{{- default "default" .Values.serviceAccount.name }} -{{- end }} -{{- end }} diff --git a/deployment/charts/ocr-service/templates/deployment.yaml b/deployment/charts/ocr-service/templates/deployment.yaml deleted file mode 100644 index 856655c1..00000000 --- a/deployment/charts/ocr-service/templates/deployment.yaml +++ /dev/null @@ -1,116 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: {{ include "ocr-service-helm.fullname" . }} - labels: - {{- include "ocr-service-helm.labels" . | nindent 4 }} -spec: - {{- if not .Values.autoscaling.enabled }} - replicas: {{ .Values.replicaCount }} - {{- end }} - selector: - matchLabels: - {{- include "ocr-service-helm.selectorLabels" . | nindent 6 }} - template: - metadata: - {{- with .Values.podAnnotations }} - annotations: - {{- toYaml . | nindent 8 }} - {{- end }} - labels: - {{- include "ocr-service-helm.labels" . | nindent 8 }} - {{- with .Values.podLabels }} - {{- toYaml . | nindent 8 }} - {{- end }} - spec: - {{- with .Values.imagePullSecrets }} - imagePullSecrets: - {{- toYaml . | nindent 8 }} - {{- end }} - serviceAccountName: {{ include "ocr-service-helm.serviceAccountName" . }} - {{- with .Values.podSecurityContext }} - securityContext: - {{- toYaml . | nindent 8 }} - {{- end }} - containers: - - name: {{ .Chart.Name }} - {{- with .Values.securityContext }} - securityContext: - {{- toYaml . | nindent 12 }} - {{- end }} - image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" - imagePullPolicy: {{ .Values.image.pullPolicy }} - env: - {{- range $key, $value := .Values.envValueFrom }} - - name: {{ $key | quote }} - valueFrom: - {{- tpl (toYaml $value) $ | nindent 14 }} - {{- end }} - {{- range $key, $value := .Values.env }} - - name: "{{ tpl $key $ }}" - value: "{{ tpl (print $value) $ }}" - {{- end }} - ports: - - name: http - containerPort: {{ .Values.service.port }} - protocol: TCP - {{- with .Values.livenessProbe }} - livenessProbe: - {{- toYaml . | nindent 12 }} - {{- end }} - {{- with .Values.readinessProbe }} - readinessProbe: - {{- toYaml . | nindent 12 }} - {{- end }} - {{- with .Values.resources }} - resources: - {{- toYaml . | nindent 12 }} - {{- end }} - {{- if or .Values.volumeMounts .Values.tmp.enabled }} - volumeMounts: - {{- if .Values.tmp.enabled }} - - name: ocr-tmp - mountPath: {{ .Values.tmp.mountPath | quote }} - {{- end }} - {{- with .Values.volumeMounts }} - {{- toYaml . | nindent 12 }} - {{- end }} - {{- end }} - {{- if or .Values.extraInitContainers }} - initContainers: - {{- end }} - {{- $root := . -}} - {{- with .Values.extraInitContainers }} - {{- tpl (toYaml .) $root | nindent 8 }} - {{- end }} - {{- if or .Values.volumes .Values.tmp.enabled }} - volumes: - {{- if .Values.tmp.enabled }} - - name: ocr-tmp - emptyDir: - {{- if .Values.tmp.emptyDir.medium }} - medium: {{ .Values.tmp.emptyDir.medium | quote }} - {{- end }} - {{- if .Values.tmp.emptyDir.sizeLimit }} - sizeLimit: {{ .Values.tmp.emptyDir.sizeLimit | quote }} - {{- end }} - {{- end }} - {{- with .Values.volumes }} - {{- toYaml . | nindent 8 }} - {{- end }} - {{- 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 }} - {{- if .Values.runtimeClassName }} - runtimeClassName: {{ .Values.runtimeClassName | quote }} - {{- end }} \ No newline at end of file diff --git a/deployment/charts/ocr-service/templates/extraManifests.yaml b/deployment/charts/ocr-service/templates/extraManifests.yaml deleted file mode 100644 index 928593c3..00000000 --- a/deployment/charts/ocr-service/templates/extraManifests.yaml +++ /dev/null @@ -1,4 +0,0 @@ -{{ range .Values.extraManifests }} ---- -{{ tpl (toYaml .) $ }} -{{ end }} \ No newline at end of file diff --git a/deployment/charts/ocr-service/templates/hpa.yaml b/deployment/charts/ocr-service/templates/hpa.yaml deleted file mode 100644 index 898fb8ae..00000000 --- a/deployment/charts/ocr-service/templates/hpa.yaml +++ /dev/null @@ -1,32 +0,0 @@ -{{- if .Values.autoscaling.enabled }} -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: {{ include "ocr-service-helm.fullname" . }} - labels: - {{- include "ocr-service-helm.labels" . | nindent 4 }} -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: {{ include "ocr-service-helm.fullname" . }} - minReplicas: {{ .Values.autoscaling.minReplicas }} - maxReplicas: {{ .Values.autoscaling.maxReplicas }} - metrics: - {{- if .Values.autoscaling.targetCPUUtilizationPercentage }} - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} - {{- end }} - {{- if .Values.autoscaling.targetMemoryUtilizationPercentage }} - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }} - {{- end }} -{{- end }} diff --git a/deployment/charts/ocr-service/templates/httproute.yaml b/deployment/charts/ocr-service/templates/httproute.yaml deleted file mode 100644 index 344938e5..00000000 --- a/deployment/charts/ocr-service/templates/httproute.yaml +++ /dev/null @@ -1,38 +0,0 @@ -{{- if .Values.httpRoute.enabled -}} -{{- $fullName := include "ocr-service-helm.fullname" . -}} -{{- $svcPort := .Values.service.port -}} -apiVersion: gateway.networking.k8s.io/v1 -kind: HTTPRoute -metadata: - name: {{ $fullName }} - labels: - {{- include "ocr-service-helm.labels" . | nindent 4 }} - {{- with .Values.httpRoute.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -spec: - parentRefs: - {{- with .Values.httpRoute.parentRefs }} - {{- toYaml . | nindent 4 }} - {{- end }} - {{- with .Values.httpRoute.hostnames }} - hostnames: - {{- toYaml . | nindent 4 }} - {{- end }} - rules: - {{- range .Values.httpRoute.rules }} - {{- with .matches }} - - matches: - {{- toYaml . | nindent 8 }} - {{- end }} - {{- with .filters }} - filters: - {{- toYaml . | nindent 8 }} - {{- end }} - backendRefs: - - name: {{ $fullName }} - port: {{ $svcPort }} - weight: 1 - {{- end }} -{{- end }} diff --git a/deployment/charts/ocr-service/templates/ingress.yaml b/deployment/charts/ocr-service/templates/ingress.yaml deleted file mode 100644 index c0da062a..00000000 --- a/deployment/charts/ocr-service/templates/ingress.yaml +++ /dev/null @@ -1,43 +0,0 @@ -{{- if .Values.ingress.enabled -}} -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: {{ include "ocr-service-helm.fullname" . }} - labels: - {{- include "ocr-service-helm.labels" . | nindent 4 }} - {{- with .Values.ingress.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -spec: - {{- with .Values.ingress.className }} - ingressClassName: {{ . }} - {{- 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 }} - {{- with .pathType }} - pathType: {{ . }} - {{- end }} - backend: - service: - name: {{ include "ocr-service-helm.fullname" $ }} - port: - number: {{ $.Values.service.port }} - {{- end }} - {{- end }} -{{- end }} diff --git a/deployment/charts/ocr-service/templates/service.yaml b/deployment/charts/ocr-service/templates/service.yaml deleted file mode 100644 index 804e3ac5..00000000 --- a/deployment/charts/ocr-service/templates/service.yaml +++ /dev/null @@ -1,18 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: {{ include "ocr-service-helm.fullname" . }} - labels: - {{- include "ocr-service-helm.labels" . | nindent 4 }} -spec: - type: {{ .Values.service.type }} - ports: - - port: {{ .Values.service.port }} - targetPort: http - protocol: TCP - name: http - {{- if (and (eq .Values.service.type "NodePort") ( .Values.service.nodePort)) }} - nodePort: {{ .Values.service.nodePort }} - {{- end }} - selector: - {{- include "ocr-service-helm.selectorLabels" . | nindent 4 }} diff --git a/deployment/charts/ocr-service/templates/serviceaccount.yaml b/deployment/charts/ocr-service/templates/serviceaccount.yaml deleted file mode 100644 index a77077c6..00000000 --- a/deployment/charts/ocr-service/templates/serviceaccount.yaml +++ /dev/null @@ -1,13 +0,0 @@ -{{- if .Values.serviceAccount.create -}} -apiVersion: v1 -kind: ServiceAccount -metadata: - name: {{ include "ocr-service-helm.serviceAccountName" . }} - labels: - {{- include "ocr-service-helm.labels" . | nindent 4 }} - {{- with .Values.serviceAccount.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -automountServiceAccountToken: {{ .Values.serviceAccount.automount }} -{{- end }} diff --git a/deployment/charts/ocr-service/templates/tests/test-connection.yaml b/deployment/charts/ocr-service/templates/tests/test-connection.yaml deleted file mode 100644 index c0e9f4f5..00000000 --- a/deployment/charts/ocr-service/templates/tests/test-connection.yaml +++ /dev/null @@ -1,15 +0,0 @@ -apiVersion: v1 -kind: Pod -metadata: - name: "{{ include "ocr-service-helm.fullname" . }}-test-connection" - labels: - {{- include "ocr-service-helm.labels" . | nindent 4 }} - annotations: - "helm.sh/hook": test -spec: - containers: - - name: wget - image: busybox - command: ['wget'] - args: ['{{ include "ocr-service-helm.fullname" . }}:{{ .Values.service.port }}/api/health', '-U helm-test {{ .Chart.Name }}-v{{ .Chart.Version }}'] - restartPolicy: Never diff --git a/deployment/charts/ocr-service/values-text-only.yaml b/deployment/charts/ocr-service/values-text-only.yaml deleted file mode 100644 index c66edeae..00000000 --- a/deployment/charts/ocr-service/values-text-only.yaml +++ /dev/null @@ -1,2 +0,0 @@ -env: - OCR_SERVICE_OPERATION_MODE: "NO_OCR" diff --git a/deployment/charts/ocr-service/values.yaml b/deployment/charts/ocr-service/values.yaml deleted file mode 100644 index aa161126..00000000 --- a/deployment/charts/ocr-service/values.yaml +++ /dev/null @@ -1,258 +0,0 @@ -# Default values for medcat-service. -# This is a YAML-formatted file. -# Declare variables to be passed into your templates. - -# -- This will set the replicaset count more information can be found here: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/ -replicaCount: 1 - -# -- This sets the container image more information can be found here: https://kubernetes.io/docs/concepts/containers/images/ -image: - # -- Image repository for the MedCAT service container - repository: cogstacksystems/ocr-service - # -- This sets the pull policy for images. - pullPolicy: IfNotPresent - # Overrides the image tag whose default is the chart appVersion. - # tag: "latest" - -tmp: - enabled: true - mountPath: /ocr_service/tmp - emptyDir: - medium: "" - sizeLimit: 1Gi - - -env: - OCR_SERVICE_HOST: "0.0.0.0" - OCR_SERVICE_PORT: "8090" - OCR_SERVICE_WORKER_CLASS: "sync" - OCR_WEB_SERVICE_WORKERS: "1" - OCR_SERVICE_LOG_LEVEL: "20" - OCR_SERVICE_DEBUG_MODE: "false" - OCR_SERVICE_OPERATION_MODE: "OCR" - OCR_SERVICE_CPU_THREADS: "1" - OCR_SERVICE_CONVERTER_THREADS: "1" - OCR_SERVICE_TESSERACT_LANG: "eng" - OCR_SERVICE_TESSERACT_TIMEOUT: "30" - OCR_SERVICE_TESSERACT_NICE: "-18" - OCR_SERVICE_TESSERACT_CUSTOM_CONFIG_FLAGS: "" - OCR_SERVICE_IMAGE_DPI: "200" - OCR_SERVICE_LIBRE_OFFICE_PROCESS_TIMEOUT: "20" - OCR_SERVICE_GUNICORN_LOG_FILE_PATH: "-" - OCR_SERVICE_GUNICORN_LOG_LEVEL: "info" - OCR_SERVICE_GUNICORN_MAX_REQUESTS_JITTER: "5000" - OCR_SERVICE_GUNICORN_MAX_REQUESTS: "50000" - OCR_SERVICE_GUNICORN_TIMEOUT: "300" - OCR_SERVICE_GUNICORN_GRACEFUL_TIMEOUT: "30" - OCR_TMP_DIR: "/ocr_service/tmp" - - -# -- Allow setting env values from field/configmap/secret references. Defaults to include k8s details for observability. -envValueFrom: - K8S_NODE_NAME: - fieldRef: - fieldPath: spec.nodeName - K8S_POD_NAME: - fieldRef: - fieldPath: metadata.name - K8S_POD_UID: - fieldRef: - fieldPath: metadata.uid - K8S_POD_NAMESPACE: - fieldRef: - fieldPath: metadata.namespace - -# -- This is for the secrets for pulling an image from a private repository more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ -imagePullSecrets: [] -# -- This is to override the chart name. -nameOverride: "" -fullnameOverride: "" - -updateStrategy: - # -- Used for Kubernetes deployment .spec.strategy.type. Allowed values are "Recreate" or "RollingUpdate". - type: RollingUpdate - # RollingUpdate default options example - # rollingUpdate: - # maxSurge: 25% - # maxUnavailable: 25% - -# This section builds out the service account more information can be found here: https://kubernetes.io/docs/concepts/security/service-accounts/ -serviceAccount: - # -- Specifies whether a service account should be created - create: true - # -- Automatically mount a ServiceAccount's API credentials? - automount: 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: "" - -# -- This is for setting Kubernetes Annotations to a Pod. -# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ -podAnnotations: {} -# -- This is for setting Kubernetes Labels to a Pod. -# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ -podLabels: {} - -podSecurityContext: - fsGroup: 10001 - fsGroupChangePolicy: OnRootMismatch - -securityContext: - runAsNonRoot: true - runAsUser: 10001 - runAsGroup: 10001 - allowPrivilegeEscalation: false - readOnlyRootFilesystem: false - capabilities: - drop: - - ALL - - -# This is for setting up a service more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/ -service: - # -- This sets the service type more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types - type: ClusterIP - # -- This sets the ports more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#field-spec-ports - port: 8090 - - -# This block is for setting up the ingress for more information can be found here: https://kubernetes.io/docs/concepts/services-networking/ingress/ -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 - -# -- Expose the service via gateway-api HTTPRoute -# Requires Gateway API resources and suitable controller installed within the cluster -# (see: https://gateway-api.sigs.k8s.io/guides/) -httpRoute: - # HTTPRoute enabled. - enabled: false - # HTTPRoute annotations. - annotations: {} - # Which Gateways this Route is attached to. - parentRefs: - - name: gateway - sectionName: http - # namespace: default - # Hostnames matching HTTP header. - hostnames: - - chart-example.local - # List of rules and filters applied. - rules: - - matches: - - path: - type: PathPrefix - value: /headers - # filters: - # - type: RequestHeaderModifier - # requestHeaderModifier: - # set: - # - name: My-Overwrite-Header - # value: this-is-the-only-value - # remove: - # - User-Agent - # - matches: - # - path: - # type: PathPrefix - # value: /echo - # headers: - # - name: version - # value: v2 - - -# -- Configure resources for the pod. More information can be found here: https://kubernetes.io/docs/concepts/containers/ -# Recommendation for a default production model is { requests: { cpu: 500m, memory: 512Mi }, limits: { cpu: null , memory: 1Gi } } -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: 2 # Note one general k8s recommendation is to leave CPU limit unset - # memory: 4Gi - # requests: - # cpu: 1 - # memory: 2Gi - -# This is to setup the liveness and readiness probes more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/ -livenessProbe: - httpGet: - path: /api/health - port: http - failureThreshold: 3 - periodSeconds: 30 - initialDelaySeconds: 30 - timeoutSeconds: 5 -readinessProbe: - httpGet: - path: /api/ready - port: http - failureThreshold: 6 - periodSeconds: 10 - initialDelaySeconds: 20 - timeoutSeconds: 5 -startupProbe: - httpGet: - path: /api/ready - port: http - failureThreshold: 90 - periodSeconds: 10 - initialDelaySeconds: 2 - timeoutSeconds: 5 - -# This section is for setting up autoscaling more information can be found here: https://kubernetes.io/docs/concepts/workloads/autoscaling/ -autoscaling: - enabled: false - minReplicas: 1 - maxReplicas: 100 - targetCPUUtilizationPercentage: 80 - # targetMemoryUtilizationPercentage: 80 - -# -- Additional volumes on the output Deployment definition. -volumes: [] -# - name: foo -# secret: -# secretName: mysecret -# optional: false - -# -- Additional volumeMounts on the output Deployment definition. -volumeMounts: [] -# - name: foo -# mountPath: "/etc/foo" -# readOnly: true - -# -- Runtime class name for the pod (e.g., "nvidia" for GPU workloads) -# More information: https://kubernetes.io/docs/concepts/containers/runtime-class/ -runtimeClassName: "" - -nodeSelector: {} - -tolerations: [] - -affinity: {} - -# -- Host aliases for the pod -hostAliases: [] - # - ip: "127.0.0.1" - # hostnames: - # - "foo.local" - -# -- Additional init containers to run before the main container. Can be templated -extraInitContainers: [] - -# -- Additional manifests to deploy to kubernetes. Can be templated -extraManifests: [] diff --git a/deployment/charts/opensearch-dashboards/rendered.yaml b/deployment/charts/opensearch-dashboards/rendered.yaml new file mode 100644 index 00000000..30c3267b --- /dev/null +++ b/deployment/charts/opensearch-dashboards/rendered.yaml @@ -0,0 +1,185 @@ +--- +# Source: opensearch-dashboards/charts/opensearch-dashboards/templates/serviceaccount.yaml +apiVersion: v1 +kind: ServiceAccount +metadata: + name: opensearch-dashboards-dashboards + labels: + helm.sh/chart: opensearch-dashboards-3.9.0 + app.kubernetes.io/name: opensearch-dashboards + app.kubernetes.io/instance: opensearch-dashboards + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm +--- +# Source: opensearch-dashboards/charts/opensearch-dashboards/templates/configmap.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: opensearch-dashboards-config + labels: + helm.sh/chart: opensearch-dashboards-3.9.0 + app.kubernetes.io/name: opensearch-dashboards + app.kubernetes.io/instance: opensearch-dashboards + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm +data: + opensearch_dashboards.yml: | + opensearch.ssl.certificateAuthorities: + - /tls/ca/ca.crt + opensearch.ssl.verificationMode: full + opensearch_security.cookie.password: ${COOKIE_PASS} + opensearch_security.cookie.secure: true + opensearchDashboards.index: .kibana + server.ssl.certificate: /tls/server/tls.crt + server.ssl.enabled: true + server.ssl.key: /tls/server/tls.key +--- +# Source: opensearch-dashboards/charts/opensearch-dashboards/templates/service.yaml +apiVersion: v1 +kind: Service +metadata: + name: opensearch-dashboards + labels: + helm.sh/chart: opensearch-dashboards-3.9.0 + app.kubernetes.io/name: opensearch-dashboards + app.kubernetes.io/instance: opensearch-dashboards + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm +spec: + type: ClusterIP + ports: + - port: 5601 + protocol: TCP + name: http + targetPort: 5601 + - name: metrics + protocol: TCP + port: 9601 + selector: + app.kubernetes.io/name: opensearch-dashboards + app.kubernetes.io/instance: opensearch-dashboards + +--- +# Source: opensearch-dashboards/charts/opensearch-dashboards/templates/deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: opensearch-dashboards + labels: + helm.sh/chart: opensearch-dashboards-3.9.0 + app.kubernetes.io/name: opensearch-dashboards + app.kubernetes.io/instance: opensearch-dashboards + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: opensearch-dashboards + app.kubernetes.io/instance: opensearch-dashboards + template: + metadata: + labels: + app.kubernetes.io/name: opensearch-dashboards + app.kubernetes.io/instance: opensearch-dashboards + annotations: + configchecksum: 560e54f7b0a1bfceca9f158c8259214cdba38c0224504307e1def2edebce4d5 + spec: + securityContext: + {} + serviceAccountName: opensearch-dashboards-dashboards + volumes: + - name: server-tls + secret: + secretName: dashboards-tls + - name: config + configMap: + name: opensearch-dashboards-config + # Currently some extra blocks accept strings + # to continue with backwards compatibility this is being kept + # whilst also allowing for yaml to be specified too. + - name: ca + secret: + items: + - key: ca.crt + path: ca.crt + secretName: opensearch-node-tls + containers: + - name: dashboards + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + runAsUser: 1000 + image: "opensearchproject/opensearch-dashboards:3.9.0" + imagePullPolicy: "IfNotPresent" + readinessProbe: + failureThreshold: 10 + initialDelaySeconds: 10 + periodSeconds: 20 + successThreshold: 1 + tcpSocket: + port: 5601 + timeoutSeconds: 5 + livenessProbe: + failureThreshold: 10 + initialDelaySeconds: 10 + periodSeconds: 20 + successThreshold: 1 + tcpSocket: + port: 5601 + timeoutSeconds: 5 + startupProbe: + failureThreshold: 20 + initialDelaySeconds: 10 + periodSeconds: 10 + successThreshold: 1 + tcpSocket: + port: 5601 + timeoutSeconds: 5 + env: + - name: OPENSEARCH_HOSTS + value: "https://opensearch-cluster-master:9200" + - name: SERVER_HOST + value: "0.0.0.0" + - name: OPENSEARCH_USERNAME + valueFrom: + secretKeyRef: + name: dashboards-auth + key: username + - name: OPENSEARCH_PASSWORD + valueFrom: + secretKeyRef: + name: dashboards-auth + key: password + - name: COOKIE_PASS + valueFrom: + secretKeyRef: + name: dashboards-auth + key: cookie + ports: + - containerPort: 5601 + name: http + protocol: TCP + resources: + limits: + cpu: "1" + memory: 1Gi + requests: + cpu: "1" + memory: 1Gi + volumeMounts: + - name: server-tls + mountPath: /tls/server + - name: config + mountPath: /usr/share/opensearch-dashboards/config/opensearch_dashboards.yml + subPath: opensearch_dashboards.yml + # Currently some extra blocks accept strings + # to continue with backwards compatibility this is being kept + # whilst also allowing for yaml to be specified too. + - mountPath: /tls/ca + name: ca + readOnly: true diff --git a/deployment/charts/opensearch/rendered.yaml b/deployment/charts/opensearch/rendered.yaml new file mode 100644 index 00000000..4af7ef2a --- /dev/null +++ b/deployment/charts/opensearch/rendered.yaml @@ -0,0 +1,502 @@ +--- +# Source: opensearch/charts/opensearch/templates/poddisruptionbudget.yaml +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: "opensearch-cluster-master-pdb" + labels: + helm.sh/chart: opensearch-3.9.0 + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/component: opensearch-cluster-master +spec: + maxUnavailable: 1 + selector: + matchLabels: + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + +--- +# Source: opensearch/charts/opensearch/templates/configmap.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: opensearch-cluster-master-config + labels: + helm.sh/chart: opensearch-3.9.0 + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/component: opensearch-cluster-master +data: + opensearch.yml: | + network.host: '${OPENSEARCH_NETWORK_HOST:0.0.0.0}' + network.publish_host: '${OPENSEARCH_NETWORK_PUBLISH_HOST:}' + logger.level: '${OPENSEARCH_LOG_LEVEL:INFO}' + + ###### CLUSTER CONFIGURATION ###### + + bootstrap.system_call_filter: '${OPENSEARCH_SYSTEM_CALL_FILTER:true}' + + # Docker supplies these settings through its environment. Helm supplies the + # Kubernetes discovery settings through the StatefulSet. + discovery.seed_hosts: '${OPENSEARCH_SEED_HOSTS:}' + cluster.initial_cluster_manager_nodes: '${OPENSEARCH_INITIAL_CLUSTER_MANAGER_NODES:}' + discovery.type: zen + + plugins.security.ssl.transport.pemcert_filepath: tls/node.crt + plugins.security.ssl.transport.pemkey_filepath: tls/node.key + plugins.security.ssl.transport.pemtrustedcas_filepath: tls/ca.crt + transport.ssl.enforce_hostname_verification: false + plugins.security.ssl.http.enabled: true + plugins.security.ssl.transport.enabled: true + plugins.security.ssl.http.pemcert_filepath: tls/node.crt + plugins.security.ssl.http.pemkey_filepath: tls/node.key + plugins.security.ssl.http.pemtrustedcas_filepath: tls/ca.crt + plugins.security.allow_unsafe_democertificates: false + plugins.security.allow_default_init_securityindex: '${OPENSEARCH_ALLOW_DEFAULT_INIT_SECURITYINDEX:false}' + + plugins.security.authcz.admin_dn: + - "CN=admin,OU=cogstack,O=cogstack,L=UK,ST=London,C=UK" + + plugins.security.nodes_dn: + - "CN=opensearch-shared,OU=cogstack,O=cogstack,L=UK,ST=London,C=UK" + + plugins.security.enable_snapshot_restore_privilege: true + plugins.security.check_snapshot_restore_write_privileges: true + cluster.routing.allocation.disk.threshold_enabled: true + + plugins.security.ssl.http.clientauth_mode : OPTIONAL + + plugins.security.roles_mapping_resolution: MAPPING_ONLY + + # Supply deployment-specific values on every node when using these features. + plugins.security.compliance.salt: '${OPENSEARCH_COMPLIANCE_SALT:}' + plugins.query.datasources.encryption.masterkey: '${OPENSEARCH_DATASOURCE_MASTER_KEY:}' + + ############## REST Management API configuration settings ############## + # Enable or disable role based access to the REST management API + # Default is that no role is allowed to access the REST management API. + plugins.security.restapi.roles_enabled: ["all_access", "security_rest_api_access"] + + # Disable particular endpoints and their HTTP methods for roles. + # By default all endpoints/methods are allowed. + #plugins.security.restapi.endpoints_disabled..: + # Example: + #plugins.security.restapi.endpoints_disabled.all_access.ACTIONGROUPS: ["PUT","POST","DELETE"] + #plugins.security.restapi.endpoints_disabled.xyz_role.LICENSE: ["DELETE"] + + # The following endpoints exist: + # ACTIONGROUPS + # CACHE + # CONFIG + # ROLES + # ROLESMAPPING + # INTERNALUSERS + # SYSTEMINFO + # PERMISSIONSINFO + + ############## Auditlog configuration settings ############## + + # Destination of the auditlog events + plugins.security.audit.type: internal_opensearch + plugins.security.audit.config.http_endpoints: '${OPENSEARCH_HOSTS:}' + plugins.security.audit.config.enable_ssl_client_auth: true + + #plugins.security.audit.enable_rest: false + #plugins.security.audit.enable_transport: false + #plugins.security.audit.config.disabled_rest_categories: NONE + #plugins.security.audit.config.disabled_transport_categories: NONE + #plugins.security.audit.config.index: auditlog6 # make sure you secure this index properly + #plugins.security.audit.config.index: "'auditlog6-'YYYY.MM.dd" #rotates index daily - make sure you secure this index properly + #plugins.security.audit.config.type: auditlog + #plugins.security.audit.config.username: auditloguser + #plugins.security.audit.config.password: auditlogpassword + #plugins.security.audit.config.enable_ssl: false + #plugins.security.audit.config.verify_hostnames: false + #plugins.security.audit.config.cert_alias: mycert + #plugins.security.audit.config.pemkey_filepath: key.pem + #plugins.security.audit.config.pemkey_content: <...pem base 64 content> + #plugins.security.audit.config.pemkey_password: secret + #plugins.security.audit.config.pemcert_filepath: cert.pem + #plugins.security.audit.config.pemcert_content: <...pem base 64 content> + #plugins.security.audit.config.pemtrustedcas_filepath: ca.pem + #plugins.security.audit.config.pemtrustedcas_content: <...pem base 64 content> + + # webhook settings + #plugins.security.audit.config.webhook.url: "http://mywebhook/endpoint" + # One of URL_PARAMETER_GET,URL_PARAMETER_POST,TEXT,JSON,SLACK + #plugins.security.audit.config.webhook.format: JSON + #plugins.security.audit.config.webhook.ssl.verify: false + #plugins.security.audit.config.webhook.ssl.pemtrustedcas_filepath: ca.pem + #plugins.security.audit.config.webhook.ssl.pemtrustedcas_content: <...pem base 64 content> + + # log4j settings + #plugins.security.audit.config.log4j.logger_name: auditlogger + #plugins.security.audit.config.log4j.level: INFO + + ############## Kerberos configuration settings ############## + # If Kerberos authentication should be used you have to configure: + + # The Path to the krb5.conf file + # Can be absolute or relative to the OpenSearch config directory + #plugins.security.kerberos.krb5_filepath: '/etc/krb5.conf' + + # The Path to the keytab where the acceptor_principal credentials are stored. + # Must be relative to the OpenSearch config directory + #plugins.security.kerberos.acceptor_keytab_filepath: 'eskeytab.tab' + + # Acceptor (Server) Principal name, must be present in acceptor_keytab_path file + #plugins.security.kerberos.acceptor_principal: 'HTTP/localhost' + + + ############## Expert settings ############## + # WARNING: Expert settings, do only use if you know what you are doing + # If you set wrong values here this this could be a security risk + # or make OpenSearch Security stop working + + # Name of the index where .opendistro_security stores its configuration. + + #plugins.security.config_index_name: .opendistro_security + + # This defines the OID of server node certificates + #plugins.security.cert.oid: '1.2.3.4.5.5' + + # This specifies the implementation of org.opensearch.security.transport.InterClusterRequestEvaluator + # that is used to determine inter-cluster request. + # Instances of org.opensearch.security.transport.InterClusterRequestEvaluator must implement a single argument + # constructor that takes an org.opensearch.common.settings.Settings + #plugins.security.cert.intercluster_request_evaluator_class: org.opensearch.security.transport.DefaultInterClusterRequestEvaluator + + # By default, normal users can restore snapshots if they have the priviliges 'cluster:admin/snapshot/restore', + # 'indices:admin/create', and 'indices:data/write/index' for the indices to be restored. + # To disable snapshot restore for normal users set 'plugins.security.enable_snapshot_restore_privilege: false'. + # This makes it so that only snapshot restore requests signed by an admin TLS certificate are accepted. + # A snapshot can only be restored when it does not contain global state and does not restore the '.opendistro_security' index + # If 'plugins.security.check_snapshot_restore_write_privileges: false' is set then the additional indices checks are omitted. + #plugins.security.enable_snapshot_restore_privilege: true + #plugins.security.check_snapshot_restore_write_privileges: true + + # Authentication cache timeout in minutes (A value of 0 disables caching, default is 60) + #plugins.security.cache.ttl_minutes: 60 + + # Disable OpenSearch Security + # WARNING: This can expose your configuration (including passwords) to the public. + #plugins.security.disabled: false + + # Protected indices are even more secure than normal indices. These indices require a role to access like any other index, but they require an additional role + # to be visible, listed in the plugins.security.protected_indices.roles setting. + # Enable protected indices + # plugins.security.protected_indices.enabled: true + # Specify a list of roles a user must be member of to touch any protected index. + # plugins.security.protected_indices.roles: ['all_access'] + + # Bundled plugins register their system indices with OpenSearch. Protect those + # registered indices without the deprecated plugins.security.system_indices.indices list. + # Allow explicit system:admin/system_index role permissions as well as super-admin access. + plugins.security.system_indices.enabled: true + plugins.security.system_indices.permission.enabled: true + + # ================= ML Commons ================= + + plugins.ml_commons.local_model.enabled: true + plugins.ml_commons.remote_inference.enabled: true + plugins.ml_commons.only_run_on_ml_node: false + plugins.ml_commons.allow_registering_model_via_url: true + plugins.ml_commons.allow_registering_model_via_local_file: true + # Permit HTTPS model repositories and only the dedicated read-only local model + # directory; do not allow arbitrary HTTP, FTP, or file-system paths. + plugins.ml_commons.trusted_url_regex: '^https://.*$|^file:///usr/share/opensearch/models/[^?#]+\.zip$' + # Permit ML Commons connectors to call only the Ollama service on the private + # CogStack Docker network. Docker resolves this stable service name to a + # private container IP, so both the general and private endpoint allowlists + # are required by OpenSearch 3.7 and later. + plugins.ml_commons.connector.private_ip_enabled: true + plugins.ml_commons.trusted_connector_endpoints_regex: + - '^http://ollama:11434/.*$' + - '^http://ollama-openai-proxy:11435/.*$' + plugins.ml_commons.trusted_connector_private_endpoints_regex: + - '^http://ollama:11434/.*$' + - '^http://ollama-openai-proxy:11435/.*$' + plugins.ml_commons.model_access_control_enabled: true + plugins.ml_commons.connector_access_control_enabled: true + plugins.ml_commons.safe_delete_model: true + plugins.ml_commons.agent_framework_enabled: true + plugins.ml_commons.rag_pipeline_feature_enabled: true + # Upper bound for asynchronous ML Commons tasks. Remote connector connection + # and response timeouts are configured per connector by opensearch-ai-init.sh. + plugins.ml_commons.ml_task_timeout_in_seconds: 600 + + # This cluster has no dedicated ML nodes, so allow both local and remote models + # to execute on data nodes. + plugins.ml_commons.task_dispatcher.eligible_node_role.local_model: + - data + plugins.ml_commons.task_dispatcher.eligible_node_role.remote_model: + - data + + + # Enable SQL-like queries, allows you to join across indices etc. + plugins.sql.enabled: true + plugins.ppl.enabled: true + + # Calcite (SQL v3 engine) + plugins.calcite.enabled: true + # WARNING: exists only in OpenSearch > 3.4, please DISABLE if you are not on this version as this setting doesn't exist. + plugins.calcite.all_join_types.allowed: true + + # coordinator-level kill switch for searches + search.cancel_after_time_interval: 5m + + # shard-level default timeout (can be overridden per request via "timeout") + search.default_search_timeout: 5m + + # relevant if SQL is paging via PIT + search.default_keep_alive: 10m + +--- +# Source: opensearch/charts/opensearch/templates/service.yaml +kind: Service +apiVersion: v1 +metadata: + name: opensearch-cluster-master + labels: + helm.sh/chart: opensearch-3.9.0 + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/component: opensearch-cluster-master + annotations: + {} +spec: + type: ClusterIP + selector: + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + ports: + - name: http + protocol: TCP + port: 9200 + - name: transport + protocol: TCP + port: 9300 + - name: metrics + protocol: TCP + port: 9600 + +--- +# Source: opensearch/charts/opensearch/templates/service.yaml +kind: Service +apiVersion: v1 +metadata: + name: opensearch-cluster-master-headless + labels: + helm.sh/chart: opensearch-3.9.0 + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/component: opensearch-cluster-master + annotations: + service.alpha.kubernetes.io/tolerate-unready-endpoints: "true" +spec: + clusterIP: None # This is needed for statefulset hostnames like opensearch-0 to resolve + # Create endpoints also if the related pod isn't ready + publishNotReadyAddresses: true + selector: + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + ports: + - name: http + port: 9200 + - name: transport + port: 9300 + - name: metrics + port: 9600 + +--- +# Source: opensearch/charts/opensearch/templates/statefulset.yaml +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: opensearch-cluster-master + labels: + helm.sh/chart: opensearch-3.9.0 + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/component: opensearch-cluster-master + annotations: + majorVersion: "3" +spec: + serviceName: opensearch-cluster-master-headless + selector: + matchLabels: + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + replicas: 1 + podManagementPolicy: Parallel + updateStrategy: + type: RollingUpdate + volumeClaimTemplates: + - metadata: + name: opensearch-cluster-master + spec: + accessModes: + - "ReadWriteOnce" + resources: + requests: + storage: "8Gi" + template: + metadata: + name: "opensearch-cluster-master" + labels: + helm.sh/chart: opensearch-3.9.0 + app.kubernetes.io/name: opensearch + app.kubernetes.io/instance: opensearch + app.kubernetes.io/version: "3.9.0" + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/component: opensearch-cluster-master + annotations: + configchecksum: b12ceef3b8576f2d1ecce0075e4684f17a60e96ad7f4c6439a661e95a2ba8fa + spec: + securityContext: + fsGroup: 1000 + runAsUser: 1000 + automountServiceAccountToken: false + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchExpressions: + - key: app.kubernetes.io/instance + operator: In + values: + - opensearch + - key: app.kubernetes.io/name + operator: In + values: + - opensearch + topologyKey: kubernetes.io/hostname + terminationGracePeriodSeconds: 120 + volumes: + - name: config + configMap: + name: opensearch-cluster-master-config + - emptyDir: {} + name: config-emptydir + - name: node-tls + secret: + secretName: opensearch-node-tls + defaultMode: 288 + enableServiceLinks: true + initContainers: + - name: fsgroup-volume + image: "busybox:latest" + imagePullPolicy: "IfNotPresent" + command: ['sh', '-c'] + args: + - 'chown -R 1000:1000 /usr/share/opensearch/data' + securityContext: + runAsUser: 0 + resources: + {} + volumeMounts: + - name: "opensearch-cluster-master" + mountPath: /usr/share/opensearch/data + - name: configfile + image: "opensearchproject/opensearch:3.9.0" + imagePullPolicy: "IfNotPresent" + command: + - sh + - -c + - | + #!/usr/bin/env bash + cp -r /tmp/configfolder/* /tmp/config/ + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + runAsUser: 1000 + resources: + {} + volumeMounts: + - mountPath: /tmp/config/ + name: config-emptydir + - name: config + mountPath: /tmp/configfolder/opensearch.yml + subPath: opensearch.yml + containers: + - name: "opensearch" + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + runAsUser: 1000 + + image: "opensearchproject/opensearch:3.9.0" + imagePullPolicy: "IfNotPresent" + readinessProbe: + failureThreshold: 3 + periodSeconds: 5 + tcpSocket: + port: 9200 + timeoutSeconds: 3 + startupProbe: + failureThreshold: 30 + initialDelaySeconds: 5 + periodSeconds: 10 + tcpSocket: + port: 9200 + timeoutSeconds: 3 + ports: + - name: http + containerPort: 9200 + - name: transport + containerPort: 9300 + - name: metrics + containerPort: 9600 + resources: + limits: + cpu: "1" + memory: 2Gi + requests: + cpu: "1" + memory: 2Gi + env: + - name: node.name + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: cluster.initial_master_nodes + value: "opensearch-cluster-master-0," + - name: discovery.seed_hosts + value: "opensearch-cluster-master-headless" + - name: cluster.name + value: "opensearch-cluster" + - name: network.host + value: "0.0.0.0" + - name: OPENSEARCH_JAVA_OPTS + value: "-Xmx512M -Xms512M" + - name: node.roles + value: "master,ingest,data,remote_cluster_client," + - name: DISABLE_INSTALL_DEMO_CONFIG + value: "true" + envFrom: + - configMapRef: + name: opensearch-env + optional: true + volumeMounts: + - name: "opensearch-cluster-master" + mountPath: /usr/share/opensearch/data + - name: node-tls + mountPath: /usr/share/opensearch/config/tls + - name: config-emptydir + mountPath: /usr/share/opensearch/config/opensearch.yml + subPath: opensearch.yml diff --git a/deployment/env/authentication.env b/deployment/env/authentication.env new file mode 100644 index 00000000..aa871deb --- /dev/null +++ b/deployment/env/authentication.env @@ -0,0 +1,14 @@ +# NiFi sample credentials for Docker development and k3s-load-auth-nifi. +# Environment values override these defaults. +NIFI_SINGLE_USER_CREDENTIALS_USERNAME="${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:-admin}" +NIFI_SINGLE_USER_CREDENTIALS_PASSWORD="${NIFI_SINGLE_USER_CREDENTIALS_PASSWORD:-cogstackNiFi}" + +# Store passwords are configured in certificates.env. +NIFI_INITIAL_ADMIN_IDENTITY=${NIFI_INITIAL_ADMIN_IDENTITY:-$NIFI_SINGLE_USER_CREDENTIALS_USERNAME} +NIFI_SENSITIVE_PROPS_KEY=${NIFI_SENSITIVE_PROPS_KEY:-c6063c770f5a281732877e7a9f7de2bc} + +# OpenSearch passwords for kibanaserver, nifi, cogstack_pipeline and cogstack_user. +OPENSEARCH_KIBANA_PASSWORD=${OPENSEARCH_KIBANA_PASSWORD:-} +OPENSEARCH_NIFI_PASSWORD=${OPENSEARCH_NIFI_PASSWORD:-} +OPENSEARCH_PIPELINE_PASSWORD=${OPENSEARCH_PIPELINE_PASSWORD:-} +OPENSEARCH_ANALYST_PASSWORD=${OPENSEARCH_ANALYST_PASSWORD:-} diff --git a/deployment/env/certificates.env b/deployment/env/certificates.env index bf9fee25..2cb9665c 100644 --- a/deployment/env/certificates.env +++ b/deployment/env/certificates.env @@ -1,28 +1,31 @@ -# Non-secret settings for the certificate generators. Leave blank to use the -# script defaults. Supply store passwords separately and use --days DAYS to -# set validity when running a generator. +# Certificate generator settings with development store passwords. +# Blank settings use the script defaults. Use --days DAYS to set validity. # -# Load from the repository root before running a generator. +# The certificate Make targets load this file automatically. +# For a direct generator invocation, load it from the repository root. # set -a +# source deployment/env/general.env # source deployment/env/certificates.env # set +a # Blank uses deployment/security/ for certificate inputs and outputs. -SECURITY_DIR= +SECURITY_DIR="${SECURITY_DIR:-}" # Optional names to add to the NiFi certificate. Match the names NGINX and the # health check verify in the deployment. -NIFI_UPSTREAM_TLS_NAME= -NIFI_HEALTHCHECK_HOST= - -# Set the namespace to include the NiFi web Service's full Kubernetes DNS name. -KUBE_NAMESPACE= -CLUSTER_DOMAIN=cluster.local +NIFI_UPSTREAM_TLS_NAME="${NIFI_UPSTREAM_TLS_NAME:-}" +NIFI_HEALTHCHECK_HOST="${NIFI_HEALTHCHECK_HOST:-}" # Browser-facing NGINX DNS names or IP addresses, comma-separated. # Blank uses localhost,127.0.0.1. -NGINX_TLS_NAMES= +NGINX_TLS_NAMES="${NGINX_TLS_NAMES:-}" # Optional comma-separated DNS aliases for each OpenSearch node and for Dashboards. -OPENSEARCH_NODE_DNS_NAMES= -OPENSEARCH_DASHBOARDS_DNS_NAMES= +OPENSEARCH_NODE_DNS_NAMES="${OPENSEARCH_NODE_DNS_NAMES:-}" +OPENSEARCH_DASHBOARDS_DNS_NAMES="${OPENSEARCH_DASHBOARDS_DNS_NAMES:-}" + +# Development store passwords. Environment values override these defaults. +NIFI_KEYSTORE_PASSWORD=${NIFI_KEYSTORE_PASSWORD:-cogstack} +NIFI_TRUSTSTORE_PASSWORD=${NIFI_TRUSTSTORE_PASSWORD:-cogstack} +OPENSEARCH_CERTIFICATE_PASSWORD=${OPENSEARCH_CERTIFICATE_PASSWORD:-${OS_CERTIFICATE_PASSWORD:-cogstack}} +ROOT_CERTIFICATE_KEYSTORE_PASSWORD="${ROOT_CERTIFICATE_KEYSTORE_PASSWORD:-cogstackNiFi}" diff --git a/deployment/env/general.env b/deployment/env/general.env new file mode 100644 index 00000000..5c8a2e08 --- /dev/null +++ b/deployment/env/general.env @@ -0,0 +1,28 @@ +# any other variables that you may want to use go here + +# Kubernetes namespace and DNS domain. +KUBE_NAMESPACE=cogstack +CLUSTER_DOMAIN=cluster.local + +# This is used to explicitly inform systems that run on Apple silicon to emulate this architecture +# set only CPU_ARCHITECTURE to amd/arm64 +# remove if this causes issues on any other platform +# possible values: amd64, arm64 +CPU_ARCHITECTURE=arm64 +DOCKER_DEFAULT_PLATFORM=linux/${CPU_ARCHITECTURE:-amd64} +COMPOSE_BAKE=True + +COGSTACK_ADMIN_EMAIL=admin@cogstack.net + +# used in NiFi for the timezone +TZ="Europe/London" + +# IMPORTANT: this is used to prefix all volumes created by docker-compose for ALL services, this includes SUBMODULES +# this has been added for backward compatibility with existing deployments +VOLUME_PREFIX=deploy_ + + +# this is the default, for containers which dont rely on individual settings +DOCKER_SHM_SIZE=512m +DOCKER_LOG_SIZE_PER_FILE="100m" +DOCKER_LOG_NUM_FILES=10 diff --git a/deployment/env/network_settings.env b/deployment/env/network_settings.env new file mode 100644 index 00000000..5ae69fcb --- /dev/null +++ b/deployment/env/network_settings.env @@ -0,0 +1,20 @@ +# use this file to set EXTRA_HOSTS in docker-compose +# useful if you have the services on separate machines/servers +# and you have generated SSL certificates using the container names rather than IP addresses +# this is the equivalent of /etc/hosts file, read this: https://tldp.org/LDP/solrhe/Securing-Optimizing-Linux-RH-Edition-v1.3/chap9sec95.html + + +# example ELASTICSEARCH_1_HOST_NAME="elasticsearch-1:0.0.0.0" +ELASTICSEARCH_1_HOST_NAME="test-1:0.0.0.0" +ELASTICSEARCH_2_HOST_NAME="test-2:0.0.0.0" +ELASTICSEARCH_3_HOST_NAME="test-3:0.0.0.0" +KIBANA_HOST_NAME="test-4:0.0.0.0" +NIFI_HOST_NAME="test-5:0.0.0.0" + +# general network settings +HTTPS_PROXY="" +HTTP_PROXY="" +NO_PROXY="" +no_proxy="" +http_proxy="" +https_proxy="" diff --git a/deployment/env/nifi.env b/deployment/env/nifi.env new file mode 120000 index 00000000..29e37aa8 --- /dev/null +++ b/deployment/env/nifi.env @@ -0,0 +1 @@ +../../apps/nifi/env/nifi.env \ No newline at end of file diff --git a/deployment/env/opensearch-dashboards.env b/deployment/env/opensearch-dashboards.env new file mode 120000 index 00000000..fbe3d735 --- /dev/null +++ b/deployment/env/opensearch-dashboards.env @@ -0,0 +1 @@ +../../apps/opensearch-dashboards/env/opensearch-dashboards.env \ No newline at end of file diff --git a/deployment/env/opensearch.env b/deployment/env/opensearch.env new file mode 120000 index 00000000..3ddb229e --- /dev/null +++ b/deployment/env/opensearch.env @@ -0,0 +1 @@ +../../apps/opensearch/env/opensearch.env \ No newline at end of file diff --git a/deployment/scripts/README.md b/deployment/scripts/README.md index e432fe85..a5817416 100644 --- a/deployment/scripts/README.md +++ b/deployment/scripts/README.md @@ -11,8 +11,22 @@ is 1,460 days for the root CA and OpenSearch certificates and 397 days for NiFi and NGINX. The root CA, NiFi and OpenSearch node generators also use Java's `keytool`. `SECURITY_DIR` defaults to `deployment/security/`. -If you need a root CA, export `ROOT_CERTIFICATE_KEYSTORE_PASSWORD` and run this -from the repository root. +The generators prompt for missing passwords with hidden input in a terminal. +For non-interactive runs, provide the required passwords through the environment +or the generator's configuration. + +`make -C deployment certs`, `make -C deployment certs-all` and the individual +certificate targets load `deployment/env/certificates.env` automatically. For +a direct invocation of the root CA generator, load the file to use its sample +store password. + +```bash +set -a +source deployment/env/certificates.env +set +a +``` + +The root CA generator uses `ROOT_CERTIFICATE_KEYSTORE_PASSWORD`. ```bash ./deployment/scripts/security/create_root_ca_cert.sh @@ -20,12 +34,13 @@ from the repository root. ### NiFi -Export the `KEYSTORE_PASSWORD` and `TRUSTSTORE_PASSWORD` that NiFi will use. -The legacy `NIFI_KEYSTORE_PASSWORD` and `NIFI_TRUSTSTORE_PASSWORD` names are -also accepted. +The NiFi generator and the default `k3s-load-auth-nifi` workflow read +`NIFI_KEYSTORE_PASSWORD` and `NIFI_TRUSTSTORE_PASSWORD` from +`deployment/env/certificates.env`. `KEYSTORE_PASSWORD` and +`TRUSTSTORE_PASSWORD` take precedence when set. Choose the command for your deployment. The default NiFi certificate covers -`nifi`, `localhost`, `cogstack-nifi`, `cogstack-nifi-web`, and `127.0.0.1`. +`nifi`, `localhost`, `cogstack-nifi`, `cogstack-nifi-headless`, and `127.0.0.1`. ```bash ./deployment/scripts/security/create_nifi_certs.sh @@ -39,7 +54,7 @@ NIFI_UPSTREAM_TLS_NAME=nifi.internal.example ./deployment/scripts/security/creat ``` For Kubernetes, set `KUBE_NAMESPACE` to include the web Service's full name. -For example, `cogstack` adds `cogstack-nifi-web.cogstack.svc.cluster.local`. +For example, `cogstack` adds `cogstack-nifi.cogstack.svc.cluster.local`. Set `CLUSTER_DOMAIN` if your cluster uses a domain other than `cluster.local`. ```bash @@ -67,7 +82,7 @@ It runs without a store password or `keytool`. ### OpenSearch -Export `ES_CERTIFICATE_PASSWORD` for the Java and PKCS#12 stores. Pass the node +Use `OPENSEARCH_CERTIFICATE_PASSWORD` for the Java and PKCS#12 stores. Pass the node hostnames when generating the node certificates. Generate the Dashboards and admin certificates with the second command. diff --git a/deployment/scripts/installation_utils/install_host_utils.sh b/deployment/scripts/installation_utils/install_host_utils.sh index d3a1ec73..41a37dc3 100755 --- a/deployment/scripts/installation_utils/install_host_utils.sh +++ b/deployment/scripts/installation_utils/install_host_utils.sh @@ -11,7 +11,7 @@ if [ "$os_distribution" == "debian" ] || [ "$os_distribution" == "ubuntu" ]; then install_missing_packages "$os_distribution" \ samba cifs-utils nfs-common nfs-kernel-server archivemount \ - htop iotop sysstat \ + htop iotop sysstat default-jdk \ jq gettext-base wget curl gnupg gnupg-agent git ca-certificates apt-transport-https python3 python3-pip python3-full openssl libssl-dev zip unzip tar nano gcc make python3-dev build-essential software-properties-common if command -v az >/dev/null 2>&1 || package_is_installed "$os_distribution" azure-cli; then @@ -27,7 +27,7 @@ elif [ "$os_distribution" == "redhat" ]; then install_missing_packages "$os_distribution" \ samba samba-client cifs-utils nfs-utils rpcbind archivemount \ - htop iotop sysstat \ + htop iotop sysstat java-21-openjdk-devel \ jq gettext yum-utils wget curl git device-mapper-persistent-data lvm2 python3 python3-pip libffi-devel openssl openssl-devel zip unzip tar nano gcc gcc-c++ make python3-devel libevent-devel if command -v az >/dev/null 2>&1 || package_is_installed "$os_distribution" azure-cli; then diff --git a/deployment/scripts/installation_utils/install_os_tools_and_software.sh b/deployment/scripts/installation_utils/install_os_tools_and_software.sh index 54c3076a..e95cfd95 100755 --- a/deployment/scripts/installation_utils/install_os_tools_and_software.sh +++ b/deployment/scripts/installation_utils/install_os_tools_and_software.sh @@ -22,6 +22,12 @@ os_distribution="$(bash "${script_dir}/detect_os.sh")" echo "Found distribution: $os_distribution " bash "${script_dir}/install_host_utils.sh" + +if ! keytool -help >/dev/null 2>&1; then + echo "Java keytool could not run after JDK installation." >&2 + exit 1 +fi + bash "${script_dir}/install_docker.sh" if [ "$install_k3s" = "true" ]; then diff --git a/deployment/scripts/security/create_nifi_certs.sh b/deployment/scripts/security/create_nifi_certs.sh index 3019c430..f4ca0135 100755 --- a/deployment/scripts/security/create_nifi_certs.sh +++ b/deployment/scripts/security/create_nifi_certs.sh @@ -9,7 +9,8 @@ # # Requires: # - Bash, OpenSSL and Java keytool -# - KEYSTORE_PASSWORD and TRUSTSTORE_PASSWORD in the environment +# - NiFi store passwords from the environment or deployment/env/certificates.env +# (prompted when missing) # - root-ca.pem and root-ca.key under certificates/root/ in SECURITY_DIR # # Optional environment variables: @@ -40,16 +41,16 @@ if (( $# > 0 )); then fi script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +if [[ -f "$script_dir/../../env/certificates.env" ]]; then + # shellcheck source=../../env/certificates.env + source "$script_dir/../../env/certificates.env" +fi security_dir=${SECURITY_DIR:-"$script_dir/../../security"} profile="$script_dir/../../security/templates/ssl-extensions-x509.cnf" ca_cert="$security_dir/certificates/root/root-ca.pem" ca_key="$security_dir/certificates/root/root-ca.key" output_dir="$security_dir/certificates/nifi" -export KEYSTORE_PASSWORD="${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD:-}}" -export TRUSTSTORE_PASSWORD="${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD:-}}" -: "${KEYSTORE_PASSWORD:?Set KEYSTORE_PASSWORD}" "${TRUSTSTORE_PASSWORD:?Set TRUSTSTORE_PASSWORD}" - for input in "$ca_cert" "$ca_key"; do if [[ ! -f "$input" || ! -r "$input" || ! -s "$input" ]]; then printf 'Missing or unreadable CA file %s. Run create_root_ca_cert.sh first.\n' "$input" >&2 @@ -65,6 +66,13 @@ for file in "${files[@]}"; do fi done +KEYSTORE_PASSWORD=${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD:-}} +TRUSTSTORE_PASSWORD=${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD:-}} +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" +require_password KEYSTORE_PASSWORD +require_password TRUSTSTORE_PASSWORD + # Build the whole bundle before publishing it. Clean up files written by this # run if any of the final writes fail. scratch_dir=$(mktemp -d) @@ -82,7 +90,7 @@ trap 'exit 143' TERM # === Add deployment-specific SANs to the template defaults names=("${NIFI_UPSTREAM_TLS_NAME:-}" "${NIFI_HEALTHCHECK_HOST:-}") if [[ -n "${KUBE_NAMESPACE:-}" ]]; then - names+=("cogstack-nifi-web.${KUBE_NAMESPACE}.svc.${CLUSTER_DOMAIN:-cluster.local}") + names+=("cogstack-nifi.${KUBE_NAMESPACE}.svc.${CLUSTER_DOMAIN:-cluster.local}") fi { diff --git a/deployment/scripts/security/create_opensearch_client_admin_certs.sh b/deployment/scripts/security/create_opensearch_client_admin_certs.sh index 8870836a..eaf36127 100755 --- a/deployment/scripts/security/create_opensearch_client_admin_certs.sh +++ b/deployment/scripts/security/create_opensearch_client_admin_certs.sh @@ -4,12 +4,14 @@ # 🔐 Create the OpenSearch Dashboards and admin certificates and keys # # Usage: -# ./create_opensearch_client_admin_certs.sh [--days DAYS] +# ./create_opensearch_client_admin_certs.sh [--admin-only|--dashboards-only] [--days DAYS] +# --admin-only skips the Dashboards certificate and PKCS#12 bundle. +# --dashboards-only skips the admin client certificate. # DAYS is a positive integer. The default validity is 1,460 days. # # Requires: # - Bash and OpenSSL -# - ES_CERTIFICATE_PASSWORD for the encrypted Dashboards PKCS#12 bundle +# - OPENSEARCH_CERTIFICATE_PASSWORD for the encrypted Dashboards PKCS#12 bundle # - root-ca.pem and root-ca.key under certificates/root/ in SECURITY_DIR # # Optional environment variables: @@ -31,17 +33,18 @@ set -euo pipefail umask 077 days=1460 +mode= +case ${1:-} in + --admin-only|--dashboards-only) mode=$1; shift ;; +esac if (( $# > 0 )); then if [[ $# -ne 2 || "$1" != --days || ! "$2" =~ ^[1-9][0-9]*$ ]]; then - printf 'Usage: %s [--days DAYS] (DAYS must be a positive integer)\n' "$0" >&2 + printf 'Usage: %s [--admin-only|--dashboards-only] [--days DAYS] (DAYS must be a positive integer)\n' "$0" >&2 exit 2 fi days=$2 fi -: "${ES_CERTIFICATE_PASSWORD:?Set ES_CERTIFICATE_PASSWORD}" -export ES_CERTIFICATE_PASSWORD - script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) security_dir=${SECURITY_DIR:-"$script_dir/../../security"} ca_cert="$security_dir/certificates/root/root-ca.pem" @@ -55,18 +58,32 @@ for input in "$ca_cert" "$ca_key"; do fi done -sans=DNS:opensearch-dashboards,DNS:kibana -if [[ -n "${OPENSEARCH_DASHBOARDS_DNS_NAMES:-}" ]]; then - dns_label='[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?' - dns_name="$dns_label(\.$dns_label)*" - if [[ ! "$OPENSEARCH_DASHBOARDS_DNS_NAMES" =~ ^$dns_name(,$dns_name)*$ ]]; then - printf 'OPENSEARCH_DASHBOARDS_DNS_NAMES must contain comma-separated DNS names.\n' >&2 - exit 2 +roles=() +files=() +if [[ "$mode" != --admin-only ]]; then + # shellcheck source=password_prompt.sh + source "$script_dir/password_prompt.sh" + OPENSEARCH_CERTIFICATE_PASSWORD=${OPENSEARCH_CERTIFICATE_PASSWORD:-${OS_CERTIFICATE_PASSWORD:-}} + require_password OPENSEARCH_CERTIFICATE_PASSWORD + roles=(client) + files=(es_kibana_client.pem es_kibana_client.key es_kibana_client.csr es_kibana_client.p12) + + sans=DNS:opensearch-dashboards,DNS:kibana + if [[ -n "${OPENSEARCH_DASHBOARDS_DNS_NAMES:-}" ]]; then + dns_label='[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?' + dns_name="$dns_label(\.$dns_label)*" + if [[ ! "$OPENSEARCH_DASHBOARDS_DNS_NAMES" =~ ^$dns_name(,$dns_name)*$ ]]; then + printf 'OPENSEARCH_DASHBOARDS_DNS_NAMES must contain comma-separated DNS names.\n' >&2 + exit 2 + fi + sans+=",DNS:${OPENSEARCH_DASHBOARDS_DNS_NAMES//,/,DNS:}" fi - sans+=",DNS:${OPENSEARCH_DASHBOARDS_DNS_NAMES//,/,DNS:}" +fi +if [[ "$mode" != --dashboards-only ]]; then + roles+=(admin) + files+=(admin.crt admin.key.pem admin.csr) fi -files=(es_kibana_client.pem es_kibana_client.key es_kibana_client.csr es_kibana_client.p12 admin.crt admin.key.pem admin.csr) for file in "${files[@]}"; do if [[ -e "$output_dir/$file" || -L "$output_dir/$file" ]]; then printf 'Output already exists: %s\n' "$output_dir/$file" >&2 @@ -88,7 +105,7 @@ trap 'exit 130' INT trap 'exit 143' TERM subject='/C=UK/ST=London/L=UK/O=cogstack/OU=cogstack' -for role in client admin; do +for role in "${roles[@]}"; do if [[ "$role" == client ]]; then key=es_kibana_client.key csr=es_kibana_client.csr @@ -111,9 +128,11 @@ for role in client admin; do openssl verify -CAfile "$ca_cert" "$scratch_dir/$cert" >/dev/null done -openssl pkcs12 -export -name es_kibana_client -inkey "$scratch_dir/es_kibana_client.key" \ - -in "$scratch_dir/es_kibana_client.pem" -certfile "$ca_cert" -out "$scratch_dir/es_kibana_client.p12" \ - -keypbe AES-256-CBC -certpbe AES-256-CBC -passout env:ES_CERTIFICATE_PASSWORD +if [[ "$mode" != --admin-only ]]; then + openssl pkcs12 -export -name es_kibana_client -inkey "$scratch_dir/es_kibana_client.key" \ + -in "$scratch_dir/es_kibana_client.pem" -certfile "$ca_cert" -out "$scratch_dir/es_kibana_client.p12" \ + -keypbe AES-256-CBC -certpbe AES-256-CBC -passout env:OPENSEARCH_CERTIFICATE_PASSWORD +fi (umask 022; mkdir -p -- "$output_dir") set -o noclobber @@ -122,6 +141,8 @@ for file in "${files[@]}"; do published+=("$output_dir/$file") cat -- "$scratch_dir/$file" } > "$output_dir/$file" + case "$file" in + *.crt|*.csr|es_kibana_client.pem) chmod 644 "$output_dir/$file" ;; + esac done -chmod 644 "$output_dir"/es_kibana_client.{pem,csr} "$output_dir"/admin.{crt,csr} -printf 'Created OpenSearch Dashboards and admin certificates under %s\n' "$output_dir" +printf 'Created OpenSearch client certificates under %s\n' "$output_dir" diff --git a/deployment/scripts/security/create_opensearch_node_cert.sh b/deployment/scripts/security/create_opensearch_node_cert.sh index d416bbeb..3dab08b7 100755 --- a/deployment/scripts/security/create_opensearch_node_cert.sh +++ b/deployment/scripts/security/create_opensearch_node_cert.sh @@ -8,7 +8,7 @@ # # Requires: # - Bash, OpenSSL and Java keytool -# - ES_CERTIFICATE_PASSWORD for the PKCS#12 bundle and Java stores +# - OPENSEARCH_CERTIFICATE_PASSWORD for the PKCS#12 bundle and Java stores # - root-ca.pem and root-ca.key under certificates/root/ in SECURITY_DIR # # Optional settings: @@ -92,8 +92,6 @@ for node in "$@"; do done done -: "${ES_CERTIFICATE_PASSWORD:?Set ES_CERTIFICATE_PASSWORD}" -export ES_CERTIFICATE_PASSWORD for input in "$ca_cert" "$ca_key"; do if [[ ! -f "$input" || ! -r "$input" || ! -s "$input" ]]; then printf 'Missing or unreadable CA file %s. Run create_root_ca_cert.sh first.\n' "$input" >&2 @@ -110,6 +108,11 @@ if [[ -e "$ca_alias" || -L "$ca_alias" ]]; then write_ca_alias=false fi +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" +OPENSEARCH_CERTIFICATE_PASSWORD=${OPENSEARCH_CERTIFICATE_PASSWORD:-${OS_CERTIFICATE_PASSWORD:-}} +require_password OPENSEARCH_CERTIFICATE_PASSWORD + # Stage all node bundles before writing deployment files. Roll back writes on failure. scratch_dir=$(mktemp -d) published=() @@ -150,15 +153,15 @@ for node in "$@"; do # Preserve OpenSearch's original aliases and the separate leaf-pinning truststore. openssl pkcs12 -export -name "$node" -inkey "$stage.key" -in "$stage.crt" \ -certfile "$ca_cert" -out "$stage.p12" -keypbe AES-256-CBC -certpbe AES-256-CBC \ - -passout env:ES_CERTIFICATE_PASSWORD + -passout env:OPENSEARCH_CERTIFICATE_PASSWORD keytool -importkeystore -noprompt -alias "$node" \ - -srckeystore "$stage.p12" -srcstoretype PKCS12 -srcstorepass:env ES_CERTIFICATE_PASSWORD \ + -srckeystore "$stage.p12" -srcstoretype PKCS12 -srcstorepass:env OPENSEARCH_CERTIFICATE_PASSWORD \ -destkeystore "$stage-keystore.jks" -deststoretype JKS \ - -deststorepass:env ES_CERTIFICATE_PASSWORD -destkeypass:env ES_CERTIFICATE_PASSWORD + -deststorepass:env OPENSEARCH_CERTIFICATE_PASSWORD -destkeypass:env OPENSEARCH_CERTIFICATE_PASSWORD keytool -importcert -noprompt -alias root-ca -file "$ca_cert" \ - -keystore "$stage-keystore.jks" -storetype JKS -storepass:env ES_CERTIFICATE_PASSWORD + -keystore "$stage-keystore.jks" -storetype JKS -storepass:env OPENSEARCH_CERTIFICATE_PASSWORD keytool -importcert -noprompt -alias "$node" -file "$stage.crt" \ - -keystore "$stage-truststore.key" -storetype JKS -storepass:env ES_CERTIFICATE_PASSWORD + -keystore "$stage-truststore.key" -storetype JKS -storepass:env OPENSEARCH_CERTIFICATE_PASSWORD done # Private files inherit mode 0600, and noclobber protects concurrent writes. diff --git a/deployment/scripts/security/create_root_ca_cert.sh b/deployment/scripts/security/create_root_ca_cert.sh index 7730d6a6..baae3e01 100755 --- a/deployment/scripts/security/create_root_ca_cert.sh +++ b/deployment/scripts/security/create_root_ca_cert.sh @@ -10,7 +10,7 @@ # # Requires: # - Bash, OpenSSL and Java keytool -# - ROOT_CERTIFICATE_KEYSTORE_PASSWORD in the environment +# - ROOT_CERTIFICATE_KEYSTORE_PASSWORD (prompted when unset) # - ../../security/templates/ssl-extensions-x509.cnf relative to this script # # Output: @@ -53,10 +53,6 @@ CRT_FILE="$ROOT_DIR/$CA_NAME.crt" CSR_FILE="$ROOT_DIR/$CA_NAME.csr" TRUSTSTORE_FILE="$ROOT_DIR/$CA_NAME-truststore.jks" -# OpenSSL and keytool read the store password from the environment. -: "${ROOT_CERTIFICATE_KEYSTORE_PASSWORD:?Set ROOT_CERTIFICATE_KEYSTORE_PASSWORD}" -export ROOT_CERTIFICATE_KEYSTORE_PASSWORD - # === Protect existing CA material # Replacing a CA invalidates trust for certificates issued under the old key. for output in "$KEY_FILE" "$PEM_FILE" "$CRT_FILE" "$CSR_FILE" "$P12_FILE" "$JKS_FILE" "$TRUSTSTORE_FILE"; do @@ -66,6 +62,10 @@ for output in "$KEY_FILE" "$PEM_FILE" "$CRT_FILE" "$CSR_FILE" "$P12_FILE" "$JKS_ fi done +# shellcheck source=password_prompt.sh +source "$SCRIPT_DIR/password_prompt.sh" +require_password ROOT_CERTIFICATE_KEYSTORE_PASSWORD + # Build the entire bundle in a private temporary directory. If publication fails, # remove the files written by this run and clean up the temporary directory. scratch_dir=$(mktemp -d) diff --git a/deployment/scripts/security/load_nifi_auth.sh b/deployment/scripts/security/load_nifi_auth.sh new file mode 100644 index 00000000..2ae6dd3a --- /dev/null +++ b/deployment/scripts/security/load_nifi_auth.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../../env/general.env +source "$script_dir/../../env/general.env" +namespace="${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}" +auth_file="${NIFI_AUTH_FILE:-$script_dir/../../env/authentication.env}" +# shellcheck disable=SC1090 # Optional deployment credentials. +if [[ -f "$auth_file" || -n ${NIFI_AUTH_FILE:-} ]]; then source "$auth_file"; fi +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" + +if [[ -z ${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:-} && -t 0 ]]; then + IFS= read -r -p 'NiFi username: ' NIFI_SINGLE_USER_CREDENTIALS_USERNAME +fi +: "${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:?Set NIFI_SINGLE_USER_CREDENTIALS_USERNAME or run in a terminal}" +require_password NIFI_SINGLE_USER_CREDENTIALS_PASSWORD +if (( ${#NIFI_SINGLE_USER_CREDENTIALS_PASSWORD} < 12 )); then + printf 'NiFi login password must be at least 12 characters.\n' >&2 + exit 1 +fi +if [[ -f "$script_dir/../../env/certificates.env" && + ( -z ${NIFI_AUTH_FILE:-} || "$auth_file" -ef "$script_dir/../../env/authentication.env" ) ]]; then + # shellcheck source=../../env/certificates.env + source "$script_dir/../../env/certificates.env" +fi +KEYSTORE_PASSWORD=${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD:-}} +TRUSTSTORE_PASSWORD=${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD:-}} +require_password KEYSTORE_PASSWORD +require_password TRUSTSTORE_PASSWORD + +existing=$(kubectl -n "$namespace" get secret nifi-auth --ignore-not-found -o json) +version=$(jq -r '.metadata.resourceVersion' <<< "$existing") +key=$(jq -r '.data.NIFI_SENSITIVE_PROPS_KEY // "" | @base64d' <<< "$existing") +NIFI_SENSITIVE_PROPS_KEY=${key:-${NIFI_SENSITIVE_PROPS_KEY:-$(openssl rand -hex 16)}} +NIFI_INITIAL_ADMIN_IDENTITY=${NIFI_INITIAL_ADMIN_IDENTITY:-$NIFI_SINGLE_USER_CREDENTIALS_USERNAME} +export NIFI_SENSITIVE_PROPS_KEY NIFI_INITIAL_ADMIN_IDENTITY NIFI_SINGLE_USER_CREDENTIALS_USERNAME + +manifest=$(jq -n --arg version "$version" '{ + apiVersion: "v1", kind: "Secret", + metadata: {name: "nifi-auth", resourceVersion: (if $version == "" then null else $version end)}, + stringData: { + SINGLE_USER_CREDENTIALS_USERNAME: env.NIFI_SINGLE_USER_CREDENTIALS_USERNAME, + SINGLE_USER_CREDENTIALS_PASSWORD: env.NIFI_SINGLE_USER_CREDENTIALS_PASSWORD, + INITIAL_ADMIN_IDENTITY: env.NIFI_INITIAL_ADMIN_IDENTITY, + KEYSTORE_PASSWORD: env.KEYSTORE_PASSWORD, + TRUSTSTORE_PASSWORD: env.TRUSTSTORE_PASSWORD, + NIFI_SENSITIVE_PROPS_KEY: env.NIFI_SENSITIVE_PROPS_KEY + } +}') +if [[ -z "$version" ]]; then + kubectl -n "$namespace" create -f - <<< "$manifest" +else + kubectl -n "$namespace" patch secret nifi-auth --type=merge --patch-file=/dev/stdin <<< "$manifest" +fi diff --git a/deployment/scripts/security/load_opensearch_auth.sh b/deployment/scripts/security/load_opensearch_auth.sh new file mode 100644 index 00000000..da49d5c6 --- /dev/null +++ b/deployment/scripts/security/load_opensearch_auth.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +set -euo pipefail + +service=${1:-} +case "$service" in + opensearch|opensearch-dashboards) ;; + *) printf '%s\n' 'Specify opensearch or opensearch-dashboards.' >&2; exit 2 ;; +esac + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../../env/general.env +source "$script_dir/../../env/general.env" +namespace="${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}" +pod=opensearch-cluster-master-0 + +if [[ "$service" == opensearch ]]; then + status=$(kubectl -n "$namespace" exec "$pod" -- curl -sS --noproxy '*' \ + --retry 3 --retry-delay 2 --retry-connrefused --max-time 10 \ + --cacert /usr/share/opensearch/config/tls/ca.crt --output /dev/null \ + --write-out '%{http_code}' https://localhost:9200/_plugins/_security/health) + case "$status" in + 200) printf '%s\n' 'OpenSearch Security is already initialized.'; exit 0 ;; + 503) ;; + *) printf 'OpenSearch Security health check returned HTTP %s.\n' "$status" >&2; exit 1 ;; + esac +fi + +auth_file=${OPENSEARCH_AUTH_FILE:-$script_dir/../../env/authentication.env} +# shellcheck disable=SC1090 # Optional deployment credentials. +if [[ -f "$auth_file" || -n ${OPENSEARCH_AUTH_FILE:-} ]]; then source "$auth_file"; fi +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" + +OPENSEARCH_KIBANA_PASSWORD=${OPENSEARCH_KIBANA_PASSWORD:-${KIBANA_PASSWORD:-}} +existing= +if [[ "$service" == opensearch-dashboards || -z "$OPENSEARCH_KIBANA_PASSWORD" ]]; then + existing=$(kubectl -n "$namespace" get secret dashboards-auth --ignore-not-found -o json) +fi +if [[ -z "$OPENSEARCH_KIBANA_PASSWORD" && -n "$existing" ]]; then + # Append a character so command substitution preserves trailing newlines. + stored_password=$(jq -j '(.data.password // "" | @base64d) + "."' <<< "$existing") + OPENSEARCH_KIBANA_PASSWORD=${stored_password%.} +fi +require_password OPENSEARCH_KIBANA_PASSWORD + +if [[ "$service" == opensearch ]]; then + export OPENSEARCH_NIFI_PASSWORD OPENSEARCH_PIPELINE_PASSWORD OPENSEARCH_ANALYST_PASSWORD \ + OS_NIFI_PASSWORD OS_PIPELINE_PASSWORD OS_ANALYST_PASSWORD + exec bash "$script_dir/../../../apps/opensearch/security/bootstrap.sh" kubectl -n "$namespace" exec -i "$pod" -- +fi + +DASHBOARDS_COOKIE_DATA=$(jq -r '.data.cookie // ""' <<< "$existing") +if [[ -z "$DASHBOARDS_COOKIE_DATA" ]]; then + cookie=$(openssl rand -hex 16) + DASHBOARDS_COOKIE_DATA=$(printf '%s' "$cookie" | openssl base64 -A) +fi +export DASHBOARDS_COOKIE_DATA + +manifest=$(jq -s '.[0] | { + apiVersion: "v1", kind: "Secret", type: "Opaque", + metadata: {name: "dashboards-auth", resourceVersion: .metadata.resourceVersion}, + data: { + username: ("kibanaserver" | @base64), + password: (env.OPENSEARCH_KIBANA_PASSWORD | @base64), + cookie: env.DASHBOARDS_COOKIE_DATA + } +}' <<< "$existing") +if [[ -z "$existing" ]]; then + kubectl -n "$namespace" create -f - <<< "$manifest" +else + kubectl -n "$namespace" patch secret dashboards-auth --type=merge --patch-file=/dev/stdin <<< "$manifest" +fi diff --git a/deployment/scripts/security/password_prompt.sh b/deployment/scripts/security/password_prompt.sh new file mode 100644 index 00000000..5fe70e22 --- /dev/null +++ b/deployment/scripts/security/password_prompt.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +require_password() { + local name=$1 password + + if [[ -n ${!name:-} ]]; then + export "${name?}" + return + fi + + if [[ ! -t 0 ]]; then + printf 'Set %s in the environment or run this command in a terminal.\n' "$name" >&2 + return 1 + fi + + if ! IFS= read -r -s -p "Enter $name: " password || [[ -z "$password" ]]; then + printf '\nSet %s to a nonempty password.\n' "$name" >&2 + return 1 + fi + + printf '\n' >&2 + export "$name=$password" +} diff --git a/deployment/security/templates/ssl-extensions-x509.cnf b/deployment/security/templates/ssl-extensions-x509.cnf index a58badde..1b626038 100755 --- a/deployment/security/templates/ssl-extensions-x509.cnf +++ b/deployment/security/templates/ssl-extensions-x509.cnf @@ -23,7 +23,7 @@ authorityKeyIdentifier = keyid,issuer DNS.1 = nifi DNS.2 = localhost DNS.3 = cogstack-nifi -DNS.4 = cogstack-nifi-web +DNS.4 = cogstack-nifi-headless IP.1 = 127.0.0.1 [req] diff --git a/release-please-config.json b/release-please-config.json index 886b0fb5..3055bc61 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -114,57 +114,6 @@ { "type": "revert", "section": "Reverts" } ] }, - "deployment/charts/ocr-service": { - "release-type": "helm", - "component": "helm-charts/ocr-service-helm", - "initial-version": "0.1.0", - "changelog-path": "CHANGELOG.md", - "bump-minor-pre-major": false, - "bump-patch-for-minor-pre-major": false, - "draft": false, - "prerelease": false, - "changelog-sections": [ - { "type": "feat", "section": "Features" }, - { "type": "fix", "section": "Bug Fixes" }, - { "type": "build", "section": "Dependencies" }, - { "type": "refactor", "section": "Code Refactoring" }, - { "type": "revert", "section": "Reverts" } - ] - }, - "deployment/charts/nifi": { - "release-type": "helm", - "component": "helm-charts/nifi", - "initial-version": "0.1.0", - "changelog-path": "CHANGELOG.md", - "bump-minor-pre-major": false, - "bump-patch-for-minor-pre-major": false, - "draft": false, - "prerelease": false, - "changelog-sections": [ - { "type": "feat", "section": "Features" }, - { "type": "fix", "section": "Bug Fixes" }, - { "type": "build", "section": "Dependencies" }, - { "type": "refactor", "section": "Code Refactoring" }, - { "type": "revert", "section": "Reverts" } - ] - }, - "deployment/charts/nginx": { - "release-type": "helm", - "component": "helm-charts/nginx", - "initial-version": "0.1.0", - "changelog-path": "CHANGELOG.md", - "bump-minor-pre-major": false, - "bump-patch-for-minor-pre-major": false, - "draft": false, - "prerelease": false, - "changelog-sections": [ - { "type": "feat", "section": "Features" }, - { "type": "fix", "section": "Bug Fixes" }, - { "type": "build", "section": "Dependencies" }, - { "type": "refactor", "section": "Code Refactoring" }, - { "type": "revert", "section": "Reverts" } - ] - }, "deployment/terraform/openstack-kubernetes-k3s": { "release-type": "simple", "component": "terraform-modules/openstack-kubernetes-k3s",