-
Notifications
You must be signed in to change notification settings - Fork 0
/
adaptiveservice.go
439 lines (385 loc) · 11.7 KB
/
adaptiveservice.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
// Package adaptiveservice is a message oriented micro service framework.
//
// Servers define micro services identified as name of "publisher_service" and
// publish them to all available scopes:
// in same process, and further in same OS, and then further in same local
// network, and then public network where a public root registry address needs
// to be configured.
// In process and OS scope, one service name can only be announced once,
// duplicated service name is treated as error.
// In network scope, there can be multiple services with the same name,
// in this case, each service provider publishes the service "publisher_service"
// along with an unique provider ID.
//
// Clients then discover wanted micro services in a way that shortest scope comes
// first. The discover() API returns a connection channel, reading the channel the
// client will get one or more connections, with each represents a connection
// to one of the service providers providing the wanted micro service.
// The connection then can be used to send/receive messages to/from the service provider.
//
// Connections can be multiplexed on client side: NewStream() API creates a new
// context in which the messages are transferred independently from other contexts
// over the same underlying connection. The intention of the multiplexer is to have
// scalability on client side: users use this mechanism to send parallel request
// messages towards the same service provider to increase execution concurrency.
//
// For server side, the incoming messages are handled in auto-scaled worker pool,
// so the multiplexer used on client side is not needed on server side.
// Servers listen to different transports for all available scopes:
// process scope, go channels are used
// OS scope, unix domain socket is used
// network scope, tcp socket is used
//
// Messages that satisfy Handle() interface are known messages. Typically
// server defines Handle() method for every message type it can handle,
// then when the known message arrived on one of the transports it is
// listening, the message is delivered to one of the workers in which
// the message's Handle() is called.
// Clients do not define Handle() method, they just send and receive message
// in a natural synchronized fashion.
//
// Services that are behind NAT can be auto proxied by the builtin reverseProxy
// service provided by the daemon server in the local network or by the root
// registry.
package adaptiveservice
import (
"errors"
"fmt"
"io"
"math/rand"
"os"
"os/signal"
"reflect"
"strings"
"sync"
"syscall"
"time"
"github.com/niubaoshu/gotiny"
"github.com/timandy/routine"
)
// Scope is publishing and discovering scope
type Scope uint16
const (
// BuiltinPublisher name
BuiltinPublisher = "builtin"
// OK can be returned by known messages as reply to indicate
// everything is OK. Client should use type int to receive it.
OK = 0
asTmpDir = "/tmp/adaptiveservice"
timeMicro = "15:04:05.000000"
dateTimeMicro = "2006-01-02 15:04:05.000000"
timeNano = "15:04:05.000000000"
dateTimeNano = "2006-01-02 15:04:05.000000000"
)
const (
// ScopeProcess is a scope where publishing and discovering services
// only happen in same process.
ScopeProcess Scope = 1 << iota
// ScopeOS is a scope where publishing and discovering services
// only happen in same OS.
ScopeOS
// ScopeLAN is a scope where publishing and discovering services
// only happen in same local network.
ScopeLAN
// ScopeWAN is a scope where publishing and discovering services
// only happen in same reachable public network.
ScopeWAN
// ScopeNetwork is a shortcut for ScopeLAN and ScopeWAN
ScopeNetwork = ScopeLAN | ScopeWAN
// ScopeAll includes all scopes, this is the default value if
// no other Scope specified.
ScopeAll = ScopeProcess | ScopeOS | ScopeLAN | ScopeWAN
)
var (
// ErrServiceNotReachable is an error where the service exists
// but somehow can not be reached, e.g. the service is behind NAT.
ErrServiceNotReachable = errors.New("service not reachable")
// ErrConnReset is an error where the connection was forced closed
// by peer.
ErrConnReset = errors.New("connection reset by peer")
// ErrServerClosed is an error where the server was closed by signal.
ErrServerClosed = errors.New("server closed by signal")
// ErrRecvTimeout is an error where no data was received within
// specified duration.
ErrRecvTimeout = errors.New("receive timeout")
)
type errServiceNotFound struct {
publisher string
service string
}
func (e errServiceNotFound) Error() string {
return "service not found: " + e.publisher + "_" + e.service
}
// ErrServiceNotFound returns an error that no wanted service was found
func ErrServiceNotFound(publisher, service string) error {
return errServiceNotFound{publisher, service}
}
type streamIO struct {
stream Stream
rbuff []byte
}
func (sio *streamIO) Read(p []byte) (n int, err error) {
if len(sio.rbuff) == 0 {
if err := sio.stream.Recv(&sio.rbuff); err != nil {
return 0, err
}
}
n = copy(p, sio.rbuff)
sio.rbuff = sio.rbuff[n:]
return
}
func (sio *streamIO) Write(p []byte) (n int, err error) {
if err := sio.stream.Send(p); err != nil {
return 0, err
}
return len(p), nil
}
func (sio *streamIO) Close() error {
return sio.stream.Send(io.EOF)
}
// NewStreamIO wraps the stream to be an io.ReadWriteCloser in which
// Read() is a Stream.Recv() that only receives []byte,
// Write is a Stream.Send() that only sends []byte.
// Use Read() Write() in pair on the client/server peer, don't mix use
// them with Send() or Recv().
func NewStreamIO(stream Stream) io.ReadWriteCloser {
return &streamIO{stream: stream}
}
// Logger is the logger interface.
type Logger interface {
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
// LoggerNull prints no log
type LoggerNull struct{}
// Debugf is Debugf
func (LoggerNull) Debugf(format string, args ...interface{}) {}
// Infof is Infof
func (LoggerNull) Infof(format string, args ...interface{}) {}
// Warnf is Warnf
func (LoggerNull) Warnf(format string, args ...interface{}) {}
// Errorf is Errorf
func (LoggerNull) Errorf(format string, args ...interface{}) {}
// LoggerAll prints all regardless of loglevel
type LoggerAll struct{}
// Debugf is Debugf
func (LoggerAll) Debugf(format string, args ...interface{}) {
h := fmt.Sprintf("%v <<%v>> ", time.Now().Format(timeNano), routine.Goid())
fmt.Printf(h+"[AS DEBUG] "+format+"\n", args...)
}
// Infof is Infof
func (LoggerAll) Infof(format string, args ...interface{}) {
h := fmt.Sprintf("%v <<%v>> ", time.Now().Format(timeNano), routine.Goid())
fmt.Printf(h+"[AS INFO] "+format+"\n", args...)
}
// Warnf is Warnf
func (LoggerAll) Warnf(format string, args ...interface{}) {
h := fmt.Sprintf("%v <<%v>> ", time.Now().Format(timeNano), routine.Goid())
fmt.Printf(h+"[AS WARN] "+format+"\n", args...)
}
// Errorf is Errorf
func (LoggerAll) Errorf(format string, args ...interface{}) {
h := fmt.Sprintf("%v <<%v>> ", time.Now().Format(timeNano), routine.Goid())
fmt.Printf(h+"[AS ERROR] "+format+"\n", args...)
}
type errorRecover interface {
Error() error
String() string
Recover() (recovered bool) // return true if the error has been recovered.
}
type noError struct{}
func (e noError) Error() error {
return nil
}
func (e noError) String() string {
return "no error"
}
func (e noError) Recover() bool {
return false
}
type unrecoverableError struct {
err error
}
func (e unrecoverableError) Error() error {
return e.err
}
func (e unrecoverableError) String() string {
return "unrecoverable error"
}
func (e unrecoverableError) Recover() bool {
return false
}
type customErrorRecover struct {
err error
str string
recoverFunc func() bool
}
func (e customErrorRecover) Error() error {
return e.err
}
func (e customErrorRecover) String() string {
return e.str
}
func (e customErrorRecover) Recover() bool {
return e.recoverFunc()
}
var (
sigCleaner struct {
sync.Mutex
closers []closer
}
sigOnce sync.Once
)
type closer interface {
close()
}
// allows io.Closer to be closer
type ioCloser func() error
func (c ioCloser) close() {
c()
}
func addSigCloser(c closer) {
sigCleaner.Lock()
sigCleaner.closers = append(sigCleaner.closers, c)
sigCleaner.Unlock()
}
func initSigCleaner(lg Logger) {
sigOnce.Do(func() {
// handle signal
signal.Ignore(syscall.SIGHUP)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigChan
lg.Warnf("signal: %s", sig.String())
sigCleaner.Lock()
for _, c := range sigCleaner.closers {
c.close()
}
sigCleaner.Unlock()
}()
})
}
var name2Type = map[string]reflect.Type{}
// RegisterType registers the type infomation to encoding sub system.
func RegisterType(i interface{}) {
//gotiny.Register(i)
rt := reflect.TypeOf(i)
name := rt.String()
gotiny.RegisterName(name, rt)
name2Type[name] = rt
}
// RegisterTypeNoPanic is like RegisterType but recovers from panic.
func RegisterTypeNoPanic(i interface{}) (err error) {
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("%v", p)
}
}()
RegisterType(i)
return
}
// GetKnownMessageTypes returns all KnownMessage types
func GetKnownMessageTypes() []string {
var registered []string
for name, rt := range name2Type {
if m, ok := rt.MethodByName("Handle"); ok {
if strings.Contains(fmt.Sprintf("%v", m), "adaptiveservice.ContextStream") {
registered = append(registered, name)
}
}
}
return registered
}
// GetRegisteredTypeByName returns a reflect.Type if it has been registered
func GetRegisteredTypeByName(name string) reflect.Type {
if rt, ok := name2Type[name]; ok {
return rt
}
return nil
}
// test if pattern matches str
// "*" matches all
// "*bar*" matches bar, foobar, or foobarabc
// "foo*abc*" matches foobarabc, foobarabc123, or fooabc
func wildcardMatch(pattern, str string) bool {
if len(pattern) == 0 {
return false
}
strs := strings.Split(pattern, "*")
var pos, index int
if index = strings.Index(str, strs[0]); index != 0 {
return false
}
end := strs[len(strs)-1]
if index = strings.LastIndex(str, end); index+len(end) != len(str) {
return false
}
for i, substr := range strs {
if i == 0 || i == len(strs)-1 || len(substr) == 0 {
continue
}
index = strings.Index(str[pos:], substr)
if index == -1 {
return false
}
pos += index + len(substr)
}
return true
}
func init() {
rand.Seed(time.Now().UnixNano())
// basic types
RegisterType(int(0))
RegisterType(int8(0))
RegisterType(int16(0))
RegisterType(int32(0))
RegisterType(int64(0))
RegisterType(uint(0))
RegisterType(uint8(0))
RegisterType(uint16(0))
RegisterType(uint32(0))
RegisterType(uint64(0))
RegisterType(float32(0))
RegisterType(float64(0))
RegisterType(complex64(0i))
RegisterType(complex128(0i))
RegisterType(uintptr(0))
RegisterType(false)
RegisterType("")
//RegisterType([]byte(nil))
RegisterType([]int(nil))
RegisterType([]int8(nil))
RegisterType([]int16(nil))
RegisterType([]int32(nil))
RegisterType([]int64(nil))
RegisterType([]uint(nil))
RegisterType([]uint8(nil))
RegisterType([]uint16(nil))
RegisterType([]uint32(nil))
RegisterType([]uint64(nil))
RegisterType([]float32(nil))
RegisterType([]float64(nil))
RegisterType([]complex64(nil))
RegisterType([]complex128(nil))
RegisterType([]uintptr(nil))
RegisterType([]bool(nil))
RegisterType([]string(nil))
// error types
RegisterType(errors.New(""))
RegisterType(fmt.Errorf("%w", io.EOF))
}
// Dummy annotation marking that the value x escapes,
// for use in cases where the reflect code is so clever that
// the compiler cannot follow.
func escapes(x interface{}) {
if dummy.b {
dummy.x = x
}
}
var dummy struct {
b bool
x interface{}
}