| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"context" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"net" |
| 10 |
"net/http" |
| 11 |
"net/http/httptest" |
| 12 |
"net/url" |
| 13 |
"os" |
| 14 |
"regexp" |
| 15 |
"strconv" |
| 16 |
"strings" |
| 17 |
"sync/atomic" |
| 18 |
"testing" |
| 19 |
"time" |
| 20 |
|
| 21 |
minio "github.com/minio/minio-go/v6" |
| 22 |
"github.com/minio/minio-go/v6/pkg/credentials" |
| 23 |
"github.com/stretchr/testify/require" |
| 24 |
"golang.org/x/sync/errgroup" |
| 25 |
) |
| 26 |
|
| 27 |
type MockCredProvider struct { |
| 28 |
} |
| 29 |
|
| 30 |
func (p *MockCredProvider) Retrieve() (credentials.Value, error) { |
| 31 |
return credentials.Value{ |
| 32 |
AccessKeyID: "mainone", |
| 33 |
SecretAccessKey: "thisiskeytrustmedude", |
| 34 |
SessionToken: "youdontneedtoken", |
| 35 |
SignerType: credentials.SignatureDefault, |
| 36 |
}, nil |
| 37 |
} |
| 38 |
|
| 39 |
func (p *MockCredProvider) IsExpired() bool { |
| 40 |
return false |
| 41 |
} |
| 42 |
|
| 43 |
func response(request *http.Request, headers http.Header, statusCode int, body string) *http.Response { |
| 44 |
return &http.Response{ |
| 45 |
StatusCode: statusCode, |
| 46 |
ProtoMajor: 1, |
| 47 |
ProtoMinor: 0, |
| 48 |
Request: request, |
| 49 |
Body: io.NopCloser(strings.NewReader(body)), |
| 50 |
Header: headers, |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
// s3ErrMode describes how the fake S3 server should mishandle an object request. |
| 55 |
type s3ErrMode int |
| 56 |
|
| 57 |
const ( |
| 58 |
s3ErrNone s3ErrMode = iota // serve the object normally |
| 59 |
s3ErrRST // send half the body, then force a TCP RST (transport error) |
| 60 |
s3ErrCorruptBody // serve a complete, well-formed response whose body is truncated |
| 61 |
) |
| 62 |
|
| 63 |
func sendObject(conn *net.TCPConn, request *http.Request, filePath string, mode s3ErrMode) error { |
| 64 |
file, err := os.Open(filePath) |
| 65 |
if err != nil { |
| 66 |
if os.IsNotExist(err) { |
| 67 |
resp := response(request, http.Header{}, 404, "") |
| 68 |
resp.Write(conn) |
| 69 |
} else { |
| 70 |
resp := response(request, http.Header{}, 500, err.Error()) |
| 71 |
resp.Write(conn) |
| 72 |
} |
| 73 |
return nil |
| 74 |
} |
| 75 |
defer file.Close() |
| 76 |
|
| 77 |
stat, err := file.Stat() |
| 78 |
if err != nil { |
| 79 |
resp := response(request, http.Header{}, 500, err.Error()) |
| 80 |
resp.Write(conn) |
| 81 |
return nil |
| 82 |
} |
| 83 |
headers := http.Header{} |
| 84 |
headers.Add("Last-Modified", stat.ModTime().Format(http.TimeFormat)) |
| 85 |
headers.Add("Content-Type", "application/octet-stream") |
| 86 |
|
| 87 |
switch mode { |
| 88 |
case s3ErrRST: |
| 89 |
headers.Add("Content-Length", strconv.FormatInt(stat.Size(), 10)) |
| 90 |
if _, err := io.WriteString(conn, "HTTP/1.0 200 OK\r\n"); err != nil { |
| 91 |
return err |
| 92 |
} |
| 93 |
if err := headers.Write(conn); err != nil { |
| 94 |
return err |
| 95 |
} |
| 96 |
if _, err := io.WriteString(conn, "\r\n"); err != nil { |
| 97 |
return err |
| 98 |
} |
| 99 |
if _, err := io.CopyN(conn, file, stat.Size()/2); err != nil { |
| 100 |
return err |
| 101 |
} |
| 102 |
// it seems that setting SO_LINGER to 0 and calling close() on the socket forces server to |
| 103 |
// send RST TCP packet, which we will use to emulate network error |
| 104 |
if err := conn.SetLinger(0); err != nil { |
| 105 |
return err |
| 106 |
} |
| 107 |
if err := conn.Close(); err != nil { |
| 108 |
return err |
| 109 |
} |
| 110 |
case s3ErrCorruptBody: |
| 111 |
// Serve a complete, well-formed HTTP response whose Content-Length matches |
| 112 |
// the bytes actually written, but only write the first half of the file. The |
| 113 |
// client reads it cleanly (no transport error), but the truncated chunk data |
| 114 |
// fails to decompress/validate - the scenario reported in issue #334. |
| 115 |
half := stat.Size() / 2 |
| 116 |
headers.Add("Content-Length", strconv.FormatInt(half, 10)) |
| 117 |
if _, err := io.WriteString(conn, "HTTP/1.0 200 OK\r\n"); err != nil { |
| 118 |
return err |
| 119 |
} |
| 120 |
if err := headers.Write(conn); err != nil { |
| 121 |
return err |
| 122 |
} |
| 123 |
if _, err := io.WriteString(conn, "\r\n"); err != nil { |
| 124 |
return err |
| 125 |
} |
| 126 |
if _, err := io.CopyN(conn, file, half); err != nil { |
| 127 |
return err |
| 128 |
} |
| 129 |
default: |
| 130 |
headers.Add("Content-Length", strconv.FormatInt(stat.Size(), 10)) |
| 131 |
resp := http.Response{ |
| 132 |
StatusCode: 200, |
| 133 |
ProtoMajor: 1, |
| 134 |
ProtoMinor: 0, |
| 135 |
Request: request, |
| 136 |
Body: file, |
| 137 |
Header: headers, |
| 138 |
} |
| 139 |
resp.Write(conn) |
| 140 |
} |
| 141 |
return nil |
| 142 |
} |
| 143 |
|
| 144 |
func handleGetObjectRequest(conn *net.TCPConn, bucket, store string, errorMode s3ErrMode, errorTimes *int, errorTimesLimit int) error { |
| 145 |
defer conn.Close() |
| 146 |
objectGetMatcher := regexp.MustCompile(`^/` + bucket + `/(.+)$`) |
| 147 |
|
| 148 |
reader := bufio.NewReader(conn) |
| 149 |
request, err := http.ReadRequest(reader) |
| 150 |
if err != nil { |
| 151 |
return err |
| 152 |
} |
| 153 |
|
| 154 |
matches := objectGetMatcher.FindStringSubmatch(request.URL.Path) |
| 155 |
if matches != nil { |
| 156 |
mode := s3ErrNone |
| 157 |
if *errorTimes < errorTimesLimit { |
| 158 |
mode = errorMode |
| 159 |
} |
| 160 |
err = sendObject(conn, request, store+"/"+matches[1], mode) |
| 161 |
(*errorTimes)++ |
| 162 |
} else { |
| 163 |
resp := response(request, http.Header{}, 400, "") |
| 164 |
resp.Write(conn) |
| 165 |
} |
| 166 |
return err |
| 167 |
} |
| 168 |
|
| 169 |
// Run S3 server that can respond objects from `store`. The first `errorTimesLimit` |
| 170 |
// object requests are mishandled according to `errorMode` (e.g. truncated body or |
| 171 |
// forced TCP reset); subsequent requests are served normally. |
| 172 |
func getTcpS3Server(t *testing.T, group *errgroup.Group, ctx context.Context, bucket, store string, errorMode s3ErrMode, errorTimesLimit int) net.Listener { |
| 173 |
var errorTimes int |
| 174 |
// using localhost + resolver let us work on hosts that support only ipv6 or only ipv4 |
| 175 |
ip, err := net.DefaultResolver.LookupIP(ctx, "ip", "localhost") |
| 176 |
require.NoError(t, err) |
| 177 |
require.NotEmpty(t, ip, "cannot resolve localhost") |
| 178 |
|
| 179 |
listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: ip[0], Port: 0}) |
| 180 |
require.NoError(t, err) |
| 181 |
|
| 182 |
group.Go(func() error { |
| 183 |
<-ctx.Done() |
| 184 |
return listener.Close() |
| 185 |
}) |
| 186 |
|
| 187 |
group.Go(func() error { |
| 188 |
for { |
| 189 |
conn, err := listener.AcceptTCP() |
| 190 |
|
| 191 |
if err != nil { |
| 192 |
if errors.Is(ctx.Err(), context.Canceled) { |
| 193 |
return nil |
| 194 |
} |
| 195 |
return err |
| 196 |
} |
| 197 |
err = handleGetObjectRequest(conn, bucket, store, errorMode, &errorTimes, errorTimesLimit) |
| 198 |
if err != nil { |
| 199 |
return err |
| 200 |
} |
| 201 |
} |
| 202 |
}) |
| 203 |
return listener |
| 204 |
} |
| 205 |
|
| 206 |
func TestS3StoreGetChunk(t *testing.T) { |
| 207 |
chunkId, err := ChunkIDFromString("dda036db05bc2b99b6b9303d28496000c34b246457ae4bbf00fe625b5cabd7cd") |
| 208 |
require.NoError(t, err) |
| 209 |
location := "vertucon-central" |
| 210 |
bucket := "doomsdaydevices" |
| 211 |
provider := MockCredProvider{} |
| 212 |
|
| 213 |
t.Run("no_error", func(t *testing.T) { |
| 214 |
// Just try to get chunk from well-behaved S3 server, no errors expected |
| 215 |
ctx, cancel := context.WithCancel(context.Background()) |
| 216 |
group, gCtx := errgroup.WithContext(ctx) |
| 217 |
|
| 218 |
ln := getTcpS3Server(t, group, ctx, bucket, "cmd/desync/testdata", s3ErrNone, 0) |
| 219 |
|
| 220 |
group.Go(func() error { |
| 221 |
defer cancel() |
| 222 |
endpoint := url.URL{Scheme: "s3+http", Host: ln.Addr().String(), Path: "/" + bucket + "/blob1.store/"} |
| 223 |
store, err := NewS3Store(&endpoint, credentials.New(&provider), location, StoreOptions{}, minio.BucketLookupAuto) |
| 224 |
if err != nil { |
| 225 |
return err |
| 226 |
} |
| 227 |
|
| 228 |
c := make(chan error) |
| 229 |
go func() { |
| 230 |
chunk, err := store.GetChunk(chunkId) |
| 231 |
if err != nil { |
| 232 |
c <- err |
| 233 |
return |
| 234 |
} |
| 235 |
if chunk.ID() != chunkId { |
| 236 |
c <- fmt.Errorf("got chunk with id equal to %q, expected %q", chunk.ID(), chunkId) |
| 237 |
return |
| 238 |
} |
| 239 |
c <- nil |
| 240 |
}() |
| 241 |
select { |
| 242 |
case <-gCtx.Done(): |
| 243 |
return nil |
| 244 |
case err = <-c: |
| 245 |
return err |
| 246 |
} |
| 247 |
}) |
| 248 |
|
| 249 |
require.NoError(t, group.Wait()) |
| 250 |
}) |
| 251 |
|
| 252 |
t.Run("fail", func(t *testing.T) { |
| 253 |
// Emulate network error - after sending half of the file S3 server sends RST to the client |
| 254 |
// We don't have retries here so we expect that GetChunk() will return error |
| 255 |
ctx, cancel := context.WithCancel(context.Background()) |
| 256 |
group, gCtx := errgroup.WithContext(ctx) |
| 257 |
|
| 258 |
ln := getTcpS3Server(t, group, ctx, bucket, "cmd/desync/testdata", s3ErrRST, 1) |
| 259 |
|
| 260 |
group.Go(func() error { |
| 261 |
defer cancel() |
| 262 |
endpoint := url.URL{Scheme: "s3+http", Host: ln.Addr().String(), Path: "/" + bucket + "/blob1.store/"} |
| 263 |
store, err := NewS3Store(&endpoint, credentials.New(&provider), location, StoreOptions{}, minio.BucketLookupAuto) |
| 264 |
if err != nil { |
| 265 |
return err |
| 266 |
} |
| 267 |
|
| 268 |
c := make(chan error) |
| 269 |
go func() { |
| 270 |
_, err := store.GetChunk(chunkId) |
| 271 |
opError := &net.OpError{} |
| 272 |
if err == nil || !errors.As(err, &opError) { |
| 273 |
c <- fmt.Errorf("expected GetChunk to fail with a net.OpError, got %v", err) |
| 274 |
return |
| 275 |
} |
| 276 |
c <- nil |
| 277 |
}() |
| 278 |
select { |
| 279 |
case <-gCtx.Done(): |
| 280 |
return nil |
| 281 |
case err = <-c: |
| 282 |
return err |
| 283 |
} |
| 284 |
}) |
| 285 |
|
| 286 |
require.NoError(t, group.Wait()) |
| 287 |
}) |
| 288 |
|
| 289 |
t.Run("recover", func(t *testing.T) { |
| 290 |
// Emulate network error - after sending half of the file S3 server sends RST to the client |
| 291 |
// We have retries here so we expect that GetChunk() will not return error |
| 292 |
ctx, cancel := context.WithCancel(context.Background()) |
| 293 |
group, gCtx := errgroup.WithContext(ctx) |
| 294 |
|
| 295 |
ln := getTcpS3Server(t, group, ctx, bucket, "cmd/desync/testdata", s3ErrRST, 1) |
| 296 |
|
| 297 |
group.Go(func() error { |
| 298 |
defer cancel() |
| 299 |
endpoint := url.URL{Scheme: "s3+http", Host: ln.Addr().String(), Path: "/" + bucket + "/blob1.store/"} |
| 300 |
store, err := NewS3Store(&endpoint, credentials.New(&provider), location, StoreOptions{ErrorRetry: 1}, minio.BucketLookupAuto) |
| 301 |
if err != nil { |
| 302 |
return err |
| 303 |
} |
| 304 |
|
| 305 |
c := make(chan error) |
| 306 |
go func() { |
| 307 |
chunk, err := store.GetChunk(chunkId) |
| 308 |
if err != nil { |
| 309 |
c <- err |
| 310 |
return |
| 311 |
} |
| 312 |
if chunk.ID() != chunkId { |
| 313 |
c <- fmt.Errorf("got chunk with id equal to %q, expected %q", chunk.ID(), chunkId) |
| 314 |
return |
| 315 |
} |
| 316 |
c <- nil |
| 317 |
}() |
| 318 |
select { |
| 319 |
case <-gCtx.Done(): |
| 320 |
return nil |
| 321 |
case err = <-c: |
| 322 |
return err |
| 323 |
} |
| 324 |
}) |
| 325 |
|
| 326 |
require.NoError(t, group.Wait()) |
| 327 |
}) |
| 328 |
|
| 329 |
t.Run("corrupt_body_fail", func(t *testing.T) { |
| 330 |
// Server returns a complete, well-formed response with a truncated body, so |
| 331 |
// the chunk data fails to decompress/validate (issue #334). With no retries |
| 332 |
// configured GetChunk() must return that error - and it must carry the |
| 333 |
// underlying decode failure, not the bogus "hash 0000..." mismatch. |
| 334 |
ctx, cancel := context.WithCancel(context.Background()) |
| 335 |
group, gCtx := errgroup.WithContext(ctx) |
| 336 |
|
| 337 |
ln := getTcpS3Server(t, group, ctx, bucket, "cmd/desync/testdata", s3ErrCorruptBody, 1) |
| 338 |
|
| 339 |
group.Go(func() error { |
| 340 |
defer cancel() |
| 341 |
endpoint := url.URL{Scheme: "s3+http", Host: ln.Addr().String(), Path: "/" + bucket + "/blob1.store/"} |
| 342 |
store, err := NewS3Store(&endpoint, credentials.New(&provider), location, StoreOptions{}, minio.BucketLookupAuto) |
| 343 |
if err != nil { |
| 344 |
return err |
| 345 |
} |
| 346 |
|
| 347 |
c := make(chan error) |
| 348 |
go func() { |
| 349 |
_, err := store.GetChunk(chunkId) |
| 350 |
if err == nil { |
| 351 |
c <- errors.New("expected GetChunk to fail on truncated chunk body") |
| 352 |
return |
| 353 |
} |
| 354 |
var ci ChunkInvalid |
| 355 |
if !errors.As(err, &ci) { |
| 356 |
c <- fmt.Errorf("expected ChunkInvalid, got %T: %v", err, err) |
| 357 |
return |
| 358 |
} |
| 359 |
if ci.Err == nil { |
| 360 |
c <- fmt.Errorf("expected ChunkInvalid to carry the underlying decode error, got %v", err) |
| 361 |
return |
| 362 |
} |
| 363 |
c <- nil |
| 364 |
}() |
| 365 |
select { |
| 366 |
case <-gCtx.Done(): |
| 367 |
return nil |
| 368 |
case err = <-c: |
| 369 |
return err |
| 370 |
} |
| 371 |
}) |
| 372 |
|
| 373 |
require.NoError(t, group.Wait()) |
| 374 |
}) |
| 375 |
|
| 376 |
t.Run("corrupt_body_recover", func(t *testing.T) { |
| 377 |
// Same truncated-body scenario, but with retries enabled GetChunk() should |
| 378 |
// retry the validation failure and succeed once a full response is served. |
| 379 |
ctx, cancel := context.WithCancel(context.Background()) |
| 380 |
group, gCtx := errgroup.WithContext(ctx) |
| 381 |
|
| 382 |
ln := getTcpS3Server(t, group, ctx, bucket, "cmd/desync/testdata", s3ErrCorruptBody, 1) |
| 383 |
|
| 384 |
group.Go(func() error { |
| 385 |
defer cancel() |
| 386 |
endpoint := url.URL{Scheme: "s3+http", Host: ln.Addr().String(), Path: "/" + bucket + "/blob1.store/"} |
| 387 |
store, err := NewS3Store(&endpoint, credentials.New(&provider), location, StoreOptions{ErrorRetry: 1}, minio.BucketLookupAuto) |
| 388 |
if err != nil { |
| 389 |
return err |
| 390 |
} |
| 391 |
|
| 392 |
c := make(chan error) |
| 393 |
go func() { |
| 394 |
chunk, err := store.GetChunk(chunkId) |
| 395 |
if err != nil { |
| 396 |
c <- err |
| 397 |
return |
| 398 |
} |
| 399 |
if chunk.ID() != chunkId { |
| 400 |
c <- fmt.Errorf("got chunk with id equal to %q, expected %q", chunk.ID(), chunkId) |
| 401 |
return |
| 402 |
} |
| 403 |
c <- nil |
| 404 |
}() |
| 405 |
select { |
| 406 |
case <-gCtx.Done(): |
| 407 |
return nil |
| 408 |
case err = <-c: |
| 409 |
return err |
| 410 |
} |
| 411 |
}) |
| 412 |
|
| 413 |
require.NoError(t, group.Wait()) |
| 414 |
}) |
| 415 |
} |
| 416 |
|
| 417 |
// A missing chunk is not a transient error and is a normal occurrence when |
| 418 |
// the store sits behind a router or cache. GetChunk must return ChunkMissing |
| 419 |
// right away instead of going through the ErrorRetry sleep/retry loop. |
| 420 |
func TestS3StoreGetMissingChunk(t *testing.T) { |
| 421 |
chunkId, err := ChunkIDFromString("dda036db05bc2b99b6b9303d28496000c34b246457ae4bbf00fe625b5cabd7cd") |
| 422 |
require.NoError(t, err) |
| 423 |
provider := MockCredProvider{} |
| 424 |
|
| 425 |
var requests int32 |
| 426 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 427 |
atomic.AddInt32(&requests, 1) |
| 428 |
w.WriteHeader(http.StatusNotFound) |
| 429 |
})) |
| 430 |
defer ts.Close() |
| 431 |
u, err := url.Parse(ts.URL) |
| 432 |
require.NoError(t, err) |
| 433 |
|
| 434 |
endpoint := url.URL{Scheme: "s3+http", Host: u.Host, Path: "/doomsdaydevices/blob1.store/"} |
| 435 |
store, err := NewS3Store(&endpoint, credentials.New(&provider), "vertucon-central", |
| 436 |
StoreOptions{ErrorRetry: 3, ErrorRetryBaseInterval: time.Millisecond}, minio.BucketLookupAuto) |
| 437 |
require.NoError(t, err) |
| 438 |
|
| 439 |
_, err = store.GetChunk(chunkId) |
| 440 |
var missing ChunkMissing |
| 441 |
require.ErrorAs(t, err, &missing) |
| 442 |
require.EqualValues(t, 1, atomic.LoadInt32(&requests), "missing chunk should not be retried") |
| 443 |
} |