/
hub.go
197 lines (164 loc) · 5.27 KB
/
hub.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
// Copyright 2018 Google Inc.
//
// 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
//
// http://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 hub launches WebDriver servers and correctly dispatches requests to the correct server
// based on session id.
package hub
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/bazelbuild/rules_webtesting/go/httphelper"
"github.com/bazelbuild/rules_webtesting/go/metadata/capabilities"
"github.com/bazelbuild/rules_webtesting/go/wsl/driver"
"github.com/bazelbuild/rules_webtesting/go/wsl/resolver"
)
// A Hub is an HTTP handler that manages incoming WebDriver requests.
type Hub struct {
// Mutex to protext access to sessions.
mu sync.RWMutex
sessions map[string]*driver.Driver
localHost string
uploader http.Handler
}
// New creates a new Hub.
func New(localHost string, uploader http.Handler) *Hub {
return &Hub{
sessions: map[string]*driver.Driver{},
localHost: localHost,
uploader: uploader,
}
}
func (h *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := strings.Split(r.URL.Path, "/")[1:]
if len(path) < 1 || path[0] != "session" {
errorResponse(w, http.StatusNotFound, 9, "unknown command", fmt.Sprintf("%q is not a known command", r.URL.Path))
return
}
if r.Method == http.MethodPost && len(path) == 1 {
h.newSession(w, r)
return
}
if len(path) < 2 {
errorResponse(w, http.StatusMethodNotAllowed, 9, "unknown method", fmt.Sprintf("%s is not a supported method for /session", r.Method))
return
}
driver := h.driver(path[1])
if driver == nil {
errorResponse(w, http.StatusNotFound, 6, "invalid session id", fmt.Sprintf("%q is not an active session", path[1]))
return
}
if r.Method == http.MethodDelete && len(path) == 2 {
h.quitSession(path[1], driver, w, r)
return
}
if len(path) == 3 && path[2] == "file" {
h.uploader.ServeHTTP(w, r)
return
}
driver.Forward(r.Context(), w, r)
}
func (h *Hub) driver(session string) *driver.Driver {
h.mu.RLock()
defer h.mu.RUnlock()
return h.sessions[session]
}
func (h *Hub) newSession(w http.ResponseWriter, r *http.Request) {
reqJSON := map[string]interface{}{}
if err := json.NewDecoder(r.Body).Decode(&reqJSON); err != nil {
errorResponse(w, http.StatusBadRequest, 13, "invalid argument", err.Error())
return
}
caps, err := capabilities.FromNewSessionArgs(reqJSON)
if err != nil {
errorResponse(w, http.StatusBadRequest, 13, "invalid argument", err.Error())
return
}
session, driver, err := h.newSessionFromCaps(r.Context(), caps, w)
if err != nil {
errorResponse(w, http.StatusInternalServerError, 33, "session not created", fmt.Sprintf("unable to create session: %v", err))
log.Printf("Error creating webdriver session: %v", err)
return
}
h.mu.Lock()
defer h.mu.Unlock()
h.sessions[session] = driver
}
func (h *Hub) newSessionFromCaps(ctx context.Context, caps *capabilities.Capabilities, w http.ResponseWriter) (string, *driver.Driver, error) {
sessionID := "last"
if i, ok := caps.AlwaysMatch["google:sessionId"]; ok {
switch ii := i.(type) {
case string:
sessionID = ii
case float64:
sessionID = strconv.Itoa(int(ii))
default:
return "", nil, fmt.Errorf("google:sessionId %#v is not a string or number", i)
}
}
resolver := resolver.New(sessionID)
caps, err := caps.Resolve(resolver.Resolve)
if err != nil {
return "", nil, err
}
wslConfig, ok := caps.AlwaysMatch["google:wslConfig"].(map[string]interface{})
if !ok {
if err := resolver.RecyclePorts(); err != nil {
log.Printf("Error recycling ports: %v", err)
}
return "", nil, errors.New("alwaysMatch capabilites must include google:wslConfig")
}
d, err := driver.New(ctx, h.localHost, sessionID, wslConfig, resolver)
if err != nil {
if err := resolver.RecyclePorts(); err != nil {
log.Printf("Error recycling ports: %v", err)
}
return "", nil, fmt.Errorf("Error launching driver binary: %w", err)
}
s, err := d.NewSession(ctx, caps, w)
if err != nil {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
if err := d.Shutdown(ctx); err != nil {
log.Printf("Error shutting down driver: %v", err)
}
return "", nil, fmt.Errorf("Error requesting new session: %w", err)
}
return s, d, nil
}
func (h *Hub) quitSession(session string, driver *driver.Driver, w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
driver.Quit(w, r)
delete(h.sessions, session)
}
func errorResponse(w http.ResponseWriter, httpStatus, status int, err, message string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
httphelper.SetDefaultResponseHeaders(w.Header())
w.WriteHeader(httpStatus)
respJSON := map[string]interface{}{
"status": status,
"value": map[string]interface{}{
"error": err,
"message": message,
},
}
json.NewEncoder(w).Encode(respJSON)
}