深入浅出etcd--02 接口与功能

软件开发是将人类心智模型投影到代码空间的过程,先有功能,再设计结构。探索项目时理解作者的用意和trade-off最为重要。
本文基于etcd 3.6.5源码与官方文档,先从设计目标谈起,梳理etcd的项目定位与数据模型,再拆解衍生出来的三大核心功能(KV、Watch、Lease)。其实是两大核心功能: KV + Watch。Watch是核心中的核心,Lease就一笔带过了。

重在分析思路,etcd的代码非常工业化,写得很细碎,需要浓缩一下。

写完文章试了试Gemini Carbon,让它优化了文字排版和内容布局,Gemini对于文本的理解还是太强了。

项目定位与数据模型

Data model | etcd 文档开头开宗明义介绍了etcd的定位,划重点:

  1. etcd是持久化、多版本的存储,每次写入都追加创建新版本而非原地覆盖,依赖定期压缩(Compaction)清理历史空间;
  2. 面向低频变更的元数据设计,提供可靠高效的变更推送机制(Watch),并原生支持时间旅行查询(获取任意未被压缩的历史版本数据)。
  3. etcd是为能在内存全量存储的少量数据设计的强一致分布式KV。

etcd is designed to reliably store infrequently updated data and provide reliable watch queries. etcd exposes previous versions of key-value pairs to support inexpensive snapshots and watch history events (“time travel queries”). A persistent, multi-version, concurrency-control data model is a good fit for these use cases.

etcd stores data in a multiversion persistent key-value store. The persistent key-value store preserves the previous version of a key-value pair when its value is superseded with new data. The key-value store is effectively immutable; its operations do not update the structure in-place, but instead always generate a new updated structure. All past versions of keys are still accessible and watchable after modification. To prevent the data store from growing indefinitely over time and from maintaining old versions, the store may be compacted to shed the oldest versions of superseded data.

etcd is a consistent distributed key-value store. Mainly used as a separate coordination service, in distributed systems. And designed to hold small amounts of data that can fit entirely in memory

时间旅行(Time Travel) 就是etcd区别于其他分布式存储的最大特点,即对外暴露获取给定逻辑时间戳(Revision)之后所有有序变更事件的能力。通常而言,ZooKeeper、Consul乃至TiKV / Spanner等系统,要么只提供针对单个键的一次性变更通知,要么将多版本时间戳隐藏在引擎内部不向用户暴露。

换句话说,功能决定了结构:etcd必须同时高效支撑两种截然不同的访问轴:

  1. 按键空间(Key Space)访问:给定Key或[Key, RangeEnd)区间,配合可选的历史版本号读取键值;
  2. 按时间轴(Revision Space)访问:给定起始Revision,顺序拉取此后发生的一连串历史变更事件。

Revision是etcd维护的 64 位全局计数器,对外暴露为单调递增的逻辑时钟。每当发生一次修改状态机的写事务,Revision就递增1;由于etcd底层使用单Raft组串行提交并应用日志,Revision在时间线上是严格连续的。

为了兼顾这两个维度,etcd采用了极具辨识度的双层索引存储模型:

  • 磁盘物理存储(bbolt)以 Revision 为主键:维护 (MainRevision, SubRevision, TombstoneFlag) -> KeyValue 的单写多读 B+ 树;
  • 内存索引(treeIndex)以用户 Key 为主键:维护 Key -> keyIndex(Generations -> Revisions) 的内存 B 树,加速键空间寻址。

这种布局背后的 trade-off 非常鲜明:

  • 一次单点Get(key)实际上对应两次查找(先查内存treeIndex拿到目标Revision,再去bbolt点查物理记录);一次逻辑上的Range(KeyPrefix)顺序扫描,在磁盘上会被放大为多次离散的Revision点查。
  • 作为交换,etcd换来了极致的连续历史事件扫描性能——无论是慢速Watch断线重连追赶(如Watch(start_revision=100)),还是后台按时间窗口裁剪历史(Compact(compact_rev=10000)),落到底层bbolt上都退化为一次极其廉价的顺序范围扫描。

由于Key -> Revision的映射只存在于内存中,崩溃重启时必须全表扫描bbolt重建内存树,所以持久化的KeyValue结构体里必须冗余存一份完整的key:

1
2
3
4
5
6
7
8
message KeyValue {
bytes key = 1;
int64 create_revision = 2;
int64 mod_revision = 3;
int64 version = 4;
bytes value = 5;
int64 lease = 6;
}
  1. mod_revision是写入该版本时的全局Revision,直接对应底层物理存储的主键;
  2. create_revision与version联合服务于生命周期(Generation)管理。etcd的删除操作不会立刻抹除旧记录,而是追加写入一条带墓碑标记('t')的空值记录,真正的物理清理留到Compact阶段异步完成。如果一个Key被删后再次同名创建,单靠重置为1的version无法区分首次创建与重建,因此引入create_revision锚定每一代生命周期的起点:
    • 假设起始全局Revision = 4:
    • Put("foo", "bar") $\rightarrow$ KeyValue{create=5, mod=5, version=1}(开启第 0 代)
    • Put("foo", "barbar") $\rightarrow$ KeyValue{create=5, mod=6, version=2}
    • Del("foo") $\rightarrow$ 写入墓碑 {main=7, sub=0, tombstone},关闭第 0 代,对外返回不存在
    • Put("foo", "bbb") $\rightarrow$ KeyValue{create=8, mod=8, version=1}(开启全新的第 1 代,与历史彻底隔离)

功能接口

核心功能接口见 etcd API guarantees | etcd 所讲,围绕同一套 MVCC 存储提供三种能力:

  1. **KV**:基础底座,提供线性一致的读、改、删、压缩与乐观锁事务;
  2. **Watch**:建立在 MVCC 历史窗口之上的订阅推送引擎;
  3. **Lease**:建立在共识状态机与内存定时器之上的对象级 TTL 生命周期管理。

KV API allows for direct reading and manipulation of key value store.
Watch API allows subscribing to key value store changes.
Lease API allows assigning a time to live to a key.
Both KV and Watch APIs allow access to not only the latest versions of keys, but also previous versions are accessible within a continuous history window, limited by a compaction operation.

KV

客户端接口定义如下,具体参数配置见 etcd API | etcd:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type KV interface {
// Put puts a key-value pair into etcd.
Put(ctx context.Context, key, val string, opts ...OpOption) (*PutResponse, error)

// Get retrieves keys.
// By default, Get will return the value for "key", if any.
// When passed WithRange(end), Get will return the keys in the range [key, end).
// When passed WithRev(rev) with rev > 0, Get retrieves keys at the given revision;
// if the required revision is compacted, the request will fail with ErrCompacted.
Get(ctx context.Context, key string, opts ...OpOption) (*GetResponse, error)

// Delete deletes a key, or optionally using WithRange(end), [key, end).
Delete(ctx context.Context, key string, opts ...OpOption) (*DeleteResponse, error)

// Compact compacts etcd KV history before the given rev.
Compact(ctx context.Context, rev int64, opts ...CompactOption) (*CompactResponse, error)

// Do applies a single Op on KV without a transaction.
Do(ctx context.Context, op Op) (OpResponse, error)

// Txn creates a transaction.
Txn(ctx context.Context) Txn
}

对外暴露的Put和Delete本质上只是单操作语法糖,事务(Txn)才是整个KV写路径的核心抽象。
etcd没有提供传统关系型数据库交互式的Begin / Commit / Rollback多轮会话事务,而是提供单次往返的原子 If - Then - Else(CAS) 原语:检查一组条件谓词,全部满足则原子执行Then分支,否则执行Else分支;分支内部可以组合Range / Put / DeleteRange甚至嵌套子Txn:

1
2
3
4
5
6
7
8
Txn(context.TODO()).If(
Compare(Value(k1), ">", v1),
Compare(Version(k1), "=", 2),
).Then(
OpPut(k2, v2), OpPut(k3, v3),
).Else(
OpPut(k4, v4), OpPut(k5, v5),
).Commit()
  • 5 种比较目标(CompareTarget):
    • VALUE:按字节序比较当前键值内容(bytes.Compare)
    • **VERSION**:比较键在当前存活代际内的修改次数(删除重建会归零重计)
    • **CREATE**:比较键的CreateRevision(常用于= 0判断键尚未存在)
    • **MOD**:比较键最后一次修改的ModRevision(实现无锁乐观并发控制最核心的凭据)
    • **LEASE**:比较键当前绑定的LeaseID
  • 4 种比较操作符(CompareResult):EQUAL(=)、NOT_EQUAL(!=)、GREATER(>)、LESS(<)。
  • 合取逻辑(AND):TxnRequest.Compare列表中的所有条件必须同时为真,Succeeded才为true。

为了防止恶意的超大事务长时间独占阻塞Raft单线程Apply循环,服务端默认限制单个事务内最多包含 128 个操作(--max-txn-ops=128,其中一次DeleteRange算作一个操作);同时规定同一执行分支内不允许对同一个 Key 多次修改(checkIntervals校验,违者直接拒绝返回ErrGRPCDuplicateKey),确保一个Key在同一个主Revision下最多产生一次状态变更。

回过头再看物理存储主键(MainRevision, SubRevision, Op)的三元组设计就清晰了:

  • MainRevision标识本次写事务的全局时间戳
  • 若单次Txn批量写入了多个不同的Key,它们共享同一个MainRevision,靠单调递增的事务内序号SubRevision(0, 1, 2...)区分先后顺序
  • Op(可选't'后缀)则用于标记删除墓碑。

事务设计的最精妙之处是借用了Fencing Token的思想,通过条件比较来消除分布式系统中悬而未决的状态,使得客户端在收到Unknown错误码时可以幂等地重试。
比如:

  1. 写请求处理完毕返回响应时丢失,客户端超时
  2. raft propose时发生Leader切换,无法确定该请求是否被执行
  3. raft entry apply时卡死导致超时

客户端只需要重新执行一遍事务,只要上次成功执行,那么Compare(Mod == x)就会失效从而返回已存在,如果上次执行失败,那么本次可以顺利执行。不需要付出任何额外的开销就实现了幂等写入。

Watch

API 保证

Watch并非简单的“尽力而为”广播,官方文档对事件流做出了严格的六项契约保证:

  • 有序(Ordered):事件严格按revision单调递增投递;已投递高版本事件后,绝不会再冒出更早版本的事件。不含嵌套事务时,同一事务内的多键事件顺序与请求操作顺序一致。
  • 唯一(Unique):同一个历史事件绝不会在同一条watcher中重复投递。
  • 可靠(Reliable):在未被压缩的历史窗口内,事件序列绝不会出现空洞(收到a和c,只要b未压缩就必然先收到b)。
  • 原子(Atomic):同一个revision内产生的所有匹配事件保证打包在同一次WatchResponse中完整送达,绝不跨包撕裂(开启大包fragment分片时除外,此时通过Fragment=true标志提示客户端重组)。
  • 可恢复(Resumable):流中断后,客户端只需携带上次收到的最大revision + 1重新建立Watch,只要未落后于压缩线即可无缝续传。
  • 可书签化(Bookmarkable):开启进度通知(progress_notify)后,一条Events为空的响应向客户端承诺“截至header.revision为止的所有匹配变更均已投递完毕”。

总结一下:

  1. 在etcd的有效时间窗口内,Watch可以保证按序、可恢复的投递事件。
  2. 即使一段时间内没有事件产生,也可以推进Watch水位。

注意:周期性推进Bookmark水位是为了防止低频变更的订阅者本地水位与集群最新Revision拉开几十万的差距——否则一旦短线重连,要么早已被Compact清理报ErrCompacted被迫全量扫库,要么让服务端扫描跨度过大的历史区间。

分析思路

理解Watch实现,从两方面入手:

  • 一条 gRPC 连接如何复用管理成百上千个Watcher订阅(网络层)
  • 快慢悬殊的消费者如何做到既不丢历史事件、又绝不阻塞 Raft 写状态机(存储层)。

先看协议定义。Watch是一条标准的 gRPC 双向流,输入流承载控制命令(创建订阅Create、取消订阅Cancel、主动索要进度水位Progress),输出流源源不断推送事件与控制响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
service Watch {
rpc Watch(stream WatchRequest) returns (stream WatchResponse) {}
}

message WatchRequest {
oneof request_union {
WatchCreateRequest create_request = 1;
WatchCancelRequest cancel_request = 2;
WatchProgressRequest progress_request = 3;
}
}

message WatchResponse {
ResponseHeader header = 1;
int64 watch_id = 2;
bool created = 3;
bool canceled = 4;
int64 compact_revision = 5;
string cancel_reason = 6;
bool fragment = 7;
repeated mvccpb.Event events = 11;
}

实现Watch功能重点围绕接收请求的recvLoop和发送响应的sendLoop展开。再穿插一点工程优化,如数据批量处理、过滤事件、管道背压就搞定了。

结合完整的服务端数据流与状态切换图,我们自底向上拆解server/storage/mvcc与server/etcdserver/api/v3rpc/watch.go的协作机制。重点放在两个问题上:

  1. Watch事件从哪里来?如何传递给网络层
  2. 订阅请求从哪里来?如何管理多个Watcher

事件发送链路

先顺着图片的左上角一路向下看:回答事件从哪里来的问题。事件描述的是数据变更,很容易想到两种处理方式:

  1. 记录一个时间戳Rev,周期性地扫描自时间戳Rev之后的KeyValue,然后封装为事件
  2. 每次事务写入完毕后,推送给Watcher,实时产生

etcd选择实时产生的方式来获取最佳的Watch性能,官方文档中提到etcd API guarantees | etcd Watch延迟一般在10ms,实际上会更快,k8s完整性测试甚至要求5ms内推送。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
message Event {
enum EventType {
PUT = 0;
DELETE = 1;
}
// type is the kind of event. If type is a PUT, it indicates
// new data has been stored to the key. If type is a DELETE,
// it indicates the key was deleted.
EventType type = 1;
// kv holds the KeyValue for the event.
// A PUT event contains current kv pair.
// A PUT event with kv.Version=1 indicates the creation of a key.
// A DELETE/EXPIRE event contains the deleted key with
// its modification revision set to the revision of deletion.
KeyValue kv = 2;
// prev_kv holds the key-value pair before the event happens.
KeyValue prev_kv = 3;
}

Event描述keyValue变更类型,最新数据,上个版本的数据。每当事务watchableStoreTxnWrite完成后都会调用End函数来转换事件,然后通知watchableStore。

1
2
3
4
5
6
7
8
9
10
11
12
rev := tw.Rev() + 1
evs := make([]mvccpb.Event, len(changes))
for i, change := range changes {
evs[i].Kv = &changes[i]
if change.CreateRevision == 0 {
evs[i].Type = mvccpb.DELETE
evs[i].Kv.ModRevision = rev
} else {
evs[i].Type = mvccpb.PUT
}
}
tw.s.notify(rev, evs)

watchableStore管理全局所有的watcher,一个watcher对应一个待监听的Key或者KeyRange以及监听进度、标识位等。每个watcher持有对应的发送管道从而将数据传递给创建它的gRPC流。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type watcher struct {
key []byte
end []byte
// victim is set when ch is blocked and undergoing victim processing
victim bool
// compacted is set when the watcher is removed because of compaction
compacted bool
startRev int64
// minRev is the minimum revision update the watcher will accept
minRev int64
id WatchID
fcs []FilterFunc
// a chan to send out the watch response.
// The chan might be shared with other watchers.
ch chan<- WatchResponse
}

notify函数会同步等待将事件包装为WatchResponse发送给所有、满足条件的watcher,此时代码依然在事务执行的路径上哦,只要有一个客户端网络卡死,会阻塞etcd的串行写循环从而导致系统卡死。因此一定要在事件发送路径上做背压和分级。

1
2
3
4
5
6
7
8
9
if w.send(WatchResponse{WatchID: w.id, Events: eb.evs, Revision: rev}) {
pendingEventsGauge.Add(float64(len(eb.evs)))
} else {
// w.ch 已满!绝不阻塞写协程,立刻打上 victim 标记踢出 synced 池
w.victim = true
victim[w] = eb
s.synced.delete(w)
}
w.minRev = rev + 1

为此,watchableStore(watchable_store.go)将所有活跃的watcher精巧地划分进三个状态池:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type watchableStore struct {
*store
mu sync.RWMutex

// 写入 w.ch 受阻的慢 watcher 暂存批次,避免阻塞写主路径
victims []watcherBatch
victimc chan struct{}

// 尚未追平当前 currentRev、需要从历史 bbolt 补课的 watcher 集合
unsynced watcherGroup
// 已经追平 currentRev、直接挂载在实时写路径上接收推送的 watcher 集合
synced watcherGroup
// ...
}

这里面用watcherGroup组织订阅者也很讲究:

  • 针对单键订阅直接放进哈希表keyWatchers以O(1)查找;
  • 针对前缀或区间订阅[key, end)则插入一棵红黑区间树(IntervalTree),在写事务产生变更时以O(log N)快速找出所有覆盖该键的订阅者。
    关于三种状态的转换我们后续再讨论,先顺着图片继续往下,看事件传递到最新进度的watcher后最终在哪里被消费。

watchStream(watcher.go)是单条 gRPC 流在存储层的代理:同一条连接上创建的几百个WatchID共享同一个容量 128 的ws.ch通道,负责分配流内递增的WatchID并代理Cancel和RequestProgress。
serverWatchStream(v3rpc/watch.go)则启动一对经典的 recvLoop + sendLoop 协程对接网络流。

响应通过watcher创建时指定的通道传递到sendLoop,代码很细,但实际上做的事情很简单:

  1. 检查一些标志位:要不要读prev_kv,要的话直接从mvcc.Range读; Watcher监听的数据是否被压缩了,被压缩的话设置标志位,客户端自行从新进度重新创建watcher
  2. 检查watcher创建后是否发送过成功创建响应,没有的话,缓存这批事件,等创建成功发送了再发
  3. 检查标志位,设置了分片的话,分批次传,否则直接传
  4. 近期发送过事件的watcher,不需要再发progress推高水位
    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
    func (sws *serverWatchStream) sendLoop() {
    // watch ids that are currently active
    ids := make(map[mvcc.WatchID]struct{})
    // watch responses pending on a watch id creation message
    pending := make(map[mvcc.WatchID][]*pb.WatchResponse)
    for {
    select {
    case wresp, ok := <-sws.watchStream.Chan():
    if !ok {
    return
    }
    // 检查一些标识位
    evs := wresp.Events
    events := make([]*mvccpb.Event, len(evs))
    sws.mu.RLock()
    needPrevKV := sws.prevKV[wresp.WatchID]
    sws.mu.RUnlock()

    for i := range evs {
    events[i] = &evs[i]
    if needPrevKV && !IsCreateEvent(evs[i]) {
    opt := mvcc.RangeOptions{Rev: evs[i].Kv.ModRevision - 1}
    r, err := sws.watchable.Range(context.TODO(), evs[i].Kv.Key, nil, opt)
    if err == nil && len(r.KVs) != 0 {
    events[i].PrevKv = &(r.KVs[0])
    }
    }
    }

    canceled := wresp.CompactRevision != 0
    wr := &pb.WatchResponse{
    Header: sws.newResponseHeader(wresp.Revision),
    WatchId: int64(wresp.WatchID),
    Events: events,
    CompactRevision: wresp.CompactRevision,
    Canceled: canceled,
    }

    // Progress notifications can have WatchID -1
    // if they announce on behalf of multiple watchers
    if wresp.WatchID != clientv3.InvalidWatchID {
    if _, okID := ids[wresp.WatchID]; !okID {
    // buffer if id not yet announced
    wrs := append(pending[wresp.WatchID], wr)
    pending[wresp.WatchID] = wrs
    continue
    }
    }

    sws.mu.RLock()
    fragmented, ok := sws.fragment[wresp.WatchID]
    sws.mu.RUnlock()

    var serr error
    // gofail: var beforeSendWatchResponse struct{}
    if !fragmented && !ok {
    serr = sws.gRPCStream.Send(wr)
    } else {
    serr = sendFragments(wr, sws.maxRequestBytes, sws.gRPCStream.Send)
    }

    sws.mu.Lock()
    if len(evs) > 0 && sws.progress[wresp.WatchID] {
    // elide next progress update if sent a key update
    sws.progress[wresp.WatchID] = false
    }
    sws.mu.Unlock()
    }
    }
    }
    除了数据流之外,发送管理流的响应(比如创建watcher成功,取消watcher成功)等由sendLoop的ctrlStream分支触发
    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
    case c, ok := <-sws.ctrlStream:
    if err := sws.gRPCStream.Send(c); err != nil {
    ///
    }
    // track id creation
    wid := mvcc.WatchID(c.WatchId)
    if c.Canceled && wid != clientv3.InvalidWatchID {
    delete(ids, wid)
    continue
    }
    if c.Created {
    // flush buffered events
    ids[wid] = struct{}{}
    for _, v := range pending[wid] {
    if err := sws.gRPCStream.Send(v); err != nil {
    ///
    }
    }
    delete(pending, wid)
    }

    case <-progressTicker.C:
    sws.mu.Lock()
    for id, ok := range sws.progress {
    if ok {
    sws.watchStream.RequestProgress(id)
    }
    sws.progress[id] = true
    }
    sws.mu.Unlock()

控制管理链路

从数据流动图右下角看齐,recvLoop其实比较无聊,大概就是:

  1. 接收到WatchCreate/WatchCancel/Progress请求,检查一些参数,将请求传递给watchableStore用于在内存中创建watcher,取消watcher
  2. 将响应传递给ctrlStream,然后由sendLoop发送响应

状态转换

对应图片中间的部分
watchableStore有两个后台协程:

  • syncWatchersLoop: 处理落后的watcher,每 100ms 扫描一次unsynced池,每轮最多挑出maxWatchersPerSync = 512个最落后的订阅者,算出它们最小的起始水位minRev;批量扫描数据转换为Event然后尝试发送,发送成功且追上进度转换为synced,发送失败降级为victims。如果数据被压缩,向其通道投递携带CompactRevision = compactMainRev的响应并将其彻底移除
  • syncVictimsLoop: 处理慢发送者,每10ms唤醒一次,遍历列表尝试把积压的事件传递给通道;一旦发送成功就进行状态转换:如果watcher进度落后最新进度,转换为unsynced watcher;否则转换为synced watcher

小细节:etcd不会在创建Watcher时检测Compact Rev,因此使用压缩的时间戳创建Watcher,会先收到创建成功响应,随后收到取消响应

Lease

实现起来太细碎了,k8s用的不多,实现etcd-shim时不是重点,此处不多赘述,如果希望学习,推荐去看Etcd教程(十)—Lease 机制源码分析 - 探索云原生 或者和AI一起讨论

小结

回顾整篇分析,从功能定位到代码落地的脉络非常清晰:

  • 因为定位是“低频配置存储 + 可靠历史变更流”,etcd选择了以全局递增 Revision 为磁盘主键 + 内存 Key 树二级索引的持久化多版本数据模型;
  • 在此之上,KV通过原子If-Then-Else事务暴露ModRevision,用极简协议同时搞定了乐观锁并发与客户端无状态幂等写;
  • Watch借助synced / unsynced / victims三态转换与非阻塞降级,在充分利用bbolt按版本顺序扫描优势的同时,将慢客户端彻底隔离在写状态机之外;

参考文献

  1. FAQ | etcd v3.6
  2. Data model | etcd v3.6
  3. etcd API guarantees | etcd v3.6
  4. etcd API Reference | etcd v3.6
  5. Etcd教程(十)—Lease 机制源码分析 - 探索云原生