jerryshao commented on code in PR #15001: URL: https://github.com/apache/gravitino/pull/15001#discussion_r4610369080
########## dev/charts/gravitino/resources/scripts/schema-migrate.sh: ########## @@ -0,0 +1,470 @@ +#!/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" +} + +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 + 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 + exists=$(psql_client -d "$GRAVITINO_DB" -tAc \ + "SELECT EXISTS (SELECT FROM information_schema.tables WHERE 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_name = '${tbl}');") + [ "$exists" = "t" ] || return 1 + fi + done < <(extract_table_names "$schema_sql") + [ "$found" = "1" ] +} + +infer_schema_version() { + local best="" f ver + 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 + best="$ver" + fi + done < <(printf '%s\n' "${files[@]}" | sort -V) + printf '%s' "$best" +} + +select_schema_file() { Review Comment: [P1] An existing 1.3.0 MySQL database has all the same table names as the 2.0.0 snapshot. With no migration record and the default empty baseline, this infers 2.0.0 and skips the upgrade that adds user_meta.enabled and group_meta.enabled. Please require an explicit baseline when snapshots are ambiguous, or inspect distinguishing columns before inferring a version. Add a 1.3.0-to-2.0.0 regression without baselineVersion. ########## dev/charts/gravitino/templates/deployment.yaml: ########## @@ -177,7 +227,162 @@ spec: volumeMounts: - mountPath: /scripts name: scripts-emptydir - {{- end }} + {{- else if and .Values.postgresql.enabled (eq (include "gravitino.schemaWaitEnabled" . | trim) "true") }} + - 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 {{ .Release.Name }}-postgresql -U "$POSTGRES_USER" -c "SELECT 1" >/dev/null 2>&1; then + current=$(PGPASSWORD="$POSTGRES_PASSWORD" psql -h {{ .Release.Name }}-postgresql -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: {{ .Release.Name }}-postgresql + key: password + 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 }} + {{- $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" -c "SELECT 1" >/dev/null 2>&1; then Review Comment: [P1] For an external user gravitino_app with database gravitino, the initial psql probe defaults to database gravitino_app and can fail forever even after migration succeeds. With currentSchema configured, the subsequent query also searches the default schema because this container lacks the Job's PGOPTIONS. Please pass -d "$GRAVITINO_DB" to the probe and propagate the same search path as the migration Job. Apply the database fix to the bundled PostgreSQL wait probe too, and cover these connection settings in tests. ########## dev/ci/check-schema-migrate.sh: ########## @@ -0,0 +1,110 @@ +#!/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" Review Comment: [P2] A successful fresh migration exits immediately after writing its version, so its logs never contain the message required here. This grep therefore fails every fresh-install lifecycle check and prevents the cross-version scenarios from reaching their upgrade phase. Emit a shared success message on both paths, or assert completion and the recorded version without requiring this branch-specific message. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
