OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / prometheus / prometheus / util / flock / flock.go
1 // Copyright 2016 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package flock provides portable file locking. It is essentially ripped out
15 // from the code of github.com/syndtr/goleveldb. Strange enough that the
16 // standard library does not provide this functionality. Once this package has
17 // proven to work as expected, we should probably turn it into a separate
18 // general purpose package for humanity.
19 package flock
20
21 import (
22         "os"
23         "path/filepath"
24 )
25
26 // Releaser provides the Release method to release a file lock.
27 type Releaser interface {
28         Release() error
29 }
30
31 // New locks the file with the provided name. If the file does not exist, it is
32 // created. The returned Releaser is used to release the lock. existed is true
33 // if the file to lock already existed. A non-nil error is returned if the
34 // locking has failed. Neither this function nor the returned Releaser is
35 // goroutine-safe.
36 func New(fileName string) (r Releaser, existed bool, err error) {
37         if err = os.MkdirAll(filepath.Dir(fileName), 0755); err != nil {
38                 return
39         }
40
41         _, err = os.Stat(fileName)
42         existed = err == nil
43
44         r, err = newLock(fileName)
45         return
46 }