-
Notifications
You must be signed in to change notification settings - Fork 100
/
operator.go
610 lines (565 loc) · 17.5 KB
/
operator.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package operator
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
apiv1 "github.com/google/android-cuttlefish/frontend/src/liboperator/api/v1"
"github.com/gorilla/mux"
gopb "github.com/google/android-cuttlefish/frontend/src/liboperator/protobuf"
grpcpb "github.com/google/android-cuttlefish/frontend/src/liboperator/protobuf"
emptypb "google.golang.org/protobuf/types/known/emptypb"
)
func createUnixSocketEndpoint(path string) (*net.UnixListener, error) {
if err := os.RemoveAll(path); err != nil {
return nil, fmt.Errorf("Failed to clean previous socket: %w", err)
}
addr, err := net.ResolveUnixAddr("unixpacket", path)
if err != nil {
// Returns a loop function that will immediately return an error when invoked
return nil, fmt.Errorf("Failed to create unix address from path: %w", err)
}
sock, err := net.ListenUnix("unixpacket", addr)
if err != nil {
return nil, fmt.Errorf("Failed to create unix socket: %w", err)
}
// Make sure the socket is only accessible by owner and group
if err := os.Chmod(path, 0770); err != nil {
// This shouldn't happen since the creation of the socket just succeeded
log.Println("Failed to change permissions on socket file: ", err)
}
return sock, err
}
// Sets up a unix socket for devices to connect to and returns a function that listens on the
// socket until an error occurs.
func SetupDeviceEndpoint(pool *DevicePool, config apiv1.InfraConfig, path string) (func() error, error) {
sock, err := createUnixSocketEndpoint(path)
if err != nil {
return nil, err
}
log.Println("Device endpoint created")
// Serve the register_device endpoint in a background thread
return func() error {
defer sock.Close()
for {
c, err := sock.AcceptUnix()
if err != nil {
return err
}
go deviceEndpoint(NewJSONUnix(c), pool, config)
}
}, nil
}
// Sets up a unix socket for server control and returns a function that listens on the socket
// until an error occurs.
func SetupControlEndpoint(pool *DevicePool, path string) (func() error, error) {
sock, err := createUnixSocketEndpoint(path)
if err != nil {
return nil, err
}
log.Println("Control endpoint created")
// Serve the register_device endpoint in a background thread
return func() error {
defer sock.Close()
for {
c, err := sock.AcceptUnix()
if err != nil {
return err
}
go controlEndpoint(NewJSONUnix(c), pool)
}
}, nil
}
// Creates a router with handlers for the following endpoints:
// GET /infra_config
// GET /groups
// GET /devices
// GET /devices?groupId={groupId}
// GET /devices/{deviceId}
// GET /devices/{deviceId}/files/{path}
// GET /devices/{deviceId}/services
// GET /devices/{deviceId}/services/{serviceName}
// GET /devices/{deviceId}/services/{serviceName}/{methodName}
// POST /devices/{deviceId}/services/{serviceName}/{methodName}
// GET /devices/{deviceId}/services/{serviceName}/{typeName}/type
// GET /devices/{deviceId}/openwrt{path:/.*}
// POST /devices/{deviceId}/openwrt{path:/.*}
// GET /polled_connections
// GET /polled_connections/{connId}/messages
// POST /polled_connections/{connId}/:forward
// The maybeIntercept parameter is a function that accepts the
// requested device file and returns a path to a file to be returned instead or
// nil if the request should be allowed to proceed to the device.
func CreateHttpHandlers(
pool *DevicePool,
polledSet *PolledSet,
config apiv1.InfraConfig,
maybeIntercept func(string) *string) *mux.Router {
router := mux.NewRouter()
// The path parameter needs to include the leading '/'
router.HandleFunc("/groups", func(w http.ResponseWriter, r *http.Request) {
listGroups(w, r, pool)
}).Methods("GET")
router.HandleFunc("/devices/{deviceId}/files{path:/.+}", func(w http.ResponseWriter, r *http.Request) {
deviceFiles(w, r, pool, maybeIntercept)
}).Methods("GET")
router.HandleFunc("/devices", func(w http.ResponseWriter, r *http.Request) {
listDevices(w, r, pool)
}).Methods("GET")
router.HandleFunc("/devices/{deviceId}", func(w http.ResponseWriter, r *http.Request) {
deviceInfo(w, r, pool)
}).Methods("GET")
router.HandleFunc("/devices/{deviceId}/services", func(w http.ResponseWriter, r *http.Request) {
grpcListServices(w, r, pool)
}).Methods("GET")
router.HandleFunc("/devices/{deviceId}/services/{serviceName}", func(w http.ResponseWriter, r *http.Request) {
grpcListMethods(w, r, pool)
}).Methods("GET")
router.HandleFunc("/devices/{deviceId}/services/{serviceName}/{methodName}", func(w http.ResponseWriter, r *http.Request) {
grpcListReqResType(w, r, pool)
}).Methods("GET")
router.HandleFunc("/devices/{deviceId}/services/{serviceName}/{methodName}", func(w http.ResponseWriter, r *http.Request) {
grpcCallUnaryMethod(w, r, pool)
}).Methods("POST")
router.HandleFunc("/devices/{deviceId}/services/{serviceName}/{typeName}/type", func(w http.ResponseWriter, r *http.Request) {
grpcTypeInformation(w, r, pool)
}).Methods("GET")
router.HandleFunc("/devices/{deviceId}/openwrt{path:/.*}", func(w http.ResponseWriter, r *http.Request) {
openwrt(w, r, pool)
}).Methods("GET", "POST")
router.HandleFunc("/polled_connections/{connId}/:forward", func(w http.ResponseWriter, r *http.Request) {
forward(w, r, polledSet)
}).Methods("POST")
router.HandleFunc("/polled_connections/{connId}/messages", func(w http.ResponseWriter, r *http.Request) {
messages(w, r, polledSet)
}).Methods("GET")
router.HandleFunc("/polled_connections", func(w http.ResponseWriter, r *http.Request) {
createPolledConnection(w, r, pool, polledSet)
}).Methods("POST")
router.HandleFunc("/infra_config", func(w http.ResponseWriter, r *http.Request) {
ReplyJSONOK(w, config)
}).Methods("GET")
return router
}
// Control endpoint
func controlEndpoint(c *JSONUnix, pool *DevicePool) {
log.Println("Controller connected")
defer c.Close()
msg := make(map[string]interface{})
if err := c.Recv(&msg); err != nil {
log.Println("Error reading control message: ", err)
return
}
typeRaw, ok := msg["message_type"]
if !ok {
log.Println("Control message doesn't include message_type: ", msg)
return
}
typeStr, ok := typeRaw.(string)
if !ok {
log.Println("Control message's message_type field is not a string: ", msg)
return
}
switch typeStr {
case "pre-register":
var preRegisterMsg apiv1.PreRegisterMsg
// Ignore errors, msg was parsed from json so this can't fail
j, _ := json.Marshal(msg)
json.Unmarshal(j, &preRegisterMsg)
PreRegister(c, pool, &preRegisterMsg)
default:
log.Println("Invalid control type: ", typeStr)
return
}
}
func PreRegister(c *JSONUnix, pool *DevicePool, msg *apiv1.PreRegisterMsg) {
var ret apiv1.PreRegistrationResponse
idSet := make(map[string]bool)
// Length ensures no writers will block on this channel
devCh := make(chan string, len(msg.Devices))
for _, d := range msg.Devices {
regCh := make(chan bool, 1)
err := pool.PreRegister(
&apiv1.DeviceDescriptor{
DeviceId: d.Id,
GroupId: msg.GroupName,
Owner: msg.Owner,
Name: d.Name,
},
regCh,
)
status := apiv1.RegistrationStatusReport{
Id: d.Id,
Status: "accepted",
}
if err != nil {
status.Status = "failed"
status.Msg = err.Error()
} else {
idSet[d.Id] = true
go func(regCh chan bool, devCh chan string, id string) {
registered, ok := <-regCh
// The channel is closed if cancelled, true is sent when registration succeeds.
if registered && ok {
devCh <- id
}
}(regCh, devCh, d.Id)
}
ret = append(ret, status)
}
if err := c.Send(ret); err != nil {
log.Println("Error sending pre-registration response: ", err)
return
}
closeCh := make(chan bool)
go func(c *JSONUnix, ch chan bool) {
// Wait until socket closes or produces another error
var err error
for err == nil {
var ignored interface{}
err = c.Recv(ignored)
}
ch <- true
}(c, closeCh)
for {
select {
case id := <-devCh:
evt := apiv1.RegistrationStatusReport{
Id: id,
Status: "registered",
}
if err := c.Send(&evt); err != nil {
log.Println("Error sending registration event: ", err)
}
delete(idSet, id)
case <-closeCh:
// Cancel all pending pre-registrations when this function returns
for id := range idSet {
pool.CancelPreRegistration(id)
}
return
}
}
}
// Device endpoint
func deviceEndpoint(c *JSONUnix, pool *DevicePool, config apiv1.InfraConfig) {
log.Println("Device connected")
defer c.Close()
var msg apiv1.RegisterMsg
if err := c.Recv(&msg); err != nil {
log.Println("Error reading from device: ", err)
return
}
id := msg.DeviceId
if id == "" {
ReplyError(c, "Missing device_id")
return
}
info := msg.Info
if info == nil {
log.Println("No device info provided by: ", id)
info = make(map[string]interface{})
}
port := msg.Port
device := pool.Register(id, c, port, info)
if device == nil {
ReplyError(c, fmt.Sprintln("Device id already taken: ", id))
return
}
defer pool.Unregister(id)
if err := device.Send(config); err != nil {
log.Println("Failed to send config to device: ", err)
return
}
for {
var msg apiv1.ForwardMsg
if err := c.Recv(&msg); err != nil {
log.Println("Error reading from device: ", err)
return
}
clientId := msg.ClientId
if clientId == 0 {
ReplyError(c, "Device forward message missing client id")
return
}
payload := msg.Payload
if payload == nil {
ReplyError(c, "Device forward message missing payload")
return
}
dMsg := map[string]interface{}{
"message_type": "device_msg",
"payload": payload,
}
if err := device.ToClient(clientId, dMsg); err != nil {
log.Println("Device: ", id, " failed to send message to client: ", err)
ReplyError(c, fmt.Sprintln("Client disconnected: ", clientId))
}
}
}
func grpcListServices(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
vars := mux.Vars(r)
conn, err := ConnectControlEnvProxyServer(vars["deviceId"], pool)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer conn.Close()
client := grpcpb.NewControlEnvProxyServiceClient(conn)
reply, err := client.ListServices(context.Background(), &emptypb.Empty{})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ReplyJSONOK(w, reply)
}
func grpcListMethods(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
vars := mux.Vars(r)
conn, err := ConnectControlEnvProxyServer(vars["deviceId"], pool)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer conn.Close()
request := gopb.ListMethodsRequest{
ServiceName: vars["serviceName"],
}
client := grpcpb.NewControlEnvProxyServiceClient(conn)
reply, err := client.ListMethods(context.Background(), &request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ReplyJSONOK(w, reply)
}
func grpcListReqResType(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
vars := mux.Vars(r)
conn, err := ConnectControlEnvProxyServer(vars["deviceId"], pool)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer conn.Close()
request := gopb.ListReqResTypeRequest{
ServiceName: vars["serviceName"],
MethodName: vars["methodName"],
}
client := grpcpb.NewControlEnvProxyServiceClient(conn)
reply, err := client.ListReqResType(context.Background(), &request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ReplyJSONOK(w, reply)
}
func grpcCallUnaryMethod(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
vars := mux.Vars(r)
conn, err := ConnectControlEnvProxyServer(vars["deviceId"], pool)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer conn.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
request := gopb.CallUnaryMethodRequest{
ServiceName: vars["serviceName"],
MethodName: vars["methodName"],
JsonFormattedProto: string(body),
}
client := grpcpb.NewControlEnvProxyServiceClient(conn)
reply, err := client.CallUnaryMethod(context.Background(), &request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ReplyJSONOK(w, reply.JsonFormattedProto)
}
func grpcTypeInformation(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
vars := mux.Vars(r)
conn, err := ConnectControlEnvProxyServer(vars["deviceId"], pool)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer conn.Close()
request := gopb.TypeInformationRequest{
ServiceName: vars["serviceName"],
TypeName: vars["typeName"],
}
client := grpcpb.NewControlEnvProxyServiceClient(conn)
reply, err := client.TypeInformation(context.Background(), &request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte(reply.TextFormattedTypeInfo))
}
func openwrt(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
vars := mux.Vars(r)
devId := vars["deviceId"]
dev := pool.GetDevice(devId)
if dev == nil {
http.Error(w, "Device not found", http.StatusNotFound)
return
}
devInfo := dev.privateData.(map[string]interface{})
openwrtDevId, ok := devInfo["openwrt_device_id"].(string)
if !ok {
http.Error(w, "Device obtaining Openwrt not found", http.StatusNotFound)
return
}
path := vars["path"]
openwrtAddr, ok := devInfo["openwrt_addr"].(string)
if !ok {
http.Error(w, "Openwrt address not found", http.StatusNotFound)
return
}
url, _ := url.Parse("http://" + openwrtAddr)
proxy := httputil.NewSingleHostReverseProxy(url)
r.URL.Path = "/devices/" + openwrtDevId + "/openwrt" + path
proxy.ServeHTTP(w, r)
}
// General client endpoints
func listGroups(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
if err := ReplyJSONOK(w, pool.GroupIds()); err != nil {
log.Println(err)
}
}
func listDevices(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
groupId := r.URL.Query().Get("groupId")
if len(groupId) == 0 {
if err := ReplyJSONOK(w, pool.GetDeviceDescList()); err != nil {
log.Println(err)
}
return
}
if err := ReplyJSONOK(w, pool.GetDeviceDescByGroupId(groupId)); err != nil {
log.Println(err)
}
}
// Get device info
func deviceInfo(w http.ResponseWriter, r *http.Request, pool *DevicePool) {
vars := mux.Vars(r)
devId := vars["deviceId"]
dev := pool.GetDevice(devId)
if dev == nil {
http.NotFound(w, r)
return
}
ReplyJSONOK(w, apiv1.DeviceInfoReply{DeviceDescriptor: dev.Descriptor, RegistrationInfo: dev.privateData})
}
func deviceFiles(w http.ResponseWriter, r *http.Request, pool *DevicePool, maybeIntercept func(string) *string) {
vars := mux.Vars(r)
devId := vars["deviceId"]
dev := pool.GetDevice(devId)
if dev == nil {
http.NotFound(w, r)
return
}
path := vars["path"]
if alt := maybeIntercept(path); alt != nil {
http.ServeFile(w, r, *alt)
} else {
r.URL.Path = path
dev.Proxy.ServeHTTP(w, r)
}
}
// Http long polling client endpoints
func createPolledConnection(w http.ResponseWriter, r *http.Request, pool *DevicePool, polledSet *PolledSet) {
var msg apiv1.NewConnMsg
err := json.NewDecoder(r.Body).Decode(&msg)
if err != nil {
log.Println("Failed to parse json from client: ", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Println("id: ", msg.DeviceId)
device := pool.GetDevice(msg.DeviceId)
if device == nil {
http.Error(w, "Device not found", http.StatusNotFound)
return
}
conn := polledSet.NewConnection(device)
reply := apiv1.NewConnReply{ConnId: conn.Id(), DeviceInfo: device.privateData}
ReplyJSONOK(w, reply)
}
func forward(w http.ResponseWriter, r *http.Request, polledSet *PolledSet) {
id := mux.Vars(r)["connId"]
conn := polledSet.GetConnection(id)
if conn == nil {
http.NotFound(w, r)
return
}
var msg apiv1.ForwardMsg
err := json.NewDecoder(r.Body).Decode(&msg)
if err != nil {
log.Println("Failed to parse json from client: ", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cMsg := apiv1.ClientMsg{
Type: "client_msg",
ClientId: conn.ClientId(),
Payload: msg.Payload,
}
if err := conn.ToDevice(cMsg); err != nil {
log.Println("Failed to send message to device: ", err)
http.Error(w, "Device disconnected", http.StatusNotFound)
}
ReplyJSONOK(w, "ok")
}
func messages(w http.ResponseWriter, r *http.Request, polledSet *PolledSet) {
id := mux.Vars(r)["connId"]
conn := polledSet.GetConnection(id)
if conn == nil {
http.NotFound(w, r)
return
}
start := 0
count := -1 // All messages
if sStr := r.FormValue("start"); sStr != "" {
i, err := strconv.Atoi(sStr)
if err != nil {
log.Println("Invalid start value: ", sStr)
http.Error(w, "Invalid value for start field", http.StatusBadRequest)
return
}
start = i
}
if cStr := r.FormValue("count"); cStr != "" {
i, err := strconv.Atoi(cStr)
if err != nil {
log.Println("Invalid count value: ", cStr)
http.Error(w, "Invalid value for count field", http.StatusBadRequest)
return
}
count = i
}
ReplyJSONOK(w, conn.GetMessages(start, count))
}