双活方案
部分用户受部署环境限制,只能部署两台服务器,同时希望提高服务可用性和数据可靠性。TDengine 双活方案通过数据复制和客户端 Failover 满足这类需求,也可用于两套 TDengine 集群之间的灾备,集群规模不受两台服务器的限制。本文介绍双活系统的架构、配置和运维。
双活是 TDengine TSDB Enterprise 特有功能,首次发布于 v3.3.0.0。从 v3.4.3.12 起,双活任务改为通过 SQL 管理,v3.3.x 使用的 taosx replica 命令行也已删除。建议使用最新版本。
双活系统由两台服务器组成,每台分别部署一套服务。对业务层而言,两台服务器及其服务构成一个完整的系统,无需感知内部细节。两个节点通常称为 Master-Slave,即“主从”或“主备”,本文中可能混用这些称呼。
TDengine 双活系统的部署架构如下,主要依靠三个机制:
- Client Driver 负责 Failover,在主节点宕机时切换到从节点
- taosX 负责将数据从当前主节点复制到从节点,双活任务由 xnoded 统一调度
- 数据订阅的写接口在写入复制的数据时,向 WAL 添加特殊标记;读接口自动过滤带有该标记的数据,避免循环复制
注:下图以单机版 TDengine 为例,实际部署时,每个 Host 均可替换为任意节点数量的 TDengine 集群。

集群配置
部署双活需要满足以下前提条件:
- 版本:执行
CREATE XNODE TASK的管理集群须升级到 v3.4.3.12 或更高版本;源端和目标端均不低于 v3.4.0.0,两端版本可以不同;taosX 与 taosd 使用相同版本。 - 数据库:源库和目标库均已预先创建且精度相同,源库的
wal_retention_period大于 0。双活任务按库创建,不支持自动同步新增数据库。 - 授权:源端和目标端均具有
active_active授权(云服务实例除外),目标端另须具有td3.0授权。 - 部署:管理集群已部署 taosX 并注册 xnode,且 xnode 能连通两端集群。注册方法见 数据接入(Xnode)。建议由源集群兼任管理集群,并使用超级用户连接源端,以便管理订阅资源和 WAL 保留标记。
WAL 保留时长影响双活系统的容错能力。如果备节点的宕机时长超过主节点的 WAL 保留时长,备节点必定会缺失数据。即使未超过,也可能丢失数据,具体取决于宕机时长与 WAL 保留时长的接近程度,以及数据同步速度。详见 异常情况。
客户端配置
目前只有 Java 连接器在 WebSocket 连接模式下支持双活,配置示例如下:
url = "jdbc:TAOS-WS://" + host + ":6041/?user=root&password=taosdata&varcharAsString=true";
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_SLAVE_CLUSTER_HOST, "192.168.1.11");
properties.setProperty(TSDBDriver.PROPERTY_KEY_SLAVE_CLUSTER_PORT, "6041");
properties.setProperty(TSDBDriver.PROPERTY_KEY_ENABLE_AUTO_RECONNECT, "true");
properties.setProperty(TSDBDriver.PROPERTY_KEY_RECONNECT_INTERVAL_MS, "2000");
properties.setProperty(TSDBDriver.PROPERTY_KEY_RECONNECT_RETRY_COUNT, "3");
connection = DriverManager.getConnection(url, properties);
各配置属性的含义如下:
| 属性名 | 含义 |
|---|---|
| PROPERTY_KEY_SLAVE_CLUSTER_HOST | 第二节点的主机名或者 ip,默认空 |
| PROPERTY_KEY_SLAVE_CLUSTER_PORT | 第二节点的端口号,默认空 |
| PROPERTY_KEY_ENABLE_AUTO_RECONNECT | 是否启用自动重连。仅在使用 WebSocket 连接时生效。true: 启用,false: 不启用。默认为 false。双活场景下请设置为 true |
| PROPERTY_KEY_RECONNECT_INTERVAL_MS | 重连的时间间隔,单位毫秒:默认 2000 毫秒,也就是 2 秒;最小值为 0,表示立即重试;最大值不做限制 |
| PROPERTY_KEY_RECONNECT_RETRY_COUNT | 每节点最多重试次数:默认值为 3;最小值为 0,表示不进行重试;最大值不做限制 |
约束条件
- 应用程序不能使用订阅接口;配置双活参数后,创建消费者会失败
- 不建议应用程序通过参数绑定写入或查询数据;如需使用,应用必须自行处理连接切换后相关对象失效的问题
- 双活场景下,不建议应用程序显式执行
USE语句,应在连接参数中指定数据库 - 使用同一客户端连接在两端切换时,该客户端使用的数据库命名、配置以及用户名、密码和权限需要在两端保持一致;双活任务本身可以将源库映射到不同名称的目标库
- 上述客户端切换只支持 WebSocket 连接模式,双活任务支持 Native 和 WebSocket 两种连接方式
- 一个双活任务只复制一个数据库,不支持自动同步新增的数据库;每个任务独占一个 topic,集群的 topic 数量受
tmqMaxTopicNum限制
运维管理
任务管理
双活任务通过 SQL 创建、查看、启动、停止、修改和删除。完整语法、参数规则和删除行为见 数据接入(Xnode)。
使用 CREATE XNODE TASK ... WITH TYPE 'replica' 创建任务。一个任务将源集群的一个库单向复制到目标集群的一个库;如需双向复制,则在两端分别创建一个任务。以下示例在 td1 和 td2 之间双向复制数据库 power:
-- 在 td1 上执行:td1 -> td2
CREATE XNODE TASK 'aa_power_td1_td2'
FROM 'tmq+ws://root:taosdata@td1:6041/power'
TO 'taos+ws://root:taosdata@td2:6041/power'
WITH TYPE 'replica';
START XNODE TASK 'aa_power_td1_td2';
-- 在 td2 上执行:td2 -> td1
CREATE XNODE TASK 'aa_power_td2_td1'
FROM 'tmq+ws://root:taosdata@td2:6041/power'
TO 'taos+ws://root:taosdata@td1:6041/power'
WITH TYPE 'replica';
START XNODE TASK 'aa_power_td2_td1';
任务创建后处于停止状态,需执行 START XNODE TASK 启动。创建时,可在 FROM 中通过 auto.offset.reset、experimental.snapshot.enable、msg.consume.start.ts 等订阅起点参数控制复制的起始位置。这些参数创建后不能修改,如需调整,须删除任务后重建。重建的任务不继承旧任务进度。
与普通任务不同,双活任务采用异步删除。DROP XNODE TASK 返回成功只表示删除请求已受理,任务先进入 deleting 状态,待源端的 topic、消费组及位点清理完成后才从 SHOW XNODE TASKS 中消失。清理遇到权限或凭据等永久错误时,任务进入 delete_failed 状态,修复后需重新执行 DROP XNODE TASK。清理完成前不能重建相同映射的任务。
查看同步进度
先在管理集群查询集群 ID,再到源集群按系统生成的 topic 和消费组名查询各 vgroup 的消费位置:
-- 在管理集群执行(ins_cluster 为特权表,需要 SYSINFO 权限)
SELECT id
FROM information_schema.ins_cluster;
-- 在源集群执行,将 <管理集群 ID> 和 <任务 ID> 替换为实际值
SELECT
topic_name,
vgroup_id,
consumer_id,
`offset`,
`rows`
FROM information_schema.ins_subscriptions
WHERE topic_name = '__replica__<管理集群 ID>_<任务 ID>'
AND consumer_group = '__replica__<管理集群 ID>_<任务 ID>';
- 快照复制阶段,
offset以tsdb:开头;进入 WAL 复制阶段后,显示为wal:<已消费版本>/<最新版本>。两个版本之差是该 vgroup 的 WAL 版本差,可近似反映积压量,与 v3.3 版本taosx replica diff的含义相同。该位置由消费者心跳上报,可能超前于已提交位点。 rows是当前消费者进程累计消费的行数,任务重启后重新计数,不代表目标端成功写入的行数。consumer_id为空表示该 vgroup 当前没有消费者,例如任务已停止。
异常情况
双活任务停止或目标端发生故障后,如果从停止同步到恢复并追平数据的总耗时超过源库的 WAL 保留时长(wal_retention_period),对应的 WAL 可能已被清理,导致目标端缺少尚未同步的数据。现有双活任务无法自动补齐这部分数据,需要人工核对两端数据,确定缺失的表和时间范围。消费位点追平并不代表两端数据一致。
如果源端仍保留相应的历史数据,可删除该复制方向的双活任务,等待清理完成后重新创建并启动。重建时,应启用历史数据快照(auto.offset.reset=earliest、experimental.snapshot.enable=true),并通过 msg.consume.start.ts 设置同步开始时间。该时间不能晚于最早缺失数据的时间戳,以便重新复制缺失数据。订阅起点参数只能在创建任务时设置,具体规则见 数据接入(Xnode)。
升级与迁移
版本升级与降级
- 滚动升级期间不要创建双活任务。所有 taosd 升级完成前,旧版本 mnode 可能忽略
TYPE选项且不报错,将其创建为普通任务,导致任务无法防止循环复制。创建后,应通过SHOW XNODE TASKS确认type列为replica。taosX 应与 taosd 同时升级。 - 降级到 v3.4.3.12 之前的版本前,必须删除所有双活任务:旧版本 mnode 不识别任务类型,可能将双活任务作为普通任务运行,并永久丢失类型标记。
从 v3.3 迁移
v3.3 的双活任务不会随软件升级自动迁移,升级后需要用 SQL 重建。新任务不复用旧任务的 topic、消费组或已提交位点。
可以 手动迁移,逐个记录旧配置并重建任务,也可以通过 脚本迁移 转换配置,按需停止、删除旧任务,并创建、启动新任务。两种方式都需先完成下述准备,并在迁移后按相同要求检查结果。v3.3 导出的双活任务不能通过 Explorer 的普通任务导入功能恢复。
迁移前准备
- 根据每个复制方向已确认的进度,确定同步开始时间,以 Unix 毫秒时间戳表示。该时间不能晚于最早可能尚未同步记录的时间戳;无法确认时,可选择
0,重放所有仍可读取的数据。不要直接使用升级完成时间。 - 记录并调大两端源库的
wal_retention_period,使保留时长覆盖停机、升级和重新追平数据所需的总时间。仅从 WAL 消费时,确认开始时间对应的数据仍在保留范围内。 - 核对每个旧 taosX 实例的任务范围、源库到目标库的映射、连接地址、凭据和调优参数。迁移文件及备份可能包含明文凭据,应限制访问。
- 按发布说明规划升级,确认升级后满足 集群配置 中的版本、数据库、授权和部署要求。使用非零开始时间时,源端所有 vnode 都须达到 v3.4.3.6;如果同时使用 WebSocket 连接,所用的 taosAdapter 也须达到该版本。
从 v3.4.3.12 起,不再提供 taosx replica 命令。升级前,必须停止所有旧复制任务及关联的新库发现监控,再停止所有独立部署的旧 taosX 服务,以免旧任务或监控在升级后恢复运行。脚本在线导出和操作旧任务都依赖旧服务,应在停止服务前完成。
手动迁移
先停止所有旧任务并完成软件升级,再按库映射逐个重建任务:
- 在旧版本上记录所有复制方向的任务配置,分别执行
taosx replica stop <id>。等待全部任务停止后,停止旧 taosX 服务。 - 按发布说明升级所有 taosd、taosX 和所需的 taosAdapter,准备数据库并注册 xnode,确认满足迁移前准备中的要求。
- 为每个源库到目标库的映射编写
CREATE XNODE TASK ... WITH TYPE 'replica'语句,并在FROM中通过msg.consume.start.ts指定已确定的同步开始时间。按 数据接入(Xnode) 中的 DSN 参数规则核对连接信息和调优参数,不要沿用旧 topic、消费组、客户端标识或其他系统保留参数。 - 在选定的管理集群创建任务,通过
SHOW XNODE TASKS WHERE type = 'replica';核对任务名称、映射和类型。确认配置正确后,执行START XNODE TASK启动对应任务。 - 所有复制方向的任务重建完成后,按 迁移后验证 完成检查和收尾工作。
以下示例重建 td1 到 td2 的 power 数据库复制任务。将地址、凭据和开始时间替换为实际值;反向复制需另建任务:
CREATE XNODE TASK 'aa_power_td1_td2'
FROM 'tmq+ws://root:taosdata@td1:6041/power?msg.consume.start.ts=1700000000000'
TO 'taos+ws://root:taosdata@td2:6041/power'
WITH TYPE 'replica';
SHOW XNODE TASKS WHERE type = 'replica';
START XNODE TASK 'aa_power_td1_td2';
脚本迁移
迁移脚本可将 v3.3.6 的双活任务配置转换为新版本的 SQL。默认只生成迁移文件,也可以按需停止、删除旧任务,或在升级后创建、启动新任务。软件升级和迁移后的数据核对仍需手动完成。
展开下方代码,将其保存为 migrate_active_active.py,使用 Python 3.8 或更高版本运行,无需安装第三方依赖。执行新任务 SQL 时,脚本会调用本机的 taos 客户端。
迁移脚本
#!/usr/bin/env python3
# Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# This program is free software: you can use, redistribute, and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# or later ("AGPL"), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Migrate v3.3.6 taosX active-active tasks to SQL-managed XNODE tasks."""
import argparse
import csv
from datetime import datetime, timedelta, timezone
import hashlib
import json
import math
import os
from pathlib import Path
import re
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import time
from urllib.error import HTTPError, URLError
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from urllib.request import Request, urlopen
SYSTEM_PARAMS = {
"replica", "msg.consume.excluded", "timeout", "prefer", "enable.wal.marker",
"group.id", "use.topic.name", "client.id",
}
CONNECTION_PARAMS = {
"token", "bearer_token", "td.connect.token", "tls_mode", "tls_version",
"tls_ca", "conn_mode",
}
SOURCE_PARAMS = CONNECTION_PARAMS | {
"auto.offset.reset", "experimental.snapshot.enable", "msg.consume.start.ts",
"enable.auto.commit", "enable.replay", "msg.consume.rawdata",
"write_concurrency", "num.of.writers", "commit.chunk.size", "commit.interval.ms",
"max.polling.timeout", "enable.concurrent.polling", "refresh.progress.interval",
"auto.commit.interval.ms", "msg.with.table.name", "session.timeout.ms",
"max.poll.interval.ms", "fetch.max.wait.ms", "min.poll.rows", "msg.enable.batchmeta",
}
DSN = re.compile(
r"^(tmq|taos)(?:\+(ws|wss|http|https|native))?://([^/?#]+)/([^?#]+)(?:\?(.*))?$"
)
INTEGER = re.compile(r"^[+-]?[0-9]+$")
TASK_ID = re.compile(r"^[1-9][0-9]*$")
RFC3339 = re.compile(
r"^(?P<date>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})"
r"(?:\.(?P<fraction>[0-9]{1,3}))?(?P<zone>Z|[+-][0-9]{2}:[0-9]{2})$"
)
STOPPED = {"stopped", "stop", "inactive"}
RUNNING = {"running"}
SQL_ERROR = re.compile(r"(?im)^\s*(?:DB error:|error:|failed to (?:open|connect|read|fetch|execute)\b|query interrupted\b|taos_fetch_row failed\b)")
SQL_SUCCESS = re.compile(r"(?im)^\s*(?:Query|Create) OK,\s*([0-9]+) row\(s\) (?:in set|affected)\b")
UNSET = object()
class MigrationError(Exception):
"""A user-facing migration error that never contains credentials."""
def unique_object(pairs):
result = {}
for name, value in pairs:
if name in result:
raise ValueError("duplicate JSON object key; resolve the ambiguous input")
result[name] = value
return result
def read_json(path):
try:
with Path(path).open(encoding="utf-8") as source:
return json.load(source, object_pairs_hook=unique_object)
except (OSError, UnicodeError, json.JSONDecodeError) as error:
raise ValueError("unable to read JSON input") from error
def timestamp(value):
if type(value) is not int or not 0 <= value <= 9223372036854775807:
raise ValueError("start time must be a nonnegative signed 64-bit Unix millisecond integer")
return value
def parse_timestamp(value):
if type(value) is int:
return timestamp(value)
if not isinstance(value, str):
raise ValueError("start time must be Unix milliseconds or RFC 3339")
if INTEGER.fullmatch(value):
try:
return timestamp(int(value, 10))
except (ValueError, OverflowError):
raise ValueError("start time is outside the signed 64-bit millisecond range") from None
matched = RFC3339.fullmatch(value)
if matched is None:
raise ValueError("start time must include Z or an explicit +HH:MM/-HH:MM timezone and at most 3 fractional digits")
fraction = (matched.group("fraction") or "").ljust(3, "0")
zone = matched.group("zone")
if zone == "Z":
offset = timezone.utc
else:
sign = 1 if zone[0] == "+" else -1
hours, minutes = map(int, zone[1:].split(":"))
if hours > 23 or minutes > 59:
raise ValueError("invalid RFC 3339 timezone offset")
offset = timezone(sign * timedelta(hours=hours, minutes=minutes))
try:
parsed = datetime.strptime(matched.group("date"), "%Y-%m-%dT%H:%M:%S").replace(
tzinfo=offset
)
except ValueError:
raise ValueError("invalid RFC 3339 start time") from None
return timestamp(int(parsed.timestamp()) * 1000 + int(fraction or 0))
def decode_parameter(value):
if re.search(r"%(?![0-9a-fA-F]{2})", value):
raise ValueError("invalid percent encoding in DSN parameter")
try:
return unquote(value, errors="strict")
except UnicodeError:
raise ValueError("invalid UTF-8 in DSN parameter") from None
def convert_dsn(value, driver, start_time=UNSET):
if not isinstance(value, str) or any(ord(char) < 32 or ord(char) == 127 for char in value):
raise ValueError("expected a plain DSN string without control characters")
matched = DSN.fullmatch(value)
if matched is None or matched[1] != driver:
raise ValueError("expected a %s DSN with addresses and a database" % driver)
authority, database, query = matched.group(3, 4, 5)
addresses = authority.rsplit("@", 1)[-1]
if not addresses or any(not address for address in addresses.split(",")):
raise ValueError("DSN addresses must not be empty")
params = {}
for pair in query.split("&") if query else []:
if not pair:
raise ValueError("empty DSN parameter")
name, separator, raw = pair.partition("=")
if not separator:
raw = ""
name, raw = decode_parameter(name), decode_parameter(raw)
if not name or name in params:
raise ValueError("duplicate or empty DSN parameter")
params[name] = raw
params = {name: raw for name, raw in params.items() if name not in SYSTEM_PARAMS}
allowed = SOURCE_PARAMS if driver == "tmq" else CONNECTION_PARAMS
unsupported = params.keys() - allowed
if unsupported:
names = ", ".join(name if re.fullmatch(r"[a-zA-Z0-9_.-]+", name) else "<invalid name>" for name in sorted(unsupported))
raise ValueError("unsupported %s DSN parameter: %s" % (driver, names))
if driver == "tmq":
if params.get("auto.offset.reset", "earliest") == "latest":
raise ValueError("migration does not support auto.offset.reset=latest")
if params.get("auto.offset.reset", "earliest") != "earliest":
raise ValueError("migration requires auto.offset.reset=earliest to cover retained data")
if params.get("experimental.snapshot.enable", "true") not in ("true", "false"):
raise ValueError("invalid experimental.snapshot.enable")
for name in ("enable.auto.commit", "enable.replay"):
if name in params and params[name] != "false":
raise ValueError("%s must be false" % name)
if start_time is not UNSET:
start_time = timestamp(start_time)
params["msg.consume.start.ts"] = str(start_time)
elif "msg.consume.start.ts" in params:
inherited = params["msg.consume.start.ts"]
if not re.fullmatch(r"[0-9]+", inherited):
raise ValueError("invalid msg.consume.start.ts")
try:
start_time = timestamp(int(inherited, 10))
except ValueError:
raise ValueError("invalid msg.consume.start.ts") from None
if "msg.consume.rawdata" in params:
rawdata = params["msg.consume.rawdata"]
if not re.fullmatch(r"[+-]?[0-9]+", rawdata) or not -2147483648 <= int(rawdata) <= 2147483647:
raise ValueError("invalid msg.consume.rawdata")
if start_time is not UNSET and start_time != 0 and int(rawdata) != 0:
raise ValueError("nonzero msg.consume.rawdata conflicts with the migration start time")
base = value.split("?", 1)[0]
encoded = "&".join(
quote(name, safe=".-_") + "=" + quote(raw, safe=".-_")
for name, raw in sorted(params.items())
)
identity = (addresses.lower(), database)
return base + ("?" + encoded if encoded else ""), identity
def is_replica(task):
labels = task.get("labels", [])
if isinstance(labels, dict):
return labels.get("type") == "replica"
if isinstance(labels, list):
return "type::replica" in labels
raise ValueError("expected task labels as an array or object")
def selected_tasks(tasks):
if not isinstance(tasks, list) or any(not isinstance(task, dict) for task in tasks):
raise ValueError("expected the JSON array returned by the old taosX /tasks endpoint")
selected = [task for task in tasks if not task.get("deleted") and is_replica(task)]
if not selected:
raise ValueError("no non-deleted replica-labelled tasks found")
return selected
def task_start_times(values):
if values is None:
return {}
result = {}
for item in values:
task_id, separator, value = item.partition("=")
if not separator or not TASK_ID.fullmatch(task_id):
raise ValueError("task start time must use TASK_ID=TIME")
if task_id in result:
raise ValueError("duplicate task start time")
result[task_id] = parse_timestamp(value)
return result
def sql_string(value):
return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
def validate_task_ids(tasks):
identifiers = set()
for task in tasks:
task_id = task.get("id")
if type(task_id) is not int or not 0 < task_id <= 9223372036854775807:
raise ValueError("task id must be a positive signed 64-bit integer")
if task_id in identifiers:
raise ValueError("duplicate legacy task id")
identifiers.add(task_id)
return identifiers
def render_with_plans(tasks, start_times=UNSET):
selected = selected_tasks(tasks)
if start_times is UNSET or start_times is None:
starts = {}
elif isinstance(start_times, dict):
starts = {str(key): parse_timestamp(value) for key, value in start_times.items()}
else:
starts = {str(task["id"]): timestamp(start_times) for task in selected}
identifiers = validate_task_ids(selected)
mappings = set()
creates, starts_sql = [], []
plans = []
for task in selected:
task_id = task.get("id")
if task.get("via") is not None or task.get("parser") not in (None, {}):
raise ValueError("VIA and custom parsers cannot be migrated to replica tasks")
if task.get("jobs", 0) not in (None, 0, 1):
raise ValueError("parallel jobs require manual review before migration")
task_key = str(task_id)
start_time = starts.get(task_key, UNSET)
try:
source, source_identity = convert_dsn(task.get("from"), "tmq", start_time)
sink, sink_identity = convert_dsn(task.get("to"), "taos", start_time)
except (TypeError, ValueError) as error:
raise ValueError("task %s: %s" % (task_id, error)) from None
mapping = source_identity, sink_identity
if mapping in mappings:
raise ValueError("duplicate mapping; choose one legacy task for each mapping")
mappings.add(mapping)
digest = hashlib.sha256(json.dumps(mapping, separators=(",", ":")).encode("utf-8")).hexdigest()[:12]
name = "aa_336_%s_%s" % (task_id, digest)
creates.append(
"CREATE XNODE TASK %s FROM %s TO %s WITH TYPE 'replica';"
% (sql_string(name), sql_string(source), sql_string(sink))
)
starts_sql.append("START XNODE TASK %s;" % sql_string(name))
plans.append({
"legacy_id": task_id,
"name": name,
"from": source,
"to": sink,
"start_time": None if start_time is UNSET else start_time,
})
if set(starts) - {str(task_id) for task_id in identifiers}:
raise ValueError("start-time task id is outside the migration scope")
return "\n".join(creates) + "\n", "\n".join(starts_sql) + "\n", plans
def render(tasks, start_times=UNSET):
if isinstance(start_times, dict) and not start_times:
raise ValueError("start-time mapping must contain at least one task")
create_sql, start_sql, _ = render_with_plans(tasks, start_times)
return create_sql, start_sql
def read_api(base_url, timeout=30):
base_url = base_url.rstrip("/")
try:
parts = urlsplit(base_url)
except ValueError:
raise ValueError("old taosX URL is invalid") from None
if parts.scheme not in ("http", "https") or not parts.netloc:
raise ValueError("old taosX URL must be an HTTP or HTTPS URL")
endpoint = urlunsplit((parts.scheme, parts.netloc, parts.path + "/tasks", "labels=type::replica", ""))
try:
response = urlopen(endpoint, timeout=timeout)
with response:
payload = response.read(16 * 1024 * 1024 + 1)
except HTTPError as error:
raise ValueError("old taosX API returned HTTP %s" % error.code) from None
except (URLError, TimeoutError, OSError, ValueError):
raise ValueError("unable to contact old taosX API") from None
if len(payload) > 16 * 1024 * 1024:
raise ValueError("old taosX API response is too large")
try:
parsed = json.loads(payload.decode("utf-8"), object_pairs_hook=unique_object)
except (UnicodeError, json.JSONDecodeError):
raise ValueError("old taosX API returned invalid JSON") from None
if not isinstance(parsed, list):
raise ValueError("old taosX API returned an unexpected response")
return parsed
def read_sqlite(path):
resolved = Path(path).resolve()
uri = resolved.as_uri() + "?mode=ro"
connection = sqlite3.connect(uri, uri=True)
connection.row_factory = sqlite3.Row
try:
task_columns = [row[1] for row in connection.execute("PRAGMA table_info(tasks)")]
if not task_columns:
raise sqlite3.Error("tasks table is missing")
fields = ", ".join('"%s"' % column.replace('"', '""') for column in task_columns)
where = " WHERE deleted = 0" if "deleted" in task_columns else ""
order = " ORDER BY id" if "id" in task_columns else ""
rows = [dict(row) for row in connection.execute("SELECT %s FROM tasks%s%s" % (fields, where, order))]
label_columns = [row[1] for row in connection.execute("PRAGMA table_info(labels)")]
if label_columns:
key_column = "key" if "key" in label_columns else "name" if "name" in label_columns else None
task_column = "id" if "id" in label_columns else "task_id" if "task_id" in label_columns else None
if key_column and task_column and "value" in label_columns:
labels = {}
query = 'SELECT "%s", "%s", "value" FROM labels' % (task_column, key_column)
for task_id, key, value in connection.execute(query):
labels.setdefault(task_id, []).append(key if value is None else "%s::%s" % (key, value))
for task in rows:
task["labels"] = labels.get(task.get("id"), task.get("labels", []))
for task in rows:
if isinstance(task.get("parser"), str):
try:
task["parser"] = json.loads(task["parser"], object_pairs_hook=unique_object)
except (UnicodeError, json.JSONDecodeError):
raise ValueError("invalid parser JSON in SQLite backup") from None
return rows
finally:
connection.close()
def snapshot_data(snapshot):
if isinstance(snapshot, list):
return snapshot, {}, None
if not isinstance(snapshot, dict) or not isinstance(snapshot.get("tasks"), list):
raise ValueError("tasks.json has an invalid snapshot format")
return snapshot["tasks"], snapshot.get("start_times", {}), snapshot.get("old_taosx_url")
def write_secure(path, content):
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as output:
output.write(content)
except Exception:
try:
os.unlink(path)
except OSError:
pass
raise
def save_generation(output, tasks, start_times, old_url, create_sql, start_sql):
output = Path(output)
if output.exists():
raise ValueError("output directory already exists")
output.mkdir(mode=0o700)
snapshot = {
"version": 1,
"old_taosx_url": old_url,
"start_times": {str(key): value for key, value in start_times.items()},
"tasks": tasks,
}
try:
write_secure(output / "tasks.json", json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n")
write_secure(output / "create.sql", create_sql)
write_secure(output / "start.sql", start_sql)
except Exception:
shutil.rmtree(output, ignore_errors=True)
raise
def canonical_task(task):
labels = task.get("labels", [])
if isinstance(labels, dict):
labels = [key if value is None else "%s::%s" % (key, value) for key, value in sorted(labels.items())]
return {
"id": task.get("id"),
"name": task.get("name"),
"from": task.get("from"),
"to": task.get("to"),
"labels": sorted(labels) if isinstance(labels, list) else labels,
"via": task.get("via"),
"parser": task.get("parser"),
"jobs": task.get("jobs"),
}
def verify_snapshot_live(snapshot_tasks, live_tasks, records=()):
expected = {task.get("id"): task for task in selected_tasks(snapshot_tasks)}
if not isinstance(live_tasks, list) or any(not isinstance(task, dict) for task in live_tasks):
raise ValueError("old taosX API returned an unexpected task list")
actual = {task.get("id"): task for task in live_tasks if not task.get("deleted")}
completed = {
record.get("id") for record in records
if record.get("action") == "delete-confirmed" or (
record.get("action") == "delete" and record.get("requested") is True and not record.get("failed")
)
}
if any(task_id not in expected for task_id, task in actual.items() if is_replica(task)):
raise ValueError("old taosX task set changed; export a new snapshot")
for task_id, expected_task in expected.items():
if task_id not in actual:
if task_id in completed:
continue
raise MigrationError("old task %s is missing with an uncertain deletion result; manual review required" % task_id)
if task_id in completed:
raise MigrationError("deleted old task %s has reappeared; manual review required" % task_id)
if canonical_task(expected_task) != canonical_task(actual[task_id]):
raise ValueError("old taosX task %s changed; export a new snapshot" % task_id)
return {task_id: task for task_id, task in actual.items() if task_id in expected}
def api_request(base_url, method, path, body=None, timeout=30, allow_not_found=False):
endpoint = base_url.rstrip("/") + path
try:
data = None if body is None else json.dumps(body).encode("utf-8")
request = Request(endpoint, data=data, method=method)
if body is not None:
request.add_header("Content-Type", "application/json")
response = urlopen(request, timeout=timeout)
with response:
payload = response.read(1024 * 1024)
except HTTPError as error:
if allow_not_found and error.code == 404:
error.close()
return
raise MigrationError("old taosX API returned HTTP %s for task operation" % error.code) from None
except (URLError, TimeoutError, OSError, ValueError):
raise MigrationError("unable to contact old taosX API for task operation") from None
if payload:
try:
result = json.loads(payload.decode("utf-8"))
except (UnicodeError, json.JSONDecodeError):
result = None
if isinstance(result, dict) and (
result.get("error") or result.get("code") not in (None, 0, "0")
):
raise MigrationError("old taosX API rejected the task operation")
def operation_results_path(output):
return Path(output) / "old-operations.json"
def save_operation_results(output, records):
path = operation_results_path(output)
temporary = path.with_suffix(".tmp")
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as result:
result.write(json.dumps(records, indent=2) + "\n")
result.flush()
os.fsync(result.fileno())
os.replace(temporary, path)
if os.name == "posix":
descriptor = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
def load_operation_results(output):
path = operation_results_path(output)
if not path.exists():
return []
records = read_json(path)
if not isinstance(records, list) or any(not isinstance(record, dict) for record in records):
raise ValueError("old-operations.json has an invalid format")
return records
def remaining_timeout(deadline, maximum=30):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise MigrationError("operation timed out; inspect saved results before retrying")
return min(maximum, remaining)
def replica_ids(tasks):
identifiers = set()
for task in selected_tasks(tasks):
labels = task.get("labels", [])
values = [labels.get("rid")] if isinstance(labels, dict) else [label[5:] for label in labels if isinstance(label, str) and label.startswith("rid::")]
if len(values) != 1 or not isinstance(values[0], str) or not values[0]:
raise ValueError("old task %s has no unambiguous replica monitor id; manual review required" % task["id"])
identifiers.add(values[0])
return sorted(identifiers)
def operate_monitors(output, old_url, tasks, records, delete=False, deadline=None):
for replica_id in replica_ids(tasks):
if any(record.get("action") == "monitor-delete" and record.get("rid") == replica_id and record.get("completed") for record in records):
continue
action = "monitor-delete" if delete else "monitor-stop"
records.append({"action": action + "-intent", "rid": replica_id})
save_operation_results(output, records)
try:
api_request(old_url, "DELETE" if delete else "POST", "/replicas/" + quote(replica_id, safe=""),
body={"action": "delete", "options": {}} if delete else {"action": "stop"},
timeout=30 if deadline is None else remaining_timeout(deadline), allow_not_found=delete)
except MigrationError:
records.append({"action": action, "rid": replica_id, "failed": True})
save_operation_results(output, records)
raise
records.append({"action": action, "rid": replica_id, "completed": True})
save_operation_results(output, records)
def report_old_tasks(snapshot_tasks, live, records, action):
completed = {record.get("id") for record in records if record.get("action") == "delete-confirmed" or (record.get("action") == "delete" and record.get("requested") is True and not record.get("failed"))}
for task in selected_tasks(snapshot_tasks):
task_id = task["id"]
status = str(live.get(task_id, {}).get("status", "unknown")).lower()
deleted = task_id in completed and task_id not in live
result = "completed" if deleted or (action == "stop" and status in STOPPED) else "pending"
if any(record.get("id") == task_id and record.get("failed") for record in records[-1:]):
result = "failed"
print("Old task %s: %s %s (status=%s)" % (task_id, action, result, "deleted" if deleted else status))
def stop_old(output, old_url, snapshot_tasks, timeout):
deadline = time.monotonic() + timeout
records = load_operation_results(output)
live = {}
try:
live = verify_snapshot_live(snapshot_tasks, read_api(old_url, timeout=remaining_timeout(deadline)), records)
operate_monitors(output, old_url, snapshot_tasks, records, deadline=deadline)
live = verify_snapshot_live(snapshot_tasks, read_api(old_url, timeout=remaining_timeout(deadline)), records)
for task_id, current in live.items():
status = str(current.get("status", "")).lower()
if status not in STOPPED:
try:
api_request(old_url, "POST", "/tasks/%s/stop" % task_id, timeout=remaining_timeout(deadline))
records.append({"action": "stop", "id": task_id, "requested": True})
except MigrationError:
records.append({"action": "stop", "id": task_id, "failed": True})
save_operation_results(output, records)
raise
else:
records.append({"action": "stop", "id": task_id, "requested": False, "status": status})
save_operation_results(output, records)
while True:
live = verify_snapshot_live(snapshot_tasks, read_api(old_url, timeout=remaining_timeout(deadline)), records)
statuses = {task_id: str(task.get("status", "")).lower() for task_id, task in live.items()}
if all(status in STOPPED for status in statuses.values()):
remaining_timeout(deadline)
records.append({"action": "stop-confirmed", "statuses": statuses})
save_operation_results(output, records)
return list(live.values())
time.sleep(min(2, remaining_timeout(deadline)))
finally:
report_old_tasks(snapshot_tasks, live, records, "stop")
def delete_old(output, old_url, snapshot_tasks):
records = load_operation_results(output)
live = {}
try:
live = verify_snapshot_live(snapshot_tasks, read_api(old_url), records)
if any(str(task.get("status", "")).lower() not in STOPPED for task in live.values()):
raise MigrationError("refusing to delete old tasks that are not stopped")
operate_monitors(output, old_url, snapshot_tasks, records, delete=True)
live = verify_snapshot_live(snapshot_tasks, read_api(old_url), records)
if any(str(task.get("status", "")).lower() not in STOPPED for task in live.values()):
raise MigrationError("refusing to delete old tasks that are not stopped")
for task_id in list(live):
records.append({"action": "delete-intent", "id": task_id})
save_operation_results(output, records)
try:
api_request(old_url, "DELETE", "/tasks/%s" % task_id)
except MigrationError:
records.append({"action": "delete", "id": task_id, "failed": True})
save_operation_results(output, records)
raise
records.append({"action": "delete", "id": task_id, "requested": True})
save_operation_results(output, records)
live = verify_snapshot_live(snapshot_tasks, read_api(old_url), records)
if task_id in live:
raise MigrationError("old task %s deletion is not confirmed; manual review required" % task_id)
records.append({"action": "delete-confirmed", "id": task_id})
save_operation_results(output, records)
finally:
report_old_tasks(snapshot_tasks, live, records, "delete")
def invoke_taos(dsn, arguments, timeout=300):
command = ["taos", "-X", dsn] + list(arguments)
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired):
raise MigrationError("unable to execute taos client") from None
output = (result.stdout or "") + "\n" + (result.stderr or "")
if result.returncode != 0 or SQL_ERROR.search(output) or not SQL_SUCCESS.search(output):
raise MigrationError("taos reported an SQL execution error")
return output
def query_rows(dsn, sql, required, timeout=300):
with tempfile.TemporaryDirectory(prefix="taosx-migration-") as directory:
result_path = Path(directory) / "result.csv"
if any(char in str(result_path) for char in ";\r\n"):
raise MigrationError("temporary directory cannot be used for taos query output")
write_secure(result_path, "")
output = invoke_taos(dsn, ["-s", sql.rstrip("; ") + " >> " + str(result_path) + ";"], timeout=timeout)
try:
with result_path.open(encoding="utf-8", newline="") as result:
reader = csv.DictReader(result, strict=True)
fields = reader.fieldnames
if fields is None:
if SQL_SUCCESS.search(output).group(1) == "0":
return []
raise MigrationError("taos returned no structured query result")
if len(set(fields)) != len(fields) or not set(required).issubset(fields):
raise MigrationError("taos query result has unexpected columns")
rows = list(reader)
except (csv.Error, UnicodeError, OSError):
raise MigrationError("unable to read structured taos query result") from None
if any(None in row or any(value is None for value in row.values()) for row in rows):
raise MigrationError("taos query result has incomplete rows")
if len(rows) != int(SQL_SUCCESS.search(output).group(1)):
raise MigrationError("taos query result is incomplete")
return rows
def preflight_protection(dsn):
try:
rows = query_rows(dsn, "SHOW VARIABLES LIKE 'xnodeDsnProtection'", ("name", "value", "reboot"))
except MigrationError:
raise MigrationError("unable to confirm xnodeDsnProtection is disabled; automatic execution is unsupported") from None
if len(rows) != 1 or rows[0]["name"] != "xnodeDsnProtection" or rows[0]["value"] != "0" or rows[0]["reboot"].lower() != "false":
raise MigrationError("automatic execution requires confirmed disabled xnodeDsnProtection with no pending restart")
def query_xnode_tasks(dsn, plans, timeout=300):
names = ", ".join(sql_string(plan["name"]) for plan in plans)
rows = query_rows(dsn, 'SELECT name, `from`, `to`, type, status, parser, via FROM information_schema.ins_xnode_tasks WHERE name IN (%s)' % names,
("name", "from", "to", "type", "status", "parser", "via"), timeout=timeout)
tasks = {}
for row in rows:
if row["name"] in tasks:
raise MigrationError("target query returned duplicate task names")
tasks[row["name"]] = row
return tasks
def verify_xnode_tasks(tasks, plans, require_running=False):
for plan in plans:
name = plan["name"]
task = tasks.get(name)
if task is None:
raise MigrationError("target task %s was not found after SQL execution" % name)
if task["type"] != "replica":
raise MigrationError("target task %s has the wrong type" % name)
if task["from"] != plan["from"] or task["to"] != plan["to"] or task["parser"] not in ("NULL", "{}") or task["via"] != "NULL":
raise MigrationError("target task %s configuration does not match the migration" % name)
if require_running and task["status"] not in RUNNING:
raise MigrationError("target task %s did not enter running state" % name)
def sql_statements(path):
contents = Path(path).read_text(encoding="utf-8")
statements = [line.strip() for line in contents.splitlines() if line.strip()]
if any(not statement.endswith(";") for statement in statements):
raise ValueError("SQL file contains an incomplete statement")
return statements
def save_new_results(output, results):
path = Path(output) / "new-operations.json"
temporary = path.with_suffix(".tmp")
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as result:
result.write(json.dumps(list(results.values()), indent=2) + "\n")
os.replace(temporary, path)
def execute_sql(output, dsn, mode, start_timeout=300):
tasks, saved_times, _ = snapshot_data(read_json(Path(output) / "tasks.json"))
create_sql, start_sql, plans = render_with_plans(tasks, saved_times)
create_path, start_path = Path(output) / "create.sql", Path(output) / "start.sql"
if create_path.read_text(encoding="utf-8") != create_sql or start_path.read_text(encoding="utf-8") != start_sql:
raise ValueError("migration SQL does not match tasks.json; preserve the directory and operation records, then review the snapshot, SQL and live task state before continuing")
results = {plan["name"]: {"name": plan["name"], "legacy_id": plan["legacy_id"], "create": "pending", "start": "pending", "status": "unknown"} for plan in plans}
active = None
stage = "create" if mode in ("create", "all") else "start"
deadline = None
try:
save_new_results(output, results)
preflight_protection(dsn)
before = query_xnode_tasks(dsn, plans)
for plan in plans:
if plan["name"] in before:
active = results[plan["name"]]
verify_xnode_tasks(before, [plan])
active = None
if mode in ("create", "all"):
for plan, statement in zip(plans, sql_statements(create_path)):
active = results[plan["name"]]
if plan["name"] not in before:
invoke_taos(dsn, ["-s", statement])
verified = query_xnode_tasks(dsn, [plan])
verify_xnode_tasks(verified, [plan])
before.update(verified)
active.update(create="completed", status=before[plan["name"]]["status"])
save_new_results(output, results)
active = None
if mode in ("start", "all"):
stage = "start"
before = query_xnode_tasks(dsn, plans)
for plan in plans:
active = results[plan["name"]]
verify_xnode_tasks(before, [plan])
active.update(create="completed", status=before[plan["name"]]["status"])
if active["status"] in RUNNING:
active["start"] = "completed"
active = None
deadline = time.monotonic() + start_timeout
for plan, statement in zip(plans, sql_statements(start_path)):
active = results[plan["name"]]
active.update(create="completed", status=before[plan["name"]]["status"])
if active["status"] not in RUNNING and active["status"] != "queued":
invoke_taos(dsn, ["-s", statement], timeout=remaining_timeout(deadline, 300))
if active["status"] in RUNNING:
active["start"] = "completed"
save_new_results(output, results)
active = None
while True:
verified = query_xnode_tasks(dsn, plans, timeout=remaining_timeout(deadline, 300))
verify_xnode_tasks(verified, plans)
for plan in plans:
result = results[plan["name"]]
result["status"] = verified[plan["name"]]["status"]
result["start"] = "completed" if result["status"] in RUNNING else "pending"
if result["status"] in ("failed", "deleted", "deleting", "delete_failed"):
result["start"] = "failed"
save_new_results(output, results)
if any(result["start"] == "failed" for result in results.values()):
raise MigrationError("one or more target tasks failed to start; inspect new-operations.json")
remaining_timeout(deadline)
if all(result["start"] == "completed" for result in results.values()):
return
time.sleep(min(2, remaining_timeout(deadline)))
except (MigrationError, ValueError, OSError):
if active is not None:
active[stage] = "failed"
if mode in ("start", "all") and deadline is not None and time.monotonic() < deadline:
try:
actual = query_xnode_tasks(dsn, plans, timeout=remaining_timeout(deadline))
for plan in plans:
if plan["name"] in actual:
verify_xnode_tasks(actual, [plan])
result = results[plan["name"]]
result["status"] = actual[plan["name"]]["status"]
if result["status"] in RUNNING:
result["start"] = "completed"
except (MigrationError, ValueError, OSError):
pass
raise
finally:
save_new_results(output, results)
for result in results.values():
print("Target task %s: create=%s start=%s status=%s" % (result["name"], result["create"], result["start"], result["status"]))
def build_parser():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Examples:
%(prog)s --old-taosx-url http://old:6050 --output-dir migration
%(prog)s --output-dir migration --stop-old --stop-timeout 300
%(prog)s --output-dir migration --delete-old
%(prog)s --output-dir migration --dsn ws://user:password@new:6041 --execute create
%(prog)s --output-dir migration --dsn ws://user:password@new:6041 --execute start --start-timeout 300
By default only generate files. Old operations cover all tasks in the snapshot
and their associated new-database discovery monitors. Stop the old taosX service
after running any required --stop-old or --delete-old operation and before
upgrading. Generate an online snapshot while the old service is readable, or
generate one from a consistent --sqlite backup after the service is stopped.
After the upgrade, use --execute create, --execute start, or --execute all
against the new management cluster. The --sqlite mode cannot stop or delete
old tasks; perform those operations before stopping the old service or handle
them manually.
Automatic SQL execution requires disabled xnodeDsnProtection; it is rejected
before writes when protection is enabled or its effective state is unknown.
Retry the same operation with the same directory after inspecting old-operations.json
or new-operations.json. Missing tasks with unconfirmed deletions need manual review.
""")
parser.add_argument("--output-dir", required=True, type=Path, help="migration directory (required): new for generation, existing for later operations")
parser.add_argument("--old-taosx-url", default=None, help="old HTTP(S) API; generation default: http://127.0.0.1:6050; later operations use the saved URL and reject changes")
parser.add_argument("--sqlite", type=Path, help="read-only consistent SQLite backup for offline generation; default: online API")
timing = parser.add_mutually_exclusive_group()
timing.add_argument("--start-time", help="generation only: override all task start times, Unix milliseconds or RFC 3339 with timezone; omitted inherits each old FROM DSN value, or the new task default if absent; 0 disables time filtering")
timing.add_argument("--task-start-time", action="append", default=[], metavar="TASK_ID=TIME", help="generation only: repeat for distinct old task IDs; override listed tasks, others inherit old FROM DSN values or the new task default; same units as --start-time; mutually exclusive with it")
parser.add_argument("--stop-old", action="store_true", help="stop all old replication tasks in the snapshot and wait until stopped; first disable their associated automatic discovery of new databases")
parser.add_argument("--delete-old", action="store_true", help="delete all old replication tasks in the snapshot and their associated new-database discovery configuration; require all tasks to be stopped")
parser.add_argument("--stop-delete-old", action="store_true", help="stop all old replication tasks and wait until stopped, then delete them; also disable and remove their associated new-database discovery configuration")
parser.add_argument("--stop-timeout", type=float, default=None, metavar="SECONDS", help="finite positive total STOP budget, including requests (default: 300 seconds)")
parser.add_argument("--execute", choices=("create", "start", "all"), help="post-upgrade SQL phase; all verifies every CREATE before START; default: no SQL execution")
parser.add_argument("--start-timeout", type=float, default=None, metavar="SECONDS", help="finite positive START and running-state wait budget; only with --execute start/all (default: 300 seconds)")
parser.add_argument("--dsn", help="required with --execute: management DSN passed unchanged to local taos -X")
return parser
def main(argv=None):
parser = build_parser()
arguments = parser.parse_args(argv)
old_operations = [arguments.stop_old, arguments.delete_old, arguments.stop_delete_old]
try:
if sum(old_operations) > 1:
raise ValueError("--stop-old, --delete-old and --stop-delete-old are mutually exclusive")
if arguments.stop_timeout is not None and (not math.isfinite(arguments.stop_timeout) or arguments.stop_timeout <= 0):
raise ValueError("--stop-timeout must be a finite positive number")
if arguments.start_timeout is not None:
if not math.isfinite(arguments.start_timeout) or arguments.start_timeout <= 0:
raise ValueError("--start-timeout must be a finite positive number")
if arguments.execute not in ("start", "all"):
raise ValueError("--start-timeout is only valid with --execute start or all")
if arguments.execute and any(old_operations):
raise ValueError("--execute cannot be combined with old task operations")
if arguments.execute:
if arguments.sqlite or arguments.old_taosx_url or arguments.start_time is not None or arguments.task_start_time or arguments.stop_timeout is not None:
raise ValueError("--execute accepts only --output-dir, --dsn and --start-timeout for start/all")
if not arguments.dsn:
raise ValueError("--dsn is required with --execute")
if not arguments.output_dir.is_dir():
raise ValueError("--output-dir must contain an existing migration")
execute_sql(arguments.output_dir, arguments.dsn, arguments.execute, arguments.start_timeout or 300)
print("Executed %s successfully" % arguments.execute)
return 0
if arguments.dsn:
raise ValueError("--dsn is only valid with --execute")
starts = {}
if arguments.start_time is not None:
starts = {"__all__": parse_timestamp(arguments.start_time)}
elif arguments.task_start_time:
starts = task_start_times(arguments.task_start_time)
has_old_operation = any(old_operations)
output_exists = arguments.output_dir.exists()
if output_exists and not has_old_operation:
raise ValueError("output directory already exists; choose an operation or a new directory")
if arguments.stop_timeout is not None and not has_old_operation:
raise ValueError("--stop-timeout requires --stop-old, --delete-old or --stop-delete-old")
if arguments.sqlite and (has_old_operation or arguments.old_taosx_url):
raise ValueError("--sqlite cannot be combined with old task operations or --old-taosx-url")
old_url = arguments.old_taosx_url or "http://127.0.0.1:6050"
if has_old_operation and output_exists:
snapshot = read_json(arguments.output_dir / "tasks.json")
tasks, saved_times, saved_url = snapshot_data(snapshot)
if not saved_url:
raise ValueError("snapshot has no old service address; manual old-task operations are required")
if saved_url and arguments.old_taosx_url and saved_url.rstrip("/") != old_url.rstrip("/"):
raise ValueError("old taosX instance does not match the snapshot")
old_url = saved_url
if arguments.start_time is not None or arguments.task_start_time:
raise ValueError("start time options are only valid when generating a migration")
else:
if arguments.sqlite:
tasks = read_sqlite(arguments.sqlite)
old_url_for_snapshot = None
else:
tasks = read_api(old_url)
old_url_for_snapshot = old_url
selected = selected_tasks(tasks)
validate_task_ids(selected)
# Sort only new generations; existing snapshots retain their SQL order.
selected.sort(key=lambda task: task["id"])
explicit_starts = {} if "__all__" not in starts else {
str(task["id"]): starts["__all__"] for task in selected
}
if "__all__" not in starts:
explicit_starts = starts
create_sql, start_sql, _ = render_with_plans(selected, explicit_starts)
save_generation(arguments.output_dir, selected, explicit_starts, old_url_for_snapshot, create_sql, start_sql)
tasks, saved_times, saved_url = selected, explicit_starts, old_url_for_snapshot
if has_old_operation:
if arguments.sqlite:
raise ValueError("offline SQLite mode cannot operate old tasks")
if arguments.stop_old or arguments.stop_delete_old:
stop_old(arguments.output_dir, old_url, tasks, arguments.stop_timeout or 300)
if arguments.delete_old or arguments.stop_delete_old:
delete_old(arguments.output_dir, old_url, tasks)
print("Old task operation completed")
else:
print("Generated tasks.json, create.sql and start.sql in %s" % arguments.output_dir)
return 0
except (ValueError, OSError, sqlite3.Error, MigrationError) as error:
print("Migration failed: %s" % error, file=sys.stderr)
usage_error = any(marker in str(error) for marker in (
"cannot be combined", "mutually exclusive", "only valid", "requires --",
))
return 2 if usage_error else 1
if __name__ == "__main__":
sys.exit(main())
升级前操作
-
在线导出旧任务并生成迁移文件。脚本直接读取旧 taosX REST API,默认端口为
6050,无需手动导出 JSON。将示例中的开始时间替换为迁移前准备时确定的值:python3 migrate_active_active.py \
--old-taosx-url http://td-a:6050 \
--start-time '2026-11-06T10:00:00+08:00' \
--output-dir replica-migration-a如果各任务需要不同的开始时间,可以多次指定
--task-start-time TASK_ID=TIME,例如--task-start-time 7=1700000000000 --task-start-time 8=1700000001000。开始时间的继承规则见 脚本参数说明。也可以使用
--sqlite /backup/taosx.db从 SQLite 备份离线生成文件,无需连接旧服务。应使用实际配置的数据库路径,通过 SQLite 备份工具或在停止服务后制作一致性备份。服务运行时,直接复制单个.db文件可能遗漏 WAL 中的内容。以下示例与在线导出二选一:python3 migrate_active_active.py \
--sqlite /backup/taosx.db \
--start-time '2026-11-06T10:00:00+08:00' \
--output-dir replica-migration-a -
检查迁移目录中的
tasks.json、create.sql和start.sql,它们分别保存旧任务快照、创建语句和启动语句。核对任务范围、地址、库映射、凭据及开始时间。不同旧 taosX 实例的任务 ID 可能相同,因此每个实例应使用独立目录。脚本不会覆盖已有目录。脚本保留库映射、连接凭据和允许的调优参数,移除旧 DSN 中的系统保留参数,并生成新的任务名称。普通任务和已删除任务不参与迁移。不支持
auto.offset.reset=latest、VIA、自定义解析器或并行任务配置;遇到重复映射或不支持的参数时会报错,需人工核对旧配置。不要直接修改生成的迁移文件。脚本执行 SQL 前会检查 SQL 文件与任务快照是否一致,不一致时停止执行。
-
在线导出后,使用同一迁移目录执行以下命令,停止该旧实例的全部双活任务及关联的新库发现监控,并等待停止完成:
python3 migrate_active_active.py \
--output-dir replica-migration-a --stop-old --stop-timeout 300删除旧任务是可选操作,可根据回滚窗口安排。确认旧任务已停止后,可使用同一目录执行
--delete-old,删除快照中的全部旧双活任务及关联的新库发现配置:python3 migrate_active_active.py \
--output-dir replica-migration-a --delete-old脚本无法用离线生成的快照停止或删除旧任务,需按旧版本的运维方式手动完成这些操作。
-
所有旧实例都完成上述操作后,停止所有独立部署的旧 taosX 服务。随后按发布说明升级 taosd、taosX 和所需的 taosAdapter,准备数据库并注册 xnode,再执行升级后操作。
升级后操作
确认升级后的环境满足 迁移前准备 中的要求,再分别处理各旧实例生成的迁移目录。
可以使用脚本分步创建并启动新任务。--dsn 用于连接新管理集群,与任务 FROM、TO 中的源端、目标端连接配置相互独立:
python3 migrate_active_active.py \
--output-dir replica-migration-a \
--dsn 'ws://root:password@td-a:6041' --execute create
python3 migrate_active_active.py \
--output-dir replica-migration-a \
--dsn 'ws://root:password@td-a:6041' --execute start --start-timeout 300
--execute create 创建任务并核对配置;--execute start 先核对配置,再启动并等待任务进入 running。也可以使用 --execute all,在全部任务创建并核对成功后,再启动任务。脚本会核对任务名称、类型、连接配置和运行状态。
安全提示:迁移期间,--dsn 参数和脚本传给 taos 的 SQL 可能会将管理集群、源端和目标端的凭据暴露在进程参数或 Shell 历史记录中。请仅在受控的运维主机上运行脚本,并在迁移完成后按需轮换或撤销临时凭据。
管理集群开启 xnodeDsnProtection 时,脚本不能自动执行 SQL;如果无法确认配置状态,或存在待重启的配置变更,脚本也会拒绝执行。此时应由管理员按集群保护要求手动创建和核对任务,不要为运行脚本关闭保护。
也可以在选定的管理集群手动执行生成的 create.sql 和 start.sql。先检查 SQL,再执行创建文件,核对每个新任务的 type='replica' 和配置,最后执行启动文件,例如:
taos -h <管理集群主机> -f replica-migration-a/create.sql
SHOW XNODE TASKS WHERE type = 'replica';
taos -h <管理集群主机> -f replica-migration-a/start.sql
所有复制方向启动后,按 迁移后验证 检查同步结果。
失败处理与重试
手动执行 SQL 失败时,先核对已创建或已启动任务的配置和状态,再重试未完成的步骤,避免重复提交整批语句。
旧任务的操作结果和新任务的执行结果分别保存在 old-operations.json 和 new-operations.json 中。失败后,保留原迁移目录,查看结果、排除原因,再用同一目录重试失败的阶段。
重试 CREATE 时,脚本只跳过同名且配置完全一致的任务;重试 START 时,跳过已运行的任务,并继续等待已排队的任务。all 的 CREATE 阶段失败时不会执行 START,已创建或已启动的新任务不会自动回滚。
如果只删除了部分旧任务,也应使用原目录重试。如果任务缺失且原因不明,或出现配置变化、文件校验失败,应保留原快照、SQL 和操作记录,核对任务实际状态后再处理;不要清空记录、替换快照或修改文件绕过检查。
脚本参数说明
每次运行 migrate_active_active.py 处理一个旧 taosX 实例或一个新管理集群。不同旧实例应使用独立的输出目录。
| 参数 | 默认值或必填条件 | 适用阶段 | 说明 |
|---|---|---|---|
--output-dir DIR | 除查看帮助外必填 | 全部 | 迁移文件目录。生成文件时须使用尚不存在的目录;后续分步操作和执行 SQL 时使用原目录 |
--old-taosx-url URL | 生成时为 http://127.0.0.1:6050;分步操作继承快照地址 | 在线生成、旧任务操作 | 旧 taosX REST API 地址,支持 HTTP 和 HTTPS。分步操作须沿用快照中保存的地址。不能与 --sqlite 或 --execute 同用 |
--sqlite FILE | 不指定则在线读取 | 离线生成 | 从一致性 SQLite 备份生成迁移文件,不连接旧服务。不能与 --old-taosx-url、旧任务操作或 --execute 同用 |
--start-time TIME | 可选 | 生成 | 为所有迁移任务指定同一开始时间,覆盖 FROM DSN 的 msg.consume.start.ts。不能与 --task-start-time 同用 |
--task-start-time TASK_ID=TIME | 可选,可重复 | 生成 | 按旧任务 ID 指定开始时间,只覆盖列出的任务。重复 ID 或不属于本次迁移范围的 ID 会报错 |
--stop-old | 默认不停止 | 旧任务操作 | 停止快照中的全部旧任务及关联的新库发现监控,并等待停止。目录不存在时先在线生成迁移文件 |
--delete-old | 默认不删除 | 旧任务操作 | 先删除关联的新库发现配置,再删除快照中的全部旧任务。任务必须已停止;此参数不会自动停止任务 |
--stop-delete-old | 默认不停止或删除 | 旧任务操作 | 先停止快照中的全部旧任务,确认全部停止后再删除;停止失败或超时不会进入删除阶段 |
--stop-timeout SECONDS | 300 秒 | 旧任务操作的停止阶段 | 查询、停止监控和任务、等待停止的总超时时间,须大于 0。只能与旧任务操作参数一起提供;单独删除不使用此超时 |
--execute MODE | 默认不执行 SQL | 升级后执行 | create 执行 CREATE 并核对任务;start 先核对任务配置,再执行 START 并检查运行状态;all 先完成全部 CREATE 并核对成功,再执行 START。读取已有迁移目录,必须同时提供 --dsn |
--start-timeout SECONDS | 300 秒 | 新任务启动阶段 | 启动任务并等待全部进入 running 的总超时时间,须大于 0。仅适用于 --execute start 或 --execute all,不包括预检和创建阶段 |
--dsn DSN | 使用 --execute 时必填 | 升级后执行 | 新管理集群的连接 DSN,例如 ws://root:password@td-a:6041,与任务 FROM、TO 的业务连接分别配置 |
-h、--help | 无需其他参数 | 帮助 | 显示命令行帮助并退出,不生成文件或操作任务 |
参数组合与时间格式要求如下:
- 不指定旧任务操作或
--execute时,只生成文件。--stop-old、--delete-old、--stop-delete-old三者互斥,也都不能与--execute同用。使用已有目录操作旧任务时,不能再指定开始时间参数。 - 两种开始时间参数均支持带
Z或±HH:MM时区的 RFC 3339 时间,例如2026-11-06T10:00:00+08:00,小数秒最多三位;整数按 Unix 毫秒解释,不能为负数。 - 开始时间按“显式指定 > 旧 FROM DSN 值 > 新任务默认值”的优先级处理。未显式指定开始时间的任务会沿用旧 FROM DSN 的
msg.consume.start.ts,旧值须为非负整数形式的 Unix 毫秒时间戳;旧值不存在时,使用新任务默认值0,即不按时间过滤。 - 显式指定
--start-time 0或--task-start-time TASK_ID=0会覆盖旧值并关闭时间过滤。最终生效的非零开始时间不能与非零msg.consume.rawdata共用。 - 继承时间过滤条件不代表继承旧 topic、消费组或消费位点,可读取范围仍受快照、数据保留和 WAL 保留情况限制。
迁移后验证
无论选择手动迁移还是脚本迁移,都需要对每个复制方向完成以下检查:
- 通过
SHOW XNODE TASKS WHERE type = 'replica';核对任务数量、源库到目标库的映射、type='replica'和运行状态,确认每个预期的复制方向都有对应的任务,且任务已经启动。 - 按 查看同步进度 中的方法,使用新任务的
__replica__<管理集群 ID>_<任务 ID>标识查询各 vgroup 的进度,确认任务持续复制并逐步追平。 - 核对同步开始时间边界、表结构和实际数据,确认迁移前后没有遗漏需要复制的数据。生成 SQL 成功、任务显示
running或消费位点追平,都不能单独证明没有丢数;数据已不在可读取的快照或 WAL 中时,需要另行补数。 - 所有方向均追平且数据验证通过后,将 WAL 保留时长恢复为原值。确认旧任务全部停止、旧 topic 无其他业务使用后,再按 v3.3 的运维方式另行清理旧资源;删除新任务不会清理旧资源。
已同步且位于开始时间之后的数据可能被重放;同时间戳覆盖及元数据幂等重放避免重复行。新任务不自动恢复旧版本的新库发现规则,后续新增数据库时仍需按库创建双活任务。








