【MIT-6.824】Lab 1: MapReduce

时间:2022-09-04 16:54:04

Lab 1链接:https://pdos.csail.mit.edu/6.824/labs/lab-1.html

Part I: Map/Reduce input and output

Part I需要补充两个关键功能:为map函数分解输出的功能和为reduce函数收集输入的功能,这两个功能对应的函数分别在common_map.go的doMap()函数和common_reduce.go的doRedce()函数。

本人首先梳理程序运行流程,其次补充代码,最后测试结果。

程序运行流程简述如下:

  1. Sequential首先获取Master对象的指针,然后利用函数闭包运行Master.run()。
  2. Master.run()会依次运行mapPhase和reducePhase。
  3. 在mapPhase中,doMap会依次处理每一个输入文件;在reducePhase中,doReduce会依次处理nReduce(论文中为R)个区域。

为实现doMap函数,需要实现以下功能:

  1. 读取inFile。
  2. 通过mapF函数,将inFile转换成key/value的切片形式。
  3. 将上一步得到的结果切割为nReduce个切片,并使用hash函数将结果分配到对应的切片中。
  4. 将上一步得到的结果转换为Json格式,并存储于文件中。
 func doMap(
jobName string, // the name of the MapReduce job
mapTask int, // which map task this is
inFile string,
nReduce int, // the number of reduce task that will be run ("R" in the paper)
mapF func(filename string, contents string) []KeyValue,
) {
// Your code here (Part I).
// read file
data, err := ioutil.ReadFile(inFile)
if err != nil{
log.Fatal("common_map.doMap: fail to read the file. The error is ", err)
} // transfer file
slice := mapF(inFile, string(data)) // initialize reduceKv
var reduceKv [][]KeyValue
for i := ; i < nReduce; i++{
temp := make([]KeyValue, )
reduceKv = append(reduceKv, temp)
} // get reduceKv
for _, s := range slice{
index := ihash(s.Key) % nReduce
reduceKv[index] = append(reduceKv[index], s)
} // get intermediate files
for i:= ; i < nReduce; i++{
file, err := os.Create(reduceName(jobName, mapTask, i))
if err != nil{
log.Fatal("common_map.doMap: fail to create the file. The error is ", err)
}
enc := json.NewEncoder(file)
for _, kv := range(reduceKv[i]){
err := enc.Encode(&kv)
if err != nil{
log.Fatal("common_map.doMap: fail to encode. The error is ", err)
}
}
file.Close()
}
}

为实现doReduce函数,需要实现如下功能:

  1. 读取文件中存储的key/value对,并对其进行排序。
  2. 将key值相同的value发送至用户定义的reduceF()中,reduceF()会返回一个新的value值。
  3. 将新的key/value对写入文件。
 func doReduce(
jobName string, // the name of the whole MapReduce job
reduceTask int, // which reduce task this is
outFile string, // write the output here
nMap int, // the number of map tasks that were run ("M" in the paper)
reduceF func(key string, values []string) string,
) {
// Your code here (Part I). // get and decode file
var slices []KeyValue
for i := ; i < nMap; i++{
fileName := reduceName(jobName, i, reduceTask)
file, err := os.Open(fileName)
if err != nil{
log.Fatal("common_reduce.doReduce: fail to open the file. The error is ", err)
}
dec := json.NewDecoder(file)
var kv KeyValue
for{
err := dec.Decode(&kv)
if err != nil{
break
}
slices = append(slices, kv)
}
file.Close()
} sort.Sort(ByKey(slices)) //return the reduced value for the key
var reducedValue []string
var outputValue []KeyValue
preKey := slices[].Key
for i, kv := range slices{
if kv.Key != preKey{
outputValue = append(outputValue, KeyValue{preKey, reduceF(preKey, reducedValue)})
reducedValue = make([]string,)
}
reducedValue = append(reducedValue, kv.Value)
preKey = kv.Key if i == (len(slices) - ){
outputValue = append(outputValue, KeyValue{preKey, reduceF(preKey, reducedValue)})
}
} //write and encode file
file, err := os.Create(outFile)
if err != nil{
log.Fatal("common_reduce.doReduce: fail to create the file. The error is ", err)
}
defer file.Close() enc := json.NewEncoder(file)
for _, kv := range outputValue{
err := enc.Encode(&kv)
if err != nil{
log.Fatal("common_reduce.doReduce: fail to encode. The error is ", err)
}
}
}

实验结果如下图所示:

【MIT-6.824】Lab 1: MapReduce

Part II: Single-worker word count

Part II需要统计文档中每个单词出现的数目,需要实现的函数为wc.go中的mapF()和reduceF()函数。

mapF()函数需要将文件拆分为单词,并返回mapreduce.KeyValue的形式。reduceF()函数需要统计每一个Key对应的Value出现的数目,并以string的形式返回。

 func mapF(filename string, contents string) []mapreduce.KeyValue {
// Your code here (Part II).
f := func(c rune) bool{
return !unicode.IsLetter(c)
} words := strings.FieldsFunc(contents, f)
var result []mapreduce.KeyValue
for _, word := range words{
result = append(result, mapreduce.KeyValue{word,""})
}
return result
} func reduceF(key string, values []string) string {
// Your code here (Part II).
sum :=
for _, value := range values{
i, err := strconv.Atoi(value)
if err != nil{
log.Fatal("wc.reduceF: fail to convert. The error is ", err)
}
sum += i
}
return strconv.Itoa(sum)
}

实验结果如下图所示:

【MIT-6.824】Lab 1: MapReduce

Part III: Distributing MapReduce tasks&&Part IV: Handling worker failures

Part III和Part IV需要将顺序执行的MapReduce框架并行化并处理worker异常。

本人分别介绍worker和master的执行流程。

worker:RunWorker()首先被调用,该函数创建新Worker并通过call()函数向Master.Register()发送RPC。

master:

  1. 在master.go的Distributed()函数中,master通过startRPCServer()启动RPC服务器,然后利用函数闭包运行run()函数。
  2. 在run()函数中,master会依次运行schedule(mapPhase)和schedule(reducePhase)。
  3. 在schedule(phase)函数中,master会开启新协程运行forwardRegistrations()函数,然后运行Part III和Part IV需要实现的schedule.go中的schedule()函数。
  4. 在介绍worker的执行流程时,本人提到worker会向Master.Register()发送RPC。在Register()函数中,master会将新的worker添加至mr.workers中并告知forwardRegistrations()出现了新的worker。
  5. 在forwardRegistrations()函数中,master通过mr.workers的数目判断是否有新的worker。若有新的worker,master通过channel通知schedule.go的schedule()函数。
  6. 在schedule()函数中,master负责为worker分配task。

为实现master对worker的调度,需要在schedule()函数中实现如下功能。

  1. 通过sync.WaitGroup判断全部任务是否完成。
  2. 通过registerChan判断是否有新的worker。若有,开启新协程为此worker分配任务。
  3. 通过带有缓冲的channel输入任务序号,从channel中取出任务序号并分配给worker。若worker异常,则重新输入任务序号。
  4. 通过call()函数向worker发送RPC。
 func schedule(jobName string, mapFiles []string, nReduce int, phase jobPhase, registerChan chan string) {
var ntasks int
var n_other int // number of inputs (for reduce) or outputs (for map)
switch phase {
case mapPhase:
ntasks = len(mapFiles)
n_other = nReduce
case reducePhase:
ntasks = nReduce
n_other = len(mapFiles)
} fmt.Printf("Schedule: %v %v tasks (%d I/Os)\n", ntasks, phase, n_other) // All ntasks tasks have to be scheduled on workers. Once all tasks
// have completed successfully, schedule() should return.
//
// Your code here (Part III, Part IV).
//
var wg sync.WaitGroup
wg.Add(ntasks) taskChan := make(chan int, ntasks)
for i := ; i < ntasks; i++{
taskChan <- i
} go func(){
for{
ch := <- registerChan
go func(address string){
for{
index := <- taskChan
result := call(address, "Worker.DoTask", &DoTaskArgs{jobName, mapFiles[index], phase, index, n_other},new(struct{}))
if result{
wg.Done()
fmt.Printf("Task %v has done\n", index)
}else{
taskChan <- index
}
}
}(ch)
}
}()
wg.Wait()
fmt.Printf("Schedule: %v done\n", phase)
}

Part V: Inverted index generation (optional, does not count in grade)

Part V需要实现倒排索引,需要补充的函数为ii.go中的mapF()和reduceF()函数。

mapF()函数需要对输入文件中的单词进行分割,返回以单词为Key,以文件题目为Value的切片。

reduceF()函数需要对相同Key对应的全部Value去重并排序,统计Value的个数。

 func mapF(document string, value string) (res []mapreduce.KeyValue) {
// Your code here (Part V).
f := func(c rune) bool{
return !unicode.IsLetter(c)
}
words := strings.FieldsFunc(value, f)
var result []mapreduce.KeyValue
for _, word := range words{
result = append(result, mapreduce.KeyValue{word, document})
}
return result
} func reduceF(key string, values []string) string {
// Your code here (Part V).
fileName := make(map[string]bool) for _, value := range values{
fileName[value] = true
} num :=
var documents []string
for key := range fileName{
num +=
documents = append(documents, key)
}
sort.Strings(documents) var result string
for i, file := range documents{
if i >= {
result += ","
}
result += file
}
return strconv.Itoa(num) + " " + result
}

实验结果如下图所示:

【MIT-6.824】Lab 1: MapReduce

Running all tests

【MIT-6.824】Lab 1: MapReduce

【MIT-6.824】Lab 1: MapReduce的更多相关文章

  1. 【MIT 6&period;824 】分布式系统 课程笔记(一)

    Lecture 02 Infrastructure: RPC & threads 一.多线程挑战 共享数据: 使用互斥信号量.或者避免共享 线程间协作: 使用channels 或者 waitg ...

  2. 【MIT 6&period;824 】分布式系统 课程笔记(二)Lecture 03 : GFS

    Lecture 03 : GFS 一.一致性 1, 弱一致性 可能会读到旧数据 2, 强一致性 读到的数据都是最新的 3, 一致性比较 强一致性对于app的写方便, 但是性能差 弱一致性有良好的性能, ...

  3. 【甘道夫】官方网站MapReduce代码注释具体实例

    引言 1.本文不描写叙述MapReduce入门知识,这类知识网上非常多.请自行查阅 2.本文的实例代码来自官网 http://hadoop.apache.org/docs/current/hadoop ...

  4. 【大数据系列】hadoop核心组件-MapReduce

    一.引入 hadoop的分布式计算框架(MapReduce是离线计算框架) 二.MapReduce设计理念 移动计算,而不是移动数据. Input HDFS先进行处理切成数据块(split)   ma ...

  5. MIT 6&period;824学习笔记1 MapReduce

    本节内容:Lect 1 MapReduce框架的执行过程: master分发任务,把map任务和reduce任务分发下去 map worker读取输入,进行map计算写入本地临时文件 map任务完成通 ...

  6. 【hadoop2&period;6&period;0】一句话形容mapreduce

    网上看到的: We want to count all the books in the library. You count up shelf #1, I count up shelf #2. Th ...

  7. MIT 6&period;824 lab1&colon;mapreduce

    这是 MIT 6.824 课程 lab1 的学习总结,记录我在学习过程中的收获和踩的坑. 我的实验环境是 windows 10,所以对lab的code 做了一些环境上的修改,如果你仅仅对code 感兴 ...

  8. 【hadoop代码笔记】Mapreduce shuffle过程之Map输出过程

    一.概要描述 shuffle是MapReduce的一个核心过程,因此没有在前面的MapReduce作业提交的过程中描述,而是单独拿出来比较详细的描述. 根据官方的流程图示如下: 本篇文章中只是想尝试从 ...

  9. 【甘道夫】MapReduce实现矩阵乘法--实现代码

    之前写了一篇分析MapReduce实现矩阵乘法算法的文章: [甘道夫]Mapreduce实现矩阵乘法的算法思路 为了让大家更直观的了解程序运行,今天编写了实现代码供大家參考. 编程环境: java v ...

随机推荐

  1. CYQ&period;Data V5 从入门到放弃ORM系列:教程 - AppConfig、AppDebug类的使用

    1:AppConfig类的介绍: Public Static (Shared) Properties IsEnumToInt 是否使用表字段枚举转Int方式(默认为false). 设置为true时,可 ...

  2. CSS画图

    The Shapes of CSS All of the below use only a single HTML element. Any kind of CSS goes, as long as ...

  3. Neutron 默认安全组规则 - 每天5分钟玩转 OpenStack(115)

    Neutron 为 instance 提供了两种管理网络安全的方法: 安全组(Security Group)和虚拟防火墙. 安全组的原理是通过 iptables 对 instance 所在计算节点的网 ...

  4. sql 入门经典(第五版) Ryan Stephens 学习笔记  第四部分:建立复杂的数据库查询&sol;

    第十三章: 在查询表里结合表 1.等值结合 : // 选择 tabla_a 和table_b 中id相等的行,输出 他们的id 和name select table_a.id , table_a.na ...

  5. iOS - UI - UISlider

    6.UISlider //滑块   设置高度 UISlider * slider = [[UISlider alloc] initWithFrame:CGRectMake(20, 100, CGRec ...

  6. Java 并发专题 : CyclicBarrier 打造一个安全的门禁系统

    继续并发专题~ 这次介绍CyclicBarrier:看一眼API的注释: /** * A synchronization aid that allows a set of threads to all ...

  7. 转载 Java基本数据类型

    Java语言是静态类型的(statical typed),也就是说所有变量和表达式的类型再编译时就已经完全确定.由于是statical typed,导致Java语言也是强类型(Strong typed ...

  8. Spring Boot分布式系统实践【扩展1】shiro&plus;redis实现session共享、simplesession反序列化失败的问题定位及反思改进

    前言 调试之前请先关闭Favicon配置 spring:     favicon:       enabled: false 不然会发现有2个请求(如果用nginx+ 浏览器调试的话) 序列化工具类[ ...

  9. spring实现一个简单的事务管理

    前两天给公司的数据库操作加了事务管理,今天博客就更一下这个吧. 先说明:本文只是简单得实现一下事务,事务的具体内容,比如事务的等级,事务的具体实现原理等等... 菜鸟水平有限,暂时还更不了这个,以后的 ...

  10. host大法之GitHub上不去

    dns解析慢,github上不去,慢 修改host. windows下路径为:C:\Windows\System32\drivers\etc\hosts Linux下路径:/etc/hosts 加入: ...