From 0a0c1884d028e46aee9e1e97f0fcce2997e0e2ee Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 23 Jun 2023 04:18:20 +0000 Subject: [PATCH 01/39] first --- assets/go-licenses.json | 15 ++ custom/conf/app.example.ini | 25 +++ go.mod | 3 + go.sum | 12 ++ modules/setting/storage.go | 37 +++- modules/storage/azure.go | 305 ++++++++++++++++++++++++++++++++ modules/storage/azure_test.go | 26 +++ modules/storage/storage_test.go | 1 + 8 files changed, 420 insertions(+), 4 deletions(-) create mode 100644 modules/storage/azure.go create mode 100644 modules/storage/azure_test.go diff --git a/assets/go-licenses.json b/assets/go-licenses.json index d8ef5bb442e2c..6e98102914740 100644 --- a/assets/go-licenses.json +++ b/assets/go-licenses.json @@ -64,6 +64,21 @@ "path": "github.com/42wim/sshsig/LICENSE", "licenseText": " Apache License\n Version 2.0, January 2004\n http://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 APPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\n Copyright [yyyy] [name of copyright owner]\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 http://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/Azure/azure-sdk-for-go/sdk/azcore", + "path": "github.com/Azure/azure-sdk-for-go/sdk/azcore/LICENSE.txt", + "licenseText": "MIT License\n\nCopyright (c) Microsoft Corporation.\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 all\ncopies 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 THE\nSOFTWARE\n" + }, + { + "name": "github.com/Azure/azure-sdk-for-go/sdk/internal", + "path": "github.com/Azure/azure-sdk-for-go/sdk/internal/LICENSE.txt", + "licenseText": "MIT License\n\nCopyright (c) Microsoft Corporation.\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 all\ncopies 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 THE\nSOFTWARE\n" + }, + { + "name": "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob", + "path": "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/LICENSE.txt", + "licenseText": " MIT License\n\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE" + }, { "name": "github.com/Azure/go-ntlmssp", "path": "github.com/Azure/go-ntlmssp/LICENSE", diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index f53d9ee089000..b57f0ae5f0606 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -1833,6 +1833,10 @@ LEVEL = Info ;; ;; Minio checksum algorithm: default (for MinIO or AWS S3) or md5 (for Cloudflare or Backblaze) ;MINIO_CHECKSUM_ALGORITHM = default +;; override the azure blob base path if storage type is azureblob +;AZURE_BLOB_BASE_PATH = attachments/ +;; override the azure blob base path if storage type is azureblob +;AZURE_BLOB_CONTAINER = attachments/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -2395,6 +2399,8 @@ LEVEL = Info ;STORAGE_TYPE = local ;; override the minio base path if storage type is minio ;MINIO_BASE_PATH = packages/ +;; override the azure blob base path if storage type is azureblob +;AZURE_BLOB_BASE_PATH = packages/ ;; ;; Path for chunked uploads. Defaults to APP_DATA_PATH + `tmp/package-upload` ;CHUNKED_UPLOAD_PATH = tmp/package-upload @@ -2468,6 +2474,8 @@ LEVEL = Info ;; ;; override the minio base path if storage type is minio ;MINIO_BASE_PATH = repo-archive/ +;; override the azure blob base path if storage type is azureblob +;AZURE_BLOB_BASE_PATH = repo-archive/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -2491,6 +2499,8 @@ LEVEL = Info ;; ;; override the minio base path if storage type is minio ;MINIO_BASE_PATH = lfs/ +;; override the azure blob base path if storage type is azureblob +;AZURE_BLOB_BASE_PATH = lfs/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -2529,6 +2539,21 @@ LEVEL = Info ;; Minio skip SSL verification available when STORAGE_TYPE is `minio` ;MINIO_INSECURE_SKIP_VERIFY = false +;[storage.azureblob] +;STORAGE_TYPE=azureblob +;; +;; Azure Blob endpoint to connect only available when STORAGE_TYPE is `azureblob` +;AZUREBLOB_ENDPOINT = https://.blob.core.windows.net/ +;; +;; Azure Blob account name to connect only available when STORAGE_TYPE is `azureblob` +;AZUREBLOB_ACCOUNT_NAME = +;; +;; Azure Blob account key to connect only available when STORAGE_TYPE is `azureblob` +;AZUREBLOB_ACCOUNT_KEY = +;; +;; Azure Blob container to store the attachments only available when STORAGE_TYPE is `azureblob` +;AZUREBLOB_CONTAINER = + ;[proxy] ;; Enable the proxy, all requests to external via HTTP will be affected ;PROXY_ENABLED = false diff --git a/go.mod b/go.mod index 7b7a51efbb7fc..7f63d25ffa848 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,8 @@ require ( gitea.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96 gitea.com/lunny/levelqueue v0.4.2-0.20220729054728-f020868cc2f7 github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.0 + github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.0.0 github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 github.com/NYTimes/gziphandler v1.1.1 github.com/PuerkitoBio/goquery v1.8.1 @@ -129,6 +131,7 @@ require ( cloud.google.com/go/compute v1.18.0 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.1.1 // indirect github.com/ClickHouse/ch-go v0.55.0 // indirect github.com/ClickHouse/clickhouse-go/v2 v2.9.1 // indirect github.com/DataDog/zstd v1.4.5 // indirect diff --git a/go.sum b/go.sum index c3ac719f3f4ad..64fef2e392e71 100644 --- a/go.sum +++ b/go.sum @@ -75,11 +75,19 @@ github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121/go.mod h1:Ock8XgA7pvU github.com/6543/go-version v1.3.1 h1:HvOp+Telns7HWJ2Xo/05YXQSB2bE0WmVgbHqwMPZT4U= github.com/6543/go-version v1.3.1/go.mod h1:oqFAHCwtLVUTLdhQmVZWYvaHXTdsbB4SY85at64SQEo= github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.0 h1:VuHAcMq8pU1IWNT/m5yRaGqbK0BiQKHT8X4DTp9CHdI= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.0/go.mod h1:tZoQYdDZNOiIjdSn0dVWVfl0NEPGOJqVLzSrcFk4Is0= github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0/go.mod h1:HcM1YX14R7CJcghJGOYCgdezslRSVzqwLf/q+4Y2r/0= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.1.0 h1:QkAcEIAKbNL4KoFr4SathZPhDhF4mVwpBMFlYjyAqy8= github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.1.1 h1:Oj853U9kG+RLTCQXpjvOnrv0WaZHxgmZz1TlLywgOPY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.1.1/go.mod h1:eWRD7oawr1Mu1sLCawqVc0CUiF43ia3qQMxLscsKQ9w= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.0.0 h1:u/LLAOFgsMv7HmNL4Qufg58y+qElGOt5qv0z1mURkRY= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.0.0/go.mod h1:2e8rMJtl2+2j+HXbTBwnyGpm5Nou7KhvSfxOq8JpTag= github.com/Azure/go-ntlmssp v0.0.0-20220621081337-cb9428e4ac1e/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= +github.com/AzureAD/microsoft-authentication-library-for-go v0.5.1 h1:BWe8a+f/t+7KY7zH2mqygeUD0t8hNFXe08p1Pb3/jKE= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= @@ -307,6 +315,7 @@ github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55k github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dlclark/regexp2 v1.9.0 h1:pTK/l/3qYIKaRXuHnEnIf7Y5NxfRPfpb7dis6/gdlVI= github.com/dlclark/regexp2 v1.9.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/dsnet/compress v0.0.2-0.20210315054119-f66993602bf5 h1:iFaUwBSo5Svw6L7HYpRu/0lE3e0BaElwnNO1qkNQxBY= github.com/dsnet/compress v0.0.2-0.20210315054119-f66993602bf5/go.mod h1:qssHWj60/X5sZFNxpG4HBPDHVqxNm4DfnCKgrbZOT+s= @@ -504,6 +513,7 @@ github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14 h1:yXtpJr/LV6PFu4nTLgfjQ github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14/go.mod h1:jPoNZLWDAqA5N3G5amEoiNbhVrmM+ZQEcnQvNQ2KaZk= github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85 h1:UjoPNDAQ5JPCjlxoJd6K8ALZqSDDhk2ymieAZOVaDg0= github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85/go.mod h1:fR6z1Ie6rtF7kl/vBYMfgD5/G5B1blui7z426/sj2DU= +github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= @@ -806,6 +816,7 @@ github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= github.com/lestrrat-go/blackmagic v1.0.0/go.mod h1:TNgH//0vYSs8VXDCfkZLgIrVTTXQELZffUV0tz3MtdQ= github.com/lestrrat-go/httpcc v1.0.0/go.mod h1:tGS/u00Vh5N6FHNkExqGGNId8e0Big+++0Gf8MBnAvE= @@ -1007,6 +1018,7 @@ github.com/pierrec/lz4/v4 v4.1.17/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFu github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= +github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4 h1:Qj1ukM4GlMWXNdMBuXcXfz/Kw9s1qm0CLY32QxuSImI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= diff --git a/modules/setting/storage.go b/modules/setting/storage.go index ed804a910a461..4df954e6cb833 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -17,11 +17,14 @@ const ( LocalStorageType StorageType = "local" // MinioStorageType is the type descriptor for minio storage MinioStorageType StorageType = "minio" + // AzureBlobStorageType is the type descriptor for azure blob storage + AzureBlobStorageType StorageType = "azureblob" ) var storageTypes = []StorageType{ LocalStorageType, MinioStorageType, + AzureBlobStorageType, } // IsValidStorageType returns true if the given storage type is valid @@ -48,12 +51,22 @@ type MinioStorageConfig struct { ServeDirect bool `ini:"SERVE_DIRECT"` } +// MinioStorageConfig represents the configuration for a minio storage +type AzureBlobStorageConfig struct { + Endpoint string `ini:"AZUREBLOB_ENDPOINT" json:",omitempty"` + AccountName string `ini:"AZUREBLOB_ACCOUNT_NAME" json:",omitempty"` + AccountKey string `ini:"AZUREBLOB_ACCOUNT_KEY" json:",omitempty"` + Container string `ini:"AZUREBLOB_CONTAINER" json:",omitempty"` + BasePath string `ini:"AZUREBLOB_BASE_PATH" json:",omitempty"` +} + // Storage represents configuration of storages type Storage struct { - Type StorageType // local or minio - Path string `json:",omitempty"` // for local type - TemporaryPath string `json:",omitempty"` - MinioConfig MinioStorageConfig // for minio type + Type StorageType // local or minio or azureblob + Path string `json:",omitempty"` // for local type + TemporaryPath string `json:",omitempty"` + MinioConfig MinioStorageConfig // for minio type + AzureBlobConfig AzureBlobStorageConfig // for azureblob type } func (storage *Storage) ToShadowCopy() Storage { @@ -179,6 +192,22 @@ func getStorage(rootCfg ConfigProvider, name, typ string, sec ConfigSection) (*S storage.MinioConfig.BasePath = ConfigSectionKeyString(extraConfigSec, "MINIO_BASE_PATH", storage.MinioConfig.BasePath) storage.MinioConfig.Bucket = ConfigSectionKeyString(extraConfigSec, "MINIO_BUCKET", storage.MinioConfig.Bucket) } + case string(AzureBlobStorageType): + storage.AzureBlobConfig.BasePath = name + "/" + + if err := targetSec.MapTo(&storage.AzureBlobConfig); err != nil { + return nil, fmt.Errorf("map azure blob config failed: %v", err) + } + // extra config section will be read SERVE_DIRECT, PATH, MINIO_BASE_PATH to override the targetsec + extraConfigSec := sec + if extraConfigSec == nil { + extraConfigSec = storageNameSec + } + + if extraConfigSec != nil { + storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(extraConfigSec, "AZUREBLOB_BASE_PATH", storage.AzureBlobConfig.BasePath) + storage.AzureBlobConfig.Container = ConfigSectionKeyString(extraConfigSec, "AZUREBLOB_CONTAINER", storage.AzureBlobConfig.Container) + } } return &storage, nil diff --git a/modules/storage/azure.go b/modules/storage/azure.go new file mode 100644 index 0000000000000..c972656887f7c --- /dev/null +++ b/modules/storage/azure.go @@ -0,0 +1,305 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package storage + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/url" + "os" + "path" + "strings" + "time" + + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/util" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container" +) + +var _ ObjectStorage = &AzureBlobStorage{} + +type azureBlobObject struct { + BlobClient *blob.Client + Context *context.Context + Name string + Size int64 + ModTime *time.Time + + Offset int64 +} + +func (a *azureBlobObject) downloadStream(p []byte) (int, error) { + if a.BlobClient == nil { + return 0, fmt.Errorf("no blob client in azure blob object") + } + if a.Context == nil { + return 0, fmt.Errorf("no context in azure blob object") + } + + if a.Offset > a.Size { + return 0, io.EOF + } + count := a.Size - a.Offset + pl := int64(len(p)) + if pl > count { + p = p[0:count] + } else { + count = pl + } + res, err := a.BlobClient.DownloadStream(*a.Context, &blob.DownloadStreamOptions{ + Range: blob.HTTPRange{ + Offset: a.Offset, + Count: count, + }, + }) + if err != nil { + return 0, convertAzureBlobErr(err) + } + a.Offset += count + + buf := bytes.NewBuffer(p) + c, err := io.Copy(buf, res.Body) + return int(c), err +} + +func (a *azureBlobObject) Close() error { + return nil +} + +func (a *azureBlobObject) Read(p []byte) (int, error) { + c, err := a.downloadStream(p) + return c, err +} + +func (a *azureBlobObject) Seek(offset int64, whence int) (int64, error) { + switch whence { + default: + return 0, errors.New("Seek: invalid whence") + case io.SeekStart: + offset += 0 + case io.SeekCurrent: + offset += a.Offset + case io.SeekEnd: + offset += a.Size + } + if offset < 0 { + return 0, errors.New("Seek: invalid offset") + } + a.Offset = offset + return offset, nil +} + +func (a *azureBlobObject) Stat() (os.FileInfo, error) { + return &azureBlobFileInfo{ + a.Name, + a.Size, + *a.ModTime, + }, nil +} + +// AzureStorage returns a azure blob storage +type AzureBlobStorage struct { + cfg *setting.AzureBlobStorageConfig + ctx context.Context + client *azblob.Client + container string + basePath string +} + +func convertAzureBlobErr(err error) error { + if err == nil { + return nil + } + + if bloberror.HasCode(err, bloberror.BlobNotFound) { + return os.ErrNotExist + } + var respErr *azcore.ResponseError + if !errors.As(err, &respErr) { + return nil + } + return fmt.Errorf(respErr.ErrorCode) +} + +// NewAzureBlobStorage returns a azure blob storage +func NewAzureBlobStorage(ctx context.Context, cfg *setting.Storage) (ObjectStorage, error) { + config := cfg.AzureBlobConfig + + log.Info("Creating Azure Blob storage at %s:%s with base path %s", config.Endpoint, config.Container, config.BasePath) + + cred, err := azblob.NewSharedKeyCredential(config.AccountName, config.AccountKey) + if err != nil { + return nil, convertAzureBlobErr(err) + } + client, err := azblob.NewClientWithSharedKeyCredential(config.Endpoint, cred, &azblob.ClientOptions{}) + if err != nil { + return nil, convertAzureBlobErr(err) + } + + _, err = client.CreateContainer(ctx, config.Container, &container.CreateOptions{}) + if err != nil { + // Check to see if we already own this container (which happens if you run this twice) + if !bloberror.HasCode(err, bloberror.ContainerAlreadyExists) { + return nil, convertMinioErr(err) + } + } + + return &AzureBlobStorage{ + cfg: &config, + ctx: ctx, + client: client, + container: config.Container, + basePath: config.BasePath, + }, nil +} + +func (a *AzureBlobStorage) buildAzureBlobPath(p string) string { + p = util.PathJoinRelX(a.basePath, p) + if p == "." || p == "/" { + p = "" // azure uses prefix, so path should be empty as relative path + } + return p +} + +func (a *AzureBlobStorage) getObjectNameFromPath(path string) string { + s := strings.Split(path, "/") + return s[len(s)-1] +} + +// Open opens a file +func (a *AzureBlobStorage) Open(path string) (Object, error) { + blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + res, err := blobClient.GetProperties(a.ctx, &blob.GetPropertiesOptions{}) + if err != nil { + return nil, convertAzureBlobErr(err) + } + return &azureBlobObject{ + Context: &a.ctx, + BlobClient: blobClient, + Name: a.getObjectNameFromPath(path), + Size: *res.ContentLength, + ModTime: res.LastModified, + }, nil +} + +// Save saves a file to azure blob storage +func (a *AzureBlobStorage) Save(path string, r io.Reader, size int64) (int64, error) { + _, err := a.client.UploadStream( + a.ctx, + a.container, + a.buildAzureBlobPath(path), + r, + &blockblob.UploadStreamOptions{}, + ) + if err != nil { + return 0, convertAzureBlobErr(err) + } + return size, nil +} + +type azureBlobFileInfo struct { + name string + size int64 + modTime time.Time +} + +func (a azureBlobFileInfo) Name() string { + return path.Base(a.name) +} + +func (a azureBlobFileInfo) Size() int64 { + return a.size +} + +func (a azureBlobFileInfo) ModTime() time.Time { + return a.modTime +} + +func (a azureBlobFileInfo) IsDir() bool { + return strings.HasSuffix(a.name, "/") +} + +func (a azureBlobFileInfo) Mode() os.FileMode { + return os.ModePerm +} + +func (a azureBlobFileInfo) Sys() interface{} { + return nil +} + +// Stat returns the stat information of the object +func (a *AzureBlobStorage) Stat(path string) (os.FileInfo, error) { + blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + res, err := blobClient.GetProperties(a.ctx, &blob.GetPropertiesOptions{}) + if err != nil { + return nil, convertAzureBlobErr(err) + } + s := strings.Split(path, "/") + return &azureBlobFileInfo{ + s[len(s)-1], + *res.ContentLength, + *res.LastModified, + }, nil +} + +// Delete delete a file +func (a *AzureBlobStorage) Delete(path string) error { + blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + _, err := blobClient.Delete(a.ctx, &blob.DeleteOptions{}) + return convertAzureBlobErr(err) +} + +// URL gets the redirect URL to a file. The presigned link is valid for 5 minutes. +func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { + return nil, ErrURLNotSupported +} + +// IterateObjects iterates across the objects in the azureblobstorage +func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, obj Object) error) error { + dirName = a.buildAzureBlobPath(dirName) + if dirName != "" { + dirName = dirName + "/" + } + pager := a.client.NewListBlobsFlatPager(a.container, &container.ListBlobsFlatOptions{ + Prefix: &dirName, + }) + for pager.More() { + resp, err := pager.NextPage(a.ctx) + if err != nil { + return convertAzureBlobErr(err) + } + for _, object := range resp.Segment.BlobItems { + fullPath := a.buildAzureBlobPath(*object.Name) + blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(fullPath) + object := &azureBlobObject{ + Context: &a.ctx, + BlobClient: blobClient, + Name: fullPath, + Size: *object.Properties.ContentLength, + ModTime: object.Properties.LastModified, + } + if err := func(object *azureBlobObject, fn func(path string, obj Object) error) error { + defer object.Close() + return fn(strings.TrimPrefix(object.Name, a.basePath), object) + }(object, fn); err != nil { + return convertAzureBlobErr(err) + } + } + } + return nil +} + +func init() { + RegisterStorageType(setting.AzureBlobStorageType, NewAzureBlobStorage) +} diff --git a/modules/storage/azure_test.go b/modules/storage/azure_test.go new file mode 100644 index 0000000000000..73436f3199e04 --- /dev/null +++ b/modules/storage/azure_test.go @@ -0,0 +1,26 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package storage + +import ( + "os" + "testing" + + "code.gitea.io/gitea/modules/setting" +) + +func TestAzureBlobStorageIterator(t *testing.T) { + if os.Getenv("CI") == "" { + t.Skip("azureBlobStorage not present outside of CI") + return + } + testStorageIterator(t, setting.AzureBlobStorageType, &setting.Storage{ + AzureBlobConfig: setting.AzureBlobStorageConfig{ + Endpoint: "https://.blob.core.windows.net/", + AccountName: "", + AccountKey: "", + Container: "test", + }, + }) +} diff --git a/modules/storage/storage_test.go b/modules/storage/storage_test.go index 5e3e9c7dba937..7edde558f3042 100644 --- a/modules/storage/storage_test.go +++ b/modules/storage/storage_test.go @@ -35,6 +35,7 @@ func testStorageIterator(t *testing.T, typStr Type, cfg *setting.Storage) { "b": {"b/1.txt", "b/2.txt", "b/3.txt", "b/x 4.txt"}, "": {"a/1.txt", "b/1.txt", "b/2.txt", "b/3.txt", "b/x 4.txt", "ab/1.txt"}, "/": {"a/1.txt", "b/1.txt", "b/2.txt", "b/3.txt", "b/x 4.txt", "ab/1.txt"}, + ".": {"a/1.txt", "b/1.txt", "b/2.txt", "b/3.txt", "b/x 4.txt", "ab/1.txt"}, "a/b/../../a": {"a/1.txt"}, } for dir, expected := range expectedList { From fce996a27af7005d794e09d129cb23b1b84380b7 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 23 Jun 2023 04:18:50 +0000 Subject: [PATCH 02/39] fix lint --- modules/storage/azure.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/storage/azure.go b/modules/storage/azure.go index c972656887f7c..25118094bfb58 100644 --- a/modules/storage/azure.go +++ b/modules/storage/azure.go @@ -269,7 +269,7 @@ func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, obj Object) error) error { dirName = a.buildAzureBlobPath(dirName) if dirName != "" { - dirName = dirName + "/" + dirName += "/" } pager := a.client.NewListBlobsFlatPager(a.container, &container.ListBlobsFlatOptions{ Prefix: &dirName, From efc0ed7114c9067db57cff79b5f5960c8a86872d Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 23 Jun 2023 05:25:56 +0000 Subject: [PATCH 03/39] add ci test --- .devcontainer/devcontainer.json | 3 ++- .github/workflows/pull-db-tests.yml | 4 ++++ modules/storage/azure_test.go | 8 +++++--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 6288e4d367c60..a0d918aaca4f8 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -20,7 +20,8 @@ "Vue.volar", "ms-azuretools.vscode-docker", "zixuanchen.vitest-explorer", - "alexcvzz.vscode-sqlite" + "alexcvzz.vscode-sqlite", + "Azurite.azurite" ] } }, diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 12e5e64e80763..9d8e85dc7534a 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -121,6 +121,10 @@ jobs: MINIO_SECRET_KEY: 12345678 ports: - "9000:9000" + azurite: + image: mcr.microsoft.com/azure-storage/azurite + ports: + - "10000:10000" steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v4 diff --git a/modules/storage/azure_test.go b/modules/storage/azure_test.go index 73436f3199e04..99d0fa5994ab8 100644 --- a/modules/storage/azure_test.go +++ b/modules/storage/azure_test.go @@ -17,9 +17,11 @@ func TestAzureBlobStorageIterator(t *testing.T) { } testStorageIterator(t, setting.AzureBlobStorageType, &setting.Storage{ AzureBlobConfig: setting.AzureBlobStorageConfig{ - Endpoint: "https://.blob.core.windows.net/", - AccountName: "", - AccountKey: "", + // https://learn.microsoft.com/ja-jp/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#ip-style-url + Endpoint: "http://127.0.0.1:10000/devstoreaccount1/", + // https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#well-known-storage-account-and-key + AccountName: "devstoreaccount1", + AccountKey: "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==", Container: "test", }, }) From 888cfa5fa47190429f9090acb40447a30efcbb64 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 23 Jun 2023 05:45:49 +0000 Subject: [PATCH 04/39] fix url --- modules/storage/azure_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/storage/azure_test.go b/modules/storage/azure_test.go index 99d0fa5994ab8..241664f4b53f8 100644 --- a/modules/storage/azure_test.go +++ b/modules/storage/azure_test.go @@ -17,7 +17,7 @@ func TestAzureBlobStorageIterator(t *testing.T) { } testStorageIterator(t, setting.AzureBlobStorageType, &setting.Storage{ AzureBlobConfig: setting.AzureBlobStorageConfig{ - // https://learn.microsoft.com/ja-jp/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#ip-style-url + // https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#ip-style-url Endpoint: "http://127.0.0.1:10000/devstoreaccount1/", // https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#well-known-storage-account-and-key AccountName: "devstoreaccount1", From ab798ecb277389162bf9b8f968050982e505a0c2 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Thu, 6 Jul 2023 05:43:42 +0000 Subject: [PATCH 05/39] remove --- modules/storage/azure.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/modules/storage/azure.go b/modules/storage/azure.go index 25118094bfb58..c270c58968adf 100644 --- a/modules/storage/azure.go +++ b/modules/storage/azure.go @@ -40,13 +40,6 @@ type azureBlobObject struct { } func (a *azureBlobObject) downloadStream(p []byte) (int, error) { - if a.BlobClient == nil { - return 0, fmt.Errorf("no blob client in azure blob object") - } - if a.Context == nil { - return 0, fmt.Errorf("no context in azure blob object") - } - if a.Offset > a.Size { return 0, io.EOF } From 48d98e72b21becf5f5695cc68a0ba61c866f5b21 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Thu, 6 Jul 2023 05:45:17 +0000 Subject: [PATCH 06/39] add todo --- modules/storage/azure.go | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/storage/azure.go b/modules/storage/azure.go index c270c58968adf..2f358c7458517 100644 --- a/modules/storage/azure.go +++ b/modules/storage/azure.go @@ -255,6 +255,7 @@ func (a *AzureBlobStorage) Delete(path string) error { // URL gets the redirect URL to a file. The presigned link is valid for 5 minutes. func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { + // TODO: Support download blobs directly from azure return nil, ErrURLNotSupported } From 2c0036876a1861aced4fc8929c67dd964f2b83b1 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 17 Nov 2023 02:23:20 +0000 Subject: [PATCH 07/39] update azure sdk --- go.mod | 6 +++--- go.sum | 26 +++++++++++++++----------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/go.mod b/go.mod index 0298a7eea142d..d150e139feb64 100644 --- a/go.mod +++ b/go.mod @@ -14,8 +14,8 @@ require ( gitea.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96 gitea.com/lunny/levelqueue v0.4.2-0.20230414023320-3c0159fe0fe4 github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121 - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.0 - github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.0.0 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.0 + github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0 github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 github.com/NYTimes/gziphandler v1.1.1 github.com/PuerkitoBio/goquery v1.8.1 @@ -131,7 +131,7 @@ require ( cloud.google.com/go/compute/metadata v0.2.3 // indirect dario.cat/mergo v1.0.0 // indirect git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect - github.com/Azure/azure-sdk-for-go/sdk/internal v1.1.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 // indirect github.com/ClickHouse/ch-go v0.58.2 // indirect github.com/ClickHouse/clickhouse-go/v2 v2.14.3 // indirect github.com/DataDog/zstd v1.5.5 // indirect diff --git a/go.sum b/go.sum index c5c5daf677452..809a76d167e32 100644 --- a/go.sum +++ b/go.sum @@ -76,19 +76,22 @@ github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121/go.mod h1:Ock8XgA7pvU github.com/6543/go-version v1.3.1 h1:HvOp+Telns7HWJ2Xo/05YXQSB2bE0WmVgbHqwMPZT4U= github.com/6543/go-version v1.3.1/go.mod h1:oqFAHCwtLVUTLdhQmVZWYvaHXTdsbB4SY85at64SQEo= github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.0 h1:VuHAcMq8pU1IWNT/m5yRaGqbK0BiQKHT8X4DTp9CHdI= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.0/go.mod h1:tZoQYdDZNOiIjdSn0dVWVfl0NEPGOJqVLzSrcFk4Is0= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.0 h1:8q4SaHjFsClSvuVne0ID/5Ka8u3fcIHyqkLjcFpNRHQ= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.0/go.mod h1:bjGvMhVMb+EEm3VRNQawDMUyMMjo+S5ewNjflkep/0Q= github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0/go.mod h1:HcM1YX14R7CJcghJGOYCgdezslRSVzqwLf/q+4Y2r/0= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.1.0 h1:QkAcEIAKbNL4KoFr4SathZPhDhF4mVwpBMFlYjyAqy8= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0 h1:vcYCAze6p19qBW7MhZybIsqD8sMV8js0NyQM8JDnVtg= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0/go.mod h1:OQeznEEkTZ9OrhHJoDD8ZDq51FHgXjqtP9z6bEwBq9U= github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.1.1 h1:Oj853U9kG+RLTCQXpjvOnrv0WaZHxgmZz1TlLywgOPY= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.1.1/go.mod h1:eWRD7oawr1Mu1sLCawqVc0CUiF43ia3qQMxLscsKQ9w= -github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.0.0 h1:u/LLAOFgsMv7HmNL4Qufg58y+qElGOt5qv0z1mURkRY= -github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.0.0/go.mod h1:2e8rMJtl2+2j+HXbTBwnyGpm5Nou7KhvSfxOq8JpTag= -github.com/Azure/go-ntlmssp v0.0.0-20220621081337-cb9428e4ac1e/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 h1:sXr+ck84g/ZlZUOZiNELInmMgOsuGwdjjVkEIde0OtY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0 h1:Ma67P/GGprNwsslzEH6+Kb8nybI8jpDTm4Wmzu2ReK8= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0/go.mod h1:c+Lifp3EDEamAkPVzMooRNOK6CZjNSdEnf1A7jsI9u4= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0 h1:gggzg0SUMs6SQbEw+3LoSsYf9YMjkupeAnHMX8O9mmY= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0/go.mod h1:+6KLcKIVgxoBDMqMO/Nvy7bZ9a0nbU3I1DtFQK3YvB4= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= -github.com/AzureAD/microsoft-authentication-library-for-go v0.5.1 h1:BWe8a+f/t+7KY7zH2mqygeUD0t8hNFXe08p1Pb3/jKE= +github.com/AzureAD/microsoft-authentication-library-for-go v1.0.0 h1:OBhqkivkhkMqLPymWEppkm7vgPQY2XsHoEkaMQ0AdZY= +github.com/AzureAD/microsoft-authentication-library-for-go v1.0.0/go.mod h1:kgDmCTgBzIEPFElEF+FK0SdjAor06dRq2Go927dnQ6o= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ClickHouse/ch-go v0.58.2 h1:jSm2szHbT9MCAB1rJ3WuCJqmGLi5UTjlNu+f530UTS0= @@ -482,7 +485,6 @@ github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f h1:3BSP1Tbs2djlpprl7w github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14= github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85 h1:UjoPNDAQ5JPCjlxoJd6K8ALZqSDDhk2ymieAZOVaDg0= github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85/go.mod h1:fR6z1Ie6rtF7kl/vBYMfgD5/G5B1blui7z426/sj2DU= -github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= @@ -742,6 +744,7 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= github.com/lestrrat-go/blackmagic v1.0.0/go.mod h1:TNgH//0vYSs8VXDCfkZLgIrVTTXQELZffUV0tz3MtdQ= github.com/lestrrat-go/httpcc v1.0.0/go.mod h1:tGS/u00Vh5N6FHNkExqGGNId8e0Big+++0Gf8MBnAvE= @@ -889,7 +892,8 @@ github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFu github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= -github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4 h1:Qj1ukM4GlMWXNdMBuXcXfz/Kw9s1qm0CLY32QxuSImI= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= From f45367f9fbd5c1fb6b5f15deafb3be33204d9125 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 17 Nov 2023 02:32:14 +0000 Subject: [PATCH 08/39] update --- modules/setting/storage.go | 46 +++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/modules/setting/storage.go b/modules/setting/storage.go index c4fa6dc5ce2a6..fb40a10046100 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -118,6 +118,8 @@ func getStorage(rootCfg ConfigProvider, name, typ string, sec ConfigSection) (*S return getStorageForLocal(targetSec, overrideSec, tp, name) case string(MinioStorageType): return getStorageForMinio(targetSec, overrideSec, tp, name) + case string(AzureBlobStorageType): + return getStorageForAzureBlob(targetSec, overrideSec, tp, name) default: return nil, fmt.Errorf("unsupported storage type %q", targetType) } @@ -251,22 +253,6 @@ func getStorageForLocal(targetSec, overrideSec ConfigSection, tp targetSecType, storage.Path = filepath.Join(targetPath, storage.Path) } } - case string(AzureBlobStorageType): - storage.AzureBlobConfig.BasePath = name + "/" - - if err := targetSec.MapTo(&storage.AzureBlobConfig); err != nil { - return nil, fmt.Errorf("map azure blob config failed: %v", err) - } - // extra config section will be read SERVE_DIRECT, PATH, MINIO_BASE_PATH to override the targetsec - extraConfigSec := sec - if extraConfigSec == nil { - extraConfigSec = storageNameSec - } - - if extraConfigSec != nil { - storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(extraConfigSec, "AZUREBLOB_BASE_PATH", storage.AzureBlobConfig.BasePath) - storage.AzureBlobConfig.Container = ConfigSectionKeyString(extraConfigSec, "AZUREBLOB_CONTAINER", storage.AzureBlobConfig.Container) - } } return &storage, nil @@ -300,3 +286,31 @@ func getStorageForMinio(targetSec, overrideSec ConfigSection, tp targetSecType, } return &storage, nil } + +func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { + var storage Storage + storage.Type = StorageType(targetSec.Key("STORAGE_TYPE").String()) + if err := targetSec.MapTo(&storage.AzureBlobConfig); err != nil { + return nil, fmt.Errorf("map azure blob config failed: %v", err) + } + + var defaultPath string + if storage.AzureBlobConfig.BasePath != "" { + if tp == targetSecIsStorage || tp == targetSecIsDefault { + defaultPath = strings.TrimSuffix(storage.AzureBlobConfig.BasePath, "/") + "/" + name + "/" + } else { + defaultPath = storage.AzureBlobConfig.BasePath + } + } + if defaultPath == "" { + defaultPath = name + "/" + } + + if overrideSec != nil { + storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(overrideSec, "AZUREBLOB_BASE_PATH", storage.AzureBlobConfig.BasePath) + storage.AzureBlobConfig.Container = ConfigSectionKeyString(overrideSec, "AZUREBLOB_CONTAINER", storage.AzureBlobConfig.Container) + } else { + storage.AzureBlobConfig.BasePath = defaultPath + } + return &storage, nil +} From e03829f0d2f93f3375378328665a9f7c47590b22 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 17 Nov 2023 02:41:26 +0000 Subject: [PATCH 09/39] rename to azureblob --- modules/storage/{azure.go => azureblob.go} | 0 modules/storage/{azure_test.go => azureblob_test.go} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename modules/storage/{azure.go => azureblob.go} (100%) rename modules/storage/{azure_test.go => azureblob_test.go} (100%) diff --git a/modules/storage/azure.go b/modules/storage/azureblob.go similarity index 100% rename from modules/storage/azure.go rename to modules/storage/azureblob.go diff --git a/modules/storage/azure_test.go b/modules/storage/azureblob_test.go similarity index 100% rename from modules/storage/azure_test.go rename to modules/storage/azureblob_test.go From 5ade5261d672e867569b170054af4f93e763239c Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 17 Nov 2023 07:11:32 +0000 Subject: [PATCH 10/39] support direct url for azure blob --- custom/conf/app.example.ini | 37 +++++++++++++++++++++++++++--------- modules/setting/storage.go | 20 ++++++++++++------- modules/storage/azureblob.go | 12 ++++++++++-- routers/web/repo/download.go | 5 +++-- 4 files changed, 54 insertions(+), 20 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index 2217ff2bf0d4e..3c5cfccf784ae 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -1832,7 +1832,7 @@ LEVEL = Info ;STORAGE_TYPE = local ;; ;; Allows the storage driver to redirect to authenticated URLs to serve files directly -;; Currently, only `minio` is supported. +;; Currently, only `minio` and `azureblob` is supported. ;SERVE_DIRECT = false ;; ;; Path for attachments. Defaults to `attachments`. Only available when STORAGE_TYPE is `local` @@ -1865,10 +1865,21 @@ LEVEL = Info ;; ;; Minio checksum algorithm: default (for MinIO or AWS S3) or md5 (for Cloudflare or Backblaze) ;MINIO_CHECKSUM_ALGORITHM = default +;; +;; Azure Blob endpoint to connect only available when STORAGE_TYPE is `azureblob` +;AZURE_BLOB_ENDPOINT = +;; +;; Azure Blob account name to connect only available when STORAGE_TYPE is `azureblob` +;AZURE_BLOB_ACCOUNT_NAME = +;; +;; Azure Blob account key to connect only available when STORAGE_TYPE is `azureblob` +;AZURE_BLOB_ACCOUNT_KEY = +;; +;; Azure Blob container to store the attachments only available when STORAGE_TYPE is `azureblob` +;AZURE_BLOB_CONTAINER = gitea +;; ;; override the azure blob base path if storage type is azureblob ;AZURE_BLOB_BASE_PATH = attachments/ -;; override the azure blob base path if storage type is azureblob -;AZURE_BLOB_CONTAINER = attachments/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -2433,6 +2444,9 @@ LEVEL = Info ;MINIO_BASE_PATH = packages/ ;; override the azure blob base path if storage type is azureblob ;AZURE_BLOB_BASE_PATH = packages/ +;; Allows the storage driver to redirect to authenticated URLs to serve files directly +;; Currently, only `minio` and `azureblob` is supported. +;SERVE_DIRECT = false ;; ;; Path for chunked uploads. Defaults to APP_DATA_PATH + `tmp/package-upload` ;CHUNKED_UPLOAD_PATH = tmp/package-upload @@ -2529,8 +2543,13 @@ LEVEL = Info ;; Where your lfs files reside, default is data/lfs. ;PATH = data/lfs ;; +;; Allows the storage driver to redirect to authenticated URLs to serve files directly +;; Currently, only `minio` and `azureblob` is supported. +;SERVE_DIRECT = false +;; ;; override the minio base path if storage type is minio ;MINIO_BASE_PATH = lfs/ +;; ;; override the azure blob base path if storage type is azureblob ;AZURE_BLOB_BASE_PATH = lfs/ @@ -2547,7 +2566,7 @@ LEVEL = Info ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; customize storage -;[storage.my_minio] +;[storage.minio] ;STORAGE_TYPE = minio ;; ;; Minio endpoint to connect only available when STORAGE_TYPE is `minio` @@ -2572,19 +2591,19 @@ LEVEL = Info ;MINIO_INSECURE_SKIP_VERIFY = false ;[storage.azureblob] -;STORAGE_TYPE=azureblob +;STORAGE_TYPE = azureblob ;; ;; Azure Blob endpoint to connect only available when STORAGE_TYPE is `azureblob` -;AZUREBLOB_ENDPOINT = https://.blob.core.windows.net/ +;AZURE_BLOB_ENDPOINT = ;; ;; Azure Blob account name to connect only available when STORAGE_TYPE is `azureblob` -;AZUREBLOB_ACCOUNT_NAME = +;AZURE_BLOB_ACCOUNT_NAME = ;; ;; Azure Blob account key to connect only available when STORAGE_TYPE is `azureblob` -;AZUREBLOB_ACCOUNT_KEY = +;AZURE_BLOB_ACCOUNT_KEY = ;; ;; Azure Blob container to store the attachments only available when STORAGE_TYPE is `azureblob` -;AZUREBLOB_CONTAINER = +;AZURE_BLOB_CONTAINER = gitea ;[proxy] ;; Enable the proxy, all requests to external via HTTP will be affected diff --git a/modules/setting/storage.go b/modules/setting/storage.go index fb40a10046100..d5890be58bcb3 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -54,11 +54,12 @@ type MinioStorageConfig struct { // MinioStorageConfig represents the configuration for a minio storage type AzureBlobStorageConfig struct { - Endpoint string `ini:"AZUREBLOB_ENDPOINT" json:",omitempty"` - AccountName string `ini:"AZUREBLOB_ACCOUNT_NAME" json:",omitempty"` - AccountKey string `ini:"AZUREBLOB_ACCOUNT_KEY" json:",omitempty"` - Container string `ini:"AZUREBLOB_CONTAINER" json:",omitempty"` - BasePath string `ini:"AZUREBLOB_BASE_PATH" json:",omitempty"` + Endpoint string `ini:"AZURE_BLOB_ENDPOINT" json:",omitempty"` + AccountName string `ini:"AZURE_BLOB_ACCOUNT_NAME" json:",omitempty"` + AccountKey string `ini:"AZURE_BLOB_ACCOUNT_KEY" json:",omitempty"` + Container string `ini:"AZURE_BLOB_CONTAINER" json:",omitempty"` + BasePath string `ini:"AZURE_BLOB_BASE_PATH" json:",omitempty"` + ServeDirect bool `ini:"SERVE_DIRECT"` } // Storage represents configuration of storages @@ -95,6 +96,10 @@ func getDefaultStorageSection(rootCfg ConfigProvider) ConfigSection { storageSec.Key("MINIO_USE_SSL").MustBool(false) storageSec.Key("MINIO_INSECURE_SKIP_VERIFY").MustBool(false) storageSec.Key("MINIO_CHECKSUM_ALGORITHM").MustString("default") + storageSec.Key("AZURE_BLOB_ENDPOINT").MustString("") + storageSec.Key("AZURE_BLOB_ACCOUNT_NAME").MustString("") + storageSec.Key("AZURE_BLOB_ACCOUNT_KEY").MustString("") + storageSec.Key("AZURE_BLOB_CONTAINER").MustString("gitea") return storageSec } @@ -307,8 +312,9 @@ func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecTy } if overrideSec != nil { - storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(overrideSec, "AZUREBLOB_BASE_PATH", storage.AzureBlobConfig.BasePath) - storage.AzureBlobConfig.Container = ConfigSectionKeyString(overrideSec, "AZUREBLOB_CONTAINER", storage.AzureBlobConfig.Container) + storage.AzureBlobConfig.ServeDirect = ConfigSectionKeyBool(overrideSec, "SERVE_DIRECT", storage.MinioConfig.ServeDirect) + storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(overrideSec, "AZURE_BLOB_BASE_PATH", storage.AzureBlobConfig.BasePath) + storage.AzureBlobConfig.Container = ConfigSectionKeyString(overrideSec, "AZURE_BLOB_CONTAINER", storage.AzureBlobConfig.Container) } else { storage.AzureBlobConfig.BasePath = defaultPath } diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 2f358c7458517..e3de78a003520 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -25,6 +25,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas" ) var _ ObjectStorage = &AzureBlobStorage{} @@ -255,8 +256,15 @@ func (a *AzureBlobStorage) Delete(path string) error { // URL gets the redirect URL to a file. The presigned link is valid for 5 minutes. func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { - // TODO: Support download blobs directly from azure - return nil, ErrURLNotSupported + blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + perm := sas.BlobPermissions{ + Read: true, + } + u, err := blobClient.GetSASURL(perm, time.Now().Add(5*time.Minute), &blob.GetSASURLOptions{}) + if err != nil { + return nil, err + } + return url.Parse(u) } // IterateObjects iterates across the objects in the azureblobstorage diff --git a/routers/web/repo/download.go b/routers/web/repo/download.go index a9e2e2b2fad77..154f4393af933 100644 --- a/routers/web/repo/download.go +++ b/routers/web/repo/download.go @@ -53,8 +53,9 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified *time.Tim return nil } - if setting.LFS.Storage.MinioConfig.ServeDirect { - // If we have a signed url (S3, object storage), redirect to this directly. + if (setting.LFS.Storage.MinioConfig.ServeDirect && setting.LFS.Storage.Type == setting.MinioStorageType) || + (setting.LFS.Storage.AzureBlobConfig.ServeDirect && setting.LFS.Storage.Type == setting.AzureBlobStorageType) { + // If we have a signed url (S3, object storage, blob storage), redirect to this directly. u, err := storage.LFS.URL(pointer.RelativePath(), blob.Name()) if u != nil && err == nil { ctx.Redirect(u.String()) From 3b49d3092f8ff64ad6b059a848e85470a44ae0c4 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 17 Nov 2023 07:13:37 +0000 Subject: [PATCH 11/39] fix --- modules/setting/storage.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/setting/storage.go b/modules/setting/storage.go index d5890be58bcb3..cd93b1871bc90 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -312,7 +312,7 @@ func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecTy } if overrideSec != nil { - storage.AzureBlobConfig.ServeDirect = ConfigSectionKeyBool(overrideSec, "SERVE_DIRECT", storage.MinioConfig.ServeDirect) + storage.AzureBlobConfig.ServeDirect = ConfigSectionKeyBool(overrideSec, "SERVE_DIRECT", storage.AzureBlobConfig.ServeDirect) storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(overrideSec, "AZURE_BLOB_BASE_PATH", storage.AzureBlobConfig.BasePath) storage.AzureBlobConfig.Container = ConfigSectionKeyString(overrideSec, "AZURE_BLOB_CONTAINER", storage.AzureBlobConfig.Container) } else { From bc275619e829e52665139c3b73c6530673eede46 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Mon, 20 Nov 2023 07:50:22 +0000 Subject: [PATCH 12/39] improve --- modules/storage/azureblob.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index e3de78a003520..39a85519b5798 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -173,7 +173,7 @@ func (a *AzureBlobStorage) getObjectNameFromPath(path string) string { // Open opens a file func (a *AzureBlobStorage) Open(path string) (Object, error) { - blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + blobClient := a.getBlobClient(path) res, err := blobClient.GetProperties(a.ctx, &blob.GetPropertiesOptions{}) if err != nil { return nil, convertAzureBlobErr(err) @@ -234,7 +234,7 @@ func (a azureBlobFileInfo) Sys() interface{} { // Stat returns the stat information of the object func (a *AzureBlobStorage) Stat(path string) (os.FileInfo, error) { - blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + blobClient := a.getBlobClient(path) res, err := blobClient.GetProperties(a.ctx, &blob.GetPropertiesOptions{}) if err != nil { return nil, convertAzureBlobErr(err) @@ -249,14 +249,14 @@ func (a *AzureBlobStorage) Stat(path string) (os.FileInfo, error) { // Delete delete a file func (a *AzureBlobStorage) Delete(path string) error { - blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + blobClient := a.getBlobClient(path) _, err := blobClient.Delete(a.ctx, &blob.DeleteOptions{}) return convertAzureBlobErr(err) } // URL gets the redirect URL to a file. The presigned link is valid for 5 minutes. func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { - blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + blobClient := a.getBlobClient(path) perm := sas.BlobPermissions{ Read: true, } @@ -302,6 +302,11 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o return nil } +// Delete delete a file +func (a *AzureBlobStorage) getBlobClient(path string) *blob.Client { + return a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) +} + func init() { RegisterStorageType(setting.AzureBlobStorageType, NewAzureBlobStorage) } From e43851383f563f5b351c24410eb9ce0a33aaab6c Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Mon, 20 Nov 2023 08:35:04 +0000 Subject: [PATCH 13/39] imporve --- modules/storage/azureblob.go | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 39a85519b5798..c5145b0707861 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -104,11 +104,12 @@ func (a *azureBlobObject) Stat() (os.FileInfo, error) { // AzureStorage returns a azure blob storage type AzureBlobStorage struct { - cfg *setting.AzureBlobStorageConfig - ctx context.Context - client *azblob.Client - container string - basePath string + cfg *setting.AzureBlobStorageConfig + ctx context.Context + client *azblob.Client + containerClient *container.Client + container string + basePath string } func convertAzureBlobErr(err error) error { @@ -150,11 +151,12 @@ func NewAzureBlobStorage(ctx context.Context, cfg *setting.Storage) (ObjectStora } return &AzureBlobStorage{ - cfg: &config, - ctx: ctx, - client: client, - container: config.Container, - basePath: config.BasePath, + cfg: &config, + ctx: ctx, + client: client, + containerClient: client.ServiceClient().NewContainerClient(config.Container), + container: config.Container, + basePath: config.BasePath, }, nil } @@ -194,6 +196,7 @@ func (a *AzureBlobStorage) Save(path string, r io.Reader, size int64) (int64, er a.container, a.buildAzureBlobPath(path), r, + // TODO: support set block size and concurrency &blockblob.UploadStreamOptions{}, ) if err != nil { @@ -250,7 +253,7 @@ func (a *AzureBlobStorage) Stat(path string) (os.FileInfo, error) { // Delete delete a file func (a *AzureBlobStorage) Delete(path string) error { blobClient := a.getBlobClient(path) - _, err := blobClient.Delete(a.ctx, &blob.DeleteOptions{}) + _, err := blobClient.Delete(a.ctx, nil) return convertAzureBlobErr(err) } @@ -260,7 +263,7 @@ func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { perm := sas.BlobPermissions{ Read: true, } - u, err := blobClient.GetSASURL(perm, time.Now().Add(5*time.Minute), &blob.GetSASURLOptions{}) + u, err := blobClient.GetSASURL(perm, time.Now().Add(5*time.Minute), nil) if err != nil { return nil, err } @@ -282,12 +285,11 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o return convertAzureBlobErr(err) } for _, object := range resp.Segment.BlobItems { - fullPath := a.buildAzureBlobPath(*object.Name) - blobClient := a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(fullPath) + blobClient := a.getBlobClient(*object.Name) object := &azureBlobObject{ Context: &a.ctx, BlobClient: blobClient, - Name: fullPath, + Name: *object.Name, Size: *object.Properties.ContentLength, ModTime: object.Properties.LastModified, } @@ -304,7 +306,7 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o // Delete delete a file func (a *AzureBlobStorage) getBlobClient(path string) *blob.Client { - return a.client.ServiceClient().NewContainerClient(a.container).NewBlobClient(a.buildAzureBlobPath(path)) + return a.containerClient.NewBlobClient(a.buildAzureBlobPath(path)) } func init() { From 8e007dcac44b3699aefc5e19f3443d4706cb210c Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 24 Nov 2023 00:36:29 +0000 Subject: [PATCH 14/39] improve azure blob url --- modules/storage/azureblob.go | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index c5145b0707861..d86dd0b7f379f 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -106,10 +106,9 @@ func (a *azureBlobObject) Stat() (os.FileInfo, error) { type AzureBlobStorage struct { cfg *setting.AzureBlobStorageConfig ctx context.Context + credential *azblob.SharedKeyCredential client *azblob.Client containerClient *container.Client - container string - basePath string } func convertAzureBlobErr(err error) error { @@ -153,15 +152,14 @@ func NewAzureBlobStorage(ctx context.Context, cfg *setting.Storage) (ObjectStora return &AzureBlobStorage{ cfg: &config, ctx: ctx, + credential: cred, client: client, containerClient: client.ServiceClient().NewContainerClient(config.Container), - container: config.Container, - basePath: config.BasePath, }, nil } func (a *AzureBlobStorage) buildAzureBlobPath(p string) string { - p = util.PathJoinRelX(a.basePath, p) + p = util.PathJoinRelX(a.cfg.BasePath, p) if p == "." || p == "/" { p = "" // azure uses prefix, so path should be empty as relative path } @@ -193,7 +191,7 @@ func (a *AzureBlobStorage) Open(path string) (Object, error) { func (a *AzureBlobStorage) Save(path string, r io.Reader, size int64) (int64, error) { _, err := a.client.UploadStream( a.ctx, - a.container, + a.cfg.Container, a.buildAzureBlobPath(path), r, // TODO: support set block size and concurrency @@ -260,14 +258,23 @@ func (a *AzureBlobStorage) Delete(path string) error { // URL gets the redirect URL to a file. The presigned link is valid for 5 minutes. func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { blobClient := a.getBlobClient(path) - perm := sas.BlobPermissions{ - Read: true, - } - u, err := blobClient.GetSASURL(perm, time.Now().Add(5*time.Minute), nil) + + // GetSASURL is a generic method built for common use cases. We need to implement it by ourselves + startTime := time.Now() + expiryTime := startTime.Add(5 * time.Minute) + qps, err := sas.BlobSignatureValues{ + ContainerName: a.cfg.Container, + BlobName: a.buildAzureBlobPath(path), + Version: sas.Version, + Permissions: (&sas.BlobPermissions{Read: true}).String(), + StartTime: startTime.UTC(), + ExpiryTime: expiryTime.UTC(), + ContentDisposition: "attachment; filename=\"" + quoteEscaper.Replace(name) + "\"", + }.SignWithSharedKey(a.credential) if err != nil { return nil, err } - return url.Parse(u) + return url.Parse(blobClient.URL() + "?" + qps.Encode()) } // IterateObjects iterates across the objects in the azureblobstorage @@ -276,7 +283,7 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o if dirName != "" { dirName += "/" } - pager := a.client.NewListBlobsFlatPager(a.container, &container.ListBlobsFlatOptions{ + pager := a.client.NewListBlobsFlatPager(a.cfg.Container, &container.ListBlobsFlatOptions{ Prefix: &dirName, }) for pager.More() { @@ -295,7 +302,7 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o } if err := func(object *azureBlobObject, fn func(path string, obj Object) error) error { defer object.Close() - return fn(strings.TrimPrefix(object.Name, a.basePath), object) + return fn(strings.TrimPrefix(object.Name, a.cfg.BasePath), object) }(object, fn); err != nil { return convertAzureBlobErr(err) } From 5faecb9d833522fac4bb0db44c5aeaef69ca81f6 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 24 Nov 2023 02:59:17 +0000 Subject: [PATCH 15/39] add path test --- modules/storage/azureblob_test.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/modules/storage/azureblob_test.go b/modules/storage/azureblob_test.go index 241664f4b53f8..782f074ab9baa 100644 --- a/modules/storage/azureblob_test.go +++ b/modules/storage/azureblob_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/modules/setting" + "github.com/stretchr/testify/assert" ) func TestAzureBlobStorageIterator(t *testing.T) { @@ -26,3 +27,29 @@ func TestAzureBlobStorageIterator(t *testing.T) { }, }) } + +func TestAzureBlobStoragePath(t *testing.T) { + m := &AzureBlobStorage{cfg: &setting.AzureBlobStorageConfig{BasePath: ""}} + assert.Equal(t, "", m.buildAzureBlobPath("/")) + assert.Equal(t, "", m.buildAzureBlobPath(".")) + assert.Equal(t, "a", m.buildAzureBlobPath("/a")) + assert.Equal(t, "a/b", m.buildAzureBlobPath("/a/b/")) + + m = &AzureBlobStorage{cfg: &setting.AzureBlobStorageConfig{BasePath: "/"}} + assert.Equal(t, "", m.buildAzureBlobPath("/")) + assert.Equal(t, "", m.buildAzureBlobPath(".")) + assert.Equal(t, "a", m.buildAzureBlobPath("/a")) + assert.Equal(t, "a/b", m.buildAzureBlobPath("/a/b/")) + + m = &AzureBlobStorage{cfg: &setting.AzureBlobStorageConfig{BasePath: "/base"}} + assert.Equal(t, "base", m.buildAzureBlobPath("/")) + assert.Equal(t, "base", m.buildAzureBlobPath(".")) + assert.Equal(t, "base/a", m.buildAzureBlobPath("/a")) + assert.Equal(t, "base/a/b", m.buildAzureBlobPath("/a/b/")) + + m = &AzureBlobStorage{cfg: &setting.AzureBlobStorageConfig{BasePath: "/base/"}} + assert.Equal(t, "base", m.buildAzureBlobPath("/")) + assert.Equal(t, "base", m.buildAzureBlobPath(".")) + assert.Equal(t, "base/a", m.buildAzureBlobPath("/a")) + assert.Equal(t, "base/a/b", m.buildAzureBlobPath("/a/b/")) +} From f7e42d272920ca6ea40d774af0f953fc485d188e Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Fri, 24 Nov 2023 08:57:15 +0000 Subject: [PATCH 16/39] fix lint --- modules/storage/azureblob_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/storage/azureblob_test.go b/modules/storage/azureblob_test.go index 782f074ab9baa..e0198ab074640 100644 --- a/modules/storage/azureblob_test.go +++ b/modules/storage/azureblob_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/modules/setting" + "github.com/stretchr/testify/assert" ) From 14a194c7dfabb6c5d811175973e852f19645196b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 2 May 2024 13:43:08 +0800 Subject: [PATCH 17/39] Add some tests for configuration of azure blob storage support --- cmd/migrate_storage.go | 41 ++++++- modules/setting/storage.go | 2 +- modules/setting/storage_test.go | 112 ++++++++++++++++++ modules/storage/azureblob.go | 4 +- .../integration/api_packages_generic_test.go | 27 +++-- 5 files changed, 174 insertions(+), 12 deletions(-) diff --git a/cmd/migrate_storage.go b/cmd/migrate_storage.go index aa49445a89e81..33557a645496f 100644 --- a/cmd/migrate_storage.go +++ b/cmd/migrate_storage.go @@ -40,7 +40,7 @@ var CmdMigrateStorage = &cli.Command{ Name: "storage", Aliases: []string{"s"}, Value: "", - Usage: "New storage type: local (default) or minio", + Usage: "New storage type: local (default), minio or azureblob", }, &cli.StringFlag{ Name: "path", @@ -48,6 +48,7 @@ var CmdMigrateStorage = &cli.Command{ Value: "", Usage: "New storage placement if store is local (leave blank for default)", }, + // Minio Storage special configurations &cli.StringFlag{ Name: "minio-endpoint", Value: "", @@ -91,6 +92,32 @@ var CmdMigrateStorage = &cli.Command{ Value: "", Usage: "Minio checksum algorithm (default/md5)", }, + // Azure Blob Storage special configurations + &cli.StringFlag{ + Name: "azureblob-endpoint", + Value: "", + Usage: "Azure Blob storage endpoint", + }, + &cli.StringFlag{ + Name: "azureblob-account-name", + Value: "", + Usage: "Azure Blob storage account name", + }, + &cli.StringFlag{ + Name: "azureblob-account-key", + Value: "", + Usage: "Azure Blob storage account key", + }, + &cli.StringFlag{ + Name: "azureblob-container", + Value: "", + Usage: "Azure Blob storage container", + }, + &cli.StringFlag{ + Name: "azureblob-base-path", + Value: "", + Usage: "Azure Blob storage base path", + }, }, } @@ -215,6 +242,18 @@ func runMigrateStorage(ctx *cli.Context) error { ChecksumAlgorithm: ctx.String("minio-checksum-algorithm"), }, }) + case string(setting.AzureBlobStorageType): + dstStorage, err = storage.NewMinioStorage( + stdCtx, + &setting.Storage{ + AzureBlobConfig: setting.AzureBlobStorageConfig{ + Endpoint: ctx.String("azureblob-endpoint"), + AccountName: ctx.String("azureblob-account-name"), + AccountKey: ctx.String("azureblob-account-key"), + Container: ctx.String("azureblob-container"), + BasePath: ctx.String("azureblob-base-path"), + }, + }) default: return fmt.Errorf("unsupported storage type: %s", ctx.String("storage")) } diff --git a/modules/setting/storage.go b/modules/setting/storage.go index a341dc00b9421..792c2904e4141 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -315,7 +315,7 @@ func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecTy if overrideSec != nil { storage.AzureBlobConfig.ServeDirect = ConfigSectionKeyBool(overrideSec, "SERVE_DIRECT", storage.AzureBlobConfig.ServeDirect) - storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(overrideSec, "AZURE_BLOB_BASE_PATH", storage.AzureBlobConfig.BasePath) + storage.AzureBlobConfig.BasePath = ConfigSectionKeyString(overrideSec, "AZURE_BLOB_BASE_PATH", defaultPath) storage.AzureBlobConfig.Container = ConfigSectionKeyString(overrideSec, "AZURE_BLOB_CONTAINER", storage.AzureBlobConfig.Container) } else { storage.AzureBlobConfig.BasePath = defaultPath diff --git a/modules/setting/storage_test.go b/modules/setting/storage_test.go index 6f38bf1d55754..44a5de68265ff 100644 --- a/modules/setting/storage_test.go +++ b/modules/setting/storage_test.go @@ -97,6 +97,44 @@ STORAGE_TYPE = minio assert.EqualValues(t, "repo-avatars/", RepoAvatar.Storage.MinioConfig.BasePath) } +func Test_getStorageInheritStorageTypeAzureBlob(t *testing.T) { + iniStr := ` +[storage] +STORAGE_TYPE = azureblob +` + cfg, err := NewConfigProviderFromData(iniStr) + assert.NoError(t, err) + + assert.NoError(t, loadPackagesFrom(cfg)) + assert.EqualValues(t, "azureblob", Packages.Storage.Type) + assert.EqualValues(t, "gitea", Packages.Storage.AzureBlobConfig.Container) + assert.EqualValues(t, "packages/", Packages.Storage.AzureBlobConfig.BasePath) + + assert.NoError(t, loadRepoArchiveFrom(cfg)) + assert.EqualValues(t, "azureblob", RepoArchive.Storage.Type) + assert.EqualValues(t, "gitea", RepoArchive.Storage.AzureBlobConfig.Container) + assert.EqualValues(t, "repo-archive/", RepoArchive.Storage.AzureBlobConfig.BasePath) + + assert.NoError(t, loadActionsFrom(cfg)) + assert.EqualValues(t, "azureblob", Actions.LogStorage.Type) + assert.EqualValues(t, "gitea", Actions.LogStorage.AzureBlobConfig.Container) + assert.EqualValues(t, "actions_log/", Actions.LogStorage.AzureBlobConfig.BasePath) + + assert.EqualValues(t, "azureblob", Actions.ArtifactStorage.Type) + assert.EqualValues(t, "gitea", Actions.ArtifactStorage.AzureBlobConfig.Container) + assert.EqualValues(t, "actions_artifacts/", Actions.ArtifactStorage.AzureBlobConfig.BasePath) + + assert.NoError(t, loadAvatarsFrom(cfg)) + assert.EqualValues(t, "azureblob", Avatar.Storage.Type) + assert.EqualValues(t, "gitea", Avatar.Storage.AzureBlobConfig.Container) + assert.EqualValues(t, "avatars/", Avatar.Storage.AzureBlobConfig.BasePath) + + assert.NoError(t, loadRepoAvatarFrom(cfg)) + assert.EqualValues(t, "azureblob", RepoAvatar.Storage.Type) + assert.EqualValues(t, "gitea", RepoAvatar.Storage.AzureBlobConfig.Container) + assert.EqualValues(t, "repo-avatars/", RepoAvatar.Storage.AzureBlobConfig.BasePath) +} + type testLocalStoragePathCase struct { loader func(rootCfg ConfigProvider) error storagePtr **Storage @@ -465,3 +503,77 @@ MINIO_BASE_PATH = /lfs assert.EqualValues(t, true, LFS.Storage.MinioConfig.UseSSL) assert.EqualValues(t, "/lfs", LFS.Storage.MinioConfig.BasePath) } + +func Test_getStorageConfiguration29(t *testing.T) { + cfg, err := NewConfigProviderFromData(` +[repo-archive] +STORAGE_TYPE = azureblob +AZURE_BLOB_ACCOUNT_NAME = my_account_name +AZURE_BLOB_ACCOUNT_KEY = my_account_key +`) + assert.NoError(t, err) + // assert.Error(t, loadRepoArchiveFrom(cfg)) + // FIXME: this should return error but now ini package's MapTo() doesn't check type + assert.NoError(t, loadRepoArchiveFrom(cfg)) +} + +func Test_getStorageConfiguration30(t *testing.T) { + cfg, err := NewConfigProviderFromData(` +[storage.repo-archive] +STORAGE_TYPE = azureblob +AZURE_BLOB_ACCOUNT_NAME = my_account_name +AZURE_BLOB_ACCOUNT_KEY = my_account_key +`) + assert.NoError(t, err) + assert.NoError(t, loadRepoArchiveFrom(cfg)) + assert.EqualValues(t, "my_account_name", RepoArchive.Storage.AzureBlobConfig.AccountName) + assert.EqualValues(t, "my_account_key", RepoArchive.Storage.AzureBlobConfig.AccountKey) + assert.EqualValues(t, "repo-archive/", RepoArchive.Storage.AzureBlobConfig.BasePath) +} + +func Test_getStorageConfiguration31(t *testing.T) { + cfg, err := NewConfigProviderFromData(` +[storage] +STORAGE_TYPE = azureblob +AZURE_BLOB_ACCOUNT_NAME = my_account_name +AZURE_BLOB_ACCOUNT_KEY = my_account_key +AZURE_BLOB_BASE_PATH = /prefix +`) + assert.NoError(t, err) + assert.NoError(t, loadRepoArchiveFrom(cfg)) + assert.EqualValues(t, "my_account_name", RepoArchive.Storage.AzureBlobConfig.AccountName) + assert.EqualValues(t, "my_account_key", RepoArchive.Storage.AzureBlobConfig.AccountKey) + assert.EqualValues(t, "/prefix/repo-archive/", RepoArchive.Storage.AzureBlobConfig.BasePath) + + cfg, err = NewConfigProviderFromData(` +[storage] +STORAGE_TYPE = azureblob +AZURE_BLOB_ACCOUNT_NAME = my_account_name +AZURE_BLOB_ACCOUNT_KEY = my_account_key +AZURE_BLOB_BASE_PATH = /prefix + +[lfs] +AZURE_BLOB_BASE_PATH = /lfs +`) + assert.NoError(t, err) + assert.NoError(t, loadLFSFrom(cfg)) + assert.EqualValues(t, "my_account_name", LFS.Storage.AzureBlobConfig.AccountName) + assert.EqualValues(t, "my_account_key", LFS.Storage.AzureBlobConfig.AccountKey) + assert.EqualValues(t, "/lfs", LFS.Storage.AzureBlobConfig.BasePath) + + cfg, err = NewConfigProviderFromData(` +[storage] +STORAGE_TYPE = azureblob +AZURE_BLOB_ACCOUNT_NAME = my_account_name +AZURE_BLOB_ACCOUNT_KEY = my_account_key +AZURE_BLOB_BASE_PATH = /prefix + +[storage.lfs] +AZURE_BLOB_BASE_PATH = /lfs +`) + assert.NoError(t, err) + assert.NoError(t, loadLFSFrom(cfg)) + assert.EqualValues(t, "my_account_name", LFS.Storage.AzureBlobConfig.AccountName) + assert.EqualValues(t, "my_account_key", LFS.Storage.AzureBlobConfig.AccountKey) + assert.EqualValues(t, "/lfs", LFS.Storage.AzureBlobConfig.BasePath) +} diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index d86dd0b7f379f..6b33d6b16766f 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -28,7 +28,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas" ) -var _ ObjectStorage = &AzureBlobStorage{} +var _ Object = &azureBlobObject{} type azureBlobObject struct { BlobClient *blob.Client @@ -102,6 +102,8 @@ func (a *azureBlobObject) Stat() (os.FileInfo, error) { }, nil } +var _ ObjectStorage = &AzureBlobStorage{} + // AzureStorage returns a azure blob storage type AzureBlobStorage struct { cfg *setting.AzureBlobStorageConfig diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index 1cbae599af56f..8ad9c16dc430b 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -144,18 +144,27 @@ func TestPackageGeneric(t *testing.T) { t.Run("ServeDirect", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - if setting.Packages.Storage.Type != setting.MinioStorageType { - t.Skip("Test skipped for non-Minio-storage.") + if setting.Packages.Storage.Type != setting.MinioStorageType && setting.Packages.Storage.Type != setting.AzureBlobStorageType { + t.Skip("Test skipped for non-Minio-storage and non-AzureBlob-storage.") return } - if !setting.Packages.Storage.MinioConfig.ServeDirect { - old := setting.Packages.Storage.MinioConfig.ServeDirect - defer func() { - setting.Packages.Storage.MinioConfig.ServeDirect = old - }() - - setting.Packages.Storage.MinioConfig.ServeDirect = true + if setting.Packages.Storage.Type == setting.MinioStorageType { + if !setting.Packages.Storage.MinioConfig.ServeDirect { + old := setting.Packages.Storage.MinioConfig.ServeDirect + defer func() { + setting.Packages.Storage.MinioConfig.ServeDirect = old + }() + + setting.Packages.Storage.MinioConfig.ServeDirect = true + } + } else if setting.Packages.Storage.Type == setting.AzureBlobStorageType { + if !setting.Packages.Storage.AzureBlobConfig.ServeDirect { + old := setting.Packages.Storage.AzureBlobConfig.ServeDirect + defer func() { + setting.Packages.Storage.AzureBlobConfig.ServeDirect = old + }() + } } req := NewRequest(t, "GET", url+"/"+filename) From c6e35389c4f438c2ed097ee0bb3dbb34e65c4bd4 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 6 May 2024 17:04:56 +0800 Subject: [PATCH 18/39] upgrade azure blob version --- cmd/migrate_storage.go | 2 +- go.mod | 6 +++--- go.sum | 16 ++++++++-------- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cmd/migrate_storage.go b/cmd/migrate_storage.go index 33557a645496f..915443451bb28 100644 --- a/cmd/migrate_storage.go +++ b/cmd/migrate_storage.go @@ -243,7 +243,7 @@ func runMigrateStorage(ctx *cli.Context) error { }, }) case string(setting.AzureBlobStorageType): - dstStorage, err = storage.NewMinioStorage( + dstStorage, err = storage.NewAzureBlobStorage( stdCtx, &setting.Storage{ AzureBlobConfig: setting.AzureBlobStorageConfig{ diff --git a/go.mod b/go.mod index c009dea277fd3..4535b793ab851 100644 --- a/go.mod +++ b/go.mod @@ -15,8 +15,8 @@ require ( gitea.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96 gitea.com/lunny/levelqueue v0.4.2-0.20230414023320-3c0159fe0fe4 github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121 - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 - github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1 + github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.3.2 github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 github.com/ProtonMail/go-crypto v1.0.0 github.com/PuerkitoBio/goquery v1.9.1 @@ -131,7 +131,7 @@ require ( dario.cat/mergo v1.0.0 // indirect filippo.io/edwards25519 v1.1.0 // indirect git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect - github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 // indirect github.com/ClickHouse/ch-go v0.61.5 // indirect github.com/ClickHouse/clickhouse-go/v2 v2.22.0 // indirect github.com/DataDog/zstd v1.5.5 // indirect diff --git a/go.sum b/go.sum index 0dc688fd7a895..d0e3ff830d255 100644 --- a/go.sum +++ b/go.sum @@ -38,20 +38,20 @@ github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121 h1:r3qt8PCHnfjOv9PN3H github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121/go.mod h1:Ock8XgA7pvULhIaHGAk/cDnRfNrF9Jey81nPcc403iU= github.com/6543/go-version v1.3.1 h1:HvOp+Telns7HWJ2Xo/05YXQSB2bE0WmVgbHqwMPZT4U= github.com/6543/go-version v1.3.1/go.mod h1:oqFAHCwtLVUTLdhQmVZWYvaHXTdsbB4SY85at64SQEo= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 h1:lGlwhPtrX6EVml1hO0ivjkUxsSyl4dsiw9qcA1k/3IQ= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1/go.mod h1:RKUqNu35KJYcVG/fqTRqmuXJZYNhYkBrnC/hX7yGbTA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1 h1:E+OJmp2tPvt1W+amx48v1eqbjDYsgN+RzP4q16yV5eM= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1/go.mod h1:a6xsAQUZg+VsS3TJ05SRp524Hs4pZ/AeFSr5ENf0Yjo= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 h1:sO0/P7g68FrryJzljemN+6GTssUXdANk6aJ7T1ZxnsQ= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1/go.mod h1:h8hyGFDsU5HMivxiS2iYFZsgDbU9OnnJ163x5UGVKYo= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 h1:6oNBlSdi1QqM1PNW7FPA6xOGA5UNsXnkaYZz9vdPGhA= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0 h1:Ma67P/GGprNwsslzEH6+Kb8nybI8jpDTm4Wmzu2ReK8= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0/go.mod h1:c+Lifp3EDEamAkPVzMooRNOK6CZjNSdEnf1A7jsI9u4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 h1:LqbJ/WzJUwBf8UiaSzgX7aMclParm9/5Vgp+TY51uBQ= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0 h1:AifHbc4mg0x9zW52WOpKbsHaDKuRhlI7TVl47thgQ70= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0/go.mod h1:T5RfihdXtBDxt1Ch2wobif3TvzTdumDy29kahv6AV9A= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.1 h1:MyVTgWR8qd/Jw1Le0NZebGBUCLbtak3bJ3z1OlqZBpw= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.1/go.mod h1:GpPjLhVR9dnUoJMyHWSPy71xY9/lcmpzIPZXmF0FCVY= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 h1:D3occbWoio4EBLkbkevetNMAVX197GkzbUMtqjGWn80= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0/go.mod h1:bTSOgj05NGRuHHhQwAdPnYr9TOdNmKlZTgGLL6nyAdI= -github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0 h1:gggzg0SUMs6SQbEw+3LoSsYf9YMjkupeAnHMX8O9mmY= -github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0/go.mod h1:+6KLcKIVgxoBDMqMO/Nvy7bZ9a0nbU3I1DtFQK3YvB4= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.3.2 h1:YUUxeiOWgdAQE3pXt2H7QXzZs0q8UBjgRbl56qo8GYM= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.3.2/go.mod h1:dmXQgZuiSubAecswZE+Sm8jkvEa7kQgTPVRvwL/nd0E= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA= From 95ab4d1c19b576a544ec0d20bee43b961519d40a Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 13 May 2024 14:52:16 +0800 Subject: [PATCH 19/39] Fix download blob --- modules/setting/storage.go | 40 +++++++++++++++++++++++----- modules/storage/azureblob.go | 51 ++++++++++++++++++++++++------------ 2 files changed, 68 insertions(+), 23 deletions(-) diff --git a/modules/setting/storage.go b/modules/setting/storage.go index 792c2904e4141..2282fef65e00a 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -6,8 +6,11 @@ package setting import ( "errors" "fmt" + "net/url" "path/filepath" "strings" + + "code.gitea.io/gitea/modules/log" ) // StorageType is a type of Storage @@ -52,6 +55,15 @@ type MinioStorageConfig struct { ServeDirect bool `ini:"SERVE_DIRECT"` } +func (cfg *MinioStorageConfig) ToShadow() { + if cfg.AccessKeyID != "" { + cfg.AccessKeyID = "******" + } + if cfg.SecretAccessKey != "" { + cfg.SecretAccessKey = "******" + } +} + // MinioStorageConfig represents the configuration for a minio storage type AzureBlobStorageConfig struct { Endpoint string `ini:"AZURE_BLOB_ENDPOINT" json:",omitempty"` @@ -62,6 +74,26 @@ type AzureBlobStorageConfig struct { ServeDirect bool `ini:"SERVE_DIRECT"` } +func (cfg AzureBlobStorageConfig) ConnectionString() string { + u, err := url.Parse(cfg.Endpoint) + if err != nil { + log.Fatal("parse endpoint %s failed: %v", cfg.Endpoint, err) + return "" + } + + return fmt.Sprintf("DefaultEndpointsProtocol=%s;AccountName=%s;AccountKey=%s;EndpointSuffix=%s", + u.Scheme, cfg.AccountName, cfg.AccountKey, u.Host) +} + +func (cfg *AzureBlobStorageConfig) ToShadow() { + if cfg.AccountKey != "" { + cfg.AccountKey = "******" + } + if cfg.AccountName != "" { + cfg.AccountName = "******" + } +} + // Storage represents configuration of storages type Storage struct { Type StorageType // local or minio or azureblob @@ -73,12 +105,8 @@ type Storage struct { func (storage *Storage) ToShadowCopy() Storage { shadowStorage := *storage - if shadowStorage.MinioConfig.AccessKeyID != "" { - shadowStorage.MinioConfig.AccessKeyID = "******" - } - if shadowStorage.MinioConfig.SecretAccessKey != "" { - shadowStorage.MinioConfig.SecretAccessKey = "******" - } + shadowStorage.MinioConfig.ToShadow() + shadowStorage.AzureBlobConfig.ToShadow() return shadowStorage } diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 6b33d6b16766f..95492c7526468 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -4,7 +4,6 @@ package storage import ( - "bytes" "context" "errors" "fmt" @@ -40,7 +39,7 @@ type azureBlobObject struct { Offset int64 } -func (a *azureBlobObject) downloadStream(p []byte) (int, error) { +func (a *azureBlobObject) downloadBuffer(p []byte) (int, error) { if a.Offset > a.Size { return 0, io.EOF } @@ -51,7 +50,7 @@ func (a *azureBlobObject) downloadStream(p []byte) (int, error) { } else { count = pl } - res, err := a.BlobClient.DownloadStream(*a.Context, &blob.DownloadStreamOptions{ + res, err := a.BlobClient.DownloadBuffer(*a.Context, p, &blob.DownloadBufferOptions{ Range: blob.HTTPRange{ Offset: a.Offset, Count: count, @@ -62,9 +61,7 @@ func (a *azureBlobObject) downloadStream(p []byte) (int, error) { } a.Offset += count - buf := bytes.NewBuffer(p) - c, err := io.Copy(buf, res.Body) - return int(c), err + return int(res), nil } func (a *azureBlobObject) Close() error { @@ -72,7 +69,7 @@ func (a *azureBlobObject) Close() error { } func (a *azureBlobObject) Read(p []byte) (int, error) { - c, err := a.downloadStream(p) + c, err := a.downloadBuffer(p) return c, err } @@ -138,7 +135,7 @@ func NewAzureBlobStorage(ctx context.Context, cfg *setting.Storage) (ObjectStora if err != nil { return nil, convertAzureBlobErr(err) } - client, err := azblob.NewClientWithSharedKeyCredential(config.Endpoint, cred, &azblob.ClientOptions{}) + client, err := azblob.NewClientWithSharedKeyCredential(config.Endpoint+"/"+config.AccountName, cred, &azblob.ClientOptions{}) if err != nil { return nil, convertAzureBlobErr(err) } @@ -175,7 +172,10 @@ func (a *AzureBlobStorage) getObjectNameFromPath(path string) string { // Open opens a file func (a *AzureBlobStorage) Open(path string) (Object, error) { - blobClient := a.getBlobClient(path) + blobClient, err := a.getBlobClient(path) + if err != nil { + return nil, convertAzureBlobErr(err) + } res, err := blobClient.GetProperties(a.ctx, &blob.GetPropertiesOptions{}) if err != nil { return nil, convertAzureBlobErr(err) @@ -191,7 +191,11 @@ func (a *AzureBlobStorage) Open(path string) (Object, error) { // Save saves a file to azure blob storage func (a *AzureBlobStorage) Save(path string, r io.Reader, size int64) (int64, error) { - _, err := a.client.UploadStream( + client, err := azblob.NewClientFromConnectionString(a.cfg.ConnectionString(), &azblob.ClientOptions{}) + if err != nil { + return 0, convertAzureBlobErr(err) + } + _, err = client.UploadStream( a.ctx, a.cfg.Container, a.buildAzureBlobPath(path), @@ -237,7 +241,10 @@ func (a azureBlobFileInfo) Sys() interface{} { // Stat returns the stat information of the object func (a *AzureBlobStorage) Stat(path string) (os.FileInfo, error) { - blobClient := a.getBlobClient(path) + blobClient, err := a.getBlobClient(path) + if err != nil { + return nil, convertAzureBlobErr(err) + } res, err := blobClient.GetProperties(a.ctx, &blob.GetPropertiesOptions{}) if err != nil { return nil, convertAzureBlobErr(err) @@ -252,14 +259,20 @@ func (a *AzureBlobStorage) Stat(path string) (os.FileInfo, error) { // Delete delete a file func (a *AzureBlobStorage) Delete(path string) error { - blobClient := a.getBlobClient(path) - _, err := blobClient.Delete(a.ctx, nil) + blobClient, err := a.getBlobClient(path) + if err != nil { + return convertAzureBlobErr(err) + } + _, err = blobClient.Delete(a.ctx, nil) return convertAzureBlobErr(err) } // URL gets the redirect URL to a file. The presigned link is valid for 5 minutes. func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { - blobClient := a.getBlobClient(path) + blobClient, err := a.getBlobClient(path) + if err != nil { + return nil, convertAzureBlobErr(err) + } // GetSASURL is a generic method built for common use cases. We need to implement it by ourselves startTime := time.Now() @@ -294,7 +307,10 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o return convertAzureBlobErr(err) } for _, object := range resp.Segment.BlobItems { - blobClient := a.getBlobClient(*object.Name) + blobClient, err := a.getBlobClient(*object.Name) + if err != nil { + return convertAzureBlobErr(err) + } object := &azureBlobObject{ Context: &a.ctx, BlobClient: blobClient, @@ -314,8 +330,9 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o } // Delete delete a file -func (a *AzureBlobStorage) getBlobClient(path string) *blob.Client { - return a.containerClient.NewBlobClient(a.buildAzureBlobPath(path)) +func (a *AzureBlobStorage) getBlobClient(path string) (*blob.Client, error) { + // blob.NewClient(blobURL string, cred azcore.TokenCredential, options *blob.ClientOptions) + return blob.NewClientFromConnectionString(a.cfg.ConnectionString(), a.cfg.Container, a.buildAzureBlobPath(path), &blob.ClientOptions{}) } func init() { From de67cea09204ee9a9163e872cfdc80eaa0f6845c Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 16 May 2024 17:30:22 +0800 Subject: [PATCH 20/39] Fix bug --- modules/storage/azureblob.go | 88 +++++++++++++++--------------------- 1 file changed, 37 insertions(+), 51 deletions(-) diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 95492c7526468..db45c25aa1a8b 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -30,65 +30,58 @@ import ( var _ Object = &azureBlobObject{} type azureBlobObject struct { - BlobClient *blob.Client - Context *context.Context + blobClient *blob.Client + Context context.Context Name string Size int64 ModTime *time.Time - - Offset int64 + offset int64 } -func (a *azureBlobObject) downloadBuffer(p []byte) (int, error) { - if a.Offset > a.Size { +func (a *azureBlobObject) Read(p []byte) (int, error) { + // TODO: improve the performance, we can implement another interface, maybe implement io.WriteTo + if a.offset >= a.Size { return 0, io.EOF } - count := a.Size - a.Offset - pl := int64(len(p)) - if pl > count { - p = p[0:count] - } else { - count = pl - } - res, err := a.BlobClient.DownloadBuffer(*a.Context, p, &blob.DownloadBufferOptions{ + count := min(int64(len(p)), a.Size-a.offset) + + res, err := a.blobClient.DownloadBuffer(a.Context, p, &blob.DownloadBufferOptions{ Range: blob.HTTPRange{ - Offset: a.Offset, + Offset: a.offset, Count: count, }, }) if err != nil { return 0, convertAzureBlobErr(err) } - a.Offset += count + a.offset += res return int(res), nil } func (a *azureBlobObject) Close() error { + a.offset = 0 return nil } -func (a *azureBlobObject) Read(p []byte) (int, error) { - c, err := a.downloadBuffer(p) - return c, err -} - func (a *azureBlobObject) Seek(offset int64, whence int) (int64, error) { switch whence { - default: - return 0, errors.New("Seek: invalid whence") case io.SeekStart: - offset += 0 + a.offset = offset case io.SeekCurrent: - offset += a.Offset + a.offset += offset case io.SeekEnd: - offset += a.Size + a.offset = a.Size - offset + default: + return 0, errors.New("Seek: invalid whence") } - if offset < 0 { + + if a.offset > a.Size { + return 0, errors.New("Seek: invalid offset") + } else if a.offset < 0 { return 0, errors.New("Seek: invalid offset") } - a.Offset = offset - return offset, nil + return a.offset, nil } func (a *azureBlobObject) Stat() (os.FileInfo, error) { @@ -103,11 +96,10 @@ var _ ObjectStorage = &AzureBlobStorage{} // AzureStorage returns a azure blob storage type AzureBlobStorage struct { - cfg *setting.AzureBlobStorageConfig - ctx context.Context - credential *azblob.SharedKeyCredential - client *azblob.Client - containerClient *container.Client + cfg *setting.AzureBlobStorageConfig + ctx context.Context + credential *azblob.SharedKeyCredential + client *azblob.Client } func convertAzureBlobErr(err error) error { @@ -135,7 +127,7 @@ func NewAzureBlobStorage(ctx context.Context, cfg *setting.Storage) (ObjectStora if err != nil { return nil, convertAzureBlobErr(err) } - client, err := azblob.NewClientWithSharedKeyCredential(config.Endpoint+"/"+config.AccountName, cred, &azblob.ClientOptions{}) + client, err := azblob.NewClientWithSharedKeyCredential(config.Endpoint, cred, &azblob.ClientOptions{}) if err != nil { return nil, convertAzureBlobErr(err) } @@ -149,11 +141,10 @@ func NewAzureBlobStorage(ctx context.Context, cfg *setting.Storage) (ObjectStora } return &AzureBlobStorage{ - cfg: &config, - ctx: ctx, - credential: cred, - client: client, - containerClient: client.ServiceClient().NewContainerClient(config.Container), + cfg: &config, + ctx: ctx, + credential: cred, + client: client, }, nil } @@ -181,8 +172,8 @@ func (a *AzureBlobStorage) Open(path string) (Object, error) { return nil, convertAzureBlobErr(err) } return &azureBlobObject{ - Context: &a.ctx, - BlobClient: blobClient, + Context: a.ctx, + blobClient: blobClient, Name: a.getObjectNameFromPath(path), Size: *res.ContentLength, ModTime: res.LastModified, @@ -191,11 +182,7 @@ func (a *AzureBlobStorage) Open(path string) (Object, error) { // Save saves a file to azure blob storage func (a *AzureBlobStorage) Save(path string, r io.Reader, size int64) (int64, error) { - client, err := azblob.NewClientFromConnectionString(a.cfg.ConnectionString(), &azblob.ClientOptions{}) - if err != nil { - return 0, convertAzureBlobErr(err) - } - _, err = client.UploadStream( + _, err := a.client.UploadStream( a.ctx, a.cfg.Container, a.buildAzureBlobPath(path), @@ -312,8 +299,8 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o return convertAzureBlobErr(err) } object := &azureBlobObject{ - Context: &a.ctx, - BlobClient: blobClient, + Context: a.ctx, + blobClient: blobClient, Name: *object.Name, Size: *object.Properties.ContentLength, ModTime: object.Properties.LastModified, @@ -331,8 +318,7 @@ func (a *AzureBlobStorage) IterateObjects(dirName string, fn func(path string, o // Delete delete a file func (a *AzureBlobStorage) getBlobClient(path string) (*blob.Client, error) { - // blob.NewClient(blobURL string, cred azcore.TokenCredential, options *blob.ClientOptions) - return blob.NewClientFromConnectionString(a.cfg.ConnectionString(), a.cfg.Container, a.buildAzureBlobPath(path), &blob.ClientOptions{}) + return a.client.ServiceClient().NewContainerClient(a.cfg.Container).NewBlobClient(a.buildAzureBlobPath(path)), nil } func init() { From 755f13a1ec98fc565e1c1e72e0ebad7ad5994e2b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 16 May 2024 18:46:53 +0800 Subject: [PATCH 21/39] Add documentations --- custom/conf/app.example.ini | 3 ++- docs/content/administration/config-cheat-sheet.en-us.md | 9 ++++++++- docs/content/administration/config-cheat-sheet.zh-cn.md | 4 ++++ modules/setting/storage.go | 4 ++-- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index 987e95b7351fc..10304f652154b 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -2615,7 +2615,8 @@ LEVEL = Info ;[storage.azureblob] ;STORAGE_TYPE = azureblob ;; -;; Azure Blob endpoint to connect only available when STORAGE_TYPE is `azureblob` +;; Azure Blob endpoint to connect only available when STORAGE_TYPE is `azureblob`, +;; e.g. https://accountname.blob.core.windows.net or http://127.0.0.1:10000/devstoreaccount1 ;AZURE_BLOB_ENDPOINT = ;; ;; Azure Blob account name to connect only available when STORAGE_TYPE is `azureblob` diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index 6c429bb652161..9cdae646b3542 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -1279,7 +1279,8 @@ is `data/lfs` and the default of `MINIO_BASE_PATH` is `lfs/`. Default storage configuration for attachments, lfs, avatars, repo-avatars, repo-archive, packages, actions_log, actions_artifact. -- `STORAGE_TYPE`: **local**: Storage type, `local` for local disk or `minio` for s3 compatible object storage service. +- `STORAGE_TYPE`: **local**: Storage type, `local` for local disk, `minio` for s3 compatible object storage service, + `azureblob` for azure blob storage service. - `SERVE_DIRECT`: **false**: Allows the storage driver to redirect to authenticated URLs to serve files directly. Currently, only Minio/S3 is supported via signed URLs, local does nothing. - `MINIO_ENDPOINT`: **localhost:9000**: Minio endpoint to connect only available when `STORAGE_TYPE` is `minio` - `MINIO_ACCESS_KEY_ID`: Minio accessKeyID to connect only available when `STORAGE_TYPE` is `minio` @@ -1290,6 +1291,12 @@ Default storage configuration for attachments, lfs, avatars, repo-avatars, repo- - `MINIO_INSECURE_SKIP_VERIFY`: **false**: Minio skip SSL verification available when STORAGE_TYPE is `minio` - `MINIO_BUCKET_LOOKUP_TYPE`: **auto**: Minio bucket lookup method defaults to auto mode; set it to `dns` for virtual host style or `path` for path style, only available when STORAGE_TYPE is `minio` +- `AZURE_BLOB_ENDPOINT`: **_empty_**: Azure Blob endpoint to connect only available when STORAGE_TYPE is `azureblob`, + e.g. https://accountname.blob.core.windows.net or http://127.0.0.1:10000/devstoreaccount1 +- `AZURE_BLOB_ACCOUNT_NAME`: **_empty_**: Azure Blob account name to connect only available when STORAGE_TYPE is `azureblob` +- `AZURE_BLOB_ACCOUNT_KEY`: **_empty_**: Azure Blob account key to connect only available when STORAGE_TYPE is `azureblob` +- `AZURE_BLOB_CONTAINER`: **gitea**: Azure Blob container to store the attachments only available when STORAGE_TYPE is `azureblob` + The recommended storage configuration for minio like below: ```ini diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index 3c6ac8c00afb7..9570cbbf1870a 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -1218,6 +1218,10 @@ ALLOW_DATA_URI_IMAGES = true - `MINIO_USE_SSL`:**false**:Minio 启用 ssl,仅在 `STORAGE_TYPE` 为 `minio` 时可用。 - `MINIO_INSECURE_SKIP_VERIFY`:**false**:Minio 跳过 SSL 验证,仅在 `STORAGE_TYPE` 为 `minio` 时可用。 - `MINIO_BUCKET_LOOKUP_TYPE`: **auto**: Minio的bucket查找方式默认为`auto`模式,可将其设置为`dns`(虚拟托管样式)或`path`(路径样式),仅当`STORAGE_TYPE`为`minio`时可用。 +- `AZURE_BLOB_ENDPOINT`: **_empty_**: Azure Blob 终端点,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。例如:https://accountname.blob.core.windows.net 或 http://127.0.0.1:10000/devstoreaccount1 +- `AZURE_BLOB_ACCOUNT_NAME`: **_empty_**: Azure Blob 账号名,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 +- `AZURE_BLOB_ACCOUNT_KEY`: **_empty_**: Azure Blob 访问密钥,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 +- `AZURE_BLOB_CONTAINER`: **gitea**: Azure Blob 容器名,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 建议的 minio 存储配置如下: diff --git a/modules/setting/storage.go b/modules/setting/storage.go index fc392f6d638bd..e475e540ec95e 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -295,7 +295,7 @@ func getStorageForLocal(targetSec, overrideSec ConfigSection, tp targetSecType, return &storage, nil } -func getStorageForMinio(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { +func getStorageForMinio(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { //nolint:dupl var storage Storage storage.Type = StorageType(targetSec.Key("STORAGE_TYPE").String()) if err := targetSec.MapTo(&storage.MinioConfig); err != nil { @@ -324,7 +324,7 @@ func getStorageForMinio(targetSec, overrideSec ConfigSection, tp targetSecType, return &storage, nil } -func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { +func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { //nolint:dupl var storage Storage storage.Type = StorageType(targetSec.Key("STORAGE_TYPE").String()) if err := targetSec.MapTo(&storage.AzureBlobConfig); err != nil { From 37c2ffc4d7c23751df9a854bfd71afe205b011c5 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 16 May 2024 21:24:29 +0800 Subject: [PATCH 22/39] Add azureblob test for mssql tests --- .github/workflows/pull-db-tests.yml | 4 ++++ modules/storage/azureblob.go | 2 +- tests/mssql.ini.tmpl | 12 +++++++----- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 575a50991996b..80cfd98d093b9 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -208,6 +208,10 @@ jobs: SA_PASSWORD: MwantsaSecurePassword1 ports: - "1433:1433" + azurite: + image: mcr.microsoft.com/azure-storage/azurite:latest + ports: + - "10000:10000" steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index db45c25aa1a8b..7c3ed3a8fd895 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -222,7 +222,7 @@ func (a azureBlobFileInfo) Mode() os.FileMode { return os.ModePerm } -func (a azureBlobFileInfo) Sys() interface{} { +func (a azureBlobFileInfo) Sys() any { return nil } diff --git a/tests/mssql.ini.tmpl b/tests/mssql.ini.tmpl index 07997f62edfed..a767a35762456 100644 --- a/tests/mssql.ini.tmpl +++ b/tests/mssql.ini.tmpl @@ -53,9 +53,6 @@ APP_DATA_PATH = tests/{{TEST_TYPE}}/gitea-{{TEST_TYPE}}-mssql/data BUILTIN_SSH_SERVER_USER = git SSH_TRUSTED_USER_CA_KEYS = ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCb4DC1dMFnJ6pXWo7GMxTchtzmJHYzfN6sZ9FAPFR4ijMLfGki+olvOMO5Fql1/yGnGfbELQa1S6y4shSvj/5K+zUFScmEXYf3Gcr87RqilLkyk16RS+cHNB1u87xTHbETaa3nyCJeGQRpd4IQ4NKob745mwDZ7jQBH8AZEng50Oh8y8fi8skBBBzaYp1ilgvzG740L7uex6fHV62myq0SXeCa+oJUjq326FU8y+Vsa32H8A3e7tOgXZPdt2TVNltx2S9H2WO8RMi7LfaSwARNfy1zu+bfR50r6ef8Yx5YKCMz4wWb1SHU1GS800mjOjlInLQORYRNMlSwR1+vLlVDciOqFapDSbj+YOVOawR0R1aqlSKpZkt33DuOBPx9qe6CVnIi7Z+Px/KqM+OLCzlLY/RS+LbxQpDWcfTVRiP+S5qRTcE3M3UioN/e0BE/1+MpX90IGpvVkA63ILYbKEa4bM3ASL7ChTCr6xN5XT+GpVJveFKK1cfNx9ExHI4rzYE= -[attachment] -PATH = tests/{{TEST_TYPE}}/gitea-{{TEST_TYPE}}-mssql/data/attachments - [mailer] ENABLED = true PROTOCOL = dummy @@ -102,8 +99,13 @@ SECRET_KEY = 9pCviYTWSb INTERNAL_TOKEN = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTU1NTE2MTh9.hhSVGOANkaKk3vfCd2jDOIww4pUk0xtg9JRde5UogyQ DISABLE_QUERY_AUTH_TOKEN = true -[lfs] -PATH = tests/{{TEST_TYPE}}/gitea-{{TEST_TYPE}}-mssql/data/lfs +[storage] +STORAGE_TYPE = azureblob +AZURE_BLOB_ENDPOINT = http://azurite:10000/devstoreaccount1 +AZURE_BLOB_ACCOUNT_NAME = devstoreaccount1 +AZURE_BLOB_ACCOUNT_KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" +AZURE_BLOB_CONTAINER = gitea +SERVE_DIRECT = false [packages] ENABLED = true From 1d0d1ed8c459cbc2751ea0583b26abe20e6b4aab Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 16 May 2024 22:23:29 +0800 Subject: [PATCH 23/39] Fix ci --- .github/workflows/pull-db-tests.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 80cfd98d093b9..00952c5ca9404 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -211,7 +211,9 @@ jobs: azurite: image: mcr.microsoft.com/azure-storage/azurite:latest ports: - - "10000:10000" + - 10000:10000 + - 10001:10001 + - 10002:10002 steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 From 8dcf589c65746a0d54a69434cc1ef07868563f37 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 16 May 2024 22:38:33 +0800 Subject: [PATCH 24/39] Fix ci --- .github/workflows/pull-db-tests.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 00952c5ca9404..2225e27454cf9 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -119,10 +119,6 @@ jobs: MINIO_SECRET_KEY: 12345678 ports: - "9000:9000" - azurite: - image: mcr.microsoft.com/azure-storage/azurite - ports: - - "10000:10000" steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 @@ -221,7 +217,7 @@ jobs: go-version-file: go.mod check-latest: true - name: Add hosts to /etc/hosts - run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mssql" | sudo tee -a /etc/hosts' + run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mssql azurite" | sudo tee -a /etc/hosts' - run: make deps-backend - run: make backend env: From c3f1090719456978abdd99e07b5eb3dd40759072 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 17 May 2024 11:20:30 +0800 Subject: [PATCH 25/39] Fix read size --- modules/setting/storage.go | 14 -------------- modules/storage/azureblob.go | 5 +++-- modules/util/io.go | 21 +++++++++++++++++++++ routers/api/actions/artifacts_chunks.go | 2 +- 4 files changed, 25 insertions(+), 17 deletions(-) diff --git a/modules/setting/storage.go b/modules/setting/storage.go index e475e540ec95e..16dac3559d588 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -6,11 +6,8 @@ package setting import ( "errors" "fmt" - "net/url" "path/filepath" "strings" - - "code.gitea.io/gitea/modules/log" ) // StorageType is a type of Storage @@ -75,17 +72,6 @@ type AzureBlobStorageConfig struct { ServeDirect bool `ini:"SERVE_DIRECT"` } -func (cfg AzureBlobStorageConfig) ConnectionString() string { - u, err := url.Parse(cfg.Endpoint) - if err != nil { - log.Fatal("parse endpoint %s failed: %v", cfg.Endpoint, err) - return "" - } - - return fmt.Sprintf("DefaultEndpointsProtocol=%s;AccountName=%s;AccountKey=%s;EndpointSuffix=%s", - u.Scheme, cfg.AccountName, cfg.AccountKey, u.Host) -} - func (cfg *AzureBlobStorageConfig) ToShadow() { if cfg.AccountKey != "" { cfg.AccountKey = "******" diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 7c3ed3a8fd895..45cac902c126a 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -182,18 +182,19 @@ func (a *AzureBlobStorage) Open(path string) (Object, error) { // Save saves a file to azure blob storage func (a *AzureBlobStorage) Save(path string, r io.Reader, size int64) (int64, error) { + rd := util.NewCountingReader(r) _, err := a.client.UploadStream( a.ctx, a.cfg.Container, a.buildAzureBlobPath(path), - r, + rd, // TODO: support set block size and concurrency &blockblob.UploadStreamOptions{}, ) if err != nil { return 0, convertAzureBlobErr(err) } - return size, nil + return int64(rd.Count()), nil } type azureBlobFileInfo struct { diff --git a/modules/util/io.go b/modules/util/io.go index 1559b019a0637..eb200c9f9a6dd 100644 --- a/modules/util/io.go +++ b/modules/util/io.go @@ -76,3 +76,24 @@ func IsEmptyReader(r io.Reader) (err error) { } } } + +type CountingReader struct { + io.Reader + n int +} + +var _ io.Reader = &CountingReader{} + +func (w *CountingReader) Count() int { + return w.n +} + +func (w *CountingReader) Read(p []byte) (int, error) { + n, err := w.Reader.Read(p) + w.n += n + return n, err +} + +func NewCountingReader(rd io.Reader) *CountingReader { + return &CountingReader{Reader: rd} +} diff --git a/routers/api/actions/artifacts_chunks.go b/routers/api/actions/artifacts_chunks.go index 3a81724b3adf3..bba8ec5f94af2 100644 --- a/routers/api/actions/artifacts_chunks.go +++ b/routers/api/actions/artifacts_chunks.go @@ -55,7 +55,7 @@ func saveUploadChunkBase(st storage.ObjectStorage, ctx *ArtifactContext, } } if writtenSize != contentSize { - checkErr = errors.Join(checkErr, fmt.Errorf("contentSize not match body size")) + checkErr = errors.Join(checkErr, fmt.Errorf("writtenSize %d not match contentSize %d", writtenSize, contentSize)) } if checkErr != nil { if err := st.Delete(storagePath); err != nil { From 22a247ac4723903dc80e141b08bf7df30ee6b5a5 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 17 May 2024 12:35:14 +0800 Subject: [PATCH 26/39] Fix test bug --- .github/workflows/pull-db-tests.yml | 6 ++++-- modules/storage/azureblob_test.go | 2 +- modules/storage/minio_test.go | 2 +- routers/api/v1/org/avatar.go | 2 ++ routers/api/v1/user/avatar.go | 2 ++ services/user/avatar.go | 30 +++++++++++++++++++---------- tests/pgsql.ini.tmpl | 3 --- 7 files changed, 30 insertions(+), 17 deletions(-) diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 2225e27454cf9..f75d7661bff2f 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -119,6 +119,10 @@ jobs: MINIO_SECRET_KEY: 12345678 ports: - "9000:9000" + azurite: + image: mcr.microsoft.com/azure-storage/azurite:latest + ports: + - 10000:10000 steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 @@ -208,8 +212,6 @@ jobs: image: mcr.microsoft.com/azure-storage/azurite:latest ports: - 10000:10000 - - 10001:10001 - - 10002:10002 steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 diff --git a/modules/storage/azureblob_test.go b/modules/storage/azureblob_test.go index e0198ab074640..30272ce5694ca 100644 --- a/modules/storage/azureblob_test.go +++ b/modules/storage/azureblob_test.go @@ -20,7 +20,7 @@ func TestAzureBlobStorageIterator(t *testing.T) { testStorageIterator(t, setting.AzureBlobStorageType, &setting.Storage{ AzureBlobConfig: setting.AzureBlobStorageConfig{ // https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#ip-style-url - Endpoint: "http://127.0.0.1:10000/devstoreaccount1/", + Endpoint: "http://azurite:10000/devstoreaccount1/", // https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#well-known-storage-account-and-key AccountName: "devstoreaccount1", AccountKey: "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==", diff --git a/modules/storage/minio_test.go b/modules/storage/minio_test.go index c6fbb91ab4723..2364ced0ef1aa 100644 --- a/modules/storage/minio_test.go +++ b/modules/storage/minio_test.go @@ -22,7 +22,7 @@ func TestMinioStorageIterator(t *testing.T) { } testStorageIterator(t, setting.MinioStorageType, &setting.Storage{ MinioConfig: setting.MinioStorageConfig{ - Endpoint: "127.0.0.1:9000", + Endpoint: "minio:9000", AccessKeyID: "123456", SecretAccessKey: "12345678", Bucket: "gitea", diff --git a/routers/api/v1/org/avatar.go b/routers/api/v1/org/avatar.go index e34c68dfc9da1..f11eb6c1cd135 100644 --- a/routers/api/v1/org/avatar.go +++ b/routers/api/v1/org/avatar.go @@ -46,6 +46,7 @@ func UpdateAvatar(ctx *context.APIContext) { err = user_service.UploadAvatar(ctx, ctx.Org.Organization.AsUser(), content) if err != nil { ctx.Error(http.StatusInternalServerError, "UploadAvatar", err) + return } ctx.Status(http.StatusNoContent) @@ -72,6 +73,7 @@ func DeleteAvatar(ctx *context.APIContext) { err := user_service.DeleteAvatar(ctx, ctx.Org.Organization.AsUser()) if err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err) + return } ctx.Status(http.StatusNoContent) diff --git a/routers/api/v1/user/avatar.go b/routers/api/v1/user/avatar.go index f912296228e7d..30ccb63587b9d 100644 --- a/routers/api/v1/user/avatar.go +++ b/routers/api/v1/user/avatar.go @@ -39,6 +39,7 @@ func UpdateAvatar(ctx *context.APIContext) { err = user_service.UploadAvatar(ctx, ctx.Doer, content) if err != nil { ctx.Error(http.StatusInternalServerError, "UploadAvatar", err) + return } ctx.Status(http.StatusNoContent) @@ -57,6 +58,7 @@ func DeleteAvatar(ctx *context.APIContext) { err := user_service.DeleteAvatar(ctx, ctx.Doer) if err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err) + return } ctx.Status(http.StatusNoContent) diff --git a/services/user/avatar.go b/services/user/avatar.go index 2d6c3faf9a509..3f87466eaa6df 100644 --- a/services/user/avatar.go +++ b/services/user/avatar.go @@ -5,8 +5,10 @@ package user import ( "context" + "errors" "fmt" "io" + "os" "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" @@ -48,16 +50,24 @@ func UploadAvatar(ctx context.Context, u *user_model.User, data []byte) error { func DeleteAvatar(ctx context.Context, u *user_model.User) error { aPath := u.CustomAvatarRelativePath() log.Trace("DeleteAvatar[%d]: %s", u.ID, aPath) - if len(u.Avatar) > 0 { - if err := storage.Avatars.Delete(aPath); err != nil { - return fmt.Errorf("Failed to remove %s: %w", aPath, err) + + return db.WithTx(ctx, func(ctx context.Context) error { + hasAvatar := len(u.Avatar) > 0 + u.UseCustomAvatar = false + u.Avatar = "" + if _, err := db.GetEngine(ctx).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil { + return fmt.Errorf("DeleteAvatar: %w", err) } - } - u.UseCustomAvatar = false - u.Avatar = "" - if _, err := db.GetEngine(ctx).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil { - return fmt.Errorf("DeleteAvatar: %w", err) - } - return nil + if hasAvatar { + if err := storage.Avatars.Delete(aPath); err != nil { + if !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("failed to remove %s: %w", aPath, err) + } + log.Warn("Deleting avatar %s but it doesn't exist", aPath) + } + } + + return nil + }) } diff --git a/tests/pgsql.ini.tmpl b/tests/pgsql.ini.tmpl index 486cfc945c1aa..6b54f790c52a0 100644 --- a/tests/pgsql.ini.tmpl +++ b/tests/pgsql.ini.tmpl @@ -54,9 +54,6 @@ APP_DATA_PATH = tests/{{TEST_TYPE}}/gitea-{{TEST_TYPE}}-pgsql/data BUILTIN_SSH_SERVER_USER = git SSH_TRUSTED_USER_CA_KEYS = ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCb4DC1dMFnJ6pXWo7GMxTchtzmJHYzfN6sZ9FAPFR4ijMLfGki+olvOMO5Fql1/yGnGfbELQa1S6y4shSvj/5K+zUFScmEXYf3Gcr87RqilLkyk16RS+cHNB1u87xTHbETaa3nyCJeGQRpd4IQ4NKob745mwDZ7jQBH8AZEng50Oh8y8fi8skBBBzaYp1ilgvzG740L7uex6fHV62myq0SXeCa+oJUjq326FU8y+Vsa32H8A3e7tOgXZPdt2TVNltx2S9H2WO8RMi7LfaSwARNfy1zu+bfR50r6ef8Yx5YKCMz4wWb1SHU1GS800mjOjlInLQORYRNMlSwR1+vLlVDciOqFapDSbj+YOVOawR0R1aqlSKpZkt33DuOBPx9qe6CVnIi7Z+Px/KqM+OLCzlLY/RS+LbxQpDWcfTVRiP+S5qRTcE3M3UioN/e0BE/1+MpX90IGpvVkA63ILYbKEa4bM3ASL7ChTCr6xN5XT+GpVJveFKK1cfNx9ExHI4rzYE= -[attachment] -PATH = tests/{{TEST_TYPE}}/gitea-{{TEST_TYPE}}-pgsql/data/attachments - [mailer] ENABLED = true PROTOCOL = dummy From 929a4e3234b27092c4a1d48a0bbc643b7e8a08ca Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 17 May 2024 12:49:46 +0800 Subject: [PATCH 27/39] Fix bug --- .github/workflows/pull-db-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index f75d7661bff2f..32e31c988e11a 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -130,7 +130,7 @@ jobs: go-version-file: go.mod check-latest: true - name: Add hosts to /etc/hosts - run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mysql elasticsearch meilisearch smtpimap" | sudo tee -a /etc/hosts' + run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 minio azurite mysql elasticsearch meilisearch smtpimap" | sudo tee -a /etc/hosts' - run: make deps-backend - run: make backend env: From 0f32f6ba39ec1cd71a16e0104a151e6bae40eb98 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 17 May 2024 21:19:57 +0800 Subject: [PATCH 28/39] Fix servedirect --- modules/packages/content_store.go | 2 +- modules/setting/storage.go | 5 +++++ modules/storage/azureblob.go | 18 +++++++++++++++--- routers/api/actions/artifacts.go | 2 +- routers/api/actions/artifactsv4.go | 2 +- routers/api/v1/repo/file.go | 4 ++-- routers/web/base.go | 2 +- routers/web/repo/actions/view.go | 2 +- routers/web/repo/attachment.go | 2 +- routers/web/repo/download.go | 3 +-- routers/web/repo/repo.go | 2 +- services/lfs/server.go | 2 +- 12 files changed, 31 insertions(+), 15 deletions(-) diff --git a/modules/packages/content_store.go b/modules/packages/content_store.go index da93e6cf6bcbb..2108be64d25fb 100644 --- a/modules/packages/content_store.go +++ b/modules/packages/content_store.go @@ -34,7 +34,7 @@ func (s *ContentStore) Get(key BlobHash256Key) (storage.Object, error) { } func (s *ContentStore) ShouldServeDirect() bool { - return setting.Packages.Storage.MinioConfig.ServeDirect + return setting.Packages.Storage.ServeDirect() } func (s *ContentStore) GetServeDirectURL(key BlobHash256Key, filename string) (*url.URL, error) { diff --git a/modules/setting/storage.go b/modules/setting/storage.go index 16dac3559d588..d44c968423f83 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -97,6 +97,11 @@ func (storage *Storage) ToShadowCopy() Storage { return shadowStorage } +func (storage *Storage) ServeDirect() bool { + return (storage.Type == MinioStorageType && storage.MinioConfig.ServeDirect) || + (storage.Type == AzureBlobStorageType && storage.AzureBlobConfig.ServeDirect) +} + const storageSectionName = "storage" func getDefaultStorageSection(rootCfg ConfigProvider) ConfigSection { diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 45cac902c126a..6fddf869d793a 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -262,9 +262,21 @@ func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { return nil, convertAzureBlobErr(err) } - // GetSASURL is a generic method built for common use cases. We need to implement it by ourselves startTime := time.Now() - expiryTime := startTime.Add(5 * time.Minute) + u, err := blobClient.GetSASURL(sas.BlobPermissions{ + Read: true, + }, time.Now().Add(5*time.Minute), &blob.GetSASURLOptions{ + StartTime: &startTime, + }) + if err != nil { + return nil, convertAzureBlobErr(err) + } + + return url.Parse(u) + + // GetSASURL is a generic method built for common use cases. We need to implement it by ourselves + /*startTime := time.Now() + expiryTime := qps, err := sas.BlobSignatureValues{ ContainerName: a.cfg.Container, BlobName: a.buildAzureBlobPath(path), @@ -277,7 +289,7 @@ func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { if err != nil { return nil, err } - return url.Parse(blobClient.URL() + "?" + qps.Encode()) + return url.Parse(blobClient.URL() + "?" + qps.Encode())*/ } // IterateObjects iterates across the objects in the azureblobstorage diff --git a/routers/api/actions/artifacts.go b/routers/api/actions/artifacts.go index 35e3ee6906837..16af957d0f6e4 100644 --- a/routers/api/actions/artifacts.go +++ b/routers/api/actions/artifacts.go @@ -428,7 +428,7 @@ func (ar artifactRoutes) getDownloadArtifactURL(ctx *ArtifactContext) { var items []downloadArtifactResponseItem for _, artifact := range artifacts { var downloadURL string - if setting.Actions.ArtifactStorage.MinioConfig.ServeDirect { + if setting.Actions.ArtifactStorage.ServeDirect() { u, err := ar.fs.URL(artifact.StoragePath, artifact.ArtifactName) if err != nil && !errors.Is(err, storage.ErrURLNotSupported) { log.Error("Error getting serve direct url: %v", err) diff --git a/routers/api/actions/artifactsv4.go b/routers/api/actions/artifactsv4.go index dde9caf4f26b2..2ace9f915f0d0 100644 --- a/routers/api/actions/artifactsv4.go +++ b/routers/api/actions/artifactsv4.go @@ -448,7 +448,7 @@ func (r *artifactV4Routes) getSignedArtifactURL(ctx *ArtifactContext) { respData := GetSignedArtifactURLResponse{} - if setting.Actions.ArtifactStorage.MinioConfig.ServeDirect { + if setting.Actions.ArtifactStorage.ServeDirect() { u, err := storage.ActionsArtifacts.URL(artifact.StoragePath, artifact.ArtifactPath) if u != nil && err == nil { respData.SignedUrl = u.String() diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 156033f58aa55..d367da25fa3b7 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -201,7 +201,7 @@ func GetRawFileOrLFS(ctx *context.APIContext) { return } - if setting.LFS.Storage.MinioConfig.ServeDirect { + if setting.LFS.Storage.ServeDirect() { // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.LFS.URL(pointer.RelativePath(), blob.Name()) if u != nil && err == nil { @@ -320,7 +320,7 @@ func download(ctx *context.APIContext, archiveName string, archiver *repo_model. downloadName := ctx.Repo.Repository.Name + "-" + archiveName rPath := archiver.RelativePath() - if setting.RepoArchive.Storage.MinioConfig.ServeDirect { + if setting.RepoArchive.Storage.ServeDirect() { // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.RepoArchives.URL(rPath, downloadName) if u != nil && err == nil { diff --git a/routers/web/base.go b/routers/web/base.go index 78dde57fa6f85..c44233f957506 100644 --- a/routers/web/base.go +++ b/routers/web/base.go @@ -23,7 +23,7 @@ func storageHandler(storageSetting *setting.Storage, prefix string, objStore sto prefix = strings.Trim(prefix, "/") funcInfo := routing.GetFuncInfo(storageHandler, prefix) - if storageSetting.MinioConfig.ServeDirect { + if storageSetting.ServeDirect() { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.Method != "GET" && req.Method != "HEAD" { http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) diff --git a/routers/web/repo/actions/view.go b/routers/web/repo/actions/view.go index 12909bddd55bf..7cc12c90e6275 100644 --- a/routers/web/repo/actions/view.go +++ b/routers/web/repo/actions/view.go @@ -625,7 +625,7 @@ func ArtifactsDownloadView(ctx *context_module.Context) { // The v4 backend enshures ContentEncoding is set to "application/zip", which is not the case for the old backend if len(artifacts) == 1 && artifacts[0].ArtifactName+".zip" == artifacts[0].ArtifactPath && artifacts[0].ContentEncoding == "application/zip" { art := artifacts[0] - if setting.Actions.ArtifactStorage.MinioConfig.ServeDirect { + if setting.Actions.ArtifactStorage.ServeDirect() { u, err := storage.ActionsArtifacts.URL(art.StoragePath, art.ArtifactPath) if u != nil && err == nil { ctx.Redirect(u.String()) diff --git a/routers/web/repo/attachment.go b/routers/web/repo/attachment.go index f0c5622aec73d..6437c39a5726c 100644 --- a/routers/web/repo/attachment.go +++ b/routers/web/repo/attachment.go @@ -127,7 +127,7 @@ func ServeAttachment(ctx *context.Context, uuid string) { return } - if setting.Attachment.Storage.MinioConfig.ServeDirect { + if setting.Attachment.Storage.ServeDirect() { // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.Attachments.URL(attach.RelativePath(), attach.Name) diff --git a/routers/web/repo/download.go b/routers/web/repo/download.go index 6c03c881a7724..802e8e6a62cb2 100644 --- a/routers/web/repo/download.go +++ b/routers/web/repo/download.go @@ -53,8 +53,7 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified *time.Tim return nil } - if (setting.LFS.Storage.MinioConfig.ServeDirect && setting.LFS.Storage.Type == setting.MinioStorageType) || - (setting.LFS.Storage.AzureBlobConfig.ServeDirect && setting.LFS.Storage.Type == setting.AzureBlobStorageType) { + if setting.LFS.Storage.ServeDirect() { // If we have a signed url (S3, object storage, blob storage), redirect to this directly. u, err := storage.LFS.URL(pointer.RelativePath(), blob.Name()) if u != nil && err == nil { diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 48be1c22968fb..ba193715695dc 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -485,7 +485,7 @@ func download(ctx *context.Context, archiveName string, archiver *repo_model.Rep downloadName := ctx.Repo.Repository.Name + "-" + archiveName rPath := archiver.RelativePath() - if setting.RepoArchive.Storage.MinioConfig.ServeDirect { + if setting.RepoArchive.Storage.ServeDirect() { // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.RepoArchives.URL(rPath, downloadName) if u != nil && err == nil { diff --git a/services/lfs/server.go b/services/lfs/server.go index 706be0d080ebc..2e330aa1a4865 100644 --- a/services/lfs/server.go +++ b/services/lfs/server.go @@ -453,7 +453,7 @@ func buildObjectResponse(rc *requestContext, pointer lfs_module.Pointer, downloa if download { var link *lfs_module.Link - if setting.LFS.Storage.MinioConfig.ServeDirect { + if setting.LFS.Storage.ServeDirect() { // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.LFS.URL(pointer.RelativePath(), pointer.Oid) if u != nil && err == nil { From 8a01693ac7b886ba66b942f4bdd943e314a7fc8d Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 17 May 2024 21:22:21 +0800 Subject: [PATCH 29/39] Remove comment code --- modules/storage/azureblob.go | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 6fddf869d793a..689e5960e4f3c 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -273,23 +273,6 @@ func (a *AzureBlobStorage) URL(path, name string) (*url.URL, error) { } return url.Parse(u) - - // GetSASURL is a generic method built for common use cases. We need to implement it by ourselves - /*startTime := time.Now() - expiryTime := - qps, err := sas.BlobSignatureValues{ - ContainerName: a.cfg.Container, - BlobName: a.buildAzureBlobPath(path), - Version: sas.Version, - Permissions: (&sas.BlobPermissions{Read: true}).String(), - StartTime: startTime.UTC(), - ExpiryTime: expiryTime.UTC(), - ContentDisposition: "attachment; filename=\"" + quoteEscaper.Replace(name) + "\"", - }.SignWithSharedKey(a.credential) - if err != nil { - return nil, err - } - return url.Parse(blobClient.URL() + "?" + qps.Encode())*/ } // IterateObjects iterates across the objects in the azureblobstorage From 068bb240fda57e1c4d94f9420f952966778ae50a Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 17 May 2024 21:38:53 +0800 Subject: [PATCH 30/39] Fix test --- tests/integration/api_packages_generic_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index 8ad9c16dc430b..396c52d0257b2 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -164,6 +164,8 @@ func TestPackageGeneric(t *testing.T) { defer func() { setting.Packages.Storage.AzureBlobConfig.ServeDirect = old }() + + setting.Packages.Storage.AzureBlobConfig.ServeDirect = true } } From 15c439d21a1db05b5d56bf1a6d641b576f622761 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 18 May 2024 13:11:22 +0800 Subject: [PATCH 31/39] Fix removing non-exist attachment --- models/repo/attachment.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/models/repo/attachment.go b/models/repo/attachment.go index 9b0de11fdc831..fa4f6c47e604a 100644 --- a/models/repo/attachment.go +++ b/models/repo/attachment.go @@ -5,11 +5,14 @@ package repo import ( "context" + "errors" "fmt" "net/url" + "os" "path" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/timeutil" @@ -188,7 +191,10 @@ func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bo if remove { for i, a := range attachments { if err := storage.Attachments.Delete(a.RelativePath()); err != nil { - return i, err + if !errors.Is(err, os.ErrNotExist) { + return i, err + } + log.Warn("Attachment file not found when deleting: %s", a.RelativePath()) } } } From 50bf9195764dce78e49b38abdc20f072503ac4b1 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 19 May 2024 11:28:52 +0800 Subject: [PATCH 32/39] improve test --- tests/integration/api_packages_generic_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index 396c52d0257b2..baa8dd66c8613 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -179,7 +179,7 @@ func TestPackageGeneric(t *testing.T) { resp2, err := (&http.Client{}).Get(location) assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp2.StatusCode) + assert.Equal(t, http.StatusOK, resp2.StatusCode, location) body, err := io.ReadAll(resp2.Body) assert.NoError(t, err) From ca6a1dc4abf3b5733f53f9960b670082b2bef5da Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 20 May 2024 17:04:43 +0800 Subject: [PATCH 33/39] package version should not have space --- tests/integration/api_packages_generic_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index baa8dd66c8613..448f7704941dd 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -26,7 +26,7 @@ func TestPackageGeneric(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) packageName := "te-st_pac.kage" - packageVersion := "1.0.3-te st" + packageVersion := "1.0.3-test" filename := "fi-le_na.me" content := []byte{1, 2, 3} From c23e531741968039c7bc5a8ebc892b56de386289 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 21 May 2024 12:24:11 +0800 Subject: [PATCH 34/39] Fix the problem that azurite's special check for SASURL --- .github/workflows/pull-db-tests.yml | 8 ++++---- tests/mssql.ini.tmpl | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 32e31c988e11a..246884f24b1bd 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -119,7 +119,7 @@ jobs: MINIO_SECRET_KEY: 12345678 ports: - "9000:9000" - azurite: + devstoreaccount1.azurite.local: # https://github.com/Azure/Azurite/issues/1583 image: mcr.microsoft.com/azure-storage/azurite:latest ports: - 10000:10000 @@ -130,7 +130,7 @@ jobs: go-version-file: go.mod check-latest: true - name: Add hosts to /etc/hosts - run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 minio azurite mysql elasticsearch meilisearch smtpimap" | sudo tee -a /etc/hosts' + run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 minio devstoreaccount1.azurite.local mysql elasticsearch meilisearch smtpimap" | sudo tee -a /etc/hosts' - run: make deps-backend - run: make backend env: @@ -208,7 +208,7 @@ jobs: SA_PASSWORD: MwantsaSecurePassword1 ports: - "1433:1433" - azurite: + devstoreaccount1.azurite.local: # https://github.com/Azure/Azurite/issues/1583 image: mcr.microsoft.com/azure-storage/azurite:latest ports: - 10000:10000 @@ -219,7 +219,7 @@ jobs: go-version-file: go.mod check-latest: true - name: Add hosts to /etc/hosts - run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mssql azurite" | sudo tee -a /etc/hosts' + run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mssql devstoreaccount1.azurite.local" | sudo tee -a /etc/hosts' - run: make deps-backend - run: make backend env: diff --git a/tests/mssql.ini.tmpl b/tests/mssql.ini.tmpl index a767a35762456..77c969e813611 100644 --- a/tests/mssql.ini.tmpl +++ b/tests/mssql.ini.tmpl @@ -101,7 +101,7 @@ DISABLE_QUERY_AUTH_TOKEN = true [storage] STORAGE_TYPE = azureblob -AZURE_BLOB_ENDPOINT = http://azurite:10000/devstoreaccount1 +AZURE_BLOB_ENDPOINT = http://devstoreaccount1.azurite.local:10000 AZURE_BLOB_ACCOUNT_NAME = devstoreaccount1 AZURE_BLOB_ACCOUNT_KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" AZURE_BLOB_CONTAINER = gitea From 4b88ab4cd5dc213dbd90a3f9ee0607cbb43660ce Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 21 May 2024 13:29:33 +0800 Subject: [PATCH 35/39] Fix test --- modules/storage/azureblob_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/storage/azureblob_test.go b/modules/storage/azureblob_test.go index 30272ce5694ca..604870cb98ebf 100644 --- a/modules/storage/azureblob_test.go +++ b/modules/storage/azureblob_test.go @@ -20,7 +20,7 @@ func TestAzureBlobStorageIterator(t *testing.T) { testStorageIterator(t, setting.AzureBlobStorageType, &setting.Storage{ AzureBlobConfig: setting.AzureBlobStorageConfig{ // https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#ip-style-url - Endpoint: "http://azurite:10000/devstoreaccount1/", + Endpoint: "http://devstoreaccount1.azurite.local:10000", // https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#well-known-storage-account-and-key AccountName: "devstoreaccount1", AccountKey: "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==", From 4511c1357068e404f05a6341ba1deda0393b0e3e Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 22 May 2024 11:21:58 +0800 Subject: [PATCH 36/39] Revert unnecessary change --- tests/integration/api_packages_generic_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index 448f7704941dd..baa8dd66c8613 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -26,7 +26,7 @@ func TestPackageGeneric(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) packageName := "te-st_pac.kage" - packageVersion := "1.0.3-test" + packageVersion := "1.0.3-te st" filename := "fi-le_na.me" content := []byte{1, 2, 3} From a3c56dd3285386072fb2907e41615d507a2df7dd Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 23 May 2024 09:32:36 +0800 Subject: [PATCH 37/39] Apply suggestions from code review Co-authored-by: yp05327 <576951401@qq.com> --- docs/content/administration/config-cheat-sheet.en-us.md | 2 +- docs/content/administration/config-cheat-sheet.zh-cn.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index 9cdae646b3542..26c61ff04b9a7 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -1295,7 +1295,7 @@ Default storage configuration for attachments, lfs, avatars, repo-avatars, repo- e.g. https://accountname.blob.core.windows.net or http://127.0.0.1:10000/devstoreaccount1 - `AZURE_BLOB_ACCOUNT_NAME`: **_empty_**: Azure Blob account name to connect only available when STORAGE_TYPE is `azureblob` - `AZURE_BLOB_ACCOUNT_KEY`: **_empty_**: Azure Blob account key to connect only available when STORAGE_TYPE is `azureblob` -- `AZURE_BLOB_CONTAINER`: **gitea**: Azure Blob container to store the attachments only available when STORAGE_TYPE is `azureblob` +- `AZURE_BLOB_CONTAINER`: **gitea**: Azure Blob container to store the data only available when STORAGE_TYPE is `azureblob` The recommended storage configuration for minio like below: diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index 9570cbbf1870a..ea0af32fe1c62 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -1221,7 +1221,7 @@ ALLOW_DATA_URI_IMAGES = true - `AZURE_BLOB_ENDPOINT`: **_empty_**: Azure Blob 终端点,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。例如:https://accountname.blob.core.windows.net 或 http://127.0.0.1:10000/devstoreaccount1 - `AZURE_BLOB_ACCOUNT_NAME`: **_empty_**: Azure Blob 账号名,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 - `AZURE_BLOB_ACCOUNT_KEY`: **_empty_**: Azure Blob 访问密钥,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 -- `AZURE_BLOB_CONTAINER`: **gitea**: Azure Blob 容器名,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 +- `AZURE_BLOB_CONTAINER`: **gitea**: 用于存储数据的 Azure Blob 容器名,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 建议的 minio 存储配置如下: From e76bf6593196113a8af8d80bd1ad41ecaa118a9f Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 23 May 2024 09:38:51 +0800 Subject: [PATCH 38/39] Update documentations --- docs/content/administration/config-cheat-sheet.en-us.md | 3 +-- docs/content/administration/config-cheat-sheet.zh-cn.md | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index 26c61ff04b9a7..a658132e17e70 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -1279,8 +1279,7 @@ is `data/lfs` and the default of `MINIO_BASE_PATH` is `lfs/`. Default storage configuration for attachments, lfs, avatars, repo-avatars, repo-archive, packages, actions_log, actions_artifact. -- `STORAGE_TYPE`: **local**: Storage type, `local` for local disk, `minio` for s3 compatible object storage service, - `azureblob` for azure blob storage service. +- `STORAGE_TYPE`: **local**: Storage type, `local` for local disk, `minio` for s3 compatible object storage service, `azureblob` for azure blob storage service. - `SERVE_DIRECT`: **false**: Allows the storage driver to redirect to authenticated URLs to serve files directly. Currently, only Minio/S3 is supported via signed URLs, local does nothing. - `MINIO_ENDPOINT`: **localhost:9000**: Minio endpoint to connect only available when `STORAGE_TYPE` is `minio` - `MINIO_ACCESS_KEY_ID`: Minio accessKeyID to connect only available when `STORAGE_TYPE` is `minio` diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index ea0af32fe1c62..7d51c758b6c11 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -1208,7 +1208,7 @@ ALLOW_DATA_URI_IMAGES = true 默认的附件、lfs、头像、仓库头像、仓库归档、软件包、操作日志、操作艺术品的存储配置。 -- `STORAGE_TYPE`:**local**:存储类型,`local` 表示本地磁盘,`minio` 表示 S3 兼容的对象存储服务。 +- `STORAGE_TYPE`:**local**:存储类型,`local` 表示本地磁盘,`minio` 表示 S3,`azureblob` 表示 azure 对象存储。 - `SERVE_DIRECT`:**false**:允许存储驱动程序重定向到经过身份验证的 URL 以直接提供文件。目前,仅支持通过签名的 URL 提供 Minio/S3,本地不执行任何操作。 - `MINIO_ENDPOINT`:**localhost:9000**:连接的 Minio 终端点,仅在 `STORAGE_TYPE` 为 `minio` 时可用。 - `MINIO_ACCESS_KEY_ID`:Minio 的 accessKeyID,仅在 `STORAGE_TYPE` 为 `minio` 时可用。 @@ -1218,6 +1218,7 @@ ALLOW_DATA_URI_IMAGES = true - `MINIO_USE_SSL`:**false**:Minio 启用 ssl,仅在 `STORAGE_TYPE` 为 `minio` 时可用。 - `MINIO_INSECURE_SKIP_VERIFY`:**false**:Minio 跳过 SSL 验证,仅在 `STORAGE_TYPE` 为 `minio` 时可用。 - `MINIO_BUCKET_LOOKUP_TYPE`: **auto**: Minio的bucket查找方式默认为`auto`模式,可将其设置为`dns`(虚拟托管样式)或`path`(路径样式),仅当`STORAGE_TYPE`为`minio`时可用。 + - `AZURE_BLOB_ENDPOINT`: **_empty_**: Azure Blob 终端点,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。例如:https://accountname.blob.core.windows.net 或 http://127.0.0.1:10000/devstoreaccount1 - `AZURE_BLOB_ACCOUNT_NAME`: **_empty_**: Azure Blob 账号名,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 - `AZURE_BLOB_ACCOUNT_KEY`: **_empty_**: Azure Blob 访问密钥,仅在 `STORAGE_TYPE` 为 `azureblob` 时可用。 From 391fd1e3e11ec9a895a4e53ad3e36f88a4f6a0a4 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 27 May 2024 14:58:58 +0800 Subject: [PATCH 39/39] Fix bug --- modules/storage/azureblob.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/storage/azureblob.go b/modules/storage/azureblob.go index 689e5960e4f3c..52a7d1637e031 100644 --- a/modules/storage/azureblob.go +++ b/modules/storage/azureblob.go @@ -67,20 +67,20 @@ func (a *azureBlobObject) Close() error { func (a *azureBlobObject) Seek(offset int64, whence int) (int64, error) { switch whence { case io.SeekStart: - a.offset = offset case io.SeekCurrent: - a.offset += offset + offset += a.offset case io.SeekEnd: - a.offset = a.Size - offset + offset = a.Size - offset default: return 0, errors.New("Seek: invalid whence") } - if a.offset > a.Size { + if offset > a.Size { return 0, errors.New("Seek: invalid offset") - } else if a.offset < 0 { + } else if offset < 0 { return 0, errors.New("Seek: invalid offset") } + a.offset = offset return a.offset, nil } @@ -112,7 +112,7 @@ func convertAzureBlobErr(err error) error { } var respErr *azcore.ResponseError if !errors.As(err, &respErr) { - return nil + return err } return fmt.Errorf(respErr.ErrorCode) }