lookup_protocol_v1.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package nsqlookupd
  2. import (
  3. "bufio"
  4. "encoding/binary"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "log"
  9. "net"
  10. "os"
  11. "strings"
  12. "sync/atomic"
  13. "time"
  14. "github.com/nsqio/nsq/internal/protocol"
  15. "github.com/nsqio/nsq/internal/version"
  16. )
  17. type LookupProtocolV1 struct {
  18. nsqlookupd *NSQLookupd
  19. }
  20. func (p *LookupProtocolV1) NewClient(conn net.Conn) protocol.Client {
  21. return NewClientV1(conn)
  22. }
  23. func (p *LookupProtocolV1) IOLoop(c protocol.Client) error {
  24. var err error
  25. var line string
  26. client := c.(*ClientV1)
  27. reader := bufio.NewReader(client)
  28. for {
  29. line, err = reader.ReadString('\n')
  30. if err != nil {
  31. break
  32. }
  33. line = strings.TrimSpace(line)
  34. params := strings.Split(line, " ")
  35. var response []byte
  36. response, err = p.Exec(client, reader, params)
  37. if err != nil {
  38. ctx := ""
  39. if parentErr := err.(protocol.ChildErr).Parent(); parentErr != nil {
  40. ctx = " - " + parentErr.Error()
  41. }
  42. p.nsqlookupd.logf(LOG_ERROR, "[%s] - %s%s", client, err, ctx)
  43. _, sendErr := protocol.SendResponse(client, []byte(err.Error()))
  44. if sendErr != nil {
  45. p.nsqlookupd.logf(LOG_ERROR, "[%s] - %s%s", client, sendErr, ctx)
  46. break
  47. }
  48. // errors of type FatalClientErr should forceably close the connection
  49. if _, ok := err.(*protocol.FatalClientErr); ok {
  50. break
  51. }
  52. continue
  53. }
  54. if response != nil {
  55. _, err = protocol.SendResponse(client, response)
  56. if err != nil {
  57. break
  58. }
  59. }
  60. }
  61. p.nsqlookupd.logf(LOG_INFO, "PROTOCOL(V1): [%s] exiting ioloop", client)
  62. if client.peerInfo != nil {
  63. registrations := p.nsqlookupd.DB.LookupRegistrations(client.peerInfo.id)
  64. for _, r := range registrations {
  65. if removed, _ := p.nsqlookupd.DB.RemoveProducer(r, client.peerInfo.id); removed {
  66. p.nsqlookupd.logf(LOG_INFO, "DB: client(%s) UNREGISTER category:%s key:%s subkey:%s",
  67. client, r.Category, r.Key, r.SubKey)
  68. }
  69. }
  70. }
  71. return err
  72. }
  73. func (p *LookupProtocolV1) Exec(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
  74. switch params[0] {
  75. case "PING":
  76. return p.PING(client, params)
  77. case "IDENTIFY":
  78. return p.IDENTIFY(client, reader, params[1:])
  79. case "REGISTER":
  80. return p.REGISTER(client, reader, params[1:])
  81. case "UNREGISTER":
  82. return p.UNREGISTER(client, reader, params[1:])
  83. }
  84. return nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid command %s", params[0]))
  85. }
  86. func getTopicChan(command string, params []string) (string, string, error) {
  87. if len(params) == 0 {
  88. return "", "", protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("%s insufficient number of params", command))
  89. }
  90. topicName := params[0]
  91. var channelName string
  92. if len(params) >= 2 {
  93. channelName = params[1]
  94. }
  95. if !protocol.IsValidTopicName(topicName) {
  96. return "", "", protocol.NewFatalClientErr(nil, "E_BAD_TOPIC", fmt.Sprintf("%s topic name '%s' is not valid", command, topicName))
  97. }
  98. if channelName != "" && !protocol.IsValidChannelName(channelName) {
  99. return "", "", protocol.NewFatalClientErr(nil, "E_BAD_CHANNEL", fmt.Sprintf("%s channel name '%s' is not valid", command, channelName))
  100. }
  101. return topicName, channelName, nil
  102. }
  103. func (p *LookupProtocolV1) REGISTER(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
  104. if client.peerInfo == nil {
  105. return nil, protocol.NewFatalClientErr(nil, "E_INVALID", "client must IDENTIFY")
  106. }
  107. topic, channel, err := getTopicChan("REGISTER", params)
  108. if err != nil {
  109. return nil, err
  110. }
  111. if channel != "" {
  112. key := Registration{"channel", topic, channel}
  113. if p.nsqlookupd.DB.AddProducer(key, &Producer{peerInfo: client.peerInfo}) {
  114. p.nsqlookupd.logf(LOG_INFO, "DB: client(%s) REGISTER category:%s key:%s subkey:%s",
  115. client, "channel", topic, channel)
  116. }
  117. }
  118. key := Registration{"topic", topic, ""}
  119. if p.nsqlookupd.DB.AddProducer(key, &Producer{peerInfo: client.peerInfo}) {
  120. p.nsqlookupd.logf(LOG_INFO, "DB: client(%s) REGISTER category:%s key:%s subkey:%s",
  121. client, "topic", topic, "")
  122. }
  123. return []byte("OK"), nil
  124. }
  125. func (p *LookupProtocolV1) UNREGISTER(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
  126. if client.peerInfo == nil {
  127. return nil, protocol.NewFatalClientErr(nil, "E_INVALID", "client must IDENTIFY")
  128. }
  129. topic, channel, err := getTopicChan("UNREGISTER", params)
  130. if err != nil {
  131. return nil, err
  132. }
  133. if channel != "" {
  134. key := Registration{"channel", topic, channel}
  135. removed, left := p.nsqlookupd.DB.RemoveProducer(key, client.peerInfo.id)
  136. if removed {
  137. p.nsqlookupd.logf(LOG_INFO, "DB: client(%s) UNREGISTER category:%s key:%s subkey:%s",
  138. client, "channel", topic, channel)
  139. }
  140. // for ephemeral channels, remove the channel as well if it has no producers
  141. if left == 0 && strings.HasSuffix(channel, "#ephemeral") {
  142. p.nsqlookupd.DB.RemoveRegistration(key)
  143. }
  144. } else {
  145. // no channel was specified so this is a topic unregistration
  146. // remove all of the channel registrations...
  147. // normally this shouldn't happen which is why we print a warning message
  148. // if anything is actually removed
  149. registrations := p.nsqlookupd.DB.FindRegistrations("channel", topic, "*")
  150. for _, r := range registrations {
  151. removed, _ := p.nsqlookupd.DB.RemoveProducer(r, client.peerInfo.id)
  152. if removed {
  153. p.nsqlookupd.logf(LOG_WARN, "client(%s) unexpected UNREGISTER category:%s key:%s subkey:%s",
  154. client, "channel", topic, r.SubKey)
  155. }
  156. }
  157. key := Registration{"topic", topic, ""}
  158. removed, left := p.nsqlookupd.DB.RemoveProducer(key, client.peerInfo.id)
  159. if removed {
  160. p.nsqlookupd.logf(LOG_INFO, "DB: client(%s) UNREGISTER category:%s key:%s subkey:%s",
  161. client, "topic", topic, "")
  162. }
  163. if left == 0 && strings.HasSuffix(topic, "#ephemeral") {
  164. p.nsqlookupd.DB.RemoveRegistration(key)
  165. }
  166. }
  167. return []byte("OK"), nil
  168. }
  169. func (p *LookupProtocolV1) IDENTIFY(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
  170. var err error
  171. if client.peerInfo != nil {
  172. return nil, protocol.NewFatalClientErr(err, "E_INVALID", "cannot IDENTIFY again")
  173. }
  174. var bodyLen int32
  175. err = binary.Read(reader, binary.BigEndian, &bodyLen)
  176. if err != nil {
  177. return nil, protocol.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to read body size")
  178. }
  179. body := make([]byte, bodyLen)
  180. _, err = io.ReadFull(reader, body)
  181. if err != nil {
  182. return nil, protocol.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to read body")
  183. }
  184. // body is a json structure with producer information
  185. peerInfo := PeerInfo{id: client.RemoteAddr().String()}
  186. err = json.Unmarshal(body, &peerInfo)
  187. if err != nil {
  188. return nil, protocol.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to decode JSON body")
  189. }
  190. peerInfo.RemoteAddress = client.RemoteAddr().String()
  191. // require all fields
  192. if peerInfo.BroadcastAddress == "" || peerInfo.TCPPort == 0 || peerInfo.HTTPPort == 0 || peerInfo.Version == "" {
  193. return nil, protocol.NewFatalClientErr(nil, "E_BAD_BODY", "IDENTIFY missing fields")
  194. }
  195. atomic.StoreInt64(&peerInfo.lastUpdate, time.Now().UnixNano())
  196. p.nsqlookupd.logf(LOG_INFO, "CLIENT(%s): IDENTIFY Address:%s TCP:%d HTTP:%d Version:%s",
  197. client, peerInfo.BroadcastAddress, peerInfo.TCPPort, peerInfo.HTTPPort, peerInfo.Version)
  198. client.peerInfo = &peerInfo
  199. if p.nsqlookupd.DB.AddProducer(Registration{"client", "", ""}, &Producer{peerInfo: client.peerInfo}) {
  200. p.nsqlookupd.logf(LOG_INFO, "DB: client(%s) REGISTER category:%s key:%s subkey:%s", client, "client", "", "")
  201. }
  202. // build a response
  203. data := make(map[string]interface{})
  204. data["tcp_port"] = p.nsqlookupd.RealTCPAddr().Port
  205. data["http_port"] = p.nsqlookupd.RealHTTPAddr().Port
  206. data["version"] = version.Binary
  207. hostname, err := os.Hostname()
  208. if err != nil {
  209. log.Fatalf("ERROR: unable to get hostname %s", err)
  210. }
  211. data["broadcast_address"] = p.nsqlookupd.opts.BroadcastAddress
  212. data["hostname"] = hostname
  213. response, err := json.Marshal(data)
  214. if err != nil {
  215. p.nsqlookupd.logf(LOG_ERROR, "marshaling %v", data)
  216. return []byte("OK"), nil
  217. }
  218. return response, nil
  219. }
  220. func (p *LookupProtocolV1) PING(client *ClientV1, params []string) ([]byte, error) {
  221. if client.peerInfo != nil {
  222. // we could get a PING before other commands on the same client connection
  223. cur := time.Unix(0, atomic.LoadInt64(&client.peerInfo.lastUpdate))
  224. now := time.Now()
  225. p.nsqlookupd.logf(LOG_INFO, "CLIENT(%s): pinged (last ping %s)", client.peerInfo.id,
  226. now.Sub(cur))
  227. atomic.StoreInt64(&client.peerInfo.lastUpdate, now.UnixNano())
  228. }
  229. return []byte("OK"), nil
  230. }