etcdctl工具介紹

今夕何兮發表於2024-06-06

1. etcdctl介紹

etcdctl是與etcd伺服器互動的命令列工具,etcdctl 用於與 etcd 通訊的 API 版本可以透過 ETCDCTL_API 環境變數設定為版本 2 或 3 。預設情況下,3.4主版本以上的 etcdctl 使用 v3 API,早期版本(3.3 及更早版本)預設使用 v2 API。export ETCDCTL_API=3控制使用v3 api版本,版本查詢

$ etcdctl version
etcdctl version: 3.5.4
API version: 3.5

2. etcdctl 命令

etcdctl 有很多子命令,具體功能可以透過etcdctl -h 命令查詢:

etcdctl -h 執行結果
NAME:
	etcdctl - A simple command line client for etcd3.

USAGE:
	etcdctl [flags]

VERSION:
	3.5.4

API VERSION:
	3.5


COMMANDS:
	alarm disarm		Disarms all alarms
	alarm list		Lists all alarms
	auth disable		Disables authentication
	auth enable		Enables authentication
	auth status		Returns authentication status
	check datascale		Check the memory usage of holding data for different workloads on a given server endpoint.
	check perf		Check the performance of the etcd cluster
	compaction		Compacts the event history in etcd
	defrag			Defragments the storage of the etcd members with given endpoints
	del			Removes the specified key or range of keys [key, range_end)
	elect			Observes and participates in leader election
	endpoint hashkv		Prints the KV history hash for each endpoint in --endpoints
	endpoint health		Checks the healthiness of endpoints specified in `--endpoints` flag
	endpoint status		Prints out the status of endpoints specified in `--endpoints` flag
	get			Gets the key or a range of keys
	help			Help about any command
	lease grant		Creates leases
	lease keep-alive	Keeps leases alive (renew)
	lease list		List all active leases
	lease revoke		Revokes leases
	lease timetolive	Get lease information
	lock			Acquires a named lock
	make-mirror		Makes a mirror at the destination etcd cluster
	member add		Adds a member into the cluster
	member list		Lists all members in the cluster
	member promote		Promotes a non-voting member in the cluster
	member remove		Removes a member from the cluster
	member update		Updates a member in the cluster
	move-leader		Transfers leadership to another etcd cluster member.
	put			Puts the given key into the store
	role add		Adds a new role
	role delete		Deletes a role
	role get		Gets detailed information of a role
	role grant-permission	Grants a key to a role
	role list		Lists all roles
	role revoke-permission	Revokes a key from a role
	snapshot restore	Restores an etcd member snapshot to an etcd directory
	snapshot save		Stores an etcd node backend snapshot to a given file
	snapshot status		[deprecated] Gets backend snapshot status of a given file
	txn			Txn processes all the requests in one transaction
	user add		Adds a new user
	user delete		Deletes a user
	user get		Gets detailed information of a user
	user grant-role		Grants a role to a user
	user list		Lists all users
	user passwd		Changes password of user
	user revoke-role	Revokes a role from a user
	version			Prints the version of etcdctl
	watch			Watches events stream on keys or prefixes

OPTIONS:
      --cacert=""				verify certificates of TLS-enabled secure servers using this CA bundle
      --cert=""					identify secure client using this TLS certificate file
      --command-timeout=5s			timeout for short running command (excluding dial timeout)
      --debug[=false]				enable client-side debug logging
      --dial-timeout=2s				dial timeout for client connections
  -d, --discovery-srv=""			domain name to query for SRV records describing cluster endpoints
      --discovery-srv-name=""			service name to query when using DNS discovery
      --endpoints=[127.0.0.1:2379]		gRPC endpoints
  -h, --help[=false]				help for etcdctl
      --hex[=false]				print byte strings as hex encoded strings
      --insecure-discovery[=true]		accept insecure SRV records describing cluster endpoints
      --insecure-skip-tls-verify[=false]	skip server certificate verification (CAUTION: this option should be enabled only for testing purposes)
      --insecure-transport[=true]		disable transport security for client connections
      --keepalive-time=2s			keepalive time for client connections
      --keepalive-timeout=6s			keepalive timeout for client connections
      --key=""					identify secure client using this TLS key file
      --password=""				password for authentication (if this option is used, --user option shouldn't include password)
      --user=""					username[:password] for authentication (prompt if password is not supplied)
  -w, --write-out="simple"			set the output format (fields, json, protobuf, simple, table)

etcdctl命令選項介紹:

# 全域性選項,所有子命令生效
--cacert= 使用此CA捆綁包驗證啟用TLS的安全伺服器的證書
--cert=   使用此TLS證書檔案識別安全客戶端
--key=    使用此TLS金鑰檔案識別安全客戶端
--insecure-skip-tls-verify[=false]  跳過伺服器證書驗證
--insecure-transport[=true] 禁用客戶端連線的傳輸安全性
--insecure-discovery[=true] 接受描述叢集端點的不安全SRV記錄
--endpoints=[127.0.0.1:2379]  gRPC端點
--user=""  username[:password] 格式提供賬號密碼
--password="" 用於身份驗證的密碼(如果使用此選項,--user選項不應包含密碼)
-w, --write-out="simple" 命令結果輸出格式(fields, json, protobuf, simple, table)
--keepalive-time=2s  客戶端連線的保持活動時間
--keepalive-timeout=6s  客戶端連線的keepalive超時
--command-timeout=5s  短期執行命令超時(不包括撥號超時)
--dial-timeout=2s  客戶端連線的撥號超時
--debug[=false]  啟用客戶端除錯日誌記錄

3. etcdctl子命令

3.1 put:新增key

$  etcdctl put msg "Hello World"
OK

3.2 get: 查詢key

$ etcdctl get msg # 預設-w simple 簡單輸出格式
msg
Hello World

$ etcdctl get msg -w json # -w 指定輸出格式
{"header":{"cluster_id":17626150517759942079,"member_id":14892368386385720469,"revision":8,"raft_term":2},"kvs":[{"key":"bXNn","create_revision":8,"mod_revision":8,"version":1,"value":"SGVsbG8gV29ybGQ="}],"count":1}

$ etcdctl get msg -w fields
"ClusterID" : 17626150517759942079
"MemberID" : 14892368386385720469
"Revision" : 10
"RaftTerm" : 2
"Key" : "msg"
"CreateRevision" : 8
"ModRevision" : 8
"Version" : 1
"Value" : "Hello World"
"Lease" : 0
"More" : false
"Count" : 1

$ etcdctl put user1 Jack
$ etcdctl put user2 Tom
$ etcdctl put user3 Eric
$ etcdctl get user --prefix  # --prefix 指定字首匹配key
user1
Jack
user2
Tom
user3
Eric

# 檢視歷史版本key
foo = bar         # revision = 2
foo1 = bar1       # revision = 3
foo = bar_new     # revision = 4
foo1 = bar1_new   # revision = 5
$ etcdctl get --prefix --rev=4 foo # 檢視版本號4 時刻對應的key值,版本號是遞增的
foo
bar_new
foo1
bar1


$ etcdctl get --prefix --limit=2 foo # 限制查詢結果數量
$ etcdctl get --from-key b # 檢視字母順序大於等於b的key,指定一個起始鍵,並從該鍵開始返回所有的鍵值對

3.3 del: 刪除key

$ etcdctl put k1 v1
$ etcdctl put k2 v2
$ etcdctl put k3 v3
$ etcdctl del k1 # 刪除單個key
1
$ etcdctl del --prefix k # 根據字首刪除key
2
$ etcdctl del foo foo9 # 範圍刪除,key從foo到foo9
$ etcdctl del --from-key b # 刪除位元組佔用大於等於key b的key-

3.4 watch: 監控key的更改

$ etcdctl watch user  # 監控key user的變動
PUT
user
Jack
PUT
user
Tom
DELETE
user
# 在其他客戶端執行一下三個操作
$ etcdctl put user Jack
$ etcdctl put user Tom
$ etcdctl del user

$ etcdctl watch user --prefix # 監控字首匹配user字串的key的變動
$ etcdctl watch user --rev=2  # 從key的某個版本開始開始監控
$ etcdctl watch foo foo9 # 監控foo 到 foo9 範圍內key的變化
$ etcdctl watch -i  # 互動式監控,可監控多個key
$ watch foo
$ watch zoo
$ etcdctl watch user -- date # 監控key變化,產生變化後執行後面的bash命令
PUT
user
Tom
2024年 06月 05日 星期三 23:32:51 CST

3.5 lease: 對key繫結租約,授予生存時間ttl

$ etcdctl lease grant  60 # etcdctl lease grant 生成租約,租約存在時間60s
lease 34958fe81f27f16b granted with TTL(60s)
$ etcdctl put --lease=34958fe81f27f16b foo bar # 將key foo繫結到租約34958fe81f27f16b,租約到期後key刪除
OK

$ etcdctl lease keep-alive 34958fe81f27f17a # 持續重新整理租約生存時間,保證不過期
lease 34958fe81f27f17a keepalived with TTL(6)
lease 34958fe81f27f17a keepalived with TTL(6)
lease 34958fe81f27f17a keepalived with TTL(6)
lease 34958fe81f27f17a keepalived with TTL(6)


$ etcdctl lease revoke 32695410dcc0ca06 # 吊銷租約,撤銷租約會刪除其繫結的所有key
lease 32695410dcc0ca06 revoked

$ etcdctl lease grant 600
lease 34958fe81f27f17e granted with TTL(600s)
$ etcdctl put user1 jack --lease 34958fe81f27f17e
$ etcdctl put user2 Ame --lease 34958fe81f27f17e
$ etcdctl lease list # 查詢租約
found 1 leases
34958fe81f27f17e
$ etcdctl lease timetolive 34958fe81f27f17e # 檢視租約生存時間
lease 34958fe81f27f17e granted with TTL(600s), remaining(535s)
$ etcdctl lease timetolive 34958fe81f27f17e --keys  # 檢視租約生存時間,附加繫結的keys資訊
lease 34958fe81f27f17e granted with TTL(600s), remaining(532s), attached keys([user1 user2])

3.6 compact: 壓縮歷史版本,刪除歷史版本key,釋放資源

$ etcdctl compact 5 # 刪除版本小於5的歷史記錄
compacted revision 5
$ etcdctl get msg --rev=4  # 查詢歷史版本小於5的key會報錯
Error: etcdserver: mvcc: required revision has been compacted

3.7 endpoint: 節點狀態檢查

$ etcdctl endpoint health -w table # 表格形式輸出當前endpoint健康狀態
+----------------+--------+-------------+-------+
|    ENDPOINT    | HEALTH |    TOOK     | ERROR |
+----------------+--------+-------------+-------+
| 127.0.0.1:2379 |   true | 10.083786ms |       |
+----------------+--------+-------------+-------+

$ etcdctl endpoint health -w table --cluster # 檢視叢集健康狀態,而非單個endpoint
+--------------------------+--------+--------------+-------+
|         ENDPOINT         | HEALTH |     TOOK     | ERROR |
+--------------------------+--------+--------------+-------+
| http://192.168.2.34:2379 |   true |   8.795604ms |       |
| http://192.168.2.36:2379 |   true |   23.82879ms |       |
| http://192.168.2.35:2379 |   true | 139.106868ms |       |
+--------------------------+--------+--------------+-------+

$ etcdctl endpoint status --cluster -w table # 檢視叢集各節點詳細資訊
+--------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
|         ENDPOINT         |        ID        | VERSION | DB SIZE | IS LEADER | IS LEARNER | RAFT TERM | RAFT INDEX | RAFT APPLIED INDEX | ERRORS |
+--------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
| http://192.168.2.36:2379 | 5655803bfd67f3f9 |   3.5.4 |   42 MB |     false |      false |         2 |      18829 |              18829 |        |
| http://192.168.2.35:2379 | afd24e635c20e17b |   3.5.4 |   42 MB |     false |      false |         2 |      18829 |              18829 |        |
| http://192.168.2.34:2379 | ceac5224eec73495 |   3.5.4 |   42 MB |      true |      false |         2 |      18829 |              18829 |        |
+--------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+

$ etcdctl  endpoint hashkv --cluster -w table # 檢視割接點歷史k v雜湊值,--rev 可指定最大版本號,預設最新版本
+--------------------------+------------+
|         ENDPOINT         |    HASH    |
+--------------------------+------------+
| http://192.168.2.36:2379 | 1570845981 |
| http://192.168.2.35:2379 | 1570845981 |
| http://192.168.2.34:2379 | 1570845981 |
+--------------------------+------------+

3.8 member: 叢集成員管理(可簡寫為mem)

$ etcdctl mem list -w table # 檢視叢集成員列表
+------------------+---------+--------+--------------------------+--------------------------+------------+
|        ID        | STATUS  |  NAME  |        PEER ADDRS        |       CLIENT ADDRS       | IS LEARNER |
+------------------+---------+--------+--------------------------+--------------------------+------------+
| 5655803bfd67f3f9 | started | etcd03 | http://192.168.2.36:2380 | http://192.168.2.36:2379 |      false |
| afd24e635c20e17b | started | etcd02 | http://192.168.2.35:2380 | http://192.168.2.35:2379 |      false |
| ceac5224eec73495 | started | etcd01 | http://192.168.2.34:2380 | http://192.168.2.34:2379 |      false |
+------------------+---------+--------+--------------------------+--------------------------+------------+

$ etcdctl member remove <memberID> # 從叢集中刪除指定id的成員

# 新增指定名稱和peer地址的raft投票節點,新節點啟動前,--initial-cluster-state引數設定為 existing,代表加入已存在的叢集
$ etcdctl member add <memberName> --peer-urls=""

$ etcdctl member promote <memberID> # 提升學習節點為投票節點

# 提升指定成員為叢集領導者
$ etcdctl --endpoints=192.168.2.34:2379,192.168.2.35:2379,192.168.2.36:2379  move-leader afd24e635c20e17b   
Leadership transferred from 5655803bfd67f3f9 to afd24e635c20e17b

$ etcdctl member update <memberID> --peer-urls="" # 更新已修改peer的成員peer資訊

3.9 snapshot: 快照管理

# 快照只能從一個 etcd 節點請求,因此 --endpoints 標誌應僅包含一個端點
$ etcdctl --endpoints=192.168.2.36:2379 snapshot save my.db # 儲存快照到my.db
{"level":"info","ts":"2024-06-06T01:58:51.196+0800","caller":"snapshot/v3_snapshot.go:65","msg":"created temporary db file","path":"my.db.part"}
{"level":"info","ts":"2024-06-06T01:58:51.205+0800","logger":"client","caller":"v3/maintenance.go:211","msg":"opened snapshot stream; downloading"}
{"level":"info","ts":"2024-06-06T01:58:51.205+0800","caller":"snapshot/v3_snapshot.go:73","msg":"fetching snapshot","endpoint":"192.168.2.36:2379"}
{"level":"info","ts":"2024-06-06T01:58:55.183+0800","logger":"client","caller":"v3/maintenance.go:219","msg":"completed snapshot read; closing"}
{"level":"info","ts":"2024-06-06T01:58:55.833+0800","caller":"snapshot/v3_snapshot.go:88","msg":"fetched snapshot","endpoint":"192.168.2.36:2379","size":"42 MB","took":"4 seconds ago"}
{"level":"info","ts":"2024-06-06T01:58:55.833+0800","caller":"snapshot/v3_snapshot.go:97","msg":"saved","path":"my.db"}
Snapshot saved at my.db

$ etcdctl --endpoints=192.168.2.36:2379 snapshot status my.db # 檢視快照狀態
Deprecated: Use `etcdutl snapshot status` instead.
+----------+----------+------------+------------+
|   HASH   | REVISION | TOTAL KEYS | TOTAL SIZE |
+----------+----------+------------+------------+
| 37ddd253 |    18766 |      37479 |      42 MB |
+----------+----------+------------+------------+

$ etcdctl  snapshot restore my.db --data-dir=""  # 恢復備份檔案到指定目錄

相關文章