Repository navigation
Expand file tree
/
Copy pathrun-snapshot-import.sh
More file actions
executable file
·306 lines (272 loc) · 11.5 KB
/
Copy pathrun-snapshot-import.sh
File metadata and controls
executable file
·306 lines (272 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/bin/bash
# ==============================================================================
# HBase Snapshot Import Helper Script
# ==============================================================================
# This script runs a range of Dataflow snapshot import jobs sequentially or in parallel.
# Can be run from any directory, e.g., 'bin/run-snapshot-import.sh'.
#
# For detailed usage and advanced options, see: SNAPSHOT_IMPORT_USAGE.md
# ==============================================================================
# ------------------------------------------------------------------------------
# Environment Variables
# ------------------------------------------------------------------------------
# Most users will need to set these variables before running the script.
# See SNAPSHOT_IMPORT_USAGE.md for details and expected values.
# --- Required / Common Configurations ---
# export PROJECT_ID="your-project-id"
# export INSTANCE_ID="your-instance-id"
# export BUCKET="your-gcs-bucket"
# export REGION="us-central1"
#
# export TABLE_NAME="your-table-name"
# export SNAPSHOT_NAME="your-snapshot-name"
# export SNAPSHOT_SOURCE_DIR="gs://your-gcs-bucket/snapshots"
# export SERVICE_ACCOUNT="your-service-account"
# --- Sharding & Tuning ---
# A 'shard' is a partition of HBase regions. Sharding allows splitting the import into
# multiple independent Dataflow jobs running in parallel to speed up the migration.
# export NUM_SHARDS="20"
# export MAX_INFLIGHT_RPCS="100"
# export BULK_MUTATION_CLOSE_TIMEOUT_MINUTES="30"
# --- Network Configurations ---
# export NETWORK="your-network"
# export SUBNETWORK="your-subnetwork"
# ------------------------------------------------------------------------------
# Usage
# ------------------------------------------------------------------------------
# Usage: bin/run-snapshot-import.sh <start_shard> <end_shard>
# (Both start and end shard indices are inclusive)
# Or: bin/run-snapshot-import.sh --all
# (Runs all shards evenly distributed across 4 parallel runner streams)
#
# Examples:
# bin/run-snapshot-import.sh 0 3
# bin/run-snapshot-import.sh --all
# Validate and parse arguments
if [ "$1" != "--all" ] && [ "$1" != "--restore-only" ]; then
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Usage: $0 <start_shard> <end_shard> [additional_args...]"
echo " (Both start and end shard indices are inclusive)"
echo " Or: $0 --all [additional_args...]"
echo " Or: $0 --restore-only [additional_args...]"
exit 1
fi
if ! [[ "$1" =~ ^[0-9]+$ ]] || ! [[ "$2" =~ ^[0-9]+$ ]]; then
echo "❌ Error: Shard indices must be non-negative integers."
exit 1
fi
if [ "$1" -gt "$2" ]; then
echo "❌ Error: start_shard ($1) cannot be greater than end_shard ($2)."
exit 1
fi
START_SHARD=$1
END_SHARD=$2
EXTRA_ARGS=("${@:3}")
else
EXTRA_ARGS=("${@:2}")
fi
# Validate and export required environment variables
REQUIRED_VARS=(PROJECT_ID INSTANCE_ID BUCKET REGION TABLE_NAME SNAPSHOT_NAME SNAPSHOT_SOURCE_DIR)
for var in "${REQUIRED_VARS[@]}"; do
if [ -z "${!var}" ]; then
echo "❌ Error: Environment variable $var is not set."
exit 1
fi
export "${var}"
done
if [ "$1" != "--restore-only" ]; then
if [ -z "${NUM_SHARDS}" ]; then
echo "❌ Error: Environment variable NUM_SHARDS is not set."
exit 1
fi
if ! [[ "${NUM_SHARDS}" =~ ^[0-9]+$ ]] || [ "${NUM_SHARDS}" -le 0 ]; then
echo "❌ Error: NUM_SHARDS must be a positive integer."
exit 1
fi
export NUM_SHARDS
if [ "$1" != "--all" ]; then
if [ "${START_SHARD}" -ge "${NUM_SHARDS}" ] || [ "${END_SHARD}" -ge "${NUM_SHARDS}" ]; then
echo "❌ Error: Shard indices (${START_SHARD}, ${END_SHARD}) must be less than NUM_SHARDS (${NUM_SHARDS})."
exit 1
fi
fi
fi
# Strip leading gs:// and trailing slashes from BUCKET for robust GCS path construction
BUCKET="${BUCKET#gs://}"
BUCKET="${BUCKET%/}"
# Set default values for optional tuning parameters
MAX_INFLIGHT_RPCS="${MAX_INFLIGHT_RPCS:-100}"
BULK_MUTATION_CLOSE_TIMEOUT_MINUTES="${BULK_MUTATION_CLOSE_TIMEOUT_MINUTES:-30}"
# Configurable Dataflow execution parameters
WORKER_MACHINE_TYPE="${WORKER_MACHINE_TYPE:-n1-highmem-4}"
DISK_SIZE_GB="${DISK_SIZE_GB:-500}"
MAX_NUM_WORKERS="${MAX_NUM_WORKERS:-10}"
USE_PUBLIC_IPS="${USE_PUBLIC_IPS:-false}"
# Deprecated: Snappy compressed snapshots are read natively, this variable is ignored.
if [ -n "${ENABLE_SNAPPY:-}" ]; then
echo "⚠️ Warning: ENABLE_SNAPPY is deprecated and ignored. Snappy compressed snapshots are supported natively."
fi
# Generate a safe, unique job name prefix to prevent collisions
SAFE_TABLE_NAME=$(echo "${TABLE_NAME}" | tr '[:upper:]' '[:lower:]' | tr '_' '-' | tr -cd '[:alnum:]-')
JOB_NAME_PREFIX="${JOB_NAME_PREFIX:-import-${SAFE_TABLE_NAME}}"
# Configurations
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
# Detect the newest shaded JAR dynamically in the target directory
JAR_PATH=""
for jar in "${SCRIPT_DIR}"/../target/bigtable-beam-import-*-shaded.jar; do
if [ -f "$jar" ]; then
if [ -z "${JAR_PATH}" ] || [ "$jar" -nt "${JAR_PATH}" ]; then
JAR_PATH="$jar"
fi
fi
done
if [ -z "${JAR_PATH}" ]; then
echo "❌ Error: Shaded JAR not found in ${SCRIPT_DIR}/../target/"
echo " Please compile and package the project first by running:"
echo " mvn clean package -DskipTests"
exit 1
fi
RESTORE_DIR="gs://${BUCKET}/restore-${SNAPSHOT_NAME}"
# If running the launcher on a newer, unsupported JDK version (e.g. JDK 25+),
# you can set JVM_OPTS to "-Dnet.bytebuddy.experimental=true" to bypass
# ByteBuddy class generation crashes during pipeline construction.
JVM_OPTS="${JVM_OPTS:-}"
# Construct optional network arguments
NETWORK_ARGS=()
if [ -n "${NETWORK}" ]; then
NETWORK_ARGS+=("--network=${NETWORK}")
fi
if [ -n "${SUBNETWORK}" ]; then
NETWORK_ARGS+=("--subnetwork=${SUBNETWORK}")
fi
# Construct optional service account arguments
SERVICE_ACCOUNT_ARGS=()
if [ -n "${SERVICE_ACCOUNT}" ]; then
SERVICE_ACCOUNT_ARGS+=("--serviceAccount=${SERVICE_ACCOUNT}")
fi
# --- RESTORE ONLY MODE ---
if [ "$1" == "--restore-only" ]; then
echo "🚀 Performing snapshot restore (blocking)..."
# shellcheck disable=SC2086
if ! java ${JVM_OPTS} -jar "${JAR_PATH}" importsnapshot \
--runner=DataflowRunner \
--project="${PROJECT_ID}" \
--bigtableInstanceId="${INSTANCE_ID}" \
--bigtableTableId="${TABLE_NAME}" \
--hbaseSnapshotSourceDir="${SNAPSHOT_SOURCE_DIR}" \
--snapshots="${SNAPSHOT_NAME}:${TABLE_NAME}" \
--stagingLocation="gs://${BUCKET}/dataflow/staging" \
--tempLocation="gs://${BUCKET}/dataflow/temp" \
--region="${REGION}" \
--performOnlyRestoreStep=true \
--restorePath="${RESTORE_DIR}" \
--jobName="${JOB_NAME_PREFIX}-restore" \
"${SERVICE_ACCOUNT_ARGS[@]}" \
"${NETWORK_ARGS[@]}" \
"${EXTRA_ARGS[@]}"; then
echo "❌ Error: Snapshot restore failed."
exit 1
fi
echo "✅ Restore completed."
echo "⚠️ IMPORTANT: Please manually cleanup the restore path once validation succeeds:"
echo " gcloud storage rm --recursive \"${RESTORE_DIR}\""
exit 0
fi
# --- AUTO-PARALLEL MODE ---
if [ "$1" == "--all" ]; then
echo "🚀 Starting fully automated snapshot import..."
# Step 1: Perform ONLY the restore step
echo "Step 1/2: Performing snapshot restore (blocking)..."
# shellcheck disable=SC2086
if ! java ${JVM_OPTS} -jar "${JAR_PATH}" importsnapshot \
--runner=DataflowRunner \
--project="${PROJECT_ID}" \
--bigtableInstanceId="${INSTANCE_ID}" \
--bigtableTableId="${TABLE_NAME}" \
--hbaseSnapshotSourceDir="${SNAPSHOT_SOURCE_DIR}" \
--snapshots="${SNAPSHOT_NAME}:${TABLE_NAME}" \
--stagingLocation="gs://${BUCKET}/dataflow/staging" \
--tempLocation="gs://${BUCKET}/dataflow/temp" \
--region="${REGION}" \
--performOnlyRestoreStep=true \
--restorePath="${RESTORE_DIR}" \
--jobName="${JOB_NAME_PREFIX}-restore" \
"${SERVICE_ACCOUNT_ARGS[@]}" \
"${NETWORK_ARGS[@]}" \
"${EXTRA_ARGS[@]}"; then
echo "❌ Error: Snapshot restore failed. Aborting import."
exit 1
fi
echo "Restore completed. Proceeding to data import."
# Step 2: Launch 4 parallel runner streams
echo "Step 2/2: Launching 4 parallel runner streams..."
MAX_CONCURRENCY=4
SHARDS_PER_RUNNER=$(( (NUM_SHARDS + MAX_CONCURRENCY - 1) / MAX_CONCURRENCY ))
pids=()
trap 'echo "⚠️ Interrupted. Stopping local launcher script..."; echo "⚠️ NOTE: Already-submitted Dataflow jobs are NOT cancelled! You must stop them manually (e.g., via Cloud Console or gcloud dataflow jobs cancel)."; [ ${#pids[@]} -gt 0 ] && kill "${pids[@]}" 2>/dev/null; exit 1' INT TERM
for (( runner=0; runner<MAX_CONCURRENCY; runner++ )); do
start=$(( runner * SHARDS_PER_RUNNER ))
end=$(( start + SHARDS_PER_RUNNER - 1 ))
[ $start -ge $NUM_SHARDS ] && break
[ $end -ge $NUM_SHARDS ] && end=$((NUM_SHARDS - 1))
echo "Launching runner $runner: shards $start to $end in background"
# Call ourselves with the range and propagate any extra arguments!
bash "${SCRIPT_DIR}/$(basename "${BASH_SOURCE[0]}")" "$start" "$end" "${EXTRA_ARGS[@]}" &
pids+=($!)
done
echo "All groups launched. Waiting for all background jobs to finish..."
failed=0
for pid in "${pids[@]}"; do
if ! wait "$pid"; then
failed=1
fi
done
if [ $failed -ne 0 ]; then
echo "❌ Error: One or more background import jobs failed."
exit 1
fi
echo "🎉 All import jobs completed!"
echo "⚠️ IMPORTANT: Please manually cleanup the restore path once validation succeeds:"
echo " gcloud storage rm --recursive \"${RESTORE_DIR}\""
exit 0
fi
# ----------------------------------------
# Standard Range Mode
for (( i=START_SHARD; i<=END_SHARD; i++ )); do
echo "Submitting Dataflow job for shardIndex: $i"
# As per the sharding contract, ALL parallel sharded jobs MUST skip the restore step
# to prevent concurrent shards from deleting the restore path.
# The --all mode runs performOnlyRestoreStep=true automatically in Step 1.
SKIP_RESTORE="true"
JOB="${JOB_NAME_PREFIX}-${i}"
# shellcheck disable=SC2086
if ! java ${JVM_OPTS} -jar "${JAR_PATH}" importsnapshot \
--runner=DataflowRunner \
--project="${PROJECT_ID}" \
--bigtableInstanceId="${INSTANCE_ID}" \
--bigtableTableId="${TABLE_NAME}" \
--hbaseSnapshotSourceDir="${SNAPSHOT_SOURCE_DIR}" \
--snapshots="${SNAPSHOT_NAME}:${TABLE_NAME}" \
--stagingLocation="gs://${BUCKET}/dataflow/staging" \
--tempLocation="gs://${BUCKET}/dataflow/temp" \
--workerMachineType="${WORKER_MACHINE_TYPE}" \
--diskSizeGb="${DISK_SIZE_GB}" \
--maxNumWorkers="${MAX_NUM_WORKERS}" \
--region="${REGION}" \
"${SERVICE_ACCOUNT_ARGS[@]}" \
--usePublicIps="${USE_PUBLIC_IPS}" \
--skipRestoreStep="${SKIP_RESTORE}" \
--deleteRestoredSnapshots=false \
--restorePath="${RESTORE_DIR}" \
--numShards="${NUM_SHARDS}" \
--shardIndex="${i}" \
--jobName="${JOB}" \
"${NETWORK_ARGS[@]}" \
--maxInflightRpcs="${MAX_INFLIGHT_RPCS}" \
--bulkMutationCloseTimeoutMinutes="${BULK_MUTATION_CLOSE_TIMEOUT_MINUTES}" \
"${EXTRA_ARGS[@]}"; then
echo "❌ Error: Dataflow job submission failed for shardIndex: ${i}"
exit 1
fi
# Sequential within this script instance
done