diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 7aab292fc..4731c285f 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -187,3 +187,42 @@ jobs: run: node --test ../scripts/bench/lib.test.mjs - name: Build (含类型检查) run: pnpm build + + # Helm chart 由社区维护:lint 并渲染两种数据库模式、用 kubeconform 校验,并核对 appVersion 与 compose 的镜像默认标签 + chart: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: azure/setup-helm@v4 + - name: appVersion matches docker-compose.yml + run: ./scripts/check_chart_version.sh + - name: Helm lint + run: | + helm lint deploy/chart --set database.url=postgres://utopia@db:5432/utopia + helm lint deploy/chart --set database.mode=cloudnativepg + # helm lint 只把缺失的 required 值当提示,这里确认没配数据库时渲染真的失败 + - name: Render without settings fails + run: | + if out=$(helm template utopia deploy/chart 2>&1); then + echo "::error::helm template succeeded without database settings" + exit 1 + fi + grep -F "database.url or database.existingSecret is required" <<<"$out" + - name: Install kubeconform + run: | + curl -sSfLo kubeconform.tar.gz https://github.com/yannh/kubeconform/releases/download/v0.8.0/kubeconform-linux-amd64.tar.gz + echo "9bc2bffbf71f261128533edaf912153948b7ff238f9a531ae6d34466ec287883 kubeconform.tar.gz" | sha256sum -c + sudo tar -xzf kubeconform.tar.gz -C /usr/local/bin kubeconform + # CloudNativePG 的 Cluster 用 datreeio/CRDs-catalog 固定提交里的 schema 校验 + - name: Render and validate + run: | + set -o pipefail + crds='https://raw.githubusercontent.com/datreeio/CRDs-catalog/a156431e79b70bc42c4a280a90abc1d5f1045e69/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' + for settings in \ + "database.url=postgres://utopia@db:5432/utopia" \ + "database.existingSecret=utopia-db,keys.existingSecret=utopia-keys,ingress.enabled=true,ingress.tlsSecretName=utopia-tls" \ + "database.mode=cloudnativepg" \ + "database.mode=cloudnativepg,database.cloudnativepg.existingSecret=utopia-db-role"; do + helm template utopia deploy/chart --set "$settings" \ + | kubeconform -strict -summary -schema-location default -schema-location "$crds" + done diff --git a/README.md b/README.md index e29fed9d9..107196de1 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,8 @@ Or build from source: docker compose -f docker-compose.yml -f docker-compose.build.yml --profile app up -d --build ``` +For Kubernetes, a community-maintained Helm chart lives in [`deploy/chart`](deploy/chart/README.md). + ### Local development ```bash diff --git a/README.zh-CN.md b/README.zh-CN.md index 827247e72..6cdf0cc17 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -108,6 +108,8 @@ docker compose --profile app up -d docker compose -f docker-compose.yml -f docker-compose.build.yml --profile app up -d --build ``` +Kubernetes 上可用社区维护的 Helm chart,见 [`deploy/chart`](deploy/chart/README.md)。 + ### 本地开发 ```bash diff --git a/deploy/chart/Chart.yaml b/deploy/chart/Chart.yaml new file mode 100644 index 000000000..8319ebc6c --- /dev/null +++ b/deploy/chart/Chart.yaml @@ -0,0 +1,7 @@ +apiVersion: v2 +name: utopia +description: Utopia, the bitemporal knowledge graph, as one replica with its own data volume +type: application +version: 0.1.0 +# Kept equal to the image default in docker-compose.yml; CI checks it. +appVersion: "0.1.0-rc9" diff --git a/deploy/chart/README.md b/deploy/chart/README.md new file mode 100644 index 000000000..35aa5bc48 --- /dev/null +++ b/deploy/chart/README.md @@ -0,0 +1,89 @@ +# Utopia Helm chart + +This chart is community-maintained. The supported way to run Utopia is still +`docker-compose.yml` at the root of the repo, and this chart follows it: the +image tag defaults to the chart's `appVersion`, which CI keeps equal to the +compose default. + +It runs one replica with a `Recreate` rollout on a single `ReadWriteOnce` +volume, because the data directory (original files, full-text index) and the +worker belong to one process. Everything optional is off by default. + +## With your own Postgres + +You need Postgres 16 or newer with pgvector. Before the first start, create +the owner, the database, the extension and the `utopia_app` runtime role as a +superuser. This is what `docker/init-app-role.sh` does for compose: + +```sql +CREATE ROLE utopia LOGIN PASSWORD ''; +CREATE DATABASE utopia OWNER utopia; +\c utopia +CREATE EXTENSION IF NOT EXISTS vector; +CREATE ROLE utopia_app LOGIN PASSWORD ''; +GRANT CONNECT ON DATABASE utopia TO utopia_app; +``` + +The migrations run as the owner and grant `utopia_app` the tables it needs, +so the role must exist before the first start. The app then runs as +`utopia_app`, which can append to the audit log but not change it. + +```bash +kubectl create secret generic utopia-db \ + --from-literal=database-url='postgres://utopia_app:@:5432/utopia' \ + --from-literal=migration-url='postgres://utopia:@:5432/utopia' +helm install utopia deploy/chart --set database.existingSecret=utopia-db +``` + +To skip the runtime role, leave out `migration-url` and point `database-url` +at the owner. `database.url` and `database.migrationUrl` also work instead of +a Secret you create, and the chart then writes the Secret itself. + +## With CloudNativePG + +With the [CloudNativePG](https://cloudnative-pg.io) operator installed, the +chart can create a one-instance cluster with pgvector and `utopia_app`, and +generate its password: + +```bash +helm install utopia deploy/chart --set database.mode=cloudnativepg +``` + +The generated password survives upgrades only through Helm's `lookup`, which +returns nothing under `helm template`, `--dry-run`, Argo CD and Flux. There it +would change on every render, so create the Secret yourself and name it: + +```bash +kubectl create secret generic utopia-db-role --type=kubernetes.io/basic-auth \ + --from-literal=username=utopia_app --from-literal=password="$(openssl rand -hex 24)" +helm install utopia deploy/chart --set database.mode=cloudnativepg \ + --set database.cloudnativepg.existingSecret=utopia-db-role +``` + +The default image is a CloudNativePG `standard` image, which ships pgvector. +If you set `database.cloudnativepg.image`, keep a `-standard-` tag. + +## Keys + +Without other settings the app keeps its credential key in `secret.key` on the +data volume and its JWT secret in the database, so back up the volume together +with the database. To hold them in Kubernetes instead, set `keys.existingSecret` to +a Secret with the keys `secret-key` and `jwt-secret`. + +## Moving from compose + +The pod runs as uid 1000, while compose runs the app as root, so a `data` +directory copied from compose is owned by root and the app cannot write to it. +Run `sudo chown -R 1000:1000 data` before copying it, and copy with a tool that +keeps the owner, such as `tar -p` or `rsync -a`. Copy the database with +`pg_dump` and `pg_restore` as usual. + +## Reaching it + +`kubectl port-forward svc/utopia 1516:80` opens it on http://localhost:1516. +For an Ingress, set `ingress.enabled=true` and `ingress.host`, plus +`ingress.tlsSecretName` for TLS, which also sets `UTOPIA_COOKIE_SECURE=true`. +If TLS ends somewhere else, set `ingress.cookieSecure` to `true` or `false` +yourself. Uploads go up to 100 MB, so the controller +must allow request bodies that large. Other app settings, such as single +sign-on, go in `extraEnv`, with the names from `.env.example`. diff --git a/deploy/chart/templates/_helpers.tpl b/deploy/chart/templates/_helpers.tpl new file mode 100644 index 000000000..635ae9096 --- /dev/null +++ b/deploy/chart/templates/_helpers.tpl @@ -0,0 +1,12 @@ +{{- define "utopia.labels" -}} +app.kubernetes.io/name: utopia +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end -}} + +{{- define "utopia.dbSecret" -}} +{{- .Values.database.existingSecret | default (printf "%s-db" .Release.Name) -}} +{{- end -}} + +{{- define "utopia.appRoleSecret" -}} +{{- .Values.database.cloudnativepg.existingSecret | default (printf "%s-db-app-role" .Release.Name) -}} +{{- end -}} diff --git a/deploy/chart/templates/data-pvc.yaml b/deploy/chart/templates/data-pvc.yaml new file mode 100644 index 000000000..2f71e5e58 --- /dev/null +++ b/deploy/chart/templates/data-pvc.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ .Release.Name }}-data + labels: + {{- include "utopia.labels" . | nindent 4 }} +spec: + accessModes: [ReadWriteOnce] + {{- with .Values.data.storageClass }} + storageClassName: {{ . }} + {{- end }} + resources: + requests: + storage: {{ .Values.data.size }} diff --git a/deploy/chart/templates/database.yaml b/deploy/chart/templates/database.yaml new file mode 100644 index 000000000..ce6619dcc --- /dev/null +++ b/deploy/chart/templates/database.yaml @@ -0,0 +1,65 @@ +{{- $mode := .Values.database.mode }} +{{- if not (has $mode (list "external" "cloudnativepg")) }} +{{- fail "database.mode must be external or cloudnativepg" }} +{{- end }} +{{- if and (eq $mode "external") (not .Values.database.existingSecret) }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "utopia.dbSecret" . }} + labels: + {{- include "utopia.labels" . | nindent 4 }} +stringData: + database-url: {{ required "database.url or database.existingSecret is required" .Values.database.url | quote }} + {{- with .Values.database.migrationUrl }} + migration-url: {{ . | quote }} + {{- end }} +{{- end }} +{{- if eq $mode "cloudnativepg" }} +{{- $roleSecret := include "utopia.appRoleSecret" . }} +{{- if not .Values.database.cloudnativepg.existingSecret }} +{{- $existing := lookup "v1" "Secret" .Release.Namespace $roleSecret }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ $roleSecret }} + labels: + {{- include "utopia.labels" . | nindent 4 }} +type: kubernetes.io/basic-auth +data: + username: {{ "utopia_app" | b64enc }} + password: {{ dig "data" "password" (randAlphaNum 32 | b64enc) $existing }} +--- +{{- end }} +# The owner utopia runs the migrations. utopia_app must exist before the +# first one, which grants it the tables only when the role is already there. +apiVersion: postgresql.cnpg.io/v1 +kind: Cluster +metadata: + name: {{ .Release.Name }}-db + labels: + {{- include "utopia.labels" . | nindent 4 }} +spec: + instances: 1 + imageName: {{ .Values.database.cloudnativepg.image }} + bootstrap: + initdb: + database: utopia + owner: utopia + postInitApplicationSQL: + - CREATE EXTENSION IF NOT EXISTS vector + - CREATE ROLE utopia_app LOGIN + - GRANT CONNECT ON DATABASE utopia TO utopia_app + managed: + roles: + - name: utopia_app + ensure: present + login: true + passwordSecret: + name: {{ $roleSecret }} + storage: + size: {{ .Values.database.cloudnativepg.size }} + {{- with .Values.database.cloudnativepg.storageClass }} + storageClass: {{ . }} + {{- end }} +{{- end }} diff --git a/deploy/chart/templates/deployment.yaml b/deploy/chart/templates/deployment.yaml new file mode 100644 index 000000000..e7d2b924d --- /dev/null +++ b/deploy/chart/templates/deployment.yaml @@ -0,0 +1,99 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ .Release.Name }} + labels: + {{- include "utopia.labels" . | nindent 4 }} +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + {{- include "utopia.labels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "utopia.labels" . | nindent 8 }} + spec: + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + containers: + - name: utopia + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + ports: + - name: http + containerPort: 1516 + env: + {{- if eq .Values.database.mode "cloudnativepg" }} + - name: UTOPIA_APP_DB_PASSWORD + valueFrom: + secretKeyRef: { name: {{ include "utopia.appRoleSecret" . }}, key: password } + - name: UTOPIA_DATABASE_URL + value: postgres://utopia_app:$(UTOPIA_APP_DB_PASSWORD)@{{ .Release.Name }}-db-rw:5432/utopia + - name: UTOPIA_MIGRATION_URL + valueFrom: + secretKeyRef: { name: {{ .Release.Name }}-db-app, key: uri } + {{- else }} + - name: UTOPIA_DATABASE_URL + valueFrom: + secretKeyRef: { name: {{ include "utopia.dbSecret" . }}, key: database-url } + - name: UTOPIA_MIGRATION_URL + valueFrom: + secretKeyRef: { name: {{ include "utopia.dbSecret" . }}, key: migration-url, optional: true } + {{- end }} + {{- with .Values.keys.existingSecret }} + - name: UTOPIA_SECRET_KEY + valueFrom: + secretKeyRef: { name: {{ . }}, key: secret-key, optional: true } + - name: UTOPIA_JWT_SECRET + valueFrom: + secretKeyRef: { name: {{ . }}, key: jwt-secret, optional: true } + {{- end }} + - name: UTOPIA_BIND_ADDR + value: 0.0.0.0:1516 + - name: UTOPIA_WEB_DIST + value: /app/web-dist + - name: UTOPIA_DATA_DIR + value: /app/data + {{- $tls := and .Values.ingress.enabled .Values.ingress.tlsSecretName }} + - name: UTOPIA_COOKIE_SECURE + value: {{ toString .Values.ingress.cookieSecure | default (ternary "true" "false" (not (empty $tls))) | quote }} + {{- with .Values.extraEnv }} + {{- toYaml . | nindent 12 }} + {{- end }} + volumeMounts: + - { name: data, mountPath: /app/data } + - { name: tmp, mountPath: /tmp } + # Migrations run before the port opens and can take long on a large + # base, so liveness waits for the startup probe. + startupProbe: + httpGet: { path: /api/v1/health, port: http } + periodSeconds: 10 + failureThreshold: 360 + readinessProbe: + httpGet: { path: /api/v1/health, port: http } + periodSeconds: 10 + livenessProbe: + httpGet: { path: /api/v1/health, port: http } + periodSeconds: 30 + resources: + {{- toYaml .Values.resources | nindent 12 }} + volumes: + - name: data + persistentVolumeClaim: + claimName: {{ .Release.Name }}-data + - name: tmp + emptyDir: {} diff --git a/deploy/chart/templates/ingress.yaml b/deploy/chart/templates/ingress.yaml new file mode 100644 index 000000000..79ce5a79d --- /dev/null +++ b/deploy/chart/templates/ingress.yaml @@ -0,0 +1,32 @@ +{{- if .Values.ingress.enabled }} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ .Release.Name }} + labels: + {{- include "utopia.labels" . | nindent 4 }} + {{- with .Values.ingress.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- with .Values.ingress.className }} + ingressClassName: {{ . }} + {{- end }} + {{- with .Values.ingress.tlsSecretName }} + tls: + - hosts: [{{ $.Values.ingress.host | quote }}] + secretName: {{ . }} + {{- end }} + rules: + - host: {{ .Values.ingress.host | quote }} + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: {{ .Release.Name }} + port: + name: http +{{- end }} diff --git a/deploy/chart/templates/service.yaml b/deploy/chart/templates/service.yaml new file mode 100644 index 000000000..086beeae1 --- /dev/null +++ b/deploy/chart/templates/service.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ .Release.Name }} + labels: + {{- include "utopia.labels" . | nindent 4 }} +spec: + selector: + {{- include "utopia.labels" . | nindent 4 }} + ports: + - name: http + port: {{ .Values.service.port }} + targetPort: http diff --git a/deploy/chart/values.yaml b/deploy/chart/values.yaml new file mode 100644 index 000000000..32d4ca4c5 --- /dev/null +++ b/deploy/chart/values.yaml @@ -0,0 +1,58 @@ +image: + repository: ghcr.io/deeplethe/utopia + # Empty: the chart's appVersion. + tag: "" + pullPolicy: IfNotPresent + +# Original files and the full-text index. One disk, one writer, so the +# Deployment runs one replica and recreates rather than rolls. +data: + size: 20Gi + storageClass: "" + +database: + # external: your own Postgres 16+ with pgvector. + # cloudnativepg: a CloudNativePG Cluster made by this chart (needs the operator). + mode: external + # external mode. Either name a Secret with the keys database-url and + # migration-url (optional), or give the URLs here and the chart writes one. + existingSecret: "" + url: "" + migrationUrl: "" + # cloudnativepg mode. The standard images ship pgvector. + cloudnativepg: + image: ghcr.io/cloudnative-pg/postgresql:16.16-standard-bookworm + # A kubernetes.io/basic-auth Secret with username utopia_app and the + # password. Empty: the chart generates one, which needs `lookup` to keep + # it across upgrades (not under helm template, Argo CD or Flux). + existingSecret: "" + size: 20Gi + storageClass: "" + +# Optional Secret with the keys secret-key and jwt-secret. Without it the app +# keeps the key in the data volume and the JWT secret in the database. +keys: + existingSecret: "" + +# Extra container environment, as Kubernetes EnvVar entries. +extraEnv: [] +# - name: UTOPIA_DB_MAX_CONNECTIONS +# value: "32" + +resources: + requests: { cpu: 250m, memory: 512Mi } + limits: { memory: 2Gi } + +service: + port: 80 + +# The controller must allow request bodies up to 100 MB (uploads). +ingress: + enabled: false + className: "" + host: utopia.example.com + # Name of the TLS Secret; empty: no tls section. + tlsSecretName: "" + # Sets UTOPIA_COOKIE_SECURE. Empty: true when tlsSecretName is set. + cookieSecure: "" + annotations: {} diff --git a/scripts/check_chart_version.sh b/scripts/check_chart_version.sh new file mode 100755 index 000000000..ff9951506 --- /dev/null +++ b/scripts/check_chart_version.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# deploy/chart 的 appVersion 必须等于 docker-compose.yml 里镜像的默认标签。 +set -euo pipefail +cd "$(dirname "$0")/.." + +compose_tag=$(sed -n 's|.*UTOPIA_IMAGE:-ghcr.io/deeplethe/utopia:\([^}]*\)}.*|\1|p' docker-compose.yml) +chart_version=$(sed -n 's/^appVersion: *"\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' deploy/chart/Chart.yaml) + +if [ -z "$compose_tag" ] || [ "$compose_tag" != "$chart_version" ]; then + echo "::error::deploy/chart appVersion '$chart_version' != docker-compose.yml image tag '$compose_tag'" + exit 1 +fi +echo "appVersion $chart_version matches docker-compose.yml"