-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
222 lines (201 loc) · 4.64 KB
/
main.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
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
const debugging = false
// max bytes to allow this server to use
const maxMemUsage = 1000000000
// max lifetime of a cache key
const maxExpireSec = 86400 * 7
type memval struct {
value string
expires time.Time
}
// IN-MEMORY CACHE
// USAGE:
// SET key expires_in_sec value
// GET key
// DEL key
// QUIT
// EXAMPLE:
// SET fav 60 chocolate
// GET fav
// QUIT
var cache = make(map[string]memval)
var mutex = &sync.Mutex{}
var shutdown = false
func main() {
lf, lferr := os.OpenFile("gomemcache.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if lferr != nil {
log.Fatalln(lferr)
}
logger := log.New(lf, "", log.LstdFlags)
li, err := net.Listen("tcp", ":8080")
if err != nil {
logger.Fatalln(err)
}
defer li.Close()
defer func() { logger.Println("Shuttin' her down"); shutdown = true }()
logger.Println("Server started")
go cleaner(logger)
for {
conn, err := li.Accept()
if err != nil {
logger.Println(err)
continue
}
go handle(conn, logger)
}
}
func cleaner(logger *log.Logger) {
if shutdown {
logger.Println("Shutdown detected (1)")
return
}
time.Sleep(time.Second * 60)
if shutdown {
logger.Println("Shutdown detected (2)")
return
}
n := time.Now()
logger.Println("Locking the cache while checking for expired keys")
dcount := 0
mutex.Lock() // need to lock it while we iterate
for k, v := range cache {
if v.expires.Before(n) {
logger.Println("Cache key expired: " + k)
delete(cache, k)
dcount++
}
}
logger.Println("Unlocking cache")
mutex.Unlock()
if dcount > 1 || !memUsageOk(logger) {
// force garbage collection
runtime.GC()
}
cleaner(logger)
}
func handle(conn net.Conn, logger *log.Logger) {
defer conn.Close()
ip := conn.RemoteAddr()
debug(logger, ip, "Connection accepted")
fmt.Fprintf(conn, "HI %s\r\n", ip.String())
scanner := bufio.NewScanner(conn)
closeconn := false
for scanner.Scan() {
ln := scanner.Text()
fs := strings.SplitN(ln, " ", 3)
if len(fs) < 1 {
continue
}
cmd := strings.ToUpper(fs[0])
switch cmd {
case "GET":
debug(logger, ip, "Handling command: "+cmd)
if len(fs) < 2 {
fmt.Fprintf(conn, "Invalid arguments for GET\r\n")
break
}
k := fs[1]
if v, ok := cache[k]; ok {
mutex.Lock()
if v.expires.Before(time.Now()) {
warn(logger, ip, "Key expired: "+k)
delete(cache, k)
fmt.Fprintf(conn, "\r\n")
mutex.Unlock()
break
}
fmt.Fprintf(conn, "%s\r\n", v.value)
mutex.Unlock()
} else {
warn(logger, ip, "Key does not exist: "+k)
fmt.Fprintf(conn, "\r\n")
}
case "SET":
debug(logger, ip, "Handling command: "+cmd)
if !memUsageOk(logger) {
warn(logger, ip, "SET command denied - memory full")
fmt.Fprintln(conn, "MEMFULL")
break
}
if len(fs) < 3 {
fmt.Fprintf(conn, "Invalid arguments for SET\r\n")
break
}
timeAndValue := strings.SplitN(fs[2], " ", 2)
if len(timeAndValue) < 2 {
fmt.Fprintf(conn, "Invalid arguments for SET\r\n")
break
}
k := fs[1]
e := timeAndValue[0]
v := timeAndValue[1]
ei := 300 // expires in 5 minutes by default
if i, err := strconv.Atoi(e); err == nil {
ei = i
if ei == 0 || ei > maxExpireSec {
ei = maxExpireSec // 30 days max
warn(logger, ip, fmt.Sprintf("Changing key '%s' expiration for %d sec", k, ei))
}
}
now := time.Now()
exptime := now.Add(time.Second * time.Duration(ei))
mutex.Lock()
cache[k] = memval{value: v, expires: exptime}
mutex.Unlock()
fmt.Fprintf(conn, "OK\r\n")
case "DEL":
debug(logger, ip, "Handling command: "+cmd)
k := fs[1]
mutex.Lock()
delete(cache, k)
mutex.Unlock()
fmt.Fprintf(conn, "OK\r\n")
case "QUIT", "END", "EXIT":
debug(logger, ip, "Handling command: "+cmd)
fmt.Fprintln(conn, "BYE")
closeconn = true
default:
debug(logger, ip, "Handling command: "+cmd)
fmt.Fprintf(conn, "INVALID COMMAND %s\r\n", fs[0])
}
if closeconn {
break
}
}
debug(logger, ip, "Ending connection")
}
func memUsageOk(logger *log.Logger) bool {
m := runtime.MemStats{}
runtime.ReadMemStats(&m)
if m.HeapInuse > maxMemUsage*0.75 {
logger.Printf("[warn] Memory usage - %+v", m)
if m.HeapInuse > maxMemUsage {
logger.Printf("[CRITICAL] Using too much system memory: %d bytes", m.HeapInuse)
return false
}
}
return true
}
func logIt(l *log.Logger, ip net.Addr, m string) {
l.Printf("[client: %s] %s", ip.String(), m)
}
func debug(l *log.Logger, ip net.Addr, m string) {
if debugging {
logIt(l, ip, "[debug] "+m)
}
}
func warn(l *log.Logger, ip net.Addr, m string) {
logIt(l, ip, "[warn] "+m)
}