-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
108 lines (91 loc) · 2.42 KB
/
http.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
package main
import (
"encoding/json"
"fmt"
"gframework/log"
"net/http"
"sync/atomic"
"time"
"github.com/hashicorp/raft"
)
type HttpServer struct {
raft *raftNodeInfo
enableWrite int32
}
func NewHttpServer(ctx *CachedContext) *HttpServer {
server := &HttpServer{
raft: ctx.raft,
enableWrite: 0,
}
http.HandleFunc("/set", server.doSet)
http.HandleFunc("/get", server.doGet)
http.HandleFunc("/join", server.doJoin)
return server
}
func (h *HttpServer) checkPermission() bool {
return atomic.LoadInt32(&h.enableWrite) == 1
}
func (h *HttpServer) setLeaderFlag(flag bool) {
if flag {
atomic.StoreInt32(&h.enableWrite, 1)
} else {
atomic.StoreInt32(&h.enableWrite, 0)
}
}
func (h *HttpServer) doGet(w http.ResponseWriter, r *http.Request) {
vars := r.URL.Query()
key := vars.Get("key")
if key == "" {
log.Error("doGet() error, get nil key")
fmt.Fprint(w, "error key\n")
return
}
ret := h.raft.fsm.cm.Get(key)
fmt.Fprintf(w, "%s\n", ret)
}
// doSet saves data to cache, only raft master node provides this api
func (h *HttpServer) doSet(w http.ResponseWriter, r *http.Request) {
if !h.checkPermission() {
fmt.Fprint(w, "not leader\n")
return
}
vars := r.URL.Query()
key := vars.Get("key")
value := vars.Get("value")
if key == "" || value == "" {
log.Error("doSet() error, get nil key or nil value")
fmt.Fprint(w, "param error\n")
return
}
event := logEntryData{Key: key, Value: value}
eventBytes, err := json.Marshal(event)
if err != nil {
log.Errorf("json.Marshal failed, err:%v", err)
fmt.Fprint(w, "internal error\n")
return
}
applyFuture := h.raft.raft.Apply(eventBytes, 5*time.Second)
if err = applyFuture.Error(); err != nil {
log.Errorf("raft.Apply failed:%v", err)
fmt.Fprint(w, "internal error\n")
return
}
fmt.Fprintf(w, "ok\n")
}
// doJoin handles joining cluster request
func (h *HttpServer) doJoin(w http.ResponseWriter, r *http.Request) {
vars := r.URL.Query()
peerAddress := vars.Get("peerAddress")
if peerAddress == "" {
log.Error("invalid PeerAddress")
fmt.Fprint(w, "invalid peerAddress\n")
return
}
addPeerFuture := h.raft.raft.AddVoter(raft.ServerID(peerAddress), raft.ServerAddress(peerAddress), 0, 0)
if err := addPeerFuture.Error(); err != nil {
log.Errorf("Error joining peer to raft, peer address:%s, err:%v, code:%d", peerAddress, err, http.StatusInternalServerError)
fmt.Fprint(w, "internal error\n")
return
}
fmt.Fprint(w, "ok")
}