| 1 | |
| 2 | |
| 3 | package containerenv |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "syscall" |
| 11 | "time" |
| 12 | |
| 13 | "golang.org/x/sys/unix" |
| 14 | ) |
| 15 | |
| 16 | func detachWorker(command *exec.Cmd) { command.SysProcAttr = &syscall.SysProcAttr{Setsid: true} } |
| 17 | func tryLockRuntime(path string) (func(), error) { |
| 18 | file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) |
| 19 | if err != nil { |
| 20 | return nil, err |
| 21 | } |
| 22 | if err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { |
| 23 | file.Close() |
| 24 | return nil, err |
| 25 | } |
| 26 | return func() { _ = unix.Flock(int(file.Fd()), unix.LOCK_UN); _ = file.Close() }, nil |
| 27 | } |
| 28 | func lockRuntime(ctx context.Context, path string) (func(), error) { |
| 29 | for { |
| 30 | unlock, err := tryLockRuntime(path) |
| 31 | if err == nil { |
| 32 | return unlock, nil |
| 33 | } |
| 34 | if !errors.Is(err, unix.EWOULDBLOCK) { |
| 35 | return nil, err |
| 36 | } |
| 37 | select { |
| 38 | case <-ctx.Done(): |
| 39 | return nil, ctx.Err() |
| 40 | case <-time.After(100 * time.Millisecond): |
| 41 | } |
| 42 | } |
| 43 | } |