package nsqlookupd

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

    "github.com/nsqio/nsq/internal/protocol"
    "github.com/nsqio/nsq/internal/version"
)

type LookupProtocolV1 struct {
    ctx *Context
}

func (p *LookupProtocolV1) IOLoop(conn net.Conn) error {
    var err error
    var line string

    client := NewClientV1(conn)
    reader := bufio.NewReader(client)
    for {
        line, err = reader.ReadString('\n')
        if err != nil {
            break
        }

        line = strings.TrimSpace(line)
        params := strings.Split(line, " ")

        var response []byte
        response, err = p.Exec(client, reader, params)
        if err != nil {
            ctx := ""
            if parentErr := err.(protocol.ChildErr).Parent(); parentErr != nil {
                ctx = " - " + parentErr.Error()
            }
            p.ctx.nsqlookupd.logf("ERROR: [%s] - %s%s", client, err, ctx)

            _, sendErr := protocol.SendResponse(client, []byte(err.Error()))
            if sendErr != nil {
                p.ctx.nsqlookupd.logf("ERROR: [%s] - %s%s", client, sendErr, ctx)
                break
            }

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

        if response != nil {
            _, err = protocol.SendResponse(client, response)
            if err != nil {
                break
            }
        }
    }

    conn.Close()
    p.ctx.nsqlookupd.logf("CLIENT(%s): closing", client)
    if client.peerInfo != nil {
        registrations := p.ctx.nsqlookupd.DB.LookupRegistrations(client.peerInfo.id)
        for _, r := range registrations {
            if removed, _ := p.ctx.nsqlookupd.DB.RemoveProducer(r, client.peerInfo.id); removed {
                p.ctx.nsqlookupd.logf("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, protocol.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 "", "", protocol.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 !protocol.IsValidTopicName(topicName) {
        return "", "", protocol.NewFatalClientErr(nil, "E_BAD_TOPIC", fmt.Sprintf("%s topic name '%s' is not valid", command, topicName))
    }

    if channelName != "" && !protocol.IsValidChannelName(channelName) {
        return "", "", protocol.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, protocol.NewFatalClientErr(nil, "E_INVALID", "client must IDENTIFY")
    }

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

    if channel != "" {
        key := Registration{"channel", topic, channel}
        if p.ctx.nsqlookupd.DB.AddProducer(key, &Producer{peerInfo: client.peerInfo}) {
            p.ctx.nsqlookupd.logf("DB: client(%s) REGISTER category:%s key:%s subkey:%s",
                client, "channel", topic, channel)
        }
    }
    key := Registration{"topic", topic, ""}
    if p.ctx.nsqlookupd.DB.AddProducer(key, &Producer{peerInfo: client.peerInfo}) {
        p.ctx.nsqlookupd.logf("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, protocol.NewFatalClientErr(nil, "E_INVALID", "client must IDENTIFY")
    }

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

    if channel != "" {
        key := Registration{"channel", topic, channel}
        removed, left := p.ctx.nsqlookupd.DB.RemoveProducer(key, client.peerInfo.id)
        if removed {
            p.ctx.nsqlookupd.logf("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
        if left == 0 && strings.HasSuffix(channel, "#ephemeral") {
            p.ctx.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
        registrations := p.ctx.nsqlookupd.DB.FindRegistrations("channel", topic, "*")
        for _, r := range registrations {
            if removed, _ := p.ctx.nsqlookupd.DB.RemoveProducer(r, client.peerInfo.id); removed {
                p.ctx.nsqlookupd.logf("WARNING: client(%s) unexpected UNREGISTER category:%s key:%s subkey:%s",
                    client, "channel", topic, r.SubKey)
            }
        }

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

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

func (p *LookupProtocolV1) IDENTIFY(client *ClientV1, reader *bufio.Reader, params []string) ([]byte, error) {
    var err error

    if client.peerInfo != nil {
        return nil, protocol.NewFatalClientErr(err, "E_INVALID", "cannot IDENTIFY again")
    }

    var bodyLen int32
    err = binary.Read(reader, binary.BigEndian, &bodyLen)
    if err != nil {
        return nil, protocol.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to read body size")
    }

    body := make([]byte, bodyLen)
    _, err = io.ReadFull(reader, body)
    if err != nil {
        return nil, protocol.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to read body")
    }

    // body is a json structure with producer information
    peerInfo := PeerInfo{id: client.RemoteAddr().String()}
    err = json.Unmarshal(body, &peerInfo)
    if err != nil {
        return nil, protocol.NewFatalClientErr(err, "E_BAD_BODY", "IDENTIFY failed to decode JSON body")
    }

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

    // require all fields
    if peerInfo.BroadcastAddress == "" || peerInfo.TCPPort == 0 || peerInfo.HTTPPort == 0 || peerInfo.Version == "" {
        return nil, protocol.NewFatalClientErr(nil, "E_BAD_BODY", "IDENTIFY missing fields")
    }

    atomic.StoreInt64(&peerInfo.lastUpdate, time.Now().UnixNano())

    p.ctx.nsqlookupd.logf("CLIENT(%s): IDENTIFY Address:%s TCP:%d HTTP:%d Version:%s",
        client, peerInfo.BroadcastAddress, peerInfo.TCPPort, peerInfo.HTTPPort, peerInfo.Version)

    client.peerInfo = &peerInfo
    if p.ctx.nsqlookupd.DB.AddProducer(Registration{"client", "", ""}, &Producer{peerInfo: client.peerInfo}) {
        p.ctx.nsqlookupd.logf("DB: client(%s) REGISTER category:%s key:%s subkey:%s", client, "client", "", "")
    }

    // build a response
    data := make(map[string]interface{})
    data["tcp_port"] = p.ctx.nsqlookupd.RealTCPAddr().Port
    data["http_port"] = p.ctx.nsqlookupd.RealHTTPAddr().Port
    data["version"] = version.Binary
    hostname, err := os.Hostname()
    if err != nil {
        log.Fatalf("ERROR: unable to get hostname %s", err)
    }
    data["broadcast_address"] = p.ctx.nsqlookupd.opts.BroadcastAddress
    data["hostname"] = hostname

    response, err := json.Marshal(data)
    if err != nil {
        p.ctx.nsqlookupd.logf("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
        cur := time.Unix(0, atomic.LoadInt64(&client.peerInfo.lastUpdate))
        now := time.Now()
        p.ctx.nsqlookupd.logf("CLIENT(%s): pinged (last ping %s)", client.peerInfo.id,
            now.Sub(cur))
        atomic.StoreInt64(&client.peerInfo.lastUpdate, now.UnixNano())
    }
    return []byte("OK"), nil
}

nsqlookup_protocol_v1.go的更多相关文章

随机推荐

  1. rails将类常量重构到数据库对应的表中之三

    经过博文之一和之二的重构,貌似代码表现的还不错,正常运行和test都通过鸟,但是,感觉告诉我们还是有什么地方不对劲啊!究竟是哪里不对劲呢?我们再来好好看一下. 我们把数据库表中的支付方式集合直接放在实 ...

  2. asp.net core中写入自定义中间件

    首先要明确什么是中间件?微软官方解释:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?tabs=aspnet ...

  3. AngularJs 隔离作用域

    初学NG,有诸多的不解,今天看了一篇文章,原文地址:https://segmentfault.com/a/1190000002773689#articleHeader0 ,本文运行的代码也出处此. 里 ...

  4. 从JavaWeb危险字符过滤浅谈ESAPI使用

    事先声明:只是浅谈,我也之用了这个组件的一点点. 又到某重要XX时期(但愿此文给面临此需求的同仁有所帮助),某Web应用第一次面临安全加固要求,AppScan的安全测试报告还是很清爽的,内容全面,提示 ...

  5. win7 64位专业版下的x64编译问题

    在Django的开发过程中,碰到一个问题,就是所有本地库的位数必须是相同的,于是某些库需要重新编译一下,工作环境,不能用盗版程序,VC++ 2008\2010 Express版本身都不支持X64的编译 ...

  6. 食物链-HZUN寒假集训

    食物链 总时间限制: 1000ms 内存限制: 65536kB 描述 动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形.A吃B, B吃C,C吃A. 现有N个动物,以1-N编号.每个动 ...

  7. CentOs 6 或 7 yum安装JDK1.8 (内含报 PYCURL ERROR 6 - "Couldn't resolve host 'mirrors.163.com'"错误解决方案)并分析为什么不能yum安装

    查看JDK的安装路径 # java -version============================查看Linux系统版本信息# cat /etc/redhat-releaseCentOS r ...

  8. C++开发中BYTE类型数组转为对应的字符串

    下午密码键盘返回了一个校验码,是BYTE类型数组,给上层应用返回最好是字符串方式,怎样原样的将BYTE数组转为string串呢?不多说,开动脑筋上手干!!! BYTE格式的数组bt{08,D7,B4, ...

  9. Beta 冲刺day3

    1.昨天的困难,今天解决的进度,以及明天要做的事情 昨天的困难:昨天主要是对第三方与企业复杂的逻辑关系进行分析和优化,以及进行部分模块的功能测试和代码测试. 今天解决的进度:根据前天得到的需求问题进行 ...

  10. Android 开发知识体系

    知识体系 1.Unix/Linux平台技术:基本命令,Linux下的开发环境 2.企业级数据库技术:SQL语言.SQL语句调优.Oracle数据库技术 3.Java 语言核心技术:Java语言基础.J ...