main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Copyright 2018 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "bufio"
  17. "bytes"
  18. "encoding/hex"
  19. "flag"
  20. "fmt"
  21. "io"
  22. "log"
  23. "os"
  24. "os/exec"
  25. "path/filepath"
  26. "strings"
  27. "time"
  28. "go.etcd.io/etcd/etcdserver/api/snap"
  29. "go.etcd.io/etcd/etcdserver/etcdserverpb"
  30. "go.etcd.io/etcd/pkg/pbutil"
  31. "go.etcd.io/etcd/pkg/types"
  32. "go.etcd.io/etcd/raft/raftpb"
  33. "go.etcd.io/etcd/wal"
  34. "go.etcd.io/etcd/wal/walpb"
  35. "go.uber.org/zap"
  36. )
  37. const (
  38. defaultEntryTypes string = "Normal,ConfigChange"
  39. )
  40. func main() {
  41. snapfile := flag.String("start-snap", "", "The base name of snapshot file to start dumping")
  42. index := flag.Uint64("start-index", 0, "The index to start dumping")
  43. // Default entry types are Normal and ConfigChange
  44. entrytype := flag.String("entry-type", defaultEntryTypes, `If set, filters output by entry type. Must be one or more than one of:
  45. ConfigChange, Normal, Request, InternalRaftRequest,
  46. IRRRange, IRRPut, IRRDeleteRange, IRRTxn,
  47. IRRCompaction, IRRLeaseGrant, IRRLeaseRevoke, IRRLeaseCheckpoint`)
  48. streamdecoder := flag.String("stream-decoder", "", `The name of an executable decoding tool, the executable must process
  49. hex encoded lines of binary input (from etcd-dump-logs)
  50. and output a hex encoded line of binary for each input line`)
  51. flag.Parse()
  52. if len(flag.Args()) != 1 {
  53. log.Fatalf("Must provide data-dir argument (got %+v)", flag.Args())
  54. }
  55. dataDir := flag.Args()[0]
  56. if *snapfile != "" && *index != 0 {
  57. log.Fatal("start-snap and start-index flags cannot be used together.")
  58. }
  59. var (
  60. walsnap walpb.Snapshot
  61. snapshot *raftpb.Snapshot
  62. err error
  63. )
  64. isIndex := *index != 0
  65. if isIndex {
  66. fmt.Printf("Start dumping log entries from index %d.\n", *index)
  67. walsnap.Index = *index
  68. } else {
  69. if *snapfile == "" {
  70. ss := snap.New(zap.NewExample(), snapDir(dataDir))
  71. snapshot, err = ss.Load()
  72. } else {
  73. snapshot, err = snap.Read(zap.NewExample(), filepath.Join(snapDir(dataDir), *snapfile))
  74. }
  75. switch err {
  76. case nil:
  77. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  78. nodes := genIDSlice(snapshot.Metadata.ConfState.Voters)
  79. fmt.Printf("Snapshot:\nterm=%d index=%d nodes=%s\n",
  80. walsnap.Term, walsnap.Index, nodes)
  81. case snap.ErrNoSnapshot:
  82. fmt.Printf("Snapshot:\nempty\n")
  83. default:
  84. log.Fatalf("Failed loading snapshot: %v", err)
  85. }
  86. fmt.Println("Start dumping log entries from snapshot.")
  87. }
  88. w, err := wal.OpenForRead(zap.NewExample(), walDir(dataDir), walsnap)
  89. if err != nil {
  90. log.Fatalf("Failed opening WAL: %v", err)
  91. }
  92. wmetadata, state, ents, err := w.ReadAll()
  93. w.Close()
  94. if err != nil && (!isIndex || err != wal.ErrSnapshotNotFound) {
  95. log.Fatalf("Failed reading WAL: %v", err)
  96. }
  97. id, cid := parseWALMetadata(wmetadata)
  98. vid := types.ID(state.Vote)
  99. fmt.Printf("WAL metadata:\nnodeID=%s clusterID=%s term=%d commitIndex=%d vote=%s\n",
  100. id, cid, state.Term, state.Commit, vid)
  101. fmt.Printf("WAL entries:\n")
  102. fmt.Printf("lastIndex=%d\n", ents[len(ents)-1].Index)
  103. fmt.Printf("%4s\t%10s\ttype\tdata", "term", "index")
  104. if *streamdecoder != "" {
  105. fmt.Printf("\tdecoder_status\tdecoded_data")
  106. }
  107. fmt.Println()
  108. listEntriesType(*entrytype, *streamdecoder, ents)
  109. }
  110. func walDir(dataDir string) string { return filepath.Join(dataDir, "member", "wal") }
  111. func snapDir(dataDir string) string { return filepath.Join(dataDir, "member", "snap") }
  112. func parseWALMetadata(b []byte) (id, cid types.ID) {
  113. var metadata etcdserverpb.Metadata
  114. pbutil.MustUnmarshal(&metadata, b)
  115. id = types.ID(metadata.NodeID)
  116. cid = types.ID(metadata.ClusterID)
  117. return id, cid
  118. }
  119. func genIDSlice(a []uint64) []types.ID {
  120. ids := make([]types.ID, len(a))
  121. for i, id := range a {
  122. ids[i] = types.ID(id)
  123. }
  124. return ids
  125. }
  126. // excerpt replaces middle part with ellipsis and returns a double-quoted
  127. // string safely escaped with Go syntax.
  128. func excerpt(str string, pre, suf int) string {
  129. if pre+suf > len(str) {
  130. return fmt.Sprintf("%q", str)
  131. }
  132. return fmt.Sprintf("%q...%q", str[:pre], str[len(str)-suf:])
  133. }
  134. type EntryFilter func(e raftpb.Entry) (bool, string)
  135. // The 9 pass functions below takes the raftpb.Entry and return if the entry should be printed and the type of entry,
  136. // the type of the entry will used in the following print function
  137. func passConfChange(entry raftpb.Entry) (bool, string) {
  138. return entry.Type == raftpb.EntryConfChange, "ConfigChange"
  139. }
  140. func passInternalRaftRequest(entry raftpb.Entry) (bool, string) {
  141. var rr etcdserverpb.InternalRaftRequest
  142. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil, "InternalRaftRequest"
  143. }
  144. func passUnknownNormal(entry raftpb.Entry) (bool, string) {
  145. var rr1 etcdserverpb.Request
  146. var rr2 etcdserverpb.InternalRaftRequest
  147. return (entry.Type == raftpb.EntryNormal) && (rr1.Unmarshal(entry.Data) != nil) && (rr2.Unmarshal(entry.Data) != nil), "UnknownNormal"
  148. }
  149. func passIRRRange(entry raftpb.Entry) (bool, string) {
  150. var rr etcdserverpb.InternalRaftRequest
  151. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.Range != nil, "InternalRaftRequest"
  152. }
  153. func passIRRPut(entry raftpb.Entry) (bool, string) {
  154. var rr etcdserverpb.InternalRaftRequest
  155. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.Put != nil, "InternalRaftRequest"
  156. }
  157. func passIRRDeleteRange(entry raftpb.Entry) (bool, string) {
  158. var rr etcdserverpb.InternalRaftRequest
  159. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.DeleteRange != nil, "InternalRaftRequest"
  160. }
  161. func passIRRTxn(entry raftpb.Entry) (bool, string) {
  162. var rr etcdserverpb.InternalRaftRequest
  163. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.Txn != nil, "InternalRaftRequest"
  164. }
  165. func passIRRCompaction(entry raftpb.Entry) (bool, string) {
  166. var rr etcdserverpb.InternalRaftRequest
  167. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.Compaction != nil, "InternalRaftRequest"
  168. }
  169. func passIRRLeaseGrant(entry raftpb.Entry) (bool, string) {
  170. var rr etcdserverpb.InternalRaftRequest
  171. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.LeaseGrant != nil, "InternalRaftRequest"
  172. }
  173. func passIRRLeaseRevoke(entry raftpb.Entry) (bool, string) {
  174. var rr etcdserverpb.InternalRaftRequest
  175. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.LeaseRevoke != nil, "InternalRaftRequest"
  176. }
  177. func passIRRLeaseCheckpoint(entry raftpb.Entry) (bool, string) {
  178. var rr etcdserverpb.InternalRaftRequest
  179. return entry.Type == raftpb.EntryNormal && rr.Unmarshal(entry.Data) == nil && rr.LeaseCheckpoint != nil, "InternalRaftRequest"
  180. }
  181. func passRequest(entry raftpb.Entry) (bool, string) {
  182. var rr1 etcdserverpb.Request
  183. var rr2 etcdserverpb.InternalRaftRequest
  184. return entry.Type == raftpb.EntryNormal && rr1.Unmarshal(entry.Data) == nil && rr2.Unmarshal(entry.Data) != nil, "Request"
  185. }
  186. type EntryPrinter func(e raftpb.Entry)
  187. // The 4 print functions below print the entry format based on there types
  188. // printInternalRaftRequest is used to print entry information for IRRRange, IRRPut,
  189. // IRRDeleteRange and IRRTxn entries
  190. func printInternalRaftRequest(entry raftpb.Entry) {
  191. var rr etcdserverpb.InternalRaftRequest
  192. if err := rr.Unmarshal(entry.Data); err == nil {
  193. fmt.Printf("%4d\t%10d\tnorm\t%s", entry.Term, entry.Index, rr.String())
  194. }
  195. }
  196. func printUnknownNormal(entry raftpb.Entry) {
  197. fmt.Printf("%4d\t%10d\tnorm\t???", entry.Term, entry.Index)
  198. }
  199. func printConfChange(entry raftpb.Entry) {
  200. fmt.Printf("%4d\t%10d", entry.Term, entry.Index)
  201. fmt.Printf("\tconf")
  202. var r raftpb.ConfChange
  203. if err := r.Unmarshal(entry.Data); err != nil {
  204. fmt.Printf("\t???")
  205. } else {
  206. fmt.Printf("\tmethod=%s id=%s", r.Type, types.ID(r.NodeID))
  207. }
  208. }
  209. func printRequest(entry raftpb.Entry) {
  210. var r etcdserverpb.Request
  211. if err := r.Unmarshal(entry.Data); err == nil {
  212. fmt.Printf("%4d\t%10d\tnorm", entry.Term, entry.Index)
  213. switch r.Method {
  214. case "":
  215. fmt.Printf("\tnoop")
  216. case "SYNC":
  217. fmt.Printf("\tmethod=SYNC time=%q", time.Unix(0, r.Time))
  218. case "QGET", "DELETE":
  219. fmt.Printf("\tmethod=%s path=%s", r.Method, excerpt(r.Path, 64, 64))
  220. default:
  221. fmt.Printf("\tmethod=%s path=%s val=%s", r.Method, excerpt(r.Path, 64, 64), excerpt(r.Val, 128, 0))
  222. }
  223. }
  224. }
  225. // evaluateEntrytypeFlag evaluates entry-type flag and choose proper filter/filters to filter entries
  226. func evaluateEntrytypeFlag(entrytype string) []EntryFilter {
  227. var entrytypelist []string
  228. if entrytype != "" {
  229. entrytypelist = strings.Split(entrytype, ",")
  230. }
  231. validRequest := map[string][]EntryFilter{"ConfigChange": {passConfChange},
  232. "Normal": {passInternalRaftRequest, passRequest, passUnknownNormal},
  233. "Request": {passRequest},
  234. "InternalRaftRequest": {passInternalRaftRequest},
  235. "IRRRange": {passIRRRange},
  236. "IRRPut": {passIRRPut},
  237. "IRRDeleteRange": {passIRRDeleteRange},
  238. "IRRTxn": {passIRRTxn},
  239. "IRRCompaction": {passIRRCompaction},
  240. "IRRLeaseGrant": {passIRRLeaseGrant},
  241. "IRRLeaseRevoke": {passIRRLeaseRevoke},
  242. "IRRLeaseCheckpoint": {passIRRLeaseCheckpoint},
  243. }
  244. filters := make([]EntryFilter, 0)
  245. for _, et := range entrytypelist {
  246. if f, ok := validRequest[et]; ok {
  247. filters = append(filters, f...)
  248. } else {
  249. log.Printf(`[%+v] is not a valid entry-type, ignored.
  250. Please set entry-type to one or more of the following:
  251. ConfigChange, Normal, Request, InternalRaftRequest,
  252. IRRRange, IRRPut, IRRDeleteRange, IRRTxn,
  253. IRRCompaction, IRRLeaseGrant, IRRLeaseRevoke, IRRLeaseCheckpoint`, et)
  254. }
  255. }
  256. return filters
  257. }
  258. // listEntriesType filters and prints entries based on the entry-type flag,
  259. func listEntriesType(entrytype string, streamdecoder string, ents []raftpb.Entry) {
  260. entryFilters := evaluateEntrytypeFlag(entrytype)
  261. printerMap := map[string]EntryPrinter{"InternalRaftRequest": printInternalRaftRequest,
  262. "Request": printRequest,
  263. "ConfigChange": printConfChange,
  264. "UnknownNormal": printUnknownNormal}
  265. var stderr bytes.Buffer
  266. args := strings.Split(streamdecoder, " ")
  267. cmd := exec.Command(args[0], args[1:]...)
  268. stdin, err := cmd.StdinPipe()
  269. if err != nil {
  270. log.Panic(err)
  271. }
  272. stdout, err := cmd.StdoutPipe()
  273. if err != nil {
  274. log.Panic(err)
  275. }
  276. cmd.Stderr = &stderr
  277. if streamdecoder != "" {
  278. err = cmd.Start()
  279. if err != nil {
  280. log.Panic(err)
  281. }
  282. }
  283. cnt := 0
  284. for _, e := range ents {
  285. passed := false
  286. currtype := ""
  287. for _, filter := range entryFilters {
  288. passed, currtype = filter(e)
  289. if passed {
  290. cnt++
  291. break
  292. }
  293. }
  294. if passed {
  295. printer := printerMap[currtype]
  296. printer(e)
  297. if streamdecoder == "" {
  298. fmt.Println()
  299. continue
  300. }
  301. // if decoder is set, pass the e.Data to stdin and read the stdout from decoder
  302. io.WriteString(stdin, hex.EncodeToString(e.Data))
  303. io.WriteString(stdin, "\n")
  304. outputReader := bufio.NewReader(stdout)
  305. decoderoutput, currerr := outputReader.ReadString('\n')
  306. if currerr != nil {
  307. fmt.Println(currerr)
  308. return
  309. }
  310. decoder_status, decoded_data := parseDecoderOutput(decoderoutput)
  311. fmt.Printf("\t%s\t%s", decoder_status, decoded_data)
  312. }
  313. }
  314. stdin.Close()
  315. err = cmd.Wait()
  316. if streamdecoder != "" {
  317. if err != nil {
  318. log.Panic(err)
  319. }
  320. if stderr.String() != "" {
  321. os.Stderr.WriteString("decoder stderr: " + stderr.String())
  322. }
  323. }
  324. fmt.Printf("\nEntry types (%s) count is : %d\n", entrytype, cnt)
  325. }
  326. func parseDecoderOutput(decoderoutput string) (string, string) {
  327. var decoder_status string
  328. var decoded_data string
  329. output := strings.Split(decoderoutput, "|")
  330. switch len(output) {
  331. case 1:
  332. decoder_status = "decoder output format is not right, print output anyway"
  333. decoded_data = decoderoutput
  334. case 2:
  335. decoder_status = output[0]
  336. decoded_data = output[1]
  337. default:
  338. decoder_status = output[0] + "(*WARNING: data might contain deliminator used by etcd-dump-logs)"
  339. decoded_data = strings.Join(output[1:], "")
  340. }
  341. return decoder_status, decoded_data
  342. }