-
Notifications
You must be signed in to change notification settings - Fork 62
/
service_provider.go
247 lines (199 loc) · 6.04 KB
/
service_provider.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
package goroslib
import (
"context"
"fmt"
"reflect"
"sync"
"time"
"github.com/bluenviron/goroslib/v2/pkg/prototcp"
"github.com/bluenviron/goroslib/v2/pkg/serviceproc"
)
type serviceProviderClientRequestReq struct {
spc *serviceProviderClient
req interface{}
}
// ServiceProviderConf is the configuration of a ServiceProvider.
type ServiceProviderConf struct {
// parent node.
Node *Node
// name of the service.
Name string
// an instance of the service type.
Srv interface{}
// function in the form func(*NameOfRequest) (*NameOfReply{}, bool)
// that will be called when a request arrives.
Callback interface{}
onClient func()
}
// ErrProviderTerminated is the error when the service provider has been terminated.
var ErrProviderTerminated = fmt.Errorf("service provider terminated")
// ServiceProvider is a ROS service provider, an entity that can receive requests
// and send back responses.
type ServiceProvider struct {
conf ServiceProviderConf
ctx context.Context
ctxCancel func()
srvType string
srvMD5 string
srvReq interface{}
clients map[*serviceProviderClient]struct{}
clientsWg sync.WaitGroup
// in
clientNew chan tcpConnServiceClientReq
clientClose chan *serviceProviderClient
clientRequest chan serviceProviderClientRequestReq
// out
done chan struct{}
}
// NewServiceProvider allocates a ServiceProvider. See ServiceProviderConf for the options.
func NewServiceProvider(conf ServiceProviderConf) (*ServiceProvider, error) {
if conf.Node == nil {
return nil, fmt.Errorf("Node is empty")
}
if conf.Name == "" {
return nil, fmt.Errorf("Name is empty")
}
if conf.Srv == nil {
return nil, fmt.Errorf("Srv is empty")
}
if reflect.TypeOf(conf.Srv).Kind() != reflect.Ptr {
return nil, fmt.Errorf("Srv is not a pointer")
}
srvElem := reflect.ValueOf(conf.Srv).Elem().Interface()
srvReq, srvRes, err := serviceproc.RequestResponse(srvElem)
if err != nil {
return nil, err
}
srvType, err := serviceproc.Type(srvElem)
if err != nil {
return nil, err
}
srvMD5, err := serviceproc.MD5(srvElem)
if err != nil {
return nil, err
}
conf.Name = conf.Node.applyCliRemapping(conf.Name)
cbt := reflect.TypeOf(conf.Callback)
if cbt.Kind() != reflect.Func {
return nil, fmt.Errorf("Callback is not a function")
}
if cbt.NumIn() != 1 {
return nil, fmt.Errorf("Callback must accept a single argument")
}
vin := cbt.In(0)
if vin.Kind() != reflect.Ptr {
return nil, fmt.Errorf("argument must be a pointer")
}
if vin.Elem() != reflect.TypeOf(srvReq) {
return nil, fmt.Errorf("invalid callback argument")
}
if cbt.NumOut() != 2 {
return nil, fmt.Errorf("Callback must return 2 values")
}
vout := cbt.Out(0)
if vout.Kind() != reflect.Ptr {
return nil, fmt.Errorf("first return value must be a pointer")
}
if vout.Elem() != reflect.TypeOf(srvRes) {
return nil, fmt.Errorf("invalid callback return value")
}
vout = cbt.Out(1)
if vout.Kind() != reflect.Bool {
return nil, fmt.Errorf("second return value must be a bool")
}
ctx, ctxCancel := context.WithCancel(conf.Node.ctx)
sp := &ServiceProvider{
conf: conf,
ctx: ctx,
ctxCancel: ctxCancel,
srvType: srvType,
srvMD5: srvMD5,
srvReq: srvReq,
clients: make(map[*serviceProviderClient]struct{}),
clientNew: make(chan tcpConnServiceClientReq),
clientClose: make(chan *serviceProviderClient),
clientRequest: make(chan serviceProviderClientRequestReq),
done: make(chan struct{}),
}
sp.conf.Node.Log(LogLevelDebug, "service provider '%s' created", sp.conf.Node.absoluteTopicName(sp.conf.Name))
cerr := make(chan error)
select {
case conf.Node.serviceProviderNew <- serviceProviderNewReq{sp: sp, res: cerr}:
err = <-cerr
if err != nil {
return nil, err
}
case <-sp.ctx.Done():
return nil, ErrProviderTerminated
}
go sp.run()
return sp, nil
}
// Close closes a ServiceProvider and shuts down all its operations.
func (sp *ServiceProvider) Close() {
sp.ctxCancel()
<-sp.done
sp.conf.Node.Log(LogLevelDebug, "service provider '%s' destroyed", sp.conf.Node.absoluteTopicName(sp.conf.Name))
}
func (sp *ServiceProvider) run() {
defer close(sp.done)
cbv := reflect.ValueOf(sp.conf.Callback)
outer:
for {
select {
case req := <-sp.clientNew:
err := func() error {
if req.header.Md5sum != "*" && req.header.Md5sum != sp.srvMD5 {
return fmt.Errorf("wrong service checksum: expected %s, got %s",
sp.srvMD5, req.header.Md5sum)
}
req.nconn.SetWriteDeadline(time.Now().Add(sp.conf.Node.conf.WriteTimeout))
return req.tconn.WriteHeader(&prototcp.HeaderServiceProvider{
Callerid: sp.conf.Node.absoluteName(),
Md5sum: sp.srvMD5,
RequestType: sp.srvType + "Request",
ResponseType: sp.srvType + "Response",
Type: sp.srvType,
})
}()
if err != nil {
sp.conf.Node.Log(LogLevelError,
"service provider '%s' is unable to accept client '%s': %s",
sp.conf.Node.absoluteTopicName(sp.conf.Name),
req.nconn.RemoteAddr(),
err)
req.nconn.Close()
continue
}
spc := newServiceProviderClient(sp, req.header.Callerid, req.nconn, req.tconn)
sp.clients[spc] = struct{}{}
case spc := <-sp.clientClose:
delete(sp.clients, spc)
case req := <-sp.clientRequest:
res := cbv.Call([]reflect.Value{reflect.ValueOf(req.req)})
state := res[1].Interface().(bool)
msg := res[0].Interface()
req.spc.nconn.SetWriteDeadline(time.Now().Add(sp.conf.Node.conf.WriteTimeout))
err := req.spc.tconn.WriteServiceResponse(state, msg)
if err != nil {
sp.conf.Node.Log(LogLevelError,
"service provider '%s' is unable to write to client '%s': %s",
sp.conf.Node.absoluteTopicName(sp.conf.Name),
req.spc.nconn.RemoteAddr(),
err)
continue
}
case <-sp.ctx.Done():
break outer
}
}
sp.ctxCancel()
sp.conf.Node.apiMasterClient.UnregisterService( //nolint:errcheck
sp.conf.Node.absoluteTopicName(sp.conf.Name),
sp.conf.Node.tcprosURL())
sp.clientsWg.Wait()
select {
case sp.conf.Node.serviceProviderClose <- sp:
case <-sp.conf.Node.ctx.Done():
}
}