From 0b6c92cd6a9f149ff5c57285464b556911e33e76 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 20 Dec 2022 11:29:50 +0800 Subject: [PATCH 01/17] create a lock abstract layer and remove old one --- go.mod | 3 ++ go.sum | 40 +++++++++++++- modules/sync/exclusive_pool.go | 69 ------------------------ modules/sync/lock.go | 92 ++++++++++++++++++++++++++++++++ modules/sync/lock_test.go | 11 ++++ modules/sync/status_pool.go | 57 -------------------- modules/sync/status_pool_test.go | 31 ----------- services/cron/cron.go | 4 -- services/cron/tasks.go | 7 ++- services/pull/check.go | 7 ++- services/pull/merge.go | 11 ++-- services/pull/pull.go | 8 ++- services/pull/update.go | 6 ++- services/repository/transfer.go | 18 +++---- services/wiki/wiki.go | 16 +++--- 15 files changed, 184 insertions(+), 196 deletions(-) delete mode 100644 modules/sync/exclusive_pool.go create mode 100644 modules/sync/lock.go create mode 100644 modules/sync/lock_test.go delete mode 100644 modules/sync/status_pool.go delete mode 100644 modules/sync/status_pool_test.go diff --git a/go.mod b/go.mod index cf3d71fa510de..60ae9729063e2 100644 --- a/go.mod +++ b/go.mod @@ -41,6 +41,7 @@ require ( github.com/go-git/go-git/v5 v5.4.3-0.20220529141257-bc1f419cebcf github.com/go-ldap/ldap/v3 v3.4.4 github.com/go-redis/redis/v8 v8.11.5 + github.com/go-redsync/redsync/v4 v4.7.1 github.com/go-sql-driver/mysql v1.6.0 github.com/go-swagger/go-swagger v0.30.3 github.com/go-testfixtures/testfixtures/v3 v3.8.1 @@ -203,7 +204,9 @@ require ( github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect + github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-multierror v1.1.0 // indirect github.com/hashicorp/go-retryablehttp v0.7.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/imdario/mergo v0.3.13 // indirect diff --git a/go.sum b/go.sum index 4ef817eaa29f0..60f9d3393e4af 100644 --- a/go.sum +++ b/go.sum @@ -554,10 +554,18 @@ github.com/go-openapi/validate v0.21.0/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUri github.com/go-openapi/validate v0.22.0 h1:b0QecH6VslW/TxtpKgzpO1SNG7GU2FsaqKdP1E2T50Y= github.com/go-openapi/validate v0.22.0/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= github.com/go-redis/redis v6.15.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg= github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= github.com/go-redis/redis/v8 v8.4.0/go.mod h1:A1tbYoHSa1fXwN+//ljcCYYJeLmVrwL9hbQN45Jdy0M= +github.com/go-redis/redis/v8 v8.11.4/go.mod h1:2Z2wHZXdQpCDXEGzqMockDpNyYvi2l4Pxt6RJr792+w= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= +github.com/go-redis/redis/v9 v9.0.0-beta.2 h1:ZSr84TsnQyKMAg8gnV+oawuQezeJR11/09THcWCQzr4= +github.com/go-redis/redis/v9 v9.0.0-beta.2/go.mod h1:Bldcd/M/bm9HbnNPi/LUtYBSD8ttcZYBMupwMXhdU0o= +github.com/go-redsync/redsync/v4 v4.7.1 h1:j5rmHCdN5qCEWp5oA2XEbGwtD4LZblqkhbcjCUsfNhs= +github.com/go-redsync/redsync/v4 v4.7.1/go.mod h1:IxV3sygNwjOERTXrj3XvNMSb1tgNgic8GvM8alwnWcM= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= @@ -568,6 +576,7 @@ github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP github.com/go-swagger/go-swagger v0.30.3 h1:HuzvdMRed/9Q8vmzVcfNBQByZVtT79DNZxZ18OprdoI= github.com/go-swagger/go-swagger v0.30.3/go.mod h1:neDPes8r8PCz2JPvHRDj8BTULLh4VJUt7n6MpQqxhHM= github.com/go-swagger/scan-repo-boundary v0.0.0-20180623220736-973b3573c013 h1:l9rI6sNaZgNC0LnF3MiE+qTmyBA/tZAg1rtyrGbUMK0= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-testfixtures/testfixtures/v3 v3.8.1 h1:uonwvepqRvSgddcrReZQhojTlWlmOlHkYAb9ZaOMWgU= github.com/go-testfixtures/testfixtures/v3 v3.8.1/go.mod h1:Kdu7YeMC0KRXVHdaQ91Vmx3pcjoTF63h4f1qTJDdXLA= github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0= @@ -671,6 +680,8 @@ github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEW github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v1.8.2 h1:H5XSIre1MB5NbPYFp+i1NBbb5qN1W8Y8YAQoAYbkm8k= +github.com/gomodule/redigo v1.8.2/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= @@ -724,6 +735,7 @@ github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= @@ -803,6 +815,7 @@ github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBt github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= @@ -812,6 +825,8 @@ github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXc github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI= +github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-retryablehttp v0.6.4/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= github.com/hashicorp/go-retryablehttp v0.7.1 h1:sUiuQAnLlbvmExtFQs72iFW/HXeUn8Z1aJLQ4LJJbTQ= github.com/hashicorp/go-retryablehttp v0.7.1/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= @@ -1155,6 +1170,7 @@ github.com/nwaples/rardecode v1.1.3 h1:cWCaZwfM5H7nAD6PyEdcVnczzV8i/JtotnyW/dD9l github.com/nwaples/rardecode v1.1.3/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= @@ -1170,16 +1186,26 @@ github.com/olivere/elastic/v7 v7.0.32/go.mod h1:c7PVmLe3Fxq77PIfY/bZmxY/TAamBhCz github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= -github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= +github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= +github.com/onsi/gomega v1.20.0 h1:8W0cWlwFkflGPLltQvLRB7ZVD5HuP6ng320w2IS245Q= +github.com/onsi/gomega v1.20.0/go.mod h1:DtrZpjmvpn2mPm4YWQa0/ALMDj9v4YxLgojwPeREyVo= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= @@ -1405,6 +1431,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 h1:QVqDTf3h2WHt08YuiTGPZLls0Wq99X9bWd0Q5ZSBesM= +github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203/go.mod h1:oqN97ltKNihBbwlX8dLpwxCl3+HnXKV/R0e+sRLd9C8= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/subosito/gotenv v1.3.0 h1:mjC+YW8QpAdXibNi+vNWgzmgBH4+5l5dCXv8cNysBLI= github.com/subosito/gotenv v1.3.0/go.mod h1:YzJjq/33h7nrwdY+iHMhEOEEbW0ovIz0tB6t6PwAXzs= @@ -1487,6 +1515,7 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.15/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.5.2 h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU= github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= @@ -1655,6 +1684,7 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1713,6 +1743,7 @@ golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLd golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -1720,6 +1751,7 @@ golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= @@ -1836,6 +1868,7 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1865,6 +1898,7 @@ golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210902050250-f475640dd07b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1873,8 +1907,10 @@ golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1981,6 +2017,7 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -1991,6 +2028,7 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/modules/sync/exclusive_pool.go b/modules/sync/exclusive_pool.go deleted file mode 100644 index fbfc1f22924c6..0000000000000 --- a/modules/sync/exclusive_pool.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2016 The Gogs Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package sync - -import ( - "sync" -) - -// ExclusivePool is a pool of non-identical instances -// that only one instance with same identity is in the pool at a time. -// In other words, only instances with different identities can be in -// the pool the same time. If another instance with same identity tries -// to get into the pool, it hangs until previous instance left the pool. -// -// This pool is particularly useful for performing tasks on same resource -// on the file system in different goroutines. -type ExclusivePool struct { - lock sync.Mutex - - // pool maintains locks for each instance in the pool. - pool map[string]*sync.Mutex - - // count maintains the number of times an instance with same identity checks in - // to the pool, and should be reduced to 0 (removed from map) by checking out - // with same number of times. - // The purpose of count is to delete lock when count down to 0 and recycle memory - // from map object. - count map[string]int -} - -// NewExclusivePool initializes and returns a new ExclusivePool object. -func NewExclusivePool() *ExclusivePool { - return &ExclusivePool{ - pool: make(map[string]*sync.Mutex), - count: make(map[string]int), - } -} - -// CheckIn checks in an instance to the pool and hangs while instance -// with same identity is using the lock. -func (p *ExclusivePool) CheckIn(identity string) { - p.lock.Lock() - - lock, has := p.pool[identity] - if !has { - lock = &sync.Mutex{} - p.pool[identity] = lock - } - p.count[identity]++ - - p.lock.Unlock() - lock.Lock() -} - -// CheckOut checks out an instance from the pool and releases the lock -// to let other instances with same identity to grab the lock. -func (p *ExclusivePool) CheckOut(identity string) { - p.lock.Lock() - defer p.lock.Unlock() - - p.pool[identity].Unlock() - if p.count[identity] == 1 { - delete(p.pool, identity) - delete(p.count, identity) - } else { - p.count[identity]-- - } -} diff --git a/modules/sync/lock.go b/modules/sync/lock.go new file mode 100644 index 0000000000000..3d4bf35513779 --- /dev/null +++ b/modules/sync/lock.go @@ -0,0 +1,92 @@ +// Copyright 2022 The Gogs Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package sync + +import ( + "sync" + + "code.gitea.io/gitea/modules/nosql" + redsync "github.com/go-redsync/redsync/v4" + goredis "github.com/go-redsync/redsync/v4/redis/goredis/v8" +) + +type Locker interface { + Lock() error + Unlock() (bool, error) +} + +type LockService interface { + NewLock(name string) Locker +} + +type memoryLock struct { + mutex *sync.Mutex +} + +func (r *memoryLock) Lock() error { + r.mutex.Lock() + return nil +} + +func (r *memoryLock) Unlock() (bool, error) { + r.mutex.Lock() + return true, nil +} + +var _ Locker = &memoryLock{} + +type memoryLockService struct { + lockes sync.Map +} + +var _ LockService = &memoryLockService{} + +func NewMemoryLockService() *memoryLockService { + return &memoryLockService{} +} + +func (l *memoryLockService) NewLock(name string) Locker { + lock, _ := l.lockes.LoadOrStore(name, &sync.Mutex{}) + return &memoryLock{mutex: lock.(*sync.Mutex)} +} + +type redisLockService struct { + rs *redsync.Redsync +} + +var _ LockService = &redisLockService{} + +func NewRedisLockService(connection string) *redisLockService { + client := nosql.GetManager().GetRedisClient(connection) + + pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...) + + // Create an instance of redisync to be used to obtain a mutual exclusion + // lock. + rs := redsync.New(pool) + + return &redisLockService{ + rs: rs, + } +} + +type redisLock struct { + mutex *redsync.Mutex +} + +func (r *redisLockService) NewLock(name string) Locker { + return &redisLock{mutex: r.rs.NewMutex(name)} +} + +func (r *redisLock) Lock() error { + return r.mutex.Lock() +} + +func (r *redisLock) Unlock() (bool, error) { + return r.mutex.Unlock() +} + +func GetLockService() LockService { + return NewMemoryLockService() +} diff --git a/modules/sync/lock_test.go b/modules/sync/lock_test.go new file mode 100644 index 0000000000000..f37081aff472a --- /dev/null +++ b/modules/sync/lock_test.go @@ -0,0 +1,11 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package sync + +import ( + "testing" +) + +func Test_Lock(t *testing.T) { +} diff --git a/modules/sync/status_pool.go b/modules/sync/status_pool.go deleted file mode 100644 index 6f075d54b79db..0000000000000 --- a/modules/sync/status_pool.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2016 The Gogs Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package sync - -import ( - "sync" - - "code.gitea.io/gitea/modules/container" -) - -// StatusTable is a table maintains true/false values. -// -// This table is particularly useful for un/marking and checking values -// in different goroutines. -type StatusTable struct { - lock sync.RWMutex - pool container.Set[string] -} - -// NewStatusTable initializes and returns a new StatusTable object. -func NewStatusTable() *StatusTable { - return &StatusTable{ - pool: make(container.Set[string]), - } -} - -// StartIfNotRunning sets value of given name to true if not already in pool. -// Returns whether set value was set to true -func (p *StatusTable) StartIfNotRunning(name string) bool { - p.lock.Lock() - added := p.pool.Add(name) - p.lock.Unlock() - return added -} - -// Start sets value of given name to true in the pool. -func (p *StatusTable) Start(name string) { - p.lock.Lock() - p.pool.Add(name) - p.lock.Unlock() -} - -// Stop sets value of given name to false in the pool. -func (p *StatusTable) Stop(name string) { - p.lock.Lock() - p.pool.Remove(name) - p.lock.Unlock() -} - -// IsRunning checks if value of given name is set to true in the pool. -func (p *StatusTable) IsRunning(name string) bool { - p.lock.RLock() - exists := p.pool.Contains(name) - p.lock.RUnlock() - return exists -} diff --git a/modules/sync/status_pool_test.go b/modules/sync/status_pool_test.go deleted file mode 100644 index e2e48862f581f..0000000000000 --- a/modules/sync/status_pool_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package sync - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_StatusTable(t *testing.T) { - table := NewStatusTable() - - assert.False(t, table.IsRunning("xyz")) - - table.Start("xyz") - assert.True(t, table.IsRunning("xyz")) - - assert.False(t, table.StartIfNotRunning("xyz")) - assert.True(t, table.IsRunning("xyz")) - - table.Stop("xyz") - assert.False(t, table.IsRunning("xyz")) - - assert.True(t, table.StartIfNotRunning("xyz")) - assert.True(t, table.IsRunning("xyz")) - - table.Stop("xyz") - assert.False(t, table.IsRunning("xyz")) -} diff --git a/services/cron/cron.go b/services/cron/cron.go index bda8f12f122e5..54053cbf303c1 100644 --- a/services/cron/cron.go +++ b/services/cron/cron.go @@ -11,7 +11,6 @@ import ( "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/process" - "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/translation" "github.com/gogs/cron" @@ -19,9 +18,6 @@ import ( var c = cron.New() -// Prevent duplicate running tasks. -var taskStatusTable = sync.NewStatusTable() - // NewContext begins cron tasks // Each cron task is run within the shutdown context as a running server // AtShutdown the cron server is stopped diff --git a/services/cron/tasks.go b/services/cron/tasks.go index 1c5493c8983d7..612c4939a2e95 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/setting" + sync_module "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/translation" ) @@ -69,9 +70,11 @@ func (t *Task) Run() { // RunWithUser will run the task incrementing the cron counter at the time with User func (t *Task) RunWithUser(doer *user_model.User, config Config) { - if !taskStatusTable.StartIfNotRunning(t.Name) { + lock := sync_module.GetLockService().NewLock(t.Name) + if lock.Lock() != nil { return } + t.lock.Lock() if config == nil { config = t.config @@ -79,7 +82,7 @@ func (t *Task) RunWithUser(doer *user_model.User, config Config) { t.ExecTimes++ t.lock.Unlock() defer func() { - taskStatusTable.Stop(t.Name) + lock.Unlock() if err := recover(); err != nil { // Recover a panic within the combinedErr := fmt.Errorf("%s\n%s", err, log.Stack(2)) diff --git a/services/pull/check.go b/services/pull/check.go index ed4b18107caf7..9844b8a1e1859 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -25,6 +25,7 @@ import ( "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/queue" + "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" asymkey_service "code.gitea.io/gitea/services/asymkey" @@ -318,8 +319,10 @@ func handle(data ...queue.Data) []queue.Data { } func testPR(id int64) { - pullWorkingPool.CheckIn(fmt.Sprint(id)) - defer pullWorkingPool.CheckOut(fmt.Sprint(id)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", id)) + lock.Lock() + defer lock.Unlock() + ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("Test PR[%d] from patch checking queue", id)) defer finished() diff --git a/services/pull/merge.go b/services/pull/merge.go index 1c42c1c17b8b7..4e32c0a08e78a 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -33,6 +33,7 @@ import ( "code.gitea.io/gitea/modules/references" repo_module "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/timeutil" asymkey_service "code.gitea.io/gitea/services/asymkey" issue_service "code.gitea.io/gitea/services/issue" @@ -141,8 +142,9 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("LoadBaseRepo: %w", err) } - pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock.Lock() + defer lock.Unlock() // Removing an auto merge pull and ignore if not exist if err := pull_model.DeleteScheduledAutoMerge(ctx, pr.ID); err != nil && !db.IsErrNotExist(err) { @@ -824,8 +826,9 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock.Lock() + defer lock.Unlock() if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) diff --git a/services/pull/pull.go b/services/pull/pull.go index afb0fa244244b..a20742e328d26 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -32,9 +32,6 @@ import ( issue_service "code.gitea.io/gitea/services/issue" ) -// TODO: use clustered lock (unique queue? or *abuse* cache) -var pullWorkingPool = sync.NewExclusivePool() - // NewPullRequest creates new pull request with labels for repository. func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issues_model.Issue, labelIDs []int64, uuids []string, pr *issues_model.PullRequest, assigneeIDs []int64) error { if err := TestPatch(pr); err != nil { @@ -131,8 +128,9 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issu // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock.Lock() + defer lock.Unlock() // Current target branch is already the same if pr.BaseBranch == targetBranch { diff --git a/services/pull/update.go b/services/pull/update.go index e09dbf624457a..4c4761a519847 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" + "code.gitea.io/gitea/modules/sync" ) // Update updates pull request with base branch. @@ -25,8 +26,9 @@ func Update(ctx context.Context, pull *issues_model.PullRequest, doer *user_mode style repo_model.MergeStyle ) - pullWorkingPool.CheckIn(fmt.Sprint(pull.ID)) - defer pullWorkingPool.CheckOut(fmt.Sprint(pull.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pull.ID)) + lock.Lock() + defer lock.Unlock() if rebase { pr = pull diff --git a/services/repository/transfer.go b/services/repository/transfer.go index f4afb7e2dec28..63bdc566b2c3b 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -20,10 +20,6 @@ import ( "code.gitea.io/gitea/modules/sync" ) -// repoWorkingPool represents a working pool to order the parallel changes to the same repository -// TODO: use clustered lock (unique queue? or *abuse* cache) -var repoWorkingPool = sync.NewExclusivePool() - // TransferOwnership transfers all corresponding setting from old user to new one. func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*organization.Team) error { if err := repo.GetOwner(ctx); err != nil { @@ -37,12 +33,13 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - repoWorkingPool.CheckIn(fmt.Sprint(repo.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("repo_working_%d", repo.ID)) + lock.Lock() if err := models.TransferOwnership(doer, newOwner.Name, repo); err != nil { - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock.Unlock() return err } - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock.Unlock() newRepo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { @@ -70,12 +67,13 @@ func ChangeRepositoryName(doer *user_model.User, repo *repo_model.Repository, ne // repo so that we can atomically rename the repo path and updates the // local copy's origin accordingly. - repoWorkingPool.CheckIn(fmt.Sprint(repo.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("repo_working_%d", repo.ID)) + lock.Lock() if err := repo_model.ChangeRepositoryName(doer, repo, newRepoName); err != nil { - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock.Unlock() return err } - repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock.Unlock() repo.Name = newRepoName notification.NotifyRenameRepository(db.DefaultContext, doer, repo, oldRepoName) diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index e483416fda76f..5345ed5ffd00c 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -23,11 +23,7 @@ import ( asymkey_service "code.gitea.io/gitea/services/asymkey" ) -var ( - reservedWikiNames = []string{"_pages", "_new", "_edit", "raw"} - // TODO: use clustered lock (unique queue? or *abuse* cache) - wikiWorkingPool = sync.NewExclusivePool() -) +var reservedWikiNames = []string{"_pages", "_new", "_edit", "raw"} const ( DefaultRemote = "origin" @@ -127,8 +123,9 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model if err = nameAllowed(newWikiName); err != nil { return err } - wikiWorkingPool.CheckIn(fmt.Sprint(repo.ID)) - defer wikiWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("wiki_working_%d", repo.ID)) + lock.Lock() + defer lock.Unlock() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) @@ -283,8 +280,9 @@ func EditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.R // DeleteWikiPage deletes a wiki page identified by its path. func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, wikiName string) (err error) { - wikiWorkingPool.CheckIn(fmt.Sprint(repo.ID)) - defer wikiWorkingPool.CheckOut(fmt.Sprint(repo.ID)) + lock := sync.GetLockService().NewLock(fmt.Sprintf("wiki_working_%d", repo.ID)) + lock.Lock() + defer lock.Unlock() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) From c87bc64d1315e9fadeea2211a93650a1b54c6edb Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 20 Dec 2022 11:42:59 +0800 Subject: [PATCH 02/17] add setting --- custom/conf/app.example.ini | 5 +++++ modules/setting/setting.go | 2 ++ modules/setting/sync.go | 23 +++++++++++++++++++++++ modules/sync/lock.go | 6 +++++- 4 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 modules/setting/sync.go diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index 754eab452ff9d..7ba00dffba9d2 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -2484,3 +2484,8 @@ ROUTER = console ;PROXY_URL = ;; Comma separated list of host names requiring proxy. Glob patterns (*) are accepted; use ** to match all hosts. ;PROXY_HOSTS = + +;[sync] +;; lock service type, could be memory or redis +; LOCK_SERVICE_TYPE = memory +; LOCK_SERVICE_CONN_STR = ; redis "addrs=127.0.0.1:6379 db=0" diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 47e0ae2cda1f5..320fa45156111 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -1135,6 +1135,8 @@ func loadFromConf(allowEmpty bool, extraConfig string) { for _, emoji := range UI.CustomEmojis { UI.CustomEmojisMap[emoji] = ":" + emoji + ":" } + + parseSyncSetting() } func parseAuthorizedPrincipalsAllow(values []string) ([]string, bool) { diff --git a/modules/setting/sync.go b/modules/setting/sync.go new file mode 100644 index 0000000000000..e11b9a351acfc --- /dev/null +++ b/modules/setting/sync.go @@ -0,0 +1,23 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package setting + +import "code.gitea.io/gitea/modules/log" + +// Sync represents configuration of sync +var Sync = struct { + LockServiceType string + LockServiceConnStr string +}{ + LockServiceType: "memory", +} + +func parseSyncSetting() { + sec := Cfg.Section("sync") + Sync.LockServiceType = sec.Key("LOCK_SERVICE_TYPE").MustString("memory") + if Sync.LockServiceType != "memory" && Sync.LockServiceType != "redis" { + log.Fatal("Unknown sync lock service type: %s", Sync.LockServiceType) + } + Sync.LockServiceConnStr = sec.Key("LOCK_SERVICE_CONN_STR").MustString("") +} diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 3d4bf35513779..141864d57f425 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Gogs Authors. All rights reserved. +// Copyright 2022 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package sync @@ -7,6 +7,7 @@ import ( "sync" "code.gitea.io/gitea/modules/nosql" + "code.gitea.io/gitea/modules/setting" redsync "github.com/go-redsync/redsync/v4" goredis "github.com/go-redsync/redsync/v4/redis/goredis/v8" ) @@ -88,5 +89,8 @@ func (r *redisLock) Unlock() (bool, error) { } func GetLockService() LockService { + if setting.Sync.LockServiceType == "redis" { + return NewRedisLockService(setting.Sync.LockServiceConnStr) + } return NewMemoryLockService() } From 845752d3686e462773990c09a49c7012967b7c0f Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 20 Dec 2022 11:44:46 +0800 Subject: [PATCH 03/17] Fix bug --- modules/sync/lock.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 141864d57f425..59cbec3c06431 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -31,7 +31,7 @@ func (r *memoryLock) Lock() error { } func (r *memoryLock) Unlock() (bool, error) { - r.mutex.Lock() + r.mutex.Unlock() return true, nil } From 30d202357f632c8b78b112458f85ffec4d5c3291 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 20 Dec 2022 11:46:04 +0800 Subject: [PATCH 04/17] comment year --- modules/setting/sync.go | 2 +- modules/sync/lock_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/setting/sync.go b/modules/setting/sync.go index e11b9a351acfc..60c1e5c41c12d 100644 --- a/modules/setting/sync.go +++ b/modules/setting/sync.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Gitea Authors. All rights reserved. +// Copyright 2022 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package setting diff --git a/modules/sync/lock_test.go b/modules/sync/lock_test.go index f37081aff472a..25622d3172ccc 100644 --- a/modules/sync/lock_test.go +++ b/modules/sync/lock_test.go @@ -1,4 +1,4 @@ -// Copyright 2017 The Gitea Authors. All rights reserved. +// Copyright 2022 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package sync From afe380ffa449a03129c32e3c8c2c1d108462c86b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 20 Dec 2022 11:49:26 +0800 Subject: [PATCH 05/17] Rename interface method --- modules/sync/lock.go | 6 +++--- services/cron/tasks.go | 2 +- services/pull/check.go | 2 +- services/pull/merge.go | 4 ++-- services/pull/pull.go | 2 +- services/pull/update.go | 2 +- services/repository/transfer.go | 4 ++-- services/wiki/wiki.go | 4 ++-- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 59cbec3c06431..0905bc71af5ca 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -18,7 +18,7 @@ type Locker interface { } type LockService interface { - NewLock(name string) Locker + GetLock(name string) Locker } type memoryLock struct { @@ -47,7 +47,7 @@ func NewMemoryLockService() *memoryLockService { return &memoryLockService{} } -func (l *memoryLockService) NewLock(name string) Locker { +func (l *memoryLockService) GetLock(name string) Locker { lock, _ := l.lockes.LoadOrStore(name, &sync.Mutex{}) return &memoryLock{mutex: lock.(*sync.Mutex)} } @@ -76,7 +76,7 @@ type redisLock struct { mutex *redsync.Mutex } -func (r *redisLockService) NewLock(name string) Locker { +func (r *redisLockService) GetLock(name string) Locker { return &redisLock{mutex: r.rs.NewMutex(name)} } diff --git a/services/cron/tasks.go b/services/cron/tasks.go index 612c4939a2e95..90c2d522801d0 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -70,7 +70,7 @@ func (t *Task) Run() { // RunWithUser will run the task incrementing the cron counter at the time with User func (t *Task) RunWithUser(doer *user_model.User, config Config) { - lock := sync_module.GetLockService().NewLock(t.Name) + lock := sync_module.GetLockService().GetLock(fmt.Sprintf("cron_tasks_%s", t.Name)) if lock.Lock() != nil { return } diff --git a/services/pull/check.go b/services/pull/check.go index 9844b8a1e1859..967aeddf9d21b 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -319,7 +319,7 @@ func handle(data ...queue.Data) []queue.Data { } func testPR(id int64) { - lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", id)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", id)) lock.Lock() defer lock.Unlock() diff --git a/services/pull/merge.go b/services/pull/merge.go index 4e32c0a08e78a..231544788dc47 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -142,7 +142,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("LoadBaseRepo: %w", err) } - lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) lock.Lock() defer lock.Unlock() @@ -826,7 +826,7 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) lock.Lock() defer lock.Unlock() diff --git a/services/pull/pull.go b/services/pull/pull.go index a20742e328d26..b9c47b005f29b 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -128,7 +128,7 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issu // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) lock.Lock() defer lock.Unlock() diff --git a/services/pull/update.go b/services/pull/update.go index 4c4761a519847..69939baa2115f 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -26,7 +26,7 @@ func Update(ctx context.Context, pull *issues_model.PullRequest, doer *user_mode style repo_model.MergeStyle ) - lock := sync.GetLockService().NewLock(fmt.Sprintf("pull_working_%d", pull.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pull.ID)) lock.Lock() defer lock.Unlock() diff --git a/services/repository/transfer.go b/services/repository/transfer.go index 63bdc566b2c3b..aaff64812b253 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -33,7 +33,7 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - lock := sync.GetLockService().NewLock(fmt.Sprintf("repo_working_%d", repo.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("repo_working_%d", repo.ID)) lock.Lock() if err := models.TransferOwnership(doer, newOwner.Name, repo); err != nil { lock.Unlock() @@ -67,7 +67,7 @@ func ChangeRepositoryName(doer *user_model.User, repo *repo_model.Repository, ne // repo so that we can atomically rename the repo path and updates the // local copy's origin accordingly. - lock := sync.GetLockService().NewLock(fmt.Sprintf("repo_working_%d", repo.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("repo_working_%d", repo.ID)) lock.Lock() if err := repo_model.ChangeRepositoryName(doer, repo, newRepoName); err != nil { lock.Unlock() diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index 5345ed5ffd00c..2f5a568f95b07 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -123,7 +123,7 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model if err = nameAllowed(newWikiName); err != nil { return err } - lock := sync.GetLockService().NewLock(fmt.Sprintf("wiki_working_%d", repo.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("wiki_working_%d", repo.ID)) lock.Lock() defer lock.Unlock() @@ -280,7 +280,7 @@ func EditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.R // DeleteWikiPage deletes a wiki page identified by its path. func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, wikiName string) (err error) { - lock := sync.GetLockService().NewLock(fmt.Sprintf("wiki_working_%d", repo.ID)) + lock := sync.GetLockService().GetLock(fmt.Sprintf("wiki_working_%d", repo.ID)) lock.Lock() defer lock.Unlock() From 11b7584ea01010c11869b7b5934ceef9dbd614d7 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 20 Dec 2022 11:51:46 +0800 Subject: [PATCH 06/17] Fix bug --- modules/sync/lock.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 0905bc71af5ca..8ba94abe8a4fa 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -88,9 +88,18 @@ func (r *redisLock) Unlock() (bool, error) { return r.mutex.Unlock() } +var ( + syncOnce sync.Once + lockService LockService +) + func GetLockService() LockService { - if setting.Sync.LockServiceType == "redis" { - return NewRedisLockService(setting.Sync.LockServiceConnStr) - } - return NewMemoryLockService() + syncOnce.Do(func() { + if setting.Sync.LockServiceType == "redis" { + lockService = NewRedisLockService(setting.Sync.LockServiceConnStr) + } else { + lockService = NewMemoryLockService() + } + }) + return lockService } From 3af650eff934cba87599171701f1003b68ccd7b3 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 21 Dec 2022 10:25:39 +0800 Subject: [PATCH 07/17] fix lint --- assets/go-licenses.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/assets/go-licenses.json b/assets/go-licenses.json index c4b62475fd4bc..d67393d7c64dd 100644 --- a/assets/go-licenses.json +++ b/assets/go-licenses.json @@ -369,6 +369,11 @@ "path": "github.com/go-redis/redis/v8/LICENSE", "licenseText": "Copyright (c) 2013 The github.com/go-redis/redis Authors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" }, + { + "name": "github.com/go-redsync/redsync/v4", + "path": "github.com/go-redsync/redsync/v4/LICENSE", + "licenseText": "Copyright (c) 2021, Mahmud Ridwan\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the Redsync nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + }, { "name": "github.com/go-sql-driver/mysql", "path": "github.com/go-sql-driver/mysql/LICENSE", @@ -484,11 +489,21 @@ "path": "github.com/gorilla/sessions/LICENSE", "licenseText": "Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n\t * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n\t * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n\t * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" }, + { + "name": "github.com/hashicorp/errwrap", + "path": "github.com/hashicorp/errwrap/LICENSE", + "licenseText": "Mozilla Public License, version 2.0\n\n1. Definitions\n\n1.1. “Contributor”\n\n means each individual or legal entity that creates, contributes to the\n creation of, or owns Covered Software.\n\n1.2. “Contributor Version”\n\n means the combination of the Contributions of others (if any) used by a\n Contributor and that particular Contributor’s Contribution.\n\n1.3. “Contribution”\n\n means Covered Software of a particular Contributor.\n\n1.4. “Covered Software”\n\n means Source Code Form to which the initial Contributor has attached the\n notice in Exhibit A, the Executable Form of such Source Code Form, and\n Modifications of such Source Code Form, in each case including portions\n thereof.\n\n1.5. “Incompatible With Secondary Licenses”\n means\n\n a. that the initial Contributor has attached the notice described in\n Exhibit B to the Covered Software; or\n\n b. that the Covered Software was made available under the terms of version\n 1.1 or earlier of the License, but not also under the terms of a\n Secondary License.\n\n1.6. “Executable Form”\n\n means any form of the work other than Source Code Form.\n\n1.7. “Larger Work”\n\n means a work that combines Covered Software with other material, in a separate\n file or files, that is not Covered Software.\n\n1.8. “License”\n\n means this document.\n\n1.9. “Licensable”\n\n means having the right to grant, to the maximum extent possible, whether at the\n time of the initial grant or subsequently, any and all of the rights conveyed by\n this License.\n\n1.10. “Modifications”\n\n means any of the following:\n\n a. any file in Source Code Form that results from an addition to, deletion\n from, or modification of the contents of Covered Software; or\n\n b. any new file in Source Code Form that contains any Covered Software.\n\n1.11. “Patent Claims” of a Contributor\n\n means any patent claim(s), including without limitation, method, process,\n and apparatus claims, in any patent Licensable by such Contributor that\n would be infringed, but for the grant of the License, by the making,\n using, selling, offering for sale, having made, import, or transfer of\n either its Contributions or its Contributor Version.\n\n1.12. “Secondary License”\n\n means either the GNU General Public License, Version 2.0, the GNU Lesser\n General Public License, Version 2.1, the GNU Affero General Public\n License, Version 3.0, or any later versions of those licenses.\n\n1.13. “Source Code Form”\n\n means the form of the work preferred for making modifications.\n\n1.14. “You” (or “Your”)\n\n means an individual or a legal entity exercising rights under this\n License. For legal entities, “You” includes any entity that controls, is\n controlled by, or is under common control with You. For purposes of this\n definition, “control” means (a) the power, direct or indirect, to cause\n the direction or management of such entity, whether by contract or\n otherwise, or (b) ownership of more than fifty percent (50%) of the\n outstanding shares or beneficial ownership of such entity.\n\n\n2. License Grants and Conditions\n\n2.1. Grants\n\n Each Contributor hereby grants You a world-wide, royalty-free,\n non-exclusive license:\n\n a. under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or as\n part of a Larger Work; and\n\n b. under Patent Claims of such Contributor to make, use, sell, offer for\n sale, have made, import, and otherwise transfer either its Contributions\n or its Contributor Version.\n\n2.2. Effective Date\n\n The licenses granted in Section 2.1 with respect to any Contribution become\n effective for each Contribution on the date the Contributor first distributes\n such Contribution.\n\n2.3. Limitations on Grant Scope\n\n The licenses granted in this Section 2 are the only rights granted under this\n License. No additional rights or licenses will be implied from the distribution\n or licensing of Covered Software under this License. Notwithstanding Section\n 2.1(b) above, no patent license is granted by a Contributor:\n\n a. for any code that a Contributor has removed from Covered Software; or\n\n b. for infringements caused by: (i) Your and any other third party’s\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n c. under Patent Claims infringed by Covered Software in the absence of its\n Contributions.\n\n This License does not grant any rights in the trademarks, service marks, or\n logos of any Contributor (except as may be necessary to comply with the\n notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\n No Contributor makes additional grants as a result of Your choice to\n distribute the Covered Software under a subsequent version of this License\n (see Section 10.2) or under the terms of a Secondary License (if permitted\n under the terms of Section 3.3).\n\n2.5. Representation\n\n Each Contributor represents that the Contributor believes its Contributions\n are its original creation(s) or it has sufficient rights to grant the\n rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\n This License is not intended to limit any rights You have under applicable\n copyright doctrines of fair use, fair dealing, or other equivalents.\n\n2.7. Conditions\n\n Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in\n Section 2.1.\n\n\n3. Responsibilities\n\n3.1. Distribution of Source Form\n\n All distribution of Covered Software in Source Code Form, including any\n Modifications that You create or to which You contribute, must be under the\n terms of this License. You must inform recipients that the Source Code Form\n of the Covered Software is governed by the terms of this License, and how\n they can obtain a copy of this License. You may not attempt to alter or\n restrict the recipients’ rights in the Source Code Form.\n\n3.2. Distribution of Executable Form\n\n If You distribute Covered Software in Executable Form then:\n\n a. such Covered Software must also be made available in Source Code Form,\n as described in Section 3.1, and You must inform recipients of the\n Executable Form how they can obtain a copy of such Source Code Form by\n reasonable means in a timely manner, at a charge no more than the cost\n of distribution to the recipient; and\n\n b. You may distribute such Executable Form under the terms of this License,\n or sublicense it under different terms, provided that the license for\n the Executable Form does not attempt to limit or alter the recipients’\n rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\n You may create and distribute a Larger Work under terms of Your choice,\n provided that You also comply with the requirements of this License for the\n Covered Software. If the Larger Work is a combination of Covered Software\n with a work governed by one or more Secondary Licenses, and the Covered\n Software is not Incompatible With Secondary Licenses, this License permits\n You to additionally distribute such Covered Software under the terms of\n such Secondary License(s), so that the recipient of the Larger Work may, at\n their option, further distribute the Covered Software under the terms of\n either this License or such Secondary License(s).\n\n3.4. Notices\n\n You may not remove or alter the substance of any license notices (including\n copyright notices, patent notices, disclaimers of warranty, or limitations\n of liability) contained within the Source Code Form of the Covered\n Software, except that You may alter any license notices to the extent\n required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\n You may choose to offer, and to charge a fee for, warranty, support,\n indemnity or liability obligations to one or more recipients of Covered\n Software. However, You may do so only on Your own behalf, and not on behalf\n of any Contributor. You must make it absolutely clear that any such\n warranty, support, indemnity, or liability obligation is offered by You\n alone, and You hereby agree to indemnify every Contributor for any\n liability incurred by such Contributor as a result of warranty, support,\n indemnity or liability terms You offer. You may include additional\n disclaimers of warranty and limitations of liability specific to any\n jurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n\n If it is impossible for You to comply with any of the terms of this License\n with respect to some or all of the Covered Software due to statute, judicial\n order, or regulation then You must: (a) comply with the terms of this License\n to the maximum extent possible; and (b) describe the limitations and the code\n they affect. Such description must be placed in a text file included with all\n distributions of the Covered Software under this License. Except to the\n extent prohibited by statute or regulation, such description must be\n sufficiently detailed for a recipient of ordinary skill to be able to\n understand it.\n\n5. Termination\n\n5.1. The rights granted under this License will terminate automatically if You\n fail to comply with any of its terms. However, if You become compliant,\n then the rights granted under this License from a particular Contributor\n are reinstated (a) provisionally, unless and until such Contributor\n explicitly and finally terminates Your grants, and (b) on an ongoing basis,\n if such Contributor fails to notify You of the non-compliance by some\n reasonable means prior to 60 days after You have come back into compliance.\n Moreover, Your grants from a particular Contributor are reinstated on an\n ongoing basis if such Contributor notifies You of the non-compliance by\n some reasonable means, this is the first time You have received notice of\n non-compliance with this License from such Contributor, and You become\n compliant prior to 30 days after Your receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\n infringement claim (excluding declaratory judgment actions, counter-claims,\n and cross-claims) alleging that a Contributor Version directly or\n indirectly infringes any patent, then the rights granted to You by any and\n all Contributors for the Covered Software under Section 2.1 of this License\n shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user\n license agreements (excluding distributors and resellers) which have been\n validly granted by You or Your distributors under this License prior to\n termination shall survive termination.\n\n6. Disclaimer of Warranty\n\n Covered Software is provided under this License on an “as is” basis, without\n warranty of any kind, either expressed, implied, or statutory, including,\n without limitation, warranties that the Covered Software is free of defects,\n merchantable, fit for a particular purpose or non-infringing. The entire\n risk as to the quality and performance of the Covered Software is with You.\n Should any Covered Software prove defective in any respect, You (not any\n Contributor) assume the cost of any necessary servicing, repair, or\n correction. This disclaimer of warranty constitutes an essential part of this\n License. No use of any Covered Software is authorized under this License\n except under this disclaimer.\n\n7. Limitation of Liability\n\n Under no circumstances and under no legal theory, whether tort (including\n negligence), contract, or otherwise, shall any Contributor, or anyone who\n distributes Covered Software as permitted above, be liable to You for any\n direct, indirect, special, incidental, or consequential damages of any\n character including, without limitation, damages for lost profits, loss of\n goodwill, work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses, even if such party shall have been\n informed of the possibility of such damages. This limitation of liability\n shall not apply to liability for death or personal injury resulting from such\n party’s negligence to the extent applicable law prohibits such limitation.\n Some jurisdictions do not allow the exclusion or limitation of incidental or\n consequential damages, so this exclusion and limitation may not apply to You.\n\n8. Litigation\n\n Any litigation relating to this License may be brought only in the courts of\n a jurisdiction where the defendant maintains its principal place of business\n and such litigation shall be governed by laws of that jurisdiction, without\n reference to its conflict-of-law provisions. Nothing in this Section shall\n prevent a party’s ability to bring cross-claims or counter-claims.\n\n9. Miscellaneous\n\n This License represents the complete agreement concerning the subject matter\n hereof. If any provision of this License is held to be unenforceable, such\n provision shall be reformed only to the extent necessary to make it\n enforceable. Any law or regulation which provides that the language of a\n contract shall be construed against the drafter shall not be used to construe\n this License against a Contributor.\n\n\n10. Versions of the License\n\n10.1. New Versions\n\n Mozilla Foundation is the license steward. Except as provided in Section\n 10.3, no one other than the license steward has the right to modify or\n publish new versions of this License. Each version will be given a\n distinguishing version number.\n\n10.2. Effect of New Versions\n\n You may distribute the Covered Software under the terms of the version of\n the License under which You originally received the Covered Software, or\n under the terms of any subsequent version published by the license\n steward.\n\n10.3. Modified Versions\n\n If you create software not governed by this License, and you want to\n create a new license for such software, you may create and use a modified\n version of this License if you rename the license and remove any\n references to the name of the license steward (except to note that such\n modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses\n If You choose to distribute Source Code Form that is Incompatible With\n Secondary Licenses under the terms of this version of the License, the\n notice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n\n This Source Code Form is subject to the\n terms of the Mozilla Public License, v.\n 2.0. If a copy of the MPL was not\n distributed with this file, You can\n obtain one at\n http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular file, then\nYou may include the notice in a location (such as a LICENSE file in a relevant\ndirectory) where a recipient would be likely to look for such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - “Incompatible With Secondary Licenses” Notice\n\n This Source Code Form is “Incompatible\n With Secondary Licenses”, as defined by\n the Mozilla Public License, v. 2.0.\n\n" + }, { "name": "github.com/hashicorp/go-cleanhttp", "path": "github.com/hashicorp/go-cleanhttp/LICENSE", "licenseText": "Mozilla Public License, version 2.0\n\n1. Definitions\n\n1.1. \"Contributor\"\n\n means each individual or legal entity that creates, contributes to the\n creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n\n means the combination of the Contributions of others (if any) used by a\n Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n\n means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n\n means Source Code Form to which the initial Contributor has attached the\n notice in Exhibit A, the Executable Form of such Source Code Form, and\n Modifications of such Source Code Form, in each case including portions\n thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n means\n\n a. that the initial Contributor has attached the notice described in\n Exhibit B to the Covered Software; or\n\n b. that the Covered Software was made available under the terms of\n version 1.1 or earlier of the License, but not also under the terms of\n a Secondary License.\n\n1.6. \"Executable Form\"\n\n means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n\n means a work that combines Covered Software with other material, in a\n separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n\n means this document.\n\n1.9. \"Licensable\"\n\n means having the right to grant, to the maximum extent possible, whether\n at the time of the initial grant or subsequently, any and all of the\n rights conveyed by this License.\n\n1.10. \"Modifications\"\n\n means any of the following:\n\n a. any file in Source Code Form that results from an addition to,\n deletion from, or modification of the contents of Covered Software; or\n\n b. any new file in Source Code Form that contains any Covered Software.\n\n1.11. \"Patent Claims\" of a Contributor\n\n means any patent claim(s), including without limitation, method,\n process, and apparatus claims, in any patent Licensable by such\n Contributor that would be infringed, but for the grant of the License,\n by the making, using, selling, offering for sale, having made, import,\n or transfer of either its Contributions or its Contributor Version.\n\n1.12. \"Secondary License\"\n\n means either the GNU General Public License, Version 2.0, the GNU Lesser\n General Public License, Version 2.1, the GNU Affero General Public\n License, Version 3.0, or any later versions of those licenses.\n\n1.13. \"Source Code Form\"\n\n means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n\n means an individual or a legal entity exercising rights under this\n License. For legal entities, \"You\" includes any entity that controls, is\n controlled by, or is under common control with You. For purposes of this\n definition, \"control\" means (a) the power, direct or indirect, to cause\n the direction or management of such entity, whether by contract or\n otherwise, or (b) ownership of more than fifty percent (50%) of the\n outstanding shares or beneficial ownership of such entity.\n\n\n2. License Grants and Conditions\n\n2.1. Grants\n\n Each Contributor hereby grants You a world-wide, royalty-free,\n non-exclusive license:\n\n a. under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or\n as part of a Larger Work; and\n\n b. under Patent Claims of such Contributor to make, use, sell, offer for\n sale, have made, import, and otherwise transfer either its\n Contributions or its Contributor Version.\n\n2.2. Effective Date\n\n The licenses granted in Section 2.1 with respect to any Contribution\n become effective for each Contribution on the date the Contributor first\n distributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\n The licenses granted in this Section 2 are the only rights granted under\n this License. No additional rights or licenses will be implied from the\n distribution or licensing of Covered Software under this License.\n Notwithstanding Section 2.1(b) above, no patent license is granted by a\n Contributor:\n\n a. for any code that a Contributor has removed from Covered Software; or\n\n b. for infringements caused by: (i) Your and any other third party's\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n c. under Patent Claims infringed by Covered Software in the absence of\n its Contributions.\n\n This License does not grant any rights in the trademarks, service marks,\n or logos of any Contributor (except as may be necessary to comply with\n the notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\n No Contributor makes additional grants as a result of Your choice to\n distribute the Covered Software under a subsequent version of this\n License (see Section 10.2) or under the terms of a Secondary License (if\n permitted under the terms of Section 3.3).\n\n2.5. Representation\n\n Each Contributor represents that the Contributor believes its\n Contributions are its original creation(s) or it has sufficient rights to\n grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\n This License is not intended to limit any rights You have under\n applicable copyright doctrines of fair use, fair dealing, or other\n equivalents.\n\n2.7. Conditions\n\n Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in\n Section 2.1.\n\n\n3. Responsibilities\n\n3.1. Distribution of Source Form\n\n All distribution of Covered Software in Source Code Form, including any\n Modifications that You create or to which You contribute, must be under\n the terms of this License. You must inform recipients that the Source\n Code Form of the Covered Software is governed by the terms of this\n License, and how they can obtain a copy of this License. You may not\n attempt to alter or restrict the recipients' rights in the Source Code\n Form.\n\n3.2. Distribution of Executable Form\n\n If You distribute Covered Software in Executable Form then:\n\n a. such Covered Software must also be made available in Source Code Form,\n as described in Section 3.1, and You must inform recipients of the\n Executable Form how they can obtain a copy of such Source Code Form by\n reasonable means in a timely manner, at a charge no more than the cost\n of distribution to the recipient; and\n\n b. You may distribute such Executable Form under the terms of this\n License, or sublicense it under different terms, provided that the\n license for the Executable Form does not attempt to limit or alter the\n recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\n You may create and distribute a Larger Work under terms of Your choice,\n provided that You also comply with the requirements of this License for\n the Covered Software. If the Larger Work is a combination of Covered\n Software with a work governed by one or more Secondary Licenses, and the\n Covered Software is not Incompatible With Secondary Licenses, this\n License permits You to additionally distribute such Covered Software\n under the terms of such Secondary License(s), so that the recipient of\n the Larger Work may, at their option, further distribute the Covered\n Software under the terms of either this License or such Secondary\n License(s).\n\n3.4. Notices\n\n You may not remove or alter the substance of any license notices\n (including copyright notices, patent notices, disclaimers of warranty, or\n limitations of liability) contained within the Source Code Form of the\n Covered Software, except that You may alter any license notices to the\n extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\n You may choose to offer, and to charge a fee for, warranty, support,\n indemnity or liability obligations to one or more recipients of Covered\n Software. However, You may do so only on Your own behalf, and not on\n behalf of any Contributor. You must make it absolutely clear that any\n such warranty, support, indemnity, or liability obligation is offered by\n You alone, and You hereby agree to indemnify every Contributor for any\n liability incurred by such Contributor as a result of warranty, support,\n indemnity or liability terms You offer. You may include additional\n disclaimers of warranty and limitations of liability specific to any\n jurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n\n If it is impossible for You to comply with any of the terms of this License\n with respect to some or all of the Covered Software due to statute,\n judicial order, or regulation then You must: (a) comply with the terms of\n this License to the maximum extent possible; and (b) describe the\n limitations and the code they affect. Such description must be placed in a\n text file included with all distributions of the Covered Software under\n this License. Except to the extent prohibited by statute or regulation,\n such description must be sufficiently detailed for a recipient of ordinary\n skill to be able to understand it.\n\n5. Termination\n\n5.1. The rights granted under this License will terminate automatically if You\n fail to comply with any of its terms. However, if You become compliant,\n then the rights granted under this License from a particular Contributor\n are reinstated (a) provisionally, unless and until such Contributor\n explicitly and finally terminates Your grants, and (b) on an ongoing\n basis, if such Contributor fails to notify You of the non-compliance by\n some reasonable means prior to 60 days after You have come back into\n compliance. Moreover, Your grants from a particular Contributor are\n reinstated on an ongoing basis if such Contributor notifies You of the\n non-compliance by some reasonable means, this is the first time You have\n received notice of non-compliance with this License from such\n Contributor, and You become compliant prior to 30 days after Your receipt\n of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\n infringement claim (excluding declaratory judgment actions,\n counter-claims, and cross-claims) alleging that a Contributor Version\n directly or indirectly infringes any patent, then the rights granted to\n You by any and all Contributors for the Covered Software under Section\n 2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user\n license agreements (excluding distributors and resellers) which have been\n validly granted by You or Your distributors under this License prior to\n termination shall survive termination.\n\n6. Disclaimer of Warranty\n\n Covered Software is provided under this License on an \"as is\" basis,\n without warranty of any kind, either expressed, implied, or statutory,\n including, without limitation, warranties that the Covered Software is free\n of defects, merchantable, fit for a particular purpose or non-infringing.\n The entire risk as to the quality and performance of the Covered Software\n is with You. Should any Covered Software prove defective in any respect,\n You (not any Contributor) assume the cost of any necessary servicing,\n repair, or correction. This disclaimer of warranty constitutes an essential\n part of this License. No use of any Covered Software is authorized under\n this License except under this disclaimer.\n\n7. Limitation of Liability\n\n Under no circumstances and under no legal theory, whether tort (including\n negligence), contract, or otherwise, shall any Contributor, or anyone who\n distributes Covered Software as permitted above, be liable to You for any\n direct, indirect, special, incidental, or consequential damages of any\n character including, without limitation, damages for lost profits, loss of\n goodwill, work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses, even if such party shall have been\n informed of the possibility of such damages. This limitation of liability\n shall not apply to liability for death or personal injury resulting from\n such party's negligence to the extent applicable law prohibits such\n limitation. Some jurisdictions do not allow the exclusion or limitation of\n incidental or consequential damages, so this exclusion and limitation may\n not apply to You.\n\n8. Litigation\n\n Any litigation relating to this License may be brought only in the courts\n of a jurisdiction where the defendant maintains its principal place of\n business and such litigation shall be governed by laws of that\n jurisdiction, without reference to its conflict-of-law provisions. Nothing\n in this Section shall prevent a party's ability to bring cross-claims or\n counter-claims.\n\n9. Miscellaneous\n\n This License represents the complete agreement concerning the subject\n matter hereof. If any provision of this License is held to be\n unenforceable, such provision shall be reformed only to the extent\n necessary to make it enforceable. Any law or regulation which provides that\n the language of a contract shall be construed against the drafter shall not\n be used to construe this License against a Contributor.\n\n\n10. Versions of the License\n\n10.1. New Versions\n\n Mozilla Foundation is the license steward. Except as provided in Section\n 10.3, no one other than the license steward has the right to modify or\n publish new versions of this License. Each version will be given a\n distinguishing version number.\n\n10.2. Effect of New Versions\n\n You may distribute the Covered Software under the terms of the version\n of the License under which You originally received the Covered Software,\n or under the terms of any subsequent version published by the license\n steward.\n\n10.3. Modified Versions\n\n If you create software not governed by this License, and you want to\n create a new license for such software, you may create and use a\n modified version of this License if you rename the license and remove\n any references to the name of the license steward (except to note that\n such modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\n Licenses If You choose to distribute Source Code Form that is\n Incompatible With Secondary Licenses under the terms of this version of\n the License, the notice described in Exhibit B of this License must be\n attached.\n\nExhibit A - Source Code Form License Notice\n\n This Source Code Form is subject to the\n terms of the Mozilla Public License, v.\n 2.0. If a copy of the MPL was not\n distributed with this file, You can\n obtain one at\n http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular file,\nthen You may include the notice in a location (such as a LICENSE file in a\nrelevant directory) where a recipient would be likely to look for such a\nnotice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n\n This Source Code Form is \"Incompatible\n With Secondary Licenses\", as defined by\n the Mozilla Public License, v. 2.0.\n\n" }, + { + "name": "github.com/hashicorp/go-multierror", + "path": "github.com/hashicorp/go-multierror/LICENSE", + "licenseText": "Mozilla Public License, version 2.0\n\n1. Definitions\n\n1.1. “Contributor”\n\n means each individual or legal entity that creates, contributes to the\n creation of, or owns Covered Software.\n\n1.2. “Contributor Version”\n\n means the combination of the Contributions of others (if any) used by a\n Contributor and that particular Contributor’s Contribution.\n\n1.3. “Contribution”\n\n means Covered Software of a particular Contributor.\n\n1.4. “Covered Software”\n\n means Source Code Form to which the initial Contributor has attached the\n notice in Exhibit A, the Executable Form of such Source Code Form, and\n Modifications of such Source Code Form, in each case including portions\n thereof.\n\n1.5. “Incompatible With Secondary Licenses”\n means\n\n a. that the initial Contributor has attached the notice described in\n Exhibit B to the Covered Software; or\n\n b. that the Covered Software was made available under the terms of version\n 1.1 or earlier of the License, but not also under the terms of a\n Secondary License.\n\n1.6. “Executable Form”\n\n means any form of the work other than Source Code Form.\n\n1.7. “Larger Work”\n\n means a work that combines Covered Software with other material, in a separate\n file or files, that is not Covered Software.\n\n1.8. “License”\n\n means this document.\n\n1.9. “Licensable”\n\n means having the right to grant, to the maximum extent possible, whether at the\n time of the initial grant or subsequently, any and all of the rights conveyed by\n this License.\n\n1.10. “Modifications”\n\n means any of the following:\n\n a. any file in Source Code Form that results from an addition to, deletion\n from, or modification of the contents of Covered Software; or\n\n b. any new file in Source Code Form that contains any Covered Software.\n\n1.11. “Patent Claims” of a Contributor\n\n means any patent claim(s), including without limitation, method, process,\n and apparatus claims, in any patent Licensable by such Contributor that\n would be infringed, but for the grant of the License, by the making,\n using, selling, offering for sale, having made, import, or transfer of\n either its Contributions or its Contributor Version.\n\n1.12. “Secondary License”\n\n means either the GNU General Public License, Version 2.0, the GNU Lesser\n General Public License, Version 2.1, the GNU Affero General Public\n License, Version 3.0, or any later versions of those licenses.\n\n1.13. “Source Code Form”\n\n means the form of the work preferred for making modifications.\n\n1.14. “You” (or “Your”)\n\n means an individual or a legal entity exercising rights under this\n License. For legal entities, “You” includes any entity that controls, is\n controlled by, or is under common control with You. For purposes of this\n definition, “control” means (a) the power, direct or indirect, to cause\n the direction or management of such entity, whether by contract or\n otherwise, or (b) ownership of more than fifty percent (50%) of the\n outstanding shares or beneficial ownership of such entity.\n\n\n2. License Grants and Conditions\n\n2.1. Grants\n\n Each Contributor hereby grants You a world-wide, royalty-free,\n non-exclusive license:\n\n a. under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or as\n part of a Larger Work; and\n\n b. under Patent Claims of such Contributor to make, use, sell, offer for\n sale, have made, import, and otherwise transfer either its Contributions\n or its Contributor Version.\n\n2.2. Effective Date\n\n The licenses granted in Section 2.1 with respect to any Contribution become\n effective for each Contribution on the date the Contributor first distributes\n such Contribution.\n\n2.3. Limitations on Grant Scope\n\n The licenses granted in this Section 2 are the only rights granted under this\n License. No additional rights or licenses will be implied from the distribution\n or licensing of Covered Software under this License. Notwithstanding Section\n 2.1(b) above, no patent license is granted by a Contributor:\n\n a. for any code that a Contributor has removed from Covered Software; or\n\n b. for infringements caused by: (i) Your and any other third party’s\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n c. under Patent Claims infringed by Covered Software in the absence of its\n Contributions.\n\n This License does not grant any rights in the trademarks, service marks, or\n logos of any Contributor (except as may be necessary to comply with the\n notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\n No Contributor makes additional grants as a result of Your choice to\n distribute the Covered Software under a subsequent version of this License\n (see Section 10.2) or under the terms of a Secondary License (if permitted\n under the terms of Section 3.3).\n\n2.5. Representation\n\n Each Contributor represents that the Contributor believes its Contributions\n are its original creation(s) or it has sufficient rights to grant the\n rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\n This License is not intended to limit any rights You have under applicable\n copyright doctrines of fair use, fair dealing, or other equivalents.\n\n2.7. Conditions\n\n Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in\n Section 2.1.\n\n\n3. Responsibilities\n\n3.1. Distribution of Source Form\n\n All distribution of Covered Software in Source Code Form, including any\n Modifications that You create or to which You contribute, must be under the\n terms of this License. You must inform recipients that the Source Code Form\n of the Covered Software is governed by the terms of this License, and how\n they can obtain a copy of this License. You may not attempt to alter or\n restrict the recipients’ rights in the Source Code Form.\n\n3.2. Distribution of Executable Form\n\n If You distribute Covered Software in Executable Form then:\n\n a. such Covered Software must also be made available in Source Code Form,\n as described in Section 3.1, and You must inform recipients of the\n Executable Form how they can obtain a copy of such Source Code Form by\n reasonable means in a timely manner, at a charge no more than the cost\n of distribution to the recipient; and\n\n b. You may distribute such Executable Form under the terms of this License,\n or sublicense it under different terms, provided that the license for\n the Executable Form does not attempt to limit or alter the recipients’\n rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\n You may create and distribute a Larger Work under terms of Your choice,\n provided that You also comply with the requirements of this License for the\n Covered Software. If the Larger Work is a combination of Covered Software\n with a work governed by one or more Secondary Licenses, and the Covered\n Software is not Incompatible With Secondary Licenses, this License permits\n You to additionally distribute such Covered Software under the terms of\n such Secondary License(s), so that the recipient of the Larger Work may, at\n their option, further distribute the Covered Software under the terms of\n either this License or such Secondary License(s).\n\n3.4. Notices\n\n You may not remove or alter the substance of any license notices (including\n copyright notices, patent notices, disclaimers of warranty, or limitations\n of liability) contained within the Source Code Form of the Covered\n Software, except that You may alter any license notices to the extent\n required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\n You may choose to offer, and to charge a fee for, warranty, support,\n indemnity or liability obligations to one or more recipients of Covered\n Software. However, You may do so only on Your own behalf, and not on behalf\n of any Contributor. You must make it absolutely clear that any such\n warranty, support, indemnity, or liability obligation is offered by You\n alone, and You hereby agree to indemnify every Contributor for any\n liability incurred by such Contributor as a result of warranty, support,\n indemnity or liability terms You offer. You may include additional\n disclaimers of warranty and limitations of liability specific to any\n jurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n\n If it is impossible for You to comply with any of the terms of this License\n with respect to some or all of the Covered Software due to statute, judicial\n order, or regulation then You must: (a) comply with the terms of this License\n to the maximum extent possible; and (b) describe the limitations and the code\n they affect. Such description must be placed in a text file included with all\n distributions of the Covered Software under this License. Except to the\n extent prohibited by statute or regulation, such description must be\n sufficiently detailed for a recipient of ordinary skill to be able to\n understand it.\n\n5. Termination\n\n5.1. The rights granted under this License will terminate automatically if You\n fail to comply with any of its terms. However, if You become compliant,\n then the rights granted under this License from a particular Contributor\n are reinstated (a) provisionally, unless and until such Contributor\n explicitly and finally terminates Your grants, and (b) on an ongoing basis,\n if such Contributor fails to notify You of the non-compliance by some\n reasonable means prior to 60 days after You have come back into compliance.\n Moreover, Your grants from a particular Contributor are reinstated on an\n ongoing basis if such Contributor notifies You of the non-compliance by\n some reasonable means, this is the first time You have received notice of\n non-compliance with this License from such Contributor, and You become\n compliant prior to 30 days after Your receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\n infringement claim (excluding declaratory judgment actions, counter-claims,\n and cross-claims) alleging that a Contributor Version directly or\n indirectly infringes any patent, then the rights granted to You by any and\n all Contributors for the Covered Software under Section 2.1 of this License\n shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user\n license agreements (excluding distributors and resellers) which have been\n validly granted by You or Your distributors under this License prior to\n termination shall survive termination.\n\n6. Disclaimer of Warranty\n\n Covered Software is provided under this License on an “as is” basis, without\n warranty of any kind, either expressed, implied, or statutory, including,\n without limitation, warranties that the Covered Software is free of defects,\n merchantable, fit for a particular purpose or non-infringing. The entire\n risk as to the quality and performance of the Covered Software is with You.\n Should any Covered Software prove defective in any respect, You (not any\n Contributor) assume the cost of any necessary servicing, repair, or\n correction. This disclaimer of warranty constitutes an essential part of this\n License. No use of any Covered Software is authorized under this License\n except under this disclaimer.\n\n7. Limitation of Liability\n\n Under no circumstances and under no legal theory, whether tort (including\n negligence), contract, or otherwise, shall any Contributor, or anyone who\n distributes Covered Software as permitted above, be liable to You for any\n direct, indirect, special, incidental, or consequential damages of any\n character including, without limitation, damages for lost profits, loss of\n goodwill, work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses, even if such party shall have been\n informed of the possibility of such damages. This limitation of liability\n shall not apply to liability for death or personal injury resulting from such\n party’s negligence to the extent applicable law prohibits such limitation.\n Some jurisdictions do not allow the exclusion or limitation of incidental or\n consequential damages, so this exclusion and limitation may not apply to You.\n\n8. Litigation\n\n Any litigation relating to this License may be brought only in the courts of\n a jurisdiction where the defendant maintains its principal place of business\n and such litigation shall be governed by laws of that jurisdiction, without\n reference to its conflict-of-law provisions. Nothing in this Section shall\n prevent a party’s ability to bring cross-claims or counter-claims.\n\n9. Miscellaneous\n\n This License represents the complete agreement concerning the subject matter\n hereof. If any provision of this License is held to be unenforceable, such\n provision shall be reformed only to the extent necessary to make it\n enforceable. Any law or regulation which provides that the language of a\n contract shall be construed against the drafter shall not be used to construe\n this License against a Contributor.\n\n\n10. Versions of the License\n\n10.1. New Versions\n\n Mozilla Foundation is the license steward. Except as provided in Section\n 10.3, no one other than the license steward has the right to modify or\n publish new versions of this License. Each version will be given a\n distinguishing version number.\n\n10.2. Effect of New Versions\n\n You may distribute the Covered Software under the terms of the version of\n the License under which You originally received the Covered Software, or\n under the terms of any subsequent version published by the license\n steward.\n\n10.3. Modified Versions\n\n If you create software not governed by this License, and you want to\n create a new license for such software, you may create and use a modified\n version of this License if you rename the license and remove any\n references to the name of the license steward (except to note that such\n modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses\n If You choose to distribute Source Code Form that is Incompatible With\n Secondary Licenses under the terms of this version of the License, the\n notice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n\n This Source Code Form is subject to the\n terms of the Mozilla Public License, v.\n 2.0. If a copy of the MPL was not\n distributed with this file, You can\n obtain one at\n http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular file, then\nYou may include the notice in a location (such as a LICENSE file in a relevant\ndirectory) where a recipient would be likely to look for such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - “Incompatible With Secondary Licenses” Notice\n\n This Source Code Form is “Incompatible\n With Secondary Licenses”, as defined by\n the Mozilla Public License, v. 2.0.\n" + }, { "name": "github.com/hashicorp/go-retryablehttp", "path": "github.com/hashicorp/go-retryablehttp/LICENSE", From a788b4415239921e559448fa865c54cf0a1b7856 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 21 Dec 2022 22:26:52 +0800 Subject: [PATCH 08/17] Remove lock when Unlock --- modules/sync/lock.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 8ba94abe8a4fa..6d91fb2dd7265 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -6,6 +6,7 @@ package sync import ( "sync" + "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/nosql" "code.gitea.io/gitea/modules/setting" redsync "github.com/go-redsync/redsync/v4" @@ -22,7 +23,8 @@ type LockService interface { } type memoryLock struct { - mutex *sync.Mutex + mutex *sync.Mutex + closer func() } func (r *memoryLock) Lock() error { @@ -32,6 +34,7 @@ func (r *memoryLock) Lock() error { func (r *memoryLock) Unlock() (bool, error) { r.mutex.Unlock() + r.closer() return true, nil } @@ -49,7 +52,13 @@ func NewMemoryLockService() *memoryLockService { func (l *memoryLockService) GetLock(name string) Locker { lock, _ := l.lockes.LoadOrStore(name, &sync.Mutex{}) - return &memoryLock{mutex: lock.(*sync.Mutex)} + return &memoryLock{ + mutex: lock.(*sync.Mutex), + closer: func() { + _, _ = l.lockes.LoadAndDelete(name) + log.Trace("Lock: %v", l.lockes) + }, + } } type redisLockService struct { From a2281ddb33f1e5b823b3f04d16eae31b9b1b0fde Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 26 Dec 2022 09:16:09 +0800 Subject: [PATCH 09/17] Use moby/locker --- go.mod | 1 + go.sum | 2 ++ modules/sync/lock.go | 27 ++++++++++++--------------- modules/sync/lock_test.go | 3 +++ 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/go.mod b/go.mod index 60ae9729063e2..c605a75ecd3b4 100644 --- a/go.mod +++ b/go.mod @@ -71,6 +71,7 @@ require ( github.com/mholt/archiver/v3 v3.5.1 github.com/microcosm-cc/bluemonday v1.0.20 github.com/minio/minio-go/v7 v7.0.39 + github.com/moby/locker v1.0.1 github.com/msteinert/pam v1.1.0 github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 github.com/niklasfasching/go-org v1.6.5 diff --git a/go.sum b/go.sum index 60f9d3393e4af..ade98d2a127db 100644 --- a/go.sum +++ b/go.sum @@ -1128,6 +1128,8 @@ github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg= +github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 6d91fb2dd7265..7f0f57a813402 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -6,11 +6,12 @@ package sync import ( "sync" - "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/nosql" "code.gitea.io/gitea/modules/setting" + redsync "github.com/go-redsync/redsync/v4" goredis "github.com/go-redsync/redsync/v4/redis/goredis/v8" + "github.com/moby/locker" ) type Locker interface { @@ -23,41 +24,37 @@ type LockService interface { } type memoryLock struct { - mutex *sync.Mutex - closer func() + locker *locker.Locker + name string } func (r *memoryLock) Lock() error { - r.mutex.Lock() + r.locker.Lock(r.name) return nil } func (r *memoryLock) Unlock() (bool, error) { - r.mutex.Unlock() - r.closer() - return true, nil + return true, r.locker.Unlock(r.name) } var _ Locker = &memoryLock{} type memoryLockService struct { - lockes sync.Map + locker *locker.Locker } var _ LockService = &memoryLockService{} func NewMemoryLockService() *memoryLockService { - return &memoryLockService{} + return &memoryLockService{ + locker: locker.New(), + } } func (l *memoryLockService) GetLock(name string) Locker { - lock, _ := l.lockes.LoadOrStore(name, &sync.Mutex{}) return &memoryLock{ - mutex: lock.(*sync.Mutex), - closer: func() { - _, _ = l.lockes.LoadAndDelete(name) - log.Trace("Lock: %v", l.lockes) - }, + locker: l.locker, + name: name, } } diff --git a/modules/sync/lock_test.go b/modules/sync/lock_test.go index 25622d3172ccc..e89b8f2b2a916 100644 --- a/modules/sync/lock_test.go +++ b/modules/sync/lock_test.go @@ -8,4 +8,7 @@ import ( ) func Test_Lock(t *testing.T) { + locker := GetLockService().GetLock("test") + locker.Lock() + locker.Unlock() } From 8ea63e451dc9511395386a89ef436161708e99ae Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 27 Dec 2022 10:38:13 +0800 Subject: [PATCH 10/17] Fix lint --- modules/sync/lock.go | 8 ++++---- services/cron/tasks.go | 8 ++++++-- services/pull/check.go | 11 +++++++++-- services/pull/merge.go | 22 ++++++++++++++++++---- services/pull/pull.go | 12 ++++++++++-- services/pull/update.go | 11 +++++++++-- services/repository/transfer.go | 29 ++++++++++++++++++++--------- services/wiki/wiki.go | 20 ++++++++++++++++---- 8 files changed, 92 insertions(+), 29 deletions(-) diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 7f0f57a813402..bad51fe6943f0 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -45,7 +45,7 @@ type memoryLockService struct { var _ LockService = &memoryLockService{} -func NewMemoryLockService() *memoryLockService { +func newMemoryLockService() *memoryLockService { return &memoryLockService{ locker: locker.New(), } @@ -64,7 +64,7 @@ type redisLockService struct { var _ LockService = &redisLockService{} -func NewRedisLockService(connection string) *redisLockService { +func newRedisLockService(connection string) *redisLockService { client := nosql.GetManager().GetRedisClient(connection) pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...) @@ -102,9 +102,9 @@ var ( func GetLockService() LockService { syncOnce.Do(func() { if setting.Sync.LockServiceType == "redis" { - lockService = NewRedisLockService(setting.Sync.LockServiceConnStr) + lockService = newRedisLockService(setting.Sync.LockServiceConnStr) } else { - lockService = NewMemoryLockService() + lockService = newMemoryLockService() } }) return lockService diff --git a/services/cron/tasks.go b/services/cron/tasks.go index 90c2d522801d0..2f30788386ef7 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -71,7 +71,8 @@ func (t *Task) Run() { // RunWithUser will run the task incrementing the cron counter at the time with User func (t *Task) RunWithUser(doer *user_model.User, config Config) { lock := sync_module.GetLockService().GetLock(fmt.Sprintf("cron_tasks_%s", t.Name)) - if lock.Lock() != nil { + if err := lock.Lock(); err != nil { + log.Error("Unable to lock cron task %s Error: %v", t.Name, err) return } @@ -82,7 +83,10 @@ func (t *Task) RunWithUser(doer *user_model.User, config Config) { t.ExecTimes++ t.lock.Unlock() defer func() { - lock.Unlock() + if _, err := lock.Unlock(); err != nil { + log.Error("Unable to unlock cron task %s Error: %v", t.Name, err) + } + if err := recover(); err != nil { // Recover a panic within the combinedErr := fmt.Errorf("%s\n%s", err, log.Stack(2)) diff --git a/services/pull/check.go b/services/pull/check.go index 967aeddf9d21b..7841dfb679711 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -320,8 +320,15 @@ func handle(data ...queue.Data) []queue.Data { func testPR(id int64) { lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", id)) - lock.Lock() - defer lock.Unlock() + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("Test PR[%d] from patch checking queue", id)) defer finished() diff --git a/services/pull/merge.go b/services/pull/merge.go index 231544788dc47..dbee20d024fc0 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -143,8 +143,15 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U } lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) - lock.Lock() - defer lock.Unlock() + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() // Removing an auto merge pull and ignore if not exist if err := pull_model.DeleteScheduledAutoMerge(ctx, pr.ID); err != nil && !db.IsErrNotExist(err) { @@ -827,8 +834,15 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) - lock.Lock() - defer lock.Unlock() + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) diff --git a/services/pull/pull.go b/services/pull/pull.go index b9c47b005f29b..4575a9075a703 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -129,8 +129,16 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issu // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) - lock.Lock() - defer lock.Unlock() + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + _, err := lock.Unlock() + if err != nil { + log.Error("lock.Unlock(): %v", err) + } + }() // Current target branch is already the same if pr.BaseBranch == targetBranch { diff --git a/services/pull/update.go b/services/pull/update.go index 69939baa2115f..71c8a8cab7ed9 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -27,8 +27,15 @@ func Update(ctx context.Context, pull *issues_model.PullRequest, doer *user_mode ) lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pull.ID)) - lock.Lock() - defer lock.Unlock() + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() if rebase { pr = pull diff --git a/services/repository/transfer.go b/services/repository/transfer.go index aaff64812b253..eb920b2a27feb 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -34,13 +34,19 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner lock := sync.GetLockService().GetLock(fmt.Sprintf("repo_working_%d", repo.ID)) - lock.Lock() + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() + if err := models.TransferOwnership(doer, newOwner.Name, repo); err != nil { - lock.Unlock() return err } - lock.Unlock() - newRepo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { return err @@ -66,15 +72,20 @@ func ChangeRepositoryName(doer *user_model.User, repo *repo_model.Repository, ne // Change repository directory name. We must lock the local copy of the // repo so that we can atomically rename the repo path and updates the // local copy's origin accordingly. - lock := sync.GetLockService().GetLock(fmt.Sprintf("repo_working_%d", repo.ID)) - lock.Lock() + if err := lock.Lock(); err != nil { + log.Error("lock.Lock(): %v", err) + return fmt.Errorf("lock.Lock: %w", err) + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() + if err := repo_model.ChangeRepositoryName(doer, repo, newRepoName); err != nil { - lock.Unlock() return err } - lock.Unlock() - repo.Name = newRepoName notification.NotifyRenameRepository(db.DefaultContext, doer, repo, oldRepoName) diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index 2f5a568f95b07..7fad1cb677fc5 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -124,8 +124,14 @@ func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model return err } lock := sync.GetLockService().GetLock(fmt.Sprintf("wiki_working_%d", repo.ID)) - lock.Lock() - defer lock.Unlock() + if err := lock.Lock(); err != nil { + return err + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) @@ -281,8 +287,14 @@ func EditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.R // DeleteWikiPage deletes a wiki page identified by its path. func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, wikiName string) (err error) { lock := sync.GetLockService().GetLock(fmt.Sprintf("wiki_working_%d", repo.ID)) - lock.Lock() - defer lock.Unlock() + if err := lock.Lock(); err != nil { + return err + } + defer func() { + if _, err := lock.Unlock(); err != nil { + log.Error("lock.Unlock: %v", err) + } + }() if err = InitWiki(ctx, repo); err != nil { return fmt.Errorf("InitWiki: %w", err) From 5cc28506730803a7a51a2820b49332a14efd0022 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 1 Jan 2023 10:39:00 +0800 Subject: [PATCH 11/17] Fix check --- assets/go-licenses.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/assets/go-licenses.json b/assets/go-licenses.json index d67393d7c64dd..78f133639f182 100644 --- a/assets/go-licenses.json +++ b/assets/go-licenses.json @@ -659,6 +659,11 @@ "path": "github.com/mitchellh/mapstructure/LICENSE", "licenseText": "The MIT License (MIT)\n\nCopyright (c) 2013 Mitchell Hashimoto\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n" }, + { + "name": "github.com/moby/locker", + "path": "github.com/moby/locker/LICENSE", + "licenseText": " Apache License\n Version 2.0, January 2004\n https://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n Copyright 2013-2018 Docker, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n" + }, { "name": "github.com/modern-go/concurrent", "path": "github.com/modern-go/concurrent/LICENSE", From 8642873f91506cf7516b46daa6b6bd7909413da5 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 1 Jan 2023 11:47:29 +0800 Subject: [PATCH 12/17] lock key --- services/pull/check.go | 6 +++++- services/pull/merge.go | 4 ++-- services/pull/pull.go | 2 +- services/pull/update.go | 2 +- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/services/pull/check.go b/services/pull/check.go index 30d96dd2bf41e..f217aaf8f5b38 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -318,8 +318,12 @@ func handle(data ...queue.Data) []queue.Data { return nil } +func getPullWorkingLockKey(prID int64) string { + return fmt.Sprintf("pull_working_%d", prID) +} + func testPR(id int64) { - lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", id)) + lock := sync.GetLockService().GetLock(getPullWorkingLockKey(id)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return diff --git a/services/pull/merge.go b/services/pull/merge.go index 9688d196395f8..d77ca1d0434af 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -150,7 +150,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("LoadBaseRepo: %w", err) } - lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pr.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -841,7 +841,7 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pr.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/pull/pull.go b/services/pull/pull.go index 4575a9075a703..e3891e5ec623f 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -128,7 +128,7 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issu // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pr.ID)) + lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pr.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/pull/update.go b/services/pull/update.go index 71c8a8cab7ed9..ae27f7900b5c9 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -26,7 +26,7 @@ func Update(ctx context.Context, pull *issues_model.PullRequest, doer *user_mode style repo_model.MergeStyle ) - lock := sync.GetLockService().GetLock(fmt.Sprintf("pull_working_%d", pull.ID)) + lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pull.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) From 3a9df2e169d52fc0ef9b1ebffe5a7a543ab50918 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 1 Jan 2023 11:52:57 +0800 Subject: [PATCH 13/17] Simple lock usage --- modules/sync/lock.go | 6 +++++- modules/sync/lock_test.go | 2 +- services/cron/tasks.go | 2 +- services/pull/check.go | 2 +- services/pull/merge.go | 4 ++-- services/pull/pull.go | 2 +- services/pull/update.go | 2 +- services/repository/transfer.go | 8 ++++++-- services/wiki/wiki.go | 8 ++++++-- 9 files changed, 24 insertions(+), 12 deletions(-) diff --git a/modules/sync/lock.go b/modules/sync/lock.go index bad51fe6943f0..14991e74bf4a0 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -99,7 +99,7 @@ var ( lockService LockService ) -func GetLockService() LockService { +func getLockService() LockService { syncOnce.Do(func() { if setting.Sync.LockServiceType == "redis" { lockService = newRedisLockService(setting.Sync.LockServiceConnStr) @@ -109,3 +109,7 @@ func GetLockService() LockService { }) return lockService } + +func GetLock(name string) Locker { + return getLockService().GetLock(name) +} diff --git a/modules/sync/lock_test.go b/modules/sync/lock_test.go index e89b8f2b2a916..255f160913375 100644 --- a/modules/sync/lock_test.go +++ b/modules/sync/lock_test.go @@ -8,7 +8,7 @@ import ( ) func Test_Lock(t *testing.T) { - locker := GetLockService().GetLock("test") + locker := GetLock("test") locker.Lock() locker.Unlock() } diff --git a/services/cron/tasks.go b/services/cron/tasks.go index 2f30788386ef7..73c04d7fe97ac 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -70,7 +70,7 @@ func (t *Task) Run() { // RunWithUser will run the task incrementing the cron counter at the time with User func (t *Task) RunWithUser(doer *user_model.User, config Config) { - lock := sync_module.GetLockService().GetLock(fmt.Sprintf("cron_tasks_%s", t.Name)) + lock := sync_module.GetLock(fmt.Sprintf("cron_tasks_%s", t.Name)) if err := lock.Lock(); err != nil { log.Error("Unable to lock cron task %s Error: %v", t.Name, err) return diff --git a/services/pull/check.go b/services/pull/check.go index f217aaf8f5b38..1b3753daee3ba 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -323,7 +323,7 @@ func getPullWorkingLockKey(prID int64) string { } func testPR(id int64) { - lock := sync.GetLockService().GetLock(getPullWorkingLockKey(id)) + lock := sync.GetLock(getPullWorkingLockKey(id)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return diff --git a/services/pull/merge.go b/services/pull/merge.go index d77ca1d0434af..20e9c18b7d755 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -150,7 +150,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U return fmt.Errorf("LoadBaseRepo: %w", err) } - lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pr.ID)) + lock := sync.GetLock(getPullWorkingLockKey(pr.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -841,7 +841,7 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques // MergedManually mark pr as merged manually func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { - lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pr.ID)) + lock := sync.GetLock(getPullWorkingLockKey(pr.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/pull/pull.go b/services/pull/pull.go index e3891e5ec623f..d6e5d036c5aae 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -128,7 +128,7 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issu // ChangeTargetBranch changes the target branch of this pull request, as the given user. func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, targetBranch string) (err error) { - lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pr.ID)) + lock := sync.GetLock(getPullWorkingLockKey(pr.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/pull/update.go b/services/pull/update.go index ae27f7900b5c9..a6ac2b6c32d9b 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -26,7 +26,7 @@ func Update(ctx context.Context, pull *issues_model.PullRequest, doer *user_mode style repo_model.MergeStyle ) - lock := sync.GetLockService().GetLock(getPullWorkingLockKey(pull.ID)) + lock := sync.GetLock(getPullWorkingLockKey(pull.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/repository/transfer.go b/services/repository/transfer.go index eb920b2a27feb..aadb99cd728de 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -20,6 +20,10 @@ import ( "code.gitea.io/gitea/modules/sync" ) +func getRepoWorkingLockKey(repoID int64) string { + return fmt.Sprintf("repo_working_%d", repoID) +} + // TransferOwnership transfers all corresponding setting from old user to new one. func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*organization.Team) error { if err := repo.GetOwner(ctx); err != nil { @@ -33,7 +37,7 @@ func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, rep oldOwner := repo.Owner - lock := sync.GetLockService().GetLock(fmt.Sprintf("repo_working_%d", repo.ID)) + lock := sync.GetLock(getRepoWorkingLockKey(repo.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) @@ -72,7 +76,7 @@ func ChangeRepositoryName(doer *user_model.User, repo *repo_model.Repository, ne // Change repository directory name. We must lock the local copy of the // repo so that we can atomically rename the repo path and updates the // local copy's origin accordingly. - lock := sync.GetLockService().GetLock(fmt.Sprintf("repo_working_%d", repo.ID)) + lock := sync.GetLock(getRepoWorkingLockKey(repo.ID)) if err := lock.Lock(); err != nil { log.Error("lock.Lock(): %v", err) return fmt.Errorf("lock.Lock: %w", err) diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index 7fad1cb677fc5..94b950037ae2e 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -118,12 +118,16 @@ func prepareWikiFileName(gitRepo *git.Repository, wikiName string) (bool, string return foundEscaped, escaped, nil } +func getWikiWorkingLockKey(repoID int64) string { + return fmt.Sprintf("wiki_working_%d", repoID) +} + // updateWikiPage adds a new page or edits an existing page in repository wiki. func updateWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldWikiName, newWikiName, content, message string, isNew bool) (err error) { if err = nameAllowed(newWikiName); err != nil { return err } - lock := sync.GetLockService().GetLock(fmt.Sprintf("wiki_working_%d", repo.ID)) + lock := sync.GetLock(getWikiWorkingLockKey(repo.ID)) if err := lock.Lock(); err != nil { return err } @@ -286,7 +290,7 @@ func EditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.R // DeleteWikiPage deletes a wiki page identified by its path. func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, wikiName string) (err error) { - lock := sync.GetLockService().GetLock(fmt.Sprintf("wiki_working_%d", repo.ID)) + lock := sync.GetLock(getWikiWorkingLockKey(repo.ID)) if err := lock.Lock(); err != nil { return err } From d2c398032af846ecb1ae94fd6f367f3446bbed75 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 10 Jan 2023 17:52:46 +0800 Subject: [PATCH 14/17] Update documentations --- custom/conf/app.example.ini | 7 ++++--- docs/content/doc/advanced/config-cheat-sheet.en-us.md | 5 +++++ docs/content/doc/advanced/config-cheat-sheet.zh-cn.md | 5 +++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index f08a0f1d3fd22..74420a93549b9 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -2489,6 +2489,7 @@ ROUTER = console ;PROXY_HOSTS = ;[sync] -;; lock service type, could be memory or redis -; LOCK_SERVICE_TYPE = memory -; LOCK_SERVICE_CONN_STR = ; redis "addrs=127.0.0.1:6379 db=0" +;; Lock service type, could be memory or redis +;LOCK_SERVICE_TYPE = memory +;; Ignored by memory type, for redis, it likes "addrs=127.0.0.1:6379 db=0" +;LOCK_SERVICE_CONN_STR = diff --git a/docs/content/doc/advanced/config-cheat-sheet.en-us.md b/docs/content/doc/advanced/config-cheat-sheet.en-us.md index 3ccef3130cac3..5a11dd78c1593 100644 --- a/docs/content/doc/advanced/config-cheat-sheet.en-us.md +++ b/docs/content/doc/advanced/config-cheat-sheet.en-us.md @@ -1290,6 +1290,11 @@ PROXY_URL = socks://127.0.0.1:1080 PROXY_HOSTS = *.github.com ``` +## Sync (`sync`) + +- `LOCK_SERVICE_TYPE`: **memory**: Lock service type, could be `memory` or `redis` +- `LOCK_SERVICE_CONN_STR`: ****: Ignored when `LOCK_SERVICE_TYPE` is `memory` type, for `redis`, it likes `addrs=127.0.0.1:6379 db=0` + ## Other (`other`) - `SHOW_FOOTER_BRANDING`: **false**: Show Gitea branding in the footer. diff --git a/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md b/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md index f10b6258c87a2..0775aefaa3f32 100644 --- a/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md +++ b/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md @@ -453,6 +453,11 @@ PROXY_URL = socks://127.0.0.1:1080 PROXY_HOSTS = *.github.com ``` +## Sync (`sync`) + +- `LOCK_SERVICE_TYPE`: **memory**: 锁服务类型,可以是 `memory` 或 `redis` +- `LOCK_SERVICE_CONN_STR`: ****: 如果 `LOCK_SERVICE_TYPE` 是 `memory`,则忽略,如果是 `redis`,则支持形式如 `addrs=127.0.0.1:6379 db=0` + ## Other (`other`) - `SHOW_FOOTER_BRANDING`: 为真则在页面底部显示Gitea的字样。 From 98dd8f4f995a1a2386cb3110db60a936bd48cc8d Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 11 Jan 2023 00:39:49 +0800 Subject: [PATCH 15/17] Apply suggestions from code review Co-authored-by: Yarden Shoham --- modules/setting/sync.go | 2 +- modules/sync/lock.go | 2 +- modules/sync/lock_test.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/setting/sync.go b/modules/setting/sync.go index 60c1e5c41c12d..b70607179b3bc 100644 --- a/modules/setting/sync.go +++ b/modules/setting/sync.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. +// Copyright 2023 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package setting diff --git a/modules/sync/lock.go b/modules/sync/lock.go index 14991e74bf4a0..c205e8ab8d91b 100644 --- a/modules/sync/lock.go +++ b/modules/sync/lock.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. +// Copyright 2023 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package sync diff --git a/modules/sync/lock_test.go b/modules/sync/lock_test.go index 255f160913375..35e54f17cbb15 100644 --- a/modules/sync/lock_test.go +++ b/modules/sync/lock_test.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Gitea Authors. All rights reserved. +// Copyright 2023 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package sync From 02ef039c3682aa3ad518a3a5d719e98a742e9303 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 11 Jan 2023 17:51:05 +0800 Subject: [PATCH 16/17] add tests --- modules/setting/setting.go | 2 +- modules/setting/sync.go | 26 +++++++++++++++++++++----- modules/setting/sync_test.go | 22 ++++++++++++++++++++++ 3 files changed, 44 insertions(+), 6 deletions(-) create mode 100644 modules/setting/sync_test.go diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 30238d6062fc0..9987a691f847a 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -1139,7 +1139,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) { UI.CustomEmojisMap[emoji] = ":" + emoji + ":" } - parseSyncSetting() + parseSyncConfig(Cfg) } func parseAuthorizedPrincipalsAllow(values []string) ([]string, bool) { diff --git a/modules/setting/sync.go b/modules/setting/sync.go index 60c1e5c41c12d..2d5ee115ada1b 100644 --- a/modules/setting/sync.go +++ b/modules/setting/sync.go @@ -3,7 +3,12 @@ package setting -import "code.gitea.io/gitea/modules/log" +import ( + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/nosql" + + ini "gopkg.in/ini.v1" +) // Sync represents configuration of sync var Sync = struct { @@ -13,11 +18,22 @@ var Sync = struct { LockServiceType: "memory", } -func parseSyncSetting() { - sec := Cfg.Section("sync") +func parseSyncConfig(rootCfg *ini.File) { + sec := rootCfg.Section("sync") Sync.LockServiceType = sec.Key("LOCK_SERVICE_TYPE").MustString("memory") - if Sync.LockServiceType != "memory" && Sync.LockServiceType != "redis" { + switch Sync.LockServiceType { + case "memory": + case "redis": + connStr := sec.Key("LOCK_SERVICE_CONN_STR").String() + if connStr == "" { + log.Fatal("LOCK_SERVICE_CONN_STR is empty for redis") + } + u := nosql.ToRedisURI(connStr) + if u == nil { + log.Fatal("LOCK_SERVICE_CONN_STR %s is not right for redis", connStr) + } + Sync.LockServiceConnStr = connStr + default: log.Fatal("Unknown sync lock service type: %s", Sync.LockServiceType) } - Sync.LockServiceConnStr = sec.Key("LOCK_SERVICE_CONN_STR").MustString("") } diff --git a/modules/setting/sync_test.go b/modules/setting/sync_test.go new file mode 100644 index 0000000000000..5273af8bf7d71 --- /dev/null +++ b/modules/setting/sync_test.go @@ -0,0 +1,22 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package setting + +import ( + "testing" + + "gopkg.in/ini.v1" +) + +func TestParseSyncConfig(t *testing.T) { + iniFile := ini.Empty() + + t.Run("RedisSyncConfig", func(t *testing.T) { + iniFile.DeleteSection("sync") + sec := iniFile.Section("sync") + sec.NewKey("LOCK_SERVICE_TYPE", "redis") + sec.NewKey("LOCK_SERVICE_CONN_STR", "addrs=127.0.0.1:6379 db=0") + parseSyncConfig(iniFile) + }) +} From 179beb8274226f58d4db87b55ed6e9d3b21408da Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 11 Jan 2023 17:52:24 +0800 Subject: [PATCH 17/17] Update documentations --- docs/content/doc/advanced/config-cheat-sheet.en-us.md | 2 +- docs/content/doc/advanced/config-cheat-sheet.zh-cn.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/content/doc/advanced/config-cheat-sheet.en-us.md b/docs/content/doc/advanced/config-cheat-sheet.en-us.md index f40a60d9baef8..d914a11112f3f 100644 --- a/docs/content/doc/advanced/config-cheat-sheet.en-us.md +++ b/docs/content/doc/advanced/config-cheat-sheet.en-us.md @@ -1293,7 +1293,7 @@ PROXY_HOSTS = *.github.com ## Sync (`sync`) - `LOCK_SERVICE_TYPE`: **memory**: Lock service type, could be `memory` or `redis` -- `LOCK_SERVICE_CONN_STR`: ****: Ignored when `LOCK_SERVICE_TYPE` is `memory` type, for `redis`, it likes `addrs=127.0.0.1:6379 db=0` +- `LOCK_SERVICE_CONN_STR`: **\**: Ignored when `LOCK_SERVICE_TYPE` is `memory` type, for `redis`, it likes `addrs=127.0.0.1:6379 db=0` ## Other (`other`) diff --git a/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md b/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md index 0775aefaa3f32..42f724be84f85 100644 --- a/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md +++ b/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md @@ -456,7 +456,7 @@ PROXY_HOSTS = *.github.com ## Sync (`sync`) - `LOCK_SERVICE_TYPE`: **memory**: 锁服务类型,可以是 `memory` 或 `redis` -- `LOCK_SERVICE_CONN_STR`: ****: 如果 `LOCK_SERVICE_TYPE` 是 `memory`,则忽略,如果是 `redis`,则支持形式如 `addrs=127.0.0.1:6379 db=0` +- `LOCK_SERVICE_CONN_STR`: **\**: 如果 `LOCK_SERVICE_TYPE` 是 `memory`,则忽略,如果是 `redis`,则支持形式如 `addrs=127.0.0.1:6379 db=0` ## Other (`other`)