snapshot_command.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. // Copyright 2016 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. "crypto/sha256"
  17. "encoding/binary"
  18. "encoding/json"
  19. "fmt"
  20. "hash/crc32"
  21. "io"
  22. "math"
  23. "os"
  24. "path/filepath"
  25. "reflect"
  26. "strings"
  27. bolt "github.com/coreos/bbolt"
  28. "github.com/coreos/etcd/etcdserver"
  29. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  30. "github.com/coreos/etcd/etcdserver/membership"
  31. "github.com/coreos/etcd/lease"
  32. "github.com/coreos/etcd/mvcc"
  33. "github.com/coreos/etcd/mvcc/backend"
  34. "github.com/coreos/etcd/pkg/fileutil"
  35. "github.com/coreos/etcd/pkg/types"
  36. "github.com/coreos/etcd/raft"
  37. "github.com/coreos/etcd/raft/raftpb"
  38. "github.com/coreos/etcd/snap"
  39. "github.com/coreos/etcd/store"
  40. "github.com/coreos/etcd/wal"
  41. "github.com/coreos/etcd/wal/walpb"
  42. "github.com/spf13/cobra"
  43. "golang.org/x/net/context"
  44. )
  45. const (
  46. defaultName = "default"
  47. defaultInitialAdvertisePeerURLs = "http://localhost:2380"
  48. )
  49. var (
  50. restoreCluster string
  51. restoreClusterToken string
  52. restoreDataDir string
  53. restorePeerURLs string
  54. restoreName string
  55. skipHashCheck bool
  56. )
  57. // NewSnapshotCommand returns the cobra command for "snapshot".
  58. func NewSnapshotCommand() *cobra.Command {
  59. cmd := &cobra.Command{
  60. Use: "snapshot <subcommand>",
  61. Short: "Manages etcd node snapshots",
  62. }
  63. cmd.AddCommand(NewSnapshotSaveCommand())
  64. cmd.AddCommand(NewSnapshotRestoreCommand())
  65. cmd.AddCommand(newSnapshotStatusCommand())
  66. return cmd
  67. }
  68. func NewSnapshotSaveCommand() *cobra.Command {
  69. return &cobra.Command{
  70. Use: "save <filename>",
  71. Short: "Stores an etcd node backend snapshot to a given file",
  72. Run: snapshotSaveCommandFunc,
  73. }
  74. }
  75. func newSnapshotStatusCommand() *cobra.Command {
  76. return &cobra.Command{
  77. Use: "status <filename>",
  78. Short: "Gets backend snapshot status of a given file",
  79. Long: `When --write-out is set to simple, this command prints out comma-separated status lists for each endpoint.
  80. The items in the lists are hash, revision, total keys, total size.
  81. `,
  82. Run: snapshotStatusCommandFunc,
  83. }
  84. }
  85. func NewSnapshotRestoreCommand() *cobra.Command {
  86. cmd := &cobra.Command{
  87. Use: "restore <filename> [options]",
  88. Short: "Restores an etcd member snapshot to an etcd directory",
  89. Run: snapshotRestoreCommandFunc,
  90. }
  91. cmd.Flags().StringVar(&restoreDataDir, "data-dir", "", "Path to the data directory")
  92. cmd.Flags().StringVar(&restoreCluster, "initial-cluster", initialClusterFromName(defaultName), "Initial cluster configuration for restore bootstrap")
  93. cmd.Flags().StringVar(&restoreClusterToken, "initial-cluster-token", "etcd-cluster", "Initial cluster token for the etcd cluster during restore bootstrap")
  94. cmd.Flags().StringVar(&restorePeerURLs, "initial-advertise-peer-urls", defaultInitialAdvertisePeerURLs, "List of this member's peer URLs to advertise to the rest of the cluster")
  95. cmd.Flags().StringVar(&restoreName, "name", defaultName, "Human-readable name for this member")
  96. cmd.Flags().BoolVar(&skipHashCheck, "skip-hash-check", false, "Ignore snapshot integrity hash value (required if copied from data directory)")
  97. return cmd
  98. }
  99. func snapshotSaveCommandFunc(cmd *cobra.Command, args []string) {
  100. if len(args) != 1 {
  101. err := fmt.Errorf("snapshot save expects one argument")
  102. ExitWithError(ExitBadArgs, err)
  103. }
  104. path := args[0]
  105. partpath := path + ".part"
  106. f, err := os.Create(partpath)
  107. if err != nil {
  108. exiterr := fmt.Errorf("could not open %s (%v)", partpath, err)
  109. ExitWithError(ExitBadArgs, exiterr)
  110. }
  111. c := mustClientFromCmd(cmd)
  112. r, serr := c.Snapshot(context.TODO())
  113. if serr != nil {
  114. os.RemoveAll(partpath)
  115. ExitWithError(ExitInterrupted, serr)
  116. }
  117. if _, rerr := io.Copy(f, r); rerr != nil {
  118. os.RemoveAll(partpath)
  119. ExitWithError(ExitInterrupted, rerr)
  120. }
  121. fileutil.Fsync(f)
  122. f.Close()
  123. if rerr := os.Rename(partpath, path); rerr != nil {
  124. exiterr := fmt.Errorf("could not rename %s to %s (%v)", partpath, path, rerr)
  125. ExitWithError(ExitIO, exiterr)
  126. }
  127. fmt.Printf("Snapshot saved at %s\n", path)
  128. }
  129. func snapshotStatusCommandFunc(cmd *cobra.Command, args []string) {
  130. if len(args) != 1 {
  131. err := fmt.Errorf("snapshot status requires exactly one argument")
  132. ExitWithError(ExitBadArgs, err)
  133. }
  134. initDisplayFromCmd(cmd)
  135. ds := dbStatus(args[0])
  136. display.DBStatus(ds)
  137. }
  138. func snapshotRestoreCommandFunc(cmd *cobra.Command, args []string) {
  139. if len(args) != 1 {
  140. err := fmt.Errorf("snapshot restore requires exactly one argument")
  141. ExitWithError(ExitBadArgs, err)
  142. }
  143. urlmap, uerr := types.NewURLsMap(restoreCluster)
  144. if uerr != nil {
  145. ExitWithError(ExitBadArgs, uerr)
  146. }
  147. cfg := etcdserver.ServerConfig{
  148. InitialClusterToken: restoreClusterToken,
  149. InitialPeerURLsMap: urlmap,
  150. PeerURLs: types.MustNewURLs(strings.Split(restorePeerURLs, ",")),
  151. Name: restoreName,
  152. }
  153. if err := cfg.VerifyBootstrap(); err != nil {
  154. ExitWithError(ExitBadArgs, err)
  155. }
  156. cl, cerr := membership.NewClusterFromURLsMap(restoreClusterToken, urlmap)
  157. if cerr != nil {
  158. ExitWithError(ExitBadArgs, cerr)
  159. }
  160. basedir := restoreDataDir
  161. if basedir == "" {
  162. basedir = restoreName + ".etcd"
  163. }
  164. waldir := filepath.Join(basedir, "member", "wal")
  165. snapdir := filepath.Join(basedir, "member", "snap")
  166. if _, err := os.Stat(basedir); err == nil {
  167. ExitWithError(ExitInvalidInput, fmt.Errorf("data-dir %q exists", basedir))
  168. }
  169. makeDB(snapdir, args[0], len(cl.Members()))
  170. makeWALAndSnap(waldir, snapdir, cl)
  171. }
  172. func initialClusterFromName(name string) string {
  173. n := name
  174. if name == "" {
  175. n = defaultName
  176. }
  177. return fmt.Sprintf("%s=http://localhost:2380", n)
  178. }
  179. // makeWAL creates a WAL for the initial cluster
  180. func makeWALAndSnap(waldir, snapdir string, cl *membership.RaftCluster) {
  181. if err := fileutil.CreateDirAll(waldir); err != nil {
  182. ExitWithError(ExitIO, err)
  183. }
  184. // add members again to persist them to the store we create.
  185. st := store.New(etcdserver.StoreClusterPrefix, etcdserver.StoreKeysPrefix)
  186. cl.SetStore(st)
  187. for _, m := range cl.Members() {
  188. cl.AddMember(m)
  189. }
  190. m := cl.MemberByName(restoreName)
  191. md := &etcdserverpb.Metadata{NodeID: uint64(m.ID), ClusterID: uint64(cl.ID())}
  192. metadata, merr := md.Marshal()
  193. if merr != nil {
  194. ExitWithError(ExitInvalidInput, merr)
  195. }
  196. w, walerr := wal.Create(waldir, metadata)
  197. if walerr != nil {
  198. ExitWithError(ExitIO, walerr)
  199. }
  200. defer w.Close()
  201. peers := make([]raft.Peer, len(cl.MemberIDs()))
  202. for i, id := range cl.MemberIDs() {
  203. ctx, err := json.Marshal((*cl).Member(id))
  204. if err != nil {
  205. ExitWithError(ExitInvalidInput, err)
  206. }
  207. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  208. }
  209. ents := make([]raftpb.Entry, len(peers))
  210. nodeIDs := make([]uint64, len(peers))
  211. for i, p := range peers {
  212. nodeIDs[i] = p.ID
  213. cc := raftpb.ConfChange{
  214. Type: raftpb.ConfChangeAddNode,
  215. NodeID: p.ID,
  216. Context: p.Context}
  217. d, err := cc.Marshal()
  218. if err != nil {
  219. ExitWithError(ExitInvalidInput, err)
  220. }
  221. e := raftpb.Entry{
  222. Type: raftpb.EntryConfChange,
  223. Term: 1,
  224. Index: uint64(i + 1),
  225. Data: d,
  226. }
  227. ents[i] = e
  228. }
  229. commit, term := uint64(len(ents)), uint64(1)
  230. if err := w.Save(raftpb.HardState{
  231. Term: term,
  232. Vote: peers[0].ID,
  233. Commit: commit}, ents); err != nil {
  234. ExitWithError(ExitIO, err)
  235. }
  236. b, berr := st.Save()
  237. if berr != nil {
  238. ExitWithError(ExitError, berr)
  239. }
  240. raftSnap := raftpb.Snapshot{
  241. Data: b,
  242. Metadata: raftpb.SnapshotMetadata{
  243. Index: commit,
  244. Term: term,
  245. ConfState: raftpb.ConfState{
  246. Nodes: nodeIDs,
  247. },
  248. },
  249. }
  250. snapshotter := snap.New(snapdir)
  251. if err := snapshotter.SaveSnap(raftSnap); err != nil {
  252. panic(err)
  253. }
  254. if err := w.SaveSnapshot(walpb.Snapshot{Index: commit, Term: term}); err != nil {
  255. ExitWithError(ExitIO, err)
  256. }
  257. }
  258. // initIndex implements ConsistentIndexGetter so the snapshot won't block
  259. // the new raft instance by waiting for a future raft index.
  260. type initIndex int
  261. func (i *initIndex) ConsistentIndex() uint64 { return uint64(*i) }
  262. // makeDB copies the database snapshot to the snapshot directory
  263. func makeDB(snapdir, dbfile string, commit int) {
  264. f, ferr := os.OpenFile(dbfile, os.O_RDONLY, 0600)
  265. if ferr != nil {
  266. ExitWithError(ExitInvalidInput, ferr)
  267. }
  268. defer f.Close()
  269. // get snapshot integrity hash
  270. if _, err := f.Seek(-sha256.Size, io.SeekEnd); err != nil {
  271. ExitWithError(ExitIO, err)
  272. }
  273. sha := make([]byte, sha256.Size)
  274. if _, err := f.Read(sha); err != nil {
  275. ExitWithError(ExitIO, err)
  276. }
  277. if _, err := f.Seek(0, io.SeekStart); err != nil {
  278. ExitWithError(ExitIO, err)
  279. }
  280. if err := fileutil.CreateDirAll(snapdir); err != nil {
  281. ExitWithError(ExitIO, err)
  282. }
  283. dbpath := filepath.Join(snapdir, "db")
  284. db, dberr := os.OpenFile(dbpath, os.O_RDWR|os.O_CREATE, 0600)
  285. if dberr != nil {
  286. ExitWithError(ExitIO, dberr)
  287. }
  288. if _, err := io.Copy(db, f); err != nil {
  289. ExitWithError(ExitIO, err)
  290. }
  291. // truncate away integrity hash, if any.
  292. off, serr := db.Seek(0, io.SeekEnd)
  293. if serr != nil {
  294. ExitWithError(ExitIO, serr)
  295. }
  296. hasHash := (off % 512) == sha256.Size
  297. if hasHash {
  298. if err := db.Truncate(off - sha256.Size); err != nil {
  299. ExitWithError(ExitIO, err)
  300. }
  301. }
  302. if !hasHash && !skipHashCheck {
  303. err := fmt.Errorf("snapshot missing hash but --skip-hash-check=false")
  304. ExitWithError(ExitBadArgs, err)
  305. }
  306. if hasHash && !skipHashCheck {
  307. // check for match
  308. if _, err := db.Seek(0, io.SeekStart); err != nil {
  309. ExitWithError(ExitIO, err)
  310. }
  311. h := sha256.New()
  312. if _, err := io.Copy(h, db); err != nil {
  313. ExitWithError(ExitIO, err)
  314. }
  315. dbsha := h.Sum(nil)
  316. if !reflect.DeepEqual(sha, dbsha) {
  317. err := fmt.Errorf("expected sha256 %v, got %v", sha, dbsha)
  318. ExitWithError(ExitInvalidInput, err)
  319. }
  320. }
  321. // db hash is OK, can now modify DB so it can be part of a new cluster
  322. db.Close()
  323. // update consistentIndex so applies go through on etcdserver despite
  324. // having a new raft instance
  325. be := backend.NewDefaultBackend(dbpath)
  326. // a lessor never timeouts leases
  327. lessor := lease.NewLessor(be, math.MaxInt64)
  328. s := mvcc.NewStore(be, lessor, (*initIndex)(&commit))
  329. txn := s.Write()
  330. btx := be.BatchTx()
  331. del := func(k, v []byte) error {
  332. txn.DeleteRange(k, nil)
  333. return nil
  334. }
  335. // delete stored members from old cluster since using new members
  336. btx.UnsafeForEach([]byte("members"), del)
  337. // todo: add back new members when we start to deprecate old snap file.
  338. btx.UnsafeForEach([]byte("members_removed"), del)
  339. // trigger write-out of new consistent index
  340. txn.End()
  341. s.Commit()
  342. s.Close()
  343. }
  344. type dbstatus struct {
  345. Hash uint32 `json:"hash"`
  346. Revision int64 `json:"revision"`
  347. TotalKey int `json:"totalKey"`
  348. TotalSize int64 `json:"totalSize"`
  349. }
  350. func dbStatus(p string) dbstatus {
  351. if _, err := os.Stat(p); err != nil {
  352. ExitWithError(ExitError, err)
  353. }
  354. ds := dbstatus{}
  355. db, err := bolt.Open(p, 0400, &bolt.Options{ReadOnly: true})
  356. if err != nil {
  357. ExitWithError(ExitError, err)
  358. }
  359. defer db.Close()
  360. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  361. err = db.View(func(tx *bolt.Tx) error {
  362. // check snapshot file integrity first
  363. var dbErrStrings []string
  364. for dbErr := range tx.Check() {
  365. dbErrStrings = append(dbErrStrings, dbErr.Error())
  366. }
  367. if len(dbErrStrings) > 0 {
  368. return fmt.Errorf("snapshot file integrity check failed. %d errors found.\n"+strings.Join(dbErrStrings, "\n"), len(dbErrStrings))
  369. }
  370. ds.TotalSize = tx.Size()
  371. c := tx.Cursor()
  372. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  373. b := tx.Bucket(next)
  374. if b == nil {
  375. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  376. }
  377. h.Write(next)
  378. iskeyb := (string(next) == "key")
  379. b.ForEach(func(k, v []byte) error {
  380. h.Write(k)
  381. h.Write(v)
  382. if iskeyb {
  383. rev := bytesToRev(k)
  384. ds.Revision = rev.main
  385. }
  386. ds.TotalKey++
  387. return nil
  388. })
  389. }
  390. return nil
  391. })
  392. if err != nil {
  393. ExitWithError(ExitError, err)
  394. }
  395. ds.Hash = h.Sum32()
  396. return ds
  397. }
  398. type revision struct {
  399. main int64
  400. sub int64
  401. }
  402. func bytesToRev(bytes []byte) revision {
  403. return revision{
  404. main: int64(binary.BigEndian.Uint64(bytes[0:8])),
  405. sub: int64(binary.BigEndian.Uint64(bytes[9:])),
  406. }
  407. }