-
Notifications
You must be signed in to change notification settings - Fork 243
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
loopback: fix race condition opening loopback device
the loopback device file could be already used/removed by another process. Since the process is inherently racy, just grab the next available index and try again until it succeeds. Closes: #2038 Signed-off-by: Giuseppe Scrivano <[email protected]>
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
//go:build linux && cgo | ||
// +build linux,cgo | ||
|
||
package loopback | ||
|
||
import ( | ||
"os" | ||
"sync" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
const ( | ||
maxDevicesPerGoroutine = 1000 | ||
maxGoroutines = 10 | ||
) | ||
|
||
func TestAttachLoopbackDeviceRace(t *testing.T) { | ||
createLoopbackDevice := func() { | ||
// Create a file to use as a backing file | ||
f, err := os.CreateTemp(t.TempDir(), "loopback-test") | ||
require.NoError(t, err) | ||
defer f.Close() | ||
|
||
defer os.Remove(f.Name()) | ||
|
||
lp, err := AttachLoopDevice(f.Name()) | ||
assert.NoError(t, err) | ||
assert.NotNil(t, lp, "loopback device file should not be nil") | ||
if lp != nil { | ||
lp.Close() | ||
} | ||
} | ||
|
||
wg := sync.WaitGroup{} | ||
|
||
for i := 0; i < maxGoroutines; i++ { | ||
wg.Add(1) | ||
go func() { | ||
defer wg.Done() | ||
for i := 0; i < maxDevicesPerGoroutine; i++ { | ||
createLoopbackDevice() | ||
} | ||
}() | ||
} | ||
wg.Wait() | ||
} |