-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache-server.go
More file actions
254 lines (218 loc) · 6.82 KB
/
Copy pathcache-server.go
File metadata and controls
254 lines (218 loc) · 6.82 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
package main
import (
"fmt"
"log"
"net"
"flag"
"time"
"context"
"net/http"
"hash/fnv"
"encoding/json"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "SDCS/kvrpc"
)
func keyHashFunc(key string) int {
hashFunc := fnv.New32a()
hashFunc.Write([]byte(key))
return int(hashFunc.Sum32() % 3)
}
var (
// id
id = flag.Int("id", 0, "The server id")
my_id int
// rpc port
rpc_port string
// data to store json
data map[string]json.RawMessage
// rpc client
client [3]pb.ServiceKVClient
)
type server struct {
pb.UnimplementedServiceKVServer
}
func (s *server) PostKV(ctx context.Context, in *pb.PostRequest) (*pb.PostReply, error) {
key := in.GetKey()
json := in.GetJson()
// log.Printf("(%v) Post Received Key: %v Json: %v", rpc_port, key, string(json))
data[key] = json
return &pb.PostReply{Success: true}, nil
}
func (s *server) GetKV(ctx context.Context, in *pb.GetRequest) (*pb.GetReply, error) {
key := in.GetKey()
// log.Printf("(%v) Get Received Key: %v", rpc_port, key)
json, exists := data[key]
if !exists {
return &pb.GetReply{Success: false, Json: nil}, nil
}
return &pb.GetReply{Success: true, Json: json}, nil
}
func (s *server) DeleteKV(ctx context.Context, in *pb.DeleteRequest) (*pb.DeleteReply, error) {
key := in.GetKey()
// log.Printf("(%v) Delete Received Key: %v", rpc_port, key)
_, exists := data[key]
if !exists {
return &pb.DeleteReply{Success: false}, nil
}
delete(data, key)
return &pb.DeleteReply{Success: true}, nil
}
func postHandler(w http.ResponseWriter, r *http.Request) {
var temp map[string]interface{}
var unique_key string
// 读取请求体并将其存储为 json.RawMessage
var rawMessage json.RawMessage
err := json.NewDecoder(r.Body).Decode(&rawMessage)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 将 json.RawMessage 解码为一个 map
err = json.Unmarshal(rawMessage, &temp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 获取第一个键
for key := range temp {
unique_key = key
break
}
target_id := keyHashFunc(unique_key)
// fmt.Printf("POST target_id is %d\n", target_id)
if target_id == my_id {
data[unique_key] = rawMessage
} else {
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err := client[target_id].PostKV(ctx, &pb.PostRequest{Key: unique_key, Json: rawMessage})
if err != nil {
log.Fatalf("could not post kv: %v", err)
}
}
// fmt.Fprintf(w, "Received POST with key:%v; json: %+v\n", unique_key, string(rawMessage))
// fmt.Fprintf(w, "%+v\n", string(rawMessage))
}
func getHandler(w http.ResponseWriter, key string) {
target_id := keyHashFunc(key)
var json json.RawMessage
// fmt.Printf("GET target_id is %d\n", target_id)
if target_id == my_id {
var exists bool
json, exists = data[key]
if !exists {
// 如果没有匹配的key,返回404
// http.Error(w, "Not found key", http.StatusNotFound)
http.Error(w, "not found", http.StatusNotFound)
return
}
} else {
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := client[target_id].GetKV(ctx, &pb.GetRequest{Key: key})
if err != nil || !r.Success {
// http.Error(w, "Not found key", http.StatusNotFound)
http.Error(w, "not found", http.StatusNotFound)
return
}
json = r.GetJson()
}
// fmt.Fprintf(w, "Received GET return %+v\n", string(json))
fmt.Fprintf(w, "%+v\n", string(json))
}
func deleteHandler(w http.ResponseWriter, key string) {
target_id := keyHashFunc(key)
// fmt.Printf("DELETE target_id is %d\n", target_id)
if target_id == my_id {
_, exists := data[key]
if !exists {
fmt.Fprintf(w, "%d\n", 0)
return
}
delete(data, key)
} else {
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := client[target_id].DeleteKV(ctx, &pb.DeleteRequest{Key: key})
if err != nil || !r.Success {
fmt.Fprintf(w, "%d\n", 0)
return
}
}
fmt.Fprintf(w, "%d\n", 1)
// fmt.Fprintf(w, "Received DELETE request for key: %v\n", key)
}
func handler(w http.ResponseWriter, r *http.Request) {
// 根据请求路径拆分URL
path := r.URL.Path
// 根路径(处理 POST 请求)
if r.Method == "POST" && path == "/" {
postHandler(w, r)
return
}
parts := strings.Split(strings.Trim(path, "/"), "/")
// 处理 GET /{key} 和 DELETE /{key}
if len(parts) == 1 {
key := parts[0]
switch r.Method {
case "GET":
getHandler(w, key)
case "DELETE":
deleteHandler(w, key)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
return
}
// 如果没有匹配的路由,返回404
http.Error(w, "Not found", http.StatusNotFound)
}
func main() {
flag.Parse()
my_id = *id
rpc_port = "50051"
// Initialize data map.
data = make(map[string]json.RawMessage)
// 创建 FNV-1a 哈希
go func(){
// Start KV RPC server.
lis, err := net.Listen("tcp", fmt.Sprintf(":%s", rpc_port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterServiceKVServer(s, &server{})
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
// Sleep for 1s
time.Sleep(1000 * time.Millisecond)
// Start KV RPC client.
for i := 0; i <= 2; i++ {
if i == my_id {
client[i] = nil
continue
}
// Set up a connection to the server.
conn, err := grpc.Dial("cache_server_" + fmt.Sprintf("%d:", i) + rpc_port, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
client[i] = pb.NewServiceKVClient(conn)
}
// Start HTTP service.
http.HandleFunc("/", handler)
fmt.Println("Starting server at :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Error starting server:", err)
}
}