zhangmeng
2019-05-17 9893edc6dda92601c81b249967384f6626abc272
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
315
316
317
package deliver
 
import (
    "fmt"
    "os"
    "strings"
    "time"
 
    "nanomsg.org/go-mangos"
    "nanomsg.org/go-mangos/protocol/bus"
    "nanomsg.org/go-mangos/protocol/pair"
    "nanomsg.org/go-mangos/protocol/pub"
    "nanomsg.org/go-mangos/protocol/pull"
    "nanomsg.org/go-mangos/protocol/push"
    "nanomsg.org/go-mangos/protocol/rep"
    "nanomsg.org/go-mangos/protocol/req"
    "nanomsg.org/go-mangos/protocol/respondent"
    "nanomsg.org/go-mangos/protocol/sub"
    "nanomsg.org/go-mangos/protocol/surveyor"
    "nanomsg.org/go-mangos/transport/all"
)
 
// type deliver
type td int
 
const (
    producer = td(iota)
    consumer
    star //mangos bus protocol
)
 
// NNG mangos wrap
type NNG struct {
    sock   mangos.Socket
    server bool
    mode   Mode
    url    string
 
    arguments []interface{}
}
 
// Send impl interface Diliver
func (n *NNG) Send(data []byte) error {
    var err error
    if n.sock == nil {
        n.sock, err = n.makeNNG(producer)
        if err != nil {
            fmt.Println("create nng producer error")
            return err
        }
    }
 
    if surveyorTime > 0 {
        time.Sleep(time.Duration(surveyorTime*2) * time.Second)
    }
 
    msg := mangos.NewMessage(len(data))
    msg.Body = data
    return n.sock.SendMsg(msg)
 
}
 
// Recv impl interface Diliver
func (n *NNG) Recv() ([]byte, error) {
    var err error
 
    if n.sock == nil {
        n.sock, err = n.makeNNG(consumer)
        if err != nil {
            fmt.Println("create nng consumer error")
            return nil, err
        }
    }
 
    var msg *mangos.Message
    if msg, err = n.sock.RecvMsg(); err != nil {
        return nil, err
    }
    return msg.Body, nil
 
}
 
// Close impl interface Deliver
func (n *NNG) Close() {
    if n.sock != nil {
        n.sock.Close()
        n.sock = nil
    }
}
 
func nngServer(m Mode, url string, args ...interface{}) *NNG {
 
    rmExistedIpcName(url)
 
    return &NNG{
        server:    true,
        mode:      m,
        url:       url,
        arguments: args,
    }
}
 
func nngClient(m Mode, url string, args ...interface{}) *NNG {
 
    return &NNG{
        server:    false,
        mode:      m,
        url:       url,
        arguments: args,
    }
 
}
 
func proto(typ td, m Mode) protocol {
    if typ == producer {
        return protoProducer(m)
    } else if typ == consumer {
        return protoConsumer(m)
    }
    return protoConsumer(m)
}
 
func (n *NNG) makeNNG(typ td) (mangos.Socket, error) {
 
    var sock mangos.Socket
    var err error
    if sock, err = newSocket(proto(typ, n.mode)); err != nil {
        return nil, err
    }
 
    if err = setSocketOptions(sock, n.arguments...); err != nil {
        sock.Close()
        sock = nil
    }
    if n.server {
        if err = sock.Listen(n.url); err != nil {
            sock.Close()
            sock = nil
        }
    } else {
        if err = sock.Dial(n.url); err != nil {
            sock.Close()
            sock = nil
        }
    }
    return sock, err
}
 
// maxRecvSize max recv size
var (
    maxRecvSize  = 33 * 1024 * 1024
    surveyorTime = -1
)
 
func defualtSocketOptions() map[string]interface{} {
 
    options := make(map[string]interface{})
 
    options[mangos.OptionMaxRecvSize] = maxRecvSize
    options[mangos.OptionWriteQLen] = 0
    options[mangos.OptionReadQLen] = 0
    // options[mangos.OptionRecvDeadline] = time.Second
    // options[mangos.OptionSendDeadline] = time.Second
    options[mangos.OptionRaw] = true
 
    return options
}
 
func setSocketOptions(sock mangos.Socket, args ...interface{}) error {
 
    options := defualtSocketOptions()
 
    switch sock.GetProtocol().Number() {
    case mangos.ProtoSub:
        topic := ""
        for _, arg := range args {
            switch arg.(type) {
            case string:
                topic = arg.(string)
            default:
            }
        }
        options[mangos.OptionSubscribe] = []byte(topic)
    case mangos.ProtoSurveyor:
        for _, arg := range args {
            switch arg.(type) {
            case int:
                if arg.(int) < 2 {
                    surveyorTime = 1
                } else {
                    surveyorTime = arg.(int) / 2
                }
            default:
            }
        }
        options[mangos.OptionSurveyTime] = time.Duration(surveyorTime) * time.Second
 
    default:
    }
 
    for k, v := range options {
        if err := sock.SetOption(k, v); err != nil {
            return err
        }
    }
    return nil
}
 
func rmExistedIpcName(url string) {
    s := strings.Split(url, "://")
 
    if s[0] == "ipc" {
        if _, err := os.Stat(s[1]); err == nil {
            os.Remove(s[1])
        }
    }
}
 
// newSocket allocates a new Socket.  The Socket is the handle used to
// access the underlying library.
func newSocket(p protocol) (mangos.Socket, error) {
 
    var s mangos.Socket
    var err error
 
    switch p {
    case PUB:
        s, err = pub.NewSocket()
    case SUB:
        s, err = sub.NewSocket()
    case PUSH:
        s, err = push.NewSocket()
    case PULL:
        s, err = pull.NewSocket()
    case REQ:
        s, err = req.NewSocket()
    case REP:
        s, err = rep.NewSocket()
    case SURVEYOR:
        s, err = surveyor.NewSocket()
    case RESPONDENT:
        s, err = respondent.NewSocket()
    case PAIR:
        s, err = pair.NewSocket()
    case BUS:
        s, err = bus.NewSocket()
    default:
        err = mangos.ErrBadProto
    }
 
    if err != nil {
        return nil, err
    }
 
    all.AddTransports(s)
 
    return s, nil
}
 
func die(format string, v ...interface{}) {
    fmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...))
    os.Exit(1)
}
 
// Protocol is the numeric abstraction to the various protocols or patterns
// that Mangos supports.
type protocol int
 
// Constants for protocols.
const (
    PUSH       = protocol(mangos.ProtoPush)
    PULL       = protocol(mangos.ProtoPull)
    PUB        = protocol(mangos.ProtoPub)
    SUB        = protocol(mangos.ProtoSub)
    REQ        = protocol(mangos.ProtoReq)
    REP        = protocol(mangos.ProtoRep)
    SURVEYOR   = protocol(mangos.ProtoSurveyor)
    RESPONDENT = protocol(mangos.ProtoRespondent)
    BUS        = protocol(mangos.ProtoBus)
    PAIR       = protocol(mangos.ProtoPair)
)
 
func protoProducer(m Mode) protocol {
    switch m {
    case PushPull:
        return PUSH
    case PubSub:
        return PUB
    case ReqRep:
        return REP
    case SurvResp:
        return SURVEYOR
    case Bus:
        return BUS
    case Pair:
        return PAIR
    }
    return PUSH
}
 
func protoConsumer(m Mode) protocol {
    switch m {
    case PushPull:
        return PULL
    case PubSub:
        return SUB
    case ReqRep:
        return REQ
    case SurvResp:
        return RESPONDENT
    case Bus:
        return BUS
    case Pair:
        return PAIR
    }
    return PULL
}