snapshot_command.go 12 KB

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