-
Notifications
You must be signed in to change notification settings - Fork 0
/
message_server.go
188 lines (164 loc) · 4.82 KB
/
message_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
// Copyright 2018 The Harbor Authors. All rights reserved.
package pool
import (
"context"
"encoding/json"
"errors"
"reflect"
"time"
"github.com/vmware/harbor/src/jobservice/logger"
"github.com/vmware/harbor/src/jobservice/opm"
"github.com/vmware/harbor/src/jobservice/period"
"github.com/garyburd/redigo/redis"
"github.com/vmware/harbor/src/jobservice/models"
"github.com/vmware/harbor/src/jobservice/utils"
)
//MessageServer implements the sub/pub mechanism via redis to do async message exchanging.
type MessageServer struct {
context context.Context
redisPool *redis.Pool
namespace string
callbacks map[string]reflect.Value //no need to sync
}
//NewMessageServer creates a new ptr of MessageServer
func NewMessageServer(ctx context.Context, namespace string, redisPool *redis.Pool) *MessageServer {
return &MessageServer{
context: ctx,
redisPool: redisPool,
namespace: namespace,
callbacks: make(map[string]reflect.Value),
}
}
//Start to serve
func (ms *MessageServer) Start() error {
defer func() {
logger.Info("Message server is stopped")
}()
//As we get one connection from the pool, don't try to close it.
conn := ms.redisPool.Get()
defer conn.Close()
psc := redis.PubSubConn{
Conn: conn,
}
err := psc.Subscribe(redis.Args{}.AddFlat(utils.KeyPeriodicNotification(ms.namespace))...)
if err != nil {
return err
}
done := make(chan error, 1)
go func() {
for {
switch res := psc.Receive().(type) {
case error:
done <- res
return
case redis.Message:
m := &models.Message{}
if err := json.Unmarshal(res.Data, m); err != nil {
//logged
logger.Warningf("Read invalid message: %s\n", res.Data)
}
if callback, ok := ms.callbacks[m.Event]; !ok {
//logged
logger.Warningf("no handler to handle event %s\n", m.Event)
} else {
//logged incoming events
logger.Infof("Receive event '%s' with data(unformatted): %+#v\n", m.Event, m.Data)
//Try to recover the concrete type
var converted interface{}
switch m.Event {
case period.EventSchedulePeriodicPolicy,
period.EventUnSchedulePeriodicPolicy:
//ignore error, actually error should not be happend because we did not change data
//after the last unmarshal try.
policyObject := &period.PeriodicJobPolicy{}
dt, _ := json.Marshal(m.Data)
json.Unmarshal(dt, policyObject)
converted = policyObject
case opm.EventRegisterStatusHook:
//ignore error
hookObject := &opm.HookData{}
dt, _ := json.Marshal(m.Data)
json.Unmarshal(dt, hookObject)
converted = hookObject
case opm.EventFireCommand:
//no need to convert []string
converted = m.Data
}
res := callback.Call([]reflect.Value{reflect.ValueOf(converted)})
e := res[0].Interface()
if e != nil {
err := e.(error)
//logged
logger.Errorf("Failed to fire callback with error: %s\n", err)
}
}
case redis.Subscription:
switch res.Kind {
case "subscribe":
logger.Infof("Subscribe redis channel %s\n", res.Channel)
break
case "unsubscribe":
//Unsubscribe all, means main goroutine is exiting
logger.Infof("Unsubscribe redis channel %s\n", res.Channel)
done <- nil
return
}
}
}
}()
logger.Info("Message server is started")
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
//blocking here
for err == nil {
select {
case <-ticker.C:
err = psc.Ping("ping!")
case <-ms.context.Done():
err = errors.New("context exit")
case err = <-done:
return err
}
}
//Unsubscribe all
psc.Unsubscribe()
return <-done
}
//Subscribe event with specified callback
func (ms *MessageServer) Subscribe(event string, callback interface{}) error {
if utils.IsEmptyStr(event) {
return errors.New("empty event is not allowed")
}
handler, err := validateCallbackFunc(callback)
if err != nil {
return err
}
ms.callbacks[event] = handler
return nil
}
func validateCallbackFunc(callback interface{}) (reflect.Value, error) {
if callback == nil {
return reflect.ValueOf(nil), errors.New("nil callback handler")
}
vFn := reflect.ValueOf(callback)
vFType := vFn.Type()
if vFType.Kind() != reflect.Func {
return reflect.ValueOf(nil), errors.New("callback handler must be a generic func")
}
inNum := vFType.NumIn()
outNum := vFType.NumOut()
if inNum != 1 || outNum != 1 {
return reflect.ValueOf(nil), errors.New("callback handler can only be func(interface{})error format")
}
inType := vFType.In(0)
var intf *interface{}
if inType != reflect.TypeOf(intf).Elem() {
return reflect.ValueOf(nil), errors.New("callback handler can only be func(interface{})error format")
}
outType := vFType.Out(0)
var e *error
if outType != reflect.TypeOf(e).Elem() {
return reflect.ValueOf(nil), errors.New("callback handler can only be func(interface{})error format")
}
return vFn, nil
}