backup_command.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Copyright 2015 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 command
  15. import (
  16. "encoding/binary"
  17. "log"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "regexp"
  22. "time"
  23. "go.etcd.io/etcd/etcdserver/api/membership"
  24. "go.etcd.io/etcd/etcdserver/api/snap"
  25. "go.etcd.io/etcd/etcdserver/etcdserverpb"
  26. "go.etcd.io/etcd/pkg/fileutil"
  27. "go.etcd.io/etcd/pkg/idutil"
  28. "go.etcd.io/etcd/pkg/pbutil"
  29. "go.etcd.io/etcd/raft/raftpb"
  30. "go.etcd.io/etcd/wal"
  31. "go.etcd.io/etcd/wal/walpb"
  32. "github.com/urfave/cli"
  33. bolt "go.etcd.io/bbolt"
  34. "go.uber.org/zap"
  35. )
  36. func NewBackupCommand() cli.Command {
  37. return cli.Command{
  38. Name: "backup",
  39. Usage: "backup an etcd directory",
  40. ArgsUsage: " ",
  41. Flags: []cli.Flag{
  42. cli.StringFlag{Name: "data-dir", Value: "", Usage: "Path to the etcd data dir"},
  43. cli.StringFlag{Name: "wal-dir", Value: "", Usage: "Path to the etcd wal dir"},
  44. cli.StringFlag{Name: "backup-dir", Value: "", Usage: "Path to the backup dir"},
  45. cli.StringFlag{Name: "backup-wal-dir", Value: "", Usage: "Path to the backup wal dir"},
  46. cli.BoolFlag{Name: "with-v3", Usage: "Backup v3 backend data"},
  47. },
  48. Action: handleBackup,
  49. }
  50. }
  51. // handleBackup handles a request that intends to do a backup.
  52. func handleBackup(c *cli.Context) error {
  53. var srcWAL string
  54. var destWAL string
  55. withV3 := c.Bool("with-v3")
  56. srcSnap := filepath.Join(c.String("data-dir"), "member", "snap")
  57. destSnap := filepath.Join(c.String("backup-dir"), "member", "snap")
  58. if c.String("wal-dir") != "" {
  59. srcWAL = c.String("wal-dir")
  60. } else {
  61. srcWAL = filepath.Join(c.String("data-dir"), "member", "wal")
  62. }
  63. if c.String("backup-wal-dir") != "" {
  64. destWAL = c.String("backup-wal-dir")
  65. } else {
  66. destWAL = filepath.Join(c.String("backup-dir"), "member", "wal")
  67. }
  68. if err := fileutil.CreateDirAll(destSnap); err != nil {
  69. log.Fatalf("failed creating backup snapshot dir %v: %v", destSnap, err)
  70. }
  71. walsnap := saveSnap(destSnap, srcSnap)
  72. metadata, state, ents := loadWAL(srcWAL, walsnap, withV3)
  73. saveDB(filepath.Join(destSnap, "db"), filepath.Join(srcSnap, "db"), state.Commit, withV3)
  74. idgen := idutil.NewGenerator(0, time.Now())
  75. metadata.NodeID = idgen.Next()
  76. metadata.ClusterID = idgen.Next()
  77. neww, err := wal.Create(zap.NewExample(), destWAL, pbutil.MustMarshal(&metadata))
  78. if err != nil {
  79. log.Fatal(err)
  80. }
  81. defer neww.Close()
  82. if err := neww.Save(state, ents); err != nil {
  83. log.Fatal(err)
  84. }
  85. if err := neww.SaveSnapshot(walsnap); err != nil {
  86. log.Fatal(err)
  87. }
  88. return nil
  89. }
  90. func saveSnap(destSnap, srcSnap string) (walsnap walpb.Snapshot) {
  91. ss := snap.New(zap.NewExample(), srcSnap)
  92. snapshot, err := ss.Load()
  93. if err != nil && err != snap.ErrNoSnapshot {
  94. log.Fatal(err)
  95. }
  96. if snapshot != nil {
  97. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  98. newss := snap.New(zap.NewExample(), destSnap)
  99. if err = newss.SaveSnap(*snapshot); err != nil {
  100. log.Fatal(err)
  101. }
  102. }
  103. return walsnap
  104. }
  105. func loadWAL(srcWAL string, walsnap walpb.Snapshot, v3 bool) (etcdserverpb.Metadata, raftpb.HardState, []raftpb.Entry) {
  106. w, err := wal.OpenForRead(zap.NewExample(), srcWAL, walsnap)
  107. if err != nil {
  108. log.Fatal(err)
  109. }
  110. defer w.Close()
  111. wmetadata, state, ents, err := w.ReadAll()
  112. switch err {
  113. case nil:
  114. case wal.ErrSnapshotNotFound:
  115. log.Printf("Failed to find the match snapshot record %+v in wal %v.", walsnap, srcWAL)
  116. log.Printf("etcdctl will add it back. Start auto fixing...")
  117. default:
  118. log.Fatal(err)
  119. }
  120. re := path.Join(membership.StoreMembersPrefix, "[[:xdigit:]]{1,16}", "attributes")
  121. memberAttrRE := regexp.MustCompile(re)
  122. removed := uint64(0)
  123. i := 0
  124. remove := func() {
  125. ents = append(ents[:i], ents[i+1:]...)
  126. removed++
  127. i--
  128. }
  129. for i = 0; i < len(ents); i++ {
  130. ents[i].Index -= removed
  131. if ents[i].Type == raftpb.EntryConfChange {
  132. log.Println("ignoring EntryConfChange raft entry")
  133. remove()
  134. continue
  135. }
  136. var raftReq etcdserverpb.InternalRaftRequest
  137. var v2Req *etcdserverpb.Request
  138. if pbutil.MaybeUnmarshal(&raftReq, ents[i].Data) {
  139. v2Req = raftReq.V2
  140. } else {
  141. v2Req = &etcdserverpb.Request{}
  142. pbutil.MustUnmarshal(v2Req, ents[i].Data)
  143. }
  144. if v2Req != nil && v2Req.Method == "PUT" && memberAttrRE.MatchString(v2Req.Path) {
  145. log.Println("ignoring member attribute update on", v2Req.Path)
  146. remove()
  147. continue
  148. }
  149. if v2Req != nil {
  150. continue
  151. }
  152. if v3 || raftReq.Header == nil {
  153. continue
  154. }
  155. log.Println("ignoring v3 raft entry")
  156. remove()
  157. }
  158. state.Commit -= removed
  159. var metadata etcdserverpb.Metadata
  160. pbutil.MustUnmarshal(&metadata, wmetadata)
  161. return metadata, state, ents
  162. }
  163. // saveDB copies the v3 backend and strips cluster information.
  164. func saveDB(destDB, srcDB string, idx uint64, v3 bool) {
  165. // open src db to safely copy db state
  166. if v3 {
  167. var src *bolt.DB
  168. ch := make(chan *bolt.DB, 1)
  169. go func() {
  170. db, err := bolt.Open(srcDB, 0444, &bolt.Options{ReadOnly: true})
  171. if err != nil {
  172. log.Fatal(err)
  173. }
  174. ch <- db
  175. }()
  176. select {
  177. case src = <-ch:
  178. case <-time.After(time.Second):
  179. log.Println("waiting to acquire lock on", srcDB)
  180. src = <-ch
  181. }
  182. defer src.Close()
  183. tx, err := src.Begin(false)
  184. if err != nil {
  185. log.Fatal(err)
  186. }
  187. // copy srcDB to destDB
  188. dest, err := os.Create(destDB)
  189. if err != nil {
  190. log.Fatal(err)
  191. }
  192. if _, err := tx.WriteTo(dest); err != nil {
  193. log.Fatal(err)
  194. }
  195. dest.Close()
  196. if err := tx.Rollback(); err != nil {
  197. log.Fatal(err)
  198. }
  199. }
  200. db, err := bolt.Open(destDB, 0644, &bolt.Options{})
  201. if err != nil {
  202. log.Fatal(err)
  203. }
  204. tx, err := db.Begin(true)
  205. if err != nil {
  206. log.Fatal(err)
  207. }
  208. // remove membership information; should be clobbered by --force-new-cluster
  209. for _, bucket := range []string{"members", "members_removed", "cluster"} {
  210. tx.DeleteBucket([]byte(bucket))
  211. }
  212. // update consistent index to match hard state
  213. if !v3 {
  214. idxBytes := make([]byte, 8)
  215. binary.BigEndian.PutUint64(idxBytes, idx)
  216. b, err := tx.CreateBucketIfNotExists([]byte("meta"))
  217. if err != nil {
  218. log.Fatal(err)
  219. }
  220. b.Put([]byte("consistent_index"), idxBytes)
  221. }
  222. if err := tx.Commit(); err != nil {
  223. log.Fatal(err)
  224. }
  225. if err := db.Close(); err != nil {
  226. log.Fatal(err)
  227. }
  228. }