World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#11099][#9013] feat(helm): Schema migration via regular Job (#15001)
Danhua Wang8b50e611ae6b
diff --git a/.github/workflows/chart-test.yaml b/.github/workflows/chart-test.yamlindex b3efa34542..ee2006471f 100644--- a/.github/workflows/chart-test.yaml+++ b/.github/workflows/chart-test.yaml@@ -160,6 +160,12 @@ jobs:if: steps.list-changed.outputs.changed == 'true'run: helm unittest --with-subchart=false dev/charts/gravitino-lance-rest-server+ - name: Schema migrate script regression (fresh + 1.2.0 upgrade chain)+ if: steps.list-changed.outputs.changed == 'true'+ run: |+ chmod +x dev/ci/test_schema_migrate.py+ python3 dev/ci/test_schema_migrate.py --engine mysql -v+- name: Set up kind clusterif: steps.list-changed.outputs.changed == 'true'uses: container-tools/kind-action@v2@@ -215,6 +221,81 @@ jobs:- name: Set up kubectluses: azure/setup-kubectl@829323503d1be3d00ca8346e5391ca0b07a9ab0d+ # Schema-migrate scenarios first so chart bugs fail before the slower ct matrix.+ - name: Schema migrate fresh install and same-revision upgrade (mysql)+ if: steps.list-changed.outputs.changed == 'true'+ run: |+ set -euo pipefail+ chmod +x dev/ci/check-schema-migrate.sh+ NS=schema-migrate-mysql+ RELEASE=gravitino-sm-mysql+ helm dependency update dev/charts/gravitino+ kubectl create namespace "$NS"+ dump_schema_migrate() {+ echo "::group::schema-migrate diagnostics (${NS})"+ kubectl get pods,jobs,secrets -n "$NS" -o wide || true+ kubectl describe pods -n "$NS" || true+ kubectl get events -n "$NS" --sort-by=.lastTimestamp || true+ kubectl logs -n "$NS" -l app.kubernetes.io/component=schema-migrate --all-containers --tail=200 || true+ kubectl logs -n "$NS" -l "release=${RELEASE}" --all-containers --tail=200 || true+ echo "::endgroup::"+ }+ trap 'dump_schema_migrate; helm uninstall "$RELEASE" -n "$NS" --wait || true; kubectl delete namespace "$NS" --wait=false || true' EXIT+ helm upgrade --install "$RELEASE" ./dev/charts/gravitino -n "$NS" --wait --timeout 10m \+ --values dev/charts/gravitino/resources/scenarios/schema-migrate-mysql.yaml \+ --set image.registry="" \+ --set image.repository="${KIND_REGISTRY}/gravitino" \+ --set image.tag="${tag}"+ bash dev/ci/check-schema-migrate.sh "$NS" "$RELEASE" mysql+ # Annotations must be strings; bare --set turns epoch into int and SSA fails.+ helm upgrade "$RELEASE" ./dev/charts/gravitino -n "$NS" --wait --timeout 10m \+ --values dev/charts/gravitino/resources/scenarios/schema-migrate-mysql.yaml \+ --set image.registry="" \+ --set image.repository="${KIND_REGISTRY}/gravitino" \+ --set image.tag="${tag}" \+ --set-string "podAnnotations.schema-migrate-upgrade=$(date +%s)"+ bash dev/ci/check-schema-migrate.sh "$NS" "$RELEASE" mysql++ - name: Schema migrate fresh install (postgresql)+ if: steps.list-changed.outputs.changed == 'true'+ run: |+ set -euo pipefail+ chmod +x dev/ci/check-schema-migrate.sh+ NS=schema-migrate-pg+ RELEASE=gravitino-sm-pg+ helm dependency update dev/charts/gravitino+ kubectl create namespace "$NS"+ dump_schema_migrate() {+ echo "::group::schema-migrate diagnostics (${NS})"+ kubectl get pods,jobs,secrets -n "$NS" -o wide || true+ kubectl describe pods -n "$NS" || true+ kubectl get events -n "$NS" --sort-by=.lastTimestamp || true+ kubectl logs -n "$NS" -l app.kubernetes.io/component=schema-migrate --all-containers --tail=200 || true+ kubectl logs -n "$NS" -l "release=${RELEASE}" --all-containers --tail=200 || true+ echo "::endgroup::"+ }+ trap 'dump_schema_migrate; helm uninstall "$RELEASE" -n "$NS" --wait || true; kubectl delete namespace "$NS" --wait=false || true' EXIT+ helm upgrade --install "$RELEASE" ./dev/charts/gravitino -n "$NS" --wait --timeout 10m \+ --values dev/charts/gravitino/resources/scenarios/schema-migrate-postgresql.yaml \+ --set image.registry="" \+ --set image.repository="${KIND_REGISTRY}/gravitino" \+ --set image.tag="${tag}"+ bash dev/ci/check-schema-migrate.sh "$NS" "$RELEASE" postgresql++ - name: Schema migrate cross-version upgrade matrix (mysql/postgresql × 1.2.0/1.3.0)+ if: steps.list-changed.outputs.changed == 'true'+ run: |+ set -euo pipefail+ chmod +x dev/ci/chart-schema-migrate-cross-version.sh+ for ENGINE in mysql postgresql; do+ for FROM_VERSION in 1.2.0 1.3.0; do+ echo "::group::cross-version ${ENGINE} from ${FROM_VERSION}"+ ENGINE="${ENGINE}" FROM_VERSION="${FROM_VERSION}" \+ bash dev/ci/chart-schema-migrate-cross-version.sh+ echo "::endgroup::"+ done+ done+- name: Run chart-testing (install default,gravitino)if: steps.list-changed.outputs.changed == 'true'run: ct install --charts dev/charts/gravitino --target-branch ${{ steps.checkout.outputs.base-ref }} --helm-extra-set-args "--set image.registry="" --set image.repository=${KIND_REGISTRY}/gravitino"diff --git a/dev/charts/gravitino/resources/config/gravitino.conf b/dev/charts/gravitino/resources/config/gravitino.confindex d4c9f16a4c..e1188b5575 100644--- a/dev/charts/gravitino/resources/config/gravitino.conf+++ b/dev/charts/gravitino/resources/config/gravitino.conf@@ -43,7 +43,7 @@ gravitino.entity.store.maxTransactionSkewTimeMs = {{ .Values.entity.maxTransactigravitino.entity.store.deleteAfterTimeMs = {{ (.Values.entity.deleteAfterTimeMs | default 604800000) | int }}gravitino.entity.store.versionRetentionCount = {{ .Values.entity.versionRetentionCount }}gravitino.entity.store.relational = {{ .Values.entity.relationalBackend | default "JDBCBackend" }}-gravitino.entity.store.relational.jdbcUrl = {{ if .Values.mysql.enabled }}jdbc:mysql://{{ .Release.Name }}-mysql:3306/{{ .Values.mysql.auth.database }}{{ else if .Values.postgresql.enabled }}jdbc:postgresql://{{ .Release.Name }}-postgresql:5432/{{ .Values.postgresql.auth.database }}{{ else }}{{ .Values.entity.jdbcUrl }}{{ end }}+gravitino.entity.store.relational.jdbcUrl = {{ if .Values.mysql.enabled }}jdbc:mysql://{{ include "gravitino.mysql.fullname" . }}:3306/{{ .Values.mysql.auth.database }}{{ else if .Values.postgresql.enabled }}jdbc:postgresql://{{ include "gravitino.postgresql.fullname" . }}:5432/{{ .Values.postgresql.auth.database }}{{ else }}{{ .Values.entity.jdbcUrl }}{{ end }}gravitino.entity.store.relational.jdbcDriver = {{ if .Values.mysql.enabled }}com.mysql.cj.jdbc.Driver{{ else if .Values.postgresql.enabled }}org.postgresql.Driver{{ else }}{{ .Values.entity.jdbcDriver }}{{ end }}gravitino.entity.store.relational.jdbcUser = {{ if .Values.mysql.enabled }}{{ .Values.mysql.auth.username }}{{ else if .Values.postgresql.enabled }}{{ .Values.postgresql.auth.username }}{{ else }}{{ .Values.entity.jdbcUser }}{{ end }}gravitino.entity.store.relational.jdbcPassword = {{ if .Values.mysql.enabled }}{{ .Values.mysql.auth.password }}{{ else if .Values.postgresql.enabled }}{{ .Values.postgresql.auth.password }}{{ else }}{{ .Values.entity.jdbcPassword }}{{ end }}diff --git a/dev/charts/gravitino/resources/scenarios/schema-migrate-mysql.yaml b/dev/charts/gravitino/resources/scenarios/schema-migrate-mysql.yamlnew file mode 100644index 0000000000..b44a8ca59d--- /dev/null+++ b/dev/charts/gravitino/resources/scenarios/schema-migrate-mysql.yaml@@ -0,0 +1,42 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++## Fresh-install / upgrade coverage for schema.migrate.enabled with in-chart MySQL.+mysql:+ enabled: true++schema:+ migrate:+ enabled: true++replicas: 1++# Fit the 512Mi limit: chart default GRAVITINO_MEM is -Xms1024m (entrypoint also+# disables UseContainerSupport), which OOMs under this CI resource budget.+env:+ - name: GRAVITINO_MEM+ value: "-Xms256m -Xmx256m -XX:MaxMetaspaceSize=128m"++resources:+ limits:+ cpu: 500m+ memory: 512Mi+ requests:+ cpu: 500m+ memory: 512Midiff --git a/dev/charts/gravitino/resources/scenarios/schema-migrate-postgresql.yaml b/dev/charts/gravitino/resources/scenarios/schema-migrate-postgresql.yamlnew file mode 100644index 0000000000..8aa5aa6f9f--- /dev/null+++ b/dev/charts/gravitino/resources/scenarios/schema-migrate-postgresql.yaml@@ -0,0 +1,47 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++## Fresh-install coverage for schema.migrate.enabled with in-chart PostgreSQL.+postgresql:+ enabled: true++schema:+ migrate:+ enabled: true++replicas: 1++initScript: |+ cp /tmp/conf/* ${GRAVITINO_HOME}/conf+ echo "Start the Gravitino Server"+ /bin/bash ${GRAVITINO_HOME}/docker/docker-entrypoint.sh++# Fit the 512Mi limit: chart default GRAVITINO_MEM is -Xms1024m (entrypoint also+# disables UseContainerSupport), which OOMs under this CI resource budget.+env:+ - name: GRAVITINO_MEM+ value: "-Xms256m -Xmx256m -XX:MaxMetaspaceSize=128m"++resources:+ limits:+ cpu: 500m+ memory: 512Mi+ requests:+ cpu: 500m+ memory: 512Midiff --git a/dev/charts/gravitino/resources/scripts/schema-migrate.sh b/dev/charts/gravitino/resources/scripts/schema-migrate.shnew file mode 100644index 0000000000..70e7c2fc1e--- /dev/null+++ b/dev/charts/gravitino/resources/scripts/schema-migrate.sh@@ -0,0 +1,576 @@+#!/usr/bin/env bash+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++# Entity-store schema init for the chart schema-migrate Job.+# Fail on any unexpected SQL error so a broken migration cannot roll out.+set -euo pipefail++: "${DB_ENGINE:?DB_ENGINE must be mysql or postgresql}"+: "${DB_HOST:?DB_HOST is required}"+: "${GRAVITINO_DB:?GRAVITINO_DB is required}"+: "${SCRIPTS_DIR:=/scripts}"++if [ "$DB_ENGINE" != mysql ] && [ "$DB_ENGINE" != postgresql ]; then+ echo "ERROR: DB_ENGINE must be mysql or postgresql (got ${DB_ENGINE})" >&2+ exit 1+fi++if [ "$DB_ENGINE" = mysql ]; then+ : "${MYSQL_USER:?MYSQL_USER is required}"+ : "${MYSQL_PWD:?MYSQL_PWD is required}"+ export MYSQL_PWD+else+ : "${POSTGRES_USER:?POSTGRES_USER is required}"+ : "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}"+fi++DB_PORT="${DB_PORT:-}"+PG_CURRENT_SCHEMA="${PG_CURRENT_SCHEMA:-}"+BASELINE_VERSION="${BASELINE_VERSION:-}"+VERSION_FILE="${SCRIPTS_DIR}/version.txt"++mysql_client() {+ local extra=()+ if [ -n "$DB_PORT" ]; then+ extra+=(-P "$DB_PORT")+ fi+ mysql -h "$DB_HOST" "${extra[@]}" -u "$MYSQL_USER" "$@"+}++psql_client() {+ local extra=()+ if [ -n "$DB_PORT" ]; then+ extra+=(-p "$DB_PORT")+ fi+ PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$DB_HOST" "${extra[@]}" -U "$POSTGRES_USER" "$@"+}++version_le() {+ [ "$(printf '%s\n%s' "$1" "$2" | sort -V | head -n1)" = "$1" ]+}++version_lt() {+ [ "$1" != "$2" ] && version_le "$1" "$2"+}++require_semver() {+ local name="$1"+ local ver="$2"+ if [[ ! "${ver}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ echo "ERROR: ${name} must be X.Y.Z (got '${ver}')" >&2+ exit 1+ fi+}++wait_for_db() {+ echo "Waiting for ${DB_ENGINE} at ${DB_HOST}..."+ if [ "$DB_ENGINE" = mysql ]; then+ until mysql_client -e "SELECT 1" >/dev/null 2>&1; do+ echo "Waiting for MySQL to be ready..."+ sleep 2+ done+ # Server ready does not mean Bitnami (or the operator) has created GRAVITINO_DB yet.+ until mysql_client -D "$GRAVITINO_DB" -e "SELECT 1" >/dev/null 2>&1; do+ echo "Waiting for MySQL database ${GRAVITINO_DB}..."+ sleep 2+ done+ else+ until psql_client -d "$GRAVITINO_DB" -c "SELECT 1" >/dev/null 2>&1; do+ echo "Waiting for PostgreSQL to be ready..."+ sleep 2+ done+ fi+}++mysql_query() {+ mysql_client -D "$GRAVITINO_DB" -sNe "$1"+}++mysql_exec() {+ mysql_client -D "$GRAVITINO_DB" -e "$1"+}++psql_query() {+ psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 -tAc "$1"+}++db_query() {+ if [ "$DB_ENGINE" = mysql ]; then+ mysql_query "$1"+ else+ psql_query "$1"+ fi+}++# Community upgrade-*-mysql.sql uses ADD COLUMN / DROP INDEX without IF NOT EXISTS.+# Ignore "already applied" errors so re-runs and overlapping snapshots stay safe.+mysql_is_already_applied_error() {+ case "$1" in+ 1060 | 1061 | 1068 | 1091 | 1176 | 1280) return 0 ;;+ *) return 1 ;;+ esac+}++mysql_apply_sql_file() {+ local file="$1"+ local out unexpected code line rc+ set +e+ out="$(mysql_client -D "$GRAVITINO_DB" --force <"$file" 2>&1)"+ rc=$?+ set -e+ if [ -n "${out}" ]; then+ printf '%s\n' "${out}"+ fi+ unexpected=""+ while IFS= read -r line; do+ [ -z "${line}" ] && continue+ code="$(printf '%s' "${line}" | sed -n 's/.*ERROR \([0-9][0-9]*\).*/\1/p')"+ [ -n "${code}" ] || continue+ if mysql_is_already_applied_error "${code}"; then+ echo "INFO: ignoring already-applied MySQL error ${code}"+ continue+ fi+ unexpected="${unexpected}${line}"$'\n'+ done < <(printf '%s\n' "${out}" | grep -E 'ERROR [0-9]+' || true)+ if [ -n "${unexpected}" ]; then+ echo "ERROR: SQL script failed: $file" >&2+ printf '%s' "${unexpected}" >&2+ exit 1+ fi+ if [ "${rc}" != 0 ] && ! printf '%s\n' "${out}" | grep -qE 'ERROR [0-9]+'; then+ echo "ERROR: mysql client failed: $file" >&2+ printf '%s\n' "${out}" >&2+ exit 1+ fi+}++apply_sql_file() {+ local file="$1"+ echo "Applying $file"+ if [ "$DB_ENGINE" = mysql ]; then+ mysql_apply_sql_file "$file"+ else+ if ! psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 -f "$file"; then+ echo "ERROR: SQL script failed: $file" >&2+ exit 1+ fi+ fi+}++# 1.3.2 widened table_column_version_info.column_name. Existing 1.3.x DBs may+# already record a later version without that ALTER; repair before ready.+ensure_column_name_capacity() {+ version_le 1.3.2 "$VERSION" || return 0++ local scope capacity+ if [ "$DB_ENGINE" = mysql ]; then+ scope='DATABASE()'+ else+ scope='current_schema()'+ fi+ capacity=$(db_query "SELECT character_maximum_length FROM information_schema.columns+ WHERE table_schema = ${scope} AND table_name = 'table_column_version_info'+ AND column_name = 'column_name';" | tr -d '[:space:]')+ case "$capacity" in+ '' | *[!0-9]*)+ echo "ERROR: Cannot determine table_column_version_info.column_name capacity" >&2+ exit 1+ ;;+ esac+ [ "$capacity" -lt 300 ] || return 0++ echo "Expanding table_column_version_info.column_name from ${capacity} to 300 characters"+ if [ "$DB_ENGINE" = mysql ]; then+ mysql_exec "ALTER TABLE table_column_version_info+ MODIFY COLUMN column_name VARCHAR(300) NOT NULL COMMENT 'column name';"+ else+ psql_query "ALTER TABLE table_column_version_info+ ALTER COLUMN column_name TYPE VARCHAR(300);" >/dev/null+ fi+}++ensure_migration_table() {+ if [ "$DB_ENGINE" = mysql ]; then+ mysql_exec "CREATE TABLE IF NOT EXISTS gravitino_schema_migration (+ id TINYINT UNSIGNED NOT NULL PRIMARY KEY,+ schema_version VARCHAR(64) NOT NULL,+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;"+ else+ psql_query "CREATE TABLE IF NOT EXISTS gravitino_schema_migration (+ id SMALLINT NOT NULL PRIMARY KEY,+ schema_version VARCHAR(64) NOT NULL,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ );" >/dev/null+ fi+}++read_recorded_version() {+ db_query "SELECT schema_version FROM gravitino_schema_migration WHERE id = 1;" 2>/dev/null | tr -d '[:space:]' || true+}++write_recorded_version() {+ local ver="$1"+ if [ "$DB_ENGINE" = mysql ]; then+ mysql_exec "INSERT INTO gravitino_schema_migration (id, schema_version) VALUES (1, '${ver}')+ ON DUPLICATE KEY UPDATE schema_version = '${ver}';"+ else+ psql_query "INSERT INTO gravitino_schema_migration (id, schema_version, updated_at)+ VALUES (1, '${ver}', NOW())+ ON CONFLICT (id) DO UPDATE SET schema_version = EXCLUDED.schema_version, updated_at = NOW();" >/dev/null+ fi+ echo "Recorded schema version ${ver}"+}++metalake_exists() {+ if [ "$DB_ENGINE" = mysql ]; then+ local count+ count=$(mysql_query "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='${GRAVITINO_DB}' AND table_name='metalake_meta';" 2>/dev/null || echo 0)+ [ "$count" = "1" ]+ else+ local exists+ # Limit to current_schema() so a populated public catalog cannot skip+ # initialization of an empty operator-selected schema (PGOPTIONS search_path).+ exists=$(psql_query \+ "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = 'metalake_meta');" 2>/dev/null || echo f)+ [ "$exists" = "t" ]+ fi+}++extract_table_names() {+ # The backticks are literal MySQL identifier quotes, not command substitution.+ # shellcheck disable=SC2016+ grep -io 'create table if not exists [`"]*[a-z0-9_]*[`"]*\|create table [`"]*[a-z0-9_]*[`"]*' "$1" |+ sed 's/.*[Tt][Aa][Bb][Ll][Ee] //; s/[Ii][Ff] [Nn][Oo][Tt] [Ee][Xx][Ii][Ss][Tt][Ss] //; s/[`"]//g'+}++schema_tables_exist() {+ local schema_sql="$1"+ local tbl exists+ local found=0+ while IFS= read -r tbl; do+ [ -z "$tbl" ] && continue+ found=1+ if [ "$DB_ENGINE" = mysql ]; then+ exists=$(mysql_query "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='${GRAVITINO_DB}' AND table_name='${tbl}';")+ [ "$exists" = "1" ] || return 1+ else+ exists=$(psql_query "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = '${tbl}');")+ [ "$exists" = "t" ] || return 1+ fi+ done < <(extract_table_names "$schema_sql")+ [ "$found" = "1" ]+}++column_exists() {+ local table="$1"+ local column="$2"+ local count+ if [ "$DB_ENGINE" = mysql ]; then+ count=$(mysql_query "SELECT COUNT(*) FROM information_schema.columns+ WHERE table_schema='${GRAVITINO_DB}' AND table_name='${table}' AND column_name='${column}'")+ [ "$count" = "1" ]+ else+ count=$(psql_query "SELECT COUNT(*) FROM information_schema.columns+ WHERE table_schema=current_schema() AND table_name='${table}' AND column_name='${column}'" | tr -d '[:space:]')+ [ "$count" = "1" ]+ fi+}++# Emit table<TAB>column for each ADD COLUMN in an upgrade script.+# Tracks the latest ALTER TABLE target so multi-line MySQL upgrades work.+extract_upgrade_add_columns() {+ local file="$1"+ local table="" line col+ while IFS= read -r line || [ -n "$line" ]; do+ if printf '%s\n' "$line" | grep -qiE 'alter[[:space:]]+table'; then+ table=$(printf '%s\n' "$line" | sed -E \+ 's/.*[Aa][Ll][Tt][Ee][Rr][[:space:]]+[Tt][Aa][Bb][Ll][Ee][[:space:]]+([Ii][Ff][[:space:]]+[Ee][Xx][Ii][Ss][Tt][Ss][[:space:]]+)?[`"]?([A-Za-z0-9_]+).*/\2/')+ if [ "$table" = "$line" ]; then+ table=""+ fi+ fi+ if [ -n "$table" ] && printf '%s\n' "$line" | grep -qiE 'add[[:space:]]+column'; then+ col=$(printf '%s\n' "$line" | sed -E \+ 's/.*[Aa][Dd][Dd][[:space:]]+[Cc][Oo][Ll][Uu][Mm][Nn][[:space:]]+([Ii][Ff][[:space:]]+[Nn][Oo][Tt][[:space:]]+[Ee][Xx][Ii][Ss][Tt][Ss][[:space:]]+)?[`"]?([A-Za-z0-9_]+).*/\2/')+ if [ -n "$col" ] && [ "$col" != "$line" ]; then+ printf '%s\t%s\n' "$table" "$col"+ fi+ fi+ done <"$file"+}++# Snapshots such as 1.3.0 and 2.0.0 share the same CREATE TABLE set; require+# columns introduced by upgrade-*-to-<ver> before claiming that version.+schema_version_markers_present() {+ local ver="$1"+ local f table column+ local found_marker=0+ shopt -s nullglob+ local files=("${SCRIPT_DB_DIR}"/upgrade-*-to-"${ver}"-"${DB_ENGINE}".sql)+ shopt -u nullglob+ if [ ${#files[@]} -eq 0 ]; then+ return 0+ fi+ for f in "${files[@]}"; do+ while IFS=$'\t' read -r table column; do+ if [ -z "$table" ] || [ -z "$column" ]; then+ continue+ fi+ found_marker=1+ column_exists "$table" "$column" || return 1+ done < <(extract_upgrade_add_columns "$f")+ done+ # Upgrade scripts exist but none ADD COLUMN (index-only / constraint-only).+ # Vacuous success would claim this snapshot for an older DB that shares the+ # same CREATE TABLE set and skip those upgrades. Treat markers as absent so+ # inference keeps the prior version (or requires schema.baselineVersion).+ [ "$found_marker" = "1" ]+}++infer_schema_version() {+ local best="" f ver+ local matched_without_markers=""+ shopt -s nullglob+ local files=("${SCRIPT_DB_DIR}"/schema-*-"${DB_ENGINE}".sql)+ shopt -u nullglob+ if [ ${#files[@]} -eq 0 ]; then+ return 0+ fi+ while IFS= read -r f; do+ ver=$(basename "$f" | sed "s/schema-\\(.*\\)-${DB_ENGINE}\\.sql/\\1/")+ if version_le "$ver" "$VERSION" && schema_tables_exist "$f"; then+ if schema_version_markers_present "$ver"; then+ best="$ver"+ matched_without_markers=""+ else+ # Tables match a newer snapshot whose upgrade columns are missing+ # (e.g. 1.3.0 DB vs schema-2.0.0.sql). Keep the prior best.+ matched_without_markers="$ver"+ fi+ fi+ done < <(printf '%s\n' "${files[@]}" | sort -V)+ if [ -n "$matched_without_markers" ] && [ -z "$best" ]; then+ echo "ERROR: Existing tables match schema-${matched_without_markers} but distinguishable upgrade markers (ADD COLUMN) for that version are missing." >&2+ echo "Cannot safely infer the starting schema version." >&2+ echo "Set schema.baselineVersion to the Gravitino version that created this database." >&2+ exit 1+ fi+ if [ -n "$matched_without_markers" ] && [ -n "$best" ] && version_lt "$best" "$matched_without_markers"; then+ # Keep diagnostics on stderr: callers capture stdout as the version only+ # (gravitino_schema_migration.schema_version is VARCHAR(64)).+ echo "INFO: Tables also match schema-${matched_without_markers}, but upgrade ADD COLUMN markers are absent; inferring ${best}." >&2+ fi+ printf '%s' "$best"+}++select_schema_file() {+ local best="" f ver+ shopt -s nullglob+ local files=("${SCRIPT_DB_DIR}"/schema-*-"${DB_ENGINE}".sql)+ shopt -u nullglob+ while IFS= read -r f; do+ [ -z "$f" ] && continue+ ver=$(basename "$f" | sed "s/schema-\\(.*\\)-${DB_ENGINE}\\.sql/\\1/")+ if version_le "$ver" "$VERSION"; then+ best="$f"+ fi+ done < <(printf '%s\n' "${files[@]}" | sort -V)+ printf '%s' "$best"+}++# Patch releases (e.g. 1.3.1) ship no upgrade-* SQL; chain from the schema+# baseline X.Y.0 so upgrade-1.3.0-to-2.0.0 still runs when the DB records 1.3.1.+schema_upgrade_script_from() {+ local recorded="$1"+ if [[ "${recorded}" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] &&+ [ "${BASH_REMATCH[3]}" != "0" ]; then+ printf '%s.%s.0' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"+ return 0+ fi+ printf '%s' "${recorded}"+}++upgrade_script_applies() {+ local current="$1"+ local from="$2"+ local baseline+ if [ "$from" = "$current" ]; then+ return 0+ fi+ baseline="$(schema_upgrade_script_from "$current")"+ [ "$from" = "$baseline" ] && [ "$from" != "$current" ]+}++find_next_upgrade() {+ local current="$1"+ local next_file="" next_to="" f base from to+ shopt -s nullglob+ local files=("${SCRIPT_DB_DIR}"/upgrade-*-to-*-"${DB_ENGINE}".sql)+ shopt -u nullglob+ [ ${#files[@]} -eq 0 ] && return 0+ while IFS= read -r f; do+ [ -z "$f" ] && continue+ base=$(basename "$f")+ # upgrade-<from>-to-<to>-<engine>.sql, split on the last "-to-".+ base="${base#upgrade-}"+ base="${base%-"${DB_ENGINE}".sql}"+ from="${base%-to-*}"+ to="${base##*-to-}"+ if upgrade_script_applies "$current" "$from" && version_le "$to" "$VERSION"; then+ if [ -z "$next_to" ] || version_lt "$to" "$next_to"; then+ next_file="$f"+ next_to="$to"+ fi+ fi+ done < <(printf '%s\n' "${files[@]}" | sort -V)+ if [ -n "$next_file" ]; then+ printf '%s %s' "$next_file" "$next_to"+ fi+}++has_unreachable_later_script() {+ local current="$1"+ local f base from to+ shopt -s nullglob+ local files=("${SCRIPT_DB_DIR}"/upgrade-*-to-*-"${DB_ENGINE}".sql)+ shopt -u nullglob+ [ ${#files[@]} -eq 0 ] && return 1+ while IFS= read -r f; do+ [ -z "$f" ] && continue+ base=$(basename "$f")+ base="${base#upgrade-}"+ base="${base%-"${DB_ENGINE}".sql}"+ from="${base%-to-*}"+ to="${base##*-to-}"+ if version_lt "$current" "$from" && version_le "$to" "$VERSION"; then+ return 0+ fi+ done < <(printf '%s\n' "${files[@]}" | sort -V)+ return 1+}++apply_upgrade_chain() {+ local current="$1"+ echo "Existing database detected. Recorded schema version: ${current}; target: ${VERSION}"+ if version_lt "$VERSION" "$current"; then+ echo "ERROR: Recorded schema version ${current} is newer than image version ${VERSION}" >&2+ exit 1+ fi+ if [ "$current" = "$VERSION" ]; then+ echo "Schema already at ${current}, skipping upgrade scripts."+ return 0+ fi+ while version_lt "$current" "$VERSION"; do+ local found next_file next_to+ found=$(find_next_upgrade "$current")+ if [ -z "$found" ]; then+ if has_unreachable_later_script "$current"; then+ echo "ERROR: No upgrade script from ${current} toward ${VERSION}, but later scripts exist." >&2+ echo "Refusing to skip intermediate migrations." >&2+ exit 1+ fi+ echo "INFO: No upgrade scripts between ${current} and ${VERSION}; checking column capacity before recording the patch version."+ return 0+ fi+ next_file=${found% *}+ next_to=${found##* }+ echo "Upgrade file: $next_file"+ apply_sql_file "$next_file"+ current="$next_to"+ write_recorded_version "$current"+ done+}++ensure_pg_schema() {+ [ "$DB_ENGINE" = postgresql ] || return 0+ [ -n "$PG_CURRENT_SCHEMA" ] || return 0+ local schema_exists+ schema_exists=$(psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 -tAc \+ "SELECT 1 FROM pg_namespace WHERE nspname = '${PG_CURRENT_SCHEMA}'")+ if [ "$schema_exists" != "1" ]; then+ psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 \+ -c "CREATE SCHEMA \"${PG_CURRENT_SCHEMA}\""+ fi+}++wait_for_db+ensure_pg_schema++VERSION=$(cat "$VERSION_FILE")+if [ -z "$VERSION" ]; then+ echo "ERROR: Please set VERSION (missing ${VERSION_FILE})" >&2+ exit 1+fi+require_semver "VERSION" "$VERSION"++SCRIPT_DB_DIR="${SCRIPTS_DIR}/${DB_ENGINE}"+schema_file=$(select_schema_file)+if [ ! -f "$schema_file" ]; then+ echo "ERROR: Failed to find schema file for ${VERSION} under ${SCRIPT_DB_DIR}" >&2+ exit 1+fi+echo "Schema file: $schema_file"++ensure_migration_table++if ! metalake_exists; then+ echo "Fresh install detected, skipping upgrade script."+ apply_sql_file "$schema_file"+ write_recorded_version "$VERSION"+ echo "Schema migration completed successfully"+ exit 0+fi++current=$(read_recorded_version)+if [ -z "$current" ] && [ -n "$BASELINE_VERSION" ]; then+ # Validate only when baseline is actually consumed (ignored if a row already exists+ # or on fresh install).+ require_semver "schema.baselineVersion / BASELINE_VERSION" "$BASELINE_VERSION"+ echo "No recorded schema version; using schema.baselineVersion=${BASELINE_VERSION}"+ current="$BASELINE_VERSION"+ write_recorded_version "$current"+fi+if [ -z "$current" ]; then+ inferred=$(infer_schema_version)+ if [ -n "$inferred" ]; then+ echo "No recorded schema version; inferred ${inferred} from existing tables."+ current="$inferred"+ write_recorded_version "$current"+ fi+fi+if [ -z "$current" ]; then+ echo "ERROR: Existing database has no recorded schema version in gravitino_schema_migration." >&2+ echo "Refusing to guess which upgrade scripts to apply." >&2+ echo "Set schema.baselineVersion to the Gravitino version that created this database," >&2+ echo "or INSERT a row: gravitino_schema_migration id=1 schema_version='x.y.z'." >&2+ echo "If the database is already at ${VERSION}, set schema.baselineVersion=${VERSION}." >&2+ exit 1+fi++apply_upgrade_chain "$current"+ensure_column_name_capacity++# Snapshot schema-*.sql is for empty databases. Re-applying it on an existing+# catalog fails on PostgreSQL CREATE INDEX (no IF NOT EXISTS) even when+# CREATE TABLE IF NOT EXISTS is a no-op.+echo "Existing database: skipping schema snapshot after upgrades."+write_recorded_version "$VERSION"+echo "Schema migration completed successfully"diff --git a/dev/charts/gravitino/templates/NOTES.txt b/dev/charts/gravitino/templates/NOTES.txtindex cc495554a4..45f3305175 100644--- a/dev/charts/gravitino/templates/NOTES.txt+++ b/dev/charts/gravitino/templates/NOTES.txt@@ -69,6 +69,19 @@ Override postgresql.auth.password (or set postgresql.auth.existingSecret)before any non-trial deployment.{{- end }}+{{- if eq (include "gravitino.schemaMigrateEnabled" . | trim) "true" }}++NOTE: Entity schema migration runs in a regular schema-migrate Job+(schema.migrate.enabled). Application Pods wait for gravitino_schema_migration+before starting. Per-pod init-mysql/init-postgresql schema apply is replaced by+wait-only inits while migrate is enabled. The Job inherits Deployment+nodeSelector/affinity/tolerations. For an existing database without a recorded+version, set schema.baselineVersion (X.Y.Z) to the version that created it.+{{- if and (not .Values.mysql.enabled) (not .Values.postgresql.enabled) }}+Set schema.migrate.existingSecret for external database credentials.+{{- end }}+{{- end }}+{{- if and (eq (include "gravitino.entityUsesExternalPostgresql" . | trim) "true") .Values.postgresql.init.enabled }}NOTE: External PostgreSQL schema init is enabled (postgresql.init.enabled).diff --git a/dev/charts/gravitino/templates/_helpers.tpl b/dev/charts/gravitino/templates/_helpers.tplindex e11c23de5a..755357cd69 100644--- a/dev/charts/gravitino/templates/_helpers.tpl+++ b/dev/charts/gravitino/templates/_helpers.tpl@@ -99,9 +99,7 @@ Return the proper Gravitino image nameReturn the proper MySQL image name for the init-mysql initContainer*/}}{{- define "init-mysql.image" -}}-{{- if .Values.mysql.enabled -}}- {{- include "gravitino.imageReference" (dict "imageRoot" .Values.mysql.image "global" .Values.global) -}}-{{- end -}}+{{- include "gravitino.imageReference" (dict "imageRoot" .Values.mysql.image "global" .Values.global) -}}{{- end -}}{{/*@@ -112,28 +110,151 @@ Return the proper Postgresql image name for the init-postgresql initContainer{{- end -}}{{/*-True when the entity store uses an external PostgreSQL JDBC URL (not in-chart Bitnami).+Bitnami MySQL subchart resource name (Service / StatefulSet / default Secret).+Matches common.names.fullname: when the release name already contains the chart+name ("mysql"), Bitnami uses the release name alone — not Release.Name-mysql.*/}}-{{- define "gravitino.entityUsesExternalPostgresql" -}}-{{- $url := .Values.entity.jdbcUrl | default "" -}}-{{- if and (not .Values.mysql.enabled) (not .Values.postgresql.enabled) (hasPrefix "jdbc:postgresql:" $url) -}}+{{- define "gravitino.mysql.fullname" -}}+{{- $mysql := .Values.mysql | default dict -}}+{{- if $mysql.fullnameOverride -}}+{{- $mysql.fullnameOverride | trunc 63 | trimSuffix "-" -}}+{{- else -}}+{{- $name := default "mysql" $mysql.nameOverride -}}+{{- if contains $name .Release.Name -}}+{{- .Release.Name | trunc 63 | trimSuffix "-" -}}+{{- else -}}+{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}+{{- end -}}+{{- end -}}+{{- end -}}++{{/*+Bitnami MySQL auth Secret name (existingSecret or chart-managed fullname).+*/}}+{{- define "gravitino.mysql.secretName" -}}+{{- $mysql := .Values.mysql | default dict -}}+{{- $auth := $mysql.auth | default dict -}}+{{- if $auth.existingSecret -}}+{{- tpl ($auth.existingSecret | toString) . -}}+{{- else -}}+{{- include "gravitino.mysql.fullname" . -}}+{{- end -}}+{{- end -}}++{{/*+Bitnami PostgreSQL subchart resource name (Service / StatefulSet / default Secret).+Matches common.names.fullname collapse when the release name contains "postgresql".+*/}}+{{- define "gravitino.postgresql.fullname" -}}+{{- $postgresql := .Values.postgresql | default dict -}}+{{- if $postgresql.fullnameOverride -}}+{{- $postgresql.fullnameOverride | trunc 63 | trimSuffix "-" -}}+{{- else -}}+{{- $name := default "postgresql" $postgresql.nameOverride -}}+{{- if contains $name .Release.Name -}}+{{- .Release.Name | trunc 63 | trimSuffix "-" -}}+{{- else -}}+{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}+{{- end -}}+{{- end -}}+{{- end -}}++{{/*+Bitnami PostgreSQL auth Secret name (existingSecret or chart-managed fullname).+*/}}+{{- define "gravitino.postgresql.secretName" -}}+{{- $postgresql := .Values.postgresql | default dict -}}+{{- $auth := $postgresql.auth | default dict -}}+{{- if $auth.existingSecret -}}+{{- tpl ($auth.existingSecret | toString) . -}}+{{- else -}}+{{- include "gravitino.postgresql.fullname" . -}}+{{- end -}}+{{- end -}}++{{/*+True when per-pod init-mysql should apply schema SQL (in-chart Bitnami only).+Skipped when schema.migrate.enabled runs the shared Job instead.+*/}}+{{- define "gravitino.mysqlSchemaInitEnabled" -}}+{{- if and .Values.mysql.enabled (ne (include "gravitino.schemaMigrateEnabled" . | trim) "true") -}}true{{- end -}}{{- end -}}{{/*-True when the init-postgresql schema init container should be rendered.-In-chart Bitnami PostgreSQL always runs schema init. External PostgreSQL runs-only when postgresql.init.enabled is true (opt-in; see issue #9013 for hook Job).+True when the init-postgresql schema init container should apply schema SQL.+In-chart Bitnami PostgreSQL always runs schema init unless schema.migrate.enabled+runs the shared Job instead. External PostgreSQL runs only when+postgresql.init.enabled is true (opt-in).*/}}{{- define "gravitino.postgresqlSchemaInitEnabled" -}}-{{- if .Values.postgresql.enabled -}}+{{- if eq (include "gravitino.schemaMigrateEnabled" . | trim) "true" -}}+{{- else if .Values.postgresql.enabled -}}true{{- else if and (eq (include "gravitino.entityUsesExternalPostgresql" . | trim) "true") .Values.postgresql.init.enabled -}}true{{- end -}}{{- end -}}+{{/*+True when Deployment should wait for gravitino_schema_migration (schema-migrate Job).+*/}}+{{- define "gravitino.schemaWaitEnabled" -}}+{{- if eq (include "gravitino.schemaMigrateEnabled" . | trim) "true" -}}+true+{{- end -}}+{{- end -}}++{{/*+How long wait-for-schema init containers poll before failing.+*/}}+{{- define "gravitino.schemaWaitTimeoutSeconds" -}}+{{- $schema := .Values.schema | default dict -}}+{{- $wait := $schema.wait | default dict -}}+{{- $n := int ($wait.timeoutSeconds | default 600) -}}+{{- if lt $n 1 -}}+{{- fail "schema.wait.timeoutSeconds must be a positive integer" -}}+{{- end -}}+{{- $n -}}+{{- end -}}++{{/*+Shared prefix for wait-for-schema init containers.+*/}}+{{- define "gravitino.schemaWaitPreamble" -}}+timeout="${SCHEMA_WAIT_TIMEOUT:-600}"+case "$timeout" in+ ''|*[!0-9]*) echo "ERROR: SCHEMA_WAIT_TIMEOUT must be a positive integer" >&2; exit 1 ;;+esac+if [ "$timeout" -lt 1 ]; then+ echo "ERROR: SCHEMA_WAIT_TIMEOUT must be a positive integer" >&2+ exit 1+fi+deadline=$((SECONDS + timeout))+required_column_name_capacity=128+if [ "$(printf '%s\n%s' 1.3.2 "$VERSION" | sort -V | head -n1)" = 1.3.2 ]; then+ required_column_name_capacity=300+fi+{{- end -}}++{{/*+Schema readiness includes the 1.3.2+ column expansion.+*/}}+{{- define "gravitino.schemaReadyQuery" -}}+SELECT schema_version FROM gravitino_schema_migration WHERE id = 1 AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = {{ if eq . "mysql" }}DATABASE(){{ else }}current_schema(){{ end }} AND table_name = 'table_column_version_info' AND column_name = 'column_name' AND character_maximum_length >= ${required_column_name_capacity});+{{- end -}}++{{/*+True when the entity store uses an external PostgreSQL JDBC URL (not in-chart Bitnami).+*/}}+{{- define "gravitino.entityUsesExternalPostgresql" -}}+{{- $url := .Values.entity.jdbcUrl | default "" -}}+{{- if and (not .Values.mysql.enabled) (not .Values.postgresql.enabled) (hasPrefix "jdbc:postgresql:" $url) -}}+true+{{- end -}}+{{- end -}}+{{/*Authority segment (host[:port]) from entity.jdbcUrl for PostgreSQL.@@ -141,7 +262,7 @@ Only a single host:port is supported. The helpers split authority on the firstcolon and do not parse IPv6 bracket literals (e.g. [::1]:5432) or multi-hostJDBC authorities (host1:5432,host2:5432). When the authority contains "[" or"," and host/port would be derived from the URL, rendering fails and asks for-postgresql.init.host and postgresql.init.port.+postgresql.init.host/port or schema.dbHost/dbPort.*/}}{{- define "gravitino.entityJdbcAuthorityFromUrl" -}}{{- $url := .Values.entity.jdbcUrl | default "" -}}@@ -149,7 +270,7 @@ postgresql.init.host and postgresql.init.port.{{- $path := trimPrefix "jdbc:postgresql://" $url -}}{{- $auth := (splitList "/" $path | first) -}}{{- if or (contains "[" $auth) (contains "," $auth) -}}-{{- fail "entity.jdbcUrl authority is IPv6 or multi-host; set postgresql.init.host and postgresql.init.port explicitly (JDBC URL host/port fallback supports only a single host:port)" -}}+{{- fail "entity.jdbcUrl authority is IPv6 or multi-host; set postgresql.init.host/port or schema.dbHost/dbPort explicitly (JDBC URL host/port fallback supports only a single host:port)" -}}{{- end -}}{{- $auth -}}{{- end -}}@@ -221,7 +342,7 @@ Hostname for init-postgresql psql (-h).{{- if .Values.postgresql.init.host -}}{{- .Values.postgresql.init.host -}}{{- else if .Values.postgresql.enabled -}}-{{- printf "%s-postgresql" .Release.Name -}}+{{- include "gravitino.postgresql.fullname" . -}}{{- else -}}{{- $fromUrl := include "gravitino.entityJdbcHostFromUrl" . | trim -}}{{- if $fromUrl -}}@@ -323,7 +444,7 @@ Secret name for init-postgresql POSTGRES_PASSWORD secretKeyRef.{{- else if and .Values.postgresql.enabled .Values.postgresql.auth.existingSecret -}}{{- tpl (.Values.postgresql.auth.existingSecret | toString) . -}}{{- else if .Values.postgresql.enabled -}}-{{- printf "%s-postgresql" .Release.Name -}}+{{- include "gravitino.postgresql.fullname" . -}}{{- else if eq (include "gravitino.entityUsesExternalPostgresql" . | trim) "true" -}}{{- fail "postgresql.init.existingSecret is required when postgresql.init.enabled is true for external PostgreSQL" -}}{{- end -}}@@ -372,4 +493,262 @@ Database name for init-postgresql GRAVITINO_DB.{{- else -}}{{- .Values.postgresql.auth.database | default "gravitino" -}}{{- end -}}-{{- end -}}\ No newline at end of file+{{- end -}}+{{/*+True when the entity store uses an external MySQL JDBC URL (not in-chart Bitnami).+*/}}+{{- define "gravitino.entityUsesExternalMysql" -}}+{{- $url := .Values.entity.jdbcUrl | default "" -}}+{{- if and (not .Values.mysql.enabled) (not .Values.postgresql.enabled) (hasPrefix "jdbc:mysql://" $url) -}}+true+{{- end -}}+{{- end -}}++{{/*+True when a relational JDBC backend is configured for schema migration.+*/}}+{{- define "gravitino.schemaHasTarget" -}}+{{- if or .Values.mysql.enabled .Values.postgresql.enabled (eq (include "gravitino.entityUsesExternalMysql" . | trim) "true") (eq (include "gravitino.entityUsesExternalPostgresql" . | trim) "true") -}}+true+{{- end -}}+{{- end -}}++{{/*+True when the schema-migrate Job should run (regular resource, not a Helm hook).+*/}}+{{- define "gravitino.schemaMigrateEnabled" -}}+{{- if .Values.schema.migrate.enabled -}}+{{- if ne (include "gravitino.schemaHasTarget" . | trim) "true" -}}+{{- fail "schema.migrate.enabled is true but no relational target: enable mysql/postgresql or set entity.jdbcUrl to jdbc:mysql:// or jdbc:postgresql://" -}}+{{- end -}}+true+{{- end -}}+{{- end -}}++{{/*+mysql or postgresql for schema migrate.+*/}}+{{- define "gravitino.schemaMigrateEngine" -}}+{{- if .Values.mysql.enabled -}}+mysql+{{- else if .Values.postgresql.enabled -}}+postgresql+{{- else if eq (include "gravitino.entityUsesExternalMysql" . | trim) "true" -}}+mysql+{{- else if eq (include "gravitino.entityUsesExternalPostgresql" . | trim) "true" -}}+postgresql+{{- end -}}+{{- end -}}++{{/*+Authority segment from jdbc:mysql:// URLs (single host:port only).+*/}}+{{- define "gravitino.entityJdbcMysqlAuthorityFromUrl" -}}+{{- $url := .Values.entity.jdbcUrl | default "" -}}+{{- if hasPrefix "jdbc:mysql://" $url -}}+{{- $path := trimPrefix "jdbc:mysql://" $url -}}+{{- $path = splitList "?" $path | first -}}+{{- if contains "@" $path -}}+{{- $path = last (splitList "@" $path) -}}+{{- end -}}+{{- $auth := splitList "/" $path | first -}}+{{- if or (contains "[" $auth) (contains "," $auth) -}}+{{- fail "entity.jdbcUrl authority is IPv6 or multi-host; set schema.dbHost and schema.dbPort explicitly" -}}+{{- end -}}+{{- $auth -}}+{{- end -}}+{{- end -}}++{{/*+Database name from jdbc:mysql://host:port/db+*/}}+{{- define "gravitino.entityJdbcMysqlDatabaseFromUrl" -}}+{{- $url := .Values.entity.jdbcUrl | default "" -}}+{{- if hasPrefix "jdbc:mysql://" $url -}}+{{- $path := trimPrefix "jdbc:mysql://" $url -}}+{{- $parts := splitList "/" $path -}}+{{- if ge (len $parts) 2 -}}+{{- $dbPart := index $parts 1 -}}+{{- $db := splitList "?" $dbPart | first -}}+{{- if $db -}}+{{- $db -}}+{{- end -}}+{{- end -}}+{{- end -}}+{{- end -}}++{{/*+Host for schema-migrate Job.+*/}}+{{- define "gravitino.schemaMigrateHost" -}}+{{- $host := .Values.schema.dbHost | default "" | toString | trim -}}+{{- if $host -}}+{{- $host -}}+{{- else if .Values.mysql.enabled -}}+{{- include "gravitino.mysql.fullname" . -}}+{{- else if .Values.postgresql.enabled -}}+{{- include "gravitino.postgresql.fullname" . -}}+{{- else if eq (include "gravitino.entityUsesExternalMysql" . | trim) "true" -}}+{{- $auth := include "gravitino.entityJdbcMysqlAuthorityFromUrl" . | trim -}}+{{- if contains ":" $auth -}}+{{- index (splitList ":" $auth) 0 -}}+{{- else -}}+{{- $auth -}}+{{- end -}}+{{- else -}}+{{- $fromUrl := include "gravitino.entityJdbcHostFromUrl" . | trim -}}+{{- if $fromUrl -}}+{{- $fromUrl -}}+{{- else -}}+{{- fail "could not parse host from entity.jdbcUrl; set schema.dbHost" -}}+{{- end -}}+{{- end -}}+{{- end -}}++{{/*+Port for schema-migrate Job.+*/}}+{{- define "gravitino.schemaMigratePort" -}}+{{- $port := .Values.schema.dbPort | default "" | toString | trim -}}+{{- if $port -}}+{{- $port -}}+{{- else if .Values.mysql.enabled -}}+3306+{{- else if .Values.postgresql.enabled -}}+5432+{{- else if eq (include "gravitino.entityUsesExternalMysql" . | trim) "true" -}}+{{- $auth := include "gravitino.entityJdbcMysqlAuthorityFromUrl" . | trim -}}+{{- if and $auth (contains ":" $auth) -}}+{{- index (splitList ":" $auth) 1 -}}+{{- else -}}+3306+{{- end -}}+{{- else -}}+{{- include "gravitino.entityJdbcPortFromUrl" . | trim -}}+{{- end -}}+{{- end -}}++{{/*+Database name for schema-migrate Job.+*/}}+{{- define "gravitino.schemaMigrateDatabase" -}}+{{- $db := .Values.schema.dbName | default "" | toString | trim -}}+{{- if $db -}}+{{- $db -}}+{{- else if .Values.mysql.enabled -}}+{{- .Values.mysql.auth.database -}}+{{- else if .Values.postgresql.enabled -}}+{{- .Values.postgresql.auth.database | default "gravitino" -}}+{{- else if eq (include "gravitino.entityUsesExternalMysql" . | trim) "true" -}}+{{- $fromUrl := include "gravitino.entityJdbcMysqlDatabaseFromUrl" . | trim -}}+{{- if $fromUrl -}}+{{- $fromUrl -}}+{{- else -}}+{{- fail "could not parse database name from entity.jdbcUrl; use jdbc:mysql://<host>:<port>/<database> or set schema.dbName" -}}+{{- end -}}+{{- else -}}+{{- $fromUrl := include "gravitino.entityJdbcDatabaseFromUrl" . | trim -}}+{{- if $fromUrl -}}+{{- $fromUrl -}}+{{- else -}}+{{- fail "could not parse database name from entity.jdbcUrl; use jdbc:postgresql://<host>:<port>/<database> or set schema.dbName" -}}+{{- end -}}+{{- end -}}+{{- end -}}++{{/*+Password Secret for external relational stores (schema-migrate Job).+*/}}+{{- define "gravitino.schemaMigrateSecretName" -}}+{{- if or .Values.mysql.enabled .Values.postgresql.enabled -}}+{{- else if .Values.schema.migrate.existingSecret -}}+{{- .Values.schema.migrate.existingSecret -}}+{{- else -}}+{{- fail "schema.migrate.existingSecret is required when schema.migrate.enabled is true for external MySQL or PostgreSQL" -}}+{{- end -}}+{{- end -}}++{{/*+PostgreSQL currentSchema for schema-migrate Job (PG_CURRENT_SCHEMA / PGOPTIONS).++Prefer schema.currentSchema; otherwise currentSchema from entity.jdbcUrl.+Only simple (unquoted-style) identifiers are accepted. Fold to lowercase so+lookup (pg_namespace.nspname), CREATE SCHEMA, and PGOPTIONS search_path all use+the same name — matching PostgreSQL unquoted-identifier / JDBC currentSchema+folding (e.g. currentSchema=App → app), same as gravitino.postgresqlInitCurrentSchema.+*/}}+{{- define "gravitino.schemaMigrateCurrentSchema" -}}+{{- $schema := "" -}}+{{- if .Values.schema.currentSchema -}}+{{- $schema = .Values.schema.currentSchema | toString | trim -}}+{{- else if eq (include "gravitino.entityUsesExternalPostgresql" . | trim) "true" -}}+{{- $schema = include "gravitino.entityJdbcCurrentSchemaFromUrl" . | trim -}}+{{- end -}}+{{- if $schema -}}+{{- if not (regexMatch "^[A-Za-z_][A-Za-z0-9_]*$" $schema) -}}+{{- fail (printf "schema.currentSchema / entity.jdbcUrl currentSchema %q must be a simple PostgreSQL identifier" $schema) -}}+{{- end -}}+{{- $schema | lower -}}+{{- end -}}+{{- end -}}++{{/*+sslmode for schema-migrate Job (postgresql).+*/}}+{{- define "gravitino.schemaMigrateSslMode" -}}+{{- if .Values.schema.sslMode -}}+{{- .Values.schema.sslMode -}}+{{- else if eq (include "gravitino.entityUsesExternalPostgresql" . | trim) "true" -}}+{{- include "gravitino.entityJdbcSslModeFromUrl" . | trim -}}+{{- end -}}+{{- end -}}++{{- define "gravitino.schemaMigrateSslCaSecretName" -}}+{{- $ssl := .Values.schema.ssl | default dict -}}+{{- $secret := $ssl.existingSecret | default "" | toString | trim -}}+{{- if $secret -}}+{{- $secret -}}+{{- end -}}+{{- end -}}++{{- define "gravitino.schemaMigrateSslCaKey" -}}+{{- $ssl := .Values.schema.ssl | default dict -}}+{{- $ssl.caCert | default "ca.crt" | toString | trim -}}+{{- end -}}++{{/*+Kubernetes Job name for schema-migrate.++Truncate the release-name portion only so the full "-schema-migrate-rN" revision+suffix always survives the 63-character Kubernetes name limit. Truncating the+complete printf string would drop the revision for long release names and make+revisions collide while the previous Job's TTL is still active.+*/}}+{{- define "gravitino.schemaMigrateJobName" -}}+{{- $suffix := printf "-schema-migrate-r%d" .Release.Revision -}}+{{- $maxRelease := int (sub 63 (len $suffix)) -}}+{{- if lt $maxRelease 1 -}}+{{- fail (printf "schema-migrate Job revision suffix %q leaves no room for a release name under the 63-character Kubernetes limit" $suffix) -}}+{{- end -}}+{{- printf "%s%s" (.Release.Name | trunc $maxRelease | trimSuffix "-") $suffix -}}+{{- end -}}++{{- define "gravitino.schemaMigrateSslValidate" -}}+{{- if ne (include "gravitino.schemaMigrateEngine" . | trim) "postgresql" -}}+{{- else -}}+{{- $mode := include "gravitino.schemaMigrateSslMode" . | trim | lower -}}+{{- $caSecret := include "gravitino.schemaMigrateSslCaSecretName" . | trim -}}+{{- if and (or (eq $mode "verify-ca") (eq $mode "verify-full")) (not $caSecret) -}}+{{- fail "schema.ssl.existingSecret is required when sslmode is verify-ca or verify-full for the schema-migrate Job" -}}+{{- end -}}+{{- end -}}+{{- end -}}++{{/*+Validate schema.migrate inputs that are knowable at render time (PostgreSQL TLS).+schema.baselineVersion shape is checked in schema-migrate.sh only when the Job+actually consumes it (unused / stale values must not block render).+*/}}+{{- define "gravitino.schemaMigrateValidate" -}}+{{- $_ := include "gravitino.schemaMigrateSslValidate" . -}}+{{- end -}}diff --git a/dev/charts/gravitino/templates/configmap.yaml b/dev/charts/gravitino/templates/configmap.yamlindex 9551f384cf..364a1ff752 100644--- a/dev/charts/gravitino/templates/configmap.yaml+++ b/dev/charts/gravitino/templates/configmap.yaml@@ -30,4 +30,6 @@ data:gravitino.conf: |-{{- tpl (.Files.Get "resources/config/gravitino.conf") . | nindent 4 }}log4j2.properties: |-- {{- tpl (.Files.Get "resources/config/log4j2.properties") . | nindent 4 }}\ No newline at end of file+ {{- tpl (.Files.Get "resources/config/log4j2.properties") . | nindent 4 }}+ schema-migrate.sh: |-+ {{- .Files.Get "resources/scripts/schema-migrate.sh" | nindent 4 }}\ No newline at end of filediff --git a/dev/charts/gravitino/templates/deployment.yaml b/dev/charts/gravitino/templates/deployment.yamlindex 74723b0574..8d0413c42e 100644--- a/dev/charts/gravitino/templates/deployment.yaml+++ b/dev/charts/gravitino/templates/deployment.yaml@@ -74,7 +74,7 @@ spec:volumeMounts:- mountPath: /tmp/scripts/name: scripts-emptydir- {{- if .Values.mysql.enabled }}+ {{- if eq (include "gravitino.mysqlSchemaInitEnabled" . | trim) "true" }}- name: init-mysqlimage: {{ include "init-mysql.image" . }}imagePullPolicy: "{{ .Values.image.pullPolicy }}"@@ -82,7 +82,7 @@ spec:- /bin/bash- -c- |- while ! mysql -h {{ .Release.Name }}-mysql -u root -e "SELECT 1"; do+ while ! mysql -h {{ include "gravitino.mysql.fullname" . }} -u root -e "SELECT 1"; doecho "Waiting for MySQL to be ready..."sleep 2done@@ -104,11 +104,11 @@ spec:fiecho "Schema file: $schema_file"echo "Upgrade file: $upgrade_file"- if ! mysql -h {{ .Release.Name }}-mysql -u root -D $GRAVITINO_DB <"$upgrade_file"; then+ if ! mysql -h {{ include "gravitino.mysql.fullname" . }} -u root -D $GRAVITINO_DB <"$upgrade_file"; thenecho "WARNING: Upgrade script failed: $upgrade_file" >&2echo "Continuing with schema script..." >&2fi- mysql -h {{ .Release.Name }}-mysql -u root -D $GRAVITINO_DB <$schema_file+ mysql -h {{ include "gravitino.mysql.fullname" . }} -u root -D $GRAVITINO_DB <$schema_fileresources:{{- toYaml .Values.initResources | nindent 12 }}securityContext:@@ -117,7 +117,57 @@ spec:- name: MYSQL_PWDvalueFrom:secretKeyRef:- name: {{ .Release.Name }}-mysql+ name: {{ include "gravitino.mysql.secretName" . }}+ key: mysql-root-password+ - name: GRAVITINO_DB+ value: {{ .Values.mysql.auth.database }}+ volumeMounts:+ - mountPath: /scripts+ name: scripts-emptydir+ {{- else if and .Values.mysql.enabled (eq (include "gravitino.schemaWaitEnabled" . | trim) "true") }}+ - name: init-mysql+ image: {{ include "init-mysql.image" . }}+ imagePullPolicy: "{{ .Values.image.pullPolicy }}"+ command:+ - /bin/bash+ - -c+ - |+ set -euo pipefail+ VERSION=$(cat /scripts/version.txt)+ if [ -z "$VERSION" ]; then+ echo "ERROR: Please set VERSION (missing /scripts/version.txt)" >&2+ exit 1+ fi+ echo "Waiting for schema version ${VERSION} (written by the schema-migrate Job)..."+ {{- include "gravitino.schemaWaitPreamble" . | nindent 14 }}+ while true; do+ if [ "$SECONDS" -ge "$deadline" ]; then+ echo "ERROR: timed out after ${timeout}s waiting for schema version ${VERSION}" >&2+ exit 1+ fi+ if mysql -h {{ include "gravitino.mysql.fullname" . }} -u root -e "SELECT 1" >/dev/null 2>&1; then+ current=$(mysql -h {{ include "gravitino.mysql.fullname" . }} -u root -D "$GRAVITINO_DB" -sNe "{{ include "gravitino.schemaReadyQuery" "mysql" }}" 2>/dev/null | tr -d '[:space:]' || true)+ if [ "$current" = "$VERSION" ]; then+ echo "Schema version ${current} is ready."+ exit 0+ fi+ echo "Recorded schema version is '${current:-<none>}'; waiting for ${VERSION}..."+ else+ echo "Waiting for MySQL to be ready..."+ fi+ sleep 2+ done+ resources:+ {{- toYaml .Values.initResources | nindent 12 }}+ securityContext:+ {{- toYaml .Values.initContainerSecurityContext | nindent 12 }}+ env:+ - name: SCHEMA_WAIT_TIMEOUT+ value: {{ include "gravitino.schemaWaitTimeoutSeconds" . | quote }}+ - name: MYSQL_PWD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.mysql.secretName" . }}key: mysql-root-password- name: GRAVITINO_DBvalue: {{ .Values.mysql.auth.database }}@@ -246,6 +296,171 @@ spec:mountPath: /db-sslreadOnly: true{{- end }}+ {{- else if and .Values.postgresql.enabled (eq (include "gravitino.schemaWaitEnabled" . | trim) "true") }}+ {{- $pgSchema := include "gravitino.schemaMigrateCurrentSchema" . | trim }}+ - name: init-postgresql+ image: {{ include "init-postgresql.image" . }}+ imagePullPolicy: "{{ .Values.image.pullPolicy }}"+ command:+ - /bin/bash+ - -c+ - |+ set -euo pipefail+ VERSION=$(cat /scripts/version.txt)+ if [ -z "$VERSION" ]; then+ echo "ERROR: Please set VERSION (missing /scripts/version.txt)" >&2+ exit 1+ fi+ echo "Waiting for schema version ${VERSION} (written by the schema-migrate Job)..."+ {{- include "gravitino.schemaWaitPreamble" . | nindent 14 }}+ while true; do+ if [ "$SECONDS" -ge "$deadline" ]; then+ echo "ERROR: timed out after ${timeout}s waiting for schema version ${VERSION}" >&2+ exit 1+ fi+ if PGPASSWORD="$POSTGRES_PASSWORD" psql -h {{ include "gravitino.postgresql.fullname" . }} -U "$POSTGRES_USER" -d "$GRAVITINO_DB" -c "SELECT 1" >/dev/null 2>&1; then+ current=$(PGPASSWORD="$POSTGRES_PASSWORD" psql -h {{ include "gravitino.postgresql.fullname" . }} -U "$POSTGRES_USER" -d "$GRAVITINO_DB" -tAc "{{ include "gravitino.schemaReadyQuery" "postgresql" }}" 2>/dev/null | tr -d '[:space:]' || true)+ if [ "$current" = "$VERSION" ]; then+ echo "Schema version ${current} is ready."+ exit 0+ fi+ echo "Recorded schema version is '${current:-<none>}'; waiting for ${VERSION}..."+ else+ echo "Waiting for PostgreSQL to be ready..."+ fi+ sleep 2+ done+ resources:+ {{- toYaml .Values.initResources | nindent 12 }}+ securityContext:+ {{- toYaml .Values.initContainerSecurityContext | nindent 12 }}+ env:+ - name: SCHEMA_WAIT_TIMEOUT+ value: {{ include "gravitino.schemaWaitTimeoutSeconds" . | quote }}+ - name: POSTGRES_USER+ value: {{ .Values.postgresql.auth.username }}+ - name: GRAVITINO_DB+ value: {{ .Values.postgresql.auth.database }}+ - name: POSTGRES_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.postgresql.secretName" . }}+ key: password+ {{- if $pgSchema }}+ - name: PGOPTIONS+ value: {{ printf "-c search_path=%s" $pgSchema | quote }}+ {{- end }}+ volumeMounts:+ - mountPath: /scripts+ name: scripts-emptydir+ {{- end }}+ {{- if and (eq (include "gravitino.schemaWaitEnabled" . | trim) "true") (not .Values.mysql.enabled) (not .Values.postgresql.enabled) }}+ {{- $engine := include "gravitino.schemaMigrateEngine" . | trim }}+ {{- $dbHost := include "gravitino.schemaMigrateHost" . | trim }}+ {{- $dbPort := include "gravitino.schemaMigratePort" . | trim }}+ {{- $dbName := include "gravitino.schemaMigrateDatabase" . | trim }}+ {{- $pgSchema := include "gravitino.schemaMigrateCurrentSchema" . | trim }}+ {{- $pgSslMode := include "gravitino.schemaMigrateSslMode" . | trim }}+ {{- $sslCaSecret := include "gravitino.schemaMigrateSslCaSecretName" . | trim }}+ - name: wait-for-schema+ {{- if eq $engine "mysql" }}+ image: {{ include "init-mysql.image" . }}+ {{- else }}+ image: {{ include "init-postgresql.image" . }}+ {{- end }}+ imagePullPolicy: "{{ .Values.image.pullPolicy }}"+ command:+ - /bin/bash+ - -c+ - |+ set -euo pipefail+ VERSION=$(cat /scripts/version.txt)+ if [ -z "$VERSION" ]; then+ echo "ERROR: Please set VERSION (missing /scripts/version.txt)" >&2+ exit 1+ fi+ echo "Waiting for schema version ${VERSION} (written by the schema-migrate Job)..."+ {{- include "gravitino.schemaWaitPreamble" . | nindent 14 }}+ while true; do+ if [ "$SECONDS" -ge "$deadline" ]; then+ echo "ERROR: timed out after ${timeout}s waiting for schema version ${VERSION}" >&2+ exit 1+ fi+ {{- if eq $engine "mysql" }}+ if mysql -h "$DB_HOST" -P "$DB_PORT" -u "$MYSQL_USER" -e "SELECT 1" >/dev/null 2>&1; then+ current=$(mysql -h "$DB_HOST" -P "$DB_PORT" -u "$MYSQL_USER" -D "$GRAVITINO_DB" -sNe "{{ include "gravitino.schemaReadyQuery" "mysql" }}" 2>/dev/null | tr -d '[:space:]' || true)+ if [ "$current" = "$VERSION" ]; then+ echo "Schema version ${current} is ready."+ exit 0+ fi+ echo "Recorded schema version is '${current:-<none>}'; waiting for ${VERSION}..."+ else+ echo "Waiting for MySQL to be ready..."+ fi+ {{- else }}+ if PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$POSTGRES_USER" -d "$GRAVITINO_DB" -c "SELECT 1" >/dev/null 2>&1; then+ current=$(PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$POSTGRES_USER" -d "$GRAVITINO_DB" -tAc "{{ include "gravitino.schemaReadyQuery" "postgresql" }}" 2>/dev/null | tr -d '[:space:]' || true)+ if [ "$current" = "$VERSION" ]; then+ echo "Schema version ${current} is ready."+ exit 0+ fi+ echo "Recorded schema version is '${current:-<none>}'; waiting for ${VERSION}..."+ else+ echo "Waiting for PostgreSQL to be ready..."+ fi+ {{- end }}+ sleep 2+ done+ resources:+ {{- toYaml .Values.initResources | nindent 12 }}+ securityContext:+ {{- toYaml .Values.initContainerSecurityContext | nindent 12 }}+ env:+ - name: SCHEMA_WAIT_TIMEOUT+ value: {{ include "gravitino.schemaWaitTimeoutSeconds" . | quote }}+ - name: DB_HOST+ value: {{ $dbHost | quote }}+ - name: DB_PORT+ value: {{ $dbPort | quote }}+ - name: GRAVITINO_DB+ value: {{ $dbName | quote }}+ {{- if eq $engine "mysql" }}+ - name: MYSQL_USER+ value: {{ .Values.entity.jdbcUser | quote }}+ - name: MYSQL_PWD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.schemaMigrateSecretName" . | trim }}+ key: {{ .Values.schema.migrate.existingSecretPasswordKey | default "password" }}+ {{- else }}+ - name: POSTGRES_USER+ value: {{ .Values.entity.jdbcUser | quote }}+ - name: POSTGRES_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.schemaMigrateSecretName" . | trim }}+ key: {{ .Values.schema.migrate.existingSecretPasswordKey | default "password" }}+ {{- if $pgSchema }}+ - name: PGOPTIONS+ value: {{ printf "-c search_path=%s" $pgSchema | quote }}+ {{- end }}+ {{- if $pgSslMode }}+ - name: PGSSLMODE+ value: {{ $pgSslMode | quote }}+ {{- end }}+ {{- if $sslCaSecret }}+ - name: PGSSLROOTCERT+ value: /db-ssl/ca.crt+ {{- end }}+ {{- end }}+ volumeMounts:+ - mountPath: /scripts+ name: scripts-emptydir+ {{- if and (ne $engine "mysql") $sslCaSecret }}+ - name: schema-migrate-ssl+ mountPath: /db-ssl+ readOnly: true+ {{- end }}{{- end }}containers:- name: {{ include "gravitino.name" . }}@@ -319,6 +534,17 @@ spec:- key: {{ include "gravitino.postgresqlInitSslCaKey" . | trim }}path: ca.crt{{- end }}+ {{- if and (eq (include "gravitino.schemaWaitEnabled" . | trim) "true") (not .Values.mysql.enabled) (not .Values.postgresql.enabled) }}+ {{- $sslCaSecret := include "gravitino.schemaMigrateSslCaSecretName" . | trim }}+ {{- if and (eq (include "gravitino.schemaMigrateEngine" . | trim) "postgresql") $sslCaSecret }}+ - name: schema-migrate-ssl+ secret:+ secretName: {{ $sslCaSecret }}+ items:+ - key: {{ include "gravitino.schemaMigrateSslCaKey" . | trim }}+ path: ca.crt+ {{- end }}+ {{- end }}{{- if not .Values.persistence.enabled }}- name: storageemptyDir: {}diff --git a/dev/charts/gravitino/templates/schema-migrate-job.yaml b/dev/charts/gravitino/templates/schema-migrate-job.yamlnew file mode 100644index 0000000000..ede22468cf--- /dev/null+++ b/dev/charts/gravitino/templates/schema-migrate-job.yaml@@ -0,0 +1,190 @@+{{- /*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+ */}}++{{- if eq (include "gravitino.schemaMigrateEnabled" . | trim) "true" }}+{{- $_ := include "gravitino.schemaMigrateValidate" . }}+{{- $engine := include "gravitino.schemaMigrateEngine" . | trim }}+{{- $dbHost := include "gravitino.schemaMigrateHost" . | trim }}+{{- $dbPort := include "gravitino.schemaMigratePort" . | trim }}+{{- $dbName := include "gravitino.schemaMigrateDatabase" . | trim }}+{{- $pgSchema := include "gravitino.schemaMigrateCurrentSchema" . | trim }}+{{- $pgSslMode := include "gravitino.schemaMigrateSslMode" . | trim }}+{{- $sslCaSecret := include "gravitino.schemaMigrateSslCaSecretName" . | trim }}+apiVersion: batch/v1+kind: Job+metadata:+ name: {{ include "gravitino.schemaMigrateJobName" . }}+ namespace: {{ include "gravitino.namespace" . }}+ labels:+ {{- include "gravitino.labels" . | nindent 4 }}+ app.kubernetes.io/component: schema-migrate+spec:+ backoffLimit: {{ .Values.schema.migrate.backoffLimit }}+ activeDeadlineSeconds: {{ .Values.schema.migrate.activeDeadlineSeconds }}+ ttlSecondsAfterFinished: 600+ completions: 1+ parallelism: 1+ template:+ metadata:+ labels:+ {{- include "gravitino.labels" . | nindent 8 }}+ app.kubernetes.io/component: schema-migrate+ spec:+ restartPolicy: Never+ {{- with .Values.global.imagePullSecrets }}+ imagePullSecrets:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ {{- with .Values.podSecurityContext }}+ securityContext:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ # Same scheduling as the Gravitino Deployment so the Job is not Pending on+ # tainted / nodeSelector-restricted clusters while wait-init times out.+ nodeSelector:+ {{- toYaml .Values.nodeSelector | nindent 8 }}+ affinity:+ {{- toYaml .Values.affinity | nindent 8 }}+ tolerations:+ {{- toYaml .Values.tolerations | nindent 8 }}+ initContainers:+ - name: sqlfile+ image: {{ include "gravitino.image" . }}+ imagePullPolicy: "{{ .Values.image.pullPolicy }}"+ command:+ - /bin/bash+ - -c+ - |+ cp -r /opt/gravitino/scripts/* /tmp/scripts/+ VERSION=$(ls /opt/gravitino/libs/gravitino-server-* | grep -oP '[0-9]+\.[0-9]+\.[0-9]+'|head -1)+ echo $VERSION > /tmp/scripts/version.txt+ resources:+ {{- toYaml .Values.initResources | nindent 12 }}+ securityContext:+ {{- toYaml .Values.initContainerSecurityContext | nindent 12 }}+ volumeMounts:+ - mountPath: /tmp/scripts/+ name: scripts-emptydir+ containers:+ - name: schema-migrate+ {{- if eq $engine "mysql" }}+ image: {{ include "init-mysql.image" . }}+ {{- else }}+ image: {{ include "init-postgresql.image" . }}+ {{- end }}+ imagePullPolicy: "{{ .Values.image.pullPolicy }}"+ command:+ - /bin/bash+ - /schema-migrate.sh+ resources:+ {{- toYaml .Values.initResources | nindent 12 }}+ securityContext:+ {{- toYaml .Values.initContainerSecurityContext | nindent 12 }}+ env:+ - name: DB_ENGINE+ value: {{ $engine | quote }}+ - name: DB_HOST+ value: {{ $dbHost | quote }}+ - name: DB_PORT+ value: {{ $dbPort | quote }}+ - name: GRAVITINO_DB+ value: {{ $dbName | quote }}+ - name: SCRIPTS_DIR+ value: /scripts+ - name: BASELINE_VERSION+ value: {{ .Values.schema.baselineVersion | default "" | quote }}+ {{- if eq $engine "mysql" }}+ {{- if .Values.mysql.enabled }}+ - name: MYSQL_USER+ value: root+ - name: MYSQL_PWD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.mysql.secretName" . }}+ key: mysql-root-password+ {{- else }}+ - name: MYSQL_USER+ value: {{ .Values.entity.jdbcUser | quote }}+ - name: MYSQL_PWD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.schemaMigrateSecretName" . | trim }}+ key: {{ .Values.schema.migrate.existingSecretPasswordKey | default "password" }}+ {{- end }}+ {{- else }}+ - name: POSTGRES_USER+ {{- if .Values.postgresql.enabled }}+ value: {{ .Values.postgresql.auth.username | quote }}+ - name: POSTGRES_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.postgresql.secretName" . }}+ key: password+ {{- else }}+ value: {{ .Values.entity.jdbcUser | quote }}+ - name: POSTGRES_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "gravitino.schemaMigrateSecretName" . | trim }}+ key: {{ .Values.schema.migrate.existingSecretPasswordKey | default "password" }}+ {{- end }}+ - name: PGPORT+ value: {{ $dbPort | quote }}+ {{- if $pgSslMode }}+ - name: PGSSLMODE+ value: {{ $pgSslMode | quote }}+ {{- end }}+ {{- if $pgSchema }}+ - name: PG_CURRENT_SCHEMA+ value: {{ $pgSchema | quote }}+ - name: PGOPTIONS+ value: {{ printf "-c search_path=%s" $pgSchema | quote }}+ {{- end }}+ {{- if $sslCaSecret }}+ - name: PGSSLROOTCERT+ value: /db-ssl/ca.crt+ {{- end }}+ {{- end }}+ volumeMounts:+ - mountPath: /scripts+ name: scripts-emptydir+ - mountPath: /schema-migrate.sh+ name: gravitino-conf+ subPath: schema-migrate.sh+ readOnly: true+ {{- if $sslCaSecret }}+ - name: schema-migrate-ssl+ mountPath: /db-ssl+ readOnly: true+ {{- end }}+ volumes:+ - name: scripts-emptydir+ emptyDir: {}+ - name: gravitino-conf+ configMap:+ name: {{ include "gravitino.fullname" . }}+ {{- if $sslCaSecret }}+ - name: schema-migrate-ssl+ secret:+ secretName: {{ $sslCaSecret }}+ items:+ - key: {{ include "gravitino.schemaMigrateSslCaKey" . | trim }}+ path: ca.crt+ {{- end }}+{{- end }}\ No newline at end of filediff --git a/dev/charts/gravitino/tests/deployment_test.yaml b/dev/charts/gravitino/tests/deployment_test.yamlindex 31767a569b..9d1f2775c1 100644--- a/dev/charts/gravitino/tests/deployment_test.yaml+++ b/dev/charts/gravitino/tests/deployment_test.yaml@@ -517,7 +517,7 @@ tests:jdbcUser: gravitino_appasserts:- failedTemplate:- errorMessage: "entity.jdbcUrl authority is IPv6 or multi-host; set postgresql.init.host and postgresql.init.port explicitly (JDBC URL host/port fallback supports only a single host:port)"+ errorMessage: "entity.jdbcUrl authority is IPv6 or multi-host; set postgresql.init.host/port or schema.dbHost/dbPort explicitly (JDBC URL host/port fallback supports only a single host:port)"- it: fails when entity.jdbcUrl authority is multi-host and host/port are derived from the URLtemplate: deployment.yaml@@ -535,7 +535,7 @@ tests:jdbcUser: gravitino_appasserts:- failedTemplate:- errorMessage: "entity.jdbcUrl authority is IPv6 or multi-host; set postgresql.init.host and postgresql.init.port explicitly (JDBC URL host/port fallback supports only a single host:port)"+ errorMessage: "entity.jdbcUrl authority is IPv6 or multi-host; set postgresql.init.host/port or schema.dbHost/dbPort explicitly (JDBC URL host/port fallback supports only a single host:port)"- it: renders when IPv6 entity.jdbcUrl has explicit postgresql.init.host and porttemplate: deployment.yamldiff --git a/dev/charts/gravitino/tests/schema_migrate_test.yaml b/dev/charts/gravitino/tests/schema_migrate_test.yamlnew file mode 100644index 0000000000..995bf45b26--- /dev/null+++ b/dev/charts/gravitino/tests/schema_migrate_test.yaml@@ -0,0 +1,499 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++suite: test schema migrate job and wait-init+templates:+ - schema-migrate-job.yaml+ - configmap.yaml+ - deployment.yaml+tests:+ - it: ships schema-migrate.sh with a full upgrade chain+ template: configmap.yaml+ release:+ name: gravitino+ asserts:+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "apply_upgrade_chain"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "find_next_upgrade"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "Refusing to skip intermediate migrations"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "schema_upgrade_script_from"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "ensure_column_name_capacity"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "schema_version_markers_present"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "found_marker"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "require_semver"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "Waiting for MySQL database"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "Schema migration completed successfully"+ - matchRegex:+ path: data["schema-migrate.sh"]+ pattern: "schema.baselineVersion"+ - notMatchRegex:+ path: data["schema-migrate.sh"]+ pattern: "tail -n 1"+ - notMatchRegex:+ path: data["schema-migrate.sh"]+ pattern: "table match is enough"++ - it: renders a regular Job without Helm hooks for in-chart PostgreSQL+ template: schema-migrate-job.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ postgresql:+ enabled: true+ asserts:+ - isKind:+ of: Job+ - notExists:+ path: metadata.annotations["helm.sh/hook"]+ - equal:+ path: spec.parallelism+ value: 1+ - equal:+ path: spec.template.spec.containers[0].command[1]+ value: /schema-migrate.sh+ - contains:+ path: spec.template.spec.containers[0].env+ content:+ name: DB_ENGINE+ value: postgresql+ - contains:+ path: spec.template.spec.containers[0].env+ content:+ name: BASELINE_VERSION+ value: ""++ - it: passes schema.baselineVersion to the migrate Job+ template: schema-migrate-job.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ baselineVersion: "1.2.0"+ postgresql:+ enabled: true+ asserts:+ - contains:+ path: spec.template.spec.containers[0].env+ content:+ name: BASELINE_VERSION+ value: "1.2.0"++ - it: postgresql wait-init does not apply upgrade SQL when migrate is enabled+ template: deployment.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ postgresql:+ enabled: true+ asserts:+ - equal:+ path: spec.template.spec.initContainers[1].name+ value: init-postgresql+ - matchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: "Waiting for schema version"+ - matchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: "gravitino_schema_migration"+ - matchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: 'psql -h .* -U "\$POSTGRES_USER" -d "\$GRAVITINO_DB" -c "SELECT 1"'+ - notMatchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: "upgrade-.*-to-.*-postgresql"+ - contains:+ path: spec.template.spec.initContainers[1].env+ content:+ name: SCHEMA_WAIT_TIMEOUT+ value: "600"++ - it: mysql wait-init does not apply upgrade SQL when migrate is enabled+ template: deployment.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ mysql:+ enabled: true+ asserts:+ - equal:+ path: spec.template.spec.initContainers[1].name+ value: init-mysql+ - matchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: "Waiting for schema version"+ - notMatchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: "upgrade-.*-to-.*-mysql"++ - it: collapses Bitnami MySQL host and Secret when release name contains mysql+ release:+ name: gravitino-sm-mysql+ set:+ schema:+ migrate:+ enabled: true+ mysql:+ enabled: true+ asserts:+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: DB_HOST+ value: gravitino-sm-mysql+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: MYSQL_PWD+ valueFrom:+ secretKeyRef:+ name: gravitino-sm-mysql+ key: mysql-root-password+ - template: deployment.yaml+ matchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: "mysql -h gravitino-sm-mysql "+ - template: deployment.yaml+ contains:+ path: spec.template.spec.initContainers[1].env+ content:+ name: MYSQL_PWD+ valueFrom:+ secretKeyRef:+ name: gravitino-sm-mysql+ key: mysql-root-password+ - template: configmap.yaml+ matchRegex:+ path: data["gravitino.conf"]+ pattern: "jdbc:mysql://gravitino-sm-mysql:3306/"++ - it: keeps Release-Name-mysql when release name does not contain mysql+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ mysql:+ enabled: true+ asserts:+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: DB_HOST+ value: gravitino-mysql+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: MYSQL_PWD+ valueFrom:+ secretKeyRef:+ name: gravitino-mysql+ key: mysql-root-password++ - it: external PostgreSQL migrate Job uses operator Secret and Deployment wait+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ existingSecret: gravitino-pg-secret+ postgresql:+ enabled: false+ entity:+ jdbcUrl: jdbc:postgresql://pg.example.ci.local:5432/gravitino_meta?currentSchema=gravitino&sslmode=require+ jdbcDriver: org.postgresql.Driver+ jdbcUser: gravitino_app+ asserts:+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: DB_HOST+ value: pg.example.ci.local+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: POSTGRES_PASSWORD+ valueFrom:+ secretKeyRef:+ name: gravitino-pg-secret+ key: password+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: PGOPTIONS+ value: "-c search_path=gravitino"+ - template: deployment.yaml+ equal:+ path: spec.template.spec.initContainers[1].name+ value: wait-for-schema+ - template: deployment.yaml+ matchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: "Waiting for schema version"+ - template: deployment.yaml+ matchRegex:+ path: spec.template.spec.initContainers[1].command[2]+ pattern: 'psql -h "\$DB_HOST" -p "\$DB_PORT" -U "\$POSTGRES_USER" -d "\$GRAVITINO_DB" -c "SELECT 1"'+ - template: deployment.yaml+ contains:+ path: spec.template.spec.initContainers[1].env+ content:+ name: PGOPTIONS+ value: "-c search_path=gravitino"++ - it: folds mixed-case schema.currentSchema to lowercase for migrate Job and Deployment wait+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ existingSecret: gravitino-pg-secret+ currentSchema: App+ postgresql:+ enabled: false+ entity:+ jdbcUrl: jdbc:postgresql://pg.example.ci.local:5432/gravitino_meta?currentSchema=OtherSchema+ jdbcDriver: org.postgresql.Driver+ jdbcUser: gravitino_app+ asserts:+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: PG_CURRENT_SCHEMA+ value: app+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: PGOPTIONS+ value: "-c search_path=app"+ - template: deployment.yaml+ equal:+ path: spec.template.spec.initContainers[1].name+ value: wait-for-schema+ - template: deployment.yaml+ contains:+ path: spec.template.spec.initContainers[1].env+ content:+ name: PGOPTIONS+ value: "-c search_path=app"++ - it: folds mixed-case currentSchema from entity.jdbcUrl to lowercase for migrate Job and wait+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ existingSecret: gravitino-pg-secret+ postgresql:+ enabled: false+ entity:+ jdbcUrl: jdbc:postgresql://pg.example.ci.local:5432/gravitino_meta?currentSchema=App&sslmode=require+ jdbcDriver: org.postgresql.Driver+ jdbcUser: gravitino_app+ asserts:+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: PG_CURRENT_SCHEMA+ value: app+ - template: schema-migrate-job.yaml+ contains:+ path: spec.template.spec.containers[0].env+ content:+ name: PGOPTIONS+ value: "-c search_path=app"+ - template: deployment.yaml+ contains:+ path: spec.template.spec.initContainers[1].env+ content:+ name: PGOPTIONS+ value: "-c search_path=app"++ - it: keeps distinct Job names across revisions for a long release name+ template: schema-migrate-job.yaml+ release:+ # 48 chars: truncating the full printf would drop "-schema-migrate-rN".+ name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+ revision: 1+ set:+ schema:+ migrate:+ enabled: true+ postgresql:+ enabled: true+ asserts:+ - equal:+ path: metadata.name+ value: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-schema-migrate-r1+ - matchRegex:+ path: metadata.name+ pattern: "-schema-migrate-r1$"++ - it: keeps a different Job name for revision 2 with the same long release name+ template: schema-migrate-job.yaml+ release:+ name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+ revision: 2+ set:+ schema:+ migrate:+ enabled: true+ postgresql:+ enabled: true+ asserts:+ - equal:+ path: metadata.name+ value: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-schema-migrate-r2+ - matchRegex:+ path: metadata.name+ pattern: "-schema-migrate-r2$"++ - it: inherits Deployment nodeSelector affinity and tolerations on the Job+ template: schema-migrate-job.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ postgresql:+ enabled: true+ nodeSelector:+ disktype: ssd+ affinity:+ nodeAffinity:+ requiredDuringSchedulingIgnoredDuringExecution:+ nodeSelectorTerms:+ - matchExpressions:+ - key: topology.kubernetes.io/zone+ operator: In+ values:+ - ci-zone+ tolerations:+ - key: dedicated+ operator: Exists+ effect: NoSchedule+ asserts:+ - equal:+ path: spec.template.spec.nodeSelector.disktype+ value: ssd+ - equal:+ path: spec.template.spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchExpressions[0].key+ value: topology.kubernetes.io/zone+ - contains:+ path: spec.template.spec.tolerations+ content:+ key: dedicated+ operator: Exists+ effect: NoSchedule++ - it: fails when schema migrate enabled without relational target+ template: schema-migrate-job.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ asserts:+ - failedTemplate:+ errorPattern: "schema.migrate.enabled is true but no relational target"++ - it: does not fail render for a non-X.Y.Z baselineVersion left unused+ template: schema-migrate-job.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ # Runtime validates only when baseline is consumed; stale typos must not+ # block helm template when a recorded version already exists.+ baselineVersion: "1.2"+ postgresql:+ enabled: true+ asserts:+ - isKind:+ of: Job+ - contains:+ path: spec.template.spec.containers[0].env+ content:+ name: BASELINE_VERSION+ value: "1.2"++ - it: fails external PostgreSQL migrate without existingSecret+ template: schema-migrate-job.yaml+ release:+ name: gravitino+ set:+ schema:+ migrate:+ enabled: true+ postgresql:+ enabled: false+ entity:+ jdbcUrl: jdbc:postgresql://pg.example.ci.local:5432/gravitino+ jdbcDriver: org.postgresql.Driver+ jdbcUser: gravitino_app+ asserts:+ - failedTemplate:+ errorPattern: "schema.migrate.existingSecret is required"diff --git a/dev/charts/gravitino/values.yaml b/dev/charts/gravitino/values.yamlindex ab802193fc..cca39467c5 100644--- a/dev/charts/gravitino/values.yaml+++ b/dev/charts/gravitino/values.yaml@@ -176,6 +176,49 @@ postgresql:##existingSecretPasswordKey: password+## Schema migration (regular Job + Deployment wait)+## Runs once per revision as a normal Job (#11099, #9013). Application Pods wait+## for gravitino_schema_migration before starting. When enabled, per-pod+## init-mysql / init-postgresql schema apply is replaced by wait-only inits.+##+schema:+ migrate:+ ## @param schema.migrate.enabled Run a schema-migrate Job for entity DB schema.+ enabled: false+ ## @param schema.migrate.backoffLimit Job retries before the Job fails.+ backoffLimit: 3+ ## @param schema.migrate.activeDeadlineSeconds Hard limit for the migrate Job.+ activeDeadlineSeconds: 600+ ## @param schema.migrate.existingSecret Password Secret for external MySQL/PostgreSQL (required when no in-chart DB).+ existingSecret: ""+ ## @param schema.migrate.existingSecretPasswordKey Key in existingSecret for entity.jdbcUser password.+ existingSecretPasswordKey: password+ ## How long Gravitino Pods wait for gravitino_schema_migration before the init fails.+ wait:+ timeoutSeconds: 600+ ## Used when an existing database has no gravitino_schema_migration row and the+ ## version cannot be inferred from tables. When consumed it must be X.Y.Z (the+ ## Job validates only on that path; unused/stale values are ignored). Set to+ ## the Gravitino version that created the database (for example 1.2.0), or to+ ## the image version to only record and skip DDL. Inference only trusts+ ## upgrade scripts that ADD COLUMN; index-only upgrades need this baseline.+ baselineVersion: ""+ ## Optional overrides when entity.jdbcUrl is not enough (IPv6, multi-host, and so on).+ dbHost: ""+ dbPort: ""+ dbName: ""+ ## PostgreSQL libpq sslmode for the migrate Job when using external PostgreSQL.+ sslMode: ""+ ## PostgreSQL search_path for the migrate Job (external PostgreSQL).+ ## Simple identifiers only; mixed case is folded to lowercase for lookup,+ ## CREATE SCHEMA, and search_path (unquoted PostgreSQL identifier / JDBC+ ## currentSchema semantics, e.g. App → app).+ currentSchema: ""+ ssl:+ ## @param schema.ssl.existingSecret CA Secret for verify-ca / verify-full (PGSSLROOTCERT).+ existingSecret: ""+ caCert: ca.crt+## THE CONFIGURATION FOR Gravitino ENTITY STORE##entity:diff --git a/dev/ci/chart-schema-migrate-cross-version.sh b/dev/ci/chart-schema-migrate-cross-version.shnew file mode 100755index 0000000000..982798f01a--- /dev/null+++ b/dev/ci/chart-schema-migrate-cross-version.sh@@ -0,0 +1,258 @@+#!/usr/bin/env bash+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++# Live kind coverage: seed an existing relational schema at FROM_VERSION, then+# helm upgrade with schema.migrate.enabled so the Job applies the upgrade chain+# to the image version.+#+# Required env:+# KIND_REGISTRY, tag+# Optional env:+# ENGINE (mysql|postgresql, default mysql)+# FROM_VERSION (1.2.0|1.3.0, default 1.2.0)+# NAMESPACE, RELEASE_NAME, CHART_DIR, VALUES_FILE, REPO_ROOT+set -euo pipefail++REPO_ROOT="${REPO_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)}"+CHART_DIR="${CHART_DIR:-${REPO_ROOT}/dev/charts/gravitino}"+ENGINE="${ENGINE:-mysql}"+FROM_VERSION="${FROM_VERSION:-1.2.0}"+CHECK_SCRIPT="${REPO_ROOT}/dev/ci/check-schema-migrate.sh"++case "$ENGINE" in+ mysql)+ VALUES_FILE="${VALUES_FILE:-${REPO_ROOT}/dev/charts/gravitino/resources/scenarios/schema-migrate-mysql.yaml}"+ SCHEMA_SQL="${REPO_ROOT}/scripts/mysql/schema-${FROM_VERSION}-mysql.sql"+ WAIT_INIT=init-mysql+ DB_LABEL=mysql+ ;;+ postgresql)+ VALUES_FILE="${VALUES_FILE:-${REPO_ROOT}/dev/charts/gravitino/resources/scenarios/schema-migrate-postgresql.yaml}"+ SCHEMA_SQL="${REPO_ROOT}/scripts/postgresql/schema-${FROM_VERSION}-postgresql.sql"+ WAIT_INIT=init-postgresql+ DB_LABEL=postgresql+ ;;+ *)+ echo "ERROR: ENGINE must be mysql or postgresql (got ${ENGINE})" >&2+ exit 1+ ;;+esac++case "$FROM_VERSION" in+ 1.2.0 | 1.3.0) ;;+ *)+ echo "ERROR: FROM_VERSION must be 1.2.0 or 1.3.0 (got ${FROM_VERSION})" >&2+ exit 1+ ;;+esac++FROM_SLUG=${FROM_VERSION//./}+NAMESPACE="${NAMESPACE:-schema-migrate-cross-${ENGINE}-${FROM_SLUG}}"+RELEASE_NAME="${RELEASE_NAME:-gravitino-sm-${ENGINE}-${FROM_SLUG}}"++: "${KIND_REGISTRY:?KIND_REGISTRY is required}"+: "${tag:?tag is required}"++if [ ! -f "$SCHEMA_SQL" ]; then+ echo "ERROR: missing baseline schema SQL: ${SCHEMA_SQL}" >&2+ exit 1+fi+if [ ! -f "$CHECK_SCRIPT" ]; then+ echo "ERROR: missing ${CHECK_SCRIPT}" >&2+ exit 1+fi++chmod +x "$CHECK_SCRIPT"+helm dependency update "$CHART_DIR"++cleanup() {+ echo "::group::schema-migrate cross-version diagnostics (${NAMESPACE})"+ kubectl get pods,jobs -n "$NAMESPACE" -o wide || true+ kubectl describe pods -n "$NAMESPACE" || true+ kubectl logs -n "$NAMESPACE" -l app.kubernetes.io/component=schema-migrate --all-containers --tail=200 || true+ kubectl logs -n "$NAMESPACE" -l "release=${RELEASE_NAME}" --all-containers --tail=200 || true+ echo "::endgroup::"+ helm uninstall "$RELEASE_NAME" -n "$NAMESPACE" --wait || true+ kubectl delete namespace "$NAMESPACE" --wait=false || true+}+trap cleanup EXIT++kubectl get namespace "$NAMESPACE" >/dev/null 2>&1 || kubectl create namespace "$NAMESPACE"++echo "==> Fresh install with schema.migrate.enabled (${ENGINE})"+helm upgrade --install "$RELEASE_NAME" "$CHART_DIR" -n "$NAMESPACE" --wait --timeout 10m \+ --values "$VALUES_FILE" \+ --set image.registry="" \+ --set image.repository="${KIND_REGISTRY}/gravitino" \+ --set image.tag="${tag}"+bash "$CHECK_SCRIPT" "$NAMESPACE" "$RELEASE_NAME" "$ENGINE"++DEPLOY=$(kubectl get deploy -n "$NAMESPACE" -l "release=${RELEASE_NAME}" -o jsonpath='{.items[0].metadata.name}')+DB_POD=$(kubectl get pods -n "$NAMESPACE" -l "app.kubernetes.io/name=${DB_LABEL}" \+ -o jsonpath='{.items[0].metadata.name}')+DB_NAME=$(kubectl get deploy -n "$NAMESPACE" "$DEPLOY" \+ -o jsonpath="{.spec.template.spec.initContainers[?(@.name==\"${WAIT_INIT}\")].env[?(@.name==\"GRAVITINO_DB\")].value}")++# Match Bitnami fullname collapse / existingSecret via the wait-init secretKeyRef.+init_secret_name() {+ local init_name="$1"+ local env_name="$2"+ local secret+ secret=$(kubectl get deploy -n "$NAMESPACE" "$DEPLOY" \+ -o jsonpath="{.spec.template.spec.initContainers[?(@.name==\"${init_name}\")].env[?(@.name==\"${env_name}\")].valueFrom.secretKeyRef.name}")+ if [ -z "$secret" ]; then+ echo "ERROR: could not resolve Secret from ${DEPLOY}/${init_name}/${env_name}" >&2+ return 1+ fi+ printf '%s\n' "$secret"+}++column_count() {+ local table="$1"+ local column="$2"+ if [ "$ENGINE" = mysql ]; then+ local root_secret root_pw+ root_secret=$(init_secret_name init-mysql MYSQL_PWD)+ root_pw=$(kubectl get secret -n "$NAMESPACE" "$root_secret" \+ -o jsonpath='{.data.mysql-root-password}' | base64 -d)+ kubectl exec -n "$NAMESPACE" "$DB_POD" -- \+ mysql -uroot -p"${root_pw}" -D "${DB_NAME}" -sNe \+ "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='${table}' AND column_name='${column}'" \+ | tr -d '[:space:]'+ else+ local pg_user pg_secret pg_pw+ pg_user=$(kubectl get deploy -n "$NAMESPACE" "$DEPLOY" \+ -o jsonpath='{.spec.template.spec.initContainers[?(@.name=="init-postgresql")].env[?(@.name=="POSTGRES_USER")].value}')+ pg_secret=$(init_secret_name init-postgresql POSTGRES_PASSWORD)+ pg_pw=$(kubectl get secret -n "$NAMESPACE" "$pg_secret" \+ -o jsonpath='{.data.password}' | base64 -d)+ kubectl exec -n "$NAMESPACE" "$DB_POD" -- \+ env PGPASSWORD="${pg_pw}" psql -U "${pg_user}" -d "${DB_NAME}" -tAc \+ "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='${table}' AND column_name='${column}'" \+ | tr -d '[:space:]'+ fi+}++assert_column() {+ local table="$1"+ local column="$2"+ local expected="$3"+ local actual+ actual=$(column_count "$table" "$column")+ if [ "$actual" != "$expected" ]; then+ echo "ERROR: ${table}.${column} count=${actual}, expected ${expected}" >&2+ exit 1+ fi+}++echo "==> Scale Gravitino to zero before reseeding ${FROM_VERSION} ${ENGINE} schema"+kubectl scale deploy -n "$NAMESPACE" "$DEPLOY" --replicas=0+kubectl wait -n "$NAMESPACE" --for=delete pod -l "release=${RELEASE_NAME}" --timeout=180s || true++echo "==> Reset database to schema-${FROM_VERSION}-${ENGINE}.sql"+REMOTE_SQL="/tmp/schema-${FROM_VERSION}-${ENGINE}.sql"+kubectl cp "$SCHEMA_SQL" "${NAMESPACE}/${DB_POD}:${REMOTE_SQL}"+if [ "$ENGINE" = mysql ]; then+ ROOT_SECRET=$(init_secret_name init-mysql MYSQL_PWD)+ ROOT_PW=$(kubectl get secret -n "$NAMESPACE" "$ROOT_SECRET" \+ -o jsonpath='{.data.mysql-root-password}' | base64 -d)+ kubectl exec -n "$NAMESPACE" "$DB_POD" -- \+ mysql -uroot -p"${ROOT_PW}" -e "DROP DATABASE IF EXISTS \`${DB_NAME}\`; CREATE DATABASE \`${DB_NAME}\`;"+ kubectl exec -n "$NAMESPACE" "$DB_POD" -- \+ bash -c "mysql -uroot -p\"${ROOT_PW}\" -D '${DB_NAME}' < '${REMOTE_SQL}'"+else+ PG_USER=$(kubectl get deploy -n "$NAMESPACE" "$DEPLOY" \+ -o jsonpath='{.spec.template.spec.initContainers[?(@.name=="init-postgresql")].env[?(@.name=="POSTGRES_USER")].value}')+ PG_SECRET=$(init_secret_name init-postgresql POSTGRES_PASSWORD)+ PG_PW=$(kubectl get secret -n "$NAMESPACE" "$PG_SECRET" \+ -o jsonpath='{.data.password}' | base64 -d)+ # Drop schema objects so leftover gravitino_schema_migration cannot leak.+ # Prefer DROP SCHEMA over DROP DATABASE: the chart app user may not be a superuser.+ kubectl exec -n "$NAMESPACE" "$DB_POD" -- \+ env PGPASSWORD="${PG_PW}" psql -U "${PG_USER}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 \+ -c "DROP SCHEMA IF EXISTS public CASCADE;" \+ -c "CREATE SCHEMA public AUTHORIZATION \"${PG_USER}\";" \+ -c "GRANT ALL ON SCHEMA public TO \"${PG_USER}\";"+ kubectl exec -n "$NAMESPACE" "$DB_POD" -- \+ env PGPASSWORD="${PG_PW}" psql -U "${PG_USER}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 -f "${REMOTE_SQL}"+fi++case "$FROM_VERSION" in+ 1.2.0)+ assert_column view_meta audit_info 0+ assert_column idp_user_meta enabled 0+ echo "Seeded ${FROM_VERSION}: view_meta.audit_info and idp_user_meta.enabled absent"+ ;;+ 1.3.0)+ assert_column view_meta audit_info 1+ assert_column idp_user_meta enabled 0+ echo "Seeded ${FROM_VERSION}: view_meta.audit_info present, idp_user_meta.enabled absent"+ ;;+esac++# 1.3.0 shares table names with 2.0.0; exercise automatic inference (no baseline)+# so upgrade columns such as idp_user_meta.enabled are still applied.+if [ "$FROM_VERSION" = "1.3.0" ]; then+ echo "==> Helm upgrade without schema.baselineVersion (${ENGINE}, infer from columns)"+ helm upgrade "$RELEASE_NAME" "$CHART_DIR" -n "$NAMESPACE" --wait --timeout 10m \+ --values "$VALUES_FILE" \+ --set image.registry="" \+ --set image.repository="${KIND_REGISTRY}/gravitino" \+ --set image.tag="${tag}" \+ --set-string "podAnnotations.schema-migrate-cross=$(date +%s)"++ bash "$CHECK_SCRIPT" "$NAMESPACE" "$RELEASE_NAME" "$ENGINE"++ JOB=$(kubectl get jobs -n "$NAMESPACE" -l app.kubernetes.io/component=schema-migrate \+ --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1:].metadata.name}')+ LOG="/tmp/${JOB}-cross-infer.log"+ kubectl logs -n "$NAMESPACE" "job/${JOB}" --all-containers=true | tee "$LOG"+ grep -q "inferred 1.3.0 from existing tables" "$LOG"+ grep -q "upgrade-1.3.0-to-2.0.0-${ENGINE}" "$LOG"+ if grep -q "upgrade-1.2.0-to-1.3.0-${ENGINE}" "$LOG"; then+ echo "ERROR: unexpected upgrade-1.2.0-to-1.3.0 when inferred baseline is 1.3.0" >&2+ exit 1+ fi+ assert_column view_meta audit_info 1+ assert_column idp_user_meta enabled 1+else+ echo "==> Helm upgrade with schema.baselineVersion=${FROM_VERSION} (${ENGINE})"+ helm upgrade "$RELEASE_NAME" "$CHART_DIR" -n "$NAMESPACE" --wait --timeout 10m \+ --values "$VALUES_FILE" \+ --set image.registry="" \+ --set image.repository="${KIND_REGISTRY}/gravitino" \+ --set image.tag="${tag}" \+ --set "schema.baselineVersion=${FROM_VERSION}" \+ --set-string "podAnnotations.schema-migrate-cross=$(date +%s)"++ bash "$CHECK_SCRIPT" "$NAMESPACE" "$RELEASE_NAME" "$ENGINE"++ JOB=$(kubectl get jobs -n "$NAMESPACE" -l app.kubernetes.io/component=schema-migrate \+ --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1:].metadata.name}')+ LOG="/tmp/${JOB}-cross.log"+ kubectl logs -n "$NAMESPACE" "job/${JOB}" --all-containers=true | tee "$LOG"+ grep -q "schema.baselineVersion=${FROM_VERSION}" "$LOG"+ grep -q "upgrade-1.2.0-to-1.3.0-${ENGINE}" "$LOG"+ grep -q "upgrade-1.3.0-to-2.0.0-${ENGINE}" "$LOG"+ assert_column view_meta audit_info 1+ assert_column idp_user_meta enabled 1+fi++echo "Cross-version schema migrate (${ENGINE} ${FROM_VERSION} -> image) passed"diff --git a/dev/ci/check-schema-migrate.sh b/dev/ci/check-schema-migrate.shnew file mode 100755index 0000000000..761c18af1a--- /dev/null+++ b/dev/ci/check-schema-migrate.sh@@ -0,0 +1,127 @@+#!/usr/bin/env bash+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++# Assert schema-migrate Job completed and gravitino_schema_migration is ready.+# Usage: check-schema-migrate.sh <namespace> <release> <mysql|postgresql>+set -euo pipefail++NS="${1:?namespace required}"+RELEASE="${2:?release required}"+ENGINE="${3:?engine mysql|postgresql required}"++echo "Checking schema-migrate Jobs in namespace ${NS}..."+kubectl get jobs -n "$NS" -l app.kubernetes.io/component=schema-migrate+kubectl wait -n "$NS" --for=condition=complete \+ job -l app.kubernetes.io/component=schema-migrate --timeout=300s++JOB=$(kubectl get jobs -n "$NS" -l app.kubernetes.io/component=schema-migrate \+ --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1:].metadata.name}')+echo "Latest schema-migrate Job: ${JOB}"++HOOK=$(kubectl get job -n "$NS" "$JOB" -o jsonpath='{.metadata.annotations.helm\.sh/hook}' || true)+if [ -n "${HOOK}" ]; then+ echo "ERROR: Job ${JOB} still has helm.sh/hook=${HOOK}" >&2+ exit 1+fi++kubectl logs -n "$NS" "job/${JOB}" --all-containers=true | tee "/tmp/${JOB}.log"+grep -q "Schema migration completed successfully" "/tmp/${JOB}.log"+VERSION=$(sed -n 's/.*Recorded schema version \([0-9][0-9.]*\).*/\1/p' "/tmp/${JOB}.log" | tail -n1)+if [ -z "$VERSION" ]; then+ echo "ERROR: could not find recorded schema version in Job logs" >&2+ exit 1+fi+echo "Recorded schema version from Job log: ${VERSION}"++DEPLOY=$(kubectl get deploy -n "$NS" -l "release=${RELEASE}" -o jsonpath='{.items[0].metadata.name}')+if [ -z "$DEPLOY" ]; then+ echo "ERROR: no Deployment with release=${RELEASE}" >&2+ exit 1+fi++WAIT_INIT="init-${ENGINE}"+CMD=$(kubectl get deploy -n "$NS" "$DEPLOY" \+ -o jsonpath="{.spec.template.spec.initContainers[?(@.name==\"${WAIT_INIT}\")].command[2]}")+echo "$CMD" | grep -q "Waiting for schema version"+if echo "$CMD" | grep -Eq "upgrade-.*-to-.*-${ENGINE}"; then+ echo "ERROR: ${WAIT_INIT} still applies upgrade SQL" >&2+ exit 1+fi++# Resolve auth Secret from the wait-init container (matches Bitnami fullname+# collapse and mysql.auth.existingSecret / postgresql.auth.existingSecret).+init_secret_name() {+ local init_name="$1"+ local env_name="$2"+ local secret+ secret=$(kubectl get deploy -n "$NS" "$DEPLOY" \+ -o jsonpath="{.spec.template.spec.initContainers[?(@.name==\"${init_name}\")].env[?(@.name==\"${env_name}\")].valueFrom.secretKeyRef.name}")+ if [ -z "$secret" ]; then+ echo "ERROR: could not resolve Secret from ${DEPLOY}/${init_name}/${env_name}" >&2+ return 1+ fi+ printf '%s\n' "$secret"+}++DB_POD=$(kubectl get pods -n "$NS" -l "app.kubernetes.io/name=${ENGINE}" \+ -o jsonpath='{.items[0].metadata.name}')+case "$ENGINE" in+ mysql)+ DB_NAME=$(kubectl get deploy -n "$NS" "$DEPLOY" \+ -o jsonpath='{.spec.template.spec.initContainers[?(@.name=="init-mysql")].env[?(@.name=="GRAVITINO_DB")].value}')+ ROOT_SECRET=$(init_secret_name init-mysql MYSQL_PWD)+ ROOT_PW=$(kubectl get secret -n "$NS" "$ROOT_SECRET" -o jsonpath='{.data.mysql-root-password}' | base64 -d)+ RECORDED=$(kubectl exec -n "$NS" "$DB_POD" -- \+ mysql -uroot -p"${ROOT_PW}" -D "${DB_NAME}" -sNe "SELECT schema_version FROM gravitino_schema_migration WHERE id=1")+ HAS_AUDIT=$(kubectl exec -n "$NS" "$DB_POD" -- \+ mysql -uroot -p"${ROOT_PW}" -D "${DB_NAME}" -sNe "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='view_meta' AND column_name='audit_info'")+ ;;+ postgresql)+ DB_NAME=$(kubectl get deploy -n "$NS" "$DEPLOY" \+ -o jsonpath='{.spec.template.spec.initContainers[?(@.name=="init-postgresql")].env[?(@.name=="GRAVITINO_DB")].value}')+ PGUSER=$(kubectl get deploy -n "$NS" "$DEPLOY" \+ -o jsonpath='{.spec.template.spec.initContainers[?(@.name=="init-postgresql")].env[?(@.name=="POSTGRES_USER")].value}')+ PG_SECRET=$(init_secret_name init-postgresql POSTGRES_PASSWORD)+ PG_PW=$(kubectl get secret -n "$NS" "$PG_SECRET" -o jsonpath='{.data.password}' | base64 -d)+ RECORDED=$(kubectl exec -n "$NS" "$DB_POD" -- \+ env PGPASSWORD="${PG_PW}" psql -U "${PGUSER}" -d "${DB_NAME}" -tAc "SELECT schema_version FROM gravitino_schema_migration WHERE id=1")+ HAS_AUDIT=$(kubectl exec -n "$NS" "$DB_POD" -- \+ env PGPASSWORD="${PG_PW}" psql -U "${PGUSER}" -d "${DB_NAME}" -tAc "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='view_meta' AND column_name='audit_info'")+ ;;+ *)+ echo "ERROR: unsupported engine ${ENGINE}" >&2+ exit 1+ ;;+esac++RECORDED=$(echo "$RECORDED" | tr -d '[:space:]')+HAS_AUDIT=$(echo "$HAS_AUDIT" | tr -d '[:space:]')+echo "DB recorded schema version: ${RECORDED}"+if [ "$RECORDED" != "$VERSION" ]; then+ echo "ERROR: DB schema version ${RECORDED} != Job recorded ${VERSION}" >&2+ exit 1+fi+if [ "$HAS_AUDIT" != "1" ]; then+ echo "ERROR: view_meta.audit_info is missing after migration" >&2+ exit 1+fi++kubectl rollout status -n "$NS" "deploy/${DEPLOY}" --timeout=300s+echo "Schema migrate checks passed for ${ENGINE} in ${NS}"diff --git a/dev/ci/test_schema_migrate.py b/dev/ci/test_schema_migrate.pynew file mode 100755index 0000000000..33e3ccb15f--- /dev/null+++ b/dev/ci/test_schema_migrate.py@@ -0,0 +1,528 @@+#!/usr/bin/env python3+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++"""Regression tests for chart schema-migrate.sh (upgrade chain + fresh install)."""++import argparse+import os+from pathlib import Path+import shutil+import subprocess+import time+import unittest+import uuid+++ROOT = Path(__file__).resolve().parents[1]+SCRIPT = ROOT / "charts/gravitino/resources/scripts/schema-migrate.sh"+SQL_ROOT = ROOT.parent / "scripts"+ENGINE = "mysql"+TARGET = "2.0.0"+++def docker(*args, check=True):+ result = subprocess.run(+ ["docker", *args], text=True, capture_output=True, timeout=180+ )+ if check and result.returncode:+ raise RuntimeError(f"docker {args[0]} failed: {result.stderr or result.stdout}")+ return result+++class TestSchemaMigrate(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ if not SCRIPT.is_file():+ raise unittest.SkipTest(f"missing {SCRIPT}")+ sql_dir = SQL_ROOT / ENGINE+ if not sql_dir.is_dir():+ raise unittest.SkipTest(f"missing {sql_dir}")++ workspace = Path(os.environ.get("GITHUB_WORKSPACE") or ROOT.parent).resolve()+ cls.work = workspace / f".schema-migrate-test-{uuid.uuid4().hex[:12]}"+ cls.work.mkdir(parents=True)+ shutil.copyfile(SCRIPT, cls.work / "schema-migrate.sh")+ shutil.copytree(sql_dir, cls.work / ENGINE)+ cls.container = "schema-migrate-" + uuid.uuid4().hex[:12]+ cls.addClassCleanup(shutil.rmtree, cls.work, True)+ cls.addClassCleanup(docker, "rm", "-f", "-v", cls.container, check=False)++ image = "mysql:8.0" if ENGINE == "mysql" else "postgres:13"+ settings = (+ [+ "-e",+ "MYSQL_ROOT_PASSWORD=runtime-test-password",+ "-e",+ "MYSQL_INITDB_SKIP_TZINFO=1",+ ]+ if ENGINE == "mysql"+ else [+ "-e",+ "POSTGRES_HOST_AUTH_METHOD=trust",+ "-e",+ "POSTGRES_INITDB_ARGS=--no-sync",+ ]+ )+ docker(+ "run",+ "-d",+ "--network",+ "none",+ "--tmpfs",+ (+ "/var/lib/mysql:rw,size=512m"+ if ENGINE == "mysql"+ else "/var/lib/postgresql/data:rw,size=256m"+ ),+ "--name",+ cls.container,+ "-v",+ f"{cls.work}:/test:ro",+ *settings,+ image,+ )+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ if (+ cls.sql(+ "mysql" if ENGINE == "mysql" else "postgres",+ "SELECT 1",+ check=False,+ ).returncode+ == 0+ ):+ return+ time.sleep(1)+ raise RuntimeError(docker("logs", cls.container).stdout)++ @classmethod+ def sql(cls, database, sql, check=True):+ if ENGINE == "postgresql":+ client = [+ "psql",+ "-U",+ "postgres",+ "-d",+ database,+ "-v",+ "ON_ERROR_STOP=1",+ "-Atc",+ sql,+ ]+ else:+ client = ["mysql", "-uroot", "-D", database, "-sNe", sql]+ return docker(+ "exec",+ "-e",+ "MYSQL_PWD=runtime-test-password",+ cls.container,+ *client,+ check=check,+ )++ def setUp(self):+ self.database = "migrate_" + uuid.uuid4().hex[:12]+ self.sql(+ "mysql" if ENGINE == "mysql" else "postgres",+ f"CREATE DATABASE {self.database}",+ )+ self.scripts = self.work / self.database+ self.scripts.mkdir(parents=True)+ # Bind-mounted work is read-only in the container; copy scripts per DB.+ # The migrate helper writes version.txt next to the engine SQL tree.+ shutil.copytree(self.work / ENGINE, self.scripts / ENGINE)++ def write_version(self, target=TARGET):+ (self.scripts / "version.txt").write_text(target + "\n")++ def migrate(self, target=TARGET, baseline="", check=True):+ self.write_version(target)+ env = [+ "-e",+ f"DB_ENGINE={ENGINE}",+ "-e",+ "DB_HOST=127.0.0.1",+ "-e",+ f"GRAVITINO_DB={self.database}",+ "-e",+ f"SCRIPTS_DIR=/test/{self.database}",+ "-e",+ "MYSQL_USER=root",+ "-e",+ "MYSQL_PWD=runtime-test-password",+ "-e",+ "POSTGRES_USER=postgres",+ "-e",+ "POSTGRES_PASSWORD=runtime-test-password",+ "-e",+ f"BASELINE_VERSION={baseline}",+ ]+ # work dir is mounted read-only; copy scripts into a writable path first.+ docker(+ "exec",+ self.container,+ "bash",+ "-c",+ f"rm -rf /tmp/{self.database} && cp -a /test/{self.database} /tmp/{self.database}",+ )+ result = docker(+ "exec",+ *env,+ "-e",+ f"SCRIPTS_DIR=/tmp/{self.database}",+ self.container,+ "bash",+ "/test/schema-migrate.sh",+ check=check,+ )+ return result++ def seed_schema_file(self, version="1.2.0"):+ schema = self.scripts / ENGINE / f"schema-{version}-{ENGINE}.sql"+ self.assertTrue(schema.is_file(), f"missing {schema}")+ docker(+ "exec",+ "-e",+ "MYSQL_PWD=runtime-test-password",+ self.container,+ "bash",+ "-c",+ f"mysql -uroot -D {self.database} < /test/{self.database}/{ENGINE}/schema-{version}-{ENGINE}.sql",+ )++ def assert_version(self, version):+ self.assertEqual(+ self.sql(+ self.database,+ "SELECT schema_version FROM gravitino_schema_migration WHERE id=1",+ ).stdout.strip(),+ version,+ )++ def assert_view_meta_has_audit_info(self):+ scope = "DATABASE()" if ENGINE == "mysql" else "current_schema()"+ self.assertEqual(+ self.sql(+ self.database,+ "SELECT COUNT(*) FROM information_schema.columns "+ f"WHERE table_schema={scope} AND table_name='view_meta' "+ "AND column_name='audit_info'",+ ).stdout.strip(),+ "1",+ )++ def assert_view_meta_missing_audit_info(self):+ scope = "DATABASE()" if ENGINE == "mysql" else "current_schema()"+ self.assertEqual(+ self.sql(+ self.database,+ "SELECT COUNT(*) FROM information_schema.columns "+ f"WHERE table_schema={scope} AND table_name='view_meta' "+ "AND column_name='audit_info'",+ ).stdout.strip(),+ "0",+ )++ def test_fresh_install_records_target_version(self):+ result = self.migrate()+ self.assertIn("Fresh install detected", result.stdout)+ self.assert_version(TARGET)+ self.assert_view_meta_has_audit_info()++ def test_existing_1_2_0_applies_full_upgrade_chain(self):+ self.seed_schema_file("1.2.0")+ self.assert_view_meta_missing_audit_info()+ result = self.migrate(baseline="1.2.0")+ self.assertIn("upgrade-1.2.0-to-1.3.0", result.stdout)+ self.assertIn("upgrade-1.3.0-to-2.0.0", result.stdout)+ self.assertNotIn("tail -n 1", result.stdout)+ self.assert_version(TARGET)+ self.assert_view_meta_has_audit_info()++ def test_tail_n_1_would_skip_intermediate_is_rejected_by_chain(self):+ """If only the last upgrade ran, view_meta.audit_info would stay missing."""+ self.seed_schema_file("1.2.0")+ # Apply only the last upgrade (the old buggy chart behavior).+ docker(+ "exec",+ "-e",+ "MYSQL_PWD=runtime-test-password",+ self.container,+ "bash",+ "-c",+ f"mysql -uroot -D {self.database} < /test/{self.database}/{ENGINE}/upgrade-1.3.0-to-2.0.0-{ENGINE}.sql || true",+ )+ self.assert_view_meta_missing_audit_info()+ result = self.migrate(baseline="1.2.0")+ self.assertIn("upgrade-1.2.0-to-1.3.0", result.stdout)+ self.assert_view_meta_has_audit_info()+ self.assert_version(TARGET)++ def test_infer_1_3_0_keeps_version_capture_clean(self):+ """Ordinary 1.3.0 seed without baseline: infer a clean X.Y.Z and upgrade.++ A real schema-1.3.0.sql fixture lacks newer snapshot tables, so+ infer_schema_version never reaches the ambiguous-column INFO branch.+ That stderr diagnostic is covered by the script redirect itself; this+ case only asserts ordinary inference + a clean recorded version token.+ """+ self.seed_schema_file("1.3.0")+ result = self.migrate(baseline="")+ self.assertIn("inferred 1.3.0 from existing tables", result.stdout)+ self.assertIn("upgrade-1.3.0-to-2.0.0", result.stdout)+ # Inference / logging must not leak diagnostic text into stdout capture.+ self.assertNotIn("INFO: Tables also match schema-", result.stdout)+ self.assertRegex(+ result.stdout,+ r"No recorded schema version; inferred 1\.3\.0 from existing tables\.",+ )+ # Recorded versions during the chain must be clean X.Y.Z tokens only.+ recorded = self.sql(+ self.database,+ "SELECT schema_version FROM gravitino_schema_migration WHERE id=1",+ ).stdout.strip()+ self.assertRegex(recorded, r"^[0-9]+\.[0-9]+\.[0-9]+$")+ self.assert_version(TARGET)+ self.assertEqual(+ self.sql(+ self.database,+ "SELECT COUNT(*) FROM information_schema.columns "+ f"WHERE table_schema=DATABASE() AND table_name='idp_user_meta' "+ "AND column_name='enabled'",+ ).stdout.strip(),+ "1",+ )++ def test_index_only_upgrade_does_not_infer_newer_snapshot(self):+ """Index-only upgrade + same CREATE TABLE set must not claim the newer ver.++ Without ADD COLUMN markers, vacuous marker success would skip the+ upgrade. Seed schema-2.0.0, add a table-identical schema-2.1.0 snapshot+ and upgrade-2.0.0-to-2.1.0 with only CREATE INDEX, then migrate to 2.1.0.+ """+ self.seed_schema_file("2.0.0")+ engine_dir = self.scripts / ENGINE+ shutil.copyfile(+ engine_dir / f"schema-2.0.0-{ENGINE}.sql",+ engine_dir / f"schema-2.1.0-{ENGINE}.sql",+ )+ (engine_dir / f"upgrade-2.0.0-to-2.1.0-{ENGINE}.sql").write_text(+ "-- Index-only fixture for inference regression\n"+ "CREATE INDEX idx_schema_migrate_probe ON metalake_meta (metalake_id);\n"+ )+ result = self.migrate(target="2.1.0", baseline="")+ self.assertIn("inferred 2.0.0 from existing tables", result.stdout)+ self.assertIn("upgrade-2.0.0-to-2.1.0", result.stdout)+ self.assertIn(+ "upgrade ADD COLUMN markers are absent; inferring 2.0.0",+ result.stderr,+ )+ self.assert_version("2.1.0")+ self.assertEqual(+ self.sql(+ self.database,+ "SELECT COUNT(*) FROM information_schema.statistics "+ f"WHERE table_schema=DATABASE() AND table_name='metalake_meta' "+ "AND index_name='idx_schema_migrate_probe'",+ ).stdout.strip(),+ "1",+ )++ def test_rejects_invalid_baseline_version_when_used(self):+ self.seed_schema_file("1.3.0")+ result = self.migrate(baseline="1.2", check=False)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("BASELINE_VERSION must be X.Y.Z", result.stderr)++ def test_ignores_invalid_baseline_when_version_already_recorded(self):+ """Stale/typo baseline must not fail once gravitino_schema_migration exists."""+ self.seed_schema_file("1.3.0")+ result = self.migrate(baseline="1.3.0")+ self.assertIn("upgrade-1.3.0-to-2.0.0", result.stdout)+ self.assert_version(TARGET)+ # Re-run with a non-X.Y.Z baseline that would fail if validated eagerly.+ result = self.migrate(baseline="1.2")+ self.assertEqual(result.returncode, 0)+ self.assertNotIn("using schema.baselineVersion=", result.stdout)+ self.assert_version(TARGET)+++class TestSchemaMigratePostgresCurrentSchema(unittest.TestCase):+ """Fresh target schema must not skip init when public already has metalake_meta."""++ @classmethod+ def setUpClass(cls):+ if not SCRIPT.is_file():+ raise unittest.SkipTest(f"missing {SCRIPT}")+ sql_dir = SQL_ROOT / "postgresql"+ if not sql_dir.is_dir():+ raise unittest.SkipTest(f"missing {sql_dir}")++ workspace = Path(os.environ.get("GITHUB_WORKSPACE") or ROOT.parent).resolve()+ cls.work = workspace / f".schema-migrate-pg-test-{uuid.uuid4().hex[:12]}"+ cls.work.mkdir(parents=True)+ shutil.copyfile(SCRIPT, cls.work / "schema-migrate.sh")+ shutil.copytree(sql_dir, cls.work / "postgresql")+ cls.container = "schema-migrate-pg-" + uuid.uuid4().hex[:12]+ cls.addClassCleanup(shutil.rmtree, cls.work, True)+ cls.addClassCleanup(docker, "rm", "-f", "-v", cls.container, check=False)++ docker(+ "run",+ "-d",+ "--network",+ "none",+ "--tmpfs",+ "/var/lib/postgresql/data:rw,size=256m",+ "--name",+ cls.container,+ "-e",+ "POSTGRES_HOST_AUTH_METHOD=trust",+ "-e",+ "POSTGRES_INITDB_ARGS=--no-sync",+ "-v",+ f"{cls.work}:/test:ro",+ "postgres:13",+ )+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ if (+ docker(+ "exec",+ cls.container,+ "psql",+ "-U",+ "postgres",+ "-d",+ "postgres",+ "-c",+ "SELECT 1",+ check=False,+ ).returncode+ == 0+ ):+ return+ time.sleep(1)+ raise RuntimeError(docker("logs", cls.container).stdout)++ def test_fresh_target_schema_ignores_public_metalake(self):+ db = "migrate_pg_" + uuid.uuid4().hex[:8]+ target = "gravitino_app"+ docker(+ "exec",+ self.container,+ "psql",+ "-U",+ "postgres",+ "-d",+ "postgres",+ "-v",+ "ON_ERROR_STOP=1",+ "-c",+ f"CREATE DATABASE {db}",+ )+ # public already has a catalog; target schema is empty.+ docker(+ "exec",+ self.container,+ "psql",+ "-U",+ "postgres",+ "-d",+ db,+ "-v",+ "ON_ERROR_STOP=1",+ "-c",+ "CREATE TABLE public.metalake_meta (id int); "+ f"CREATE SCHEMA {target};",+ )++ scripts = self.work / db+ scripts.mkdir(parents=True)+ shutil.copytree(self.work / "postgresql", scripts / "postgresql")+ (scripts / "version.txt").write_text(TARGET + "\n")+ docker(+ "exec",+ self.container,+ "bash",+ "-c",+ f"rm -rf /tmp/{db} && cp -a /test/{db} /tmp/{db}",+ )++ result = docker(+ "exec",+ "-e",+ "DB_ENGINE=postgresql",+ "-e",+ "DB_HOST=127.0.0.1",+ "-e",+ f"GRAVITINO_DB={db}",+ "-e",+ f"SCRIPTS_DIR=/tmp/{db}",+ "-e",+ "POSTGRES_USER=postgres",+ "-e",+ "POSTGRES_PASSWORD=runtime-test-password",+ "-e",+ f"PG_CURRENT_SCHEMA={target}",+ "-e",+ f"PGOPTIONS=-c search_path={target}",+ self.container,+ "bash",+ "/test/schema-migrate.sh",+ )+ self.assertIn("Fresh install detected", result.stdout)+ self.assertIn("Schema migration completed successfully", result.stdout)++ # Target schema got the snapshot; public still only has the stub table.+ target_tables = docker(+ "exec",+ self.container,+ "psql",+ "-U",+ "postgres",+ "-d",+ db,+ "-Atc",+ "SELECT COUNT(*) FROM information_schema.tables "+ f"WHERE table_schema='{target}' AND table_name='metalake_meta'",+ ).stdout.strip()+ self.assertEqual(target_tables, "1")+ recorded = docker(+ "exec",+ self.container,+ "psql",+ "-U",+ "postgres",+ "-d",+ db,+ "-Atc",+ f"SET search_path TO {target}; "+ "SELECT schema_version FROM gravitino_schema_migration WHERE id=1",+ ).stdout.strip()+ self.assertEqual(recorded, TARGET)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--engine", choices=("mysql",), default="mysql")+ args, remaining = parser.parse_known_args()+ ENGINE = args.engine+ unittest.main(argv=[__file__, *remaining])diff --git a/docs/chart.md b/docs/chart.mdindex 9a6fca650e..6f39abb203 100644--- a/docs/chart.md+++ b/docs/chart.md@@ -142,6 +142,33 @@ Replace database-1.***.***.rds.amazonaws.com with your actual MySQL host. \Change admin and admin123 to your actual MySQL username and password. \Ensure the target MySQL database (gravitino) exists before deployment._+### Schema migration Job (MySQL / PostgreSQL)++For install and upgrade, you can run entity-store schema SQL once per revision in a+regular Kubernetes Job instead of per-pod init containers (avoids rolling-update+races). Enable it with `schema.migrate.enabled=true`. The Job and its ConfigMap are+created together in the same release; Gravitino Pods wait on+`gravitino_schema_migration` before starting (so bundled databases can come up first).++The migrate script records the current schema version and applies the full+`upgrade-*-to-*-*.sql` chain from that version to the image version. For an+existing database that has no recorded version, set `schema.baselineVersion`+(`X.Y.Z`) to the Gravitino version that created it (or to the image version to+only record and skip DDL). The Job validates that shape only when baseline is+actually used; a stale value is ignored once `gravitino_schema_migration`+already has a row. Automatic inference only treats a snapshot as current when+`upgrade-*-to-<version>` scripts add distinguishable columns; index-only+upgrades that share the same table set require an explicit baseline. The Job+uses the same `nodeSelector` / `affinity` / `tolerations` as the Gravitino+Deployment. The `entity.jdbcUser` (or in-chart DB admin) needs rights to create+and alter entity-store tables and to read `gravitino_schema_migration`.++For external MySQL or PostgreSQL, set `schema.migrate.existingSecret` to a Secret+that holds the `entity.jdbcUser` password. Optional `schema.dbHost`, `schema.dbPort`,+and `schema.dbName` override JDBC URL parsing. For PostgreSQL `currentSchema` and+TLS, use `schema.currentSchema`, `schema.sslMode`, and `schema.ssl.existingSecret`+as needed.+### Deploy Gravitino with GCS as Object StoreIf your catalog uses Google Cloud Storage (GCS) as the object store, you need to set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable in the container and mount the service account key file.