liuxiaolong
2021-02-03 cb12947ffbd30cea09bbe253f0e28b0e2222f952
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
package bhomeclient
 
import (
    "basic.com/valib/bhomebus.git"
    "context"
    "encoding/json"
    "errors"
    "fmt"
    "os"
    "time"
)
 
type MicroNode struct {
    ctx         context.Context
    handle         *BHBus
    reg         *RegisterInfo
    procInfo     *ProcInfo
    handlers     map[string]MicroFunc
    serverId     string
    fnLog         func(...interface{})
 
    SubCh         chan *MsgInfo
}
 
func NewMicroNode(ctx context.Context,q chan os.Signal, serverId string, reg *RegisterInfo, fnLog func(v ...interface{})) (*MicroNode, error){
    conf := NewConfig(KEY_REGISTER,512,5,1000,1000,1000, fnLog)
    handle, err := Register(ctx, q, conf, reg)
    if err != nil {
        return nil, err
    }
    mn := &MicroNode {
        ctx: ctx,
        serverId: serverId,
        handle:   handle,
        reg:      reg,
        procInfo: &reg.Proc,
        fnLog:    fnLog,
        SubCh:    make(chan *MsgInfo, 512),
    }
 
    return mn, nil
}
 
func (ms *MicroNode) printLog(v ...interface{}) {
    if ms.fnLog != nil {
        ms.fnLog(v...)
    } else {
        fmt.Println(v...)
    }
}
 
func (ms *MicroNode) UpdateNodeTopics(ts []NodeInfo) {
    ms.handle.UpdateNodeTopics(ts)
}
 
func (ms *MicroNode) DeRegister() error {
    if ms.handle != nil {
        return ms.handle.DeRegister(ms.reg)
    }
    return errors.New("ms.handle is nil")
}
 
func (ms *MicroNode) startHeartbeat() {
    hbi := &HeartBeatInfo{
        HealthLevel: "health",
        Fps:         12,
        WarnInfo:    "warn",
        ErrorInfo:   "error",
        Proc:    *ms.procInfo,
    }
 
    t := time.NewTicker(1 * time.Second)
    defer t.Stop()
 
    for {
        select {
        case <-ms.ctx.Done():
            return
        case <-t.C:
            ms.handle.HeartBeat(hbi)
        }
    }
}
 
func (ms *MicroNode) StartClient() {
    go ms.startHeartbeat()
}
 
func (ms *MicroNode) StartServer(funcMap map[string]MicroFunc) {
    ms.handlers = funcMap
 
    go ms.startHeartbeat()
 
    for {
        select {
        case <- ms.ctx.Done():
            return
        default:
            msgS, msgR, keyR := ms.handle.GetMsg()
            if msgS != nil {
                //收到其它进程的发布消息
                ms.printLog("Recv Sub Message:", string(msgS.Body))
                ms.SubCh <- msgS
            }
            if msgR != nil {
                //收到其它进程的请求消息
                go ms.serve(msgR, keyR)
            }
 
            time.Sleep(50 * time.Millisecond)
        }
    }
}
 
func (ms *MicroNode) Request(serverId string, request Request, milliSecs int) (*Reply,error) {
    t := time.Now()
 
    ms.printLog("1:", time.Since(t))
    t = time.Now()
    rb, _ := json.Marshal(request)
    msgR := &MsgInfo {
        Topic: request.Path,
        Body: rb,
    }
    ms.printLog("2:", time.Since(t))
    return ms.handle.Request(serverId, msgR, milliSecs)
}
 
func (ms *MicroNode) RequestTopic(serverId string, request Request, milliSecs int) (*Reply,error) {
    rb, _ := json.Marshal(request)
    msgR := &MsgInfo{
        Topic: request.Path,
        Body: rb,
    }
 
    return ms.handle.Request(serverId, msgR, milliSecs)
}
 
func (ms *MicroNode) RequestOnly(rData []byte, nodes []bhomebus.NetNode) ([]byte, error) {
    return ms.handle.RequestOnly(rData, nodes)
}
 
//获取本机中某一个主题的 key  (结果只有一个元素)
func (ms *MicroNode) GetLocalNetNodeByTopic(topicName string) []bhomebus.NetNode {
    netNodes, err := ms.handle.GetNetNodeByTopic(ms.serverId, ms.procInfo, topicName)
    if err != nil {
        ms.printLog("topic:",topicName, " netNodes:", netNodes, "err:", err)
        return nil
    }
    return netNodes
}
 
//获取集群中所有节点某个主题的key信息,   (结果可能有多个)
func (ms *MicroNode) GetAllNetNodesByTopic(topicName string) []bhomebus.NetNode {
    netNodes, err := ms.handle.GetNetNodeByTopic("", ms.procInfo, topicName)
    if err != nil {
        return nil
    }
    return netNodes
}
 
func (ms *MicroNode) GetRegisteredClient() ([]RegisteredClient,error) {
    r := MsgInfo{
        SrcProc: *ms.procInfo,
        MsgType: MesgType_ReqRep,
        Topic: TOPIC_QUERYPROC,
    }
    cr, err := ms.handle.RequestCenter(&r)
    if err != nil {
        ms.printLog("requestCenter reply:", cr, "err:", err)
        return nil, err
    }
    if cr.Success {
        rd,err := json.Marshal(cr.Data)
        if err == nil {
            var list []RegisteredClient
            err = json.Unmarshal(rd, &list)
            if err == nil {
                return list, nil
            } else {
                ms.printLog("unmarshal to RegisteredClient list err:", err)
            }
        } else {
            return nil, fmt.Errorf("marshal reply.Data err:%s", err.Error())
        }
    } else {
        ms.printLog("request center failed,status:", cr.Success, "msg:", cr.Msg, " data:", cr.Data)
    }
    return nil, fmt.Errorf("GetRegisteredClient list failed")
}
 
func (ms *MicroNode) serve(msgR *MsgInfo, p int) {
    if ms.handlers == nil {
        return
    }
 
    var reqBody Request
    var ri *Reply
    err := json.Unmarshal(msgR.Body, &reqBody)
    if err != nil {
        ms.printLog("serve unmarshal msgR.Body err:", err)
        ri = &Reply {
            Msg: err.Error(),
        }
    } else {
        ms.printLog("srcProc:", msgR.SrcProc,"reqBody Path:", reqBody.Path, " contentType:", reqBody.ContentType, " formMap:",reqBody.FormMap, " postFormMap:", reqBody.PostFormMap, "to key: ", p)
 
        if f,ok := ms.handlers[reqBody.Path];ok {
            reqBody.SrcProc = msgR.SrcProc
            ri = f(&reqBody)
            ms.printLog("call funcMap f,reply:", *ri)
        } else {
            ms.printLog("ms.funcMap not eixst path: ", reqBody.Path)
            ri = &Reply{
                Success: false,
                Msg: "请求的接口不存在,请检查url",
                Data: "请求的接口不存在,请检查url",
            }
        }
    }
 
    retErr := ms.handle.Reply(p, ri)
    if retErr != nil {
        ms.printLog("retErr:", retErr)
    }
}
 
//发布到本机
func (ms *MicroNode) Publish(topic string,msg []byte) error {
    nodes := append([]bhomebus.NetNode{}, bhomebus.NetNode{
        Key: 8,
    })
    return ms.PublishNet(nodes, topic, msg)
}
 
func (ms *MicroNode) PublishNet(nodes []bhomebus.NetNode, topic string,msg []byte) error {
    pi := &MsgInfo{
        Topic: topic,
        Body: msg,
    }
    return ms.handle.Pub(nodes, pi)
}
 
//订阅主题
func (ms *MicroNode) Subscribe(topics []string) {
    ms.handle.Sub(topics)
    for _,t := range topics {
        if ms.reg.SubTopic == nil {
            ms.reg.SubTopic = make([]string, 0)
        }
        found := false
        for _,it := range ms.reg.SubTopic {
            if it == t {
                found = true
                break
            }
        }
        if !found {
            ms.reg.SubTopic = append(ms.reg.SubTopic, t)
        }
    }
}
 
//取消订阅的主题
func (ms *MicroNode) DeSub(topics []string) {
    ms.printLog("DeSub topics:", topics)
    ms.handle.DeSub(topics)
    if ms.reg.SubTopic != nil {
        var leftTopics []string
        for _,t := range ms.reg.SubTopic {
            found := false
            for _,it := range topics {
                if it == t {
                    found = true
                    break
                }
            }
            if !found {
                leftTopics = append(leftTopics, t)
            }
        }
        ms.reg.SubTopic = leftTopics
    }
}
 
//free handle
func (ms *MicroNode) Free() {
    if ms.handle != nil {
        ms.handle.Free()
    }
}