package nsqd

import (
    "encoding/binary"
    "fmt"
    "io"
    "net"
    "time"

    "github.com/nsqio/go-nsq"
)

// lookupPeer is a low-level type for connecting/reading/writing to nsqlookupd
//
// A lookupPeer instance is designed to connect lazily to nsqlookupd and reconnect
// gracefully (i.e. it is all handled by the library).  Clients can simply use the
// Command interface to perform a round-trip.
type lookupPeer struct {
    l               Logger
    addr            string
    conn            net.Conn
    state           int32
    connectCallback func(*lookupPeer)
    maxBodySize     int64
    Info            peerInfo
}

// peerInfo contains metadata for a lookupPeer instance (and is JSON marshalable)
type peerInfo struct {
    TCPPort          int    `json:"tcp_port"`
    HTTPPort         int    `json:"http_port"`
    Version          string `json:"version"`
    BroadcastAddress string `json:"broadcast_address"`
}

// newLookupPeer creates a new lookupPeer instance connecting to the supplied address.
//
// The supplied connectCallback will be called *every* time the instance connects.
func newLookupPeer(addr string, maxBodySize int64, l Logger, connectCallback func(*lookupPeer)) *lookupPeer {
    return &lookupPeer{
        l:               l,
        addr:            addr,
        state:           stateDisconnected,
        maxBodySize:     maxBodySize,
        connectCallback: connectCallback,
    }
}

// Connect will Dial the specified address, with timeouts
func (lp *lookupPeer) Connect() error {
    lp.l.Output(2, fmt.Sprintf("LOOKUP connecting to %s", lp.addr))
    conn, err := net.DialTimeout("tcp", lp.addr, time.Second)
    if err != nil {
        return err
    }
    lp.conn = conn
    return nil
}

// String returns the specified address
func (lp *lookupPeer) String() string {
    return lp.addr
}

// Read implements the io.Reader interface, adding deadlines
func (lp *lookupPeer) Read(data []byte) (int, error) {
    lp.conn.SetReadDeadline(time.Now().Add(time.Second))
    return lp.conn.Read(data)
}

// Write implements the io.Writer interface, adding deadlines
func (lp *lookupPeer) Write(data []byte) (int, error) {
    lp.conn.SetWriteDeadline(time.Now().Add(time.Second))
    return lp.conn.Write(data)
}

// Close implements the io.Closer interface
func (lp *lookupPeer) Close() error {
    lp.state = stateDisconnected
    if lp.conn != nil {
        return lp.conn.Close()
    }
    return nil
}

// Command performs a round-trip for the specified Command.
//
// It will lazily connect to nsqlookupd and gracefully handle
// reconnecting in the event of a failure.
//
// It returns the response from nsqlookupd as []byte
func (lp *lookupPeer) Command(cmd *nsq.Command) ([]byte, error) {
    initialState := lp.state
    if lp.state != stateConnected {
        err := lp.Connect()
        if err != nil {
            return nil, err
        }
        lp.state = stateConnected
        lp.Write(nsq.MagicV1)
        if initialState == stateDisconnected {
            lp.connectCallback(lp)
        }
    }
    if cmd == nil {
        return nil, nil
    }
    _, err := cmd.WriteTo(lp)
    if err != nil {
        lp.Close()
        return nil, err
    }
    resp, err := readResponseBounded(lp, lp.maxBodySize)
    if err != nil {
        lp.Close()
        return nil, err
    }
    return resp, nil
}

func readResponseBounded(r io.Reader, limit int64) ([]byte, error) {
    var msgSize int32

    // message size
    err := binary.Read(r, binary.BigEndian, &msgSize)
    if err != nil {
        return nil, err
    }

    if int64(msgSize) > limit {
        return nil, fmt.Errorf("response body size (%d) is greater than limit (%d)",
            msgSize, limit)
    }

    // message binary data
    buf := make([]byte, msgSize)
    _, err = io.ReadFull(r, buf)
    if err != nil {
        return nil, err
    }

    return buf, nil
}

lookup_peer.go的更多相关文章

随机推荐

  1. javascript中的in运算符

    in运算符希望它的左操作数是一个字符串或可以转换为字符串,希望他的又操作数是一个对象:如果右侧对象拥有一个名为左操作数值的属性名,那么表达式返回true: var point = {x:1,y:1}; ...

  2. Spring security在MS-SQL下的初始化脚本

    -- create table users( -- username nvarchar(50) not null primary key, -- password nvarchar(50) not n ...

  3. Mac下面解决PYTHONPATH配置的方法

    问题起因:MacPort安装的Python包在/opt目录里面,和系统安装的python包不在一起,由于Mac下面编译安装无止境的找不到问题,虽然MacPort解决了这个问题,但是它安装的东西,得自己 ...

  4. php实现点击文字提交表单并传递数据至下一个页面

    <?php $id="4";//等会要把这个数据传到第二个页面 ?> <?php echo "<li>"; echo " ...

  5. RDC去省赛玩前の日常训练 Chapter 1

    4/3 技能点 A. 生成树的计数 论文:周冬<生成树的计数及其应用>(看不懂 pending) 一个栗子:Codeforces 719D 两个做法 Matrix-Tree + 高斯消元, ...

  6. DDGScreenShot--iOS 图片处理--多图片拼接 (swift)

    写在前面 最近总结了关于图片处理相关的内容,之前在二三四五工作的时候,也做过关于这方面的分享,图片的处理内容很多,会分很多模块来讲解. 今天简单讲多图片的拼接. 上代码 func composeIma ...

  7. ScalaPB(2): 在scala中用gRPC实现微服务

    gRPC是google开源提供的一个RPC软件框架,它的特点是极大简化了传统RPC的开发流程和代码量,使用户可以免除许多陷阱并聚焦于实际应用逻辑中.作为一种google的最新RPC解决方案,gRPC具 ...

  8. 基于Python的数据分析:数据库索引效率探究

    索引在数据库中是一个很特殊的存在,它的目的就是为了提高数据查询得效率.同样,它也有弊端,更新一个带索引的表的时间比更新一个没有带索引的时间更长.有得有失.我希望做一些研究测试,搞清楚索引对于我们使用数 ...

  9. Java注解处理器--编译时处理的注解

    1. 一些基本概念 在开始之前,我们需要声明一件重要的事情是:我们不是在讨论在运行时通过反射机制运行处理的注解,而是在讨论在编译时处理的注解.注解处理器是 javac 自带的一个工具,用来在编译时期扫 ...

  10. win10装ubuntu双系统

    由于在win下进行web开发出现各种问题相当头疼. 所以今天折腾了一天想装个ubuntu,查看了网上好多教程,不得不说,网上的人很多都是不负责任的,教程都是过时根本就不负责任,关键的地方一笔带过,简单 ...