Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/lockutil/lockutil_unix.go
2610 views
1
//go:build !windows
2
3
// SPDX-FileCopyrightText: Copyright The Lima Authors
4
// SPDX-License-Identifier: Apache-2.0
5
6
// From https://github.com/containerd/nerdctl/blob/v0.13.0/pkg/lockutil/lockutil_unix.go
7
/*
8
Copyright The containerd Authors.
9
10
Licensed under the Apache License, Version 2.0 (the "License");
11
you may not use this file except in compliance with the License.
12
You may obtain a copy of the License at
13
14
http://www.apache.org/licenses/LICENSE-2.0
15
16
Unless required by applicable law or agreed to in writing, software
17
distributed under the License is distributed on an "AS IS" BASIS,
18
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
See the License for the specific language governing permissions and
20
limitations under the License.
21
*/
22
23
package lockutil
24
25
import (
26
"fmt"
27
"os"
28
29
"github.com/sirupsen/logrus"
30
"golang.org/x/sys/unix"
31
)
32
33
func WithDirLock(dir string, fn func() error) error {
34
dirFile, err := os.Open(dir)
35
if err != nil {
36
return err
37
}
38
defer dirFile.Close()
39
if err := Flock(dirFile, unix.LOCK_EX); err != nil {
40
return fmt.Errorf("failed to lock %q: %w", dir, err)
41
}
42
defer func() {
43
if err := Flock(dirFile, unix.LOCK_UN); err != nil {
44
logrus.WithError(err).Errorf("failed to unlock %q", dir)
45
}
46
}()
47
return fn()
48
}
49
50
func Flock(f *os.File, flags int) error {
51
fd := int(f.Fd())
52
for {
53
err := unix.Flock(fd, flags)
54
if err == nil || err != unix.EINTR {
55
return err
56
}
57
}
58
}
59
60