├── .gitignore ├── LICENSE ├── README.md ├── azure-pipelines.yml ├── errors.go ├── go.mod ├── go.sum ├── lock.go ├── locker_client.go ├── locker_client_oldmysql_test.go └── locker_client_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | vendor/ 16 | 17 | # IDE meta 18 | .idea 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-mysql-lock 2 | [![GoDoc](https://godoc.org/github.com/sanketplus/go-mysql-lock?status.svg)](https://godoc.org/github.com/sanketplus/go-mysql-lock) 3 | [![Azure DevOps builds](https://img.shields.io/azure-devops/build/sanketplus/go-mysql-lock/1)](https://dev.azure.com/sanketplus/go-mysql-lock/_build?definitionId=1) 4 | [![Azure DevOps coverage](https://img.shields.io/azure-devops/coverage/sanketplus/go-mysql-lock/1)](https://dev.azure.com/sanketplus/go-mysql-lock/_build?definitionId=1) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/sanketplus/go-mysql-lock)](https://goreportcard.com/report/github.com/sanketplus/go-mysql-lock) 6 | 7 | go-mysql-lock provides locking primitive based on MySQL's [GET_LOCK](https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html#function_get-lock) 8 | Lock names are strings and MySQL enforces a maximum length on lock names of 64 characters. 9 | 10 | ## Use cases 11 | Though there are mature locking primitives provided by systems like Zookeeper and etcd, when you have an application which 12 | is primarily dependent on MySQL for its uptime and health, added resiliency provided by systems just mentioned doesn't add 13 | much benefit. go-mysql-lock helps when you have multiple application instances which are backed by a common mysql instance 14 | and you want only one of those application instances to hold a lock and do certain tasks. 15 | 16 | #### Installation 17 | ```$bash 18 | go get github.com/sanketplus/go-mysql-lock 19 | ``` 20 | 21 | ### Example: 22 | 23 | ```go 24 | package main 25 | 26 | import ( 27 | "context" 28 | "database/sql" 29 | 30 | _ "github.com/go-sql-driver/mysql" 31 | "github.com/sanketplus/go-mysql-lock" 32 | ) 33 | 34 | func main() { 35 | db, _ := sql.Open("mysql", "root@tcp(localhost:3306)/dyno_test") 36 | 37 | locker := gomysqllock.NewMysqlLocker(db) 38 | 39 | lock, _ := locker.Obtain("foo") 40 | lock.Release() 41 | } 42 | ``` 43 | 44 | ## Features 45 | #### Customizable Refresh Period 46 | Once the lock is obtained, a goroutine periodically (default every 1 second) keeps pinging on connection since the lock 47 | is valid on a connection(session). To configure the refresh interval 48 | ```go 49 | locker := gomysqllock.NewMysqlLocker(db, gomysqllock.WithRefreshInterval(time.Millisecond*500)) 50 | ``` 51 | 52 | #### Obtain Lock With Context 53 | By default, an attempt to obtain a lock is backed by background context. That means the `Obtain` call would block 54 | indefinitely. Optionally, an `Obtain` call can be made with user given context which will get cancelled with the given 55 | context. 56 | 57 | The following call will give up after a second if the lock was not obtained. 58 | ```go 59 | locker := gomysqllock.NewMysqlLocker(db) 60 | ctxShort, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second)) 61 | lock, err := locker.ObtainContext(ctxShort, "key") 62 | ``` 63 | 64 | #### Obtain Lock With (MySQL) Timeout 65 | MySQL has the ability to timeout and return if the lock can't be acquired in a given number of seconds. 66 | This timeout can be specified when using `ObtainTimeout` and `ObtainTimeoutContext`. On timeout, `ErrMySQLTimeout` is returned, and the lock is not obtained. 67 | 68 | The following call will give up after a second if the lock was not obtained, using MySQL timeout option: 69 | ```go 70 | locker := gomysqllock.NewMysqlLocker(db) 71 | lock, err := locker.ObtainTimeout("key", 1) 72 | ``` 73 | 74 | #### Know When The Lock is Lost 75 | Obtained lock has a context which is cancelled if the lock is lost. This is determined while a goroutine keeps pinging the connection. If there is an error while pinging, assuming connection has an error, the context is cancelled. And the lock owner gets notified of the lost lock. 76 | ```go 77 | context := lock.GetContext() 78 | ``` 79 | 80 | ### Compatibility 81 | 82 | This library is tested (automatically) against MySQL 8 and MariaDB 10.1, and it should work for MariaDB versions >= 10.1, MySQL versions >= 5.6, and Vitess versions >= 15.0. 83 | 84 | Note that `GET_LOCK` function won't lock indefinitely on MariaDB 10.1 / MySQL 5.6 and older, as `0` or negative value for timeouts are not accepted in those versions. This means that **in MySQL <= 5.6 / MariaDB <= 10.1 you can't use `Obtain` or `ObtainContext`**. To achieve a similar goal, you can use `ObtainTimeout` (and `ObtainTimeoutContext`) using a very high timeout value. 85 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # Go 2 | # Build your Go project. 3 | # Add steps that test, save build artifacts, deploy, and more: 4 | # https://docs.microsoft.com/azure/devops/pipelines/languages/go 5 | 6 | trigger: 7 | - master 8 | - dev 9 | 10 | pool: 11 | vmImage: 'ubuntu-latest' 12 | 13 | variables: 14 | GOVERSION: 1.13 15 | GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path 16 | GOBIN: '$(GOPATH)/bin' # Go binaries path 17 | 18 | steps: 19 | - script: | 20 | docker run -d -p 3306:3306 --name mysql8 -e MYSQL_ALLOW_EMPTY_PASSWORD=yes mysql:8 21 | displayName: 'Start Mysql docker' 22 | 23 | - script: | 24 | docker run -d -p 3305:3306 --name mariadb101 -e MYSQL_ALLOW_EMPTY_PASSWORD=yes mariadb:10.1 25 | displayName: 'Start old MariaDB docker' 26 | 27 | - task: GoTool@0 28 | displayName: 'Use Go $(GOVERSION)' 29 | inputs: 30 | version: '$(GOVERSION)' 31 | 32 | - task: Go@0 33 | inputs: 34 | command: 'get' 35 | arguments: 'github.com/axw/gocov/...' 36 | 37 | - task: Go@0 38 | inputs: 39 | command: 'get' 40 | arguments: 'github.com/AlekSi/gocov-xml' 41 | 42 | - script: | 43 | $GOBIN/gocov test -v | $GOBIN/gocov-xml > coverage.xml 44 | workingDirectory: $(System.DefaultWorkingDirectory) 45 | displayName: "Execute Tests and Generate Coverage Report" 46 | 47 | - task: PublishCodeCoverageResults@1 48 | inputs: 49 | codeCoverageTool: 'Cobertura' 50 | summaryFileLocation: '$(System.DefaultWorkingDirectory)/coverage.xml' 51 | failIfCoverageEmpty: true 52 | displayName: "Publish Coverage Results" 53 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package gomysqllock 2 | 3 | import "errors" 4 | 5 | // ErrGetLockContextCancelled is returned when user given context is cancelled while trying to obtain the lock 6 | var ErrGetLockContextCancelled = errors.New("context cancelled while trying to obtain lock") 7 | 8 | // ErrMySQLTimeout is returned when the MySQL server can't acquire the lock in the specified timeout 9 | var ErrMySQLTimeout = errors.New("(mysql) timeout while acquiring the lock") 10 | 11 | // ErrMySQLInternalError is returned when MySQL is returning a generic internal error 12 | var ErrMySQLInternalError = errors.New("internal mysql error acquiring the lock") 13 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/sanketplus/go-mysql-lock 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/go-sql-driver/mysql v1.5.0 7 | github.com/stretchr/testify v1.6.1 8 | go.uber.org/goleak v1.1.10 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= 4 | github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= 5 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 6 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 7 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 8 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 9 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 10 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 11 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 12 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 13 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 14 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= 15 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 16 | go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0= 17 | go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= 18 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 19 | golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= 20 | golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 21 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 22 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 23 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 24 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 25 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 26 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 27 | golang.org/x/tools v0.0.0-20191108193012-7d206e10da11 h1:Yq9t9jnGoR+dBuitxdo9l6Q7xh/zOyNnYUtDKaQ3x0E= 28 | golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 29 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 30 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 31 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 32 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 33 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 34 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 35 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 36 | -------------------------------------------------------------------------------- /lock.go: -------------------------------------------------------------------------------- 1 | package gomysqllock 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "errors" 7 | "sync" 8 | "time" 9 | ) 10 | 11 | var ( 12 | ErrLockReleased = errors.New("Lock already released") 13 | ) 14 | 15 | // Lock denotes an acquired lock and presents two methods, one for getting the context which is cancelled when the lock 16 | // is lost/released and other for Releasing the lock 17 | type Lock struct { 18 | key string 19 | conn *sql.Conn 20 | unlocker chan (struct{}) 21 | lostLockContext context.Context 22 | cancelFunc context.CancelFunc 23 | released bool 24 | mx sync.Mutex 25 | } 26 | 27 | // GetContext returns a context which is cancelled when the lock is lost or released 28 | func (l *Lock) GetContext() context.Context { 29 | return l.lostLockContext 30 | } 31 | 32 | // Release unlocks the lock 33 | func (l *Lock) Release() error { 34 | l.mx.Lock() 35 | defer l.mx.Unlock() 36 | if !l.released { 37 | l.released = true 38 | l.unlocker <- struct{}{} 39 | l.conn.ExecContext(context.Background(), "DO RELEASE_LOCK(?)", l.key) 40 | return l.conn.Close() 41 | } 42 | 43 | return ErrLockReleased 44 | } 45 | 46 | func (l *Lock) refresher(duration time.Duration, cancelFunc context.CancelFunc) { 47 | for { 48 | select { 49 | case <-time.After(duration): 50 | deadline := time.Now().Add(duration) 51 | contextDeadline, deadlineCancelFunc := context.WithDeadline(context.Background(), deadline) 52 | 53 | // try refresh, else cancel 54 | err := l.conn.PingContext(contextDeadline) 55 | if err != nil { 56 | cancelFunc() 57 | deadlineCancelFunc() 58 | // this will make sure connection is closed 59 | l.Release() 60 | return 61 | } 62 | deadlineCancelFunc() // to avoid context leak 63 | case <-l.unlocker: 64 | cancelFunc() 65 | return 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /locker_client.go: -------------------------------------------------------------------------------- 1 | package gomysqllock 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "fmt" 7 | "time" 8 | ) 9 | 10 | // DefaultRefreshInterval is the periodic duration with which a connection is refreshed/pinged 11 | const DefaultRefreshInterval = time.Second 12 | 13 | type lockerOpt func(locker *MysqlLocker) 14 | 15 | // MysqlLocker is the client which provide APIs to obtain lock 16 | type MysqlLocker struct { 17 | db *sql.DB 18 | refreshInterval time.Duration 19 | } 20 | 21 | // NewMysqlLocker returns an instance of locker which can be used to obtain locks 22 | func NewMysqlLocker(db *sql.DB, lockerOpts ...lockerOpt) *MysqlLocker { 23 | locker := &MysqlLocker{ 24 | db: db, 25 | refreshInterval: DefaultRefreshInterval, 26 | } 27 | 28 | for _, opt := range lockerOpts { 29 | opt(locker) 30 | } 31 | 32 | return locker 33 | } 34 | 35 | // WithRefreshInterval sets the duration for refresh interval for each obtained lock 36 | func WithRefreshInterval(d time.Duration) lockerOpt { 37 | return func(l *MysqlLocker) { l.refreshInterval = d } 38 | } 39 | 40 | // Obtain tries to acquire lock (with no MySQL timeout) with background context. This call is expected to block is lock is already held 41 | func (l MysqlLocker) Obtain(key string) (*Lock, error) { 42 | return l.ObtainTimeoutContext(context.Background(), key, -1) 43 | } 44 | 45 | // ObtainTimeout tries to acquire lock with background context and a MySQL timeout. This call is expected to block is lock is already held 46 | func (l MysqlLocker) ObtainTimeout(key string, timeout int) (*Lock, error) { 47 | return l.ObtainTimeoutContext(context.Background(), key, timeout) 48 | } 49 | 50 | // ObtainContext tries to acquire lock and gives up when the given context is cancelled 51 | func (l MysqlLocker) ObtainContext(ctx context.Context, key string) (*Lock, error) { 52 | return l.ObtainTimeoutContext(ctx, key, -1) 53 | } 54 | 55 | // ObtainTimeoutContext tries to acquire lock and gives up when the given context is cancelled 56 | func (l MysqlLocker) ObtainTimeoutContext(ctx context.Context, key string, timeout int) (*Lock, error) { 57 | cancellableContext, cancelFunc := context.WithCancel(context.Background()) 58 | 59 | dbConn, err := l.db.Conn(ctx) 60 | if err != nil { 61 | cancelFunc() 62 | return nil, fmt.Errorf("failed to get a db connection: %w", err) 63 | } 64 | 65 | row := dbConn.QueryRowContext(ctx, "SELECT GET_LOCK(?, ?)", key, timeout) 66 | 67 | var res sql.NullInt32 68 | err = row.Scan(&res) 69 | if err != nil { 70 | //Close database connection whenever failed to acquire lock 71 | defer dbConn.Close() 72 | // mysql error does not tell if it was due to context closing, checking it manually 73 | select { 74 | case <-ctx.Done(): 75 | cancelFunc() 76 | return nil, ErrGetLockContextCancelled 77 | default: 78 | break 79 | } 80 | cancelFunc() 81 | return nil, fmt.Errorf("could not read mysql response: %w", err) 82 | } else if !res.Valid { 83 | //Close database connection whenever failed to acquire lock 84 | defer dbConn.Close() 85 | // Internal MySQL error occurred, such as out-of-memory, thread killed or others (the doc is not clear) 86 | // Note: some MySQL/MariaDB versions (like MariaDB 10.1) does not support -1 as timeout parameters 87 | cancelFunc() 88 | return nil, ErrMySQLInternalError 89 | } else if res.Int32 == 0 { 90 | //Close database connection whenever failed to acquire lock 91 | defer dbConn.Close() 92 | // MySQL Timeout 93 | cancelFunc() 94 | return nil, ErrMySQLTimeout 95 | } 96 | 97 | lock := &Lock{ 98 | key: key, 99 | conn: dbConn, 100 | unlocker: make(chan struct{}, 1), 101 | lostLockContext: cancellableContext, 102 | cancelFunc: cancelFunc, 103 | } 104 | go lock.refresher(l.refreshInterval, cancelFunc) 105 | 106 | return lock, nil 107 | } 108 | -------------------------------------------------------------------------------- /locker_client_oldmysql_test.go: -------------------------------------------------------------------------------- 1 | package gomysqllock 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "strings" 7 | "testing" 8 | "time" 9 | 10 | _ "github.com/go-sql-driver/mysql" 11 | "github.com/stretchr/testify/assert" 12 | ) 13 | 14 | func setupDB_oldDB(t *testing.T) *sql.DB { 15 | db, err := sql.Open("mysql", "root@tcp(localhost:3305)/") 16 | assert.NoError(t, err, "failed to setup db") 17 | return db 18 | } 19 | 20 | func getLockContext_oldDB(ctx context.Context, t *testing.T, key string, db *sql.DB) *Lock { 21 | locker := NewMysqlLocker(db) 22 | l, err := locker.ObtainTimeoutContext(ctx, key, 100000) 23 | assert.NoError(t, err, "failed to obtain lock") 24 | return l 25 | } 26 | 27 | func getLock_oldDB(t *testing.T, key string, db *sql.DB) *Lock { 28 | locker := NewMysqlLocker(db) 29 | l, err := locker.ObtainTimeout(key, 10) 30 | assert.NoError(t, err, "failed to obtain lock") 31 | return l 32 | } 33 | 34 | func releaseLock_oldDB(t *testing.T, l *Lock) { 35 | err := l.Release() 36 | assert.NoError(t, err, "failed to release lock") 37 | } 38 | 39 | func TestMysqlLocker_LockContext_oldDB_Success(t *testing.T) { 40 | ctx := context.Background() 41 | db := setupDB_oldDB(t) 42 | key := "foo" 43 | lock := getLockContext_oldDB(ctx, t, key, db) 44 | lockContext := lock.GetContext() 45 | releaseLock_oldDB(t, lock) 46 | 47 | // making sure lock's context is done after lock is released 48 | select { 49 | case <-lockContext.Done(): 50 | default: 51 | assert.Fail(t, "lock's context is not cancelled after lock is released") 52 | } 53 | } 54 | 55 | func TestMysqlLocker_LockContext_oldDB_Timeout(t *testing.T) { 56 | db := setupDB_oldDB(t) 57 | locker := NewMysqlLocker(db, WithRefreshInterval(time.Millisecond*500)) 58 | key := "bar" 59 | 60 | // obtain lock 61 | lock := getLock_oldDB(t, key, db) 62 | 63 | // try to get the same lock with timeout context 64 | ctxShort, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(time.Second)) 65 | _, err := locker.ObtainTimeoutContext(ctxShort, key, 10) 66 | 67 | cancelFunc() 68 | assert.Equal(t, ErrGetLockContextCancelled, err) 69 | 70 | releaseLock_oldDB(t, lock) 71 | } 72 | 73 | func TestMysqlLocker_DBError_oldDB_AfterLock(t *testing.T) { 74 | db := setupDB_oldDB(t) 75 | key := "baz" 76 | 77 | // obtain lock 78 | lock := getLock_oldDB(t, key, db) 79 | lockContext := lock.GetContext() 80 | 81 | // perhaps also simulate db crash 82 | lock.conn.Close() 83 | 84 | // sleeping so that periodic refresher (running 1 sec by default) cancels the context 85 | time.Sleep(time.Second * 2) 86 | 87 | // making sure lock's context is done after db is closed 88 | select { 89 | case <-lockContext.Done(): 90 | assert.Contains(t, lockContext.Err().Error(), "context canceled") 91 | default: 92 | assert.Fail(t, "lock's context is not cancelled after lock is released") 93 | } 94 | } 95 | 96 | func TestMysqlLocker_Obtain_oldDB_DBError(t *testing.T) { 97 | // broken db connection 98 | db, _ := sql.Open("mysql", "root@tcp(localhost:33006)/") 99 | locker := NewMysqlLocker(db) 100 | 101 | _, err := locker.Obtain("test") 102 | assert.Contains(t, err.Error(), "failed to get a db connection") 103 | } 104 | 105 | func TestMysqlLocker_Obtain_oldDB_DBScanError(t *testing.T) { 106 | db, _ := sql.Open("mysql", "root@tcp(localhost:3305)/") 107 | locker := NewMysqlLocker(db) 108 | 109 | // setting very long key name shall result into error 110 | _, err := locker.Obtain(strings.Repeat("x", 100)) 111 | assert.Contains(t, err.Error(), "internal mysql error acquiring the lock") 112 | } 113 | -------------------------------------------------------------------------------- /locker_client_test.go: -------------------------------------------------------------------------------- 1 | //go:build !oldmysql 2 | // +build !oldmysql 3 | 4 | package gomysqllock 5 | 6 | import ( 7 | "context" 8 | "database/sql" 9 | "strings" 10 | "testing" 11 | "time" 12 | 13 | _ "github.com/go-sql-driver/mysql" 14 | "github.com/stretchr/testify/assert" 15 | "go.uber.org/goleak" 16 | ) 17 | 18 | func TestMain(m *testing.M) { 19 | // ignoring go routines spawned for db connection maintenance 20 | goleak.VerifyTestMain(m, goleak.IgnoreTopFunction("database/sql.(*DB).connectionOpener"), 21 | goleak.IgnoreTopFunction("github.com/go-sql-driver/mysql.(*mysqlConn).startWatcher.func1"), 22 | goleak.IgnoreTopFunction("database/sql.(*DB).connectionResetter"), 23 | ) 24 | } 25 | 26 | func setupDB(t *testing.T) *sql.DB { 27 | db, err := sql.Open("mysql", "root@tcp(localhost:3306)/") 28 | assert.NoError(t, err, "failed to setup db") 29 | return db 30 | } 31 | 32 | func getLockContext(ctx context.Context, t *testing.T, key string, db *sql.DB) *Lock { 33 | locker := NewMysqlLocker(db) 34 | l, err := locker.ObtainContext(ctx, key) 35 | assert.NoError(t, err, "failed to obtain lock") 36 | return l 37 | } 38 | 39 | func getLock(t *testing.T, key string, db *sql.DB) *Lock { 40 | locker := NewMysqlLocker(db) 41 | l, err := locker.Obtain(key) 42 | assert.NoError(t, err, "failed to obtain lock") 43 | return l 44 | } 45 | 46 | func releaseLock(t *testing.T, l *Lock) { 47 | err := l.Release() 48 | assert.NoError(t, err, "failed to release lock") 49 | } 50 | 51 | func TestMysqlLocker_LockContext_Success(t *testing.T) { 52 | ctx := context.Background() 53 | db := setupDB(t) 54 | key := "foo" 55 | lock := getLockContext(ctx, t, key, db) 56 | lockContext := lock.GetContext() 57 | releaseLock(t, lock) 58 | 59 | // making sure lock's context is done after lock is released 60 | select { 61 | case <-lockContext.Done(): 62 | default: 63 | assert.Fail(t, "lock's context is not cancelled after lock is released") 64 | } 65 | } 66 | 67 | func TestMysqlLocker_LockContext_Timeout(t *testing.T) { 68 | db := setupDB(t) 69 | locker := NewMysqlLocker(db, WithRefreshInterval(time.Millisecond*500)) 70 | key := "bar" 71 | 72 | // obtain lock 73 | lock := getLock(t, key, db) 74 | 75 | // try to get the same lock with timeout context 76 | ctxShort, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(time.Second)) 77 | _, err := locker.ObtainContext(ctxShort, key) 78 | 79 | cancelFunc() 80 | assert.Equal(t, ErrGetLockContextCancelled, err) 81 | 82 | releaseLock(t, lock) 83 | } 84 | 85 | func TestMysqlLocker_DBError_AfterLock(t *testing.T) { 86 | db := setupDB(t) 87 | key := "baz" 88 | 89 | // obtain lock 90 | lock := getLock(t, key, db) 91 | lockContext := lock.GetContext() 92 | 93 | // perhaps also simulate db crash 94 | lock.conn.Close() 95 | 96 | // sleeping so that periodic refresher (running 1 sec by default) cancels the context 97 | time.Sleep(time.Second * 2) 98 | 99 | // making sure lock's context is done after db is closed 100 | select { 101 | case <-lockContext.Done(): 102 | assert.Contains(t, lockContext.Err().Error(), "context canceled") 103 | default: 104 | assert.Fail(t, "lock's context is not cancelled after lock is released") 105 | } 106 | } 107 | 108 | func TestMysqlLocker_Obtain_DBError(t *testing.T) { 109 | // broken db connection 110 | db, _ := sql.Open("mysql", "root@tcp(localhost:33006)/") 111 | locker := NewMysqlLocker(db) 112 | 113 | _, err := locker.Obtain("test") 114 | assert.Contains(t, err.Error(), "failed to get a db connection") 115 | } 116 | 117 | func TestMysqlLocker_Obtain_DBScanError(t *testing.T) { 118 | db, _ := sql.Open("mysql", "root@tcp(localhost:3306)/") 119 | locker := NewMysqlLocker(db) 120 | 121 | // setting very long key name shall result into error 122 | _, err := locker.Obtain(strings.Repeat("x", 100)) 123 | assert.Contains(t, err.Error(), "could not read mysql response") 124 | } 125 | 126 | func TestMysqlLocker_Multiple_Release(t *testing.T) { 127 | ctx := context.Background() 128 | db := setupDB(t) 129 | key := "foo" 130 | lock := getLockContext(ctx, t, key, db) 131 | lockContext := lock.GetContext() 132 | releaseLock(t, lock) 133 | 134 | // making sure lock's context is done after lock is released 135 | select { 136 | case <-lockContext.Done(): 137 | default: 138 | assert.Fail(t, "lock's context is not cancelled after lock is released") 139 | } 140 | 141 | // Attempt to release a second time. We expect to get an error indicating the lock is 142 | // already released. 143 | err := lock.Release() 144 | assert.Equal(t, err, ErrLockReleased, "expected an error indicating that the lock was already released") 145 | } 146 | --------------------------------------------------------------------------------