snapshot_command.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. "encoding/binary"
  17. "encoding/json"
  18. "fmt"
  19. "hash/crc32"
  20. "io"
  21. "os"
  22. "path"
  23. "strings"
  24. "github.com/boltdb/bolt"
  25. "github.com/coreos/etcd/etcdserver"
  26. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  27. "github.com/coreos/etcd/etcdserver/membership"
  28. "github.com/coreos/etcd/mvcc"
  29. "github.com/coreos/etcd/mvcc/backend"
  30. "github.com/coreos/etcd/pkg/fileutil"
  31. "github.com/coreos/etcd/pkg/types"
  32. "github.com/coreos/etcd/raft"
  33. "github.com/coreos/etcd/raft/raftpb"
  34. "github.com/coreos/etcd/wal"
  35. "github.com/spf13/cobra"
  36. "golang.org/x/net/context"
  37. )
  38. const (
  39. defaultName = "default"
  40. defaultInitialAdvertisePeerURLs = "http://localhost:2380"
  41. )
  42. var (
  43. restoreCluster string
  44. restoreClusterToken string
  45. restoreDataDir string
  46. restorePeerURLs string
  47. restoreName string
  48. )
  49. // NewSnapshotCommand returns the cobra command for "snapshot".
  50. func NewSnapshotCommand() *cobra.Command {
  51. cmd := &cobra.Command{
  52. Use: "snapshot",
  53. Short: "snapshot manages etcd node snapshots.",
  54. }
  55. cmd.AddCommand(NewSnapshotSaveCommand())
  56. cmd.AddCommand(NewSnapshotRestoreCommand())
  57. cmd.AddCommand(newSnapshotStatusCommand())
  58. return cmd
  59. }
  60. func NewSnapshotSaveCommand() *cobra.Command {
  61. return &cobra.Command{
  62. Use: "save <filename>",
  63. Short: "save stores an etcd node backend snapshot to a given file.",
  64. Run: snapshotSaveCommandFunc,
  65. }
  66. }
  67. func newSnapshotStatusCommand() *cobra.Command {
  68. return &cobra.Command{
  69. Use: "status <filename>",
  70. Short: "status gets backend snapshot status of a given file.",
  71. Long: `When --write-out is set to simple, this command prints out comma-separated status lists for each endpoint.
  72. The items in the lists are hash, revision, total keys, total size.
  73. `,
  74. Run: snapshotStatusCommandFunc,
  75. }
  76. }
  77. func NewSnapshotRestoreCommand() *cobra.Command {
  78. cmd := &cobra.Command{
  79. Use: "restore <filename>",
  80. Short: "restore an etcd member snapshot to an etcd directory",
  81. Run: snapshotRestoreCommandFunc,
  82. }
  83. cmd.Flags().StringVar(&restoreDataDir, "data-dir", "", "Path to the data directory.")
  84. cmd.Flags().StringVar(&restoreCluster, "initial-cluster", initialClusterFromName(defaultName), "Initial cluster configuration for restore bootstrap.")
  85. cmd.Flags().StringVar(&restoreClusterToken, "initial-cluster-token", "etcd-cluster", "Initial cluster token for the etcd cluster during restore bootstrap.")
  86. cmd.Flags().StringVar(&restorePeerURLs, "initial-advertise-peer-urls", defaultInitialAdvertisePeerURLs, "List of this member's peer URLs to advertise to the rest of the cluster.")
  87. cmd.Flags().StringVar(&restoreName, "name", defaultName, "Human-readable name for this member.")
  88. return cmd
  89. }
  90. func snapshotSaveCommandFunc(cmd *cobra.Command, args []string) {
  91. if len(args) != 1 {
  92. err := fmt.Errorf("snapshot save expects one argument")
  93. ExitWithError(ExitBadArgs, err)
  94. }
  95. path := args[0]
  96. partpath := path + ".part"
  97. f, err := os.Create(partpath)
  98. defer f.Close()
  99. if err != nil {
  100. exiterr := fmt.Errorf("could not open %s (%v)", partpath, err)
  101. ExitWithError(ExitBadArgs, exiterr)
  102. }
  103. c := mustClientFromCmd(cmd)
  104. r, serr := c.Snapshot(context.TODO())
  105. if serr != nil {
  106. os.RemoveAll(partpath)
  107. ExitWithError(ExitInterrupted, serr)
  108. }
  109. if _, rerr := io.Copy(f, r); rerr != nil {
  110. os.RemoveAll(partpath)
  111. ExitWithError(ExitInterrupted, rerr)
  112. }
  113. fileutil.Fsync(f)
  114. if rerr := os.Rename(partpath, path); rerr != nil {
  115. exiterr := fmt.Errorf("could not rename %s to %s (%v)", partpath, path, rerr)
  116. ExitWithError(ExitIO, exiterr)
  117. }
  118. fmt.Printf("Snapshot saved at %s\n", path)
  119. }
  120. func snapshotStatusCommandFunc(cmd *cobra.Command, args []string) {
  121. if len(args) != 1 {
  122. err := fmt.Errorf("snapshot status requires exactly one argument")
  123. ExitWithError(ExitBadArgs, err)
  124. }
  125. initDisplayFromCmd(cmd)
  126. ds := dbStatus(args[0])
  127. display.DBStatus(ds)
  128. }
  129. func snapshotRestoreCommandFunc(cmd *cobra.Command, args []string) {
  130. if len(args) != 1 {
  131. err := fmt.Errorf("snapshot restore requires exactly one argument")
  132. ExitWithError(ExitBadArgs, err)
  133. }
  134. urlmap, uerr := types.NewURLsMap(restoreCluster)
  135. if uerr != nil {
  136. ExitWithError(ExitBadArgs, uerr)
  137. }
  138. cfg := etcdserver.ServerConfig{
  139. InitialClusterToken: restoreClusterToken,
  140. InitialPeerURLsMap: urlmap,
  141. PeerURLs: types.MustNewURLs(strings.Split(restorePeerURLs, ",")),
  142. Name: restoreName,
  143. }
  144. if err := cfg.VerifyBootstrap(); err != nil {
  145. ExitWithError(ExitBadArgs, err)
  146. }
  147. cl, cerr := membership.NewClusterFromURLsMap(restoreClusterToken, urlmap)
  148. if cerr != nil {
  149. ExitWithError(ExitBadArgs, cerr)
  150. }
  151. basedir := restoreDataDir
  152. if basedir == "" {
  153. basedir = restoreName + ".etcd"
  154. }
  155. waldir := path.Join(basedir, "member", "wal")
  156. snapdir := path.Join(basedir, "member", "snap")
  157. if _, err := os.Stat(basedir); err == nil {
  158. ExitWithError(ExitInvalidInput, fmt.Errorf("data-dir %q exists", basedir))
  159. }
  160. makeDB(snapdir, args[0])
  161. makeWAL(waldir, cl)
  162. }
  163. func initialClusterFromName(name string) string {
  164. n := name
  165. if name == "" {
  166. n = defaultName
  167. }
  168. return fmt.Sprintf("%s=http://localhost:2380", n, n)
  169. }
  170. // makeWAL creates a WAL for the initial cluster
  171. func makeWAL(waldir string, cl *membership.RaftCluster) {
  172. if err := os.MkdirAll(waldir, 0755); err != nil {
  173. ExitWithError(ExitIO, err)
  174. }
  175. m := cl.MemberByName(restoreName)
  176. md := &etcdserverpb.Metadata{NodeID: uint64(m.ID), ClusterID: uint64(cl.ID())}
  177. metadata, merr := md.Marshal()
  178. if merr != nil {
  179. ExitWithError(ExitInvalidInput, merr)
  180. }
  181. w, walerr := wal.Create(waldir, metadata)
  182. if walerr != nil {
  183. ExitWithError(ExitIO, walerr)
  184. }
  185. defer w.Close()
  186. peers := make([]raft.Peer, len(cl.MemberIDs()))
  187. for i, id := range cl.MemberIDs() {
  188. ctx, err := json.Marshal((*cl).Member(id))
  189. if err != nil {
  190. ExitWithError(ExitInvalidInput, err)
  191. }
  192. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  193. }
  194. ents := make([]raftpb.Entry, len(peers))
  195. for i, p := range peers {
  196. cc := raftpb.ConfChange{
  197. Type: raftpb.ConfChangeAddNode,
  198. NodeID: p.ID,
  199. Context: p.Context}
  200. d, err := cc.Marshal()
  201. if err != nil {
  202. ExitWithError(ExitInvalidInput, err)
  203. }
  204. e := raftpb.Entry{
  205. Type: raftpb.EntryConfChange,
  206. Term: 1,
  207. Index: uint64(i + 1),
  208. Data: d,
  209. }
  210. ents[i] = e
  211. }
  212. w.Save(raftpb.HardState{
  213. Term: 1,
  214. Vote: peers[0].ID,
  215. Commit: uint64(len(ents))}, ents)
  216. }
  217. // initIndex implements ConsistentIndexGetter so the snapshot won't block
  218. // the new raft instance by waiting for a future raft index.
  219. type initIndex struct{}
  220. func (*initIndex) ConsistentIndex() uint64 { return 1 }
  221. // makeDB copies the database snapshot to the snapshot directory
  222. func makeDB(snapdir, dbfile string) {
  223. f, ferr := os.OpenFile(dbfile, os.O_RDONLY, 0600)
  224. if ferr != nil {
  225. ExitWithError(ExitInvalidInput, ferr)
  226. }
  227. defer f.Close()
  228. if err := os.MkdirAll(snapdir, 0755); err != nil {
  229. ExitWithError(ExitIO, err)
  230. }
  231. dbpath := path.Join(snapdir, "db")
  232. db, dberr := os.OpenFile(dbpath, os.O_WRONLY|os.O_CREATE, 0600)
  233. if dberr != nil {
  234. ExitWithError(ExitIO, dberr)
  235. }
  236. if _, err := io.Copy(db, f); err != nil {
  237. ExitWithError(ExitIO, err)
  238. }
  239. db.Close()
  240. // update consistentIndex so applies go through on etcdserver despite
  241. // having a new raft instance
  242. be := backend.NewDefaultBackend(dbpath)
  243. s := mvcc.NewStore(be, nil, &initIndex{})
  244. id := s.TxnBegin()
  245. btx := be.BatchTx()
  246. del := func(k, v []byte) error {
  247. _, _, err := s.TxnDeleteRange(id, k, nil)
  248. return err
  249. }
  250. // delete stored members from old cluster since using new members
  251. btx.UnsafeForEach([]byte("members"), del)
  252. btx.UnsafeForEach([]byte("members_removed"), del)
  253. // trigger write-out of new consistent index
  254. s.TxnEnd(id)
  255. s.Commit()
  256. s.Close()
  257. }
  258. type dbstatus struct {
  259. Hash uint32 `json:"hash"`
  260. Revision int64 `json:"revision"`
  261. TotalKey int `json:"totalKey"`
  262. TotalSize int64 `json:"totalSize"`
  263. }
  264. func dbStatus(p string) dbstatus {
  265. if _, err := os.Stat(p); err != nil {
  266. ExitWithError(ExitError, err)
  267. }
  268. ds := dbstatus{}
  269. db, err := bolt.Open(p, 0400, nil)
  270. if err != nil {
  271. ExitWithError(ExitError, err)
  272. }
  273. defer db.Close()
  274. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  275. err = db.View(func(tx *bolt.Tx) error {
  276. ds.TotalSize = tx.Size()
  277. c := tx.Cursor()
  278. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  279. b := tx.Bucket(next)
  280. if b == nil {
  281. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  282. }
  283. h.Write(next)
  284. iskeyb := (string(next) == "key")
  285. b.ForEach(func(k, v []byte) error {
  286. h.Write(k)
  287. h.Write(v)
  288. if iskeyb {
  289. rev := bytesToRev(k)
  290. ds.Revision = rev.main
  291. }
  292. ds.TotalKey++
  293. return nil
  294. })
  295. }
  296. return nil
  297. })
  298. if err != nil {
  299. ExitWithError(ExitError, err)
  300. }
  301. ds.Hash = h.Sum32()
  302. return ds
  303. }
  304. type revision struct {
  305. main int64
  306. sub int64
  307. }
  308. func bytesToRev(bytes []byte) revision {
  309. return revision{
  310. main: int64(binary.BigEndian.Uint64(bytes[0:8])),
  311. sub: int64(binary.BigEndian.Uint64(bytes[9:])),
  312. }
  313. }