程式碼研究室簡介
1. 簡介
Bigtable 是全代管的高效能 NoSQL 資料庫服務,專門處理龐大分析和作業工作負載。從 Apache Cassandra 等現有資料庫遷移至 Bigtable 時,通常需要仔細規劃,以便將停機時間和應用程式影響降到最低。
本程式碼研究室將示範從 Cassandra 遷移至 Bigtable 的遷移策略,並結合使用以下代理工具:
- Cassandra-Bigtable Proxy:允許 Cassandra 用戶端和工具 (例如
cqlsh
或驅動程式) 透過翻譯查詢,使用 Cassandra Query Language (CQL) 通訊協定與 Bigtable 互動。 - Datastax 零停機遷移 (ZDM) Proxy:開放原始碼 Proxy,位於應用程式和資料庫服務 (原始 Cassandra 和目標 Bigtable,透過 Cassandra-Bigtable Proxy) 之間。這項服務會自動調度雙寫作業並管理流量路由,讓您在應用程式變更和停機時間降到最低的情況下進行遷移。
- Cassandra 資料遷移工具 (CDM):開放原始碼工具,用於將歷史資料大量遷移自來源 Cassandra 叢集至目標 Bigtable 執行個體。
課程內容
- 如何在 Compute Engine 上設定基本 Cassandra 叢集。
- 如何建立 Bigtable 執行個體。
- 如何部署及設定 Cassandra-Bigtable Proxy,將 Cassandra 結構定義對應至 Bigtable。
- 如何部署及設定 Datastax ZDM Proxy,以便進行雙寫。
- 如何使用 Cassandra Data Migrator 工具大量遷移現有資料。
- 以 Proxy 為基礎的 Cassandra 到 Bigtable 遷移作業的整體工作流程。
軟硬體需求
- 已啟用計費功能的 Google Cloud 專案。新使用者可申請免費試用。
- 對 Google Cloud 的概念有基本瞭解,例如專案、Compute Engine、虛擬私人雲端網路和防火牆規則。熟悉 Linux 指令列工具。
- 使用已安裝及設定
gcloud
CLI 的機器,或使用 Google Cloud Shell。
在本程式碼研究室中,我們主要會使用同一個虛擬私有雲網路和區域中的 Compute Engine 虛擬機器 (VM),以簡化網路。建議使用內部 IP 位址。
2. 設定環境
1. 選取或建立 Google Cloud 專案
前往 Google Cloud 控制台,選取現有專案或建立新專案。記下專案 ID。
2. 啟用必要的 API
確認已為專案啟用 Compute Engine API 和 Bigtable API。
gcloud services enable compute.googleapis.com bigtable.googleapis.com bigtableadmin.googleapis.com --project=<your-project-id>
請將 替換為實際的專案 ID。
3. 選擇區域和可用區
為資源選取區域和可用區。我們將以 us-central1 和 us-central1-c 做為範例。為了方便起見,請將這些變數定義為環境變數:
export PROJECT_ID="<your-project-id>" export REGION="us-central1" export ZONE="us-central1-c" gcloud config set project $PROJECT_ID gcloud config set compute/region $REGION gcloud config set compute/zone $ZONE
4. 設定防火牆規則
我們需要允許在預設虛擬私有雲網路中,透過多個通訊埠進行 VM 間的通訊:
- Cassandra/Proxies CQL 連接埠:9042
- ZDM Proxy 健康狀態檢查通訊埠:14001
- SSH:22
建立防火牆規則,允許這些通訊埠上的內部流量。我們會使用標記 cassandra-migration
,輕鬆將這項規則套用至相關的 VM。
gcloud compute firewall-rules create allow-migration-internal \ --network=default \ --action=ALLOW \ --rules=tcp:22,tcp:9042,tcp:14001 \ --source-ranges=10.128.0.0/9 # Adjust if using a custom VPC/IP range \ --target-tags=cassandra-migration
3. 部署 Cassandra 叢集 (Origin)
在本程式碼研究室中,我們會在 Compute Engine 上設定簡單的單節點 Cassandra 叢集。在實際使用情況中,您會連線至現有的叢集。
1. 為 Cassandra 建立 GCE VM
gcloud compute instances create cassandra-origin \ --machine-type=e2-medium \ --image-family=ubuntu-2004-lts \ --image-project=ubuntu-os-cloud \ --tags=cassandra-migration \ --boot-disk-size=20GB
2. 安裝 Cassandra
# Install Java (Cassandra dependency) sudo apt-get update sudo apt-get install -y openjdk-11-jre-headless # Add Cassandra repository echo "deb [https://debian.cassandra.apache.org](https://debian.cassandra.apache.org) 41x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list curl [https://downloads.apache.org/cassandra/KEYS](https://downloads.apache.org/cassandra/KEYS) | sudo apt-key add - # Install Cassandra sudo apt-get update sudo apt-get install -y cassandra
3. 建立鍵值空間和資料表
我們將使用員工表格範例,並建立名為「zdmbigtable」的鍵空間。
cd ~/apache-cassandra bin/cqlsh <your-localhost-ip? 9042 #starts the cql shell
在 cqlsh 中:
-- Create keyspace (adjust replication for production) CREATE KEYSPACE zdmbigtable WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}; -- Use the keyspace USE zdmbigtable; -- Create the employee table CREATE TABLE employee ( name text PRIMARY KEY, age bigint, code int, credited double, balance float, is_active boolean, birth_date timestamp ); -- Exit cqlsh EXIT;
請保留 SSH 工作階段,或記下這個 VM 的 IP 位址 (hostname -I)。
4. 設定 Bigtable (目標)
時間長度 0:01
建立 Bigtable 執行個體。我們會使用 zdmbigtable 做為執行個體 ID。
gcloud bigtable instances create zdmbigtable \ --display-name="ZDM Bigtable Target" \ --cluster=bigtable-c1 \ --cluster-zone=$ZONE \ --cluster-num-nodes=1 # Use 1 node for dev/testing; scale as needed
Bigtable 資料表本身會在稍後由 Cassandra-Bigtable Proxy 設定指令碼建立。
5. 設定 Cassandra-Bigtable Proxy
1. 為 Cassandra-Bigtable Proxy 建立 Compute Engine VM
gcloud compute instances create bigtable-proxy-vm \ --machine-type=e2-medium \ --image-family=ubuntu-2004-lts \ --image-project=ubuntu-os-cloud \ --tags=cassandra-migration \ --boot-disk-size=20GB
使用 SSH 連線至 bigtable-proxy-vm:
gcloud compute ssh bigtable-proxy-vm
在 VM 中:
# Install Git and Go sudo apt-get update sudo apt-get install -y git golang-go # Clone the proxy repository # Replace with the actual repository URL if different git clone https://github.com/GoogleCloudPlatform/cloud-bigtable-ecosystem.git cd cassandra-to-bigtable-proxy/ # Set Go environment variables export GOPATH=$HOME/go export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
2. 設定 Proxy
nano config.yaml
更新下列變數。如需更進階的設定,請使用 GitHub 提供的這個範例。
#!/bin/bash
cassandraToBigtableConfigs:
# Global default GCP Project ID
projectId: <your-project-id>
listeners:
- name: cluster1
port: 9042
bigtable:
#If you want to use multiple instances then pass the instance names by comma seperated
#Instance name should not contain any special characters except underscore(_)
instanceIds: zdmbigtable
# Number of grpc channels to be used for Bigtable session.
Session:
grpcChannels: 4
otel:
# Set enabled to true or false for OTEL metrics/traces/logs.
enabled: False
# Name of the collector service to be setup as a sidecar
serviceName: cassandra-to-bigtable-otel-service
healthcheck:
# Enable the health check in this proxy application config only if the
# "health_check" extension is added to the OTEL collector service configuration.
#
# Recommendation:
# Enable the OTEL health check if you need to verify the collector's availability
# at the start of the application. For development or testing environments, it can
# be safely disabled to reduce complexity.
# Enable/Disable Health Check for OTEL, Default 'False'.
enabled: False
# Health check endpoint for the OTEL collector service
endpoint: localhost:13133
metrics:
# Collector service endpoint
endpoint: localhost:4317
traces:
# Collector service endpoint
endpoint: localhost:4317
#Sampling ratio should be between 0 and 1. Here 0.05 means 5/100 Sampling ratio.
samplingRatio: 1
loggerConfig:
# Specifies the type of output, here it is set to 'file' indicating logs will be written to a file.
# Value of `outputType` should be `file` for file type or `stdout` for standard output.
# Default value is `stdout`.
outputType: stdout
# Set this only if the outputType is set to `file`.
# The path and name of the log file where logs will be stored. For example, output.log, Required Key.
# Default `/var/log/cassandra-to-spanner-proxy/output.log`.
fileName: output/output.log
# Set this only if the outputType is set to `file`.
# The maximum size of the log file in megabytes before it is rotated. For example, 500 for 500 MB.
maxSize: 10
# Set this only if the outputType is set to `file`.
# The maximum number of backup log files to keep. Once this limit is reached, the oldest log file will be deleted.
maxBackups: 2
# Set this only if the outputType is set to `file`.
# The maximum age in days for a log file to be retained. Logs older than this will be deleted. Required Key.
# Default 3 days
maxAge: 1
# Set this only if the outputType is set to `file`.
# Default value is set to 'False'. Change the value to 'True', if log files are required to be compressed.
compress: True
儲存並關閉檔案 (在 nano 中依序按下 Ctrl+X、Y 和 Enter 鍵)。
3. 啟動 Cassandra-Bigtable Proxy
啟動 Proxy 伺服器。
# At the root of the cassandra-to-bigtable-proxy directory go run proxy.go
Proxy 會啟動並監聽通訊埠 9042 的傳入 CQL 連線。請讓這個終端機工作階段持續執行。記下這個 VM 的 IP 位址 (主機名稱 -I)
4. 透過 CQL 建立資料表
將 cqlsh
連線至 Cassandra-Bigtable Proxy VM 的 IP 位址。
在 cqlsh
中執行下列指令
-- Create the employee table CREATE TABLE zdmbigtable.employee ( name text PRIMARY KEY, age bigint, code int, credited double, balance float, is_active boolean, birth_date timestamp );
在 Google Cloud 控制台中確認員工資料表和中繼資料表是否存在於 Bigtable 執行個體中。
6. 設定 ZDM Proxy
ZDM Proxy 至少需要兩部機器:一或多個負責處理流量的 Proxy 節點,以及用於透過 Ansible 部署和調度的「Jumphost」。
1. 為 ZDM Proxy 建立 Compute Engine VM
我們需要兩個 VM:zdm-proxy-jumphost 和 zdm-proxy-node-1
# Jumphost VM gcloud compute instances create zdm-jumphost \ --machine-type=e2-medium \ --image-family=ubuntu-2004-lts \ --image-project=ubuntu-os-cloud \ --tags=cassandra-migration \ --boot-disk-size=20GB # Proxy Node VM gcloud compute instances create zdm-proxy-node-1 \ --machine-type=e2-standard-8 \ --image-family=ubuntu-2004-lts \ --image-project=ubuntu-os-cloud \ --tags=cassandra-migration \ --boot-disk-size=20GB
記下這兩個 VM 的 IP 位址。
2. 準備跳躍主機
透過 SSH 連線至 zdm-jumphost
gcloud compute ssh zdm-jumphost
# Install Git and Ansible
sudo apt-get update
sudo apt-get install -y git ansible
跳躍主機內部
git clone https:\/\/github.com/datastax/zdm-proxy-automation.git
cd zdm-proxy-automation/ansible/
編輯主設定檔 vars/zdm_proxy_cluster_config.yml:
請分別使用 Cassandra VM 和 Cassandra-Bigtable Proxy VM 的內部 IP 位址,更新 origin_contact_points 和 target_contact_points。我們並未設定驗證方法,因此請將其註解掉。
##############################
#### ORIGIN CONFIGURATION ####
##############################
## Origin credentials (leave commented if no auth)
# origin_username: ...
# origin_password: ...
## Set the following two parameters only if Origin is a self-managed, non-Astra cluster
origin_contact_points: <Your-Cassandra-VM-Internal-IP> # Replace!
origin_port: 9042
##############################
#### TARGET CONFIGURATION ####
##############################
## Target credentials (leave commented if no auth)
# target_username: ...
# target_password: ...
## Set the following two parameters only if Target is a self-managed, non-Astra cluster
target_contact_points: <Your-Bigtable-Proxy-VM-Internal-IP> # Replace!
target_port: 9042
# --- Other ZDM Proxy settings can be configured below ---
# ... (keep defaults for this codelab)
儲存並關閉這個檔案。
3. 使用 Ansible 部署 ZDM Proxy
在 jumphost 的 ansible 目錄中執行 Ansible Playbook:
ansible-playbook deploy_zdm_proxy.yml -i zdm_ansible_inventory
這個指令會在 Proxy 節點 (zdm-proxy-node-1) 上安裝必要軟體 (例如 Docker)、提取 ZDM Proxy Docker 映像檔,並使用您提供的設定啟動 Proxy 容器。
4. 驗證 ZDM Proxy 健康狀態
從 jumphost 檢查在 zdm-proxy-node-1 (port 14001) 上執行的 ZDM proxy 就緒端點:
# Replace <zdm-proxy-node-1-internal-ip> with the actual internal IP.
curl -G http://<zdm-proxy-node-1-internal-ip>:14001/health/readiness
您應該會看到類似以下的輸出內容,表示來源 (Cassandra) 和目標 (Cassandra-Bigtable Proxy) 都正常運作:
{
"OriginStatus": {
"Addr": "<Your-Cassandra-VM-Internal-IP>:9042",
"CurrentFailureCount": 0,
"FailureCountThreshold": 1,
"Status": "UP"
},
"TargetStatus": {
"Addr": "<Your-Bigtable-Proxy-VM-Internal-IP>:9042",
"CurrentFailureCount": 0,
"FailureCountThreshold": 1,
"Status": "UP"
},
"Status": "UP"
}
7. 設定應用程式並開始雙寫
時間長度 0:05
在實際遷移作業的這個階段,您需要重新設定應用程式,讓其指向 ZDM Proxy 節點的 IP 位址 (例如:9042),而非直接連線至 Cassandra。
應用程式連線至 ZDM Proxy 後,讀取作業預設會從來源 (Cassandra) 提供。寫入作業會同時傳送至來源 (Cassandra) 和目標 (Bigtable,透過 Cassandra-Bigtable Proxy)。這樣一來,應用程式就能繼續正常運作,同時確保新資料同時寫入兩個資料庫。您可以使用 cqlsh 測試連線,並從網路中的 jumphost 或其他 VM 指向 ZDM Proxy:
Cqlsh <zdm-proxy-node-1-ip-address> 9042
請嘗試插入一些資料:
INSERT INTO zdmbigtable.employee (name, age, is_active) VALUES ('Alice', 30, true); SELECT * FROM employee WHERE name = 'Alice';
這項資料應同時寫入 Cassandra 和 Bigtable。如要確認這項資訊,請前往 Google Cloud 控制台,然後開啟 Bigtable 執行個體的 Bigtable 查詢編輯器。執行「SELECT * FROM employee」查詢,您應該會看到最近插入的資料。
8. 使用 Cassandra Data Migrator 遷移歷來資料
新資料已啟用雙寫功能,請使用 Cassandra 資料遷移工具 (CDM) 將現有的歷來資料從 Cassandra 複製到 Bigtable。
1. 為 CDM 建立 Compute Engine VM
這個 VM 需要足夠的記憶體來執行 Spark。
gcloud compute instances create cdm-migrator-vm \ --machine-type=e2-medium \ --image-family=ubuntu-2004-lts \ --image-project=ubuntu-os-cloud \ --tags=cassandra-migration \ --boot-disk-size=40GB
2. 安裝必要條件 (Java 11、Spark)
透過 SSH 連線至 cdm-migrator-vm:
gcloud compute ssh cdm-migrator-vm
在 VM 中:
# Install Java 11
sudo apt-get update
sudo apt-get install -y openjdk-11-jdk
# Verify Java installation
java -version
# Download and Extract Spark (Using version 3.5.3 as requested)
# Check the Apache Spark archives for the correct URL if needed
wget [https://archive.apache.org/dist/spark/spark-3.5.3/spark-3.5.3-bin-hadoop3-scala2.13.tgz](https://archive.apache.org/dist/spark/spark-3.5.3/spark-3.5.3-bin-hadoop3-scala2.13.tgz) tar -xvzf spark-3.5.3-bin-hadoop3-scala2.13.tgz
export SPARK_HOME=$PWD/spark-3.5.3-bin-hadoop3-scala2.13
export PATH=$PATH:$SPARK_HOME/bin
3. 下載 Cassandra 資料遷移工具
下載 CDM 工具 JAR 檔案。請查看 Cassandra Data Migrator GitHub 版本頁面,找出所需版本的正確網址。
# Example using version 5.2.2 - replace URL if needed
wget https://github.com/datastax/cassandra-data-migrator/releases/download/v5.2.2/cassandra-data-migrator-5.2.2.jar)
4. 設定 CDM
建立名為 cdm.properties 的屬性檔案
Nano cdm.properties
請貼上下列設定,並替換 IP 位址,並停用 TTL/Writetime 功能,因為 Bigtable 不直接支援這類功能。將驗證註解保留。
# Origin Cassandra Connection
spark.cdm.connect.origin.host <Your-Cassandra-VM-IP-Address> # Replace!
spark.cdm.connect.origin.port 9042
spark.cdm.connect.origin.username cassandra # Leave default, or set if auth is enabled #
spark.cdm.connect.origin.password cassandra # Leave default, or set if auth is enabled #
# Target Bigtable (via Cassandra-Bigtable Proxy)
Connection spark.cdm.connect.target.host <Your-Bigtable-Proxy-VM-IP-Address> # Replace!
spark.cdm.connect.target.port 9042
spark.cdm.connect.target.username cassandra # Leave default, or set if auth is enabled #
spark.cdm.connect.target.password cassandra # Leave default, or set if auth is enabled #
# Disable TTL/Writetime features (Important for Bigtable compatibility via Proxy)
spark.cdm.feature.origin.ttl.automatic false
spark.cdm.feature.origin.writetime.automatic false
spark.cdm.feature.target.ttl.automatic false
spark.cdm.feature.target.writetime.automatic false
儲存並關閉檔案。
5. 執行遷移工作
使用 spark-submit 執行遷移作業。這個指令會指示 Spark 使用屬性檔案執行 CDM jar,並指定要遷移的鍵空間和資料表。根據虛擬機器大小和資料量調整記憶體設定 (–driver-memory、–executor-memory)。
請確認您位於含有 CDM JAR 和屬性檔案的目錄中。如果您下載的是其他版本,請替換「cassandra-data-migrator-5.2.2.jar」。
./spark-3.5.3-bin-hadoop3-scala2.13/bin/spark-submit \ --properties-file cdm.properties \ --master "local[*]" \ --driver-memory 4G \ --executor-memory 4G \ --class com.datastax.cdm.job.Migrate \ cassandra-data-migrator-5.2.2.jar &> cdm_migration_$(date +%Y%m%d_%H%M).log
這項轉換作業會在背景執行,記錄會寫入 cdm_migration_... .log。監控記錄檔,瞭解進度和錯誤:
tail -f cdm_migration_*.log
6. 驗證資料遷移作業
CDM 工作順利完成後,請確認 Bigtable 中是否有歷來資料。由於 Cassandra-Bigtable Proxy 允許 CQL 讀取,您可以再次使用 cqlsh 連線至 ZDM Proxy (在遷移後會將讀取作業路由至目標,或可進行設定),或直接連線至 Cassandra-Bigtable Proxy,以便查詢資料。透過 ZDM Proxy 連線:
cqlsh <zdm-proxy-node-1-ip-address> 9042
在 cqlsh 中:
SELECT COUNT(*) FROM zdmbigtable.employee; -- Check row count matches origin SELECT * FROM employee LIMIT 10; -- Check some sample data
或者,如果在 CDM VM 或 Cloud Shell 上安裝了 cbt 工具,您可以直接在 Bigtable 中查詢資料:
# First, install cbt if needed
# gcloud components update
# gcloud components install cbt
# Then lookup a specific row (replace 'some_employee_name' with an actual primary key)
cbt -project $PROJECT_ID -instance zdmbigtable lookup employee some_employee_name
9. 系統截承 (概念)
徹底驗證 Cassandra 和 Bigtable 之間的資料一致性後,您就可以進行最終切換。
在 ZDM Proxy 中,轉換作業需要重新設定,以便主要從目標 (Bigtable) 讀取,而非從來源 (Cassandra) 讀取。這通常是透過 ZDM Proxy 的設定完成,可有效將應用程式的讀取流量轉移至 Bigtable。
確認 Bigtable 可正確放送所有流量後,您可以:
- 重新設定 ZDM Proxy,停止雙寫。
- 停用原始 Cassandra 叢集。
- 移除 ZDM Proxy,讓應用程式直接連線至 Cassandra-Bigtable Proxy,或使用原生 Java 版 Bigtable CQL 用戶端。
為了切換至新系統,您必須重新設定 ZDM Proxy,但這項操作不在本基本程式碼研究室的範圍內,詳情請參閱 Datastax ZDM 說明文件。
10. 清除所用資源
為避免產生費用,請刪除在本程式碼研究室中建立的資源。
1. 刪除 Compute Engine VM
gcloud compute instances delete cassandra-origin-vm zdm-proxy-jumphost zdm-proxy-node-1 bigtable-proxy-vm cdm-migrator-vm --zone=$ZONE --quiet
2. 刪除 Bigtable 執行個體
gcloud bigtable instances delete zdmbigtable
3. 刪除防火牆規則
gcloud compute firewall-rules delete allow-migration-internal
4. 刪除 Cassandra 資料庫 (如果已在本機安裝或保留)
如果您是在本頁所建立的 Compute Engine VM 外部安裝 Cassandra,請按照適當步驟移除資料或卸載 Cassandra。
11. 恭喜!
您已成功完成從 Apache Cassandra 遷移至 Bigtable 的 Proxy 遷移路徑設定程序!
您學會了如何:
部署 Cassandra 和 Bigtable。
- 設定 Cassandra-Bigtable Proxy,以便與 CQL 相容。
- 部署 Datastax ZDM Proxy 來管理雙寫和流量。
- 使用 Cassandra Data Migrator 移動歷來資料。
這個方法可利用 Proxy 層,在不變更程式碼的情況下,以最少的停機時間進行遷移。
後續步驟
- 查看 Bigtable 說明文件
- 如需進階設定和轉換程序,請參閱 Datastax ZDM Proxy 說明文件。
- 詳情請參閱 Cassandra-Bigtable Proxy 存放區。
- 如需進階用途,請查看 Cassandra Data Migrator 存放區。
- 試試其他 Google Cloud 程式碼研究室