-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
324 lines (273 loc) · 7.81 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
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"bufio"
"log"
"net/http"
"sync"
"os"
"strconv"
"time"
"github.com/segmentio/ksuid"
)
type State struct {
M sync.Mutex
Rooms map[string]int
WaitingClients []string
Clients map[string]*client
}
type client struct {
ID string
LastAccess time.Time
Link string
}
type Config struct {
Key string
Addr string
StateFile string
MetricsFile string
}
var state State
var config Config
var metricsFile *os.File
func persistState() {
data, _ := json.Marshal(state.Rooms)
err := ioutil.WriteFile(config.StateFile, data, 0644)
if err != nil {
log.Printf("error writing state: %v", err)
}
}
func giveSlotToClient(url string) {
var waitingClient *client = nil
for waitingClient == nil {
if len(state.WaitingClients) == 0 {
return
}
uuid := state.WaitingClients[0]
state.WaitingClients = state.WaitingClients[1:]
waitingClient = state.Clients[uuid]
}
log.Printf("room %s reserved for %s", url, waitingClient.ID)
waitingClient.Link = url
state.Rooms[url] -= 1
}
func handleFree(w http.ResponseWriter, r *http.Request) {
state.M.Lock()
defer state.M.Unlock()
keys, present := r.URL.Query()["key"]
if !present || len(keys) != 1 || keys[0] != config.Key {
w.WriteHeader(http.StatusUnauthorized)
return
}
url := r.FormValue("url")
if url == "" {
w.WriteHeader(http.StatusInternalServerError)
return
}
count, err := strconv.Atoi(r.FormValue("count"))
if err != nil || count <= 0 {
w.WriteHeader(http.StatusInternalServerError)
return
}
state.Rooms[url] += count;
log.Printf("free %s", r.FormValue("url"))
giveSlotToClient(url)
data, _ := json.Marshal(state.Rooms)
w.Write(data)
persistState()
}
func handleDelete(w http.ResponseWriter, r *http.Request) {
state.M.Lock()
defer state.M.Unlock()
keys, present := r.URL.Query()["key"]
if !present || len(keys) != 1 || keys[0] != config.Key {
w.WriteHeader(http.StatusUnauthorized)
return
}
url := r.FormValue("url")
if url == "" {
w.WriteHeader(http.StatusInternalServerError)
return
}
delete(state.Rooms, url)
log.Printf("delete %s", r.FormValue("url"))
data, _ := json.Marshal(state.Rooms)
w.Write(data)
persistState()
}
func handleRegisterRoom(w http.ResponseWriter, r *http.Request) {
state.M.Lock()
defer state.M.Unlock()
keys, present := r.URL.Query()["key"]
if !present || len(keys) != 1 || keys[0] != config.Key {
w.WriteHeader(http.StatusUnauthorized)
return
}
url := r.FormValue("url")
if url == "" {
w.WriteHeader(http.StatusInternalServerError)
return
}
count, err := strconv.Atoi(r.FormValue("count"))
if err != nil || count <= 0 {
w.WriteHeader(http.StatusInternalServerError)
return
}
_, exists := state.Rooms[url]
if exists {
w.WriteHeader(http.StatusConflict)
return
}
state.Rooms[url] = count;
log.Printf("register %s", r.FormValue("url"))
data, _ := json.Marshal(state.Rooms)
w.Write(data)
persistState()
}
func cleanUp() {
for uuid, c := range state.Clients {
now := time.Now()
timeout, _ := time.ParseDuration("30s")
if now.Sub(c.LastAccess) > timeout {
log.Printf("Client %s too old", uuid)
// delete from client list
delete(state.Clients, uuid)
// free slot for room
if c.Link != "" {
state.Rooms[c.Link] += 1
}
// refresh queue
var newqueue []string
for _, cuuid := range state.WaitingClients {
if cuuid != uuid {
newqueue = append(newqueue, cuuid)
}
}
state.WaitingClients = newqueue
}
}
}
func findRoom(uuid string) string {
cleanUp()
var roomBest string
currentClient := state.Clients[uuid]
// uuid registered?
if currentClient == nil {
log.Printf("uuid %s not registered", uuid)
return "nouuid"
}
currentClient.LastAccess = time.Now()
// check if there is a reserved room
if currentClient.Link != "" {
log.Printf("room %s given to %s", currentClient.Link, currentClient.ID)
delete(state.Clients, uuid)
return currentClient.Link
}
// search for room with most available spots
freeCountBest := 0
for room, freeCount := range(state.Rooms) {
if freeCount < freeCountBest {
continue
}
freeCountBest = freeCount
roomBest = room
}
if freeCountBest == 0 {
position := 0
for _, id := range state.WaitingClients {
position++
if id == uuid {
break
}
}
return "wait" + strconv.Itoa(position) + " watch stream for entertainment"
}
state.Rooms[roomBest] -= 1;
log.Printf("room %s [%d] given to %s", roomBest, freeCountBest, currentClient.ID)
delete(state.Clients, uuid)
return roomBest
}
func handleRegisterClient(w http.ResponseWriter, r *http.Request) {
state.M.Lock()
defer state.M.Unlock()
uuid := ksuid.New().String()
log.Printf("uuid registered: %s", uuid)
currentClient := client{ID: uuid, LastAccess: time.Now(), Link: ""}
state.Clients[uuid] = ¤tClient
state.WaitingClients = append(state.WaitingClients, uuid)
fmt.Fprintf(metricsFile, "%d %d\n", time.Now().UnixNano(), len(state.WaitingClients))
fmt.Fprintf(w, uuid)
}
func handlePoll(w http.ResponseWriter, r *http.Request) {
state.M.Lock()
defer state.M.Unlock()
room := findRoom(r.FormValue("uuid"))
fmt.Fprintf(w, "%s", room)
persistState()
}
func handleState(w http.ResponseWriter, r *http.Request) {
state.M.Lock()
defer state.M.Unlock()
data, _ := json.Marshal(state.Rooms)
w.Write(data)
}
func main() {
configFile := "config.json"
if len(os.Args) > 1 {
configFile = os.Args[1]
}
// load config
data, err := ioutil.ReadFile(configFile)
if err != nil {
panic(err)
}
json.Unmarshal(data, &config)
// load state
data, err = ioutil.ReadFile(config.StateFile)
if err != nil && !os.IsNotExist(err) {
panic(err)
}
if data != nil {
json.Unmarshal(data, &state.Rooms)
} else {
state.Rooms = make(map[string]int)
}
state.Clients = make(map[string]*client)
metricsFile, err = os.OpenFile(config.MetricsFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatalf("error opening metrics file: %v", err)
}
defer metricsFile.Close()
buf, err := os.Open("uuids.list")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = buf.Close(); err != nil {
log.Fatal(err)
}
}()
snl := bufio.NewScanner(buf)
for snl.Scan() {
uuid := snl.Text()
currentClient := client{ID: uuid, LastAccess: time.Now(), Link: ""}
state.Clients[uuid] = ¤tClient
state.WaitingClients = append(state.WaitingClients, uuid)
log.Printf("uuid importted: %s", uuid)
}
err = snl.Err()
if err != nil {
log.Fatal(err)
}
http.Handle("/", http.FileServer(http.Dir("static")))
http.HandleFunc("/api/poll", handlePoll)
http.HandleFunc("/api/free", handleFree)
http.HandleFunc("/api/state", handleState)
http.HandleFunc("/api/delete", handleDelete)
http.HandleFunc("/api/register", handleRegisterRoom)
http.HandleFunc("/api/register_client", handleRegisterClient)
log.Printf("listening on %s", config.Addr)
http.ListenAndServe(config.Addr, nil)
}