-
Notifications
You must be signed in to change notification settings - Fork 0
/
raftstorage_server.go
74 lines (61 loc) · 1.44 KB
/
raftstorage_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
package storage
import (
"context"
"fmt"
"log"
"net/http"
"time"
"go.etcd.io/etcd/etcdserver/api/rafthttp"
"go.etcd.io/etcd/pkg/types"
"go.uber.org/zap"
)
type RaftStorageServer struct {
server *http.Server
transport *rafthttp.Transport
rs *RaftStorage
done chan struct{}
}
func NewRaftStorageServer(bindAddr string, bindPort int, clusterId uint64, rs *RaftStorage) (*RaftStorageServer, error) {
raftTransport := &rafthttp.Transport{
Logger: zap.NewExample(),
ID: types.ID(rs.NodeId),
ClusterID: types.ID(clusterId),
Raft: rs,
ErrorC: make(chan error, 1),
}
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", bindAddr, bindPort),
Handler: raftTransport.Handler(),
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
}
s := &RaftStorageServer{
transport: raftTransport,
server: server,
done: make(chan struct{}),
}
return s, nil
}
func (t *RaftStorageServer) Start() error {
err := t.transport.Start()
if err != nil {
return err
}
go func() {
for err := range t.transport.ErrorC {
log.Printf("raft transport error: %v", err)
}
}()
go t.server.ListenAndServe()
return nil
}
func (t *RaftStorageServer) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := t.server.Shutdown(ctx)
t.transport.Stop()
return err
}
func (s *RaftStorageServer) Storage() *RaftStorage {
return s.rs
}