go语言nsq源码解读七 lookup_protocol_v1.go
本篇将解读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的更多相关文章
- go语言nsq源码解读八 http.go、http_server.go
这篇讲另两个文件http.go.http_server.go,这两个文件和第六讲go语言nsq源码解读六 tcp.go.tcp_server.go里的两个文件是相对应的.那两个文件用于处理tcp请求, ...
- (转)go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin
转自:http://www.baiyuxiong.com/?p=886 ---------------------------------------------------------------- ...
- go语言 nsq源码解读三 nsqlookupd源码nsqlookupd.go
从本节开始,将逐步阅读nsq各模块的代码. 读一份代码,我的思路一般是: 1.了解用法,知道了怎么使用,对理解代码有宏观上有很大帮助. 2.了解各大模块的功能特点,同时再想想,如果让自己来实现这些模块 ...
- go语言nsq源码解读一-基本介绍
简单介绍一下nsq. 参考 http://feilong.me/2013/05/nsq-realtime-message-processing-system 的介绍:NSQ是由知名短链接服务商bitl ...
- go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin
nsqlookupd: 官方文档解释见:http://bitly.github.io/nsq/components/nsqlookupd.html 用官方话来讲是:nsqlookupd管理拓扑信息,客 ...
- go语言nsq源码解读九 tcp和http中channel、topic的增删
通过前面多篇文章,nsqlookupd基本已经解读完毕了,不过在关于channel和topic的增删上还比较模糊,所以本篇将站在宏观的角度来总结一下,tcp.go和http.go两个文件中关于chan ...
- go语言nsq源码解读六 tcp.go、tcp_server.go
本篇讲nsqlookupd中tcp.go.tcp_server.go tcp_server.go位于util目录下. 12345678910111213141516171819202122232425 ...
- go语言 nsq源码解读四 nsqlookupd源码options.go、context.go和wait_group_wrapper.go
本节会解读nsqlookupd.go文件中涉及到的其中三个文件:options.go.context.go和wait_group_wrapper.go. options.go 123456789101 ...
- go语言nsq源码解读五 nsqlookupd源码registration_db.go
本篇将讲解registration_db.go文件. 1234567891011121314151617181920212223242526272829303132333435363738394041 ...
随机推荐
- css选择器语法速查
通用选择器 *{} 类似于通配符,匹配文档中所有元素类型: 类型选择器 h1,h2,p{} 匹配以逗号隔开元素列表中的所有元素 类选择器 .glass{} or p.glass{} id选择器 #id ...
- Java 必看的 Spring 知识汇总!有比这更全的算我输!
往 期 精 彩 推 荐 [1]Java Web技术经验总结 [2]15个顶级Java多线程面试题及答案,快来看看吧 [3]面试官最喜欢问的十道java面试题 [4]从零讲JAVA ,给你一条清晰 ...
- oracle 数据库 date + 1 转载
http://blog.csdn.net/yjp198713/article/details/18131871 oracle 求两个时间点直接的分钟.小时数 1.获得时间差毫秒数: select ce ...
- NIO 多线程
本文可看成是对Doug Lea Scalable IO in Java一文的翻译. 当前分布式计算 Web Services盛行天下,这些网络服务的底层都离不开对socket的操作.他们都有一个共同的 ...
- sqlServer遇到的问题
重置自增列:dbcc checkident(表名,reseed,数字(初始值))
- Ocelot中文文档-中间件注入和重写
警告!请谨慎使用. 如果您在中间件管道中看到任何异常或奇怪的行为,并且正在使用以下任何一种行为.删除它们,然后重试! 当在Startup.cs中配置Ocelot的时候,可以添加或覆盖中间件.如下所示: ...
- 如何确保API的安全性
目标: 定义API安全性要求 使用security scheme来应用资源和方法级策略 定义API的自定义security scheme 将OAuth2.0外部供应商策略应用到资源方法 为API定义一 ...
- KNN算法思想与实现
第二章 k近邻 2.1 算法描述 (1)采用测量不同特征值之间的距离进行分类 优点:对异常点不敏感,精度高,无数据输入设定 缺点:空间,计算复杂度高 适合数据:标称与数值 (2)算法的工作原理: 基于 ...
- Linux(二十二)Ubuntu安装和配置
Ubuntu的介绍 Ubuntu是一个以桌面应用为主的开源GNU/Linux操作系统,Ubuntu是基于GNU/Linux,支持x86.amd64(即x64)和ppc架构,由全球化的专业开发团队(Ca ...
- robot framework之弹出窗口的处理关键字实战
1.1 弹出窗口的处理关键字 5.8.1 Alert Should Be Present关键字 按F5 查看Alert Should Be Present关键字的说明,如下图