main.go 12 KB

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