-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
282 lines (243 loc) · 7.8 KB
/
worker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package mr
import (
"fmt"
"log"
"net/rpc"
"hash/fnv"
"os"
"io/ioutil"
"time"
"encoding/json"
"sort"
)
////////////////////////////////////////////////
// Declarations
////////////////////////////////////////////////
//
// Map functions return a slice of KeyValue.
//
type KeyValue struct {
Key string
Value string
}
type WorkerDetails struct {
Id int
Pid int
R int // No of reduce workers
StartTime time.Time
State string // state of worker : Map, Reduce, Done, Wait
MapFileName string // Ts
ReduceFileName string // TS
ReduceFileNo int // TS
Status string
AllMapWorkers []int // TS
}
var CurrentWorker WorkerDetails
////////////////////////////////////////////////
// Main Functions
////////////////////////////////////////////////
//
// main/mrworker.go calls this function.
//
func Worker(mapf func(string, string) []KeyValue, reducef func(string, []string) string) bool {
CurrentWorker = GetTask()
///fmt.Println("Current worker details are :",CurrentWorker)
// A special keyword to tell if all files are done
for CurrentWorker.State != "Done" {
if CurrentWorker.State == "Map"{
MapTask(CurrentWorker.MapFileName, mapf)
//time.Sleep(50 * time.Millisecond) // Used to test map running in parallel or not
TellMasterIAmDone(CurrentWorker)
///res := TellMasterIAmDone(CurrentWorker)
///fmt.Println("Master reply for our Done request, for Map worker ",CurrentWorker.Id,res.Message)
} else if CurrentWorker.State == "Wait" {
time.Sleep(1 * time.Second)
} else if CurrentWorker.State == "Reduce" {
ReduceTask(CurrentWorker.ReduceFileNo, CurrentWorker.AllMapWorkers, reducef)
//time.Sleep(50 * time.Millisecond) // Used to test reduce running in parallel or not
TellMasterIAmDone(CurrentWorker)
///res := TellMasterIAmDone(CurrentWorker)
///fmt.Println("Master reply for our Done request, for Reduce worker ",CurrentWorker.Id,res.Message)
}
//fmt.Println(CurrentWorker)
CurrentWorker = GetTask()
}
return true
}
////////////////////////////////////////////////
// Map Reduce functions
////////////////////////////////////////////////
// for sorting by key.
type ByKey []KeyValue
// for sorting by key.
func (a ByKey) Len() int { return len(a) }
func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByKey) Less(i, j int) bool { return a[i].Key < a[j].Key }
// Perform map job for the current file with the passed map func
func MapTask(filename string, mapf func(string,string)[]KeyValue) bool {
create := CreateInterFiles()
if !create {
return false
}
file, err := os.Open(filename)
if err != nil {
log.Fatalf("cannot open %v", filename)
return false
}
content, err := ioutil.ReadAll(file)
if err != nil {
log.Fatalf("cannot read %v", filename)
return false
}
//fmt.Println(content)
file.Close()
//fmt.Println(string(content))
kva := mapf(filename, string(content))
for _,kv := range kva {
reduceFileNo := (ihash(kv.Key) % CurrentWorker.R)
WriteMapTo(reduceFileNo,kv)
}
return true
}
// Perform Reduce Job for the current file with the passed reduce function
func ReduceTask(reduceFileNo int,listOfMapWorkerFiles []int, reducef func(string, []string)string ) bool {
// get all the files to read from NXM buckets
// load to memory(in a slice)
intermediate := GetKvForReduce(listOfMapWorkerFiles, reduceFileNo)
//fmt.Println("intermediate values are ",intermediate)
// sort the slice, Map-Reduce paper states if the intermediate data is too large for memory
// we send it for external sort
sort.Sort(ByKey(intermediate))
// create file to write to
reduceFile := fmt.Sprint("mr-out-", reduceFileNo)
rFile, err := os.Create(reduceFile)
if err != nil {
return false
}
// reducef
//
// call Reduce on each distinct key in intermediate[],
// and print the result to mr-out-*.
//
i := 0
for i < len(intermediate) {
j := i + 1
// Find the first index which is different from intermediate[i].key
for j < len(intermediate) && intermediate[j].Key == intermediate[i].Key {
j++
}
values := []string{}
for k := i; k < j; k++ {
values = append(values, intermediate[k].Value)
}
output := reducef(intermediate[i].Key, values)
//fmt.Println("intermediate key for reduce is : ",intermediate[i].Key)
// write to file
fmt.Fprintf(rFile, "%v %v\n", intermediate[i].Key, output)
i = j
}
// close file
rFile.Close()
return true
}
////////////////////////////////////////////////
// Helper functions
////////////////////////////////////////////////
//
// use ihash(key) % NReduce to choose the reduce
// task number for each KeyValue emitted by Map.
//
func ihash(key string) int {
h := fnv.New32a()
h.Write([]byte(key))
return int(h.Sum32() & 0x7fffffff)
}
// Tell Master worker is done
func TellMasterIAmDone(worker WorkerDetails ) MessageForWorker {
Msg := MessageForWorker{}
call("MasterDetails.WorkerDone", &worker, &Msg)
///fmt.Println("Message received is ",Msg.Message)
return Msg
}
// Ask for new task from Master
func GetTask() WorkerDetails{
na := NoArgs{}
NewTask := WorkerDetails{}
call("MasterDetails.AssignNewTask",&na, &NewTask)
///fmt.Println("Task is :", NewTask.Task)
return NewTask
}
// Create R(no of reduce files to create) Temporary Map files
func CreateInterFiles() bool {
//fmt.Println("creating new interm files",CurrentWorker.R)
for i:= 0; i < CurrentWorker.R; i++{
tFile := fmt.Sprint("mr-inter-" , CurrentWorker.Id , "-" , i ,".tmp")
nFile,err := os.Create(tFile)
if err != nil {
fmt.Println(err)
return false
}
nFile.Close()
}
return true
}
// Write Map KeyValue Slice output to R-th file
func WriteMapTo(reduceFileNo int,KV KeyValue) bool {
filename := fmt.Sprint("mr-inter-", CurrentWorker.Id, "-", reduceFileNo, ".tmp")
file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Println("Error while writinf to map file", err)
}
enc := json.NewEncoder(file)
er := enc.Encode(KV)
if er != nil {
fmt.Println(err)
}
file.Close()
return true
}
// Read data from all the intermediate files for a specefic reduce task
func GetKvForReduce(listOfMapWorkerFiles []int, reduceFileNo int) []KeyValue {
kva := []KeyValue{}
for _, mapworker := range listOfMapWorkerFiles {
interFile := fmt.Sprint("mr-inter-", mapworker, "-", reduceFileNo)
file, err := os.Open(interFile)
if err != nil {
fmt.Println("err in GetKvForReduce", err)
}
dec := json.NewDecoder(file)
for {
var kv KeyValue
if err := dec.Decode(&kv); err != nil {
break
}
//fmt.Println("Kv for this ket is ",kv)
kva = append(kva, kv)
}
file.Close()
}
return kva
}
////////////////////////////////////////////////
// Send RPC
////////////////////////////////////////////////
// send an RPC request to the master, wait for the response.
// usually returns true.
// returns false if something goes wrong.
//
func call(rpcname string, args interface{}, reply interface{}) bool {
//, err := rpc.DialHTTP("tcp", "127.0.0.1"+":1534")
sockname := masterSock()
c, err := rpc.DialHTTP("unix", sockname)
if err != nil {
fmt.Println(err)
log.Fatal("dialing:", err)
}
defer c.Close()
err = c.Call(rpcname, args, reply)
if err == nil {
return true
}
fmt.Println("Error in call function for server",err)
return false
}