-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
405 lines (341 loc) · 8.15 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
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"regexp"
"strconv"
"sync"
"time"
"github.com/aaron-seo/proxy-herd/mooserver"
)
// Google API KEY
var GOOGLE_API_KEY string
// a string to string map of server names and their ports on SEASnet
var ports = map[string]string{
"Juzang": "10371",
"Bernard": "10372",
"Jaquez": "10373",
"Johnson": "10374",
"Clark": "10375",
}
// slice of servers that this instance will talk to (bidirectionally)
var neighbors []string
// this specific server's ID, to be parsed in command line
var serverID string
func init() {
flag.StringVar(&serverID, "id", "default", "label to identify server")
}
func main() {
flag.Parse()
// get key through environment variables
GOOGLE_API_KEY = os.Getenv("GOOGLE_API_KEY")
// logging
err := os.Mkdir("logs", 0755)
f, err := os.OpenFile("logs/"+serverID+".log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err)
}
defer f.Close()
log.SetOutput(f)
// set neighbors according to spec
switch serverID {
case "Juzang":
neighbors = []string{"Clark", "Bernard", "Johnson"}
break
case "Bernard":
neighbors = []string{"Juzang", "Jaquez", "Johnson"}
break
case "Jaquez":
neighbors = []string{"Clark", "Bernard", "Johnson"}
break
case "Johnson":
neighbors = []string{"Bernard", "Jaquez"}
break
case "Clark":
neighbors = []string{"Jaquez", "Juzang"}
break
default:
panic("invalid server id")
}
mux := mooserver.NewServeMux()
// for client-server
mux.HandleFunc("IAMAT", HandleIAMAT)
mux.HandleFunc("WHATSAT", HandleWHATSAT)
// for server-server
mux.HandleFunc("AT", HandleAT)
log.Printf("server %s listening on port %s", serverID, ports[serverID])
log.Fatal(mooserver.ListenAndServe(":"+ports[serverID], mux))
}
// Handles IAMAT commands
func HandleIAMAT(w mooserver.ResponseWriter, r *mooserver.Request) {
log.Printf("%s HandleIAMAT: ", serverID)
// validate requested command
if len(r.Command.Fields) != 4 {
fmt.Fprintf(w, "? %s", r.Command.Raw)
return
}
iamat := parseIAMAT(r.Command.Fields)
log.Printf("%s HandleIAMAT: %+v", serverID, iamat)
timeNow := float64(time.Now().UnixNano()) / float64(time.Second)
timeDelta := timeNow - iamat.timestamp
loc := location{
serverID,
timeDelta,
iamat.client,
iamat.latitude,
iamat.longitude,
iamat.timestamp,
}
storeAndPropagate(loc)
log.Printf("%s HandleIAMAT: AT %s %f %s %f %f %f", serverID,
serverID,
timeDelta,
iamat.client,
iamat.latitude,
iamat.longitude,
iamat.timestamp)
if iamat.latitude >= 0 {
fmt.Fprintf(w, "AT %s %f %s +%f%f %f",
serverID,
timeDelta,
iamat.client,
iamat.latitude,
iamat.longitude,
iamat.timestamp)
} else {
fmt.Fprintf(w, "AT %s %f %s %f%f %f",
serverID,
timeDelta,
iamat.client,
iamat.latitude,
iamat.longitude,
iamat.timestamp)
}
}
// handles WHATSAT command
func HandleWHATSAT(w mooserver.ResponseWriter, r *mooserver.Request) {
log.Printf("%s WHATSAT", serverID)
// validate requested command
if len(r.Command.Fields) != 4 {
fmt.Fprintf(w, "? %s", r.Command.Raw)
return
}
locations.mu.Lock()
defer locations.mu.Unlock()
whatsat := parseWHATSAT(r.Command.Fields)
log.Printf("%s WHATSAT: %+v", serverID, whatsat)
loc := locations.lns[whatsat.client]
query := fmt.Sprintf("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=%f&key=%s",
loc.latitude,
loc.longitude,
whatsat.radius*1000,
GOOGLE_API_KEY)
resp, err := http.Get(query)
if err != nil {
log.Fatal(err)
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Fatal(err)
}
var bodyJSON map[string]interface{}
err = json.Unmarshal(body, &bodyJSON)
if err != nil {
log.Fatal(err)
}
// get bounded results
tmpResult := make([]interface{}, whatsat.bound)
for k, v := range bodyJSON {
switch k {
case "results":
switch vv := v.(type) {
case []interface{}:
for i, u := range vv {
if i >= whatsat.bound {
break
}
tmpResult[i] = u
}
}
}
}
bodyJSON["results"] = tmpResult
parsedJSON, _ := json.MarshalIndent(bodyJSON, "", "\t")
log.Printf("%s WHATSAT: AT %s %f %s %f %f %f\n%s", serverID,
loc.serverID,
loc.timeDelta,
loc.client,
loc.latitude,
loc.longitude,
loc.timestamp,
string(parsedJSON))
if loc.latitude >= 0 {
fmt.Fprintf(w, "AT %s %f %s +%f%f %f\n%s",
loc.serverID,
loc.timeDelta,
loc.client,
loc.latitude,
loc.longitude,
loc.timestamp,
string(parsedJSON))
} else {
fmt.Fprintf(w, "AT %s %f %s %f%f %f\n%s",
loc.serverID,
loc.timeDelta,
loc.client,
loc.latitude,
loc.longitude,
loc.timestamp,
string(parsedJSON))
}
}
// handles AT command
func HandleAT(w mooserver.ResponseWriter, r *mooserver.Request) {
log.Printf("%s AT", serverID)
// validate requested command
if len(r.Command.Fields) != 6 {
fmt.Fprintf(w, "? %s", r.Command.Raw)
return
}
at := parseAT(r.Command.Fields)
log.Printf("%s AT: %+v", serverID, at)
loc := location{
at.serverID,
at.timeDelta,
at.client,
at.latitude,
at.longitude,
at.timestamp,
}
storeAndPropagate(loc)
}
// helper functions to parse commands into respective data structures
func parseIAMAT(fields []string) IAMAT {
latitude, longitude := parseCoordinate(fields[2])
timestamp, _ := strconv.ParseFloat(fields[3], 64)
parsed := IAMAT{
client: fields[1],
latitude: latitude,
longitude: longitude,
timestamp: timestamp,
}
return parsed
}
func parseWHATSAT(fields []string) WHATSAT {
radius, _ := strconv.ParseFloat(fields[2], 64)
bound, _ := strconv.Atoi(fields[3])
parsed := WHATSAT{
client: fields[1],
radius: radius,
bound: bound,
}
return parsed
}
func parseAT(fields []string) AT {
latitude, longitude := parseCoordinate(fields[4])
timeDelta, _ := strconv.ParseFloat(fields[2], 64)
timestamp, _ := strconv.ParseFloat(fields[5], 64)
parsed := AT{
fields[1],
timeDelta,
fields[3],
latitude,
longitude,
timestamp,
}
return parsed
}
type IAMAT struct {
client string
latitude float64
longitude float64
timestamp float64
}
type WHATSAT struct {
client string
radius float64
bound int
}
type AT struct {
serverID string
timeDelta float64
client string
latitude float64
longitude float64
timestamp float64
}
// helper function for ISO coordinates
func parseCoordinate(coord string) (float64, float64) {
ISOCoord := regexp.MustCompile(`((\+|-)\d+\.?\d*){2}`)
result := ISOCoord.FindString(coord)
INDCoord := regexp.MustCompile(`(\+|-)\d+\.?\d*`)
pair := INDCoord.FindAllString(result, 2)
latitude, _ := strconv.ParseFloat(pair[0], 64)
longitude, _ := strconv.ParseFloat(pair[1], 64)
return latitude, longitude
}
// for storing locations in server
type location struct {
serverID string
timeDelta float64
client string
latitude float64
longitude float64
timestamp float64
}
type locationsStore struct {
mu sync.RWMutex
lns map[string]location
}
var locations locationsStore
func storeAndPropagate(loc location) {
if ok := check(loc); ok {
store(loc)
propagate(loc)
} else {
//log.Println("circular")
}
}
// checks circular cycling
func check(loc location) bool {
locations.mu.Lock()
defer locations.mu.Unlock()
if _, ok := locations.lns[loc.client]; ok {
if locations.lns[loc.client].timestamp == loc.timestamp {
return false
}
}
return true
}
func store(loc location) {
locations.mu.Lock()
defer locations.mu.Unlock()
if locations.lns == nil {
locations.lns = make(map[string]location)
}
locations.lns[loc.client] = loc
}
func propagate(loc location) {
for _, neighbor := range neighbors {
//log.Println("neighbor " + neighbor)
conn, err := net.Dial("tcp", "localhost:"+ports[neighbor])
if err != nil {
log.Printf("%s Error dialing tcp to %s", serverID, neighbor)
return
}
defer conn.Close()
if loc.latitude >= 0 {
//log.Printf("IAMAT %s +%f%f %f", loc.client, loc.latitude, loc.longitude, loc.timestamp)
fmt.Fprintf(conn, "AT %s %f %s +%f%f %f", loc.serverID, loc.timeDelta, loc.client, loc.latitude, loc.longitude, loc.timestamp)
} else {
fmt.Fprintf(conn, "AT %s %f %s %f%f %f", loc.serverID, loc.timeDelta, loc.client, loc.latitude, loc.longitude, loc.timestamp)
}
}
}