metadata_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. package metadata
  2. import (
  3. "net/http/httptest"
  4. "path/filepath"
  5. "testing"
  6. "time"
  7. "imuslab.com/arozos/mod/cluster/membership"
  8. )
  9. /*
  10. Helpers
  11. */
  12. func init() {
  13. //Shorten the liveness windows so leader failover is observable in tests
  14. membership.HeartbeatInterval = 500 * time.Millisecond
  15. membership.OnlineWindow = 2 * time.Second
  16. membership.OfflineWindow = 4 * time.Second
  17. }
  18. type testNode struct {
  19. m *membership.Manager
  20. meta *Manager
  21. srv *httptest.Server
  22. id string
  23. }
  24. func fastOption(m *membership.Manager) Option {
  25. return Option{
  26. Membership: m,
  27. LeaseDuration: 3 * time.Second,
  28. LeaseRenew: 1 * time.Second,
  29. LeaseTick: 200 * time.Millisecond,
  30. PendingRetry: 300 * time.Millisecond,
  31. LogKeep: 50,
  32. }
  33. }
  34. func newTestNode(t *testing.T, id string) *testNode {
  35. t.Helper()
  36. dir := t.TempDir()
  37. m, err := membership.NewManager(membership.Option{
  38. NodeID: id,
  39. DBFile: filepath.Join(dir, "cluster.db"),
  40. KeyFile: filepath.Join(dir, "node.key"),
  41. Version: "test",
  42. DefaultName: "Node " + id,
  43. })
  44. if err != nil {
  45. t.Fatalf("NewManager(%s): %v", id, err)
  46. }
  47. meta, err := New(fastOption(m))
  48. if err != nil {
  49. t.Fatalf("metadata.New(%s): %v", id, err)
  50. }
  51. srv := httptest.NewServer(m.ACNHandler())
  52. cfg := m.Config()
  53. cfg.AdvertiseURL = srv.URL
  54. if err := m.UpdateConfig(cfg); err != nil {
  55. t.Fatalf("UpdateConfig: %v", err)
  56. }
  57. n := &testNode{m: m, meta: meta, srv: srv, id: id}
  58. t.Cleanup(func() {
  59. meta.Close()
  60. m.Close()
  61. srv.Close()
  62. })
  63. return n
  64. }
  65. func waitFor(t *testing.T, what string, timeout time.Duration, cond func() bool) {
  66. t.Helper()
  67. deadline := time.Now().Add(timeout)
  68. for !cond() {
  69. if time.Now().After(deadline) {
  70. t.Fatalf("timed out waiting for %s", what)
  71. }
  72. time.Sleep(25 * time.Millisecond)
  73. }
  74. }
  75. // cluster3 returns three joined nodes; a joined first so it becomes leader.
  76. func cluster3(t *testing.T) (*testNode, *testNode, *testNode) {
  77. t.Helper()
  78. a := newTestNode(t, "node-a")
  79. b := newTestNode(t, "node-b")
  80. c := newTestNode(t, "node-c")
  81. if _, err := a.m.CreateCluster("Meta"); err != nil {
  82. t.Fatalf("CreateCluster: %v", err)
  83. }
  84. time.Sleep(1100 * time.Millisecond) //Joined is in seconds; keep a strictly first
  85. for _, n := range []*testNode{b, c} {
  86. token, _, _ := a.m.NewJoinToken(time.Hour)
  87. if _, err := n.m.JoinCluster(token); err != nil {
  88. t.Fatalf("JoinCluster(%s): %v", n.id, err)
  89. }
  90. }
  91. waitFor(t, "a to become leader", 10*time.Second, func() bool { return a.meta.IsLeader() })
  92. waitFor(t, "everyone to know the leader", 10*time.Second, func() bool {
  93. return b.meta.Leader() == "node-a" && c.meta.Leader() == "node-a"
  94. })
  95. return a, b, c
  96. }
  97. func hasPath(n *testNode, p string) bool {
  98. _, err := n.meta.Stat(p)
  99. return err == nil
  100. }
  101. /*
  102. Pure store tests
  103. */
  104. func TestNormalizePath(t *testing.T) {
  105. tests := map[string]string{
  106. "": "/",
  107. "/": "/",
  108. "photos": "/photos",
  109. "/photos/": "/photos",
  110. "cluster:/photos/a.jpg": "/photos/a.jpg",
  111. "cluster:photos\\x\\y": "/photos/x/y",
  112. "/a/../b/./c": "/b/c",
  113. "/../x": "/x",
  114. }
  115. for in, want := range tests {
  116. if got := NormalizePath(in); got != want {
  117. t.Errorf("NormalizePath(%q) = %q want %q", in, got, want)
  118. }
  119. }
  120. if TopFolder("/photos/2026/a.jpg") != "/photos" || TopFolder("/") != "/" || ParentPath("/a/b") != "/a" || ParentPath("/") != "/" {
  121. t.Errorf("TopFolder / ParentPath wrong")
  122. }
  123. }
  124. func TestStoreLWWAndPaths(t *testing.T) {
  125. n := newTestNode(t, "solo")
  126. st := n.meta.st
  127. if !st.putFile(&FileRecord{ID: "f1", Path: "/docs/a.txt", Size: 1, Version: 10}) {
  128. t.Fatalf("first put should store")
  129. }
  130. if st.putFile(&FileRecord{ID: "f1", Path: "/docs/a.txt", Size: 99, Version: 5}) {
  131. t.Errorf("older version must be ignored")
  132. }
  133. if rec, _ := st.getFileByPath("/docs/a.txt"); rec.Size != 1 {
  134. t.Errorf("stale write applied")
  135. }
  136. //Rename moves the path index
  137. st.putFile(&FileRecord{ID: "f1", Path: "/docs/b.txt", Size: 1, Version: 11})
  138. if _, ok := st.getFileByPath("/docs/a.txt"); ok {
  139. t.Errorf("old path still resolves")
  140. }
  141. if rec, ok := st.getFileByPath("/docs/b.txt"); !ok || rec.ID != "f1" {
  142. t.Errorf("new path does not resolve")
  143. }
  144. //Tombstone hides from listing but the record stays
  145. st.putFile(&FileRecord{ID: "f1", Path: "/docs/b.txt", Removed: true, Version: 12})
  146. if _, ok := st.getFileByPath("/docs/b.txt"); ok {
  147. t.Errorf("tombstone resolves")
  148. }
  149. if _, ok := st.getFileByID("f1"); !ok {
  150. t.Errorf("tombstone record lost")
  151. }
  152. //Re-create under the same path with a new ID and newer version wins
  153. st.putFile(&FileRecord{ID: "f2", Path: "/docs/b.txt", Version: 13})
  154. if rec, ok := st.getFileByPath("/docs/b.txt"); !ok || rec.ID != "f2" {
  155. t.Errorf("re-created path should resolve to f2")
  156. }
  157. }
  158. func TestStoreListDirAndPolicy(t *testing.T) {
  159. n := newTestNode(t, "solo")
  160. st := n.meta.st
  161. st.putFile(&FileRecord{ID: "d1", Path: "/photos", IsDir: true, Version: 1})
  162. st.putFile(&FileRecord{ID: "d2", Path: "/photos/2026", IsDir: true, Version: 1})
  163. st.putFile(&FileRecord{ID: "f1", Path: "/photos/a.jpg", Version: 1})
  164. st.putFile(&FileRecord{ID: "f2", Path: "/photos/2026/b.jpg", Version: 1})
  165. st.putFile(&FileRecord{ID: "f3", Path: "/photosx/c.jpg", Version: 1})
  166. root := st.listDir("/")
  167. if len(root) != 1 || root[0].Path != "/photos" {
  168. //"/photosx/c.jpg" has no directory record, so only /photos is a direct child
  169. t.Errorf("root should list only /photos, got %+v", root)
  170. }
  171. kids := st.listDir("/photos")
  172. if len(kids) != 2 || kids[0].Path != "/photos/2026" || kids[1].Path != "/photos/a.jpg" {
  173. t.Errorf("listDir(/photos) = %+v", kids)
  174. }
  175. if sub := st.listSubtree("/photos"); len(sub) != 3 {
  176. t.Errorf("subtree should have 3 entries, got %d", len(sub))
  177. }
  178. files, dirs := st.counts()
  179. if files != 3 || dirs != 2 {
  180. t.Errorf("counts = %d files %d dirs", files, dirs)
  181. }
  182. if p := st.policyFor("/photos/2026/b.jpg"); p.Replicas != 1 || p.Folder != "/photos" {
  183. t.Errorf("default policy wrong: %+v", p)
  184. }
  185. st.putPolicy(&Policy{Folder: "/photos/anything", Replicas: 3, Version: 1})
  186. if p := st.policyFor("/photos/2026/b.jpg"); p.Replicas != 3 {
  187. t.Errorf("policy lookup should walk to the top folder, got %+v", p)
  188. }
  189. if st.putPolicy(&Policy{Folder: "/photos", Replicas: 1, Version: 0}) {
  190. t.Errorf("older policy version applied")
  191. }
  192. }
  193. func TestStoreLog(t *testing.T) {
  194. n := newTestNode(t, "solo")
  195. st := n.meta.st
  196. for i := 0; i < 5; i++ {
  197. st.appendLog(Entry{Kind: KindPolicy}, 1)
  198. }
  199. if st.getLastSeq() != 5 {
  200. t.Fatalf("lastSeq = %d", st.getLastSeq())
  201. }
  202. entries, ok := st.logAfter(2, 10)
  203. if !ok || len(entries) != 3 || entries[0].Seq != 3 {
  204. t.Errorf("logAfter(2) = %v %+v", ok, entries)
  205. }
  206. entries, ok = st.logAfter(0, 2)
  207. if !ok || len(entries) != 2 {
  208. t.Errorf("logAfter page size ignored")
  209. }
  210. st.compactLog(2)
  211. if _, ok := st.logAfter(1, 10); ok {
  212. t.Errorf("compacted range should report not ok")
  213. }
  214. if entries, ok := st.logAfter(3, 10); !ok || len(entries) != 2 {
  215. t.Errorf("retained tail should be readable: %v %+v", ok, entries)
  216. }
  217. }
  218. /*
  219. Multi-node tests
  220. */
  221. func TestLeaderElectionAndFailover(t *testing.T) {
  222. a, b, c := cluster3(t)
  223. st := b.meta.Status()
  224. if st.Leader != "node-a" || st.IsLeader || st.LeaderName != "Node node-a" {
  225. t.Errorf("b status: %+v", st)
  226. }
  227. term := a.meta.st.getLease().Term
  228. //Leader dies completely (no heartbeats, no renewals): b (joined before c)
  229. //takes over once a drops out of the eligible set and the lease expires
  230. a.meta.Close()
  231. a.m.Close()
  232. a.srv.Close()
  233. waitFor(t, "b to become leader", 20*time.Second, func() bool { return b.meta.IsLeader() })
  234. waitFor(t, "c to follow b", 10*time.Second, func() bool { return c.meta.Leader() == "node-b" })
  235. if b.meta.st.getLease().Term <= term {
  236. t.Errorf("new leader must use a higher term")
  237. }
  238. //Changes keep flowing without a
  239. if err := b.meta.Submit(KindPolicy, &Policy{Folder: "/docs", Replicas: 2}); err != nil {
  240. t.Fatalf("submit on b: %v", err)
  241. }
  242. waitFor(t, "c to get the policy", 5*time.Second, func() bool { return c.meta.PolicyFor("/docs/x").Replicas == 2 })
  243. }
  244. func TestReplicationThroughLeaderAndFollower(t *testing.T) {
  245. a, b, c := cluster3(t)
  246. //Submit on the leader reaches both followers
  247. if err := a.meta.Submit(KindFile, &FileRecord{ID: "f1", Path: "/docs/a.txt", Size: 10}); err != nil {
  248. t.Fatalf("submit: %v", err)
  249. }
  250. waitFor(t, "followers to get f1", 5*time.Second, func() bool { return hasPath(b, "/docs/a.txt") && hasPath(c, "/docs/a.txt") })
  251. //Submit on a follower goes through the leader to everyone
  252. if err := c.meta.Submit(KindFile, &FileRecord{ID: "f2", Path: "/docs/b.txt", Size: 20}); err != nil {
  253. t.Fatalf("submit on c: %v", err)
  254. }
  255. waitFor(t, "a and b to get f2", 5*time.Second, func() bool { return hasPath(a, "/docs/b.txt") && hasPath(b, "/docs/b.txt") })
  256. //Version assigned by Submit strictly increases and older data never wins
  257. rec, _ := a.meta.Stat("/docs/a.txt")
  258. v1 := rec.Version
  259. rec.Size = 11
  260. a.meta.Submit(KindFile, rec)
  261. rec2, _ := a.meta.Stat("/docs/a.txt")
  262. if rec2.Version <= v1 || rec2.Size != 11 {
  263. t.Errorf("version not bumped: %d -> %d", v1, rec2.Version)
  264. }
  265. stale := rec2.Clone()
  266. stale.Size = 5
  267. stale.Version = v1
  268. b.meta.apply(mustEntry(t, KindFile, stale, v1, "node-b"))
  269. if got, _ := b.meta.Stat("/docs/a.txt"); got.Size == 5 {
  270. t.Errorf("stale entry overwrote newer record")
  271. }
  272. //Rename keeps the ID, directory listing works everywhere
  273. a.meta.Submit(KindFile, &FileRecord{ID: "d1", Path: "/docs", IsDir: true})
  274. rec, _ = a.meta.Stat("/docs/b.txt")
  275. rec.Path = "/docs/c.txt"
  276. a.meta.Submit(KindFile, rec)
  277. waitFor(t, "rename to reach b", 5*time.Second, func() bool {
  278. r, err := b.meta.Stat("/docs/c.txt")
  279. return err == nil && r.ID == "f2" && !hasPath(b, "/docs/b.txt")
  280. })
  281. if kids, err := c.meta.ListDir("/docs"); err != nil || len(kids) != 2 {
  282. t.Errorf("ListDir on c: %v %+v", err, kids)
  283. }
  284. }
  285. func TestCatchupByLogAndSnapshot(t *testing.T) {
  286. a, b, _ := cluster3(t)
  287. //Isolate b: close its server so pushes fail, then write on a
  288. b.srv.Close()
  289. for i := 0; i < 5; i++ {
  290. a.meta.Submit(KindFile, &FileRecord{ID: "f" + string(rune('0'+i)), Path: "/logs/" + string(rune('0'+i)), Size: int64(i)})
  291. }
  292. if hasPath(b, "/logs/4") {
  293. t.Fatalf("b must not have received pushes while isolated")
  294. }
  295. //Bring b back with a fresh server on a new URL; heartbeats carry the lease
  296. //and lastSeq so b notices the gap and catches up by log
  297. b.srv = httptest.NewServer(b.m.ACNHandler())
  298. cfg := b.m.Config()
  299. cfg.AdvertiseURL = b.srv.URL
  300. b.m.UpdateConfig(cfg)
  301. waitFor(t, "b to catch up by log", 15*time.Second, func() bool { return hasPath(b, "/logs/0") && hasPath(b, "/logs/4") })
  302. //Now force a snapshot: compact the leader log entirely and reset b
  303. b.srv.Close()
  304. for i := 0; i < 60; i++ {
  305. a.meta.Submit(KindPolicy, &Policy{Folder: "/p" + uitoa(uint64(i)), Replicas: 2})
  306. }
  307. a.meta.st.compactLog(0)
  308. b.srv = httptest.NewServer(b.m.ACNHandler())
  309. cfg.AdvertiseURL = b.srv.URL
  310. b.m.UpdateConfig(cfg)
  311. waitFor(t, "b to catch up by snapshot", 15*time.Second, func() bool {
  312. return b.meta.PolicyFor("/p59/x").Replicas == 2 && b.meta.Status().Applied == a.meta.st.getLastSeq()
  313. })
  314. }
  315. func TestPendingWhenNoLeader(t *testing.T) {
  316. a := newTestNode(t, "node-a")
  317. if err := a.meta.Submit(KindFile, &FileRecord{ID: "x", Path: "/x"}); err != ErrNotInCluster {
  318. t.Errorf("submit outside cluster: %v", err)
  319. }
  320. a.m.CreateCluster("Solo")
  321. //Before the first lease tick there is no leader: change is queued locally
  322. if err := a.meta.Submit(KindFile, &FileRecord{ID: "x", Path: "/x", Size: 1}); err != nil {
  323. t.Fatalf("submit: %v", err)
  324. }
  325. if !hasPath(a, "/x") {
  326. t.Errorf("local apply must be immediate")
  327. }
  328. waitFor(t, "pending to drain once a is leader", 10*time.Second, func() bool {
  329. return a.meta.IsLeader() && a.meta.Status().Pending == 0 && a.meta.st.getLastSeq() >= 1
  330. })
  331. }
  332. func TestLeaveResetsStore(t *testing.T) {
  333. a, b, _ := cluster3(t)
  334. a.meta.Submit(KindFile, &FileRecord{ID: "f1", Path: "/keep.txt"})
  335. waitFor(t, "b to get the file", 5*time.Second, func() bool { return hasPath(b, "/keep.txt") })
  336. if err := b.m.LeaveCluster(); err != nil {
  337. t.Fatalf("leave: %v", err)
  338. }
  339. if hasPath(b, "/keep.txt") || b.meta.Status().InCluster {
  340. t.Errorf("metadata should be wiped after leaving")
  341. }
  342. if hasPath(a, "/keep.txt") == false {
  343. t.Errorf("a must keep its data")
  344. }
  345. }
  346. func mustEntry(t *testing.T, kind string, rec interface{}, version int64, origin string) Entry {
  347. t.Helper()
  348. e, err := newEntry(kind, rec, version, origin)
  349. if err != nil {
  350. t.Fatalf("newEntry: %v", err)
  351. }
  352. return e
  353. }