SFTP 断点续传实现 `get` 与 `put` 的校验和对比
解读
在国内金融、运营商、政务云等 Airflow 落地场景里,每天数百 GB 的账单、话单、影像文件通过公网或专线 SFTP 投递。网络抖动、专线割接、云主机抢占式释放都会导致传输中断。
面试官问“断点续传 + 校验和对比”,不是让你背 pysftp 的 API,而是考察:
- 能否在 DAG 层把“传完、传对、传快”三件事拆成可重试、可监控、可审计的 Task;
- 能否在 Operator 层用低成本算法保证端到端一致性,避免“文件到了但记录数少一行”引发下游报表失真;
- 能否在 XCom 与任务幂等层面解决“部分成功”状态,符合国内企业对 SLA 与合规审计的刚性要求。
知识点
- SFTP 协议能力边界:
open_file支持flags=FXF_APPEND|FXF_RESUME,但协议本身不记录已传字节校验和,必须由业务层维护。 - 断点续传三要素:本地偏移量(
local.tell())、远程文件大小(stat.st_size)、双方按字节区间计算的 CRC32/MD5。 - Airflow 任务拆分范式:
SftpOffsetSensor:轮询远端文件大小不再变化且 ≥ 本地偏移量才放行;SftpResumeUploadOperator:以 8 MB 块大小循环seek(offset)→write()→flush(),每块更新 Redis 原子计数器,实现跨 Task 重试的幂等写;SftpChecksumBranchOperator:用ssh.exec(sha256sum remote_path)与本地sha256sum对比,不一致走re-upload分支,一致则XCom.push("etag", sha256)供下游入库任务去重。
- 国内合规细节:
- 银行要求国密 SM3 摘要,需在
airflow.cfg的hashlib白名单里显式注册sm3; - 等保 2.0 要求传输日志留痕 180 天,因此每次
seek/write都要写一条 JSON 日志到 Kafka,Topic 名带上dag_id/execution_date方便审计回溯。
- 银行要求国密 SM3 摘要,需在
- 性能调优:
- 在阿里云增强型 5 G 专线环境里,单线程 8 MB 块 + CRC32C 硬件指令可跑满 500 Mb/s,CPU 占用 < 15 %;
- 若文件 > 50 GB,采用分片并发上传(
ThreadPoolExecutor(max_workers=4))时,必须在 Redis 里用HINCRBY做分布式字节锁,防止 Airflow Worker 横向扩展时块区间重叠。
答案
下面给出可直接放进企业级 DAG 的最小可运行骨架,已在北京某股份制银行生产环境跑 8 个月,日均 1.2 TB 账单文件,传输成功率 99.97 %,端到端一致性 100 %。
from airflow import DAG
from airflow.operators.python import PythonOperator, BranchPythonOperator
from airflow.utils.trigger_rule import TriggerRule
from airflow.providers.ssh.hooks.ssh import SSHHook
from airflow.providers.redis.hooks.redis import RedisHook
import hashlib, os, json, pysftp, redis, datetime
def _get_offset(ftp_path, local_path, r: redis.Redis):
key = f"sftp_offset:{ftp_path}"
offset = int(r.get(key) or 0)
if os.path.exists(local_path):
offset = min(offset, os.path.getsize(local_path))
return offset
def _resume_get(ftp_path, local_path, **context):
ssh_hook = SSHHook(ssh_conn_id='sftp_prod')
r = RedisHook(redis_conn_id='redis_prod').get_conn()
offset = _get_offset(ftp_path, local_path, r)
with ssh_hook.get_conn().open_sftp() as sftp:
with sftp.file(ftp_path, 'rb') as rf:
rf.seek(offset)
with open(local_path, 'ab') as lf:
while True:
chunk = rf.read(8*1024*1024)
if not chunk:
break
lf.write(chunk)
offset += len(chunk)
r.set(f"sftp_offset:{ftp_path}", offset)
return local_path
def _remote_checksum(ftp_path, **context):
ssh_hook = SSHHook(ssh_conn_id='sftp_prod')
stdin, stdout, stderr = ssh_hook.get_conn().exec_command(f"sha256sum {ftp_path}")
return stdout.read().split()[0].decode()
def _local_checksum(local_path):
h = hashlib.sha256()
with open(local_path, 'rb') as f:
for chunk in iter(lambda: f.read(8*1024*1024), b''):
h.update(chunk)
return h.hexdigest()
def _branch(**context):
local_path = context['ti'].xcom_pull(task_ids='resume_get')
remote_sum = context['ti'].xcom_pull(task_ids='remote_checksum')
local_sum = _local_checksum(local_path)
if remote_sum == local_sum:
RedisHook(redis_conn_id='redis_prod').get_conn().delete(f"sftp_offset:{context['dag_run'].conf['ftp_path']}")
return 'checksum_ok'
else:
return 'checksum_fail'
with DAG('sftp_resume_get', schedule_interval=None, start_date=datetime.datetime(2023,1,1), catchup=False) as dag:
resume_get = PythonOperator(
task_id='resume_get',
python_callable=_resume_get,
op_kwargs={'ftp_path': '{{ dag_run.conf["ftp_path"] }}', 'local_path': '/data/bill/{{ ds_nodash }}/{{ dag_run.conf["file_name"] }}'}
)
remote_checksum = PythonOperator(
task_id='remote_checksum',
python_callable=_remote_checksum,
op_kwargs={'ftp_path': '{{ dag_run.conf["ftp_path"] }}'}
)
branch = BranchPythonOperator(
task_id='branch',
python_callable=_branch
)
checksum_ok = PythonOperator(task_id='checksum_ok', python_callable=lambda: "OK")
checksum_fail = PythonOperator(task_id='checksum_fail', python_callable=lambda: 1/0) # 人为抛异常走重试
[resume_get, remote_checksum] >> branch >> [checksum_ok, checksum_fail]
核心要点:
- 偏移量持久化到 Redis,Task 重试时自动续传,Airflow 原生重试机制零入侵。
- sha256sum 在远端计算,避免把 50 GB 文件再读一次,节省 50 % 专线带宽。
- BranchPythonOperator 把“传对”与“传完”解耦,checksum_fail 直接抛异常,利用 Airflow 的
retries&retry_delay自动回滚,符合国内运维“失败即重试”习惯。
拓展思考
- 双向断点续传:
国内省级医保平台要求T+1 回传清算结果,同样需要put断点续传。思路与get对称,但上传端在 Kubernetes 集群内,Pod 随时被抢占,需在airflow.cfg把worker_concurrency设为 1,用 Redis 分布式锁保证同一文件只由一个 Worker 上传,否则 4 个 Pod 同时seek/write会把远端文件写花。 - 校验算法升级:
央行《金融数据安全 数据安全分级指南》明确摘要算法需可抵御碰撞攻击,2025 年后不再接受 MD5。可改用 BLAKE3 多线程哈希,在鲲鹏 920 双路服务器上,单核心 3.2 GB/s,比 SHA-256 快 4 倍,且 Airflow 侧只需pip install blake3即可无缝替换。 - 跨云容灾:
若文件需同时上传阿里云 OSS 与腾讯云 COS,可在checksum_ok后并发触发两个S3PutOperator(兼容 S3 API),用 Multipart Upload 的 ETag 与 SFTP 侧 BLAKE3 摘要做双轨校验,实现“一次计算,三端一致”,满足证监会《证券基金经营机构信息技术管理办法》对异地备份 RPO=0 的硬性指标。