snapshot_command.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. initDisplayFromCmd(cmd)
  121. ds := dbStatus(args[0])
  122. display.DBStatus(ds)
  123. }
  124. func snapshotRestoreCommandFunc(cmd *cobra.Command, args []string) {
  125. if len(args) != 1 {
  126. err := fmt.Errorf("snapshot restore requires exactly one argument")
  127. ExitWithError(ExitBadArgs, err)
  128. }
  129. urlmap, uerr := types.NewURLsMap(restoreCluster)
  130. if uerr != nil {
  131. ExitWithError(ExitBadArgs, uerr)
  132. }
  133. cfg := etcdserver.ServerConfig{
  134. InitialClusterToken: restoreClusterToken,
  135. InitialPeerURLsMap: urlmap,
  136. PeerURLs: types.MustNewURLs(strings.Split(restorePeerURLs, ",")),
  137. Name: restoreName,
  138. }
  139. if err := cfg.VerifyBootstrap(); err != nil {
  140. ExitWithError(ExitBadArgs, err)
  141. }
  142. cl, cerr := membership.NewClusterFromURLsMap(restoreClusterToken, urlmap)
  143. if cerr != nil {
  144. ExitWithError(ExitBadArgs, cerr)
  145. }
  146. basedir := restoreDataDir
  147. if basedir == "" {
  148. basedir = restoreName + ".etcd"
  149. }
  150. waldir := path.Join(basedir, "member", "wal")
  151. snapdir := path.Join(basedir, "member", "snap")
  152. if _, err := os.Stat(basedir); err == nil {
  153. ExitWithError(ExitInvalidInput, fmt.Errorf("data-dir %q exists", basedir))
  154. }
  155. makeDB(snapdir, args[0])
  156. makeWAL(waldir, cl)
  157. }
  158. func initialClusterFromName(name string) string {
  159. n := name
  160. if name == "" {
  161. n = defaultName
  162. }
  163. return fmt.Sprintf("%s=http://localhost:2380,%s=http://localhost:7001", n, n)
  164. }
  165. // makeWAL creates a WAL for the initial cluster
  166. func makeWAL(waldir string, cl *membership.RaftCluster) {
  167. if err := os.MkdirAll(waldir, 0755); err != nil {
  168. ExitWithError(ExitIO, err)
  169. }
  170. m := cl.MemberByName(restoreName)
  171. md := &etcdserverpb.Metadata{NodeID: uint64(m.ID), ClusterID: uint64(cl.ID())}
  172. metadata, merr := md.Marshal()
  173. if merr != nil {
  174. ExitWithError(ExitInvalidInput, merr)
  175. }
  176. w, walerr := wal.Create(waldir, metadata)
  177. if walerr != nil {
  178. ExitWithError(ExitIO, walerr)
  179. }
  180. defer w.Close()
  181. peers := make([]raft.Peer, len(cl.MemberIDs()))
  182. for i, id := range cl.MemberIDs() {
  183. ctx, err := json.Marshal((*cl).Member(id))
  184. if err != nil {
  185. ExitWithError(ExitInvalidInput, err)
  186. }
  187. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  188. }
  189. ents := make([]raftpb.Entry, len(peers))
  190. for i, p := range peers {
  191. cc := raftpb.ConfChange{
  192. Type: raftpb.ConfChangeAddNode,
  193. NodeID: p.ID,
  194. Context: p.Context}
  195. d, err := cc.Marshal()
  196. if err != nil {
  197. ExitWithError(ExitInvalidInput, err)
  198. }
  199. e := raftpb.Entry{
  200. Type: raftpb.EntryConfChange,
  201. Term: 1,
  202. Index: uint64(i + 1),
  203. Data: d,
  204. }
  205. ents[i] = e
  206. }
  207. w.Save(raftpb.HardState{
  208. Term: 1,
  209. Vote: peers[0].ID,
  210. Commit: uint64(len(ents))}, ents)
  211. }
  212. // initIndex implements ConsistentIndexGetter so the snapshot won't block
  213. // the new raft instance by waiting for a future raft index.
  214. type initIndex struct{}
  215. func (*initIndex) ConsistentIndex() uint64 { return 1 }
  216. // makeDB copies the database snapshot to the snapshot directory
  217. func makeDB(snapdir, dbfile string) {
  218. f, ferr := os.OpenFile(dbfile, os.O_RDONLY, 0600)
  219. if ferr != nil {
  220. ExitWithError(ExitInvalidInput, ferr)
  221. }
  222. defer f.Close()
  223. if err := os.MkdirAll(snapdir, 0755); err != nil {
  224. ExitWithError(ExitIO, err)
  225. }
  226. dbpath := path.Join(snapdir, "db")
  227. db, dberr := os.OpenFile(dbpath, os.O_WRONLY|os.O_CREATE, 0600)
  228. if dberr != nil {
  229. ExitWithError(ExitIO, dberr)
  230. }
  231. if _, err := io.Copy(db, f); err != nil {
  232. ExitWithError(ExitIO, err)
  233. }
  234. db.Close()
  235. // update consistentIndex so applies go through on etcdserver despite
  236. // having a new raft instance
  237. be := backend.NewDefaultBackend(dbpath)
  238. s := storage.NewStore(be, nil, &initIndex{})
  239. id := s.TxnBegin()
  240. btx := be.BatchTx()
  241. del := func(k, v []byte) error {
  242. _, _, err := s.TxnDeleteRange(id, k, nil)
  243. return err
  244. }
  245. // delete stored members from old cluster since using new members
  246. btx.UnsafeForEach([]byte("members"), del)
  247. btx.UnsafeForEach([]byte("members_removed"), del)
  248. // trigger write-out of new consistent index
  249. s.TxnEnd(id)
  250. s.Commit()
  251. s.Close()
  252. }
  253. type dbstatus struct {
  254. Hash uint32 `json:"hash"`
  255. Revision int64 `json:"revision"`
  256. TotalKey int `json:"totalKey"`
  257. TotalSize int64 `json:"totalSize"`
  258. }
  259. func dbStatus(p string) dbstatus {
  260. ds := dbstatus{}
  261. db, err := bolt.Open(p, 0600, nil)
  262. if err != nil {
  263. ExitWithError(ExitError, err)
  264. }
  265. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  266. err = db.View(func(tx *bolt.Tx) error {
  267. ds.TotalSize = tx.Size()
  268. c := tx.Cursor()
  269. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  270. b := tx.Bucket(next)
  271. if b == nil {
  272. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  273. }
  274. h.Write(next)
  275. iskeyb := (string(next) == "key")
  276. b.ForEach(func(k, v []byte) error {
  277. h.Write(k)
  278. h.Write(v)
  279. if iskeyb {
  280. rev := bytesToRev(k)
  281. ds.Revision = rev.main
  282. }
  283. ds.TotalKey++
  284. return nil
  285. })
  286. }
  287. return nil
  288. })
  289. if err != nil {
  290. ExitWithError(ExitError, err)
  291. }
  292. ds.Hash = h.Sum32()
  293. return ds
  294. }
  295. type revision struct {
  296. main int64
  297. sub int64
  298. }
  299. func bytesToRev(bytes []byte) revision {
  300. return revision{
  301. main: int64(binary.BigEndian.Uint64(bytes[0:8])),
  302. sub: int64(binary.BigEndian.Uint64(bytes[9:])),
  303. }
  304. }