mapreduce_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package jobs
  2. import (
  3. "context"
  4. "encoding/json"
  5. "path"
  6. "strings"
  7. "testing"
  8. "time"
  9. "imuslab.com/arozos/mod/cluster/metadata"
  10. )
  11. /*
  12. mrExecutor pretends to be the AGI runtime for map/reduce: it recognises
  13. the wrappers the runner builds and produces what the real scripts would.
  14. Map tasks emit (extension, 1) per input; the reducer sums the values.
  15. */
  16. type mrExecutor struct {
  17. base *fakeExecutor
  18. node string
  19. }
  20. func (m *mrExecutor) UserExists(owner string) bool { return m.base.UserExists(owner) }
  21. func (m *mrExecutor) Run(ctx context.Context, rec Record, source string, hooks ExecHooks) (json.RawMessage, error) {
  22. m.base.mu.Lock()
  23. m.base.ran = append(m.base.ran, rec.Spec.ID)
  24. fail := m.base.failAll
  25. m.base.mu.Unlock()
  26. if fail {
  27. return nil, ErrNoMapper
  28. }
  29. switch {
  30. case strings.Contains(source, "mapper(JOB.inputs, emit)"):
  31. if !strings.Contains(source, "function mapper(") {
  32. return nil, ErrNoMapper
  33. }
  34. pairs := [][]interface{}{}
  35. for _, in := range rec.Spec.Inputs {
  36. ext := strings.TrimPrefix(path.Ext(in), ".")
  37. pairs = append(pairs, []interface{}{ext, 1})
  38. }
  39. js, _ := json.Marshal(pairs)
  40. if hooks.Log != nil {
  41. hooks.Log("mapped " + itoa(len(rec.Spec.Inputs)) + " files on " + rec.State.Node)
  42. }
  43. return js, nil
  44. case strings.Contains(source, "reducer(__keys["):
  45. var args struct {
  46. Groups map[string][]json.RawMessage `json:"groups"`
  47. }
  48. if json.Unmarshal(rec.Spec.Args, &args) != nil {
  49. return nil, ErrNoMapper
  50. }
  51. out := map[string]int{}
  52. for k, vals := range args.Groups {
  53. out[k] = len(vals)
  54. }
  55. js, _ := json.Marshal(out)
  56. return js, nil
  57. }
  58. return json.RawMessage(`null`), nil
  59. }
  60. const mrScript = `function mapper(files, emit) { files.forEach(function(f){ emit(f, 1); }); }
  61. function reducer(key, values) { return values.length; }`
  62. // addFile publishes a file record with a healthy copy on the given node.
  63. func addFile(t *testing.T, n *testNode, p string, node string, volume string) {
  64. t.Helper()
  65. rec := &metadata.FileRecord{ID: "file:" + p, Path: p, Size: 10, Checksum: "x"}
  66. rec.SetLocation(metadata.Location{VolumeID: volume, NodeID: node, State: metadata.LocVerified, Checksum: "x"})
  67. rec.Primary = volume
  68. if err := n.meta.Submit(metadata.KindFile, rec); err != nil {
  69. t.Fatalf("submit file: %v", err)
  70. }
  71. }
  72. func addVolume(t *testing.T, n *testNode, id string, node string) {
  73. t.Helper()
  74. if err := n.meta.Submit(metadata.KindVolume, &metadata.Volume{ID: id, NodeID: node, Name: id}); err != nil {
  75. t.Fatalf("submit volume: %v", err)
  76. }
  77. }
  78. func TestMapReduceSourceWrappers(t *testing.T) {
  79. m := sourceFor(Record{Spec: Spec{Kind: KindMap, Script: mrScript}})
  80. if !strings.Contains(m, "mapper(JOB.inputs, emit)") || !strings.Contains(m, "__emitted") {
  81. t.Errorf("map wrapper wrong")
  82. }
  83. r := sourceFor(Record{Spec: Spec{Kind: KindReduce, Script: mrScript}})
  84. if !strings.Contains(r, "reducer(__keys[") || !strings.Contains(r, "JOB.args.groups") {
  85. t.Errorf("reduce wrapper wrong")
  86. }
  87. plain := sourceFor(Record{Spec: Spec{Kind: KindRun, Script: goodScript}})
  88. if !strings.Contains(plain, "run(JOB)") {
  89. t.Errorf("run wrapper wrong")
  90. }
  91. }
  92. func TestMapReduceEndToEnd(t *testing.T) {
  93. base := newExec("toby")
  94. execA := &mrExecutor{base: base, node: "node-a"}
  95. execB := &mrExecutor{base: newExec("toby"), node: "node-b"}
  96. a := newTestNode(t, "node-a", execA, manifest("linux", "amd64"))
  97. b := newTestNode(t, "node-b", execB, manifest("linux", "amd64"))
  98. if _, err := a.m.CreateCluster("MR"); err != nil {
  99. t.Fatalf("CreateCluster: %v", err)
  100. }
  101. time.Sleep(1100 * time.Millisecond)
  102. token, _, _ := a.m.NewJoinToken(time.Hour)
  103. if _, err := b.m.JoinCluster(token); err != nil {
  104. t.Fatalf("join: %v", err)
  105. }
  106. waitFor(t, "leader", 10*time.Second, func() bool { return a.meta.IsLeader() && b.meta.Leader() == "node-a" })
  107. //Six jpg on a, three png on b
  108. addVolume(t, a, "vol-a", "node-a")
  109. addVolume(t, a, "vol-b", "node-b")
  110. for i := 0; i < 6; i++ {
  111. addFile(t, a, "/data/a"+itoa(i)+".jpg", "node-a", "vol-a")
  112. }
  113. for i := 0; i < 3; i++ {
  114. addFile(t, a, "/data/b"+itoa(i)+".png", "node-b", "vol-b")
  115. }
  116. waitFor(t, "files replicated", 5*time.Second, func() bool { return len(b.meta.Glob("/data/**")) == 9 })
  117. rec, err := a.jobs.Submit(Spec{
  118. Owner: "toby", Name: "count", Script: mrScript, Kind: KindMapReduce,
  119. Dataset: "cluster:/data/**", PartitionMax: 4,
  120. })
  121. if err != nil {
  122. t.Fatalf("Submit: %v", err)
  123. }
  124. waitFor(t, "map/reduce to finish", 30*time.Second, func() bool {
  125. r, ok := a.jobs.Get(rec.Spec.ID)
  126. return ok && r.Done()
  127. })
  128. final, _ := a.jobs.Get(rec.Spec.ID)
  129. if final.State.Status != StatusSucceeded {
  130. t.Fatalf("parent failed: %+v", final.State)
  131. }
  132. var out map[string]int
  133. if err := json.Unmarshal(final.State.Output, &out); err != nil {
  134. t.Fatalf("output: %v (%s)", err, final.State.Output)
  135. }
  136. if out["jpg"] != 6 || out["png"] != 3 {
  137. t.Errorf("counts wrong: %+v", out)
  138. }
  139. if final.State.Progress != 1 {
  140. t.Errorf("progress should be 1, got %v", final.State.Progress)
  141. }
  142. //Children: map tasks ran where their inputs are, plus one reduce
  143. kids := a.jobs.children(rec.Spec.ID)
  144. mapCount, reduceCount := 0, 0
  145. for _, k := range kids {
  146. switch k.Spec.Kind {
  147. case KindMap:
  148. mapCount++
  149. if len(k.Spec.Inputs) > 4 {
  150. t.Errorf("partition larger than PartitionMax: %d", len(k.Spec.Inputs))
  151. }
  152. //Every input of a map task has a copy on the node that ran it
  153. for _, in := range k.Spec.Inputs {
  154. fr, err := a.meta.Stat(in)
  155. if err != nil {
  156. t.Fatalf("stat %s: %v", in, err)
  157. }
  158. onNode := false
  159. for _, l := range fr.HealthyLocations() {
  160. if l.NodeID == k.State.Node {
  161. onNode = true
  162. }
  163. }
  164. if !onNode {
  165. t.Errorf("map task ran on %s but %s has no copy there", k.State.Node, in)
  166. }
  167. }
  168. case KindReduce:
  169. reduceCount++
  170. }
  171. }
  172. //6 jpg on a -> 2 partitions (max 4), 3 png on b -> 1 partition
  173. if mapCount != 3 || reduceCount != 1 {
  174. t.Errorf("expected 3 map tasks and 1 reduce, got %d and %d", mapCount, reduceCount)
  175. }
  176. }
  177. func TestMapReduceValidationAndOrphans(t *testing.T) {
  178. a := newTestNode(t, "solo", newExec("toby"), manifest("linux", "amd64"))
  179. a.m.CreateCluster("MR")
  180. waitFor(t, "leader", 5*time.Second, func() bool { return a.meta.IsLeader() })
  181. if _, err := a.jobs.Submit(Spec{Owner: "toby", Script: mrScript, Kind: KindMapReduce}); err == nil {
  182. t.Errorf("map/reduce without a dataset accepted")
  183. }
  184. //A dataset that matches nothing succeeds with an empty result
  185. rec, err := a.jobs.Submit(Spec{Owner: "toby", Name: "empty", Script: mrScript, Kind: KindMapReduce, Dataset: "/nothing/**"})
  186. if err != nil {
  187. t.Fatalf("Submit: %v", err)
  188. }
  189. waitFor(t, "empty dataset job", 10*time.Second, func() bool {
  190. r, ok := a.jobs.Get(rec.Spec.ID)
  191. return ok && r.Done()
  192. })
  193. final, _ := a.jobs.Get(rec.Spec.ID)
  194. if final.State.Status != StatusSucceeded || string(final.State.Output) != "{}" {
  195. t.Errorf("empty dataset: %+v", final.State)
  196. }
  197. //A file whose only copy is on an unknown node fails the job with a reason
  198. addVolume(t, a, "ghost-vol", "ghost-node")
  199. addFile(t, a, "/data/lost.jpg", "ghost-node", "ghost-vol")
  200. rec2, _ := a.jobs.Submit(Spec{Owner: "toby", Name: "orphan", Script: mrScript, Kind: KindMapReduce, Dataset: "/data/**"})
  201. waitFor(t, "orphan job to fail", 10*time.Second, func() bool {
  202. r, ok := a.jobs.Get(rec2.Spec.ID)
  203. return ok && r.State.Status == StatusFailed
  204. })
  205. failed, _ := a.jobs.Get(rec2.Spec.ID)
  206. if !strings.Contains(failed.State.Error, "lost.jpg") {
  207. t.Errorf("failure should name the unreachable file: %q", failed.State.Error)
  208. }
  209. }
  210. func TestMapFailureFailsParent(t *testing.T) {
  211. base := newExec("toby")
  212. base.failAll = true
  213. a := newTestNode(t, "solo", &mrExecutor{base: base}, manifest("linux", "amd64"))
  214. a.m.CreateCluster("MR")
  215. waitFor(t, "leader", 5*time.Second, func() bool { return a.meta.IsLeader() })
  216. addVolume(t, a, "vol", "solo")
  217. addFile(t, a, "/data/x.jpg", "solo", "vol")
  218. rec, err := a.jobs.Submit(Spec{Owner: "toby", Name: "boom", Script: mrScript, Kind: KindMapReduce, Dataset: "/data/**", MaxAttempts: 1})
  219. if err != nil {
  220. t.Fatalf("Submit: %v", err)
  221. }
  222. waitFor(t, "parent to fail", 30*time.Second, func() bool {
  223. r, ok := a.jobs.Get(rec.Spec.ID)
  224. return ok && r.State.Status == StatusFailed
  225. })
  226. final, _ := a.jobs.Get(rec.Spec.ID)
  227. if !strings.Contains(final.State.Error, "map") {
  228. t.Errorf("parent error should name the failing task: %q", final.State.Error)
  229. }
  230. for _, k := range a.jobs.children(rec.Spec.ID) {
  231. if !k.Done() {
  232. t.Errorf("child %s left running after the parent failed", k.Spec.Name)
  233. }
  234. }
  235. }