-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_svc.go
76 lines (61 loc) · 1.23 KB
/
node_svc.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
package dlm
import (
"context"
"errors"
"log/slog"
"net"
"net/rpc"
)
// Start start the node and its RPC service
func (n *Node) Start() error {
n.mu.Lock()
defer n.mu.Unlock()
l, err := net.Listen("tcp", n.addr)
if err != nil {
return err
}
_, err = n.db.ExecContext(context.Background(), CreateTableLease)
if err != nil {
return err
}
_, err = n.db.ExecContext(context.Background(), CreateTableTopic)
if err != nil {
return err
}
n.server = rpc.NewServer()
n.listener = l
go n.waitRequest()
n.stopped = false
n.logger.Info("dlm: node is running")
return n.server.RegisterName("dlm", n)
}
// Stop stop the node and its RPC service
func (n *Node) Stop() {
n.mu.Lock()
defer n.mu.Unlock()
n.listener.Close()
n.stopped = true
n.logger.Info("dlm: node is stopped")
}
func (n *Node) isStopped() bool {
n.mu.RLock()
defer n.mu.RUnlock()
return n.stopped
}
func (n *Node) waitRequest() {
for {
conn, err := n.listener.Accept()
if n.isStopped() {
return
}
if err != nil {
// listener is closed
if errors.Is(err, net.ErrClosed) {
return
}
n.logger.Warn("dlm: wait request", slog.String("err", err.Error()), slog.String("addr", n.addr))
continue
}
go n.server.ServeConn(conn)
}
}