-
Notifications
You must be signed in to change notification settings - Fork 102
/
z_conncut_test.go
326 lines (305 loc) · 6.78 KB
/
z_conncut_test.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
// +build !posix
// Copyright 2020 The Godror Authors
//
//
// SPDX-License-Identifier: UPL-1.0 OR Apache-2.0
package godror_test
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"testing"
"time"
"github.com/godror/godror"
)
// TestConnCut tests prepared statements handling connection cuting.
//
// WARNING: this won't work if the remote needs TLS !!!
func TestConnCut(t *testing.T) {
if os.Getenv("GODROR_TEST_DB") == "" {
t.Skip("TestConnCut does not work with the default TLS'd Cloud DB")
}
// First, find out the remote address of the connection
rem1 := make(map[string]net.TCPAddr)
if err := getRemotes(rem1); err != nil {
t.Fatal(err)
}
P, err := godror.ParseDSN(testConStr)
if err != nil {
t.Fatal(err)
}
P.StandaloneConnection = true
db, err := sql.Open("godror", P.StringWithPassword())
if err != nil {
t.Fatal(err)
}
defer db.Close()
ctx, cancel := context.WithTimeout(testContext("ConnCut"), 52*time.Second)
defer cancel()
const qry = "SELECT SYS_CONTEXT('userenv', 'service_name') FROM all_objects"
var upstream net.TCPAddr
rem2 := make(map[string]net.TCPAddr)
var serviceName string
for i := 0; i < 10; i++ {
for k := range rem2 {
delete(rem2, k)
}
shortCtx, shortCancel := context.WithTimeout(ctx, 5*time.Second)
rows, err := db.QueryContext(shortCtx, qry)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
rows.Next()
err = rows.Scan(&serviceName)
shortCancel()
if err != nil {
t.Fatal(err)
}
err = getRemotes(rem2)
if err != nil {
t.Fatal(err)
}
t.Log("service:", serviceName)
for k := range rem2 {
if _, ok := rem1[k]; ok {
delete(rem2, k)
continue
}
upstream = rem2[k]
}
if len(rem2) == 1 {
break
}
}
db.Close()
if len(rem2) != 1 {
t.Skipf("cannot find remote address of %q: when connecting to it, %v connections has been created",
testConStr, rem2)
}
t.Log("upstream:", upstream.String())
t.Parallel()
// Second, create proxy for it
px, err := newTCPProxy(ctx, upstream, t)
if err != nil {
t.Fatal(err)
}
pxCtx, pxCancel := context.WithCancel(ctx)
defer pxCancel()
go func() { px.Serve(pxCtx) }()
P.ConnectString = px.ListenAddr() + "/" + serviceName
db, err = sql.Open("godror", P.StringWithPassword())
if err != nil {
t.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(2)
db.SetMaxIdleConns(2)
t.Log("pinging", P.String())
time.Sleep(100 * time.Millisecond)
shortCtx, shortCancel := context.WithTimeout(ctx, 3*time.Second)
done := make(chan struct{})
go func() {
select {
case <-ctx.Done():
pxCancel()
case <-done:
return
}
}()
err = db.PingContext(shortCtx)
close(done)
shortCancel()
if err != nil {
t.Skip(err)
}
// Now the real test
// 1. prepare statement
stmt, err := db.PrepareContext(ctx, "SELECT object_name FROM all_objects WHERE ROWNUM <= :2")
if err != nil {
t.Fatal(err)
}
defer stmt.Close()
// force both connections to be in use
rows1, err := stmt.QueryContext(ctx, 99)
if err != nil {
t.Fatal(err)
}
rows2, err := stmt.QueryContext(ctx, 99)
if err != nil {
rows1.Close()
t.Fatal(err)
}
rows2.Close()
rows1.Close()
for i := 0; i < 10; i++ {
shortCtx, shortCancel = context.WithTimeout(ctx, 5*time.Second)
var s string
err = stmt.QueryRowContext(shortCtx, 1).Scan(&s)
shortCancel()
if err != nil {
if i <= 3 {
t.Errorf("%d. %v", i+1, err)
} else {
t.Logf("%d. %v", i+1, err)
}
}
t.Log(s)
shortCtx, shortCancel = context.WithTimeout(ctx, 5*time.Second)
err := db.PingContext(shortCtx)
shortCancel()
if err != nil {
if i <= 3 {
t.Error(err)
} else {
t.Log(err)
}
}
if i == 3 {
t.Log("canceling proxy")
go func() {
pxCancel()
}()
}
}
}
type tcpProxy struct {
upstream net.TCPAddr
lsnr *net.TCPListener
*testing.T
}
func (px tcpProxy) ListenAddr() string { return px.lsnr.Addr().String() }
func newTCPProxy(ctx context.Context, upstream net.TCPAddr, t *testing.T) (*tcpProxy, error) {
var d net.Dialer
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
conn, err := d.DialContext(ctx, "tcp", upstream.String())
cancel()
if err != nil {
return nil, err
}
conn.Close()
px := tcpProxy{upstream: upstream, T: t}
px.lsnr, err = net.ListenTCP("tcp", &net.TCPAddr{IP: net.ParseIP("127.0.0.1")}) // random port on localhost
return &px, err
}
func (px *tcpProxy) Serve(ctx context.Context) error {
go func() {
<-ctx.Done()
px.lsnr.Close()
}()
for {
down, err := px.lsnr.AcceptTCP()
if err != nil {
if px.T != nil {
px.Log(err)
}
var tErr interface{ Temporary() bool }
if errors.As(err, &tErr) && !tErr.Temporary() {
return err
}
continue
}
go px.handleConn(ctx, down)
}
}
func (px *tcpProxy) handleConn(ctx context.Context, down *net.TCPConn) error {
defer down.Close()
up, err := net.DialTCP("tcp", nil, &px.upstream)
if err != nil {
if px.T != nil {
px.Log(err)
}
return err
}
defer up.Close()
go func() {
<-ctx.Done()
up.Close()
down.Close()
}()
pipe := func(ctx context.Context, dst, src *net.TCPConn) error {
buf := make([]byte, 512)
var consecEOF int
//remote := src.RemoteAddr()
for {
if err := ctx.Err(); err != nil {
dst.Close()
return err
}
n, err := src.Read(buf)
if n != 0 {
if _, writeErr := dst.Write(buf[:n]); writeErr != nil {
return writeErr
}
}
if err == nil {
consecEOF = 0
} else if err == io.EOF {
consecEOF++
if consecEOF > 3 {
return err
}
time.Sleep(time.Second)
continue
} else {
consecEOF = 0
if px.T != nil {
px.Logf("Copy from %s to %s: %v", src.RemoteAddr(), dst.RemoteAddr(), err)
}
return err
}
}
}
slowCtx, slowCancel := context.WithCancel(context.Background())
defer slowCancel()
go func() {
pipe(ctx, down, up)
time.Sleep(2 * time.Second)
slowCancel()
}()
return pipe(slowCtx, up, down)
}
// /proc/self/net/tcp 3. col is rem_addr:port
func getRemotes(dest map[string]net.TCPAddr) error {
for _, nm := range []string{"/proc/self/net/tcp", "/proc/self/net/tcp6"} {
b, err := ioutil.ReadFile(nm)
if err != nil {
return err
}
lines := bytes.Split(b, []byte{'\n'})
if len(lines) < 1 {
return errors.New("empty " + nm)
} else if len(lines) < 2 {
return nil
}
for _, line := range lines[1:] {
fields := bytes.Fields(line)
if len(fields) <= 2 {
continue
}
var local, remote net.TCPAddr
if _, err := fmt.Sscanf(string(fields[1])+" "+string(fields[2]), "%X:%X %X:%X",
&local.IP, &local.Port, &remote.IP, &remote.Port,
); err != nil {
return err
}
if remote.Port != 0 {
reverseBytes(local.IP)
reverseBytes(remote.IP)
dest[local.String()] = remote
}
}
}
return nil
}
func reverseBytes(p []byte) {
for i, j := 0, len(p)-1; i < j; i, j = i+1, j-1 {
p[i], p[j] = p[j], p[i]
}
}