Skip to content

Commit 430b304

Browse files
committed
connect: proxy fixes
1 parent 7161588 commit 430b304

5 files changed

Lines changed: 184 additions & 115 deletions

File tree

connect/connect_proxy_test.go

Lines changed: 69 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
//go:build !race
2+
3+
// note race detection on this test progressively slows down the test until it stops working
4+
//
15
package main
26

37
import (
@@ -11,6 +15,8 @@ import (
1115
"encoding/json"
1216
"fmt"
1317
"io"
18+
"os/exec"
19+
"sync"
1420
"time"
1521

1622
// "strings"
@@ -41,9 +47,24 @@ func testConnectProxy(t *testing.T) {
4147
ctx, cancel := context.WithCancel(context.Background())
4248
defer cancel()
4349

50+
func() {
51+
fmt.Printf(`
52+
53+
** This test requires many file descriptions.
54+
** Setting "ulimit -n 1048576".
55+
** The value will not be reset when the test ends.
56+
57+
`)
58+
_, err := exec.Command("/bin/sh", "-c", "ulimit -n 1048576").CombinedOutput()
59+
if err != nil {
60+
panic(err)
61+
}
62+
}()
63+
4464
maxMessageContentSize := model.ByteCount(4096)
4565

46-
// sequenceIdleTimeout := 100 * time.Millisecond
66+
// clean up lingering residents at this timeout
67+
// idleTimeout := 5 * time.Minute
4768
// receiveTimeout := 900 * time.Second
4869
// minResendInterval := 10 * time.Millisecond
4970
// standardContractTransferByteCount := 4 * maxMessageContentSize
@@ -123,8 +144,8 @@ func testConnectProxy(t *testing.T) {
123144

124145
settings := DefaultExchangeSettings()
125146
settings.ExchangeBufferSize = 0
126-
// settings.ResidentIdleTimeout = sequenceIdleTimeout
127-
// settings.ForwardIdleTimeout = sequenceIdleTimeout
147+
// settings.ResidentIdleTimeout = idleTimeout
148+
// settings.ForwardIdleTimeout = idleTimeout
128149
settings.FramerSettings.MaxMessageLen = int(2 * maxMessageContentSize)
129150
settings.ForwardEnforceActiveContracts = true
130151
settings.IngressSecurityPolicyGenerator = connect.DisableSecurityPolicyWithStats
@@ -244,7 +265,6 @@ func testConnectProxy(t *testing.T) {
244265

245266
platformUrl, port := randServerUrl()
246267
providerTransportSettings := connect.DefaultPlatformTransportSettings()
247-
providerTransportSettings.QuicTlsConfig.InsecureSkipVerify = true
248268
providerTransportSettings.H3Port = port + 443
249269
providerTransportSettings.DnsPort = port + 53
250270
providerTransportSettings.FramerSettings.MaxMessageLen = int(2 * maxMessageContentSize)
@@ -273,7 +293,7 @@ func testConnectProxy(t *testing.T) {
273293
}
274294

275295
providerClientIds := []server.Id{}
276-
for range 2 {
296+
for range 32 {
277297
providerClientId := runProvider()
278298
// providerClientId := server.NewId()
279299
providerClientIds = append(providerClientIds, providerClientId)
@@ -283,7 +303,7 @@ func testConnectProxy(t *testing.T) {
283303
case <-time.After(2 * time.Second):
284304
}
285305

286-
for range 2 {
306+
for i := range 1024 {
287307
// create a proxy client, connect to a random server, and route to a random provider
288308

289309
providerClientId := providerClientIds[mathrand.Intn(len(providerClientIds))]
@@ -353,10 +373,10 @@ func testConnectProxy(t *testing.T) {
353373
// TODO for some reason go does not pass the host header in the proxy
354374
// TODO force the auth token
355375
// FIXME see ProxyConnectHeader
356-
addr, _ := randHttpsPoxyServerHostPort()
357-
httpsProxyUrlStr := fmt.Sprintf("https://%s", addr)
358-
httpsProxyUrl, err := url.Parse(httpsProxyUrlStr)
359-
assert.Equal(t, err, nil)
376+
// addr, _ := randHttpsPoxyServerHostPort()
377+
// httpsProxyUrlStr := fmt.Sprintf("https://%s", addr)
378+
// httpsProxyUrl, err := url.Parse(httpsProxyUrlStr)
379+
// assert.Equal(t, err, nil)
360380

361381
// proxyDialer := &net.Dialer{
362382
// Timeout: 15 * time.Second,
@@ -369,26 +389,34 @@ func testConnectProxy(t *testing.T) {
369389
proxyConnectHeader.Add("Proxy-Authorization", fmt.Sprintf("Bearer %s", result.ProxyConfigResult.AuthToken))
370390

371391
proxyHttpClient := &http.Client{
372-
Timeout: 60 * time.Second,
392+
Timeout: 120 * time.Second,
373393
Transport: &http.Transport{
394+
// MaxIdleConns: 1, // Max idle connections in the pool
395+
// IdleConnTimeout: 30 * time.Second, // Max time an idle connection stays open
396+
// DisableKeepAlives: true,
374397
// TLSHandshakeTimeout: 15 * time.Second,
375-
Proxy: http.ProxyURL(httpsProxyUrl),
398+
// Proxy: http.ProxyURL(httpsProxyUrl),
399+
Proxy: func(r *http.Request) (*url.URL, error) {
400+
addr, _ := randHttpsPoxyServerHostPort()
401+
httpsProxyUrlStr := fmt.Sprintf("https://%s", addr)
402+
return url.Parse(httpsProxyUrlStr)
403+
},
376404
// DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
377405
// addr, _ = randServerHostPort()
378406
// fmt.Printf("DIAL %s VIA %s %s\n", httpsProxyUrl, network, addr)
379407
// return proxyDialer.DialContext(ctx, network, addr)
380408
// },
381409
ProxyConnectHeader: proxyConnectHeader,
382-
TLSClientConfig: &tls.Config{
383-
InsecureSkipVerify: true,
384-
},
385410
},
386411
}
387412

388-
for range 2 {
413+
runOne := func() {
414+
// var err error
415+
// for range 2 {
389416
addr, _ := randServerHostPort()
390417
targetUrlString := fmt.Sprintf("https://%s/status", addr)
391418
// targetUrlString := "https://api.bringyour.com/hello"
419+
// var r *http.Response
392420
r, err := proxyHttpClient.Get(targetUrlString)
393421
assert.Equal(t, err, nil)
394422
if err == nil {
@@ -399,8 +427,33 @@ func testConnectProxy(t *testing.T) {
399427
err = json.Unmarshal(b, &m)
400428
assert.Equal(t, err, nil)
401429
assert.NotEqual(t, m["client_address"], nil)
430+
return
402431
}
432+
// FIXME
433+
// else something flaky about the proxy connection
434+
// try again
435+
// }
436+
// assert.Equal(t, err, nil)
437+
}
438+
439+
// run in serial
440+
for j := range 32 {
441+
fmt.Printf("[%d][%d][s]start\n", i, j)
442+
runOne()
443+
}
444+
445+
// run in parallel
446+
var wg sync.WaitGroup
447+
for j := range 32 {
448+
wg.Add(1)
449+
go func() {
450+
defer wg.Done()
451+
452+
fmt.Printf("[%d][%d][p]start\n", i, j)
453+
runOne()
454+
}()
403455
}
456+
wg.Wait()
404457

405458
proxyHttpClient.CloseIdleConnections()
406459

connect/resident.go

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1491,6 +1491,8 @@ func NewResident(
14911491
instanceId server.Id,
14921492
residentId server.Id,
14931493
) *Resident {
1494+
glog.V(1).Infof("[r]create")
1495+
14941496
cancelCtx, cancel := context.WithCancel(ctx)
14951497

14961498
proxyDeviceConfig := model.GetProxyDeviceConfigForClient(cancelCtx, clientId, instanceId)
@@ -1682,7 +1684,9 @@ func (self *Resident) handleClientForward(path connect.TransferPath, transferFra
16821684

16831685
// FIXME deep packet inspection to look at the contract frames and verify contracts before forwarding
16841686

1685-
c := func() bool {
1687+
initForward := func() *ResidentForward {
1688+
self.stateLock.Lock()
1689+
defer self.stateLock.Unlock()
16861690

16871691
nextForward := func() *ResidentForward {
16881692
if self.exchange.settings.ForwardEnforceActiveContracts {
@@ -1729,43 +1733,50 @@ func (self *Resident) handleClientForward(path connect.TransferPath, transferFra
17291733
}
17301734
})
17311735

1732-
var replacedForward *ResidentForward
1733-
func() {
1734-
self.stateLock.Lock()
1735-
defer self.stateLock.Unlock()
1736-
replacedForward = self.forwards[destinationId]
1737-
self.forwards[destinationId] = forward
1738-
}()
1739-
if replacedForward != nil {
1740-
replacedForward.Cancel()
1741-
}
1742-
glog.V(1).Infof("[rf]open %s->%s\n", sourceId, destinationId)
1743-
17441736
return forward
17451737
}
17461738

17471739
limit := false
17481740
var forward *ResidentForward
1749-
func() {
1750-
self.stateLock.Lock()
1751-
defer self.stateLock.Unlock()
1752-
var ok bool
1753-
forward, ok = self.forwards[destinationId]
1754-
if !ok && self.exchange.settings.MaxConcurrentForwardsPerResident <= len(self.forwards) {
1755-
limit = true
1756-
}
1757-
}()
1741+
// func() {
1742+
// self.stateLock.Lock()
1743+
// defer self.stateLock.Unlock()
1744+
var ok bool
1745+
forward, ok = self.forwards[destinationId]
1746+
if !ok && self.exchange.settings.MaxConcurrentForwardsPerResident <= len(self.forwards) {
1747+
limit = true
1748+
}
1749+
// }()
17581750

17591751
if forward == nil && limit {
17601752
glog.Infof("[rf]abuse forward limit %s->%s", sourceId, destinationId)
17611753
self.abuseLimiter.delay()
1762-
return false
1754+
return nil
17631755
}
17641756

17651757
if forward == nil || !forward.UpdateActivity() {
17661758
forward = nextForward()
1759+
1760+
var replacedForward *ResidentForward
1761+
// func() {
1762+
// self.stateLock.Lock()
1763+
// defer self.stateLock.Unlock()
1764+
replacedForward = self.forwards[destinationId]
1765+
self.forwards[destinationId] = forward
1766+
// }()
1767+
if replacedForward != nil {
1768+
replacedForward.Cancel()
1769+
}
1770+
glog.V(1).Infof("[rf]open %s->%s\n", sourceId, destinationId)
1771+
17671772
}
17681773

1774+
return forward
1775+
}
1776+
1777+
c := func() bool {
1778+
forward := initForward()
1779+
17691780
if forward == nil {
17701781
return false
17711782
}

connect/resident_proxy.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
// "fmt"
88
"time"
99

10+
"github.com/urnetwork/glog"
11+
1012
"github.com/urnetwork/connect"
1113
"github.com/urnetwork/connect/protocol"
1214
"github.com/urnetwork/sdk"
@@ -67,6 +69,7 @@ func NewResidentProxyDevice(
6769
proxyDeviceConfig *model.ProxyDeviceConfig,
6870
settings *ResidentProxyDeviceSettings,
6971
) (*ResidentProxyDevice, error) {
72+
glog.Infof("[rp]create")
7073

7174
// this jwt is used to access the services in the network space
7275
byJwt, err := jwt.LoadByJwtFromClientId(ctx, clientId)
@@ -133,6 +136,8 @@ func (self *ResidentProxyDevice) AddTun() (
133136
receive chan []byte,
134137
closeTun func(),
135138
) {
139+
glog.Infof("[rp]add tun")
140+
136141
send = make(chan []byte, self.exchange.settings.ExchangeBufferSize)
137142
receive = make(chan []byte, self.exchange.settings.ExchangeBufferSize)
138143

connect/resident_proxy_generator.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
"github.com/urnetwork/connect"
1010
"github.com/urnetwork/connect/protocol"
11+
"github.com/urnetwork/glog"
1112
"github.com/urnetwork/server"
1213
"github.com/urnetwork/server/controller"
1314
"github.com/urnetwork/server/jwt"
@@ -72,6 +73,10 @@ func (self *exchangeGenerator) clientSession() *session.ClientSession {
7273
return session.NewLocalClientSession(self.ctx, "127.0.0.1", self.byJwt)
7374
}
7475

76+
func (self *exchangeGenerator) cleanupSession() *session.ClientSession {
77+
return session.NewLocalClientSession(context.Background(), "127.0.0.1", self.byJwt)
78+
}
79+
7580
func (self *exchangeGenerator) NextDestinations(count int, excludeDestinations []connect.MultiHopId, rankMode string) (map[connect.MultiHopId]connect.DestinationStats, error) {
7681
excludeDestinationsIds := [][]server.Id{}
7782
for _, excludeDestination := range excludeDestinations {
@@ -169,7 +174,7 @@ func (self *exchangeGenerator) RemoveClientArgs(args *connect.MultiClientGenerat
169174
ClientId: server.Id(args.ClientId),
170175
}
171176

172-
model.RemoveNetworkClient(removeNetworkClient, self.clientSession())
177+
model.RemoveNetworkClient(removeNetworkClient, self.cleanupSession())
173178
}
174179

175180
func (self *exchangeGenerator) RemoveClientWithArgs(client *connect.Client, args *connect.MultiClientGeneratorClientArgs) {

0 commit comments

Comments
 (0)