本篇将解读nsqlookup处理tcp请求的核心代码文件lookup_protocol_v1.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package nsqlookupd

import (
    "bufio"
    "encoding/binary"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net"
    "os"
    "strings"
    "time"

    "github.com/bitly/go-nsq"
    "github.com/bitly/nsq/util"
)

type LookupProtocolV1 struct {
    context *Context
}

//实现util\Protocol.go中定义的Protocol的接口的IOLoop方法
func (p *LookupProtocolV1) IOLoop(conn net.Conn) error {
    var err error
    var line string

    //在nsqlookupd\client_v1.go中定义了NewClientV1方法
    client := NewClientV1(conn)
    err = nil
    //此处需要注意为何NewReader可以传入client作为参数。
    //打开client_v1.go可以看到,其中嵌入了net.Conn,用JAVA的思想可以说,ClientV1是继承自net.Conn的。
    //那接下来的问题是:查官方文档http://golang.org/pkg/bufio/#NewReader
    //NewReader的参数类型为io.Reader,这和net.Conn也不同啊
    //为一探究竟,我们打开go的源码。分别打开go源码下src\pkg\io\io.go和src\pkg\net\net.go
    //发现io.Reader是一个接口,其中有一个方法 Read(p []byte) (n int, err error)
    //net.Conn也是一个接口,下面有很多方法,其中一个是 Read(b []byte) (n int, err error)
    //可以看出,这两个方法的参数是完全一样的。即net.Conn里的方法完全能覆盖io.Reader里定义的方法

    //插播一段关于go接口的描述:所谓Go语言式的接口,就是不用显示声明类型T实现了接口I,只要类型T的公开方法完全满足接口I的要求,就可以把类型T的对象用在需要接口I的地方。这种做法的学名叫做Structural Typing

    //所以我们这里可以传入client作为参数
    reader := bufio.NewReader(client)
    for {
        //每次读取一行数据
        line, err = reader.ReadString('\n')
        if err != nil {
            break
        }

        //去掉两边的空格
        line = strings.TrimSpace(line)
        //将数据用空格分割成数组,根据后面的代码可看出,第一个参数是动作类型,包括四种:PING IDENTIFY REGISTER UNREGISTER
        params := strings.Split(line, " ")

        //调用LookupProtocolV1的Exec方法
        response, err := p.Exec(client, reader, params)
        if err != nil {
            context := ""
            if parentErr := err.(util.ChildErr).Parent(); parentErr != nil {
                context = " - " + parentErr.Error()
            }
            log.Printf("ERROR: [%s] - %s%s", client, err.Error(), context)

            //返回错误给客户端,SendResponse方法在util\Protocol.go中定义
            _, err = util.SendResponse(client, []byte(err.Error()))
            if err != nil {
                break
            }

            // errors of type FatalClientErr should forceably close the connection
            if _, ok := err.(*util.FatalClientErr); ok {
                break
            }
            continue
        }

        //Exec方法返回了响应数据,将响应发送到客户端
        if response != nil {
            _, err = util.SendResponse(client, response)
            //响应发送出错就退出
            if err != nil {
                break
            }
        }
    }

    //如果前面的for循环退出了,则表示程序要退出了,将注册信息都从RegistrationDB中删除
    log.Printf("CLIENT(%s): closing", client)
    if client.peerInfo != nil {
        registrations := p.context.nsqlookupd.DB.LookupRegistrations(client.peerInfo.id)
        for _, r := range registrations {
            if removed, _ := p.context.nsqlookupd.DB.RemoveProducer(r, client.peerInfo.id); removed {
                log.Printf("DB: client(%s) UNREGISTER category:%s key:%s subkey:%s",
                    client, r.Category, r.Key, r.SubKey)
            }
        }
    }
    return err
}

//请求分发,根据每行数据的第一个参数,调用不同的方法
func (p *LookupProtocolV1) Exec(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
    switch params[0] {
    case "PING":
        return p.PING(client, params)
    case "IDENTIFY":
        return p.IDENTIFY(client, reader, params[1:])
    case "REGISTER":
        return p.REGISTER(client, reader, params[1:])
    case "UNREGISTER":
        return p.UNREGISTER(client, reader, params[1:])
    }

    //数据不合法,提示出错。
    return nil, util.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid command %s", params[0]))
}

func getTopicChan(command string, params []string) (string, string, error) {
    if len(params) == 0 {
        return "", "", util.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("%s insufficient number of params", command))
    }

    topicName := params[0]
    var channelName string
    if len(params) >= 2 {
        channelName = params[1]
    }

    if !nsq.IsValidTopicName(topicName) {
        return "", "", util.NewFatalClientErr(nil, "E_BAD_TOPIC", fmt.Sprintf("%s topic name '%s' is not valid", command, topicName))
    }

    if channelName != "" && !nsq.IsValidChannelName(channelName) {
        return "", "", util.NewFatalClientErr(nil, "E_BAD_CHANNEL", fmt.Sprintf("%s channel name '%s' is not valid", command, channelName))
    }

    return topicName, channelName, nil
}

func (p *LookupProtocolV1) REGISTER(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
    if client.peerInfo == nil {
        return nil, util.NewFatalClientErr(nil, "E_INVALID", "client must IDENTIFY")
    }

    //调用本文件里的getTopicChan方法,从参数params中取的topic和channel
    topic, channel, err := getTopicChan("REGISTER", params)
    if err != nil {
        return nil, err
    }

    if channel != "" {
        //定义Registration类型的变量,category为channel,Key为topic,SubKey为channel
        key := Registration{"channel", topic, channel}
        //将client做为一个producer保存在RegistrationDB中
        if p.context.nsqlookupd.DB.AddProducer(key, &Producer{peerInfo: client.peerInfo}) {
            log.Printf("DB: client(%s) REGISTER category:%s key:%s subkey:%s",
                client, "channel", topic, channel)
        }
    }
    //定义Registration类型的变量,category为topic,Key为topic,SubKey为空
    key := Registration{"topic", topic, ""}
    //使用另一个key又保存了一次,具体这么做的原因还不是很明确,待确定。
    if p.context.nsqlookupd.DB.AddProducer(key, &Producer{peerInfo: client.peerInfo}) {
        log.Printf("DB: client(%s) REGISTER category:%s key:%s subkey:%s",
            client, "topic", topic, "")
    }

    return []byte("OK"), nil
}

//反注册,做了和注册相反的事情
func (p *LookupProtocolV1) UNREGISTER(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
    if client.peerInfo == nil {
        return nil, util.NewFatalClientErr(nil, "E_INVALID", "client must IDENTIFY")
    }

    topic, channel, err := getTopicChan("UNREGISTER", params)
    if err != nil {
        return nil, err
    }

    //params参数中有指定channel
    if channel != "" {
        key := Registration{"channel", topic, channel}
        removed, left := p.context.nsqlookupd.DB.RemoveProducer(key, client.peerInfo.id)
        if removed {
            log.Printf("DB: client(%s) UNREGISTER category:%s key:%s subkey:%s",
                client, "channel", topic, channel)
        }
        // for ephemeral channels, remove the channel as well if it has no producers
        //把没有producers并标注为ephemeral(中文意思为短暂的)的channels也删除了,此句话翻译了作者的注释
        //但是看起来有些不太懂,主要原因是目前对channel topic的概念还不清楚,这个也需待后续明了。
        //left=0表示这个Registration下面所有的Producer都被删完了
        if left == 0 && strings.HasSuffix(channel, "#ephemeral") {
            //将Registration也删除掉了
            p.context.nsqlookupd.DB.RemoveRegistration(key)
        }
    } else {
        // no channel was specified so this is a topic unregistration
        // remove all of the channel registrations...
        // normally this shouldn't happen which is why we print a warning message
        // if anything is actually removed
        //没有指定channel,所以是topic的反注册
        //删除掉所有channel的注册
        //一般来说,这不应该发生,如果确实有东西被删掉了,是不正常的,所以在下面的LOG里打印了一个warning
        registrations := p.context.nsqlookupd.DB.FindRegistrations("channel", topic, "*")
        for _, r := range registrations {
            if removed, _ := p.context.nsqlookupd.DB.RemoveProducer(r, client.peerInfo.id); removed {
                log.Printf("WARNING: client(%s) unexpected UNREGISTER category:%s key:%s subkey:%s",
                    client, "channel", topic, r.SubKey)
            }
        }

        key := Registration{"topic", topic, ""}
        if removed, _ := p.context.nsqlookupd.DB.RemoveProducer(key, client.peerInfo.id); removed {
            log.Printf("DB: client(%s) UNREGISTER category:%s key:%s subkey:%s",
                client, "topic", topic, "")
        }
    }

    return []byte("OK"), nil
}

/**
*Client与nsqdlookupd连接后,在进行PING REGISTER UNREGISTER操作之前,必须先IDENTIFY,通过IDENTIFY来初始化peerInfo。
 */
func (p *LookupProtocolV1) IDENTIFY(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
    var err error

    //不能重复初始化peerInfo,已经初始化时,返回错误。
    if client.peerInfo != nil {
        return nil, util.NewFatalClientErr(err, "E_INVALID", "cannot IDENTIFY again")
    }

    //读取数据的长度到bodyLen变量中,用于判断数据包结尾
    var bodyLen int32
    err = binary.Read(reader, binary.BigEndian, &bodyLen)
    if err != nil {
        return nil, util.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to read body size")
    }

    //取bodyLen长度的数据。
    body := make([]byte, bodyLen)
    _, err = io.ReadFull(reader, body)
    if err != nil {
        return nil, util.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to read body")
    }

    // body is a json structure with producer information
    //body是一个json结构的数据
    //PeerInfo类型在nsqlookupd\registration_db.go文件中定义
    //PeerInfo类型在Producer类型和ClientV1类型中都有使用
    //id作为PeerInfo的唯一性标识,将在后续经常使用
    peerInfo := PeerInfo{id: client.RemoteAddr().String()}
    err = json.Unmarshal(body, &peerInfo)
    if err != nil {
        return nil, util.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to decode JSON body")
    }

    peerInfo.RemoteAddress = client.RemoteAddr().String()

    // require all fields
    //校验JSON传来的数据是否完整
    if peerInfo.BroadcastAddress == "" || peerInfo.TcpPort == 0 || peerInfo.HttpPort == 0 || peerInfo.Version == "" {
        return nil, util.NewFatalClientErr(nil, "E_BAD_BODY", "IDENTIFY missing fields")
    }

    //修改peerInfo的lastUpdate值为当前时间
    peerInfo.lastUpdate = time.Now()

    log.Printf("CLIENT(%s): IDENTIFY Address:%s TCP:%d HTTP:%d Version:%s",
        client, peerInfo.BroadcastAddress, peerInfo.TcpPort, peerInfo.HttpPort, peerInfo.Version)

    //把当前client加入到RegistrationDB的记录里。Registration的category是"client",Key和SubKey为空
    client.peerInfo = &peerInfo
    if p.context.nsqlookupd.DB.AddProducer(Registration{"client", "", ""}, &Producer{peerInfo: client.peerInfo}) {
        log.Printf("DB: client(%s) REGISTER category:%s key:%s subkey:%s", client, "client", "", "")
    }

    // build a response
    //构建一个响应给client
    data := make(map[string]interface{})
    //返回nsqlookupd监听的TCP端口
    data["tcp_port"] = p.context.nsqlookupd.tcpAddr.Port
    //返回nsqlookupd监听的HTTP端口
    data["http_port"] = p.context.nsqlookupd.httpAddr.Port
    data["version"] = util.BINARY_VERSION
    hostname, err := os.Hostname()
    if err != nil {
        log.Fatalf("ERROR: unable to get hostname %s", err.Error())
    }
    data["broadcast_address"] = p.context.nsqlookupd.options.BroadcastAddress
    data["hostname"] = hostname

    //转化为一个JSON字符串
    response, err := json.Marshal(data)
    if err != nil {
        log.Printf("ERROR: marshaling %v", data)
        return []byte("OK"), nil
    }
    return response, nil
}

func (p *LookupProtocolV1) PING(client *ClientV1, params []string) ([]byte, error) {
    if client.peerInfo != nil {
        // we could get a PING before other commands on the same client connection
        now := time.Now()
        log.Printf("CLIENT(%s): pinged (last ping %s)", client.peerInfo.id, now.Sub(client.peerInfo.lastUpdate))
        //修改client.peerInfo的lastUpdate值为当前时间
        client.peerInfo.lastUpdate = now
    }
    return []byte("OK"), nil
}

整体来看,代码的结构还是比较清晰的,不过在REGISTER和UNREGISTER方法里,关于channel、topic的概念、关系还不是很了解, 所以理解起来会比较模糊,我们先放一放,继续往下看,等我们读的代码越来越多的时候,就会明白这里的逻辑了。
本篇就到这里了。

go语言nsq源码解读七 lookup_protocol_v1.go的更多相关文章

  1. go语言nsq源码解读八 http.go、http_server.go

    这篇讲另两个文件http.go.http_server.go,这两个文件和第六讲go语言nsq源码解读六 tcp.go.tcp_server.go里的两个文件是相对应的.那两个文件用于处理tcp请求, ...

  2. (转)go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin

    转自:http://www.baiyuxiong.com/?p=886 ---------------------------------------------------------------- ...

  3. go语言 nsq源码解读三 nsqlookupd源码nsqlookupd.go

    从本节开始,将逐步阅读nsq各模块的代码. 读一份代码,我的思路一般是: 1.了解用法,知道了怎么使用,对理解代码有宏观上有很大帮助. 2.了解各大模块的功能特点,同时再想想,如果让自己来实现这些模块 ...

  4. go语言nsq源码解读一-基本介绍

    简单介绍一下nsq. 参考 http://feilong.me/2013/05/nsq-realtime-message-processing-system 的介绍:NSQ是由知名短链接服务商bitl ...

  5. go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin

    nsqlookupd: 官方文档解释见:http://bitly.github.io/nsq/components/nsqlookupd.html 用官方话来讲是:nsqlookupd管理拓扑信息,客 ...

  6. go语言nsq源码解读九 tcp和http中channel、topic的增删

    通过前面多篇文章,nsqlookupd基本已经解读完毕了,不过在关于channel和topic的增删上还比较模糊,所以本篇将站在宏观的角度来总结一下,tcp.go和http.go两个文件中关于chan ...

  7. go语言nsq源码解读六 tcp.go、tcp_server.go

    本篇讲nsqlookupd中tcp.go.tcp_server.go tcp_server.go位于util目录下. 12345678910111213141516171819202122232425 ...

  8. go语言 nsq源码解读四 nsqlookupd源码options.go、context.go和wait_group_wrapper.go

    本节会解读nsqlookupd.go文件中涉及到的其中三个文件:options.go.context.go和wait_group_wrapper.go. options.go 123456789101 ...

  9. go语言nsq源码解读五 nsqlookupd源码registration_db.go

    本篇将讲解registration_db.go文件. 1234567891011121314151617181920212223242526272829303132333435363738394041 ...

随机推荐

  1. oracle 修改 字段名称

    暂时应该没有对应的方法,所以我用自己想好的方法去修改 /*修改原字段名name为name_tmp,是将想改名称的字段改为没用/临时的字段*/ Alter  table 表名 rename column ...

  2. 使用JConsole以及VisualVM进行jvm程序的监控,排错,调优

    这里只是做一个备份,便于以后继续. 添加两个感觉好的链接吧: http://www.linuxidc.com/Linux/2015-02/113420.htm http://blog.csdn.net ...

  3. 全局程序集缓存GAC

    GAC中的所有的Assembly都会存放在系统目录"%winroot%\assembly下面.放在系统目录下的好处之一是可以让系统管理员通过用户权限来控制Assembly的访问. 目录:C: ...

  4. Day4_名称空间与作用域

    函数嵌套: 函数的嵌套调用:在调用一个函数的过程中,又调用了了另外一个函数 比如说比较多个值的大小,可以利用这种方法: def max2(x,y): if x > y: return x els ...

  5. Hession集成Spring + maven依赖通讯comm项目 + 解决@ResponseBody中文乱码

    hessian结合spring的demo         hessian的maven依赖: <!-- hessian --> <dependency>         < ...

  6. Leetcode_删除排序数组中的重复项

    Leetcode  删除排序数组中的重复项 题目: 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度. 不要使用 额外的数组空间,你必须在原地修改输入数 ...

  7. javascript中字符串和字符串变量的问题

    var s = new String("hello"); s.indexOf(1) = 'p'; //错误,indexof()是函数 s[1]='p' //错误,在c和c++可以改 ...

  8. meta的用法

    META标签,是HTML语言head区的一个辅助性标签.在几乎所有的page里,我们都可以看 到类似下面这段html代码: -------------------------------------- ...

  9. 洛谷 P2587 解题报告

    P2587 [ZJOI2008]泡泡堂 题目描述 第XXXX届NOI期间,为了加强各省选手之间的交流,组委会决定组织一场省际电子竞技大赛,每一个省的代表队由n名选手组成,比赛的项目是老少咸宜的网络游戏 ...

  10. arcEngine开发之根据点坐标创建Shp图层

    思路 根据点坐标创建Shapefile文件大致思路是这样的: (1)创建表的工作空间,通过 IField.IFieldsEdit.IField 等接口创建属性字段,添加到要素集中. (2)根据获取点的 ...