-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
websocket.go
128 lines (110 loc) · 3.79 KB
/
websocket.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
/*
Copyright 2020 The Knative Authors
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 e2e
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
"k8s.io/apimachinery/pkg/util/wait"
pkgTest "knative.dev/pkg/test"
ingress "knative.dev/pkg/test/ingress"
"knative.dev/serving/test"
)
const (
connectRetryInterval = 1 * time.Second
connectTimeout = 1 * time.Minute
)
const message = "Hello, websocket"
// connect attempts to establish WebSocket connection with the Service.
// It will retry until reaching `connectTimeout` duration.
func connect(t *testing.T, clients *test.Clients, domain, timeout string) (*websocket.Conn, error) {
var (
err error
address string
)
address = domain
mapper := func(in string) string { return in }
if !test.ServingFlags.ResolvableDomain {
address, mapper, err = ingress.GetIngressEndpoint(context.Background(), clients.KubeClient, pkgTest.Flags.IngressEndpoint)
if err != nil {
return nil, err
}
}
rawQuery := fmt.Sprintf("delay=%s", timeout)
u := url.URL{Scheme: "ws", Host: net.JoinHostPort(address, mapper("80")), Path: "/", RawQuery: rawQuery}
if test.ServingFlags.HTTPS {
u = url.URL{Scheme: "wss", Host: net.JoinHostPort(address, mapper("443")), Path: "/", RawQuery: rawQuery}
}
var conn *websocket.Conn
waitErr := wait.PollUntilContextTimeout(context.Background(), connectRetryInterval, connectTimeout, true, func(context.Context) (bool, error) {
t.Logf("Connecting using websocket: url=%s, host=%s", u.String(), domain)
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 45 * time.Second,
}
if test.ServingFlags.HTTPS {
dialer.TLSClientConfig = test.TLSClientConfig(context.Background(), t.Logf, clients)
dialer.TLSClientConfig.ServerName = domain // Set ServerName for pseudo hostname with TLS.
}
c, resp, err := dialer.Dial(u.String(), http.Header{"Host": {domain}})
if err == nil {
t.Log("WebSocket connection established.")
conn = c
return true, nil
}
if resp == nil {
// We don't have an HTTP response, probably TCP errors.
t.Log("Connection failed:", err)
return false, nil
}
body, readErr := io.ReadAll(resp.Body)
if readErr != nil {
t.Logf("Connection failed: %v. Failed to read HTTP response: %v", err, readErr)
return false, nil
}
t.Logf("HTTP connection failed: %v. Response=%+v. ResponseBody=%q", err, resp, body)
return false, nil
})
return conn, waitErr
}
func ValidateWebSocketConnection(t *testing.T, clients *test.Clients, names test.ResourceNames, timeoutSeconds string) error {
t.Helper()
// Establish the websocket connection.
conn, err := connect(t, clients, names.URL.Hostname(), timeoutSeconds)
if err != nil {
return err
}
defer conn.Close()
// Send a message.
t.Logf("Sending message %q to server.", message)
if err = conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
return err
}
t.Log("Message sent.")
// Read back the echoed message and compared with sent.
_, recv, err := conn.ReadMessage()
if err != nil {
return err
} else if strings.HasPrefix(string(recv), message) {
t.Logf("Received message %q from echo server.", recv)
return nil
}
return fmt.Errorf("expected to receive back the message: %q but received %q", message, string(recv))
}