-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathgrpc_func.go
More file actions
355 lines (326 loc) · 9.89 KB
/
grpc_func.go
File metadata and controls
355 lines (326 loc) · 9.89 KB
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
/*
* Copyright 2024 Function Stream Org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package grpc
import (
"fmt"
"github.com/functionstream/function-stream/common"
"github.com/functionstream/function-stream/fs/api"
"github.com/functionstream/function-stream/fs/contube"
"github.com/functionstream/function-stream/fs/runtime/grpc/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"log/slog"
"net"
"sync"
"sync/atomic"
)
type GRPCFuncRuntime struct {
api.FunctionRuntime
Name string
instance api.FunctionInstance
ctx context.Context
status *proto.FunctionStatus
readyOnce sync.Once
readyCh chan error
input chan contube.Record
output chan contube.Record
stopFunc func()
processing atomic.Bool
log *slog.Logger
}
type Status int32
const (
NotReady Status = iota
Ready
)
// FSSReconcileServer is the struct that implements the FSServiceServer interface.
type FSSReconcileServer struct {
proto.UnimplementedFSReconcileServer
ctx context.Context
readyCh chan struct{}
connected sync.Once
reconcile chan *proto.FunctionStatus
functions map[string]*GRPCFuncRuntime
functionsMu sync.Mutex
status int32
log *slog.Logger
}
func NewFSReconcile(ctx context.Context) *FSSReconcileServer {
return &FSSReconcileServer{
ctx: ctx,
readyCh: make(chan struct{}),
reconcile: make(chan *proto.FunctionStatus, 100),
functions: make(map[string]*GRPCFuncRuntime),
log: slog.With(slog.String("component", "grpc-reconcile-server")),
}
}
func (s *FSSReconcileServer) WaitForReady() <-chan struct{} {
return s.readyCh
}
func (s *FSSReconcileServer) Reconcile(_ *proto.ConnectRequest, stream proto.FSReconcile_ReconcileServer) error {
s.connected.Do(func() {
close(s.readyCh)
})
if Status(atomic.LoadInt32(&s.status)) == Ready {
return fmt.Errorf("there is already a reconcile stream")
}
s.log.InfoContext(s.ctx, "reconcile client connected")
defer func() {
atomic.StoreInt32(&s.status, int32(NotReady))
s.log.InfoContext(s.ctx, "grpc reconcile stream closed")
}()
// Sync all exiting function status to the newly connected reconcile client
s.functionsMu.Lock()
statusList := make([]*proto.FunctionStatus, 0, len(s.functions))
for _, v := range s.functions {
statusList = append(statusList, v.status)
}
s.functionsMu.Unlock()
for _, v := range statusList {
err := stream.Send(v)
if err != nil {
s.log.ErrorContext(stream.Context(), "failed to send status update", slog.Any("status", v))
// Continue to send the next status update.
}
}
for {
select {
case status := <-s.reconcile:
s.log.DebugContext(s.ctx, "sending status update", slog.Any("status", status))
err := stream.Send(status)
if err != nil {
s.log.ErrorContext(stream.Context(), "failed to send status update", slog.Any("status", status))
// Continue to send the next status update.
}
case <-stream.Context().Done():
return nil
case <-s.ctx.Done():
return nil
}
}
}
func (s *FSSReconcileServer) UpdateStatus(_ context.Context, newStatus *proto.FunctionStatus) (*proto.Response, error) {
s.log.DebugContext(s.ctx, "received status update", slog.Any("status", newStatus))
s.functionsMu.Lock()
instance, ok := s.functions[newStatus.Name]
if !ok {
s.functionsMu.Unlock()
s.log.ErrorContext(s.ctx, "receive non-exist function status update", slog.Any("name", newStatus.Name))
return &proto.Response{
Status: proto.Response_ERROR,
Message: common.OptionalStr("function not found"),
}, nil
}
s.functionsMu.Unlock()
instance.Update(newStatus)
return &proto.Response{
Status: proto.Response_OK,
}, nil
}
func (s *FSSReconcileServer) NewFunctionRuntime(instance api.FunctionInstance) (api.FunctionRuntime, error) {
name := instance.Definition().Name
log := instance.Logger().With(
slog.String("component", "grpc-runtime"),
)
go func() {
<-instance.Context().Done()
s.removeFunction(name)
}()
runtime := &GRPCFuncRuntime{
Name: name,
instance: instance,
readyCh: make(chan error),
input: make(chan contube.Record),
output: make(chan contube.Record),
status: &proto.FunctionStatus{
Name: name,
Status: proto.FunctionStatus_CREATING,
},
ctx: instance.Context(),
stopFunc: func() { // TODO: remove it, we should use instance.ctx to control the lifecycle
s.removeFunction(name)
},
log: log,
}
{
s.functionsMu.Lock()
defer s.functionsMu.Unlock()
if _, ok := s.functions[name]; ok {
return nil, fmt.Errorf("function already exists")
}
s.functions[name] = runtime
}
s.reconcile <- runtime.status
log.InfoContext(runtime.ctx, "Creating GRPC function runtime")
return runtime, nil
}
func (s *FSSReconcileServer) getFunc(name string) (*GRPCFuncRuntime, error) {
s.functionsMu.Lock()
defer s.functionsMu.Unlock()
instance, ok := s.functions[name]
if !ok {
return nil, fmt.Errorf("function not found")
}
return instance, nil
}
func (s *FSSReconcileServer) removeFunction(name string) {
s.functionsMu.Lock()
defer s.functionsMu.Unlock()
instance, ok := s.functions[name]
if !ok {
return
}
s.log.InfoContext(instance.ctx, "Removing function", slog.Any("name", name))
delete(s.functions, name)
}
func isFinalStatus(status proto.FunctionStatus_Status) bool {
return status == proto.FunctionStatus_FAILED || status == proto.FunctionStatus_DELETED
}
func (f *GRPCFuncRuntime) Update(new *proto.FunctionStatus) {
if f.status.Status == proto.FunctionStatus_CREATING && isFinalStatus(new.Status) {
f.readyCh <- fmt.Errorf("function failed to start")
}
if f.status.Status != new.Status {
f.log.InfoContext(f.ctx, "Function status update", slog.Any("new_status", new.Status), slog.Any("old_status", f.status.Status))
}
f.status = new
}
func (f *GRPCFuncRuntime) WaitForReady() <-chan error {
return f.readyCh
}
// Stop stops the function runtime and remove it
// It is different from the ctx.Cancel. It will make sure the runtime has been deleted after this method returns.
func (f *GRPCFuncRuntime) Stop() {
f.log.InfoContext(f.ctx, "Stopping function runtime")
f.stopFunc()
}
func (f *GRPCFuncRuntime) Call(event contube.Record) (contube.Record, error) {
f.input <- event
out := <-f.output
f.processing.Store(false)
return out, nil
}
type FunctionServerImpl struct {
proto.UnimplementedFunctionServer
reconcileSvr *FSSReconcileServer
}
func NewFunctionServerImpl(s *FSSReconcileServer) *FunctionServerImpl {
return &FunctionServerImpl{
reconcileSvr: s,
}
}
func (f *FunctionServerImpl) Process(req *proto.FunctionProcessRequest, stream proto.Function_ProcessServer) error {
runtime, err := f.reconcileSvr.getFunc(req.Name)
if err != nil {
return err
}
log := runtime.log
log.InfoContext(stream.Context(), "Start processing events using GRPC")
runtime.readyOnce.Do(func() {
runtime.readyCh <- err
})
errCh := make(chan error)
defer func() {
if runtime.processing.Load() {
runtime.output <- nil
runtime.processing.Store(false)
}
}()
logCounter := common.LogCounter()
for {
select {
case event := <-runtime.input:
log.DebugContext(stream.Context(), "sending event", slog.Any("count", logCounter))
runtime.processing.Store(true)
err := stream.Send(&proto.Event{Payload: string(event.GetPayload())}) // TODO: Change payload type to bytes
if err != nil {
log.Error("failed to send event", slog.Any("error", err))
return err
}
case <-stream.Context().Done():
return nil
case <-runtime.ctx.Done():
return nil
case e := <-errCh:
return e
}
}
}
func (f *FunctionServerImpl) getFunctionRuntime(ctx context.Context) (*GRPCFuncRuntime, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, fmt.Errorf("failed to get metadata")
}
if _, ok := md["name"]; !ok || len(md["name"]) == 0 {
return nil, fmt.Errorf("the metadata doesn't contain the function name")
}
return f.reconcileSvr.getFunc(md["name"][0])
}
func (f *FunctionServerImpl) Output(ctx context.Context, e *proto.Event) (*proto.Response, error) {
runtime, err := f.getFunctionRuntime(ctx)
if err != nil {
return nil, err
}
runtime.log.DebugContext(ctx, "received event")
runtime.output <- contube.NewRecordImpl([]byte(e.Payload), func() {})
return &proto.Response{
Status: proto.Response_OK,
}, nil
}
func (f *FunctionServerImpl) PutState(ctx context.Context, req *proto.PutStateRequest) (*proto.Response, error) {
runtime, err := f.getFunctionRuntime(ctx)
if err != nil {
return nil, err
}
runtime.log.DebugContext(ctx, "put state")
err = runtime.instance.FunctionContext().PutState(req.Key, req.Value)
if err != nil {
return nil, err
}
return &proto.Response{
Status: proto.Response_OK,
}, nil
}
func (f *FunctionServerImpl) GetState(ctx context.Context, req *proto.GetStateRequest) (*proto.GetStateResponse, error) {
runtime, err := f.getFunctionRuntime(ctx)
if err != nil {
return nil, err
}
runtime.log.DebugContext(ctx, "get state")
v, err := runtime.instance.FunctionContext().GetState(req.Key)
if err != nil {
return nil, err
}
return &proto.GetStateResponse{
Value: v,
}, nil
}
func StartGRPCServer(f *FSSReconcileServer, addr string) (*grpc.Server, error) {
lis, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
s := grpc.NewServer()
proto.RegisterFSReconcileServer(s, f)
proto.RegisterFunctionServer(s, NewFunctionServerImpl(f))
go func() {
if err := s.Serve(lis); err != nil {
slog.Error("failed to serve", slog.Any("error", err))
}
}()
return s, nil
}