pax_global_header 0000666 0000000 0000000 00000000064 14176637215 0014526 g ustar 00root root 0000000 0000000 52 comment=11eeddb42c6c709cc089b3806526d8bd69a9327f
mutex-2.0.0/ 0000775 0000000 0000000 00000000000 14176637215 0012667 5 ustar 00root root 0000000 0000000 mutex-2.0.0/LICENSE 0000664 0000000 0000000 00000021501 14176637215 0013673 0 ustar 00root root 0000000 0000000 All files in this repository are licensed as follows. If you contribute
to this repository, it is assumed that you license your contribution
under the same license unless you state otherwise.
All files Copyright (C) 2015 Canonical Ltd. unless otherwise specified in the file.
This software is licensed under the LGPLv3, included below.
As a special exception to the GNU Lesser General Public License version 3
("LGPL3"), the copyright holders of this Library give you permission to
convey to a third party a Combined Work that links statically or dynamically
to this Library without providing any Minimal Corresponding Source or
Minimal Application Code as set out in 4d or providing the installation
information set out in section 4e, provided that you comply with the other
provisions of LGPL3 and provided that you meet, for the Application the
terms and conditions of the license(s) which apply to the Application.
Except as stated in this special exception, the provisions of LGPL3 will
continue to comply in full to this Library. If you modify this Library, you
may apply this exception to your version of this Library, but you are not
obliged to do so. If you do not wish to do so, delete this exception
statement from your version. This exception does not (and cannot) modify any
license terms which apply to the Application, with which you must still
comply.
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
mutex-2.0.0/Makefile 0000664 0000000 0000000 00000001073 14176637215 0014330 0 ustar 00root root 0000000 0000000 PROJECT := github.com/juju/mutex/v2
.PHONY: check-licence check-go check
check: check-licence check-go
go test $(PROJECT)/...
check-licence:
@(fgrep -rl "Licensed under the LGPLv3" .;\
fgrep -rl "Code generated by MockGen. DO NOT EDIT." .;\
find . -name "*.go") | sed -e 's,\./,,' | sort | uniq -u | \
xargs -I {} echo FAIL: licence missed: {}
check-go:
$(eval GOFMT := $(strip $(shell gofmt -l .| sed -e "s/^/ /g")))
@(if [ x$(GOFMT) != x"" ]; then \
echo go fmt is sad: $(GOFMT); \
exit 1; \
fi )
@(go vet -all -composites=false -copylocks=false .)
mutex-2.0.0/README.md 0000664 0000000 0000000 00000007111 14176637215 0014146 0 ustar 00root root 0000000 0000000
# mutex
`import "github.com/juju/mutex/v2"`
* [Overview](#pkg-overview)
* [Index](#pkg-index)
## Overview
package mutex provides a named machine level mutex shareable between processes.
[](https://godoc.org/github.com/juju/mutex)
Mutexes have names. Each each name, only one mutex for that name can be
acquired at the same time, within and across process boundaries. If a
process dies while the mutex is held, the mutex is automatically released.
The Linux/MacOS implementation uses flock, while the Windows implementation
uses a named mutex.
## Index
* [Variables](#pkg-variables)
* [type Clock](#Clock)
* [type Releaser](#Releaser)
* [func Acquire(spec Spec) (Releaser, error)](#Acquire)
* [type Spec](#Spec)
* [func (s *Spec) Validate() error](#Spec.Validate)
#### Package files
[doc.go](/src/github.com/juju/mutex/doc.go) [errors.go](/src/github.com/juju/mutex/errors.go) [legacy_mutex_linux.go](/src/github.com/juju/mutex/legacy_mutex_linux.go) [mutex.go](/src/github.com/juju/mutex/mutex.go) [mutex_flock.go](/src/github.com/juju/mutex/mutex_flock.go)
## Variables
``` go
var (
ErrTimeout = errors.New("timeout acquiring mutex")
ErrCancelled = errors.New("cancelled acquiring mutex")
)
```
## type [Clock](/src/target/mutex.go?s=682:907#L28)
``` go
type Clock interface {
// After waits for the duration to elapse and then sends the
// current time on the returned channel.
After(time.Duration) <-chan time.Time
// Now returns the current clock time.
Now() time.Time
}
```
Clock provides an interface for dealing with clocks.
## type [Releaser](/src/target/mutex.go?s=337:624#L19)
``` go
type Releaser interface {
// Release releases the mutex. Release may be called multiple times, but
// only the first call will release this instance of the mutex. Release is
// unable to release the mutex successfully it will call panic to forcibly
// release the mutex.
Release()
}
```
Releaser defines the Release method that is the only thing that can be done
to a acquired mutex.
### func [Acquire](/src/target/mutex.go?s=1757:1798#L61)
``` go
func Acquire(spec Spec) (Releaser, error)
```
Acquire will attempt to acquire the named mutex. If the Timout value
is hit, ErrTimeout is returned. If the Cancel channel is signalled,
ErrCancelled is returned.
## type [Spec](/src/target/mutex.go?s=986:1583#L38)
``` go
type Spec struct {
// Name is required, and must start with a letter and contain at most
// 40 letters, numbers or dashes.
Name string
// Clock must be provided and is exposed for testing purposes.
Clock Clock
// Delay defines how often to check for lock acquisition, for
// compatibility code that requires polling.
Delay time.Duration
// Timeout allows the caller to specify how long to wait. If Timeout
// is zero, then the call will block forever.
Timeout time.Duration
// Cancel if signalled will cause the Acquire method to return with ErrCancelled.
Cancel <-chan struct{}
}
```
Spec defines the name of the mutex and behaviour of the Acquire function.
### func (\*Spec) [Validate](/src/target/mutex.go?s=2640:2671#L105)
``` go
func (s *Spec) Validate() error
```
Validate checks the attributes of Spec for validity.
- - -
Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md)
mutex-2.0.0/doc.go 0000664 0000000 0000000 00000001161 14176637215 0013762 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
/*
package mutex provides a named machine level mutex shareable between processes.
[godoc-link-here]
Mutexes have names. Each each name, only one mutex for that name can be
acquired at the same time, within and across process boundaries. If a
process dies while the mutex is held, the mutex is automatically released.
The Linux/MacOS implementation uses flock, while the Windows implementation
uses a named mutex. On Linux, we also acquire an abstract domain socket for
compatibility with older implementations.
*/
package mutex
mutex-2.0.0/errors.go 0000664 0000000 0000000 00000000411 14176637215 0014526 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package mutex
import (
"github.com/juju/errors"
)
var (
ErrTimeout = errors.New("timeout acquiring mutex")
ErrCancelled = errors.New("cancelled acquiring mutex")
)
mutex-2.0.0/export_test.go 0000664 0000000 0000000 00000000276 14176637215 0015603 0 ustar 00root root 0000000 0000000 // Copyright 2016-2017 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package mutex
var (
// Export the Envars so we can test it via mocks
Envars = &envars
)
mutex-2.0.0/go.mod 0000664 0000000 0000000 00000002002 14176637215 0013767 0 ustar 00root root 0000000 0000000 module github.com/juju/mutex/v2
go 1.17
require (
github.com/golang/mock v1.5.0
github.com/juju/errors v0.0.0-20220203013757-bd733f3c86b9
github.com/juju/testing v0.0.0-20220203020004-a0ff61f03494
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c
)
require (
github.com/juju/clock v0.0.0-20190205081909-9c5c9712527c // indirect
github.com/juju/collections v0.0.0-20200605021417-0d0ec82b7271 // indirect
github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4 // indirect
github.com/juju/mgo/v2 v2.0.0-20210302023703-70d5d206e208 // indirect
github.com/juju/retry v0.0.0-20180821225755-9058e192b216 // indirect
github.com/juju/utils/v3 v3.0.0-20220130232349-cd7ecef0e94a // indirect
github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23 // indirect
github.com/kr/pretty v0.2.1 // indirect
github.com/kr/text v0.2.0 // indirect
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a // indirect
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
mutex-2.0.0/go.sum 0000664 0000000 0000000 00000024720 14176637215 0014027 0 ustar 00root root 0000000 0000000 github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/golang/mock v1.5.0 h1:jlYHihg//f7RRwuPfptm04yp4s7O6Kw8EZiVYIGcH0g=
github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8=
github.com/juju/ansiterm v0.0.0-20160907234532-b99631de12cf/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU=
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU=
github.com/juju/clock v0.0.0-20190205081909-9c5c9712527c h1:3UvYABOQRhJAApj9MdCN+Ydv841ETSoy6xLzdmmr/9A=
github.com/juju/clock v0.0.0-20190205081909-9c5c9712527c/go.mod h1:nD0vlnrUjcjJhqN5WuCWZyzfd5AHZAC9/ajvbSx69xA=
github.com/juju/cmd v0.0.0-20171107070456-e74f39857ca0/go.mod h1:yWJQHl73rdSX4DHVKGqkAip+huBslxRwS8m9CrOLq18=
github.com/juju/collections v0.0.0-20200605021417-0d0ec82b7271 h1:4R626WTwa7pRYQFiIRLVPepMhm05eZMEx+wIurRnMLc=
github.com/juju/collections v0.0.0-20200605021417-0d0ec82b7271/go.mod h1:5XgO71dV1JClcOJE+4dzdn4HrI5LiyKd7PlVG6eZYhY=
github.com/juju/errors v0.0.0-20150916125642-1b5e39b83d18/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q=
github.com/juju/errors v0.0.0-20200330140219-3fe23663418f/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q=
github.com/juju/errors v0.0.0-20220203013757-bd733f3c86b9 h1:EJHbsNpQyupmMeWTq7inn+5L/WZ7JfzCVPJ+DP9McCQ=
github.com/juju/errors v0.0.0-20220203013757-bd733f3c86b9/go.mod h1:TRm7EVGA3mQOqSVcBySRY7a9Y1/gyVhh/WTCnc5sD4U=
github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE=
github.com/juju/httpprof v0.0.0-20141217160036-14bf14c30767/go.mod h1:+MaLYz4PumRkkyHYeXJ2G5g5cIW0sli2bOfpmbaMV/g=
github.com/juju/loggo v0.0.0-20170605014607-8232ab8918d9/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U=
github.com/juju/loggo v0.0.0-20200526014432-9ce3a2e09b5e/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U=
github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4 h1:NO5tuyw++EGLnz56Q8KMyDZRwJwWO8jQnj285J3FOmY=
github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4/go.mod h1:NIXFioti1SmKAlKNuUwbMenNdef59IF52+ZzuOmHYkg=
github.com/juju/mgo/v2 v2.0.0-20210302023703-70d5d206e208 h1:/WiCm+Vpj87e4QWuWwPD/bNE9kDrWCLvPBHOQNcG2+A=
github.com/juju/mgo/v2 v2.0.0-20210302023703-70d5d206e208/go.mod h1:0OChplkvPTZ174D2FYZXg4IB9hbEwyHkD+zT+/eK+Fg=
github.com/juju/mutex v0.0.0-20171110020013-1fe2a4bf0a3a h1:fFpWkIPzpzxd3CC+qfU5adsawpG371Ie4TmRkhxwyNU=
github.com/juju/mutex v0.0.0-20171110020013-1fe2a4bf0a3a/go.mod h1:Y3oOzHH8CQ0Ppt0oCKJ2JFO81/EsWenH5AEqigLH+yY=
github.com/juju/retry v0.0.0-20151029024821-62c620325291/go.mod h1:OohPQGsr4pnxwD5YljhQ+TZnuVRYpa5irjugL1Yuif4=
github.com/juju/retry v0.0.0-20180821225755-9058e192b216 h1:/eQL7EJQKFHByJe3DeE8Z36yqManj9UY5zppDoQi4FU=
github.com/juju/retry v0.0.0-20180821225755-9058e192b216/go.mod h1:OohPQGsr4pnxwD5YljhQ+TZnuVRYpa5irjugL1Yuif4=
github.com/juju/testing v0.0.0-20180402130637-44801989f0f7/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA=
github.com/juju/testing v0.0.0-20190723135506-ce30eb24acd2/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA=
github.com/juju/testing v0.0.0-20210302031854-2c7ee8570c07/go.mod h1:7lxZW0B50+xdGFkvhAb8bwAGt6IU87JB1H9w4t8MNVM=
github.com/juju/testing v0.0.0-20220202055744-1ad0816210a6/go.mod h1:QgWc2UdIPJ8t3rnvv95tFNOsQDfpXYEZDbP281o3b2c=
github.com/juju/testing v0.0.0-20220203020004-a0ff61f03494 h1:XEDzpuZb8Ma7vLja3+5hzUqVTvAqm5Y+ygvnDs5iTMM=
github.com/juju/testing v0.0.0-20220203020004-a0ff61f03494/go.mod h1:rUquetT0ALL48LHZhyRGvjjBH8xZaZ8dFClulKK5wK4=
github.com/juju/utils v0.0.0-20180424094159-2000ea4ff043/go.mod h1:6/KLg8Wz/y2KVGWEpkK9vMNGkOnu4k/cqs8Z1fKjTOk=
github.com/juju/utils v0.0.0-20200116185830-d40c2fe10647 h1:wQpkHVbIIpz1PCcLYku9KFWsJ7aEMQXHBBmLy3tRBTk=
github.com/juju/utils v0.0.0-20200116185830-d40c2fe10647/go.mod h1:6/KLg8Wz/y2KVGWEpkK9vMNGkOnu4k/cqs8Z1fKjTOk=
github.com/juju/utils/v2 v2.0.0-20200923005554-4646bfea2ef1/go.mod h1:fdlDtQlzundleLLz/ggoYinEt/LmnrpNKcNTABQATNI=
github.com/juju/utils/v3 v3.0.0-20220130232349-cd7ecef0e94a h1:5ZWDCeCF0RaITrZGemzmDFIhjR/MVSvBUqgSyaeTMbE=
github.com/juju/utils/v3 v3.0.0-20220130232349-cd7ecef0e94a/go.mod h1:LzwbbEN7buYjySp4nqnti6c6olSqRXUk6RkbSUUP1n8=
github.com/juju/version v0.0.0-20161031051906-1f41e27e54f2/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U=
github.com/juju/version v0.0.0-20180108022336-b64dbd566305/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U=
github.com/juju/version v0.0.0-20191219164919-81c1be00b9a6 h1:nrqc9b4YKpKV4lPI3GPPFbo5FUuxkWxgZE2Z8O4lgaw=
github.com/juju/version v0.0.0-20191219164919-81c1be00b9a6/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U=
github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23 h1:wtEPbidt1VyHlb8RSztU6ySQj29FLsOQiI9XiJhXDM4=
github.com/juju/version/v2 v2.0.0-20211007103408-2e8da085dc23/go.mod h1:Ljlbryh9sYaUSGXucslAEDf0A2XUSGvDbHJgW8ps6nc=
github.com/julienschmidt/httprouter v1.1.1-0.20151013225520-77a895ad01eb/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lunixbochs/vtclean v0.0.0-20160125035106-4fbf7632a2c6/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
github.com/masterzen/azure-sdk-for-go v3.2.0-beta.0.20161014135628-ee4f0065d00c+incompatible/go.mod h1:mf8fjOu33zCqxUjuiU3I8S1lJMyEAlH+0F2+M5xl3hE=
github.com/masterzen/simplexml v0.0.0-20160608183007-4572e39b1ab9/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc=
github.com/masterzen/winrm v0.0.0-20161014151040-7a535cd943fc/go.mod h1:CfZSN7zwz5gJiFhZJz49Uzk7mEBHIceWmbFmYx7Hf7E=
github.com/masterzen/xmlpath v0.0.0-20140218185901-13f4951698ad/go.mod h1:A0zPC53iKKKcXYxr4ROjpQRQ5FgJXtelNdSmHHuq/tY=
github.com/mattn/go-colorable v0.0.6/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.0-20160806122752-66b8e73f3f5c/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U=
golang.org/x/crypto v0.0.0-20180214000028-650f4a345ab4/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180406214816-61147c48b25b/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20160105164936-4f90aeace3a2/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/errgo.v1 v1.0.0-20161222125816-442357a80af5/go.mod h1:u0ALmqvLRxLI95fkdCEWrE6mhWYZW1aMOJHp5YXLHTg=
gopkg.in/httprequest.v1 v1.1.1/go.mod h1:/CkavNL+g3qLOrpFHVrEx4NKepeqR4XTZWNj4sGGjz0=
gopkg.in/mgo.v2 v2.0.0-20160818015218-f2b6f6c918c4/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk=
gopkg.in/yaml.v2 v2.0.0-20170712054546-1be3d31502d6/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
launchpad.net/gocheck v0.0.0-20140225173054-000000000087/go.mod h1:hj7XX3B/0A+80Vse0e+BUHsHMTEhd0O4cpUHr/e/BUM=
launchpad.net/xmlpath v0.0.0-20130614043138-000000000004/go.mod h1:vqyExLOM3qBx7mvYRkoxjSCF945s0mbe7YynlKYXtsA=
mutex-2.0.0/mutex.go 0000664 0000000 0000000 00000004675 14176637215 0014374 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package mutex
import (
"regexp"
"time"
"github.com/juju/errors"
)
var (
validName = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]*$")
)
// Releaser defines the Release method that is the only thing that can be done
// to a acquired mutex.
type Releaser interface {
// Release releases the mutex. Release may be called multiple times, but
// only the first call will release this instance of the mutex. Release is
// unable to release the mutex successfully it will call panic to forcibly
// release the mutex.
Release()
}
// Clock provides an interface for dealing with clocks.
type Clock interface {
// After waits for the duration to elapse and then sends the
// current time on the returned channel.
After(time.Duration) <-chan time.Time
// Now returns the current clock time.
Now() time.Time
}
// Spec defines the name of the mutex and behaviour of the Acquire function.
type Spec struct {
// Name is required, and must start with a letter and contain at most
// 40 letters, numbers or dashes.
Name string
// Clock must be provided and is exposed for testing purposes.
Clock Clock
// Delay defines how often to check for lock acquisition, for
// compatibility code that requires polling.
Delay time.Duration
// Timeout allows the caller to specify how long to wait. If Timeout
// is zero, then the call will block forever.
Timeout time.Duration
// Cancel if signalled will cause the Acquire method to return with ErrCancelled.
Cancel <-chan struct{}
}
// Acquire will attempt to acquire the named mutex. If the Timout value
// is hit, ErrTimeout is returned. If the Cancel channel is signalled,
// ErrCancelled is returned.
func Acquire(spec Spec) (Releaser, error) {
if err := spec.Validate(); err != nil {
return nil, errors.Trace(err)
}
var timeout <-chan time.Time
if spec.Timeout > 0 {
timeout = spec.Clock.After(spec.Timeout)
}
return acquire(spec, timeout)
}
// Validate checks the attributes of Spec for validity.
func (s *Spec) Validate() error {
if len(s.Name) > 40 {
return errors.NotValidf("Name longer than 40 characters")
}
if !validName.MatchString(s.Name) {
return errors.NotValidf("Name %q", s.Name)
}
if s.Clock == nil {
return errors.NotValidf("missing Clock")
}
if s.Delay <= 0 {
return errors.NotValidf("non positive Delay")
}
if s.Timeout < 0 {
return errors.NotValidf("negative Timeout")
}
return nil
}
mutex-2.0.0/mutex_flock.go 0000664 0000000 0000000 00000011501 14176637215 0015534 0 ustar 00root root 0000000 0000000 // Copyright 2016-2017 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
//go:build !windows
// +build !windows
package mutex
import (
"os"
"path/filepath"
"strconv"
"sync"
"syscall"
"time"
"github.com/juju/errors"
)
func acquire(spec Spec, timeout <-chan time.Time) (Releaser, error) {
done := make(chan struct{})
defer close(done)
select {
case result := <-acquireFlock(spec.Name, done):
if result.err != nil {
return nil, errors.Trace(result.err)
}
return result.m, nil
case <-timeout:
return nil, ErrTimeout
case <-spec.Cancel:
return nil, ErrCancelled
}
}
var envars Environment = osEnvironment{}
var (
mu sync.Mutex
active = make(map[string][]*waiter)
)
type waiter struct {
ch chan<- acquireResult
done <-chan struct{}
}
type acquireResult struct {
m Releaser
err error
}
// acquireFlock returns a channel on which an acquireResult will be
// sent when the mutex acquisition completes, successfully or not.
//
// In Go, there is no natural way to cancel a flock syscall, so we
// allow a flock syscall to continue on even when there is nothing
// waiting for it, and then release the lock in that case. To avoid
// an unbounded collection of goroutines, we ensure that there is
// only one goroutine making a flock syscall at a time, per mutex
// name.
func acquireFlock(name string, done <-chan struct{}) <-chan acquireResult {
result := make(chan acquireResult)
w := &waiter{result, done}
mu.Lock()
defer mu.Unlock()
if waiters, ok := active[name]; ok {
active[name] = append(waiters, w)
return result
}
flockName := filepath.Join(os.TempDir(), "juju-"+name)
chownFromRoot := func() error {
if cmd, ok := envars.LookupEnv("SUDO_COMMAND"); ok && cmd != "" {
var uid, gid int
uid, err := strconv.Atoi(envars.Getenv("SUDO_UID"))
if err != nil {
return errors.Annotate(err, "parsing SUDO_UID")
}
gid, err = strconv.Atoi(envars.Getenv("SUDO_GID"))
if err != nil {
return errors.Annotate(err, "parsing SUDO_GID")
}
return syscall.Chown(flockName, uid, gid)
}
return nil
}
open := func() (int, error) {
fd, err := syscall.Open(flockName, syscall.O_CREAT|syscall.O_RDONLY|syscall.O_CLOEXEC, 0600)
if err != nil {
if os.IsPermission(err) {
err = errors.Annotatef(err, "unable to open %s", flockName)
}
return fd, err
}
// Attempting to open a lock file as root whilst using sudo can cause
// the lock file to have the wrong permissions for a non-sudo user.
// Subsequent calls to acquire the lock file can then lead to cryptic
// error messages. Let's attempt to help people out, either by
// correcting the permissions, or explaining why we can't help them.
// info: lp 1758369
if chownErr := chownFromRoot(); chownErr != nil {
// The file has the wrong permissions, but we should let the acquire
// continue.
}
return fd, err
}
flock := func() (Releaser, error) {
fd, err := open()
if err != nil {
return nil, errors.Trace(err)
}
if err := syscall.Flock(fd, syscall.LOCK_EX); err != nil {
syscall.Close(fd)
return nil, errors.Trace(err)
}
return &mutex{fd: fd}, nil
}
acquire := func() bool {
releaser, err := flock()
result := acquireResult{releaser, err}
mu.Lock()
defer mu.Unlock()
var sent bool
waiters := active[name]
for !sent && len(waiters) > 0 {
w, waiters = waiters[0], waiters[1:]
select {
case w.ch <- result:
sent = true
case <-w.done:
// waiter is done, so just
// remove it from the list
// and try the next one
}
}
if !sent && releaser != nil {
// No active waiters, release the lock.
releaser.Release()
}
if len(waiters) > 0 {
active[name] = waiters
return true
}
delete(active, name)
return false
}
go func() {
for acquire() {
}
}()
active[name] = []*waiter{w}
return result
}
// mutex implements Releaser using the flock syscall.
type mutex struct {
mu sync.Mutex
fd int
}
// Release is part of the Releaser interface.
func (m *mutex) Release() {
m.mu.Lock()
defer m.mu.Unlock()
if m.fd == 0 {
return
}
err := syscall.Close(m.fd)
if err != nil {
panic(err)
}
m.fd = 0
}
// Environment defines a simple interface with interacting with environmental
// variables.
//go:generate mockgen -package mutex_test -destination mutex_mock_test.go github.com/juju/mutex Environment
type Environment interface {
// LookupEnv retrieves the value of the environment variable named
// by the key.
LookupEnv(string) (string, bool)
// Getenv retrieves the value of the environment variable named by the key.
Getenv(string) string
}
// osEnvironment provides a default way to access environmental values to the
// acquire method.
type osEnvironment struct{}
func (osEnvironment) LookupEnv(key string) (string, bool) {
return os.LookupEnv(key)
}
func (osEnvironment) Getenv(key string) string {
return os.Getenv(key)
}
mutex-2.0.0/mutex_mock_test.go 0000664 0000000 0000000 00000003435 14176637215 0016435 0 ustar 00root root 0000000 0000000 // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/juju/mutex (interfaces: Environment)
// Package mutex_test is a generated GoMock package.
package mutex_test
import (
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockEnvironment is a mock of Environment interface
type MockEnvironment struct {
ctrl *gomock.Controller
recorder *MockEnvironmentMockRecorder
}
// MockEnvironmentMockRecorder is the mock recorder for MockEnvironment
type MockEnvironmentMockRecorder struct {
mock *MockEnvironment
}
// NewMockEnvironment creates a new mock instance
func NewMockEnvironment(ctrl *gomock.Controller) *MockEnvironment {
mock := &MockEnvironment{ctrl: ctrl}
mock.recorder = &MockEnvironmentMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockEnvironment) EXPECT() *MockEnvironmentMockRecorder {
return m.recorder
}
// Getenv mocks base method
func (m *MockEnvironment) Getenv(arg0 string) string {
ret := m.ctrl.Call(m, "Getenv", arg0)
ret0, _ := ret[0].(string)
return ret0
}
// Getenv indicates an expected call of Getenv
func (mr *MockEnvironmentMockRecorder) Getenv(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Getenv", reflect.TypeOf((*MockEnvironment)(nil).Getenv), arg0)
}
// LookupEnv mocks base method
func (m *MockEnvironment) LookupEnv(arg0 string) (string, bool) {
ret := m.ctrl.Call(m, "LookupEnv", arg0)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(bool)
return ret0, ret1
}
// LookupEnv indicates an expected call of LookupEnv
func (mr *MockEnvironmentMockRecorder) LookupEnv(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LookupEnv", reflect.TypeOf((*MockEnvironment)(nil).LookupEnv), arg0)
}
mutex-2.0.0/mutex_test.go 0000664 0000000 0000000 00000030761 14176637215 0015426 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package mutex_test
import (
"fmt"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
"github.com/golang/mock/gomock"
jt "github.com/juju/testing"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/mutex/v2"
)
const (
shortWait = 10 * time.Millisecond
longWait = 10 * shortWait
appWait = 5 * time.Second
)
type mutexSuite struct{}
var _ = gc.Suite(&mutexSuite{})
func (s *mutexSuite) TestSpecValidity(c *gc.C) {
for i, test := range []struct {
spec mutex.Spec
err string
}{{
spec: mutex.Spec{Name: "", Clock: &fakeClock{}, Delay: time.Millisecond},
err: `Name "" not valid`,
}, {
spec: mutex.Spec{Name: "42", Clock: &fakeClock{}, Delay: time.Millisecond},
err: `Name "42" not valid`,
}, {
spec: mutex.Spec{Name: "a", Clock: &fakeClock{}, Delay: time.Millisecond},
}, {
spec: mutex.Spec{Name: "a very very long name that is over the length limit", Clock: &fakeClock{}, Delay: time.Millisecond},
err: `Name longer than 40 characters not valid`,
}, {
spec: mutex.Spec{Name: "test-42", Clock: &fakeClock{}, Delay: time.Millisecond},
}, {
spec: mutex.Spec{Name: "with a space", Clock: &fakeClock{}, Delay: time.Millisecond},
err: `Name "with a space" not valid`,
}, {
spec: mutex.Spec{Name: "test-42", Delay: time.Millisecond},
err: `missing Clock not valid`,
}, {
spec: mutex.Spec{Name: "test-42", Clock: &fakeClock{}},
err: `non positive Delay not valid`,
}, {
spec: mutex.Spec{Name: "test-42", Clock: &fakeClock{}, Delay: -time.Second},
err: `non positive Delay not valid`,
}, {
spec: mutex.Spec{Name: "test-42", Clock: &fakeClock{}, Delay: time.Millisecond, Timeout: -time.Second},
err: `negative Timeout not valid`,
}} {
c.Logf("test %d", i+1)
err := test.spec.Validate()
if test.err == "" {
c.Check(err, jc.ErrorIsNil)
} else {
c.Check(err, gc.ErrorMatches, test.err)
}
}
}
func (s *mutexSuite) spec() mutex.Spec {
// On the off chance there are multiple tests running, we shouldn't
// clash on the lock name.
return mutex.Spec{
Name: fmt.Sprintf("testing-%d", os.Getpid()),
Clock: &fakeClock{time.Millisecond},
Delay: 10 * time.Second,
}
}
func (s *mutexSuite) TestLockNoContention(c *gc.C) {
r, err := mutex.Acquire(s.spec())
c.Assert(err, jc.ErrorIsNil)
r.Release()
}
func (s *mutexSuite) TestLockContentionWithinProcessTimeout(c *gc.C) {
spec := s.spec()
spec.Timeout = time.Millisecond
r, err := mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
defer r.Release()
second, err := mutex.Acquire(spec)
c.Assert(second, gc.IsNil)
c.Assert(err, gc.Equals, mutex.ErrTimeout)
}
func (s *mutexSuite) TestLockAfterTimeout(c *gc.C) {
spec := s.spec()
spec.Timeout = time.Nanosecond
r, err := mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
defer r.Release()
_, err = mutex.Acquire(spec)
c.Assert(err, gc.Equals, mutex.ErrTimeout)
r.Release()
r, err = mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
r.Release()
}
func (s *mutexSuite) TestLockContentionWithinProcessCancel(c *gc.C) {
cancel := make(chan struct{})
done := make(chan struct{})
spec := s.spec()
spec.Cancel = cancel
r, err := mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
defer r.Release()
go func() {
second, err := mutex.Acquire(spec)
c.Check(second, gc.IsNil)
c.Check(err, gc.Equals, mutex.ErrCancelled)
close(done)
}()
close(cancel)
<-done
}
func (s *mutexSuite) TestSecondReleaseFine(c *gc.C) {
r, err := mutex.Acquire(s.spec())
c.Assert(err, jc.ErrorIsNil)
r.Release()
r.Release()
}
func (s *mutexSuite) TestDifferentNamesDontBlock(c *gc.C) {
spec1 := s.spec()
spec2 := spec1
spec2.Name = fmt.Sprintf("other-%d", os.Getpid())
r1, err := mutex.Acquire(spec1)
c.Assert(err, jc.ErrorIsNil)
defer r1.Release()
r2, err := mutex.Acquire(spec2)
c.Assert(err, jc.ErrorIsNil)
defer r2.Release()
}
func (s *mutexSuite) TestLockBlocks(c *gc.C) {
kill := make(chan struct{})
spec := s.spec()
// this will block until the other process has the lock.
remote := LockFromAnotherProc(c, spec.Name, kill, true, true)
acquired := make(chan struct{})
done := make(chan struct{})
go func() {
r, err := mutex.Acquire(spec)
if c.Check(err, gc.IsNil) {
close(acquired)
r.Release()
}
close(done)
}()
// Waiting for something not to happen is inherently hard...
select {
case <-acquired:
c.Fatalf("Unexpected lock acquisition")
case <-time.After(shortWait * 2):
// all good.
}
close(kill)
<-done
<-remote
}
func (s *mutexSuite) TestProcessReleasesWhenDead(c *gc.C) {
spec := s.spec()
kill := make(chan struct{})
// this will block until the other process has the lock.
remote := LockFromAnotherProc(c, spec.Name, kill, false, false)
acquired := make(chan struct{})
done := make(chan struct{})
go func() {
r, err := mutex.Acquire(spec)
if c.Check(err, gc.IsNil) {
close(acquired)
r.Release()
}
close(done)
}()
close(kill)
select {
case <-acquired:
// all good.
case <-time.After(appWait):
c.Fatalf("timout waiting for mutex to be acquired")
}
<-done
<-remote
}
func (s *mutexSuite) TestStress(c *gc.C) {
const lockAttempts = 200
const concurrentLocks = 10
var counter = new(int64)
// Use atomics to update lockState to make sure the lock isn't held by
// someone else. A value of 1 means locked, 0 means unlocked.
var lockState = new(int32)
var wg sync.WaitGroup
spec := s.spec()
var stress = func() {
defer wg.Done()
for i := 0; i < lockAttempts; i++ {
r, err := mutex.Acquire(spec)
if !c.Check(err, jc.ErrorIsNil) {
return
}
state := atomic.AddInt32(lockState, 1)
if !c.Check(state, gc.Equals, int32(1)) {
return
}
// Tell the go routine scheduler to give a slice to someone else
// while we have this locked.
runtime.Gosched()
// need to decrement prior to unlock to avoid the race of someone
// else grabbing the lock before we decrement the state.
atomic.AddInt32(lockState, -1)
r.Release()
// increment the general counter
atomic.AddInt64(counter, 1)
}
}
for i := 0; i < concurrentLocks; i++ {
wg.Add(1)
go stress()
}
wg.Wait()
c.Assert(*counter, gc.Equals, int64(lockAttempts*concurrentLocks))
}
// TestMutexNotInherited tests that subprocesses do not inherit mutexes.
func (s *mutexSuite) TestMutexNotInherited(c *gc.C) {
spec := s.spec()
r, err := mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
defer r.Release()
kill := make(chan struct{})
SleepFromAnotherProc(c, kill)
defer close(kill)
r.Release()
// We should be able to acquire again now.
spec.Timeout = time.Nanosecond
r, err = mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
r.Release()
}
// TestFilePermissions tests that the file permissions are correct.
func (s *mutexSuite) TestFilePermissions(c *gc.C) {
spec := s.spec()
r, err := mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
defer r.Release()
filePath := filepath.Join(os.TempDir(), "juju-"+spec.Name)
fileInfo, err := os.Stat(filePath)
c.Assert(err, jc.ErrorIsNil)
stat, ok := fileInfo.Sys().(*syscall.Stat_t)
c.Assert(ok, jc.IsTrue)
current, err := user.Current()
c.Assert(err, jc.ErrorIsNil)
c.Assert(fmt.Sprintf("%d", stat.Uid), gc.Equals, current.Uid)
c.Assert(fmt.Sprintf("%d", stat.Gid), gc.Equals, current.Gid)
}
// TestFilePermissionsWithSudo tests that the file permissions are correct.
func (s *mutexSuite) TestFilePermissionsWithSudoEnvars(c *gc.C) {
ctrl := gomock.NewController(c)
defer ctrl.Finish()
envion := NewMockEnvironment(ctrl)
restore := jt.PatchValue(mutex.Envars, envion)
defer restore()
current, err := user.Current()
c.Assert(err, jc.ErrorIsNil)
exp := envion.EXPECT()
exp.LookupEnv("SUDO_COMMAND").Return("test", true)
exp.Getenv("SUDO_UID").Return(current.Uid)
exp.Getenv("SUDO_GID").Return(current.Gid)
spec := s.spec()
r, err := mutex.Acquire(spec)
c.Assert(err, jc.ErrorIsNil)
defer r.Release()
filePath := filepath.Join(os.TempDir(), "juju-"+spec.Name)
fileInfo, err := os.Stat(filePath)
c.Assert(err, jc.ErrorIsNil)
stat, ok := fileInfo.Sys().(*syscall.Stat_t)
c.Assert(ok, jc.IsTrue)
c.Assert(fmt.Sprintf("%d", stat.Uid), gc.Equals, current.Uid)
c.Assert(fmt.Sprintf("%d", stat.Gid), gc.Equals, current.Gid)
}
// LockFromAnotherProc will launch a process and block until that process has
// created the lock file. If we time out waiting for the other process to take
// the lock, this function will fail the current test.
func LockFromAnotherProc(c *gc.C, name string, kill chan struct{}, wait, unlock bool) (done chan struct{}) {
listener, err := net.Listen("tcp", "localhost:0")
c.Assert(err, jc.ErrorIsNil)
defer listener.Close()
cmd := exec.Command(os.Args[0], "-test.run", "TestLockFromOtherProcess")
cmd.Env = append(
// We must preserve os.Environ() on Windows,
// or the subprocess will fail in weird and
// wonderful ways.
os.Environ(),
"MUTEX_TEST_HELPER_WANTED=1",
"MUTEX_TEST_HELPER_NAME="+name,
"MUTEX_TEST_HELPER_ADDR="+listener.Addr().String(),
"MUTEX_TEST_HELPER_WAIT="+fmt.Sprint(unlock),
"MUTEX_TEST_HELPER_UNLOCK="+fmt.Sprint(unlock),
)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Start(); err != nil {
c.Fatalf("error starting other proc: %v", err)
}
done = make(chan struct{})
go func() {
cmd.Wait()
close(done)
}()
go func() {
select {
case <-kill:
// this may fail, but there's not much we can do about it
_ = cmd.Process.Kill()
case <-done:
}
}()
haveLock := make(chan struct{})
go func() {
conn, err := listener.Accept()
if c.Check(err, jc.ErrorIsNil) {
// Just close it, the signal is enough.
conn.Close()
close(haveLock)
}
}()
select {
case <-done:
c.Fatalf("other process failed before acquiring lock")
case <-haveLock:
// all good
case <-time.After(appWait):
c.Fatalf("other process failed to acquire lock")
}
return done
}
// SleepFromAnotherProc will launch a process and cause it to sleep
// for a minute, to prove that subprocesses do not inherit the mutex.
func SleepFromAnotherProc(c *gc.C, kill chan struct{}) (done chan struct{}) {
listener, err := net.Listen("tcp", "localhost:0")
c.Assert(err, jc.ErrorIsNil)
defer listener.Close()
cmd := exec.Command(os.Args[0], "-test.run", "TestSleepFromOtherProcess")
cmd.Env = append(
// We must preserve os.Environ() on Windows,
// or the subprocess will fail in weird and
// wonderful ways.
os.Environ(),
"MUTEX_TEST_HELPER_WANTED=1",
"MUTEX_TEST_HELPER_ADDR="+listener.Addr().String(),
)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
c.Assert(cmd.Start(), jc.ErrorIsNil)
done = make(chan struct{})
go func() {
defer close(done)
cmd.Wait()
}()
go func() {
select {
case <-kill:
cmd.Process.Kill()
case <-done:
}
}()
started := make(chan struct{})
go func() {
conn, err := listener.Accept()
if c.Check(err, jc.ErrorIsNil) {
// Just close it, the signal is enough.
conn.Close()
close(started)
}
}()
select {
case <-started:
case <-done:
c.Fatalf("other process exited")
case <-time.After(appWait):
c.Fatalf("timed out waiting for other process to connect")
}
return done
}
func TestLockFromOtherProcess(t *testing.T) {
if os.Getenv("MUTEX_TEST_HELPER_WANTED") == "" {
return
}
name := os.Getenv("MUTEX_TEST_HELPER_NAME")
unlock := os.Getenv("MUTEX_TEST_HELPER_UNLOCK") == "true"
wait := os.Getenv("MUTEX_TEST_HELPER_WAIT") == "true"
spec := mutex.Spec{
Name: name,
Clock: &fakeClock{shortWait},
Delay: shortWait,
}
r, err := mutex.Acquire(spec)
if err != nil {
fmt.Fprintf(os.Stderr, "error acquiring mutex %q: %v", name, err)
os.Exit(1)
}
// Connect to the first process to let it know we have the connection.
addr := os.Getenv("MUTEX_TEST_HELPER_ADDR")
_, err = net.Dial("tcp", addr)
// We don't care about the connection because the server will just close the
// connection anyway.
if err != nil {
fmt.Fprintf(os.Stderr, "error notifying primary process: %v", err)
os.Exit(1)
}
if wait {
time.Sleep(longWait)
}
if unlock {
r.Release()
}
os.Exit(0)
}
func TestSleepFromOtherProcess(t *testing.T) {
if os.Getenv("MUTEX_TEST_HELPER_WANTED") == "" {
return
}
addr := os.Getenv("MUTEX_TEST_HELPER_ADDR")
_, err := net.Dial("tcp", addr)
if err != nil {
fmt.Fprintf(os.Stderr, "error notifying primary process: %v \n", err)
os.Exit(1)
}
time.Sleep(time.Minute)
os.Exit(0)
}
type fakeClock struct {
delay time.Duration
}
func (f *fakeClock) After(time.Duration) <-chan time.Time {
return time.After(f.delay)
}
func (f *fakeClock) Now() time.Time {
return time.Now()
}
mutex-2.0.0/mutex_windows.go 0000664 0000000 0000000 00000014364 14176637215 0016142 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package mutex
import (
"runtime"
"sync"
"syscall"
"time"
"unsafe"
"github.com/juju/errors"
)
var (
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateMutex = modkernel32.NewProc("CreateMutexW")
procReleaseMutex = modkernel32.NewProc("ReleaseMutex")
procWaitForMultipleObjects = modkernel32.NewProc("WaitForMultipleObjects")
procCreateEvent = modkernel32.NewProc("CreateEventW")
procSetEvent = modkernel32.NewProc("SetEvent")
)
const (
_ERROR_ALREADY_EXISTS = 183
_WAIT_OBJECT_0 = 0x00000000
_WAIT_ABANDONED_0 = 0x00000080
_WAIT_TIMEOUT = 0x00000102
_INFINITE = 0xffffffff
)
type mutex struct {
name string
mu sync.Mutex
release chan struct{}
released chan struct{}
}
func acquire(spec Spec, timeoutCh <-chan time.Time) (Releaser, error) {
// Avoid further work if the acquisition
// has already been cancelled.
select {
case <-spec.Cancel:
return nil, ErrCancelled
default:
}
m := &mutex{
name: spec.Name,
release: make(chan struct{}),
released: make(chan struct{}),
}
releaseCh := m.release
errCh := make(chan error, 1)
go func() {
defer close(m.released)
// ReleaseMutex must be called
// from the same OS thread that
// owns the mutex, i.e. the one
// that acquires it.
//
// Note that this also prevents
// any other goroutines from
// running on the same OS thread
// while the mutex is held, so
// we prevent reentrant lock
// acquisitions.
runtime.LockOSThread()
handle, err := acquireMutex(
"juju-mutex-"+spec.Name,
spec.Timeout,
spec.Cancel,
)
errCh <- err
if err != nil {
return
}
// Wait until the mutex is Release()d, and
// then release and close the mutex.
<-releaseCh
// NOTE(axw) it is not enough to just close
// the handle, it must be released first.
// It will only be abandoned when the OS
// thread underlying this goroutine exits.
// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684266(v=vs.85).aspx
if err := releaseMutex(handle); err != nil {
panic(err)
}
if err := syscall.Close(handle); err != nil {
panic(err)
}
}()
if err := <-errCh; err != nil {
// The acquireMutex call failed, which means
// the goroutine will exit. Wait for it to
// clean up before returning.
<-m.released
return nil, err
}
return m, nil
}
// Release implements Releaser.
func (m *mutex) Release() {
m.mu.Lock()
defer m.mu.Unlock()
if m.release != nil {
close(m.release)
m.release = nil
}
<-m.released
}
func acquireMutex(
name string,
timeout time.Duration,
cancel <-chan struct{},
) (syscall.Handle, error) {
mutexName, err := syscall.UTF16PtrFromString(name)
if err != nil {
return syscall.InvalidHandle, errors.Trace(err)
}
result, _, errno := syscall.Syscall(
procCreateMutex.Addr(), 3,
uintptr(0), // attributes
uintptr(0), // initial owner
uintptr(unsafe.Pointer(mutexName)),
)
if result == 0 {
if errno != 0 {
return syscall.InvalidHandle, errno
}
return syscall.InvalidHandle, syscall.EINVAL
}
// Mutex was successfully created, or already exists.
// In either case, we don't own the mutex, and must
// wait for it below.
handle := syscall.Handle(result)
handles := []syscall.Handle{handle}
if cancel != nil {
eventHandle, err := createEvent()
if err != nil {
return syscall.InvalidHandle, errors.Trace(err)
}
defer syscall.Close(eventHandle)
// Put the event handle first, so
// cancellation takes precedence.
handles = []syscall.Handle{eventHandle, handle}
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-done:
case <-cancel:
setEvent(eventHandle)
}
}()
}
if timeout == 0 {
// -1 indicates to waitForMultipleObjects
// that it should wait indefinitely.
timeout = -1
}
i, err := waitForMultipleObjects(handles, timeout)
if err != nil {
syscall.Close(handle)
return syscall.InvalidHandle, err
}
if i+1 == len(handles) {
return handle, nil
}
syscall.Close(handle)
return syscall.InvalidHandle, ErrCancelled
}
func releaseMutex(handle syscall.Handle) error {
result, _, errno := syscall.Syscall(procReleaseMutex.Addr(), 3, uintptr(handle), uintptr(1), 0)
if result == 0 {
if errno != 0 {
return errno
}
return syscall.EINVAL
}
return nil
}
// waitForMultipleObjects calls the WaitForMultipleObjects Windows API, with the
// given handles and timeout. If the timeout value is negative, there is no timeout.
//
// The return value is the index of the handle that was signalled, or an error.
//
// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
func waitForMultipleObjects(handles []syscall.Handle, timeout time.Duration) (int, error) {
timeoutMillis := uintptr(_INFINITE)
if timeout >= 0 {
timeoutMillis = uintptr(timeout.Seconds() * 1000)
}
result, _, errno := syscall.Syscall6(
procWaitForMultipleObjects.Addr(), 4,
uintptr(len(handles)),
uintptr(unsafe.Pointer(&handles[0])),
uintptr(0), // FALSE (don't wait for all)
timeoutMillis,
0, 0,
)
if result == _WAIT_TIMEOUT {
return -1, ErrTimeout
}
if result >= _WAIT_OBJECT_0 && result < uintptr(_WAIT_OBJECT_0+len(handles)) {
return int(result - _WAIT_OBJECT_0), nil
}
if result >= _WAIT_ABANDONED_0 && result < uintptr(_WAIT_ABANDONED_0+len(handles)) {
// The thread that owned the mutex exited without releasing the
// mutex. Ownership of the mutex is still granted as above.
return int(result - _WAIT_ABANDONED_0), nil
}
if errno != 0 {
return -1, errno
}
return -1, syscall.GetLastError()
}
func createEvent() (syscall.Handle, error) {
result, _, errno := syscall.Syscall6(
procCreateEvent.Addr(), 4,
uintptr(0), // lpEventAttributes
uintptr(1), // bManualReset
uintptr(0), // bInitialState
uintptr(0), // lpName
0, 0,
)
if result == 0 {
if errno != 0 {
return syscall.Handle(0), errno
}
return syscall.Handle(0), syscall.EINVAL
}
return syscall.Handle(result), nil
}
func setEvent(handle syscall.Handle) error {
result, _, errno := syscall.Syscall(procSetEvent.Addr(), 1, uintptr(handle), 0, 0)
if result == 0 {
if errno != 0 {
return errno
}
return syscall.EINVAL
}
return nil
}
mutex-2.0.0/package_test.go 0000664 0000000 0000000 00000000316 14176637215 0015650 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package mutex_test
import (
"testing"
gc "gopkg.in/check.v1"
)
func Test(t *testing.T) {
gc.TestingT(t)
}