-
Notifications
You must be signed in to change notification settings - Fork 1
/
jam-session.go
342 lines (281 loc) · 8.33 KB
/
jam-session.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
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/creativenucleus/bytejammer/config"
"github.com/creativenucleus/bytejammer/machines"
"github.com/creativenucleus/bytejammer/util"
"github.com/google/uuid"
)
type JamSession struct {
port int
// Our friendly name...
name string
// The slug we can use to saved this config to disk...
slug string
startTime time.Time
// The connections, machines, and the connections between them
manager *JamSessionManager
chLog chan string
}
func startJamSession(port int, name string, chLog chan string) (*JamSession, error) {
nameSlug := util.GetSlug(name)
if nameSlug == "" {
return nil, errors.New("Invalid session name - unable to make slug")
}
now := time.Now()
js := JamSession{
port: port,
name: name,
slug: fmt.Sprintf("%s_%s", util.GetSlugFromTime(now), nameSlug),
startTime: now,
manager: makeJamSessionManager(),
chLog: chLog,
}
basePath := js.getBasePath()
chLog <- fmt.Sprintf("Creating directory: %s", basePath)
err := util.EnsurePathExists(basePath, os.ModePerm)
if err != nil {
return nil, err
}
config := getJamSessionConfig(js)
configData, err := json.Marshal(config)
if err != nil {
return nil, err
}
err = os.WriteFile(fmt.Sprintf("%s/config.json", basePath), configData, 0644)
if err != nil {
return nil, err
}
err = js.start()
if err != nil {
return nil, err
}
return &js, nil
}
func (js *JamSession) start() error {
js.chLog <- fmt.Sprintf("Starting server on port %d", js.port)
webServer := &http.Server{
Addr: fmt.Sprintf(":%d", js.port),
ReadHeaderTimeout: 3 * time.Second,
}
http.HandleFunc("/ws-bytejam", js.wsBytejam())
// #TODO: catch an error!
go webServer.ListenAndServe()
return nil
}
func (js *JamSession) wsBytejam() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
js.chLog <- fmt.Sprintf("Client connected")
conn, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
js.chLog <- fmt.Sprintf("Client connected but couldn't upgrade: %s", err)
return
}
defer conn.Close()
/*
var m *machines.Machine
if s.broadcaster != nil {
tic, err = machines.NewNusanServerTic(slug, broadcaster)
if err != nil {
log.Print("ERR new TIC:", err)
return
}
log.Print("not implemented")
return
} else {
m, err = machines.LaunchMachine("TIC-80", true, false, true)
if err != nil {
log.Print("ERR new TIC:", err)
return
}
s.chLog <- "TIC-80 Launched"
}
defer m.Shutdown()
*/
jsConn := NewJamSessionConnection(conn)
js.manager.registerConn(jsConn)
go jsConn.runServerWsConnRead(js)
go jsConn.runServerWsConnWrite(js)
// #TODO: send the server status
// hp.sendServerStatus(true)
// #TODO: handle exit
for {
select {
case <-jsConn.signalKick:
// #TODO: Close down read and write channels
fmt.Println("KICKED")
return
}
}
}
}
func (js *JamSession) stop() error {
fmt.Println("JamSession->stop not yet implemented")
return nil
}
func (js *JamSession) getBasePath() string {
return fmt.Sprintf("%sserver-data/%s", config.WORK_DIR, js.slug)
}
func (js *JamSession) getStatus() MsgServerStatus {
msg := MsgServerStatus{
Type: "server-status",
}
for _, jc := range js.manager.conns {
status := "waiting"
machineUuid := ""
machine := js.manager.getMachineForConn(jc)
if machine != nil {
status = fmt.Sprintf("Connected: %s", machine.MachineName)
machineUuid = machine.Uuid.String()
}
msg.Data.Clients = append(msg.Data.Clients, struct {
Uuid string
DisplayName string
ShortUuid string
Status string
MachineUuid string
LastPingTime string
}{
Uuid: jc.connUuid.String(),
DisplayName: jc.identity.displayName,
ShortUuid: jc.getIdentityShortUuid(),
Status: status,
MachineUuid: machineUuid,
LastPingTime: time.Now().Format(time.RFC3339),
})
}
for _, m := range js.manager.machines {
name := "(unassigned)"
clientUuid := ""
client := js.manager.getConnForMachine(m)
if client != nil {
name = client.identity.displayName
clientUuid = client.connUuid.String()
}
msg.Data.Machines = append(msg.Data.Machines, struct {
Uuid string
MachineName string
ProcessID int
Platform string
Status string
ClientUuid string
JammerDisplayName string
LastSnapshotTime string
}{
Uuid: m.Uuid.String(),
MachineName: m.MachineName,
ProcessID: m.Tic.GetProcessID(),
Platform: m.Platform,
Status: "running",
ClientUuid: clientUuid,
JammerDisplayName: name,
LastSnapshotTime: time.Now().Format(time.RFC3339),
})
}
return msg
}
func (js *JamSession) startMachine() (*machines.Machine, error) {
m, err := machines.LaunchMachine("TIC-80", true, true, false)
if err != nil {
return nil, err
}
js.manager.registerMachine(m)
js.chLog <- fmt.Sprintf("TIC-80 Launched: %s", m.MachineName)
return m, err
}
func (js *JamSession) startMachineForConn(connUuid uuid.UUID) (*machines.Machine, error) {
conn := js.manager.getConn(connUuid)
if conn == nil {
return nil, errors.New("Unable to find conn")
}
m, err := machines.LaunchMachine("TIC-80", true, true, false)
if err != nil {
return nil, err
}
js.manager.registerMachine(m)
js.manager.linkMachineToConn(m.Uuid, conn.connUuid)
// TODO: May have identity?
js.chLog <- fmt.Sprintf("TIC-80 Launched: %s for %s", m.MachineName, conn.connUuid)
return m, err
}
func (js *JamSession) identifyMachines() {
count := 0
for _, c := range js.manager.conns {
m := js.manager.getMachineForConn(c)
if m != nil {
err := c.sendMachineNameCode(m.MachineName)
if err != nil {
js.chLog <- fmt.Sprintln("ERR write:", err)
}
count++
}
}
js.chLog <- fmt.Sprintf("Identification sent to %d machines for 30 seconds", count)
}
func (js *JamSession) closeMachine(data DataCloseMachine) {
// #TODO: unlink and unregister!
fmt.Printf("CLOSE: %s\n", data.Uuid)
err := machines.ShutdownMachine(data.Uuid)
if err != nil {
js.chLog <- fmt.Sprintf("ERR shutdown: %s", err)
return
}
js.chLog <- fmt.Sprintf("Machine %s closed", data.Uuid)
}
func (js *JamSession) connectMachineClient(data DataConnectMachineClient) {
fmt.Printf("connect: %s to %s\n", data.ClientUuid, data.MachineUuid)
machineUuid, err := uuid.Parse(data.MachineUuid)
if err != nil {
js.chLog <- fmt.Sprintf("ERR connect: %s", err)
return
}
connUuid, err := uuid.Parse(data.ClientUuid)
if err != nil {
js.chLog <- fmt.Sprintf("ERR connect: %s", err)
return
}
machine := machines.GetMachine(machineUuid)
if machine == nil {
js.chLog <- fmt.Sprintf("ERR connect: Could not find Machine ID")
return
}
conn := js.manager.getConn(connUuid)
if conn == nil {
js.chLog <- fmt.Sprintf("ERR connect: Could not find Jammer ID")
return
}
js.manager.linkMachineToConn(machineUuid, connUuid)
js.chLog <- fmt.Sprintf("Connected %s to %s", data.ClientUuid, data.MachineUuid)
}
func (js *JamSession) disconnectMachineClient(data DataDisconnectMachineClient) {
fmt.Printf("Disconnect: %s to %s\n", data.ClientUuid, data.MachineUuid)
machineUuid, err := uuid.Parse(data.MachineUuid)
if err != nil {
js.chLog <- fmt.Sprintf("ERR connect: %s", err)
return
}
connUuid, err := uuid.Parse(data.ClientUuid)
if err != nil {
js.chLog <- fmt.Sprintf("ERR connect: %s", err)
return
}
conn := js.manager.getConn(connUuid)
if conn == nil {
js.chLog <- fmt.Sprintf("ERR connect: Could not find Jammer ID")
return
}
machine := js.manager.getMachineForConn(conn)
if machine == nil {
js.chLog <- fmt.Sprintf("ERR connect: Jammer does not have a machine")
}
if machine.Uuid != machineUuid {
js.chLog <- fmt.Sprintf("ERR connect: Jammer's machine ID does not match the requested one")
}
js.manager.unlinkMachineFromConn(machineUuid, connUuid)
js.chLog <- fmt.Sprintf("Disconnected %s from %s", data.ClientUuid, data.MachineUuid)
}