/
register.go
363 lines (333 loc) · 10.2 KB
/
register.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
// Copyright (c) 2016 IBM Corp. All rights reserved.
// Use of this source code is governed by the Apache License,
// Version 2.0, a copy of which can be found in the LICENSE file.
// Room registration.
package main
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"strings"
"time"
)
const (
// The maximum number of query results (previously-registered rooms)
// that we will accept when asking for all rooms registered by our
// current userid. See rememberMyRooms().
MaxRegQueries = 2048
)
type ConnDetails struct {
Type string `json:"type,omitempty"`
Target string `json:"target,omitempty"`
}
type DoorGroup struct {
North string `json:"n,omitempty"`
South string `json:"s,omitempty"`
East string `json:"e,omitempty"`
West string `json:"w,omitempty"`
// Up is allowed, but is currently ignored.
Up string `json:"u,omitempty"`
// Down is allowed, but is currently ignored
Down string `json:"d,omitempty"`
}
type RoomRegistrationReq struct {
Name string `json:"name,omitempty"`
FullName string `json:"fullName,omitempty"`
ConnectionDetails ConnDetails `json:"connectionDetails,omitempty"`
Doors DoorGroup `json:"doors,omitempty"`
}
type RoomRegistrationResp struct {
Id string `json:"_id,omitempty"`
Rev string `json:"_rev,omitempty"`
Owner string `json:"owner,omitempty"`
Info RoomRegistrationReq `json:"info,omitempty"`
Type string `json:"type,omitempty"`
}
// Registers our room with the GameOn! server, with retries on failure.
func registerWithRetries(client *http.Client) (e error) {
locus := "REG_W_RETRIES"
checkpoint(locus, fmt.Sprintf("retries=%d secondsBetween=%d", config.retries, config.secondsBetween))
for i := 0; i < config.retries; i++ {
checkpoint(locus, fmt.Sprintf("Begin attempt %d of %d",
i+1, config.retries))
e = register(client)
if e == nil {
checkpoint(locus, "Registration was successful.")
rememberMyRooms(client)
return
}
checkpoint(locus, fmt.Sprintf("sleeping %d seconds.", config.secondsBetween))
if i+1 < config.retries {
time.Sleep(time.Duration(config.secondsBetween) * time.Second)
}
}
checkpoint(locus, "Registration failed.")
e = RegError{fmt.Sprintf("Timed out. Last error: %s", e.Error())}
return
}
// Registers our room with the game-on server if the room is not
// already registered.
func register(client *http.Client) (err error) {
locus := "REG"
checkpoint(locus, "Begin")
var registered bool
registered, err = checkForPriorRegistration(client)
if err != nil {
checkpoint(locus, fmt.Sprintf("err=%s", err.Error()))
return
}
if registered {
checkpoint(locus, fmt.Sprintf("WasAlreadyRegistered %s", config.roomName))
return
}
checkpoint(locus, "WeNeedToRegister")
err = registerOurRoom(client)
if err == nil {
checkpoint(locus, fmt.Sprintf("Registered %s", config.roomName))
} else {
checkpoint(locus, fmt.Sprintf("RegistrationFailed err=%s", err.Error()))
}
return
}
func checkForPriorRegistration(client *http.Client) (registered bool, err error) {
locus := "REG.CHECKPRIOR"
checkpoint(locus, "Begin")
queryParams := fmt.Sprintf("name=%s&owner=%s", config.roomName, config.id)
u := fmt.Sprintf("http://%s/map/v1/sites?%s",
config.gameonAddr,
queryParams)
fmt.Println(u)
if config.debug {
checkpoint(locus, fmt.Sprintf("GET.URL %s", u))
}
req, err := http.NewRequest("GET", u, nil)
if err != nil {
checkpoint(locus, fmt.Sprintf("NewRequest.Error err=%s", err.Error()))
return
}
resp, err := client.Do(req)
if err != nil {
checkpoint(locus, fmt.Sprintf("Get.Error err=%s", err.Error()))
return
}
body, err := extractBody(resp)
if err != nil {
checkpoint(locus, fmt.Sprintf("Body.Error err=%s", err.Error()))
return
}
switch resp.StatusCode {
case http.StatusOK:
checkpoint(locus, "AlreadyRegistered")
registered = true
traceResponseBody(locus, resp, body)
if config.debug {
// We expect a one element array from our query.
// Do not propagate any errors from this debug logging.
var regResp [1]RoomRegistrationResp
e := json.Unmarshal([]byte(body), ®Resp)
if e != nil {
log.Printf("%s: JSON unmarshalling error: %s\n",
locus, e.Error())
log.Printf("%s : Offending JSON: %s\n", locus, body)
return
}
rememberedRegistration.Id = regResp[0].Id
printRoomRegistrationResp(locus, ®Resp[0])
}
return
case http.StatusNoContent:
checkpoint(locus, "NotCurrentlyRegistered")
traceResponseBody(locus, resp, body)
return
default:
checkpoint(locus, "UnsupportedStatusCode")
printResponseBody(locus, resp, body)
return
}
}
func registerOurRoom(client *http.Client) (err error) {
locus := "REG.REGROOM"
checkpoint(locus, "Begin")
var registration string
registration, err = genRegistration()
if err != nil {
log.Printf("\nREG.REGROOM.InternalError\n")
log.Printf("Internal registration error: %s\n", err.Error())
return
}
u := fmt.Sprintf("%s://%s/map/v1/sites", config.protocol, config.gameonAddr)
if config.debug {
log.Printf("\nREG.POST URL: %s\n", u)
log.Println("----- registration json begin -----")
log.Println(registration)
log.Println("----- registration json end -----")
}
req, err := http.NewRequest("POST", u, strings.NewReader(registration))
if err != nil {
checkpoint(locus, fmt.Sprintf("NewRequest.Error err=%s", err.Error()))
return
}
addAuthenticationHeaders(req, registration)
resp, err := client.Do(req)
if err != nil {
checkpoint(locus, fmt.Sprintf("Post.Error err=%s", err.Error()))
return
}
body, err := extractBody(resp)
if err != nil {
checkpoint(locus, fmt.Sprintf("Body.Error err=%s", err.Error()))
return
}
checkpoint(locus, fmt.Sprintf("Status=%s", resp.Status))
switch resp.StatusCode {
case http.StatusCreated:
checkpoint(locus, "Registered")
traceResponseBody(locus, resp, body)
err = rememberRegistration(resp, body)
return
case http.StatusConflict:
err = RegError{fmt.Sprintf("Bad status: %s", resp.Status)}
checkpoint(locus, fmt.Sprintf("Internal Error. Attempt to reregister. Status=%s", resp.Status))
printResponseBody(locus, resp, body)
return
default:
err = RegError{fmt.Sprintf("Unhandled Status: %s", resp.Status)}
checkpoint(locus, fmt.Sprintf("Unhandled Status=%s", resp.Status))
printResponseBody(locus, resp, body)
return
}
}
func printRoomRegistrationResp(locus string, r *RoomRegistrationResp) {
j, err := json.MarshalIndent(r, "", " ")
if err == nil {
log.Printf("\n%s\n%s\n", locus, string(j))
}
}
// Generate a JSON string containing our registration info.
func genRegistration() (rs string, err error) {
var reg RoomRegistrationReq
reg.Name = config.roomName
reg.FullName = config.roomName
// Door descriptions are collected from an inside-looking-out
// perspective, but Game On! wants a description from the
// connecting room's point of view. So, our commandline
// North is what GameOn! wants for the South.
reg.Doors.North = config.south
reg.Doors.South = config.north
reg.Doors.East = config.west
reg.Doors.West = config.east
reg.Doors.Up = config.down
reg.Doors.Down = config.up
reg.ConnectionDetails.Type = "websocket"
reg.ConnectionDetails.Target = fmt.Sprintf("ws://%s:%d",
config.callbackAddr, config.callbackPort)
j, err := json.MarshalIndent(reg, "", " ")
if err != nil {
return
}
rs = string(j)
return
}
// Conditionally print an http.Response body string
// if config.debug is true.
func traceResponseBody(locus string, r *http.Response, body string) {
if config.debug {
printResponseBody(locus, r, body)
}
}
// Unconditionally print an http.Response body string.
func printResponseBody(locus string, r *http.Response, body string) {
log.Printf("\n%s.RESP.StatusCode=%s\n", locus, r.Status)
if r.StatusCode == http.StatusNotFound {
// Avoid the noise.
return
}
log.Printf("%s.RESP.Body='%s'\n", locus, body)
}
// We stash our room registration response in rememberedRegistration
// so that we can use it later if we choose to do so.
var rememberedRegistration RoomRegistrationResp
// Remember our registration data in case we chose to use it later.
func rememberRegistration(r *http.Response, body string) (err error) {
locus := "REG.REMEMBER"
var rememberedRegistration RoomRegistrationResp
err = json.Unmarshal([]byte(body), &rememberedRegistration)
if err != nil {
log.Printf("rememberRegistration : A JSON unmarshalling error occured: %s\n",
err.Error())
log.Printf("rememberRegistration :Offending JSON: %s\n", body)
return
}
if config.debug {
printRoomRegistrationResp(locus, &rememberedRegistration)
}
return
}
// Returns the body string from an http.Response. This can
// only be called once as the body is closed after reading
// its contents.
func extractBody(r *http.Response) (body string, e error) {
defer r.Body.Close()
b, e := ioutil.ReadAll(r.Body)
if e == nil {
body = string(b)
}
return
}
type RoomQueryResp struct {
Id string `json:"_id,omitempty"`
Owner string `json:"owner,omitempty"`
Info RoomRegistrationReq `json:"info,omitempty"`
}
var MyRooms map[string]string
func rememberMyRooms(client *http.Client) (err error) {
locus := "REG.LISTMYROOMS"
MyRooms = make(map[string]string)
u := fmt.Sprintf("%s://%s/map/v1/sites?owner=%s",
config.protocol, config.gameonAddr, config.id)
checkpoint(locus, u)
req, err := http.NewRequest("GET", u, nil)
if err != nil {
checkpoint(locus, fmt.Sprintf("NewRequest.Error err=%s", err.Error()))
return
}
addAuthenticationHeaders(req, "")
resp, err := client.Do(req)
if err != nil {
checkpoint(locus, fmt.Sprintf("Get.Error err=%s", err.Error()))
return
}
body, err := extractBody(resp)
if err != nil {
checkpoint(locus, fmt.Sprintf("Body.Error err=%s", err.Error()))
return
}
traceResponseBody(locus, resp, body)
switch resp.StatusCode {
case http.StatusOK:
var qr [MaxRegQueries]RoomQueryResp
e := json.Unmarshal([]byte(body), &qr)
if e != nil {
log.Printf("%s: JSON unmarshalling error: %s\n",
locus, e.Error())
log.Printf("%s : Offending JSON: %s\n", locus, body)
return
}
for _, r := range qr {
if len(r.Id) > 0 {
MyRooms[r.Id] = r.Info.FullName
}
}
if config.debug {
for k, v := range MyRooms {
log.Printf("%s --> %s\n", k, v)
}
}
return
default:
checkpoint(locus, "FAILED.")
}
return
}