-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathhandle_http_test.go
More file actions
3573 lines (3182 loc) · 118 KB
/
Copy pathhandle_http_test.go
File metadata and controls
3573 lines (3182 loc) · 118 KB
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build !windows
/***************************************************************
*
* Copyright (C) 2025, Pelican Project, Morgridge Institute for Research
*
* 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 client
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"fmt"
"io"
"io/fs"
"math/big"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
"golang.org/x/net/webdav"
"github.com/pelicanplatform/pelican/config"
"github.com/pelicanplatform/pelican/error_codes"
"github.com/pelicanplatform/pelican/param"
"github.com/pelicanplatform/pelican/pelican_url"
"github.com/pelicanplatform/pelican/server_structs"
"github.com/pelicanplatform/pelican/server_utils"
"github.com/pelicanplatform/pelican/test_utils"
)
func TestMain(m *testing.M) {
cleanup := test_utils.SetupGlobalTestLogging()
server_utils.ResetTestState()
if err := config.InitClient(); err != nil {
cleanup()
os.Exit(1)
}
code := m.Run()
cleanup()
os.Exit(code)
}
// TestNewTransferDetails checks the creation of transfer details
func TestNewTransferDetails(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
os.Setenv("http_proxy", "http://proxy.edu:3128")
t.Cleanup(func() {
require.NoError(t, os.Unsetenv("http_proxy"))
})
t.Run("ServerWithHTTPAndPort", func(t *testing.T) {
server := "http://cache.edu:8000"
transfers := generateTransferDetails(server, transferDetailsOptions{false, ""})
assert.Equal(t, 2, len(transfers))
assert.Equal(t, "cache.edu:8000", transfers[0].Url.Host)
assert.Equal(t, "http", transfers[0].Url.Scheme)
assert.Equal(t, true, transfers[0].Proxy)
assert.Equal(t, "cache.edu:8000", transfers[1].Url.Host)
assert.Equal(t, "http", transfers[1].Url.Scheme)
assert.Equal(t, false, transfers[1].Proxy)
})
t.Run("ServerWithHTTPSAndPort", func(t *testing.T) {
server := "https://cache.edu:8443"
transfers := generateTransferDetails(server, transferDetailsOptions{true, ""})
assert.Equal(t, 1, len(transfers))
assert.Equal(t, "cache.edu:8443", transfers[0].Url.Host)
assert.Equal(t, "https", transfers[0].Url.Scheme)
assert.Equal(t, false, transfers[0].Proxy)
})
t.Run("ServerWithHTTPAndNoPort", func(t *testing.T) {
server := "http://cache.edu"
// Case 3: cache without port with http
transfers := generateTransferDetails(server, transferDetailsOptions{false, ""})
assert.Equal(t, 2, len(transfers))
assert.Equal(t, "cache.edu", transfers[0].Url.Host)
assert.Equal(t, "http", transfers[0].Url.Scheme)
assert.Equal(t, true, transfers[0].Proxy)
assert.Equal(t, "cache.edu", transfers[1].Url.Host)
assert.Equal(t, "http", transfers[1].Url.Scheme)
assert.Equal(t, false, transfers[1].Proxy)
})
t.Run("ServerWithHTTPSAndNoPort", func(t *testing.T) {
// Case 4. cache without port with https
server := "https://cache.edu"
transfers := generateTransferDetails(server, transferDetailsOptions{true, ""})
assert.Equal(t, 1, len(transfers))
assert.Equal(t, "cache.edu", transfers[0].Url.Host)
assert.Equal(t, "https", transfers[0].Url.Scheme)
assert.Equal(t, false, transfers[0].Proxy)
})
}
func TestNewTransferDetailsEnv(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
os.Setenv("http_proxy", "http://proxy.edu:3128")
t.Cleanup(func() {
require.NoError(t, os.Unsetenv("http_proxy"))
})
testCache := "http://cache.edu:8000"
os.Setenv("OSG_DISABLE_PROXY_FALLBACK", "")
test_utils.InitClient(t, map[string]any{})
transfers := generateTransferDetails(testCache, transferDetailsOptions{})
assert.Equal(t, 1, len(transfers))
assert.Equal(t, true, transfers[0].Proxy)
os.Unsetenv("http_proxy")
transfers = generateTransferDetails(testCache, transferDetailsOptions{true, ""})
assert.Equal(t, 1, len(transfers))
assert.Equal(t, "https", transfers[0].Url.Scheme)
assert.Equal(t, false, transfers[0].Proxy)
os.Unsetenv("OSG_DISABLE_PROXY_FALLBACK")
server_utils.ResetTestState()
err := config.InitClient()
assert.Nil(t, err)
}
func TestSlowTransfers(t *testing.T) {
t.Cleanup(func() {
goleak.VerifyNone(t,
// Ignore the progress bars
goleak.IgnoreTopFunction("github.com/vbauerster/mpb/v8.(*Progress).serve"),
goleak.IgnoreTopFunction("github.com/vbauerster/mpb/v8.heapManager.run"),
)
})
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// Adjust down some timeouts to speed up the test
test_utils.InitClient(t, map[string]any{
"Client.SlowTransferWindow": "2s",
"Client.SlowTransferRampupTime": "1s",
})
channel := make(chan bool)
slowDownload := 1024 * 10 // 10 KiB/s < 100 KiB/s
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "HEAD" {
w.Header().Add("Content-Length", "1024000")
w.WriteHeader(http.StatusOK)
return
}
buffer := make([]byte, slowDownload)
for {
select {
case <-channel:
return
default:
_, err := w.Write(buffer)
if err != nil {
return
}
w.(http.Flusher).Flush()
time.Sleep(1 * time.Second)
}
}
}))
defer svr.CloseClientConnections()
defer svr.Close()
testCache := svr.URL
os.Setenv("http_proxy", "http://proxy.edu:3128")
t.Cleanup(func() {
require.NoError(t, os.Unsetenv("http_proxy"))
})
transfers := generateTransferDetails(testCache, transferDetailsOptions{false, ""})
assert.Equal(t, 2, len(transfers))
assert.Equal(t, svr.URL, transfers[0].Url.String())
finishedChannel := make(chan bool)
var err error
// Do a quick timeout
go func() {
fname := filepath.Join(t.TempDir(), "test.txt")
var writer *os.File
writer, err = os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
_, _, _, _, err = downloadHTTP(ctx, nil, nil, transfers[0], fname, writer, 0, -1, "", "")
finishedChannel <- true
}()
select {
case <-finishedChannel:
if err == nil {
t.Fatal("Error is nil, download should have failed")
}
case <-time.After(time.Second * 160):
// 120 seconds for warmup, 30 seconds for download
t.Fatal("Maximum downloading time reach, download should have failed")
}
// Close the channel to allow the download to complete
close(channel)
// Make sure the errors are correct
assert.NotNil(t, err)
// Check we have an overlapping PelicanError type
_, ok := err.(*error_codes.PelicanError)
if ok {
var slowTransferError *SlowTransferError
assert.Contains(t, err.Error(), "Transfer.SlowTransfer Error: Error code 6002:")
// Check we successfully wrapped an already defined SlowTransferError
assert.True(t, errors.As(err, &slowTransferError))
} else {
t.Fatal("Error is not of type PelicanError")
}
}
// Test stopped transfer
func TestStoppedTransfer(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
os.Setenv("http_proxy", "http://proxy.edu:3128")
t.Cleanup(func() {
require.NoError(t, os.Unsetenv("http_proxy"))
})
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// Adjust down the timeouts
test_utils.InitClient(t, map[string]any{
"Client.StoppedTransferTimeout": "2s",
"Client.SlowTransferRampupTime": "100s",
})
channel := make(chan bool)
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "HEAD" {
w.Header().Add("Content-Length", "102400")
w.WriteHeader(http.StatusOK)
return
}
buffer := make([]byte, 1024*100)
for {
select {
case <-channel:
return
default:
_, err := w.Write(buffer)
if err != nil {
return
}
w.(http.Flusher).Flush()
time.Sleep(1 * time.Second)
buffer = make([]byte, 0)
}
}
}))
defer svr.CloseClientConnections()
defer svr.Close()
testCache := svr.URL
transfers := generateTransferDetails(testCache, transferDetailsOptions{false, ""})
assert.Equal(t, 2, len(transfers))
assert.Equal(t, svr.URL, transfers[0].Url.String())
finishedChannel := make(chan bool)
var err error
go func() {
fname := filepath.Join(t.TempDir(), "test.txt")
var writer *os.File
writer, err = os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
_, _, _, _, err = downloadHTTP(ctx, nil, nil, transfers[0], fname, writer, 0, -1, "", "")
finishedChannel <- true
}()
select {
case <-finishedChannel:
if err == nil {
t.Fatal("Download should have failed")
}
case <-time.After(time.Second * 150):
t.Fatal("Download should have failed")
}
// Close the channel to allow the download to complete
close(channel)
// Make sure the errors are correct
assert.NotNil(t, err)
// Check that it's wrapped in a PelicanError and contains StoppedTransferError
assert.True(t, errors.Is(err, &StoppedTransferError{}), "Error should contain StoppedTransferError")
// Check that it's wrapped in a PelicanError with the correct code
var pe *error_codes.PelicanError
require.True(t, errors.As(err, &pe), "Error should be wrapped in PelicanError")
assert.Equal(t, 6001, pe.Code(), "Should be Transfer.StoppedTransfer error code")
assert.Equal(t, "Transfer.StoppedTransfer", pe.ErrorType(), "Should be Transfer.StoppedTransfer error type")
assert.True(t, pe.IsRetryable(), "StoppedTransfer should be retryable")
assert.True(t, IsRetryable(err))
}
// Test connection error
func TestConnectionError(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, _, _ := test_utils.TestContext(context.Background(), t)
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("dialClosedPort: Listen failed: %v", err)
}
addr := l.Addr().String()
l.Close()
fname := filepath.Join(t.TempDir(), "test.txt")
writer, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
_, _, _, _, err = downloadHTTP(ctx, nil, nil,
transferAttemptDetails{Url: &url.URL{Host: addr, Scheme: "http"}, Proxy: false},
fname, writer, 0, -1, "", "",
)
// downloadHTTP returns unwrapped ConnectionSetupError; wrapping happens in the download loop
var cse *ConnectionSetupError
require.True(t, errors.As(err, &cse), "Error should be a ConnectionSetupError")
// Verify that when wrapped, it has the correct properties (simulating download loop behavior)
wrappedErr := error_codes.NewContact_ConnectionSetupError(cse)
var pe *error_codes.PelicanError
require.True(t, errors.As(wrappedErr, &pe), "Wrapped error should be a PelicanError")
// Use the generated error code instead of hardcoding to make the test robust to code changes
expectedErr := error_codes.NewContact_ConnectionSetupError(errors.New("test"))
assert.Equal(t, expectedErr.Code(), pe.Code(), "Should map to Contact.ConnectionSetup error code")
assert.Equal(t, expectedErr.ErrorType(), pe.ErrorType(), "Should map to Contact.ConnectionSetup error type")
assert.Equal(t, expectedErr.IsRetryable(), pe.IsRetryable(), "Connection setup failures should be retryable")
}
func TestAllocateMemoryError(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// Create a custom transport that returns ENOMEM to simulate the actual error condition
// In production, this happens at handle_http.go:2780-2784 when client.Do returns ENOMEM
enomemTransport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return nil, syscall.Errno(syscall.ENOMEM)
},
}
// Create an HTTP client with the custom transport
client := &http.Client{
Transport: enomemTransport,
Timeout: time.Second,
}
// Create a request that will trigger the ENOMEM error
req, err := http.NewRequestWithContext(ctx, "GET", "http://example.com/test", nil)
require.NoError(t, err)
// Call client.Do which should return ENOMEM
_, err = client.Do(req)
require.Error(t, err, "Should have an error from ENOMEM")
// Verify that the error contains ENOMEM
var sysErr syscall.Errno
require.True(t, errors.As(err, &sysErr), "Error should be a syscall.Errno")
assert.Equal(t, syscall.ENOMEM, sysErr, "Error should be ENOMEM")
}
func TestNetworkResetError(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// Set up an HTTP server that hijacks the connection and resets it during transfer
// This simulates ECONNRESET/EPIPE during transfer
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Hijack the connection so we can control when to reset it
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, bufrw, err := hj.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer conn.Close()
// Send HTTP response headers
_, _ = bufrw.WriteString("HTTP/1.1 200 OK\r\n")
_, _ = bufrw.WriteString("Content-Length: 1000\r\n")
_, _ = bufrw.WriteString("\r\n")
_ = bufrw.Flush()
// Send some data to ensure client starts reading
_, _ = conn.Write([]byte("some data"))
_ = conn.(*net.TCPConn).SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
// Give the client time to start reading the response body
time.Sleep(100 * time.Millisecond)
// Force TCP RST by setting SO_LINGER to 0
// This causes the connection to send RST instead of FIN when closed
if tcpConn, ok := conn.(*net.TCPConn); ok {
_ = tcpConn.SetLinger(0) // Set linger to 0 to send RST on close
rawConn, err := tcpConn.SyscallConn()
if err == nil {
_ = rawConn.Control(func(fd uintptr) {
// Also set SO_LINGER via syscall to ensure RST
var linger syscall.Linger
linger.Onoff = 1
linger.Linger = 0
_ = syscall.SetsockoptLinger(int(fd), syscall.SOL_SOCKET, syscall.SO_LINGER, &linger)
})
}
}
// Close connection with RST (due to SO_LINGER) while client is reading
conn.Close()
}))
defer svr.Close()
serverAddr := strings.TrimPrefix(svr.URL, "http://")
fname := filepath.Join(t.TempDir(), "test.txt")
writer, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
// Call downloadHTTP which should trigger NetworkResetError when connection is reset
_, _, _, _, err = downloadHTTP(ctx, nil, nil,
transferAttemptDetails{Url: &url.URL{Scheme: "http", Host: serverAddr}, Proxy: false},
fname, writer, 0, -1, "", "",
)
// The error should be wrapped as Contact.ConnectionReset in the download loop
// We need to check the TransferAttemptError to see the wrapped error
// But downloadHTTP returns the raw error, so we need to simulate the wrapping
require.Error(t, err, "Should have an error from connection reset")
// Check if it's a syscall error that would trigger NetworkResetError
// The download loop checks for ECONNRESET/EPIPE at using errors.Is
// errors.Is should work even if the error is wrapped (through ConnectionSetupError -> OpError -> ECONNRESET)
require.True(t, errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE),
"Error should be ECONNRESET or EPIPE (possibly wrapped), got: %T, error: %v", err, err)
}
func TestProxyConnectionError(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// Create a custom transport that simulates a proxy connection failure
// In production, this happens when http.Client.Do() tries to connect to a proxy
// and the connection fails (e.g., proxy is unreachable)
proxyAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:3128")
require.NoError(t, err)
proxyConnectionErr := &net.OpError{
Op: "proxyconnect",
Net: "tcp",
Addr: proxyAddr,
Err: errors.New("connection refused"),
}
// Create a custom transport that returns the proxy connection error
customTransport := &http.Transport{
Proxy: func(*http.Request) (*url.URL, error) {
// Return a proxy URL to force proxy usage
return url.Parse("http://127.0.0.1:3128")
},
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
// When the client tries to dial the proxy, return the proxy connection error
if addr == "127.0.0.1:3128" {
return nil, proxyConnectionErr
}
// For other addresses, use default dialer
var d net.Dialer
return d.DialContext(ctx, network, addr)
},
}
// Create an HTTP client with the custom transport
client := &http.Client{
Transport: customTransport,
Timeout: time.Second,
}
// Create a request that will trigger the proxy connection
req, err := http.NewRequestWithContext(ctx, "GET", "http://example.com/test", nil)
require.NoError(t, err)
// Call client.Do which should return the proxy connection error
_, err = client.Do(req)
require.Error(t, err, "Should have an error from proxy connection failure")
// Verify that the error is a *net.OpError with Op == "proxyconnect"
// The error might be wrapped in url.Error
var ope *net.OpError
var ue *url.Error
if errors.As(err, &ue) {
innerErr := ue.Unwrap()
if innerOpe, ok := innerErr.(*net.OpError); ok {
ope = innerOpe
}
}
if ope == nil {
require.True(t, errors.As(err, &ope), "Error should be a *net.OpError, got: %T, error: %v", err, err)
}
assert.Equal(t, "proxyconnect", ope.Op, "Error should be a proxyconnect operation")
// Verify that when wrapped (as it would be in the download loop), it has the correct properties
proxyErr := &ConnectionSetupError{URL: "http://example.com/test", Err: err}
wrappedErr := error_codes.NewContact_ConnectionSetupError(proxyErr)
var pe *error_codes.PelicanError
require.True(t, errors.As(wrappedErr, &pe), "Wrapped error should be a PelicanError")
// Use the generated error code instead of hardcoding to make the test robust to code changes
expectedErr := error_codes.NewContact_ConnectionSetupError(errors.New("test"))
assert.Equal(t, expectedErr.Code(), pe.Code(), "Should map to Contact.ConnectionSetup error code")
assert.Equal(t, expectedErr.ErrorType(), pe.ErrorType(), "Should map to Contact.ConnectionSetup error type")
assert.Equal(t, expectedErr.IsRetryable(), pe.IsRetryable(), "Proxy connection failures should be retryable")
}
func TestTrailerError(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// Set up an HTTP server that returns an error trailer
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Trailer", "X-Transfer-Status")
w.Header().Set("X-Transfer-Status", "500: Unable to read test.txt; input/output error")
chunkedWriter := httputil.NewChunkedWriter(w)
defer chunkedWriter.Close()
_, err := chunkedWriter.Write([]byte("Test data"))
if err != nil {
t.Fatalf("Error writing to chunked writer: %v", err)
}
}))
defer svr.Close()
os.Setenv("http_proxy", "http://proxy.edu:3128")
t.Cleanup(func() {
require.NoError(t, os.Unsetenv("http_proxy"))
})
testCache := svr.URL
transfers := generateTransferDetails(testCache, transferDetailsOptions{false, ""})
assert.Equal(t, 2, len(transfers))
assert.Equal(t, svr.URL, transfers[0].Url.String())
// Call DownloadHTTP and check if the error is returned correctly
fname := filepath.Join(t.TempDir(), "test.txt")
writer, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
_, _, _, _, err = downloadHTTP(ctx, nil, nil, transfers[0], fname, writer, 0, -1, "", "")
assert.NotNil(t, err)
// Check that it's wrapped in a PelicanError
var pe *error_codes.PelicanError
require.True(t, errors.As(err, &pe), "Error should be wrapped in PelicanError")
assert.Equal(t, 6000, pe.Code(), "Should be Transfer error code")
assert.Equal(t, "Transfer", pe.ErrorType(), "Should be Transfer error type")
// Check the underlying error message
assert.Contains(t, pe.Unwrap().Error(), "download error after server response started: Unable to read test.txt; input/output error")
}
func TestUploadZeroLengthFile(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//t.Logf("%s", dump)
assert.Equal(t, "PUT", r.Method, "Not PUT Method")
assert.Equal(t, int64(0), r.ContentLength, "ContentLength should be 0")
}))
defer ts.Close()
reader := bytes.NewReader([]byte{})
request, err := http.NewRequest("PUT", ts.URL, reader)
if err != nil {
assert.NoError(t, err)
}
request.Header.Set("Authorization", "Bearer test")
errorChan := make(chan error, 1)
responseChan := make(chan *http.Response)
go runPut(request, responseChan, errorChan, false)
select {
case err := <-errorChan:
assert.NoError(t, err)
case response := <-responseChan:
assert.Equal(t, http.StatusOK, response.StatusCode)
case <-time.After(time.Second * 2):
assert.Fail(t, "Timeout while waiting for response")
}
}
func TestFailedUpload(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//t.Logf("%s", dump)
assert.Equal(t, "PUT", r.Method, "Not PUT Method")
w.WriteHeader(http.StatusInternalServerError)
_, err := w.Write([]byte("Error"))
assert.NoError(t, err)
}))
defer ts.Close()
reader := strings.NewReader("test")
request, err := http.NewRequest("PUT", ts.URL, reader)
if err != nil {
assert.NoError(t, err)
}
request.Header.Set("Authorization", "Bearer test")
errorChan := make(chan error, 1)
responseChan := make(chan *http.Response)
go runPut(request, responseChan, errorChan, false)
select {
case err := <-errorChan:
assert.Error(t, err)
case response := <-responseChan:
assert.Equal(t, http.StatusInternalServerError, response.StatusCode)
case <-time.After(time.Second * 2):
assert.Fail(t, "Timeout while waiting for response")
}
}
func TestUploadLocalFileNotFound(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
test_utils.InitClient(t, map[string]any{})
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Return 404 for PROPFIND (stat) requests so upload doesn't think file exists
if r.Method == "PROPFIND" {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
tsURL, err := url.Parse(ts.URL)
require.NoError(t, err)
transfer := &transferFile{
ctx: context.Background(),
localPath: "/nonexistent/path/to/file.txt",
remoteURL: tsURL,
xferType: transferTypeUpload,
job: &TransferJob{
remoteURL: &pelican_url.PelicanURL{
Scheme: "pelican://",
Host: tsURL.Host,
Path: "/test/file.txt",
},
dirResp: server_structs.DirectorResponse{
XPelNsHdr: server_structs.XPelNs{
CollectionsUrl: tsURL, // Point to our mock server
},
},
},
callback: nil,
attempts: []transferAttemptDetails{
{
Url: tsURL,
Proxy: false,
},
},
}
transferResult, err := uploadObject(transfer)
require.Error(t, err) // uploadObject returns error when local stat fails
require.Error(t, transferResult.Error) // And the result also contains the error
// Verify it's wrapped in Parameter.FileNotFound PelicanError
var pe *error_codes.PelicanError
require.True(t, errors.As(err, &pe), "Error should be wrapped in PelicanError")
assert.Equal(t, 1011, pe.Code(), "Should be Parameter.FileNotFound error code")
assert.Equal(t, "Parameter.FileNotFound", pe.ErrorType(), "Should be Parameter.FileNotFound error type")
assert.False(t, pe.IsRetryable(), "Local file not found should not be retryable")
// Verify the error message
assert.Contains(t, err.Error(), "stat /nonexistent/path/to/file.txt: no such file or directory")
}
func TestSortAttempts(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, cancel, _ := test_utils.TestContext(context.Background(), t)
neverRespond := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
select {
case <-ctx.Done():
case <-ticker.C:
}
})
alwaysRespond := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.Header().Set("Content-Length", "1")
w.Header().Set("Content-Range", "bytes 0-0/42")
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("A"))
require.NoError(t, err)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
})
svr1 := httptest.NewServer(neverRespond)
defer svr1.Close()
url1, err := url.Parse(svr1.URL)
require.NoError(t, err)
attempt1 := transferAttemptDetails{Url: url1}
svr2 := httptest.NewServer(alwaysRespond)
defer svr2.Close()
url2, err := url.Parse(svr2.URL)
require.NoError(t, err)
attempt2 := transferAttemptDetails{Url: url2}
svr3 := httptest.NewServer(alwaysRespond)
defer svr3.Close()
url3, err := url.Parse(svr3.URL)
require.NoError(t, err)
attempt3 := transferAttemptDetails{Url: url3}
defer cancel()
token := NewTokenGenerator(nil, nil, config.TokenSharedRead, false)
token.SetToken("aaa")
size, results := sortAttempts(ctx, "/path", []transferAttemptDetails{attempt1, attempt2, attempt3}, token)
assert.Equal(t, int64(42), size)
assert.Equal(t, svr2.URL, results[0].Url.String())
assert.Equal(t, svr3.URL, results[1].Url.String())
assert.Equal(t, svr1.URL, results[2].Url.String())
size, results = sortAttempts(ctx, "/path", []transferAttemptDetails{attempt2, attempt3, attempt1}, token)
assert.Equal(t, int64(42), size)
assert.Equal(t, svr2.URL, results[0].Url.String())
assert.Equal(t, svr3.URL, results[1].Url.String())
assert.Equal(t, svr1.URL, results[2].Url.String())
size, results = sortAttempts(ctx, "/path", []transferAttemptDetails{attempt1, attempt1}, token)
assert.Equal(t, int64(-1), size)
assert.Equal(t, svr1.URL, results[0].Url.String())
assert.Equal(t, svr1.URL, results[1].Url.String())
size, results = sortAttempts(ctx, "/path", []transferAttemptDetails{attempt2, attempt3}, token)
assert.Equal(t, int64(42), size)
assert.Equal(t, svr2.URL, results[0].Url.String())
assert.Equal(t, svr3.URL, results[1].Url.String())
}
func TestTimeoutHeaderSetForDownload(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
test_utils.InitClient(t, map[string]any{
"Transport.ResponseHeaderTimeout": 10 * time.Second,
})
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// We have this flag because our server will get a few requests throughout its lifetime and the other
// requests do not contain the X-Pelican-Timeout header
timeoutHeaderFound := false
// Create a mock server to download from
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the "X-Pelican-Timeout" header is set
if !timeoutHeaderFound {
if r.Header.Get("X-Pelican-Timeout") == "" {
t.Error("X-Pelican-Timeout header is not set")
}
assert.Equal(t, "9.5s", r.Header.Get("X-Pelican-Timeout"))
timeoutHeaderFound = true
}
}))
defer server.Close()
serverURL, err := url.Parse(server.URL)
assert.NoError(t, err)
fname := filepath.Join(t.TempDir(), "test.txt")
writer, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
_, _, _, _, err = downloadHTTP(ctx, nil, nil, transferAttemptDetails{Url: serverURL, Proxy: false},
fname, writer, 0, -1, "", "",
)
assert.NoError(t, err)
server_utils.ResetTestState()
}
func TestJobIdHeaderSetForDownload(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
test_utils.InitClient(t, map[string]any{})
// Create a test .job.ad file
jobAdFile, err := os.CreateTemp("", ".job.ad")
assert.NoError(t, err)
// Write the job ad to the file
_, err = jobAdFile.WriteString("GlobalJobId = \"12345\"")
assert.NoError(t, err)
jobAdFile.Close()
os.Setenv("_CONDOR_JOB_AD", jobAdFile.Name())
jobAdOnce = sync.Once{}
ctx, _, _ := test_utils.TestContext(context.Background(), t)
// We have this flag because our server will get a few requests throughout its lifetime and the other
// requests do not contain the X-Pelican-Timeout header
timeoutHeaderFound := false
// Create a mock server to download from
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the "X-Pelican-Timeout" header is set
if !timeoutHeaderFound {
if r.Header.Get("X-Pelican-JobId") == "" {
t.Error("X-Pelican-JobId header is not set")
}
assert.Equal(t, "12345", r.Header.Get("X-Pelican-JobId"))
timeoutHeaderFound = true
}
}))
defer server.Close()
serverURL, err := url.Parse(server.URL)
assert.NoError(t, err)
fname := filepath.Join(t.TempDir(), "test.txt")
writer, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
_, _, _, _, err = downloadHTTP(ctx, nil, nil, transferAttemptDetails{Url: serverURL, Proxy: false},
fname, writer, 0, -1, "", "",
)
assert.NoError(t, err)
server_utils.ResetTestState()
os.Unsetenv("_CONDOR_JOB_AD")
}
// Server test object for testing user agent
type (
server_test struct {
server *httptest.Server
user_agent *string
}
)
// Test to ensure the user-agent header is being updating in the request made within DownloadHTTP()
func TestProjInUserAgent(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
ctx, _, _ := test_utils.TestContext(context.Background(), t)
server_test := server_test{}
// Create a mock server to download from
server_test.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Note: we check for this HEAD request because within DownloadHTTP() we make a HEAD request to get the content length
// This request is a different user-agent header (and different request) so we need to ignore it so server_test.user_agent is not overwritten
if r.Method == "HEAD" {
w.WriteHeader(http.StatusNoContent)
return
}
userAgent := r.UserAgent()
server_test.user_agent = &userAgent
}))
defer server_test.server.Close()
defer server_test.server.CloseClientConnections()
serverURL, err := url.Parse(server_test.server.URL)
assert.NoError(t, err)
fname := filepath.Join(t.TempDir(), "test.txt")
writer, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
assert.NoError(t, err)
defer writer.Close()
_, _, _, _, err = downloadHTTP(ctx, nil, nil, transferAttemptDetails{Url: serverURL, Proxy: false},
fname, writer, 0, -1, "", "test")
assert.NoError(t, err)
// Test the user-agent header is what we expect it to be
assert.Equal(t, "pelican-client/"+config.GetVersion()+" project/test", *server_test.user_agent)
}
// The test should prove that the function getObjectServersToTry returns the correct number of servers,
// and that any duplicates are removed
func TestGetObjectServersToTry(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
sortedServers := []string{
"http://cache-1.com", // set an HTTP scheme to check that it's switched to https
"https://cache-2.com",
"https://cache-2.com", // make sure duplicates are removed
"https://cache-3.com",
"https://cache-4.com",
"https://cache-5.com",
}
t.Run("RequiredTokenTriggersHTTPS", func(t *testing.T) {
directorResponse := server_structs.DirectorResponse{
XPelNsHdr: server_structs.XPelNs{
RequireToken: true,
},
}
job := &TransferJob{
dirResp: directorResponse,
}
transfers := getObjectServersToTry(sortedServers, job, 3, "")
// Check that there are no duplicates in the result
cacheSet := make(map[string]bool)
for _, transfer := range transfers {
if cacheSet[transfer.Url.String()] {
t.Errorf("Found duplicate cache: %v", transfer.Url.String())
}
cacheSet[transfer.Url.String()] = true
}
// Verify we got the correct caches in our transfer attempt details
require.Len(t, transfers, 3)
assert.Equal(t, "https://cache-1.com", transfers[0].Url.String())
assert.Equal(t, "https://cache-2.com", transfers[1].Url.String())
assert.Equal(t, "https://cache-3.com", transfers[2].Url.String())
})
t.Run("NoRequiredTokenPreservesHTTP", func(t *testing.T) {
directorResponse := server_structs.DirectorResponse{
XPelNsHdr: server_structs.XPelNs{
RequireToken: false,
},
}
job := &TransferJob{
dirResp: directorResponse,
}
transfers := getObjectServersToTry(sortedServers, job, 3, "")
cacheSet := make(map[string]bool)
for _, transfer := range transfers {
if cacheSet[transfer.Url.String()] {
t.Errorf("Found duplicate cache: %v", transfer.Url.String())
}
cacheSet[transfer.Url.String()] = true
}
require.Len(t, transfers, 3)
assert.Equal(t, "http://cache-1.com", transfers[0].Url.String())
assert.Equal(t, "https://cache-2.com", transfers[1].Url.String())
assert.Equal(t, "https://cache-3.com", transfers[2].Url.String())
})
}
// Test that the project name is correctly extracted from the job ad file
func TestSearchJobAd(t *testing.T) {
t.Cleanup(test_utils.SetupTestLogging(t))
// Create a temporary file
tempFile, err := os.CreateTemp("", "test")