snapshot_command.go 9.0 KB

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