/
server.go
366 lines (335 loc) · 9.6 KB
/
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
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
package main
// #cgo LDFLAGS: -L ./lib -lmonkeyS
// #include "./lib/core.h"
// #include <stdlib.h>
import "C"
import (
"unsafe"
"fmt"
"net"
"strings"
"./tcp"
"./convert"
"reflect"
"./minheap"
"strconv"
"flag"
"sync"
)
////////////////////////////////////// 库级锁 ////////////////////////////////////////////////////////////////
var mutex map[C.Database]*sync.RWMutex
////////////////////////////////////// MinHeap ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// command类型 用于解析处理各种数据库命令 //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
var (
acceptedCmd = []string{"set","get","delete","remove","createdb","switchdb","dropdb",/*"push","pop","destroy",*/"listdb"}
port = flag.String("p","1517","侦听端口号")
)
type command []byte
func (cmd command) Set(db **C.Database) []byte {
//锁并发
_,ok := mutex[**db];
if !ok {
mutex[**db] = new(sync.RWMutex)
}
mutex[**db].Lock()
defer mutex[**db].Unlock()
response := []byte{}
key,next := convert.ParseUntil(cmd,' ',4)
value,_ := convert.ParseUntil(cmd,0,next+1)
//fmt.Println("set ",key,value)
r := C.Set(&(*db).tIndex,(*C.char)(convert.Bytes2C(key)),(convert.Bytes2C(value)))
for i := 0;;i++ {
response = append(response,byte(r.msg[i]))
if response[i] == 0 { break; }
}
return response
}
func (cmd command) Get(db **C.Database) []byte {
//锁并发
_,ok := mutex[**db];
if !ok {
mutex[**db] = new(sync.RWMutex)
}
mutex[**db].RLock()
defer mutex[**db].RUnlock()
response := []byte{}
key,_ := convert.ParseUntil(cmd,0,4)
r := C.Get(&(*db).tIndex,(*C.char)(convert.Bytes2C(key)))
if int(r.code) == 0 {
for i := 0;;i++ {
response = append(response,byte(*(*C.char)(unsafe.Pointer((uintptr(r.pData)+uintptr(i))))))
if response[i] == 0 { break; }
}
}else {
}
return response
}
func (cmd command) Delete(db **C.Database) []byte {
return cmd.Remove(db)
}
func (cmd command) Remove(db **C.Database) []byte {
//锁并发
_,ok := mutex[**db];
if !ok {
mutex[**db] = new(sync.RWMutex)
}
mutex[**db].Lock()
defer mutex[**db].Unlock()
response := []byte{}
key,_ := convert.ParseUntil(cmd,0,7)
r := C.Delete(&(*db).tIndex,(*C.char)(convert.Bytes2C(key)))
for i := 0;;i++ {
response = append(response,byte(r.msg[i]))
if response[i] == 0 { break; }
}
return response
}
func (cmd command) Createdb(db **C.Database) []byte {
response := []byte{}
key,_ := convert.ParseUntil(cmd,0,9)
d := C.CreateDB((*C.char)(convert.Bytes2C(key)))
if d != nil {
*db = d
response = []byte("Already exist,switched\n")
}else {
response = []byte("Created\n")
}
return response
}
func (cmd command) Switchdb(db **C.Database) []byte {
response := []byte{}
key,_ := convert.ParseUntil(cmd,0,9)
d := C.SwitchDB((*C.char)(convert.Bytes2C(key)))
if d != nil {
*db = d
response = []byte("ok\n")
}else {
response = []byte("fail\n")
}
return response
}
func (cmd command) Dropdb(db **C.Database) []byte {
//锁并发
_,ok := mutex[**db];
if !ok {
mutex[**db] = new(sync.RWMutex)
}
mutex[**db].Lock()
defer mutex[**db].Unlock()
response := []byte{}
key,_ := convert.ParseUntil(cmd,0,7)
*db = C.DropDB((*C.char)(convert.Bytes2C(key)))
return response
}
func (cmd command) Listdb(db **C.Database) []byte {
response := []byte{}
r := C.ListDB()
for i := 0;i < 1024;i++ {
b := byte(*(*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(r))+uintptr(i))))
response = append(response,b)
if(b == 0){ break; }
}
C.free(unsafe.Pointer(r))
return response
}
func (cmd command) Push(db **C.Database) []byte {
var response []byte
key,next := convert.ParseUntil(cmd,' ',5)
key2,next := convert.ParseUntil(cmd,' ',next+1)
value,_ := convert.ParseUntil(cmd,0,next+1)
var i int
btnode := C.BTree_search((*db).tIndex,(C.KeyType)(C.GetHash((*C.char)(convert.Bytes2C(key)))),(*C.int)(unsafe.Pointer(&i)))
if uintptr(unsafe.Pointer(btnode)) != uintptr(0) { //B树上有此堆
heap := (*minheap.MinHeap)(btnode.pRecord[i]) //BUG GO GC 会回收掉上次的内存
k,_ := strconv.Atoi(string(key2))
v,_ := strconv.Atoi(string(value))
heap.Push(minheap.Pair{Key:uint32(k),Value:uint32(v)})
response = []byte("Pushed")
}else { //建一个新的堆
heap := minheap.New()
C.BTree_insert(&(*db).tIndex, (C.KeyType)(C.GetHash((*C.char)(convert.Bytes2C(key)))), unsafe.Pointer(&heap))
k,_ := strconv.Atoi(string(key2))
v,_ := strconv.Atoi(string(value))
heap.Push(minheap.Pair{Key:uint32(k),Value:uint32(v)})
response = []byte("Created and pushed")
}
return response
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
func initDB() { //初始化数据库
str0 := "monkey"
C.CreateDB((*C.char)(convert.String2C(str0))) //创建基础数据库
str0 = "config" //配置数据库
C.CreateDB((*C.char)(convert.String2C(str0)))
key := "passwd" //初始密码
data := "monkey"
db := C.SwitchDB((*C.char)(convert.String2C(str0)))
C.Set(&(db.tIndex),(*C.char)(convert.String2C(key)),(convert.String2C(data)))
}
func listen() {
servicePort := ":"+*port
tcpAddr,err := net.ResolveTCPAddr("tcp4",servicePort)
if err != nil {
panic(err)
}
l,err := net.ListenTCP("tcp",tcpAddr) //侦听TCP
if err != nil {
panic(err)
}
fmt.Println("Server Started on "+*port+"!")
for{
conn,err := l.AcceptTCP()
conn.SetKeepAlive(true)
conn.SetNoDelay(true)
if err != nil {
panic(err)
}
s := tcp.TCPSession{Conn:conn}
s.Init()
go Handler(&s)
}
}
func main() {
flag.Parse()
//初始化锁
mutex = make(map[C.Database]*sync.RWMutex)
initDB()
listen()
}
func auth(s *tcp.TCPSession) bool {
buff := s.ReadMessage()
params := strings.Split(string(buff)," ")
str0 := "config"
db := C.SwitchDB((*C.char)(convert.String2C(str0)))
if params[0] != "auth" {
s.SendMessage([]byte("Please auth first!"))
return false
}
r := C.Get(&(db.tIndex),(*C.char)(convert.String2C("passwd")))
if int(r.code) == 0 {
passwd := []byte{}
for i := 0;;i++ {
passwd = append(passwd,byte(*(*C.char)(unsafe.Pointer((uintptr(r.pData)+uintptr(i))))))
if passwd[i] == 0 {
break
}
}
if convert.Equal(passwd,[]byte(params[1])) {
s.SendMessage([]byte("Auth success"))
return true
} else {
s.SendMessage([]byte("Auth fail"))
return false
}
}else {
s.SendMessage([]byte("Auth success"))
return true
}
}
func Handler(s *tcp.TCPSession) {
fmt.Println("Run a new handler to client.")
for !auth(s){
}
str := "monkey"
db := C.SwitchDB((*C.char)(convert.String2C(str)))//环境变量-当前数据库
for {
if s.Closed {
fmt.Println("Close a client.")
break
}
buff := s.ReadMessage()
// if err != nil {
// conn.Close()
// break
// }
if len(buff) == 0 {
fmt.Println("Close a client.")
return
}
//commands := bytes.Split(buff,[]byte{0})
//for _,cmd := range commands {
TranslateMessage2(s,&db,buff)
//} //解析消息
}
}
func TranslateMessage2(s *tcp.TCPSession,db **C.Database,message []byte) {
com := command(message)
//fmt.Println("处理:",string(message))
response := []byte{}
for _,cmd := range acceptedCmd {
if convert.StartBy(message,cmd) {
result := reflect.ValueOf(com).MethodByName(convert.UpperHead(cmd)).Call([]reflect.Value{reflect.ValueOf(db)})
response = result[0].Interface().([]byte)
break
}
}
s.SendMessage(response)
}
////////////////////////////////////////Dumplated//////////////////////////////////////////////////////////////////////////
func TranslateMessage(s *tcp.TCPSession,db **C.Database,message []byte) {
command := string(message)
params := strings.Split(command," ")
//fmt.Println(params)
response := []byte{}
if params[0] == "set" {
r := C.Set(&(*db).tIndex,(*C.char)(convert.String2C(params[1])),(convert.String2C(params[2])))
for i := 0;;i++ {
response = append(response,byte(r.msg[i]))
if response[i] == 0 { break; }
}
}else if params[0] == "get" {
r := C.Get(&(*db).tIndex,(*C.char)(convert.String2C(params[1])))
// for i := 0;;i++ {
// response = append(response,byte(r.msg[i]))
// if response[i] == 0 { break; }
// }
if int(r.code) == 0 {
for i := 0;;i++ {
response = append(response,byte(*(*C.char)(unsafe.Pointer((uintptr(r.pData)+uintptr(i))))))
if response[i] == 0 { break; }
}
}else {
// for i := 0;;i++ {
// response = append(response,byte(r.msg[i]))
// if response[i] == 0 { break; }
// }
}
}else if params[0] == "delete" || params[0] == "remove" {
r := C.Delete(&(*db).tIndex,(*C.char)(convert.String2C(params[1])))
for i := 0;;i++ {
response = append(response,byte(r.msg[i]))
if response[i] == 0 { break; }
}
}else if params[0] == "createdb" {
d := C.CreateDB((*C.char)(convert.String2C(params[1])))
if d != nil {
*db = d
response = []byte("Already exist,switched\n")
}else {
response = []byte("Created\n")
}
}else if params[0] == "switchdb" {
d := C.SwitchDB((*C.char)(convert.String2C(params[1])))
if d != nil {
*db = d
response = []byte("ok\n")
}else {
response = []byte("fail\n")
}
}else if params[0] == "dropdb" {
*db = C.DropDB((*C.char)(convert.String2C(params[1])))
}else if strings.EqualFold("listdb",params[0]) {
r := C.ListDB()
for i := 0;i < 1024;i++ {
b := byte(*(*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(r))+uintptr(i))))
response = append(response,b)
if(b == 0){ break; }
}
C.free(unsafe.Pointer(r))
}else {
//fmt.Println("unkown command:",params[0])
}
s.SendMessage(response)
}