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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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/16] 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" )