-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsynerex-server.go
1219 lines (1087 loc) · 36.9 KB
/
synerex-server.go
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
//go:generate protoc -I ../api --go_out=paths=source_relative,plugins=grpc:../api ../api/synerex.proto
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net"
"os"
"path"
"strconv"
"strings"
"sync"
"time"
api "github.com/synerex/synerex_api"
nodeapi "github.com/synerex/synerex_nodeapi"
pbase "github.com/synerex/synerex_proto"
sxutil "github.com/synerex/synerex_sxutil"
"github.com/rcrowley/go-metrics"
"google.golang.org/grpc"
)
const MessageChannelBufferSize = 100
var (
port = flag.Int("port", getServerPort(), "The Synerex Server Listening Port")
servaddr = flag.String("servaddr", getServerHostName(), "Server Address for Other Providers")
nodeport = flag.Int("nodeport", getNodeservPort(), "The Node ID Server Listening Port")
nodeaddr = flag.String("nodeaddr", getNodeservHostName(), "Node ID Server Address")
name = flag.String("name", getServerName(), "Server Name for Other Providers")
isMetrics = flag.Bool("metrics", getIsMetrics(), "Expose Server Metrics")
// log = logrus.New() // for default logging
server_id uint64
sinfo *synerexServerInfo
)
//type sxutil.IDType uint64
type synerexServerInfo struct {
demandChans [pbase.ChannelTypeMax][]chan *api.Demand // create slices for each ChannelType(each slice contains channels)
supplyChans [pbase.ChannelTypeMax][]chan *api.Supply
mbusChans map[uint64][]chan *api.MbusMsg // Private Message bus for each provider
mbusMap map[sxutil.IDType]map[uint64]chan *api.MbusMsg // map from sxutil.IDType to Mbus channel
demandMap [pbase.ChannelTypeMax]map[sxutil.IDType]chan *api.Demand // map from sxutil.IDType to Demand channel
supplyMap [pbase.ChannelTypeMax]map[sxutil.IDType]chan *api.Supply // map from sxutil.IDType to Supply channel
waitConfirms [pbase.ChannelTypeMax]map[sxutil.IDType]chan *api.Target // confirm maps
gatewayMap map[sxutil.IDType]chan *api.GatewayMsg // for gateway. (//TODO: should use channels)
dmu, smu, mmu, wmu, gmu sync.RWMutex
messageStore *MessageStore // message store
}
// for metrics
var (
totalMessages = metrics.NewCounter()
receiveMessages = metrics.NewCounter()
sendMessages = metrics.NewCounter()
mbusMessages = metrics.NewCounter()
)
func getServerHostName() string {
env := os.Getenv("SX_SERVER_HOST")
if env != "" {
return env
} else {
return "127.0.0.1"
}
}
func getNodeservHostName() string {
env := os.Getenv("SX_NODESERV_HOST")
if env != "" {
return env
} else {
return "127.0.0.1"
}
}
func getServerPort() int {
env := os.Getenv("SX_SERVER_PORT")
if env != "" {
env, _ := strconv.Atoi(env)
return env
} else {
return 10000
}
}
func getNodeservPort() int {
env := os.Getenv("SX_NODESERV_PORT")
if env != "" {
env, _ := strconv.Atoi(env)
return env
} else {
return 9990
}
}
func getServerName() string {
env := os.Getenv("SX_SERVER_NAME")
if env != "" {
return env
} else {
return "SynerexServer"
}
}
func getIsMetrics() bool {
env := os.Getenv("SX_SERVER_METRICS")
if env == "false" {
return false
} else {
return true
}
}
func init() {
// sxutil.InitNodeNum(0)
// for Logrus initialization
// log.Formatter = new(logprefix.TextFormatter)
// log.Level = logrus.DebugLevel // TODO: Should we change this by flag?
// log.Printf("Initialized!")
if *isMetrics {
log.Printf("Register Metrics")
// for metrics initialization
metrics.Register("messages.total", totalMessages)
metrics.Register("messages.receive", receiveMessages)
metrics.Register("messages.send", sendMessages)
metrics.Register("messages.mbus", mbusMessages)
// log -> syslog
InitMetricsLog()
}
}
func sendDemand(s *synerexServerInfo, dm *api.Demand, isGateway bool) (okFlag bool, okMsg string) {
okFlag = true
okMsg = ""
totalMessages.Inc(1)
receiveMessages.Inc(1)
s.dmu.RLock()
chs := s.demandChans[dm.GetChannelType()]
for i := range chs {
ch := chs[i]
if len(ch) < MessageChannelBufferSize { // performance trouble?
totalMessages.Inc(1)
sendMessages.Inc(1)
ch <- dm
} else {
okFlag = false
okMsg = fmt.Sprintf("SendDemand MessageDrop %v", dm)
log.Printf(okMsg)
}
}
s.dmu.RUnlock()
if len(s.gatewayMap) > 0 && !isGateway {
gm := &api.GatewayMsg{
SrcSynerexId: server_id,
MsgType: api.MsgType_DEMAND,
MsgOneof: &api.GatewayMsg_Demand{Demand: dm},
}
s.gmu.RLock()
for _, gch := range s.gatewayMap { // TODO: may performance check!
totalMessages.Inc(1)
sendMessages.Inc(1)
gch <- gm
}
s.gmu.RUnlock()
}
return okFlag, okMsg
}
// Implementation of each Protocol API
func (s *synerexServerInfo) NotifyDemand(c context.Context, dm *api.Demand) (r *api.Response, e error) {
// send demand for desired channels
okFlag, okMsg := sendDemand(s, dm, false)
r = &api.Response{Ok: okFlag, Err: okMsg}
return r, nil
}
func sendSupply(s *synerexServerInfo, sp *api.Supply, isGateway bool) (okFlag bool, okMsg string) {
okFlag = true
okMsg = ""
s.smu.RLock()
totalMessages.Inc(1)
receiveMessages.Inc(1)
chs := s.supplyChans[sp.GetChannelType()]
for i := range chs {
ch := chs[i]
if len(ch) < MessageChannelBufferSize { // run under not blocking state.
totalMessages.Inc(1)
sendMessages.Inc(1)
ch <- sp
} else {
okMsg = fmt.Sprintf("SendSupply MessageDrop %v", sp)
okFlag = false
log.Printf(okMsg)
}
}
s.smu.RUnlock()
if len(s.gatewayMap) > 0 && !isGateway {
gm := &api.GatewayMsg{
SrcSynerexId: server_id,
MsgType: api.MsgType_SUPPLY,
MsgOneof: &api.GatewayMsg_Supply{Supply: sp},
}
s.gmu.RLock()
for _, gch := range s.gatewayMap { // TODO: may performance check!
totalMessages.Inc(1)
sendMessages.Inc(1)
gch <- gm
}
s.gmu.RUnlock()
}
return okFlag, okMsg
}
func (s *synerexServerInfo) NotifySupply(c context.Context, sp *api.Supply) (r *api.Response, e error) {
// fmt.Printf("Notify Supply!!!")
ctype := sp.GetChannelType()
if ctype == 0 || ctype >= pbase.ChannelTypeMax {
log.Printf("ChannelType Error! %d", ctype)
r = &api.Response{Ok: false, Err: "ChannelType Error"}
return r, errors.New("ChannelType Error")
}
okFlag, okMsg := sendSupply(s, sp, false)
r = &api.Response{Ok: okFlag, Err: okMsg}
return r, nil
}
func (s *synerexServerInfo) ProposeDemand(c context.Context, dm *api.Demand) (r *api.Response, e error) {
ctype := dm.GetChannelType()
if ctype == 0 || ctype >= pbase.ChannelTypeMax {
log.Printf("ChannelType Error! %d", ctype)
r = &api.Response{Ok: false, Err: "ChannelType Error"}
return r, errors.New("ChannelType Error")
}
okFlag, okMsg := sendDemand(s, dm, false)
r = &api.Response{Ok: okFlag, Err: okMsg}
return r, nil
}
func (s *synerexServerInfo) ProposeSupply(c context.Context, sp *api.Supply) (r *api.Response, e error) {
ctype := sp.GetChannelType()
if ctype == 0 || ctype >= pbase.ChannelTypeMax {
log.Printf("ChannelType Error! %d", ctype)
r = &api.Response{Ok: false, Err: "ChannelType Error"}
return r, errors.New("ChannelType Error")
}
okFlag, okMsg := sendSupply(s, sp, false)
r = &api.Response{Ok: okFlag, Err: okMsg}
return r, nil
}
func (s *synerexServerInfo) SelectSupply(c context.Context, tg *api.Target) (r *api.ConfirmResponse, e error) {
targetSender := s.messageStore.getSrcId(tg.GetTargetId()) // find source from Id
ctype := tg.GetChannelType()
if ctype == 0 || ctype >= pbase.ChannelTypeMax {
log.Printf("ChannelType Error! %d", ctype)
r = &api.ConfirmResponse{Ok: false, Err: "ChannelType Error"}
return r, errors.New("ChannelType Error")
}
s.dmu.RLock()
// find subscribe demand with sender
ch, ok := s.demandMap[ctype][sxutil.IDType(targetSender)]
s.dmu.RUnlock()
if !ok {
//TODO: there might be packet through gateway...
if len(s.gatewayMap) == 0 {
r = &api.ConfirmResponse{Ok: false, Err: "Can't find demand target from SelectSupply"}
log.Printf("Can't find SelectSupply target ID %d, src %d", tg.GetTargetId(), targetSender)
e = errors.New("Cant find channel in SelectSupply")
return
} else {
// TODO: implement select for gateway!
return
}
}
id := sxutil.GenerateIntID()
dm := &api.Demand{
Id: id, // generate ID from synerex server
SenderId: tg.SenderId,
TargetId: tg.TargetId,
ChannelType: tg.ChannelType,
MbusId: id, // mbus id is a message id for select.
}
//
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("ServSelSupply", int(tg.Type), dm.Id, tg.SenderId, tg.TargetId, tg.TargetId, args)
tch := make(chan *api.Target)
s.wmu.Lock()
s.waitConfirms[tg.ChannelType][sxutil.IDType(id)] = tch
s.wmu.Unlock()
ch <- dm // send select message
// wait for confim...
select {
case tb := <-tch: // got confirm!
s.wmu.Lock() // remove waitChannel
delete(s.waitConfirms[tg.ChannelType], sxutil.IDType(id))
s.wmu.Unlock()
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("gotConfirm", int(tg.Type), dm.Id, tb.SenderId, tb.TargetId, tb.TargetId, args)
if tb.TargetId == id {
if tb.MbusId == id {
r = &api.ConfirmResponse{Ok: true, Err: "", MbusId: id}
return r, nil
} else {
r = &api.ConfirmResponse{Ok: true, Err: "no mbus id"}
return r, nil
}
}
case <-time.After(30 * time.Second): // timeout! // todo: reconsider expiration time.
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("notConfirm", int(tg.Type), dm.Id, tg.SenderId, tg.TargetId, tg.TargetId, args)
r = &api.ConfirmResponse{Ok: false, Err: "waitConfirm Timeout!"}
}
return r, errors.New("Should not happen")
}
func (s *synerexServerInfo) SelectModifiedSupply(c context.Context, sp *api.Supply) (r *api.ConfirmResponse, e error) {
targetSender := s.messageStore.getSrcId(sp.GetTargetId()) // find source from Id
ctype := sp.GetChannelType()
if ctype == 0 || ctype >= pbase.ChannelTypeMax {
log.Printf("ChannelType Error! %d", ctype)
r = &api.ConfirmResponse{Ok: false, Err: "ChannelType Error"}
return r, errors.New("ChannelType Error")
}
s.dmu.RLock()
// find subscribe demand with sender
ch, ok := s.demandMap[ctype][sxutil.IDType(targetSender)]
s.dmu.RUnlock()
if !ok {
//TODO: there might be packet through gateway...
if len(s.gatewayMap) == 0 {
r = &api.ConfirmResponse{Ok: false, Err: "Can't find demand target from SelectSupply"}
log.Printf("Can't find SelectSupply target ID %d, src %d", sp.GetTargetId(), targetSender)
e = errors.New("Cant find channel in SelectSupply")
return
} else {
// TODO: implement select for gateway!
return
}
}
id := sxutil.GenerateIntID()
// This time we send modified Supply with Demand frame.
dm := &api.Demand{
Id: id, // generate ID from synerex server
SenderId: sp.SenderId,
TargetId: sp.TargetId,
ChannelType: sp.ChannelType,
DemandName: sp.SupplyName,
Ts: sp.Ts,
ArgJson: sp.ArgJson,
MbusId: id, // mbus id is a message id for select.
Cdata: sp.Cdata,
}
//
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("ServSelSupply", int(tg.Type), dm.Id, tg.SenderId, tg.TargetId, tg.TargetId, args)
tch := make(chan *api.Target)
s.wmu.Lock()
s.waitConfirms[sp.ChannelType][sxutil.IDType(id)] = tch
s.wmu.Unlock()
ch <- dm // send select message
// wait for confim...
select {
case tb := <-tch: // got confirm!
s.wmu.Lock() // remove waitChannel
delete(s.waitConfirms[sp.ChannelType], sxutil.IDType(id))
s.wmu.Unlock()
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("gotConfirm", int(tg.Type), dm.Id, tb.SenderId, tb.TargetId, tb.TargetId, args)
if tb.TargetId == id {
if tb.MbusId == id {
r = &api.ConfirmResponse{Ok: true, Err: "", MbusId: id}
return r, nil
} else {
r = &api.ConfirmResponse{Ok: true, Err: "no mbus id"}
return r, nil
}
}
case <-time.After(30 * time.Second): // timeout! // todo: reconsider expiration time.
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("notConfirm", int(tg.Type), dm.Id, tg.SenderId, tg.TargetId, tg.TargetId, args)
r = &api.ConfirmResponse{Ok: false, Err: "waitConfirm Timeout!"}
}
return r, errors.New("Should not happen")
}
func (s *synerexServerInfo) SelectDemand(c context.Context, tg *api.Target) (r *api.ConfirmResponse, e error) {
targetSender := s.messageStore.getSrcId(tg.GetTargetId()) // find source from Id
ctype := tg.GetChannelType()
if ctype == 0 || ctype >= pbase.ChannelTypeMax {
log.Printf("ChannelType Error! %d", ctype)
r = &api.ConfirmResponse{Ok: false, Err: "ChannelType Error"}
return r, errors.New("ChannelType Error")
}
s.dmu.RLock()
// find subscribe supply with sender
ch, ok := s.supplyMap[ctype][sxutil.IDType(targetSender)]
s.dmu.RUnlock()
if !ok {
//TODO: there might be packet through gateway...
if len(s.gatewayMap) == 0 {
r = &api.ConfirmResponse{Ok: false, Err: "Can't find supply target from SelectDemand"}
log.Printf("Can't find SelectDemand target ID %d, src %d", tg.GetTargetId(), targetSender)
e = errors.New("Cant find channel in SelectDemand")
return
} else {
// TODO: implement select for gateway!
return
}
}
id := sxutil.GenerateIntID()
sp := &api.Supply{
Id: id, // generate ID from synerex server
SenderId: tg.SenderId,
TargetId: tg.TargetId,
ChannelType: tg.ChannelType,
MbusId: id, // mbus id is a message id for select.
}
//
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("ServSelDemand", int(tg.Type), dm.Id, tg.SenderId, tg.TargetId, tg.TargetId, args)
tch := make(chan *api.Target)
s.wmu.Lock()
s.waitConfirms[tg.ChannelType][sxutil.IDType(id)] = tch
log.Printf("waitConfirms: %+v", s.waitConfirms)
s.wmu.Unlock()
ch <- sp // send select message
// wait for confim...
select {
case tb := <-tch: // got confirm!
s.wmu.Lock() // remove waitChannel
delete(s.waitConfirms[tg.ChannelType], sxutil.IDType(id))
s.wmu.Unlock()
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("gotConfirm", int(tg.Type), dm.Id, tb.SenderId, tb.TargetId, tb.TargetId, args)
if tb.TargetId == id {
if tb.MbusId == id {
r = &api.ConfirmResponse{Ok: true, Err: "", MbusId: id}
return r, nil
} else {
r = &api.ConfirmResponse{Ok: true, Err: "no mbus id"}
return r, nil
}
}
case <-time.After(30 * time.Second): // timeout! // todo: reconsider expiration time.
// args := idToNode(tg.SenderId) + "->" + idToNode(tg.TargetId)
// go monitorapi.SendMessage("notConfirm", int(tg.Type), dm.Id, tg.SenderId, tg.TargetId, tg.TargetId, args)
r = &api.ConfirmResponse{Ok: false, Err: "waitConfirm Timeout!"}
}
return r, errors.New("Should not happen")
}
func (s *synerexServerInfo) Confirm(c context.Context, tg *api.Target) (r *api.Response, e error) {
// check waitConfirms
s.wmu.RLock()
ch, ok := s.waitConfirms[tg.ChannelType][sxutil.IDType(tg.TargetId)]
s.wmu.RUnlock()
// go monitorapi.SendMessage("ServConfirm", int(tg.ChannelType), tg.Id, tg.SenderId, 0, tg.TargetId, "ConfirmTo")
if !ok {
ss := fmt.Sprintf("Can't find targetID %d in channel %d", tg.TargetId, tg.ChannelType)
log.Print(ss)
r = &api.Response{Ok: false, Err: ss}
return r, errors.New(ss)
}
ch <- tg // send OK
r = &api.Response{Ok: true, Err: ""}
return r, nil
}
// go routine which wait demand channel and sending demands to each providers.
func demandServerFunc(ch chan *api.Demand, stream api.Synerex_SubscribeDemandServer, id sxutil.IDType, chnum uint32) error {
for dm := range ch { // block until receiving info
err := stream.Send(dm)
if err != nil {
log.Printf("Error in DemandServer Error %v", err)
return err
}
}
log.Printf("SubscribeDemand for Client node %v Channel %d is closed.", id, chnum)
return nil
}
// remove channel from slice
func removeDemandChannelFromSlice(sl []chan *api.Demand, c chan *api.Demand) []chan *api.Demand {
for i, ch := range sl {
if ch == c {
return append(sl[:i], sl[i+1:]...)
}
}
log.Printf("Cant find channel %v in removeChannel", c)
return sl
}
func removeSupplyChannelFromSlice(sl []chan *api.Supply, c chan *api.Supply) []chan *api.Supply {
for i, ch := range sl {
if ch == c {
return append(sl[:i], sl[i+1:]...)
}
}
log.Printf("Cant find channel %v in removeChannel", c)
return sl
}
// SubscribeDemand is called form client to subscribe channel
func (s *synerexServerInfo) SubscribeDemand(ch *api.Channel, stream api.Synerex_SubscribeDemandServer) error {
// TODO: we can check the duplication of node id here! (especially 1024 snowflake node ID)
idt := sxutil.IDType(ch.GetClientId())
s.dmu.Lock()
_, ok := s.demandMap[ch.ChannelType][idt]
if ok { // check the availability of duplicated client ID
s.dmu.Unlock()
return fmt.Errorf("duplicated SubscribeDemand ClientID %d", idt)
}
log.Printf("Subscribe Demand Channel:%d, Node:%d Args: %s", ch.ChannelType, ch.ClientId, ch.ArgJson)
// It is better to logging here.
// monitorapi.SendMes(&monitorapi.Mes{Message:"Subscribe Demand", Args: fmt.Sprintf("Type:%d,From: %x %s",ch.Type,ch.ClientId, ch.ArgJson )})
// monitorapi.SendMessage("SubscribeDemand", int(ch.Type), 0, ch.ClientId, 0, 0, ch.ArgJson)
subCh := make(chan *api.Demand, MessageChannelBufferSize)
// We should think about thread safe coding.
tp := ch.GetChannelType()
s.demandChans[tp] = append(s.demandChans[tp], subCh)
s.demandMap[tp][idt] = subCh // mapping from clientID to channel
s.dmu.Unlock()
demandServerFunc(subCh, stream, idt, tp) // infinite go routine?
// if this returns, stream might be closed.
// we should remove channel
s.dmu.Lock()
_, ok = s.demandMap[tp][idt]
if ok {
delete(s.demandMap[tp], idt) // remove map from idt
s.demandChans[tp] = removeDemandChannelFromSlice(s.demandChans[tp], subCh)
log.Printf("Remove Demand Stream Channel %v", ch)
}
s.dmu.Unlock()
return nil
}
// This function is created for each subscribed provider
// This is not efficient if the number of providers increases.
func supplyServerFunc(ch chan *api.Supply, stream api.Synerex_SubscribeSupplyServer, idt sxutil.IDType, chnum uint32) error {
for sp := range ch { // block until receiving info
err := stream.Send(sp)
if err != nil {
log.Printf("Error in SupplyServer Error %v", err)
log.Printf("SubscribeSupply for Client node %v Channel %d is closed.", idt, chnum)
return err
}
}
log.Printf("SubscribeSupply for Client node %v Channel %d is closed.", idt, chnum)
return nil
}
func (s *synerexServerInfo) SubscribeSupply(ch *api.Channel, stream api.Synerex_SubscribeSupplyServer) error {
idt := sxutil.IDType(ch.GetClientId())
tp := ch.GetChannelType()
s.smu.Lock()
_, ok := s.supplyMap[tp][idt]
if ok { // check the availability of duplicated client ID
s.smu.Unlock()
return errors.New(fmt.Sprintf("duplicated SubscribeSupply for ClientID %v", idt))
}
subCh := make(chan *api.Supply, MessageChannelBufferSize)
log.Printf("Subscribe Supply Channel:%d, Node:%d Args: %s", ch.ChannelType, ch.ClientId, ch.ArgJson)
// monitorapi.SendMes(&monitorapi.Mes{Message:"Subscribe Supply", Args: fmt.Sprintf("Type:%d, From: %x %s",ch.Type,ch.ClientId,ch.ArgJson )})
// monitorapi.SendMessage("SubscribeSupply", int(ch.Type), 0, ch.ClientId, 0, 0, ch.ArgJson)
s.supplyChans[tp] = append(s.supplyChans[tp], subCh)
s.supplyMap[tp][idt] = subCh // mapping from clientID to channel
s.smu.Unlock()
err := supplyServerFunc(subCh, stream, idt, tp)
// this supply stream may closed. so take care.
s.smu.Lock()
_, ok = s.supplyMap[tp][idt] // still exist? (may removed by others)
if ok {
delete(s.supplyMap[tp], idt) // remove map from idt
s.supplyChans[tp] = removeSupplyChannelFromSlice(s.supplyChans[tp], subCh)
log.Printf("Remove Supply Stream Channel %v", ch)
}
s.smu.Unlock()
return err
}
// for closing demand channel
func (s *synerexServerInfo) CloseDemandChannel(ctx context.Context, ch *api.Channel) (resp *api.Response, err error) {
idt := sxutil.IDType(ch.GetClientId())
tp := ch.GetChannelType()
err = nil
s.smu.Lock()
subCh, ok := s.demandMap[tp][idt]
if ok {
delete(s.demandMap[tp], idt) // remove map from idt
s.demandChans[tp] = removeDemandChannelFromSlice(s.demandChans[tp], subCh)
log.Printf("Remove Demand Channel %v", ch)
close(subCh) // close subchannel!
resp = &api.Response{
Ok: true,
}
} else {
log.Printf("Cannot find Demand Channel %v", ch)
resp = &api.Response{
Ok: false,
Err: fmt.Sprintf("Cannot find Demand Channel %v", ch),
}
}
s.smu.Unlock()
return resp, nil
}
func (s *synerexServerInfo) CloseSupplyChannel(ctx context.Context, ch *api.Channel) (resp *api.Response, err error) {
idt := sxutil.IDType(ch.GetClientId())
tp := ch.GetChannelType()
s.smu.Lock()
subCh, ok := s.supplyMap[tp][idt]
if ok {
delete(s.supplyMap[tp], idt) // remove map from idt
s.supplyChans[tp] = removeSupplyChannelFromSlice(s.supplyChans[tp], subCh)
log.Printf("Remove Supply Channel %v", ch)
close(subCh) // close subchannel!
resp = &api.Response{
Ok: true,
}
} else {
log.Printf("Cannot find Supply Channel %v", ch)
resp = &api.Response{
Ok: false,
Err: fmt.Sprintf("Cannot find Supply Channel %v", ch),
}
}
s.smu.Unlock()
return resp, nil
}
func showAllSubscribers() {
supp := make([]string, 0)
for tp, chans := range sinfo.supplyMap {
if len(chans) > 0 {
supp = append(supp, fmt.Sprintf("SupplyType:%d", tp))
for node, _ := range chans {
supp = append(supp, fmt.Sprintf("ID:%d", node))
}
}
}
for tp, chans := range sinfo.demandMap {
if len(chans) > 0 {
supp = append(supp, fmt.Sprintf("DemandType:%d", tp))
for node, _ := range chans {
supp = append(supp, fmt.Sprintf("ID:%d", node))
}
}
}
log.Printf("ShowAll: %v", supp)
}
func closeAllChannels(node_id int32) {
idt := sxutil.IDType(node_id)
sinfo.smu.Lock()
// starting from supplyMap
for tp, chans := range sinfo.supplyMap {
subCh, ok := chans[idt]
if ok {
delete(chans, idt) // remove map from idt
// log.Printf("Length of supplyChans %d", len(sinfo.supplyChans[tp]))
sinfo.supplyChans[tp] = removeSupplyChannelFromSlice(sinfo.supplyChans[tp], subCh)
log.Printf("Remove Supply Channel node_id %v, chan %v", idt, tp)
close(subCh) // close subchannel!
}
}
for tp, chans := range sinfo.demandMap {
subCh, ok := chans[idt]
if ok {
delete(chans, idt) // remove map from idt
// log.Printf("Length of demandChans %d", len(sinfo.demandChans[tp]))
sinfo.demandChans[tp] = removeDemandChannelFromSlice(sinfo.demandChans[tp], subCh)
log.Printf("Remove Demand Channel node_id %v, chan %v", idt, tp)
close(subCh) // close subchannel!
}
}
sinfo.smu.Unlock()
}
// Closing all channels related to provider ID.
func (s *synerexServerInfo) CloseAllChannels(ctx context.Context, pid *api.ProviderID) (resp *api.Response, err error) {
closeAllChannels(int32(pid.GetClientId()))
resp = &api.Response{
Ok: true,
}
return resp, nil
}
// This function is created for each subscribed provider
// This is not efficient if the number of providers increases.
func mbusServerFunc(ch chan *api.MbusMsg, stream api.Synerex_SubscribeMbusServer, id sxutil.IDType) error {
for {
select {
case msg := <-ch:
if msg.GetMsgId() == 0 { // close message
return nil // grace close
}
if sxutil.IDType(msg.GetSenderId()) != id { // do not send msg from myself
tgt := sxutil.IDType(msg.GetTargetId())
if tgt == 0 || tgt == id { // =0 broadcast , = tgt unicast
err := stream.Send(msg)
if err != nil {
// log.Printf("Error mBus Error %v", err)
return err
}
totalMessages.Inc(1) // update total counter
mbusMessages.Inc(1) // update mbus counter
}
}
}
}
}
func removeMbusChannelFromSlice(sl []chan *api.MbusMsg, c chan *api.MbusMsg) []chan *api.MbusMsg {
for i, ch := range sl {
if ch == c {
return append(sl[:i], sl[i+1:]...)
}
}
log.Printf("Cant find channel %v in removeMbusChannel", c)
return sl
}
func (s *synerexServerInfo) SubscribeMbus(mb *api.Mbus, stream api.Synerex_SubscribeMbusServer) error {
mbusCh := make(chan *api.MbusMsg, MessageChannelBufferSize) // make channel for each mbus
id := sxutil.IDType(mb.GetClientId())
mbid := mb.MbusId
s.mmu.Lock()
chans, cok := s.mbusChans[mbid]
if cok == false {
log.Printf("new MbusChan for MbusID %d", mbid)
} else {
log.Printf("next MbusChan for MbusID %d, len(%d)", mbid, len(chans))
}
s.mbusChans[mbid] = append(chans, mbusCh)
mm, ok := s.mbusMap[id]
if ok {
// mm[mbid] = mbusCh
} else {
mm = make(map[uint64]chan *api.MbusMsg)
mm[mbid] = mbusCh
s.mbusMap[id] = mm
}
s.mmu.Unlock()
err := mbusServerFunc(mbusCh, stream, id) // loop until close for each subscriber.
s.mmu.Lock()
s.mbusChans[mbid] = removeMbusChannelFromSlice(s.mbusChans[mbid], mbusCh)
delete(s.mbusMap, id)
// log.Printf("Remove Mbus Stream Channel %v", ch)
s.mmu.Unlock()
return err
}
// update name from synerex_api v0.4.1
func (s *synerexServerInfo) SendMbusMsg(c context.Context, msg *api.MbusMsg) (r *api.Response, err error) {
// FIXME: wait until all subscriber is comming
count := 0 // loop counter.
for {
chans, ok := s.mbusChans[msg.GetMbusId()]
if ok && len(chans) >= 2 {
log.Printf("##### All subscriber comming!! [MbusID: %d]\n", msg.GetMbusId())
break
}
count++
if count > 10 {
log.Printf("##### Mbus Subscription timeout [MbusId: %d]\n", msg.GetMbusId())
break
}
log.Printf("##### Another Subscriber wating... [MbusId: %d, len(chans): %d]\n", msg.GetMbusId(), len(chans))
time.Sleep(1 * time.Second)
}
okFlag := true
okMsg := ""
s.mmu.RLock()
chs := s.mbusChans[msg.GetMbusId()] // get channel slice from mbus_id
for i := range chs {
ch := chs[i]
if len(ch) < MessageChannelBufferSize { // run under not blocking state.
ch <- msg
} else {
okMsg = fmt.Sprintf("MBus MessageDrop %v", msg)
okFlag = false
log.Printf(okMsg) // TODO: thisi is a critical log (message drop)
}
}
s.mmu.RUnlock()
r = &api.Response{Ok: okFlag, Err: okMsg}
return r, nil
}
func (s *synerexServerInfo) CloseMbus(c context.Context, mb *api.Mbus) (r *api.Response, err error) {
okFlag := true
okMsg := ""
s.mmu.RLock()
chs := s.mbusChans[mb.GetMbusId()] // get channel slice from mbus_id
cmsg := &api.MbusMsg{ // this is close message
MsgId: 0,
}
for i := range chs {
ch := chs[i]
if len(ch) < MessageChannelBufferSize { // run under not blocking state.
ch <- cmsg
} else {
okMsg = fmt.Sprintf("MBusClose MessageDrop %v", cmsg)
okFlag = false
log.Printf(okMsg)
}
}
s.mmu.RUnlock()
r = &api.Response{Ok: okFlag, Err: okMsg}
return r, nil
}
// from synerex_api v0.4.0
func (s *synerexServerInfo) CreateMbus(c context.Context, mbo *api.MbusOpt) (mb *api.Mbus, err error) {
// just generate new unique ID
// TODO: private mbus is not implemented yet!
if mbo.MbusType == api.MbusOpt_PRIVATE {
log.Printf("Private MBUS is not yet implemented!")
}
mb = &api.Mbus{}
mb.ClientId = 0 // client must set their own ID.
mb.MbusId = sxutil.GenerateIntID() // generate unique ID for new Mbus.
return mb, nil
}
// from synerex_api v0.4.0
func (s *synerexServerInfo) GetMbusState(c context.Context, mb *api.Mbus) (mbs *api.MbusState, err error) {
// return the status of Mbus.
// TODO: this method is not fully implemented yet!
mbs = &api.MbusState{
MbusId: mb.MbusId,
Status: api.MbusState_INVALID,
Subscribers: []uint64{},
}
return mbs, nil
}
func gatewayServerFunc(ch chan *api.GatewayMsg, ssgs api.Synerex_SubscribeGatewayServer) error {
for {
select {
case sp := <-ch:
err := ssgs.Send(sp)
if err != nil {
return err
}
}
}
}
// for Gateway subscribe
func (s *synerexServerInfo) SubscribeGateway(gi *api.GatewayInfo, ssgs api.Synerex_SubscribeGatewayServer) error {
log.Printf("Subscribe Gateway %v\n", gi)
idt := sxutil.IDType(gi.GetClientId())
// tp := gi.GetChannels() // not using channels:
s.gmu.RLock()
_, ok := s.gatewayMap[idt]
s.gmu.RUnlock()
if ok { // check the availability of duplicated gateway client ID
return errors.New(fmt.Sprintf("duplicated SubscribeGateway for ClientID %v", idt))
}
subCh := make(chan *api.GatewayMsg, MessageChannelBufferSize)
s.gmu.Lock()
s.gatewayMap[idt] = subCh // mapping from clientID to channel
s.gmu.Unlock()
err := gatewayServerFunc(subCh, ssgs)
// this supply stream may closed. so take care.
s.gmu.Lock()
delete(s.gatewayMap, idt) // remove map from idt
log.Printf("Remove Gateway Client %v", idt)
s.gmu.Unlock()
return err
}
// for Gateway Forward
func (s *synerexServerInfo) ForwardToGateway(ctx context.Context, gm *api.GatewayMsg) (*api.Response, error) {
// need to extract each message and then send them..
// send demand for desired channels
okFlag := true
okMsg := ""
msgType := gm.GetMsgType()
switch msgType {
case api.MsgType_DEMAND:
dm := gm.GetDemand()
okFlag, okMsg = sendDemand(s, dm, true)
case api.MsgType_SUPPLY:
sp := gm.GetSupply()
okFlag, okMsg = sendSupply(s, sp, true)
/*
case api.MsgType_TARGET:
tg := gm.GetTarget()
okFlag, okMsg = sendTarget(s, tg)
case api.MsgType_MBUS:
mb := gm.GetMbus()
okFlag, okMsg = sendMbus(s,mb)
case api.MsgType_MBUSMSG:
mbm := gm.GetMbusMsg()
okFlag, okMsg = sendMbusMsg(s,mbm)
*/
}
r := &api.Response{Ok: okFlag, Err: okMsg}
return r, nil
}
func newServerInfo() *synerexServerInfo {
var ms synerexServerInfo
s := &ms
for i := 0; i < pbase.ChannelTypeMax; i++ {
s.demandMap[i] = make(map[sxutil.IDType]chan *api.Demand)
s.supplyMap[i] = make(map[sxutil.IDType]chan *api.Supply)
s.waitConfirms[i] = make(map[sxutil.IDType]chan *api.Target)
}
s.mbusChans = make(map[uint64][]chan *api.MbusMsg)
s.mbusMap = make(map[sxutil.IDType]map[uint64]chan *api.MbusMsg)
s.messageStore = CreateLocalMessageStore()
s.gatewayMap = make(map[sxutil.IDType]chan *api.GatewayMsg)
return s
}
// synerex ID system
var (
NodeBits uint8 = 10
StepBits uint8 = 12
nodeMax int64 = -1 ^ (-1 << NodeBits)
nodeMask int64 = nodeMax << StepBits
nodeShift uint8 = StepBits
nodeMap = make(map[int]string)
)
func idToNode(id uint64) string {
nodeNum := int(int64(id) & nodeMask >> nodeShift) // snowflake node ID:
// var ok bool
var str string
// if str, ok = nodeMap[nodeNum]; !ok {
// str = sxutil.GetNodeName(nodeNum)
// }
rs := strings.Replace(str, "Provider", "", -1)
rs2 := strings.Replace(rs, "Server", "", -1)
return rs2 + ":" + strconv.Itoa(nodeNum)
}