diff --git a/go.mod b/go.mod index 2713f33eabad..350f76b248bd 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( github.com/gofrs/uuid v4.4.0+incompatible github.com/golang-jwt/jwt/v4 v4.5.0 github.com/google/go-cmp v0.5.9 - github.com/google/uuid v1.3.1 + github.com/google/uuid v1.4.0 github.com/hashicorp/go-azure-helpers v0.66.2 github.com/hashicorp/go-azure-sdk/resource-manager v0.20240229.1102109 github.com/hashicorp/go-azure-sdk/sdk v0.20240229.1102109 @@ -29,7 +29,7 @@ require ( github.com/mitchellh/mapstructure v1.5.0 github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9 github.com/sergi/go-diff v1.2.0 - github.com/tombuildsstuff/giovanni v0.20.0 + github.com/tombuildsstuff/giovanni v0.25.1 github.com/tombuildsstuff/kermit v0.20240122.1123108 golang.org/x/crypto v0.18.0 golang.org/x/tools v0.13.0 diff --git a/go.sum b/go.sum index d50fa903ca8f..d9db26cc608f 100644 --- a/go.sum +++ b/go.sum @@ -1,36 +1,23 @@ dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= -github.com/Azure/azure-sdk-for-go v45.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go v56.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/azure-sdk-for-go v66.0.0+incompatible h1:bmmC38SlE8/E81nNADlgmVGurPWMHDX2YNXVQMrBpEE= github.com/Azure/azure-sdk-for-go v66.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= -github.com/Azure/go-autorest/autorest v0.11.3/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= -github.com/Azure/go-autorest/autorest v0.11.19/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= github.com/Azure/go-autorest/autorest v0.11.29 h1:I4+HL/JDvErx2LjyzaVxllw2lRDB5/BT2Bm4g20iqYw= github.com/Azure/go-autorest/autorest v0.11.29/go.mod h1:ZtEzC4Jy2JDrZLxvWs8LrBWEBycl1hbT1eknI8MtfAs= -github.com/Azure/go-autorest/autorest/adal v0.9.0/go.mod h1:/c022QCutn2P7uY+/oQWWNcK9YU+MH96NgK+jErpbcg= -github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= -github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= -github.com/Azure/go-autorest/autorest/adal v0.9.14/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= github.com/Azure/go-autorest/autorest/adal v0.9.22/go.mod h1:XuAbAEUv2Tta//+voMI038TrJBqjKam0me7qR+L8Cmk= github.com/Azure/go-autorest/autorest/adal v0.9.23 h1:Yepx8CvFxwNKpH6ja7RZ+sKX+DWYNldbLiALMC3BTz8= github.com/Azure/go-autorest/autorest/adal v0.9.23/go.mod h1:5pcMqFkdPhviJdlEy3kC/v1ZLnQl0MH6XA5YCcMhy4c= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.0/go.mod h1:JljT387FplPzBA31vUcvsetLKF3pec5bdAxjVU4kI2s= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.2/go.mod h1:7qkJkT+j6b+hIpzMOwPChJhTqS8VbsqqgULzMNRugoM= github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= -github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/mocks v0.4.2 h1:PGN4EDXnuQbojHbU0UWoNvmu9AGVwYHG9/fkDYhtAfw= github.com/Azure/go-autorest/autorest/mocks v0.4.2/go.mod h1:Vy7OitM9Kei0i1Oj+LvyAWMXJHeKH1MVlzFugfVrmyU= github.com/Azure/go-autorest/autorest/to v0.4.0 h1:oXVqrxakqqV1UZdSazDOPOLvOIz+XA683u8EctwboHk= github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE= -github.com/Azure/go-autorest/autorest/validation v0.3.0/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= github.com/Azure/go-autorest/autorest/validation v0.3.1 h1:AgyqjAd94fwNAoTjl/WQXg4VvFeRFpO+UhNyRXqF1ac= github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= -github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg= github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= @@ -67,16 +54,11 @@ github.com/dave/jennifer v1.6.0/go.mod h1:AxTG893FiZKqxy3FP1kL80VMshSMuz2G+Egvsz github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= -github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= -github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic= @@ -104,15 +86,13 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-azure-helpers v0.12.0/go.mod h1:Zc3v4DNeX6PDdy7NljlYpnrdac1++qNW0I4U+ofGwpg= github.com/hashicorp/go-azure-helpers v0.66.2 h1:+Pzuo7pdKl0hBXXr5ymmhs4Q40tHAo2nAvHq4WgSjx8= github.com/hashicorp/go-azure-helpers v0.66.2/go.mod h1:kJxXrFtJKJdOEqvad8pllAe7dhP4DbN8J6sqFZe47+4= github.com/hashicorp/go-azure-sdk/resource-manager v0.20240229.1102109 h1:3e4ceMmTqM2upGPdGlEynSqx1tLbQ8qzRVdzVllxp0U= @@ -130,7 +110,6 @@ github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrj github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c= github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-plugin v1.5.1 h1:oGm7cWBaYIp3lJpx1RUEfLWophprE2EV/KUeqBYo+6k= @@ -200,7 +179,6 @@ github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= @@ -244,10 +222,11 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/tombuildsstuff/giovanni v0.20.0 h1:IM/I/iNWMXnPYwcSq8uxV7TKDlv7Nejq0bRK9i6O/C0= -github.com/tombuildsstuff/giovanni v0.20.0/go.mod h1:66KVLYma2whJhEdxPSPL3GQHkulhK+C5CluKfHGfPF4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/tombuildsstuff/giovanni v0.25.1 h1:GP3Q+LAs7Uwf1ZXogOyq7bG4v0A7ROtuU2UKBzIxLK0= +github.com/tombuildsstuff/giovanni v0.25.1/go.mod h1:U5QCrP5ATt9csJfaceJaqV96ZDCn1yWLhzw04oIaYE8= github.com/tombuildsstuff/kermit v0.20240122.1123108 h1:icQaxsv/ANv/KC4Sr0V1trrWA/XIL+3QAVBDpiSTgj8= github.com/tombuildsstuff/kermit v0.20240122.1123108/go.mod h1:T3YBVFhRV4qA7SbnRaNE6eapIMpKDA9rG/V7Ocsjlno= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= @@ -267,9 +246,6 @@ github.com/zclconf/go-cty v1.14.0/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgr golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= diff --git a/internal/common/client_options.go b/internal/common/client_options.go index 6eba6eeaedcc..1b5c831b5d3b 100644 --- a/internal/common/client_options.go +++ b/internal/common/client_options.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/go-azure-helpers/sender" "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/hashicorp/go-azure-sdk/sdk/client" - "github.com/hashicorp/go-azure-sdk/sdk/client/resourcemanager" "github.com/hashicorp/go-azure-sdk/sdk/environments" "github.com/hashicorp/terraform-plugin-sdk/v2/meta" "github.com/hashicorp/terraform-provider-azurerm/internal/features" @@ -66,24 +65,20 @@ type ClientOptions struct { } // Configure set up a resourcemanager.Client using an auth.Authorizer from hashicorp/go-azure-sdk -func (o ClientOptions) Configure(c *resourcemanager.Client, authorizer auth.Authorizer) { - c.Authorizer = authorizer - c.UserAgent = userAgent(c.UserAgent, o.TerraformVersion, o.PartnerId, o.DisableTerraformPartnerID) +func (o ClientOptions) Configure(c client.BaseClient, authorizer auth.Authorizer) { + c.SetAuthorizer(authorizer) + c.SetUserAgent(userAgent(c.GetUserAgent(), o.TerraformVersion, o.PartnerId, o.DisableTerraformPartnerID)) - requestMiddlewares := make([]client.RequestMiddleware, 0) if !o.DisableCorrelationRequestID { id := o.CustomCorrelationRequestID if id == "" { id = correlationRequestID() } - requestMiddlewares = append(requestMiddlewares, correlationRequestIDMiddleware(id)) + c.AppendRequestMiddleware(correlationRequestIDMiddleware(id)) } - requestMiddlewares = append(requestMiddlewares, requestLoggerMiddleware("AzureRM")) - c.RequestMiddlewares = &requestMiddlewares - c.ResponseMiddlewares = &[]client.ResponseMiddleware{ - responseLoggerMiddleware("AzureRM"), - } + c.AppendRequestMiddleware(requestLoggerMiddleware("AzureRM")) + c.AppendResponseMiddleware(responseLoggerMiddleware("AzureRM")) } // ConfigureClient sets up an autorest.Client using an autorest.Authorizer diff --git a/internal/provider/helpers.go b/internal/provider/helpers.go new file mode 100644 index 000000000000..eb1ce774a23d --- /dev/null +++ b/internal/provider/helpers.go @@ -0,0 +1,128 @@ +package provider + +import ( + "encoding/base64" + "fmt" + "os" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func decodeCertificate(clientCertificate string) ([]byte, error) { + var pfx []byte + if clientCertificate != "" { + out := make([]byte, base64.StdEncoding.DecodedLen(len(clientCertificate))) + n, err := base64.StdEncoding.Decode(out, []byte(clientCertificate)) + if err != nil { + return pfx, fmt.Errorf("could not decode client certificate data: %v", err) + } + pfx = out[:n] + } + return pfx, nil +} + +func getOidcToken(d *schema.ResourceData) (*string, error) { + idToken := strings.TrimSpace(d.Get("oidc_token").(string)) + + if path := d.Get("oidc_token_file_path").(string); path != "" { + fileTokenRaw, err := os.ReadFile(path) + + if err != nil { + return nil, fmt.Errorf("reading OIDC Token from file %q: %v", path, err) + } + + fileToken := strings.TrimSpace(string(fileTokenRaw)) + + if idToken != "" && idToken != fileToken { + return nil, fmt.Errorf("mismatch between supplied OIDC token and supplied OIDC token file contents - please either remove one or ensure they match") + } + + idToken = fileToken + } + + if d.Get("use_aks_workload_identity").(bool) && os.Getenv("AZURE_FEDERATED_TOKEN_FILE") != "" { + path := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") + fileTokenRaw, err := os.ReadFile(os.Getenv("AZURE_FEDERATED_TOKEN_FILE")) + + if err != nil { + return nil, fmt.Errorf("reading OIDC Token from file %q provided by AKS Workload Identity: %v", path, err) + } + + fileToken := strings.TrimSpace(string(fileTokenRaw)) + + if idToken != "" && idToken != fileToken { + return nil, fmt.Errorf("mismatch between supplied OIDC token and OIDC token file contents provided by AKS Workload Identity - please either remove one, ensure they match, or disable use_aks_workload_identity") + } + + idToken = fileToken + } + + return &idToken, nil +} + +func getClientId(d *schema.ResourceData) (*string, error) { + clientId := strings.TrimSpace(d.Get("client_id").(string)) + + if path := d.Get("client_id_file_path").(string); path != "" { + fileClientIdRaw, err := os.ReadFile(path) + + if err != nil { + return nil, fmt.Errorf("reading Client ID from file %q: %v", path, err) + } + + fileClientId := strings.TrimSpace(string(fileClientIdRaw)) + + if clientId != "" && clientId != fileClientId { + return nil, fmt.Errorf("mismatch between supplied Client ID and supplied Client ID file contents - please either remove one or ensure they match") + } + + clientId = fileClientId + } + + if d.Get("use_aks_workload_identity").(bool) && os.Getenv("AZURE_CLIENT_ID") != "" { + aksClientId := os.Getenv("AZURE_CLIENT_ID") + if clientId != "" && clientId != aksClientId { + return nil, fmt.Errorf("mismatch between supplied Client ID and that provided by AKS Workload Identity - please remove, ensure they match, or disable use_aks_workload_identity") + } + clientId = aksClientId + } + + return &clientId, nil +} + +func getClientSecret(d *schema.ResourceData) (*string, error) { + clientSecret := strings.TrimSpace(d.Get("client_secret").(string)) + + if path := d.Get("client_secret_file_path").(string); path != "" { + fileSecretRaw, err := os.ReadFile(path) + + if err != nil { + return nil, fmt.Errorf("reading Client Secret from file %q: %v", path, err) + } + + fileSecret := strings.TrimSpace(string(fileSecretRaw)) + + if clientSecret != "" && clientSecret != fileSecret { + return nil, fmt.Errorf("mismatch between supplied Client Secret and supplied Client Secret file contents - please either remove one or ensure they match") + } + + clientSecret = fileSecret + } + + return &clientSecret, nil +} + +func getTenantId(d *schema.ResourceData) (*string, error) { + tenantId := strings.TrimSpace(d.Get("tenant_id").(string)) + + if d.Get("use_aks_workload_identity").(bool) && os.Getenv("AZURE_TENANT_ID") != "" { + aksTenantId := os.Getenv("AZURE_TENANT_ID") + if tenantId != "" && tenantId != aksTenantId { + return nil, fmt.Errorf("mismatch between supplied Tenant ID and that provided by AKS Workload Identity - please remove, ensure they match, or disable use_aks_workload_identity") + } + tenantId = aksTenantId + } + + return &tenantId, nil +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 5c2d5fc23fe8..4c6fbac83948 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -5,7 +5,6 @@ package provider import ( "context" - "encoding/base64" "fmt" "log" "os" @@ -510,124 +509,6 @@ func buildClient(ctx context.Context, p *schema.Provider, d *schema.ResourceData return client, nil } -func decodeCertificate(clientCertificate string) ([]byte, error) { - var pfx []byte - if clientCertificate != "" { - out := make([]byte, base64.StdEncoding.DecodedLen(len(clientCertificate))) - n, err := base64.StdEncoding.Decode(out, []byte(clientCertificate)) - if err != nil { - return pfx, fmt.Errorf("could not decode client certificate data: %v", err) - } - pfx = out[:n] - } - return pfx, nil -} - -func getOidcToken(d *schema.ResourceData) (*string, error) { - idToken := strings.TrimSpace(d.Get("oidc_token").(string)) - - if path := d.Get("oidc_token_file_path").(string); path != "" { - fileTokenRaw, err := os.ReadFile(path) - - if err != nil { - return nil, fmt.Errorf("reading OIDC Token from file %q: %v", path, err) - } - - fileToken := strings.TrimSpace(string(fileTokenRaw)) - - if idToken != "" && idToken != fileToken { - return nil, fmt.Errorf("mismatch between supplied OIDC token and supplied OIDC token file contents - please either remove one or ensure they match") - } - - idToken = fileToken - } - - if d.Get("use_aks_workload_identity").(bool) && os.Getenv("AZURE_FEDERATED_TOKEN_FILE") != "" { - path := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") - fileTokenRaw, err := os.ReadFile(os.Getenv("AZURE_FEDERATED_TOKEN_FILE")) - - if err != nil { - return nil, fmt.Errorf("reading OIDC Token from file %q provided by AKS Workload Identity: %v", path, err) - } - - fileToken := strings.TrimSpace(string(fileTokenRaw)) - - if idToken != "" && idToken != fileToken { - return nil, fmt.Errorf("mismatch between supplied OIDC token and OIDC token file contents provided by AKS Workload Identity - please either remove one, ensure they match, or disable use_aks_workload_identity") - } - - idToken = fileToken - } - - return &idToken, nil -} - -func getClientId(d *schema.ResourceData) (*string, error) { - clientId := strings.TrimSpace(d.Get("client_id").(string)) - - if path := d.Get("client_id_file_path").(string); path != "" { - fileClientIdRaw, err := os.ReadFile(path) - - if err != nil { - return nil, fmt.Errorf("reading Client ID from file %q: %v", path, err) - } - - fileClientId := strings.TrimSpace(string(fileClientIdRaw)) - - if clientId != "" && clientId != fileClientId { - return nil, fmt.Errorf("mismatch between supplied Client ID and supplied Client ID file contents - please either remove one or ensure they match") - } - - clientId = fileClientId - } - - if d.Get("use_aks_workload_identity").(bool) && os.Getenv("AZURE_CLIENT_ID") != "" { - aksClientId := os.Getenv("AZURE_CLIENT_ID") - if clientId != "" && clientId != aksClientId { - return nil, fmt.Errorf("mismatch between supplied Client ID and that provided by AKS Workload Identity - please remove, ensure they match, or disable use_aks_workload_identity") - } - clientId = aksClientId - } - - return &clientId, nil -} - -func getClientSecret(d *schema.ResourceData) (*string, error) { - clientSecret := strings.TrimSpace(d.Get("client_secret").(string)) - - if path := d.Get("client_secret_file_path").(string); path != "" { - fileSecretRaw, err := os.ReadFile(path) - - if err != nil { - return nil, fmt.Errorf("reading Client Secret from file %q: %v", path, err) - } - - fileSecret := strings.TrimSpace(string(fileSecretRaw)) - - if clientSecret != "" && clientSecret != fileSecret { - return nil, fmt.Errorf("mismatch between supplied Client Secret and supplied Client Secret file contents - please either remove one or ensure they match") - } - - clientSecret = fileSecret - } - - return &clientSecret, nil -} - -func getTenantId(d *schema.ResourceData) (*string, error) { - tenantId := strings.TrimSpace(d.Get("tenant_id").(string)) - - if d.Get("use_aks_workload_identity").(bool) && os.Getenv("AZURE_TENANT_ID") != "" { - aksTenantId := os.Getenv("AZURE_TENANT_ID") - if tenantId != "" && tenantId != aksTenantId { - return nil, fmt.Errorf("mismatch between supplied Tenant ID and that provided by AKS Workload Identity - please remove, ensure they match, or disable use_aks_workload_identity") - } - tenantId = aksTenantId - } - - return &tenantId, nil -} - const resourceProviderRegistrationErrorFmt = `Error ensuring Resource Providers are registered. Terraform automatically attempts to register the Resource Providers it supports to diff --git a/internal/services/arckubernetes/arc_kubernetes_flux_configuration_resource.go b/internal/services/arckubernetes/arc_kubernetes_flux_configuration_resource.go index ccdac918aa82..68810ecab054 100644 --- a/internal/services/arckubernetes/arc_kubernetes_flux_configuration_resource.go +++ b/internal/services/arckubernetes/arc_kubernetes_flux_configuration_resource.go @@ -7,7 +7,6 @@ import ( "context" "fmt" "regexp" - "strings" "time" "github.com/hashicorp/go-azure-helpers/lang/pointer" @@ -16,11 +15,12 @@ import ( "github.com/hashicorp/go-azure-sdk/resource-manager/kubernetesconfiguration/2022-11-01/fluxconfiguration" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" storageValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) const ( @@ -570,7 +570,7 @@ func (r ArcKubernetesFluxConfigurationResource) Create() sdk.ResourceFunc { properties.Properties.Bucket, properties.Properties.ConfigurationProtectedSettings = expandBucketDefinitionModel(model.Bucket) } else if _, exists = metadata.ResourceData.GetOk("blob_storage"); exists { properties.Properties.SourceKind = pointer.To(fluxconfiguration.SourceKindTypeAzureBlob) - azureBlob, err := expandArcAzureBlobDefinitionModel(model.BlobStorage) + azureBlob, err := expandArcAzureBlobDefinitionModel(model.BlobStorage, metadata.Client.Storage.StorageDomainSuffix) if err != nil { return fmt.Errorf("expanding `blob_storage`: %+v", err) } @@ -624,7 +624,7 @@ func (r ArcKubernetesFluxConfigurationResource) Update() sdk.ResourceFunc { properties.Properties.ConfigurationProtectedSettings = nil if metadata.ResourceData.HasChange("blob_storage") { - azureBlob, err := expandArcAzureBlobDefinitionModel(model.BlobStorage) + azureBlob, err := expandArcAzureBlobDefinitionModel(model.BlobStorage, metadata.Client.Storage.StorageDomainSuffix) if err != nil { return fmt.Errorf("expanding `blob_storage`: %+v", err) } @@ -717,7 +717,7 @@ func (r ArcKubernetesFluxConfigurationResource) Read() sdk.ResourceFunc { if model := resp.Model; model != nil { if properties := model.Properties; properties != nil { - blobStorage, err := flattenArcAzureBlobDefinitionModel(properties.AzureBlob, configModel.BlobStorage) + blobStorage, err := flattenArcAzureBlobDefinitionModel(properties.AzureBlob, configModel.BlobStorage, metadata.Client.Storage.StorageDomainSuffix) if err != nil { return fmt.Errorf("flattening `blob_storage`: %+v", err) } @@ -762,7 +762,7 @@ func (r ArcKubernetesFluxConfigurationResource) Delete() sdk.ResourceFunc { } } -func expandArcAzureBlobDefinitionModel(inputList []AzureBlobDefinitionModel) (*fluxconfiguration.AzureBlobDefinition, error) { +func expandArcAzureBlobDefinitionModel(inputList []AzureBlobDefinitionModel, storageDomainSuffix string) (*fluxconfiguration.AzureBlobDefinition, error) { if len(inputList) == 0 { return nil, nil } @@ -778,13 +778,13 @@ func expandArcAzureBlobDefinitionModel(inputList []AzureBlobDefinitionModel) (*f } if input.ContainerID != "" { - id, err := parse.StorageContainerDataPlaneID(input.ContainerID) + id, err := containers.ParseContainerID(input.ContainerID, storageDomainSuffix) if err != nil { return nil, err } - output.ContainerName = &id.Name - output.Url = pointer.To(strings.TrimSuffix(input.ContainerID, "/"+id.Name)) + output.ContainerName = &id.ContainerName + output.Url = pointer.To(id.AccountId.ID()) } if input.LocalAuthRef != "" { @@ -969,17 +969,19 @@ func expandRepositoryRefDefinitionModel(referenceType string, referenceValue str return &output, nil } -func flattenArcAzureBlobDefinitionModel(input *fluxconfiguration.AzureBlobDefinition, azureBlob []AzureBlobDefinitionModel) ([]AzureBlobDefinitionModel, error) { +func flattenArcAzureBlobDefinitionModel(input *fluxconfiguration.AzureBlobDefinition, azureBlob []AzureBlobDefinitionModel, storageDomainSuffix string) ([]AzureBlobDefinitionModel, error) { outputList := make([]AzureBlobDefinitionModel, 0) if input == nil { return outputList, nil } - id, err := parse.StorageContainerDataPlaneID(fmt.Sprintf("%s/%s", pointer.From(input.Url), pointer.From(input.ContainerName))) + accountId, err := accounts.ParseAccountID(pointer.From(input.Url), storageDomainSuffix) if err != nil { - return nil, err + return nil, fmt.Errorf("parsing account %q: %+v", pointer.From(input.Url), err) } + id := containers.NewContainerID(*accountId, pointer.From(input.ContainerName)) + output := AzureBlobDefinitionModel{ ContainerID: id.ID(), LocalAuthRef: pointer.From(input.LocalAuthRef), diff --git a/internal/services/containers/kubernetes_flux_configuration_resource.go b/internal/services/containers/kubernetes_flux_configuration_resource.go index d5b25970cdf8..3814185e3ee6 100644 --- a/internal/services/containers/kubernetes_flux_configuration_resource.go +++ b/internal/services/containers/kubernetes_flux_configuration_resource.go @@ -7,7 +7,6 @@ import ( "context" "fmt" "regexp" - "strings" "time" "github.com/hashicorp/go-azure-helpers/lang/pointer" @@ -16,11 +15,12 @@ import ( "github.com/hashicorp/go-azure-sdk/resource-manager/kubernetesconfiguration/2022-11-01/fluxconfiguration" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" storageValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) const ( @@ -589,7 +589,7 @@ func (r KubernetesFluxConfigurationResource) Create() sdk.ResourceFunc { properties.Properties.Bucket, properties.Properties.ConfigurationProtectedSettings = expandBucketDefinitionModel(model.Bucket) } else if _, exists = metadata.ResourceData.GetOk("blob_storage"); exists { properties.Properties.SourceKind = pointer.To(fluxconfiguration.SourceKindTypeAzureBlob) - azureBlob, err := expandAzureBlobDefinitionModel(model.BlobStorage) + azureBlob, err := expandAzureBlobDefinitionModel(model.BlobStorage, metadata.Client.Storage.StorageDomainSuffix) if err != nil { return fmt.Errorf("expanding `blob_storage`: %+v", err) } @@ -643,7 +643,7 @@ func (r KubernetesFluxConfigurationResource) Update() sdk.ResourceFunc { properties.Properties.ConfigurationProtectedSettings = nil if metadata.ResourceData.HasChange("blob_storage") { - azureBlob, err := expandAzureBlobDefinitionModel(model.BlobStorage) + azureBlob, err := expandAzureBlobDefinitionModel(model.BlobStorage, metadata.Client.Storage.StorageDomainSuffix) if err != nil { return fmt.Errorf("expanding `blob_storage`: %+v", err) } @@ -735,7 +735,7 @@ func (r KubernetesFluxConfigurationResource) Read() sdk.ResourceFunc { if model := resp.Model; model != nil { if properties := model.Properties; properties != nil { - blobStorage, err := flattenAzureBlobDefinitionModel(properties.AzureBlob, configModel.BlobStorage) + blobStorage, err := flattenAzureBlobDefinitionModel(properties.AzureBlob, configModel.BlobStorage, metadata.Client.Storage.StorageDomainSuffix) if err != nil { return fmt.Errorf("flattening `blob_storage`: %+v", err) } @@ -780,7 +780,7 @@ func (r KubernetesFluxConfigurationResource) Delete() sdk.ResourceFunc { } } -func expandAzureBlobDefinitionModel(inputList []AzureBlobDefinitionModel) (*fluxconfiguration.AzureBlobDefinition, error) { +func expandAzureBlobDefinitionModel(inputList []AzureBlobDefinitionModel, storageDomainSuffix string) (*fluxconfiguration.AzureBlobDefinition, error) { if len(inputList) == 0 { return nil, nil } @@ -797,13 +797,13 @@ func expandAzureBlobDefinitionModel(inputList []AzureBlobDefinitionModel) (*flux } if input.ContainerID != "" { - id, err := parse.StorageContainerDataPlaneID(input.ContainerID) + id, err := containers.ParseContainerID(input.ContainerID, storageDomainSuffix) if err != nil { return nil, err } - output.ContainerName = &id.Name - output.Url = pointer.To(strings.TrimSuffix(input.ContainerID, "/"+id.Name)) + output.ContainerName = &id.ContainerName + output.Url = pointer.To(id.AccountId.ID()) } if input.LocalAuthRef != "" { @@ -1002,17 +1002,19 @@ func expandRepositoryRefDefinitionModel(referenceType string, referenceValue str return &output, nil } -func flattenAzureBlobDefinitionModel(input *fluxconfiguration.AzureBlobDefinition, azureBlob []AzureBlobDefinitionModel) ([]AzureBlobDefinitionModel, error) { +func flattenAzureBlobDefinitionModel(input *fluxconfiguration.AzureBlobDefinition, azureBlob []AzureBlobDefinitionModel, storageDomainSuffix string) ([]AzureBlobDefinitionModel, error) { outputList := make([]AzureBlobDefinitionModel, 0) if input == nil { return outputList, nil } - id, err := parse.StorageContainerDataPlaneID(fmt.Sprintf("%s/%s", pointer.From(input.Url), pointer.From(input.ContainerName))) + accountId, err := accounts.ParseAccountID(pointer.From(input.Url), storageDomainSuffix) if err != nil { - return nil, err + return nil, fmt.Errorf("parsing account %q: %+v", pointer.From(input.Url), err) } + id := containers.NewContainerID(*accountId, pointer.From(input.ContainerName)) + output := AzureBlobDefinitionModel{ ContainerID: id.ID(), LocalAuthRef: pointer.From(input.LocalAuthRef), diff --git a/internal/services/legacy/virtual_machine_resource.go b/internal/services/legacy/virtual_machine_resource.go index e1d7d72e3e37..a1fb4be0c752 100644 --- a/internal/services/legacy/virtual_machine_resource.go +++ b/internal/services/legacy/virtual_machine_resource.go @@ -30,7 +30,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" "github.com/tombuildsstuff/kermit/sdk/compute/2023-03-01/compute" "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) @@ -1033,24 +1033,24 @@ func resourceVirtualMachineDeleteVhd(ctx context.Context, storageClient *intStor } uri := *vhd.URI - id, err := blobs.ParseResourceID(uri) + id, err := blobs.ParseBlobID(uri, storageClient.StorageDomainSuffix) if err != nil { return fmt.Errorf("parsing %q: %s", uri, err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q (Disk %q)!", id.AccountName, uri) + return fmt.Errorf("Unable to locate Storage Account %q (Disk %q)!", id.AccountId.AccountName, uri) } if err != nil { return fmt.Errorf("building Blobs Client: %s", err) } - blobsClient, err := storageClient.BlobsClient(ctx, *account) + blobsClient, err := storageClient.BlobsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Blobs Client: %s", err) } @@ -1058,8 +1058,8 @@ func resourceVirtualMachineDeleteVhd(ctx context.Context, storageClient *intStor input := blobs.DeleteInput{ DeleteSnapshots: false, } - if _, err := blobsClient.Delete(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("deleting Blob %q (Container %q / Account %q / Resource Group %q): %s", id.BlobName, id.ContainerName, id.AccountName, account.ResourceGroup, err) + if _, err := blobsClient.Delete(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("deleting Blob %q (Container %q / Account %q / Resource Group %q): %s", id.BlobName, id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } return nil diff --git a/internal/services/legacy/virtual_machine_resource_test.go b/internal/services/legacy/virtual_machine_resource_test.go index 656633a55ee0..1e5eb5e0d43a 100644 --- a/internal/services/legacy/virtual_machine_resource_test.go +++ b/internal/services/legacy/virtual_machine_resource_test.go @@ -7,14 +7,16 @@ import ( "context" "fmt" "testing" + "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" ) type VirtualMachineResource struct{} @@ -238,6 +240,9 @@ func (VirtualMachineResource) deallocate(ctx context.Context, client *clients.Cl func (VirtualMachineResource) unmanagedDiskExistsInContainer(blobName string, shouldExist bool) acceptance.ClientCheckFunc { return func(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + accountName := state.Attributes["storage_account_name"] containerName := state.Attributes["name"] @@ -249,15 +254,15 @@ func (VirtualMachineResource) unmanagedDiskExistsInContainer(blobName string, sh return fmt.Errorf("Unable to locate Storage Account %q!", accountName) } - client, err := clients.Storage.BlobsClient(ctx, *account) + client, err := clients.Storage.BlobsDataPlaneClient(ctx, *account, clients.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Blobs Client: %s", err) } input := blobs.GetPropertiesInput{} - props, err := client.GetProperties(ctx, accountName, containerName, blobName, input) + props, err := client.GetProperties(ctx, containerName, blobName, input) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse) { if !shouldExist { return nil } diff --git a/internal/services/machinelearning/machine_learning_datastore_blobstorage_resource.go b/internal/services/machinelearning/machine_learning_datastore_blobstorage_resource.go index 81dbe550c3ff..a18f56dac9c3 100644 --- a/internal/services/machinelearning/machine_learning_datastore_blobstorage_resource.go +++ b/internal/services/machinelearning/machine_learning_datastore_blobstorage_resource.go @@ -160,14 +160,9 @@ func (r MachineLearningDataStoreBlobStorage) Create() sdk.ResourceFunc { Type: pointer.To(string(datastore.DatastoreTypeAzureBlob)), } - storageDomainSuffix, ok := metadata.Client.Account.Environment.Storage.DomainSuffix() - if !ok { - return fmt.Errorf("could not determine Storage domain suffix for environment %q", metadata.Client.Account.Environment.Name) - } - props := &datastore.AzureBlobDatastore{ AccountName: pointer.To(containerId.StorageAccountName), - Endpoint: storageDomainSuffix, + Endpoint: pointer.To(metadata.Client.Storage.StorageDomainSuffix), ContainerName: pointer.To(containerId.ContainerName), Description: pointer.To(model.Description), ServiceDataAccessAuthIdentity: pointer.To(datastore.ServiceDataAccessAuthIdentity(model.ServiceDataAuthIdentity)), diff --git a/internal/services/machinelearning/machine_learning_datastore_datalake_gen2_resource.go b/internal/services/machinelearning/machine_learning_datastore_datalake_gen2_resource.go index 819e8bd67594..ee95fb156a10 100644 --- a/internal/services/machinelearning/machine_learning_datastore_datalake_gen2_resource.go +++ b/internal/services/machinelearning/machine_learning_datastore_datalake_gen2_resource.go @@ -178,6 +178,7 @@ func (r MachineLearningDataStoreDataLakeGen2) Create() sdk.ResourceFunc { props := &datastore.AzureDataLakeGen2Datastore{ AccountName: containerId.StorageAccountName, + Endpoint: pointer.To(metadata.Client.Storage.StorageDomainSuffix), Filesystem: containerId.ContainerName, Description: utils.String(model.Description), ServiceDataAccessAuthIdentity: pointer.To(datastore.ServiceDataAccessAuthIdentity(model.ServiceDataIdentity)), diff --git a/internal/services/machinelearning/machine_learning_datastore_fileshare_resource.go b/internal/services/machinelearning/machine_learning_datastore_fileshare_resource.go index 4e452949b913..a1b50df2fbcd 100644 --- a/internal/services/machinelearning/machine_learning_datastore_fileshare_resource.go +++ b/internal/services/machinelearning/machine_learning_datastore_fileshare_resource.go @@ -161,6 +161,7 @@ func (r MachineLearningDataStoreFileShare) Create() sdk.ResourceFunc { props := &datastore.AzureFileDatastore{ AccountName: fileShareId.StorageAccountName, + Endpoint: pointer.To(metadata.Client.Storage.StorageDomainSuffix), FileShareName: fileShareId.FileshareName, Description: pointer.To(model.Description), ServiceDataAccessAuthIdentity: pointer.To(datastore.ServiceDataAccessAuthIdentity(model.ServiceDataIdentity)), diff --git a/internal/services/storage/blobs.go b/internal/services/storage/blobs.go index 116c69ad9445..70e59082642b 100644 --- a/internal/services/storage/blobs.go +++ b/internal/services/storage/blobs.go @@ -14,14 +14,11 @@ import ( "runtime" "strings" "sync" - "time" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" ) -const pollingInterval = time.Second * 15 - type BlobUpload struct { Client *blobs.Client @@ -96,7 +93,7 @@ func (sbu BlobUpload) copy(ctx context.Context) error { CopySource: sbu.SourceUri, MetaData: sbu.MetaData, } - if err := sbu.Client.CopyAndWait(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input, pollingInterval); err != nil { + if err := sbu.Client.CopyAndWait(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("copy/waiting: %s", err) } @@ -108,7 +105,7 @@ func (sbu BlobUpload) createEmptyAppendBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutAppendBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutAppendBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutAppendBlob: %s", err) } @@ -124,7 +121,7 @@ func (sbu BlobUpload) createEmptyBlockBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutBlockBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutBlockBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutBlockBlob: %s", err) } @@ -161,7 +158,7 @@ func (sbu BlobUpload) uploadBlockBlob(ctx context.Context) error { if sbu.ContentMD5 != "" { input.ContentMD5 = utils.String(sbu.ContentMD5) } - if err := sbu.Client.PutBlockBlobFromFile(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, file, input); err != nil { + if err := sbu.Client.PutBlockBlobFromFile(ctx, sbu.ContainerName, sbu.BlobName, file, input); err != nil { return fmt.Errorf("PutBlockBlobFromFile: %s", err) } @@ -178,7 +175,7 @@ func (sbu BlobUpload) createEmptyPageBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutPageBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutPageBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutPageBlob: %s", err) } @@ -228,7 +225,7 @@ func (sbu BlobUpload) uploadPageBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutPageBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutPageBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutPageBlob: %s", err) } @@ -373,7 +370,7 @@ func (sbu BlobUpload) blobPageUploadWorker(ctx context.Context, uploadCtx blobPa Content: chunk, } - if _, err := sbu.Client.PutPageUpdate(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutPageUpdate(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { uploadCtx.errors <- fmt.Errorf("writing page at offset %d for file %q: %s", page.offset, sbu.Source, err) uploadCtx.wg.Done() continue diff --git a/internal/services/storage/client/client.go b/internal/services/storage/client/client.go index 199f0dbbfc56..c5d47935bc7f 100644 --- a/internal/services/storage/client/client.go +++ b/internal/services/storage/client/client.go @@ -4,61 +4,53 @@ package client import ( - "context" "fmt" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage" // nolint: staticcheck - "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" storage_v2023_01_01 "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2023-01-01" "github.com/hashicorp/go-azure-sdk/resource-manager/storagesync/2020-03-01/cloudendpointresource" "github.com/hashicorp/go-azure-sdk/resource-manager/storagesync/2020-03-01/storagesyncservicesresource" "github.com/hashicorp/go-azure-sdk/resource-manager/storagesync/2020-03-01/syncgroupresource" + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/hashicorp/go-azure-sdk/sdk/client/resourcemanager" "github.com/hashicorp/terraform-provider-azurerm/internal/common" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/shim" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" ) +// StorageDomainSuffix is used by validation functions +var StorageDomainSuffix *string + type Client struct { + SubscriptionId string + AccountsClient *storage.AccountsClient - FileSystemsClient *filesystems.Client - ADLSGen2PathsClient *paths.Client - BlobServicesClient *storage.BlobServicesClient BlobInventoryPoliciesClient *storage.BlobInventoryPoliciesClient + BlobServicesClient *storage.BlobServicesClient EncryptionScopesClient *storage.EncryptionScopesClient - Environment azure.Environment FileServicesClient *storage.FileServicesClient SyncCloudEndpointsClient *cloudendpointresource.CloudEndpointResourceClient - SyncServiceClient *storagesyncservicesresource.StorageSyncServicesResourceClient SyncGroupsClient *syncgroupresource.SyncGroupResourceClient - SubscriptionId string + SyncServiceClient *storagesyncservicesresource.StorageSyncServicesResourceClient ResourceManager *storage_v2023_01_01.Client - resourceManagerAuthorizer autorest.Authorizer - storageAdAuth *autorest.Authorizer + AzureEnvironment azure.Environment + StorageDomainSuffix string + + authorizerForAad auth.Authorizer } func NewClient(o *common.ClientOptions) (*Client, error) { - accountsClient := storage.NewAccountsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&accountsClient.Client, o.ResourceManagerAuthorizer) + storageSuffix, ok := o.Environment.Storage.DomainSuffix() + if !ok { + return nil, fmt.Errorf("determining domain suffix for storage in environment: %s", o.Environment.Name) + } - fileSystemsClient := filesystems.NewWithEnvironment(o.AzureEnvironment) - o.ConfigureClient(&fileSystemsClient.Client, o.StorageAuthorizer) + // Set global variable for post-configure validation + StorageDomainSuffix = storageSuffix - adlsGen2PathsClient := paths.NewWithEnvironment(o.AzureEnvironment) - o.ConfigureClient(&adlsGen2PathsClient.Client, o.StorageAuthorizer) + accountsClient := storage.NewAccountsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&accountsClient.Client, o.ResourceManagerAuthorizer) blobServicesClient := storage.NewBlobServicesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&blobServicesClient.Client, o.ResourceManagerAuthorizer) @@ -100,12 +92,9 @@ func NewClient(o *common.ClientOptions) (*Client, error) { // (which should fix #2977) when the storage clients have been moved in here client := Client{ AccountsClient: &accountsClient, - FileSystemsClient: &fileSystemsClient, - ADLSGen2PathsClient: &adlsGen2PathsClient, BlobServicesClient: &blobServicesClient, BlobInventoryPoliciesClient: &blobInventoryPoliciesClient, EncryptionScopesClient: &encryptionScopesClient, - Environment: o.AzureEnvironment, FileServicesClient: &fileServicesClient, ResourceManager: resourceManager, SubscriptionId: o.SubscriptionId, @@ -113,195 +102,13 @@ func NewClient(o *common.ClientOptions) (*Client, error) { SyncServiceClient: syncServiceClient, SyncGroupsClient: syncGroupsClient, - resourceManagerAuthorizer: o.ResourceManagerAuthorizer, + AzureEnvironment: o.AzureEnvironment, + StorageDomainSuffix: *storageSuffix, } if o.StorageUseAzureAD { - client.storageAdAuth = &o.StorageAuthorizer + client.authorizerForAad = o.Authorizers.Storage } return &client, nil } - -func (client Client) AccountsDataPlaneClient(ctx context.Context, account accountDetails) (*accounts.Client, error) { - if client.storageAdAuth != nil { - accountsClient := accounts.NewWithEnvironment(client.Environment) - accountsClient.Client.Authorizer = *client.storageAdAuth - return &accountsClient, nil - } - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKey) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - accountsClient := accounts.NewWithEnvironment(client.Environment) - accountsClient.Client.Authorizer = storageAuth - return &accountsClient, nil -} - -func (client Client) BlobsClient(ctx context.Context, account accountDetails) (*blobs.Client, error) { - if client.storageAdAuth != nil { - blobsClient := blobs.NewWithEnvironment(client.Environment) - blobsClient.Client.Authorizer = *client.storageAdAuth - return &blobsClient, nil - } - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKey) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - blobsClient := blobs.NewWithEnvironment(client.Environment) - blobsClient.Client.Authorizer = storageAuth - return &blobsClient, nil -} - -func (client Client) ContainersClient(ctx context.Context, account accountDetails) (shim.StorageContainerWrapper, error) { - if client.storageAdAuth != nil { - containersClient := containers.NewWithEnvironment(client.Environment) - containersClient.Client.Authorizer = *client.storageAdAuth - shim := shim.NewDataPlaneStorageContainerWrapper(&containersClient) - return shim, nil - } - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKey) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - containersClient := containers.NewWithEnvironment(client.Environment) - containersClient.Client.Authorizer = storageAuth - - shim := shim.NewDataPlaneStorageContainerWrapper(&containersClient) - return shim, nil -} - -func (client Client) FileShareDirectoriesClient(ctx context.Context, account accountDetails) (*directories.Client, error) { - // NOTE: Files do not support AzureAD Authentication - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - directoriesClient := directories.NewWithEnvironment(client.Environment) - directoriesClient.Client.Authorizer = storageAuth - return &directoriesClient, nil -} - -func (client Client) FileShareFilesClient(ctx context.Context, account accountDetails) (*files.Client, error) { - // NOTE: Files do not support AzureAD Authentication - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - filesClient := files.NewWithEnvironment(client.Environment) - filesClient.Client.Authorizer = storageAuth - return &filesClient, nil -} - -func (client Client) FileSharesClient(ctx context.Context, account accountDetails) (shim.StorageShareWrapper, error) { - // NOTE: Files do not support AzureAD Authentication - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - sharesClient := shares.NewWithEnvironment(client.Environment) - sharesClient.Client.Authorizer = storageAuth - shim := shim.NewDataPlaneStorageShareWrapper(&sharesClient) - return shim, nil -} - -func (client Client) QueuesClient(ctx context.Context, account accountDetails) (shim.StorageQueuesWrapper, error) { - if client.storageAdAuth != nil { - queueClient := queues.NewWithEnvironment(client.Environment) - queueClient.Client.Authorizer = *client.storageAdAuth - return shim.NewDataPlaneStorageQueueWrapper(&queueClient), nil - } - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - queuesClient := queues.NewWithEnvironment(client.Environment) - queuesClient.Client.Authorizer = storageAuth - return shim.NewDataPlaneStorageQueueWrapper(&queuesClient), nil -} - -func (client Client) TableEntityClient(ctx context.Context, account accountDetails) (*entities.Client, error) { - // NOTE: Table Entity does not support AzureAD Authentication - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLiteForTable) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - entitiesClient := entities.NewWithEnvironment(client.Environment) - entitiesClient.Client.Authorizer = storageAuth - return &entitiesClient, nil -} - -func (client Client) TablesClient(ctx context.Context, account accountDetails) (shim.StorageTableWrapper, error) { - // NOTE: Tables do not support AzureAD Authentication - - accountKey, err := account.AccountKey(ctx, client) - if err != nil { - return nil, fmt.Errorf("retrieving Account Key: %s", err) - } - - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLiteForTable) - if err != nil { - return nil, fmt.Errorf("building Authorizer: %+v", err) - } - - tablesClient := tables.NewWithEnvironment(client.Environment) - tablesClient.Client.Authorizer = storageAuth - shim := shim.NewDataPlaneStorageTableWrapper(&tablesClient) - return shim, nil -} diff --git a/internal/services/storage/client/data_plane.go b/internal/services/storage/client/data_plane.go new file mode 100644 index 000000000000..7e8a070209fd --- /dev/null +++ b/internal/services/storage/client/data_plane.go @@ -0,0 +1,308 @@ +package client + +import ( + "context" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/shim" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables" +) + +type DataPlaneOperation struct { + SupportsAadAuthentication bool + SupportsSharedKeyAuthentication bool + + sharedKeyAuthenticationType auth.SharedKeyType +} + +func (Client) DataPlaneOperationSupportingAnyAuthMethod() DataPlaneOperation { + return DataPlaneOperation{ + SupportsAadAuthentication: true, + SupportsSharedKeyAuthentication: true, + } +} + +func (Client) DataPlaneOperationSupportingOnlySharedKeyAuth() DataPlaneOperation { + return DataPlaneOperation{ + SupportsAadAuthentication: false, + SupportsSharedKeyAuthentication: true, + } +} + +func (c Client) configureDataPlane(ctx context.Context, clientName string, baseClient client.BaseClient, account accountDetails, operation DataPlaneOperation) error { + if operation.SupportsAadAuthentication && c.authorizerForAad != nil { + baseClient.SetAuthorizer(c.authorizerForAad) + return nil + } + + if operation.SupportsSharedKeyAuthentication { + accountKey, err := account.AccountKey(ctx, c) + if err != nil { + return fmt.Errorf("retrieving Storage Account Key: %s", err) + } + + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, operation.sharedKeyAuthenticationType) + if err != nil { + return fmt.Errorf("building Shared Key Authorizer for %s client: %+v", clientName, err) + } + + baseClient.SetAuthorizer(storageAuth) + return nil + } + + return fmt.Errorf("building %s client: no configured authentication types are supported", clientName) +} + +func (c Client) AccountsDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (*accounts.Client, error) { + const clientName = "Blob Storage Accounts" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeBlob) + if err != nil { + return nil, err + } + + apiClient, err := accounts.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return apiClient, nil +} + +func (c Client) BlobsDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (*blobs.Client, error) { + const clientName = "Blob Storage Blobs" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeBlob) + if err != nil { + return nil, err + } + + apiClient, err := blobs.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return apiClient, nil +} + +func (c Client) ContainersDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (shim.StorageContainerWrapper, error) { + const clientName = "Blob Storage Containers" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeBlob) + if err != nil { + return nil, err + } + + apiClient, err := containers.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return shim.NewDataPlaneStorageContainerWrapper(apiClient), nil +} + +func (c Client) DataLakeFilesystemsDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (*filesystems.Client, error) { + const clientName = "Data Lake Gen2 Filesystems" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeDfs) + if err != nil { + return nil, err + } + + apiClient, err := filesystems.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return apiClient, nil +} + +func (c Client) DataLakePathsDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (*paths.Client, error) { + const clientName = "Data Lake Gen2 Paths" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeDfs) + if err != nil { + return nil, err + } + + apiClient, err := paths.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return apiClient, nil +} + +func (c Client) FileShareDirectoriesDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (*directories.Client, error) { + const clientName = "File Storage Share Directories" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeFile) + if err != nil { + return nil, err + } + + apiClient, err := directories.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return apiClient, nil +} + +func (c Client) FileShareFilesDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (*files.Client, error) { + const clientName = "File Storage Share Files" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeFile) + if err != nil { + return nil, err + } + + apiClient, err := files.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return apiClient, nil +} + +func (c Client) FileSharesDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (shim.StorageShareWrapper, error) { + const clientName = "File Storage Shares" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeFile) + if err != nil { + return nil, err + } + + apiClient, err := shares.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return shim.NewDataPlaneStorageShareWrapper(apiClient), nil +} + +func (c Client) QueuesDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (shim.StorageQueuesWrapper, error) { + const clientName = "File Storage Queue Queues" + operation.sharedKeyAuthenticationType = auth.SharedKey + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeQueue) + if err != nil { + return nil, err + } + + apiClient, err := queues.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return shim.NewDataPlaneStorageQueueWrapper(apiClient), nil +} + +func (c Client) TableEntityDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (*entities.Client, error) { + const clientName = "Table Storage Share Entities" + operation.sharedKeyAuthenticationType = auth.SharedKeyTable + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeTable) + if err != nil { + return nil, err + } + + apiClient, err := entities.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return apiClient, nil +} + +func (c Client) TablesDataPlaneClient(ctx context.Context, account accountDetails, operation DataPlaneOperation) (shim.StorageTableWrapper, error) { + const clientName = "Table Storage Share Tables" + operation.sharedKeyAuthenticationType = auth.SharedKeyTable + + baseUri, err := account.DataPlaneEndpoint(EndpointTypeTable) + if err != nil { + return nil, err + } + + apiClient, err := tables.NewWithBaseUri(*baseUri) + if err != nil { + return nil, fmt.Errorf("building %s client: %+v", clientName, err) + } + + err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + if err != nil { + return nil, err + } + + return shim.NewDataPlaneStorageTableWrapper(apiClient), nil +} diff --git a/internal/services/storage/client/helpers.go b/internal/services/storage/client/helpers.go index 7d4a82865cb2..47e2fe3162f5 100644 --- a/internal/services/storage/client/helpers.go +++ b/internal/services/storage/client/helpers.go @@ -7,6 +7,7 @@ import ( "context" "fmt" "log" + "strings" "sync" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage" // nolint: staticcheck @@ -20,6 +21,16 @@ var ( credentialsLock = sync.RWMutex{} ) +type EndpointType string + +const ( + EndpointTypeBlob = "blob" + EndpointTypeDfs = "dfs" + EndpointTypeFile = "file" + EndpointTypeQueue = "queue" + EndpointTypeTable = "table" +) + type accountDetails struct { ID string Kind storage.Kind @@ -42,11 +53,11 @@ func (ad *accountDetails) AccountKey(ctx context.Context, client Client) (*strin log.Printf("[DEBUG] Cache Miss - looking up the account key for storage account %q..", ad.name) props, err := client.AccountsClient.ListKeys(ctx, ad.ResourceGroup, ad.name, storage.ListKeyExpandKerb) if err != nil { - return nil, fmt.Errorf("Listing Keys for Storage Account %q (Resource Group %q): %+v", ad.name, ad.ResourceGroup, err) + return nil, fmt.Errorf("listing Keys for Storage Account %q (Resource Group %q): %+v", ad.name, ad.ResourceGroup, err) } if props.Keys == nil || len(*props.Keys) == 0 || (*props.Keys)[0].Value == nil { - return nil, fmt.Errorf("Keys were nil for Storage Account %q (Resource Group %q): %+v", ad.name, ad.ResourceGroup, err) + return nil, fmt.Errorf("keys were nil for Storage Account %q (Resource Group %q): %+v", ad.name, ad.ResourceGroup, err) } keys := *props.Keys @@ -58,7 +69,49 @@ func (ad *accountDetails) AccountKey(ctx context.Context, client Client) (*strin return ad.accountKey, nil } -func (client Client) AddToCache(accountName string, props storage.Account) error { +func (ad *accountDetails) DataPlaneEndpoint(endpointType EndpointType) (*string, error) { + if ad.Properties == nil { + return nil, fmt.Errorf("storage account %q has no properties", ad.name) + } + if ad.Properties.PrimaryEndpoints == nil { + return nil, fmt.Errorf("storage account %q has missing endpoints", ad.name) + } + + var baseUri string + + switch endpointType { + case EndpointTypeBlob: + if ad.Properties.PrimaryEndpoints.Blob != nil { + baseUri = strings.TrimSuffix(*ad.Properties.PrimaryEndpoints.Blob, "/") + } + case EndpointTypeDfs: + if ad.Properties.PrimaryEndpoints.Dfs != nil { + baseUri = strings.TrimSuffix(*ad.Properties.PrimaryEndpoints.Dfs, "/") + } + case EndpointTypeFile: + if ad.Properties.PrimaryEndpoints.File != nil { + baseUri = strings.TrimSuffix(*ad.Properties.PrimaryEndpoints.File, "/") + } + case EndpointTypeQueue: + if ad.Properties.PrimaryEndpoints.Queue != nil { + baseUri = strings.TrimSuffix(*ad.Properties.PrimaryEndpoints.Queue, "/") + } + case EndpointTypeTable: + if ad.Properties.PrimaryEndpoints.Table != nil { + baseUri = strings.TrimSuffix(*ad.Properties.PrimaryEndpoints.Table, "/") + } + default: + return nil, fmt.Errorf("internal-error: unrecognised endpoint type %q when building storage client", endpointType) + } + + if baseUri == "" { + return nil, fmt.Errorf("determining storage account %s endpoint for : %q", endpointType, ad.name) + } + + return &baseUri, nil +} + +func (c Client) AddToCache(accountName string, props storage.Account) error { accountsLock.Lock() defer accountsLock.Unlock() @@ -72,13 +125,13 @@ func (client Client) AddToCache(accountName string, props storage.Account) error return nil } -func (client Client) RemoveAccountFromCache(accountName string) { +func (c Client) RemoveAccountFromCache(accountName string) { accountsLock.Lock() delete(storageAccountsCache, accountName) accountsLock.Unlock() } -func (client Client) FindAccount(ctx context.Context, accountName string) (*accountDetails, error) { +func (c Client) FindAccount(ctx context.Context, accountName string) (*accountDetails, error) { accountsLock.Lock() defer accountsLock.Unlock() @@ -86,7 +139,7 @@ func (client Client) FindAccount(ctx context.Context, accountName string) (*acco return &existing, nil } - accountsPage, err := client.AccountsClient.List(ctx) + accountsPage, err := c.AccountsClient.List(ctx) if err != nil { return nil, fmt.Errorf("retrieving storage accounts: %+v", err) } diff --git a/internal/services/storage/helpers/schema.go b/internal/services/storage/helpers/schema.go new file mode 100644 index 000000000000..5a3909f1f7c7 --- /dev/null +++ b/internal/services/storage/helpers/schema.go @@ -0,0 +1,38 @@ +package helpers + +import ( + "context" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" +) + +type StorageIDValidationFunc func(id, storageDomainSuffix string) error + +// ImporterValidatingStorageResourceId is similar to pluginsdk.ImporterValidatingResourceId whilst additionally passing in +// the storage domain suffix for the current environment/cloud, so that the domain component of the ID can be validated. +func ImporterValidatingStorageResourceId(validateFunc StorageIDValidationFunc) *schema.ResourceImporter { + return ImporterValidatingStorageResourceIdThen(validateFunc, nil) +} + +// ImporterValidatingStorageResourceIdThen is similar to pluginsdk.ImporterValidatingResourceIdThen whilst additionally passing in +// the storage domain suffix for the current environment/cloud, so that the domain component of the ID can be validated. +func ImporterValidatingStorageResourceIdThen(validateFunc StorageIDValidationFunc, thenFunc pluginsdk.ImporterFunc) *schema.ResourceImporter { + return &schema.ResourceImporter{ + StateContext: func(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}) ([]*pluginsdk.ResourceData, error) { + storageDomainSuffix := meta.(*clients.Client).Storage.StorageDomainSuffix + log.Printf("[DEBUG] Importing Storage Resource - parsing %q using domain suffix %q", d.Id(), storageDomainSuffix) + if err := validateFunc(d.Id(), storageDomainSuffix); err != nil { + return []*pluginsdk.ResourceData{d}, err + } + + if thenFunc != nil { + return thenFunc(ctx, d, meta) + } + + return []*pluginsdk.ResourceData{d}, nil + }, + } +} diff --git a/internal/services/storage/migration/share.go b/internal/services/storage/migration/share.go index 6e48a71d3ae9..431069cd4f94 100644 --- a/internal/services/storage/migration/share.go +++ b/internal/services/storage/migration/share.go @@ -12,7 +12,8 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) var _ pluginsdk.StateUpgrade = ShareV0ToV1{} @@ -54,25 +55,28 @@ func (s ShareV1ToV2) UpgradeFunc() pluginsdk.StateUpgraderFunc { // name/resourceGroup/accountName parsedId := strings.Split(id, "/") if len(parsedId) != 3 { - return rawState, fmt.Errorf("Expected 3 segments in the ID but got %d", len(parsedId)) + return rawState, fmt.Errorf("expected 3 segments in the ID but got %d", len(parsedId)) } shareName := parsedId[0] accountName := parsedId[2] - environment := meta.(*clients.Client).Account.AzureEnvironment - client := shares.NewWithEnvironment(environment) + accountId := accounts.AccountId{ + AccountName: accountName, + SubDomainType: "file", + DomainSuffix: meta.(*clients.Client).Storage.StorageDomainSuffix, + } - newResourceId := client.GetResourceID(accountName, shareName) + newResourceId := shares.NewShareID(accountId, shareName) log.Printf("[DEBUG] Updating Resource ID from %q to %q", id, newResourceId) - rawState["id"] = newResourceId + rawState["id"] = newResourceId.ID() return rawState, nil } } -// the schema schema was used for both V0 and V1 +// this schema was used for both V0 and V1 func shareSchemaForV0AndV1() map[string]*pluginsdk.Schema { return map[string]*pluginsdk.Schema{ "name": { diff --git a/internal/services/storage/migration/share_test.go b/internal/services/storage/migration/share_test.go index 6f7496e5b9f0..8484eb67510b 100644 --- a/internal/services/storage/migration/share_test.go +++ b/internal/services/storage/migration/share_test.go @@ -10,7 +10,9 @@ import ( "testing" "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-sdk/sdk/environments" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + storageClient "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" ) func TestShareV0ToV1(t *testing.T) { @@ -59,10 +61,10 @@ func TestShareV0ToV1(t *testing.T) { } func TestShareV1ToV2(t *testing.T) { - clouds := []azure.Environment{ - azure.ChinaCloud, - azure.PublicCloud, - azure.USGovernmentCloud, + clouds := []*environments.Environment{ + environments.AzureChina(), + environments.AzurePublic(), + environments.AzureUSGovernment(), } for _, cloud := range clouds { @@ -76,14 +78,22 @@ func TestShareV1ToV2(t *testing.T) { "quota": 5120, } + storageSuffix, ok := cloud.Storage.DomainSuffix() + if !ok { + t.Fatalf("determining domain suffix for storage in environment: %s", cloud.Name) + } + meta := &clients.Client{ Account: &clients.ResourceManagerAccount{ - AzureEnvironment: cloud, + Environment: *cloud, + }, + Storage: &storageClient.Client{ + StorageDomainSuffix: *storageSuffix, }, } expected := map[string]interface{}{ - "id": fmt.Sprintf("https://account1.file.%s/share1", cloud.StorageEndpointSuffix), + "id": fmt.Sprintf("https://account1.file.%s/share1", *storageSuffix), "name": "share1", "resource_group_name": "group1", "storage_account_name": "account1", diff --git a/internal/services/storage/parse/storage_container_data_plane.go b/internal/services/storage/parse/storage_container_data_plane.go deleted file mode 100644 index 47dc25a7ec8c..000000000000 --- a/internal/services/storage/parse/storage_container_data_plane.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -import ( - "fmt" - "net/url" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" -) - -var _ resourceids.Id = StorageContainerDataPlaneId{} - -type StorageContainerDataPlaneId struct { - AccountName string - DomainSuffix string - Name string -} - -func (id StorageContainerDataPlaneId) String() string { - components := []string{ - fmt.Sprintf("Account Name %q", id.AccountName), - fmt.Sprintf("Domain Suffix %q", id.DomainSuffix), - fmt.Sprintf("Name %q", id.Name), - } - return fmt.Sprintf("Storage Container %s", strings.Join(components, " / ")) -} - -func (id StorageContainerDataPlaneId) ID() string { - return fmt.Sprintf("https://%s.blob.%s/%s", id.AccountName, id.DomainSuffix, id.Name) -} - -func NewStorageContainerDataPlaneId(accountName, domainSuffix, name string) StorageContainerDataPlaneId { - return StorageContainerDataPlaneId{ - AccountName: accountName, - DomainSuffix: domainSuffix, - Name: name, - } -} - -func StorageContainerDataPlaneID(id string) (*StorageContainerDataPlaneId, error) { - parsed, err := containers.ParseResourceID(id) - if err != nil { - return nil, err - } - - uri, err := url.Parse(id) - if err != nil { - return nil, err - } - - host := uri.Host - hostSegments := strings.Split(host, ".") - if len(hostSegments) == 0 { - return nil, fmt.Errorf("expected multiple host segments but got 0") - } - domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.blob.", hostSegments[0])) - - return &StorageContainerDataPlaneId{ - AccountName: parsed.AccountName, - DomainSuffix: domainNameSuffix, - Name: parsed.ContainerName, - }, nil -} diff --git a/internal/services/storage/parse/storage_queue_data_plane.go b/internal/services/storage/parse/storage_queue_data_plane.go deleted file mode 100644 index 3fd6770ec093..000000000000 --- a/internal/services/storage/parse/storage_queue_data_plane.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -import ( - "fmt" - "net/url" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" -) - -var _ resourceids.Id = StorageQueueDataPlaneId{} - -type StorageQueueDataPlaneId struct { - AccountName string - DomainSuffix string - Name string -} - -func (id StorageQueueDataPlaneId) String() string { - components := []string{ - fmt.Sprintf("Account Name %q", id.AccountName), - fmt.Sprintf("Domain Suffix %q", id.DomainSuffix), - fmt.Sprintf("Name %q", id.Name), - } - return fmt.Sprintf("Storage Queue %s", strings.Join(components, " / ")) -} - -func (id StorageQueueDataPlaneId) ID() string { - return fmt.Sprintf("https://%s.queue.%s/%s", id.AccountName, id.DomainSuffix, id.Name) -} - -func NewStorageQueueDataPlaneId(accountName, domainSuffix, name string) StorageQueueDataPlaneId { - return StorageQueueDataPlaneId{ - AccountName: accountName, - DomainSuffix: domainSuffix, - Name: name, - } -} - -func StorageQueueDataPlaneID(id string) (*StorageQueueDataPlaneId, error) { - parsed, err := queues.ParseResourceID(id) - if err != nil { - return nil, err - } - - uri, err := url.Parse(id) - if err != nil { - return nil, err - } - - host := uri.Host - hostSegments := strings.Split(host, ".") - if len(hostSegments) == 0 { - return nil, fmt.Errorf("expected multiple host segments but got 0") - } - domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.queue.", hostSegments[0])) - - return &StorageQueueDataPlaneId{ - AccountName: parsed.AccountName, - DomainSuffix: domainNameSuffix, - Name: parsed.QueueName, - }, nil -} diff --git a/internal/services/storage/parse/storage_share_data_plane.go b/internal/services/storage/parse/storage_share_data_plane.go deleted file mode 100644 index 321fff4a7a8f..000000000000 --- a/internal/services/storage/parse/storage_share_data_plane.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -import ( - "fmt" - "net/url" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" -) - -// TODO: tests for this -var _ resourceids.Id = StorageShareDataPlaneId{} - -type StorageShareDataPlaneId struct { - AccountName string - DomainSuffix string - Name string -} - -func (id StorageShareDataPlaneId) String() string { - components := []string{ - fmt.Sprintf("Account Name %q", id.AccountName), - fmt.Sprintf("Domain Suffix %q", id.DomainSuffix), - fmt.Sprintf("Name %q", id.Name), - } - return fmt.Sprintf("Storage Share (%s)", strings.Join(components, " / ")) -} - -func (id StorageShareDataPlaneId) ID() string { - return fmt.Sprintf("https://%s.file.%s/%s", id.AccountName, id.DomainSuffix, id.Name) -} - -func NewStorageShareDataPlaneId(accountName, domainSuffix, name string) StorageShareDataPlaneId { - return StorageShareDataPlaneId{ - AccountName: accountName, - DomainSuffix: domainSuffix, - Name: name, - } -} - -func StorageShareDataPlaneID(id string) (*StorageShareDataPlaneId, error) { - parsed, err := shares.ParseResourceID(id) - if err != nil { - return nil, err - } - - uri, err := url.Parse(id) - if err != nil { - return nil, err - } - - host := uri.Host - hostSegments := strings.Split(host, ".") - if len(hostSegments) == 0 { - return nil, fmt.Errorf("expected multiple host segments but got 0") - } - domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.file.", hostSegments[0])) - - return &StorageShareDataPlaneId{ - AccountName: parsed.AccountName, - DomainSuffix: domainNameSuffix, - Name: parsed.ShareName, - }, nil -} diff --git a/internal/services/storage/parse/storage_table_data_plane.go b/internal/services/storage/parse/storage_table_data_plane.go deleted file mode 100644 index bf668f89f317..000000000000 --- a/internal/services/storage/parse/storage_table_data_plane.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -import ( - "fmt" - "net/url" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" -) - -// TODO: tests for this -var _ resourceids.Id = StorageTableDataPlaneId{} - -type StorageTableDataPlaneId struct { - AccountName string - DomainSuffix string - Name string -} - -func (id StorageTableDataPlaneId) String() string { - components := []string{ - fmt.Sprintf("Account Name %q", id.AccountName), - fmt.Sprintf("Domain Suffix %q", id.DomainSuffix), - fmt.Sprintf("Name %q", id.Name), - } - return fmt.Sprintf("Storage Table %s", strings.Join(components, " / ")) -} - -func (id StorageTableDataPlaneId) ID() string { - return fmt.Sprintf("https://%s.table.%s/Tables('%s')", id.AccountName, id.DomainSuffix, id.Name) -} - -func NewStorageTableDataPlaneId(accountName, domainSuffix, name string) StorageTableDataPlaneId { - return StorageTableDataPlaneId{ - AccountName: accountName, - DomainSuffix: domainSuffix, - Name: name, - } -} - -func StorageTableDataPlaneID(input string) (*StorageTableDataPlaneId, error) { - parsed, err := tables.ParseResourceID(input) - if err != nil { - return nil, err - } - - uri, err := url.Parse(input) - if err != nil { - return nil, err - } - - host := uri.Host - hostSegments := strings.Split(host, ".") - if len(hostSegments) == 0 { - return nil, fmt.Errorf("expected multiple host segments but got 0") - } - domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.table.", hostSegments[0])) - - return &StorageTableDataPlaneId{ - AccountName: parsed.AccountName, - DomainSuffix: domainNameSuffix, - Name: parsed.TableName, - }, nil -} diff --git a/internal/services/storage/parse/storage_table_entities.go b/internal/services/storage/parse/storage_table_entities.go index 4c18c883d341..5d4fa0caf755 100644 --- a/internal/services/storage/parse/storage_table_entities.go +++ b/internal/services/storage/parse/storage_table_entities.go @@ -16,6 +16,7 @@ import ( // TODO: tests for this var _ resourceids.Id = StorageTableEntitiesId{} +// StorageTableEntitiesId is used by the plural data source azurerm_storage_table_entities type StorageTableEntitiesId struct { AccountName string DomainSuffix string @@ -37,14 +38,14 @@ func (id StorageTableEntitiesId) ID() string { return fmt.Sprintf("https://%s.table.%s/%s(%s)", id.AccountName, id.DomainSuffix, id.TableName, id.Filter) } -func NewStorageTableEntitiesId(accountName, domainSuffix, tablename, filter string) StorageTableEntitiesId { +func NewStorageTableEntitiesId(accountName, domainSuffix, tableName, filter string) StorageTableEntitiesId { s := utils.Base64EncodeIfNot(filter) sha := sha1.Sum([]byte(s)) filterHash := hex.EncodeToString(sha[:]) return StorageTableEntitiesId{ AccountName: accountName, DomainSuffix: domainSuffix, - TableName: tablename, + TableName: tableName, Filter: filterHash, } } diff --git a/internal/services/storage/shim/containers.go b/internal/services/storage/shim/containers.go index 55156bb5d9f3..c29325ce4aa2 100644 --- a/internal/services/storage/shim/containers.go +++ b/internal/services/storage/shim/containers.go @@ -6,16 +6,16 @@ package shim import ( "context" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) type StorageContainerWrapper interface { - Create(ctx context.Context, resourceGroup, accountName, containerName string, input containers.CreateInput) error - Delete(ctx context.Context, resourceGroup, accountName, containerName string) error - Exists(ctx context.Context, resourceGroup, accountName, containerName string) (*bool, error) - Get(ctx context.Context, resourceGroup, accountName, containerName string) (*StorageContainerProperties, error) - UpdateAccessLevel(ctx context.Context, resourceGroup, accountName, containerName string, level containers.AccessLevel) error - UpdateMetaData(ctx context.Context, resourceGroup, accountName, containerName string, metadata map[string]string) error + Create(ctx context.Context, containerName string, input containers.CreateInput) error + Delete(ctx context.Context, containerName string) error + Exists(ctx context.Context, containerName string) (*bool, error) + Get(ctx context.Context, containerName string) (*StorageContainerProperties, error) + UpdateAccessLevel(ctx context.Context, containerName string, level containers.AccessLevel) error + UpdateMetaData(ctx context.Context, containerName string, metaData map[string]string) error } type StorageContainerProperties struct { diff --git a/internal/services/storage/shim/containers_data_plane.go b/internal/services/storage/shim/containers_data_plane.go index 2310188f5230..e365ef9819fb 100644 --- a/internal/services/storage/shim/containers_data_plane.go +++ b/internal/services/storage/shim/containers_data_plane.go @@ -6,12 +6,10 @@ package shim import ( "context" "fmt" - "strings" - "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) type DataPlaneStorageContainerWrapper struct { @@ -24,59 +22,37 @@ func NewDataPlaneStorageContainerWrapper(client *containers.Client) StorageConta } } -func (w DataPlaneStorageContainerWrapper) Create(ctx context.Context, _, accountName, containerName string, input containers.CreateInput) error { - timeout, ok := ctx.Deadline() - if !ok { - return fmt.Errorf("context is missing a timeout") - } - - if resp, err := w.client.Create(ctx, accountName, containerName, input); err != nil { - // If we fail due to previous delete still in progress, then we can retry - if utils.ResponseWasConflict(resp.Response) && strings.Contains(err.Error(), "ContainerBeingDeleted") { - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"waitingOnDelete"}, - Target: []string{"succeeded"}, - Refresh: w.createRefreshFunc(ctx, accountName, containerName, input), - PollInterval: 10 * time.Second, - NotFoundChecks: 180, - Timeout: time.Until(timeout), - } - - if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("failed creating container: %+v", err) - } - } else { - return fmt.Errorf("failed creating container: %+v", err) - } +func (w DataPlaneStorageContainerWrapper) Create(ctx context.Context, containerName string, input containers.CreateInput) error { + if _, err := w.client.Create(ctx, containerName, input); err != nil { + return fmt.Errorf("creating container: %+v", err) } return nil } -func (w DataPlaneStorageContainerWrapper) Delete(ctx context.Context, _, accountName, containerName string) error { - resp, err := w.client.Delete(ctx, accountName, containerName) - if utils.ResponseWasNotFound(resp) { +func (w DataPlaneStorageContainerWrapper) Delete(ctx context.Context, containerName string) error { + resp, err := w.client.Delete(ctx, containerName) + if response.WasNotFound(resp.HttpResponse) { return nil } return err } -func (w DataPlaneStorageContainerWrapper) Exists(ctx context.Context, _, accountName, containerName string) (*bool, error) { - existing, err := w.client.GetProperties(ctx, accountName, containerName) +func (w DataPlaneStorageContainerWrapper) Exists(ctx context.Context, containerName string) (*bool, error) { + existing, err := w.client.GetProperties(ctx, containerName, containers.GetPropertiesInput{}) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return nil, err + if response.WasNotFound(existing.HttpResponse) { + return pointer.To(false), nil } + return nil, err } - - exists := !utils.ResponseWasNotFound(existing.Response) - return &exists, nil + return pointer.To(true), nil } -func (w DataPlaneStorageContainerWrapper) Get(ctx context.Context, _, accountName, containerName string) (*StorageContainerProperties, error) { - props, err := w.client.GetProperties(ctx, accountName, containerName) +func (w DataPlaneStorageContainerWrapper) Get(ctx context.Context, containerName string) (*StorageContainerProperties, error) { + props, err := w.client.GetProperties(ctx, containerName, containers.GetPropertiesInput{}) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse) { return nil, nil } @@ -91,29 +67,18 @@ func (w DataPlaneStorageContainerWrapper) Get(ctx context.Context, _, accountNam }, nil } -func (w DataPlaneStorageContainerWrapper) UpdateAccessLevel(ctx context.Context, _, accountName, containerName string, level containers.AccessLevel) error { - _, err := w.client.SetAccessControl(ctx, accountName, containerName, level) - return err -} - -func (w DataPlaneStorageContainerWrapper) UpdateMetaData(ctx context.Context, _, accountName, containerName string, metaData map[string]string) error { - _, err := w.client.SetMetaData(ctx, accountName, containerName, metaData) +func (w DataPlaneStorageContainerWrapper) UpdateAccessLevel(ctx context.Context, containerName string, level containers.AccessLevel) error { + input := containers.SetAccessControlInput{ + AccessLevel: level, + } + _, err := w.client.SetAccessControl(ctx, containerName, input) return err } -func (w DataPlaneStorageContainerWrapper) createRefreshFunc(ctx context.Context, accountName string, containerName string, input containers.CreateInput) pluginsdk.StateRefreshFunc { - return func() (interface{}, string, error) { - resp, err := w.client.Create(ctx, accountName, containerName, input) - if err != nil { - if !utils.ResponseWasConflict(resp.Response) { - return nil, "", err - } - - if utils.ResponseWasConflict(resp.Response) && strings.Contains(err.Error(), "ContainerBeingDeleted") { - return nil, "waitingOnDelete", nil - } - } - - return "succeeded", "succeeded", nil +func (w DataPlaneStorageContainerWrapper) UpdateMetaData(ctx context.Context, containerName string, metaData map[string]string) error { + input := containers.SetMetaDataInput{ + MetaData: metaData, } + _, err := w.client.SetMetaData(ctx, containerName, input) + return err } diff --git a/internal/services/storage/shim/queues.go b/internal/services/storage/shim/queues.go index d145093014b0..d6d1d4e432c9 100644 --- a/internal/services/storage/shim/queues.go +++ b/internal/services/storage/shim/queues.go @@ -6,17 +6,17 @@ package shim import ( "context" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues" ) type StorageQueuesWrapper interface { - Create(ctx context.Context, resourceGroup, accountName, queueName string, metaData map[string]string) error - Delete(ctx context.Context, resourceGroup, accountName, queueName string) error - Exists(ctx context.Context, resourceGroup, accountName, queueName string) (*bool, error) - Get(ctx context.Context, resourceGroup, accountName, queueName string) (*StorageQueueProperties, error) - GetServiceProperties(ctx context.Context, resourceGroup, accountName string) (*queues.StorageServiceProperties, error) - UpdateMetaData(ctx context.Context, resourceGroup, accountName, queueName string, metaData map[string]string) error - UpdateServiceProperties(ctx context.Context, resourceGroup, accountName string, properties queues.StorageServiceProperties) error + Create(ctx context.Context, queueName string, metaData map[string]string) error + Delete(ctx context.Context, queueName string) error + Exists(ctx context.Context, queueName string) (*bool, error) + Get(ctx context.Context, queueName string) (*StorageQueueProperties, error) + GetServiceProperties(ctx context.Context) (*queues.StorageServiceProperties, error) + UpdateMetaData(ctx context.Context, queueName string, metaData map[string]string) error + UpdateServiceProperties(ctx context.Context, properties queues.StorageServiceProperties) error } type StorageQueueProperties struct { diff --git a/internal/services/storage/shim/queues_data_plane.go b/internal/services/storage/shim/queues_data_plane.go index 3052f205761a..8b52b1e9d068 100644 --- a/internal/services/storage/shim/queues_data_plane.go +++ b/internal/services/storage/shim/queues_data_plane.go @@ -6,8 +6,9 @@ package shim import ( "context" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues" ) type DataPlaneStorageQueueWrapper struct { @@ -20,32 +21,34 @@ func NewDataPlaneStorageQueueWrapper(client *queues.Client) StorageQueuesWrapper } } -func (w DataPlaneStorageQueueWrapper) Create(ctx context.Context, _, accountName, queueName string, metaData map[string]string) error { - _, err := w.client.Create(ctx, accountName, queueName, metaData) +func (w DataPlaneStorageQueueWrapper) Create(ctx context.Context, queueName string, metaData map[string]string) error { + input := queues.CreateInput{ + MetaData: metaData, + } + _, err := w.client.Create(ctx, queueName, input) return err } -func (w DataPlaneStorageQueueWrapper) Delete(ctx context.Context, _, accountName, queueName string) error { - _, err := w.client.Delete(ctx, accountName, queueName) +func (w DataPlaneStorageQueueWrapper) Delete(ctx context.Context, queueName string) error { + _, err := w.client.Delete(ctx, queueName) return err } -func (w DataPlaneStorageQueueWrapper) Exists(ctx context.Context, _, accountName, queueName string) (*bool, error) { - existing, err := w.client.GetMetaData(ctx, accountName, queueName) +func (w DataPlaneStorageQueueWrapper) Exists(ctx context.Context, queueName string) (*bool, error) { + existing, err := w.client.GetMetaData(ctx, queueName) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { - return utils.Bool(false), nil + if response.WasNotFound(existing.HttpResponse) { + return pointer.To(false), nil } return nil, err } - - return utils.Bool(true), nil + return pointer.To(true), nil } -func (w DataPlaneStorageQueueWrapper) Get(ctx context.Context, _, accountName, queueName string) (*StorageQueueProperties, error) { - props, err := w.client.GetMetaData(ctx, accountName, queueName) +func (w DataPlaneStorageQueueWrapper) Get(ctx context.Context, queueName string) (*StorageQueueProperties, error) { + props, err := w.client.GetMetaData(ctx, queueName) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse) { return nil, nil } return nil, err @@ -56,10 +59,10 @@ func (w DataPlaneStorageQueueWrapper) Get(ctx context.Context, _, accountName, q }, nil } -func (w DataPlaneStorageQueueWrapper) GetServiceProperties(ctx context.Context, resourceGroup, accountName string) (*queues.StorageServiceProperties, error) { - serviceProps, err := w.client.GetServiceProperties(ctx, accountName) +func (w DataPlaneStorageQueueWrapper) GetServiceProperties(ctx context.Context) (*queues.StorageServiceProperties, error) { + serviceProps, err := w.client.GetServiceProperties(ctx) if err != nil { - if utils.ResponseWasNotFound(serviceProps.Response) { + if response.WasNotFound(serviceProps.HttpResponse) { return nil, nil } return nil, err @@ -68,12 +71,18 @@ func (w DataPlaneStorageQueueWrapper) GetServiceProperties(ctx context.Context, return &serviceProps.StorageServiceProperties, nil } -func (w DataPlaneStorageQueueWrapper) UpdateMetaData(ctx context.Context, _, accountName, queueName string, metaData map[string]string) error { - _, err := w.client.SetMetaData(ctx, accountName, queueName, metaData) +func (w DataPlaneStorageQueueWrapper) UpdateMetaData(ctx context.Context, queueName string, metaData map[string]string) error { + input := queues.SetMetaDataInput{ + MetaData: metaData, + } + _, err := w.client.SetMetaData(ctx, queueName, input) return err } -func (w DataPlaneStorageQueueWrapper) UpdateServiceProperties(ctx context.Context, _, accountName string, properties queues.StorageServiceProperties) error { - _, err := w.client.SetServiceProperties(ctx, accountName, properties) +func (w DataPlaneStorageQueueWrapper) UpdateServiceProperties(ctx context.Context, properties queues.StorageServiceProperties) error { + input := queues.SetStorageServicePropertiesInput{ + Properties: properties, + } + _, err := w.client.SetServiceProperties(ctx, input) return err } diff --git a/internal/services/storage/shim/shares.go b/internal/services/storage/shim/shares.go index 702e34b492b2..375595520e30 100644 --- a/internal/services/storage/shim/shares.go +++ b/internal/services/storage/shim/shares.go @@ -6,18 +6,18 @@ package shim import ( "context" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) type StorageShareWrapper interface { - Create(ctx context.Context, resourceGroup, accountName, shareName string, input shares.CreateInput) error - Delete(ctx context.Context, resourceGroup, accountName, shareName string) error - Exists(ctx context.Context, resourceGroup, accountName, shareName string) (*bool, error) - Get(ctx context.Context, resourceGroup, accountName, shareName string) (*StorageShareProperties, error) - UpdateACLs(ctx context.Context, resourceGroup, accountName, shareName string, acls []shares.SignedIdentifier) error - UpdateMetaData(ctx context.Context, resourceGroup, accountName, shareName string, metaData map[string]string) error - UpdateQuota(ctx context.Context, resourceGroup, accountName, shareName string, quotaGB int) error - UpdateTier(ctx context.Context, resourceGroup, accountName, shareName string, tier shares.AccessTier) error + Create(ctx context.Context, shareName string, input shares.CreateInput) error + Delete(ctx context.Context, shareName string) error + Exists(ctx context.Context, shareName string) (*bool, error) + Get(ctx context.Context, shareName string) (*StorageShareProperties, error) + UpdateACLs(ctx context.Context, shareName string, input shares.SetAclInput) error + UpdateMetaData(ctx context.Context, shareName string, metaData map[string]string) error + UpdateQuota(ctx context.Context, shareName string, quotaGB int) error + UpdateTier(ctx context.Context, shareName string, tier shares.AccessTier) error } type StorageShareProperties struct { diff --git a/internal/services/storage/shim/shares_data_plane.go b/internal/services/storage/shim/shares_data_plane.go index ae88b650cd55..a251059fd1b3 100644 --- a/internal/services/storage/shim/shares_data_plane.go +++ b/internal/services/storage/shim/shares_data_plane.go @@ -6,12 +6,10 @@ package shim import ( "context" "fmt" - "strings" - "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) type DataPlaneStorageShareWrapper struct { @@ -24,66 +22,43 @@ func NewDataPlaneStorageShareWrapper(client *shares.Client) StorageShareWrapper } } -func (w DataPlaneStorageShareWrapper) Create(ctx context.Context, _, accountName, shareName string, input shares.CreateInput) error { - timeout, ok := ctx.Deadline() - if !ok { - return fmt.Errorf("context is missing a timeout") +func (w DataPlaneStorageShareWrapper) Create(ctx context.Context, shareName string, input shares.CreateInput) error { + if _, err := w.client.Create(ctx, shareName, input); err != nil { + return fmt.Errorf("creating share: %+v", err) } - - resp, err := w.client.Create(ctx, accountName, shareName, input) - if err == nil { - return nil - } - - // If we fail due to previous delete still in progress, then we can retry - if utils.ResponseWasConflict(resp) && strings.Contains(err.Error(), "ShareBeingDeleted") { - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"waitingOnDelete"}, - Target: []string{"succeeded"}, - Refresh: w.createRefreshFunc(ctx, accountName, shareName, input), - PollInterval: 10 * time.Second, - NotFoundChecks: 180, - Timeout: time.Until(timeout), - } - - _, err := stateConf.WaitForStateContext(ctx) - return err - } - - // otherwise it's a legit error, so raise it - return err + return nil } -func (w DataPlaneStorageShareWrapper) Delete(ctx context.Context, _, accountName, shareName string) error { - deleteSnapshots := true - _, err := w.client.Delete(ctx, accountName, shareName, deleteSnapshots) +func (w DataPlaneStorageShareWrapper) Delete(ctx context.Context, shareName string) error { + input := shares.DeleteInput{ + DeleteSnapshots: true, + } + _, err := w.client.Delete(ctx, shareName, input) return err } -func (w DataPlaneStorageShareWrapper) Exists(ctx context.Context, _, accountName, shareName string) (*bool, error) { - existing, err := w.client.GetProperties(ctx, accountName, shareName) +func (w DataPlaneStorageShareWrapper) Exists(ctx context.Context, shareName string) (*bool, error) { + existing, err := w.client.GetProperties(ctx, shareName) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { - return nil, nil + if response.WasNotFound(existing.HttpResponse) { + return pointer.To(false), nil } - return nil, err } - - return utils.Bool(true), nil + return pointer.To(true), nil } -func (w DataPlaneStorageShareWrapper) Get(ctx context.Context, _, accountName, shareName string) (*StorageShareProperties, error) { - props, err := w.client.GetProperties(ctx, accountName, shareName) +func (w DataPlaneStorageShareWrapper) Get(ctx context.Context, shareName string) (*StorageShareProperties, error) { + props, err := w.client.GetProperties(ctx, shareName) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse) { return nil, nil } return nil, err } - acls, err := w.client.GetACL(ctx, accountName, shareName) + acls, err := w.client.GetACL(ctx, shareName) if err != nil { return nil, err } @@ -97,44 +72,30 @@ func (w DataPlaneStorageShareWrapper) Get(ctx context.Context, _, accountName, s }, nil } -func (w DataPlaneStorageShareWrapper) UpdateACLs(ctx context.Context, _, accountName, shareName string, acls []shares.SignedIdentifier) error { - _, err := w.client.SetACL(ctx, accountName, shareName, acls) +func (w DataPlaneStorageShareWrapper) UpdateACLs(ctx context.Context, shareName string, input shares.SetAclInput) error { + _, err := w.client.SetACL(ctx, shareName, input) return err } -func (w DataPlaneStorageShareWrapper) UpdateMetaData(ctx context.Context, _, accountName, shareName string, metaData map[string]string) error { - _, err := w.client.SetMetaData(ctx, accountName, shareName, metaData) +func (w DataPlaneStorageShareWrapper) UpdateMetaData(ctx context.Context, shareName string, metaData map[string]string) error { + input := shares.SetMetaDataInput{ + MetaData: metaData, + } + _, err := w.client.SetMetaData(ctx, shareName, input) return err } -func (w DataPlaneStorageShareWrapper) UpdateQuota(ctx context.Context, _, accountName, shareName string, quotaGB int) error { - _, err := w.client.SetProperties(ctx, accountName, shareName, shares.ShareProperties{ +func (w DataPlaneStorageShareWrapper) UpdateQuota(ctx context.Context, shareName string, quotaGB int) error { + _, err := w.client.SetProperties(ctx, shareName, shares.ShareProperties{ QuotaInGb: "aGB, }) return err } -func (w DataPlaneStorageShareWrapper) UpdateTier(ctx context.Context, _, accountname, shareName string, tier shares.AccessTier) error { +func (w DataPlaneStorageShareWrapper) UpdateTier(ctx context.Context, shareName string, tier shares.AccessTier) error { props := shares.ShareProperties{ AccessTier: &tier, } - _, err := w.client.SetProperties(ctx, accountname, shareName, props) + _, err := w.client.SetProperties(ctx, shareName, props) return err } - -func (w DataPlaneStorageShareWrapper) createRefreshFunc(ctx context.Context, accountName string, shareName string, input shares.CreateInput) pluginsdk.StateRefreshFunc { - return func() (interface{}, string, error) { - resp, err := w.client.Create(ctx, accountName, shareName, input) - if err != nil { - if !utils.ResponseWasConflict(resp) { - return nil, "", err - } - - if utils.ResponseWasConflict(resp) && strings.Contains(err.Error(), "ShareBeingDeleted") { - return nil, "waitingOnDelete", nil - } - } - - return "succeeded", "succeeded", nil - } -} diff --git a/internal/services/storage/shim/tables.go b/internal/services/storage/shim/tables.go index f928d83fcea0..0734e971a046 100644 --- a/internal/services/storage/shim/tables.go +++ b/internal/services/storage/shim/tables.go @@ -6,13 +6,13 @@ package shim import ( "context" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables" ) type StorageTableWrapper interface { - Create(ctx context.Context, resourceGroup string, accountName string, tableName string) error - Delete(ctx context.Context, resourceGroup string, accountName string, tableName string) error - Exists(ctx context.Context, resourceGroup string, accountName string, tableName string) (*bool, error) - GetACLs(ctx context.Context, resourceGroup string, accountName string, tableName string) (*[]tables.SignedIdentifier, error) - UpdateACLs(ctx context.Context, resourceGroup string, accountName string, tableName string, acls []tables.SignedIdentifier) error + Create(ctx context.Context, tableName string) error + Delete(ctx context.Context, tableName string) error + Exists(ctx context.Context, tableName string) (*bool, error) + GetACLs(ctx context.Context, tableName string) (*[]tables.SignedIdentifier, error) + UpdateACLs(ctx context.Context, tableName string, acls []tables.SignedIdentifier) error } diff --git a/internal/services/storage/shim/tables_data_plane.go b/internal/services/storage/shim/tables_data_plane.go index f8a998f06069..447fca894677 100644 --- a/internal/services/storage/shim/tables_data_plane.go +++ b/internal/services/storage/shim/tables_data_plane.go @@ -6,8 +6,9 @@ package shim import ( "context" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables" ) type DataPlaneStorageTableWrapper struct { @@ -20,31 +21,29 @@ func NewDataPlaneStorageTableWrapper(client *tables.Client) StorageTableWrapper } } -func (w DataPlaneStorageTableWrapper) Create(ctx context.Context, _, accountName, tableName string) error { - _, err := w.client.Create(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) Create(ctx context.Context, tableName string) error { + _, err := w.client.Create(ctx, tableName) return err } -func (w DataPlaneStorageTableWrapper) Delete(ctx context.Context, _, accountName, tableName string) error { - _, err := w.client.Delete(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) Delete(ctx context.Context, tableName string) error { + _, err := w.client.Delete(ctx, tableName) return err } -func (w DataPlaneStorageTableWrapper) Exists(ctx context.Context, _, accountName, tableName string) (*bool, error) { - existing, err := w.client.Exists(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) Exists(ctx context.Context, tableName string) (*bool, error) { + existing, err := w.client.Exists(ctx, tableName) if err != nil { - if utils.ResponseWasNotFound(existing) { - return nil, nil + if response.WasNotFound(existing.HttpResponse) { + return pointer.To(false), nil } - return nil, err } - - return utils.Bool(true), nil + return pointer.To(true), nil } -func (w DataPlaneStorageTableWrapper) GetACLs(ctx context.Context, _, accountName, tableName string) (*[]tables.SignedIdentifier, error) { - acls, err := w.client.GetACL(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) GetACLs(ctx context.Context, tableName string) (*[]tables.SignedIdentifier, error) { + acls, err := w.client.GetACL(ctx, tableName) if err != nil { return nil, err } @@ -52,7 +51,7 @@ func (w DataPlaneStorageTableWrapper) GetACLs(ctx context.Context, _, accountNam return &acls.SignedIdentifiers, nil } -func (w DataPlaneStorageTableWrapper) UpdateACLs(ctx context.Context, _, accountName, tableName string, acls []tables.SignedIdentifier) error { - _, err := w.client.SetACL(ctx, accountName, tableName, acls) +func (w DataPlaneStorageTableWrapper) UpdateACLs(ctx context.Context, tableName string, acls []tables.SignedIdentifier) error { + _, err := w.client.SetACL(ctx, tableName, acls) return err } diff --git a/internal/services/storage/storage_account_resource.go b/internal/services/storage/storage_account_resource.go index cb95fc31c2dd..9e91d1172a17 100644 --- a/internal/services/storage/storage_account_resource.go +++ b/internal/services/storage/storage_account_resource.go @@ -40,8 +40,8 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues" ) var ( @@ -1310,7 +1310,7 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e existing, err := client.GetProperties(ctx, id.ResourceGroupName, id.StorageAccountName, "") if err != nil { if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %s", id, err) + return fmt.Errorf("checking for existing %s: %s", id, err) } } @@ -1585,16 +1585,15 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e if !supportLevel.supportQueue { return fmt.Errorf("`queue_properties` aren't supported for account kind %q in sku tier %q", accountKind, accountTier) } - storageClient := meta.(*clients.Client).Storage - account, err := storageClient.FindAccount(ctx, id.StorageAccountName) + accountDetails, err := storageClient.FindAccount(ctx, id.StorageAccountName) if err != nil { return fmt.Errorf("retrieving %s: %+v", id, err) } - if account == nil { + if accountDetails == nil { return fmt.Errorf("unable to locate %q", id) } - queueClient, err := storageClient.QueuesClient(ctx, *account) + queueClient, err := storageClient.QueuesDataPlaneClient(ctx, *accountDetails, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Queues Client: %s", err) } @@ -1604,7 +1603,7 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("expanding `queue_properties`: %+v", err) } - if err = queueClient.UpdateServiceProperties(ctx, id.ResourceGroupName, id.StorageAccountName, queueProperties); err != nil { + if err = queueClient.UpdateServiceProperties(ctx, queueProperties); err != nil { return fmt.Errorf("updating Queue Properties: %+v", err) } } @@ -1641,7 +1640,6 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e if !supportLevel.supportStaticWebsite { return fmt.Errorf("`static_website` aren't supported for account kind %q in sku tier %q", accountKind, accountTier) } - storageClient := meta.(*clients.Client).Storage account, err := storageClient.FindAccount(ctx, id.StorageAccountName) if err != nil { @@ -1651,7 +1649,7 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("unable to locate %s", id) } - accountsClient, err := storageClient.AccountsDataPlaneClient(ctx, *account) + accountsClient, err := storageClient.AccountsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Accounts Data Plane Client: %s", err) } @@ -1689,7 +1687,7 @@ func resourceStorageAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) e if accountKind == string(storage.KindBlobStorage) || accountKind == string(storage.KindStorage) { if storageType == string(storage.SkuNameStandardZRS) { - return fmt.Errorf("a `account_replication_type` of `ZRS` isn't supported for Blob Storage accounts") + return fmt.Errorf("an `account_replication_type` of `ZRS` isn't supported for Blob Storage accounts") } } @@ -1957,7 +1955,7 @@ func resourceStorageAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("unable to locate %s", *id) } - queueClient, err := storageClient.QueuesClient(ctx, *account) + queueClient, err := storageClient.QueuesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Queues Client: %s", err) } @@ -1967,7 +1965,7 @@ func resourceStorageAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("expanding `queue_properties` for %s: %+v", *id, err) } - if err = queueClient.UpdateServiceProperties(ctx, account.ResourceGroup, id.StorageAccountName, queueProperties); err != nil { + if err = queueClient.UpdateServiceProperties(ctx, queueProperties); err != nil { return fmt.Errorf("updating Queue Properties for %s: %+v", *id, err) } } @@ -2012,7 +2010,7 @@ func resourceStorageAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("unable to locate %s", *id) } - accountsClient, err := storageClient.AccountsDataPlaneClient(ctx, *account) + accountsClient, err := storageClient.AccountsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Data Plane client for %s: %+v", *id, err) } @@ -2298,12 +2296,12 @@ func resourceStorageAccountRead(d *pluginsdk.ResourceData, meta interface{}) err } if supportLevel.supportQueue { - queueClient, err := storageClient.QueuesClient(ctx, *account) + queueClient, err := storageClient.QueuesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Queues Client: %s", err) } - queueProps, err := queueClient.GetServiceProperties(ctx, id.ResourceGroupName, id.StorageAccountName) + queueProps, err := queueClient.GetServiceProperties(ctx) if err != nil { return fmt.Errorf("retrieving queue properties for %s: %+v", *id, err) } @@ -2327,13 +2325,7 @@ func resourceStorageAccountRead(d *pluginsdk.ResourceData, meta interface{}) err } if supportLevel.supportStaticWebsite { - storageClient := meta.(*clients.Client).Storage - account, err := storageClient.FindAccount(ctx, id.StorageAccountName) - if err != nil { - return fmt.Errorf("retrieving %s: %+v", *id, err) - } - - accountsClient, err := storageClient.AccountsDataPlaneClient(ctx, *account) + accountsClient, err := storageClient.AccountsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Accounts Data Plane Client: %s", err) } @@ -3628,18 +3620,16 @@ func flattenedSharePropertiesSMB(input *storage.SmbSetting) []interface{} { } func flattenStaticWebsiteProperties(input accounts.GetServicePropertiesResult) []interface{} { - if storageServiceProps := input.StorageServiceProperties; storageServiceProps != nil { - if staticWebsite := storageServiceProps.StaticWebsite; staticWebsite != nil { - if !staticWebsite.Enabled { - return []interface{}{} - } + if staticWebsite := input.StaticWebsite; staticWebsite != nil { + if !staticWebsite.Enabled { + return []interface{}{} + } - return []interface{}{ - map[string]interface{}{ - "index_document": staticWebsite.IndexDocument, - "error_404_document": staticWebsite.ErrorDocument404Path, - }, - } + return []interface{}{ + map[string]interface{}{ + "index_document": staticWebsite.IndexDocument, + "error_404_document": staticWebsite.ErrorDocument404Path, + }, } } return []interface{}{} diff --git a/internal/services/storage/storage_blob_data_source.go b/internal/services/storage/storage_blob_data_source.go index cbe1c2a1b655..314284c5b298 100644 --- a/internal/services/storage/storage_blob_data_source.go +++ b/internal/services/storage/storage_blob_data_source.go @@ -9,11 +9,12 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" ) func dataSourceStorageBlob() *pluginsdk.Resource { @@ -82,28 +83,33 @@ func dataSourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) erro account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", accountName, name, containerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %v", accountName, name, containerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", accountName) + return fmt.Errorf("locating Storage Account %q", accountName) } - blobsClient, err := storageClient.BlobsClient(ctx, *account) + blobsClient, err := storageClient.BlobsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Blobs Client: %s", err) + return fmt.Errorf("building Blobs Client: %v", err) } - id := blobsClient.GetResourceID(accountName, containerName, name) + accountId, err := accounts.ParseAccountID(accountName, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := blobs.NewBlobID(*accountId, containerName, name) - log.Printf("[INFO] Retrieving Storage Blob %q (Container %q / Account %q).", name, containerName, accountName) + log.Printf("[INFO] Retrieving %s", id) input := blobs.GetPropertiesInput{} - props, err := blobsClient.GetProperties(ctx, accountName, containerName, name, input) + props, err := blobsClient.GetProperties(ctx, containerName, name, input) if err != nil { - if utils.ResponseWasNotFound(props.Response) { - return fmt.Errorf("the Blob %q was not found in Container %q / Account %q", name, containerName, accountName) + if response.WasNotFound(props.HttpResponse) { + return fmt.Errorf("%s was not found", id) } - return fmt.Errorf("retrieving properties for Blob %q (Container %q / Account %q): %s", name, containerName, accountName, err) + return fmt.Errorf("retrieving properties for %s: %v", id, err) } d.Set("name", name) @@ -125,9 +131,9 @@ func dataSourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) erro d.Set("type", strings.TrimSuffix(string(props.BlobType), "Blob")) - d.SetId(id) + d.SetId(id.ID()) - d.Set("url", id) + d.Set("url", id.ID()) if err := d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { return fmt.Errorf("setting `metadata`: %+v", err) diff --git a/internal/services/storage/storage_blob_resource.go b/internal/services/storage/storage_blob_resource.go index d7e5e837a012..bc75137f6ac0 100644 --- a/internal/services/storage/storage_blob_resource.go +++ b/internal/services/storage/storage_blob_resource.go @@ -10,15 +10,18 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" ) func resourceStorageBlob() *pluginsdk.Resource { @@ -33,8 +36,8 @@ func resourceStorageBlob() *pluginsdk.Resource { 0: migration.BlobV0ToV1{}, }), - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := blobs.ParseResourceID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := blobs.ParseBlobID(id, storageDomainSuffix) return err }), @@ -47,10 +50,10 @@ func resourceStorageBlob() *pluginsdk.Resource { Schema: map[string]*pluginsdk.Schema{ "name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - // TODO: add validation + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringIsNotEmpty, }, "storage_account_name": { @@ -175,28 +178,34 @@ func resourceStorageBlobCreate(d *pluginsdk.ResourceData, meta interface{}) erro account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", accountName, name, containerName, err) + return fmt.Errorf("retrieving Storage Account %q for Blob %q (Container %q): %v", accountName, name, containerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", accountName) + return fmt.Errorf("locating Storage Account %q", accountName) } - blobsClient, err := storageClient.BlobsClient(ctx, *account) + blobsClient, err := storageClient.BlobsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Blobs Client: %s", err) + return fmt.Errorf("building Blobs Client: %v", err) + } + + accountId := accounts.AccountId{ + AccountName: accountName, + DomainSuffix: storageClient.StorageDomainSuffix, + SubDomainType: accounts.BlobSubDomainType, } - id := blobsClient.GetResourceID(accountName, containerName, name) + id := blobs.NewBlobID(accountId, containerName, name) if d.IsNewResource() { input := blobs.GetPropertiesInput{} - props, err := blobsClient.GetProperties(ctx, accountName, containerName, name, input) + props, err := blobsClient.GetProperties(ctx, containerName, name, input) if err != nil { - if !utils.ResponseWasNotFound(props.Response) { - return fmt.Errorf("checking if Blob %q exists (Container %q / Account %q / Resource Group %q): %s", name, containerName, accountName, account.ResourceGroup, err) + if !response.WasNotFound(props.HttpResponse) { + return fmt.Errorf("checking for existing %s: %v", id, err) } } - if !utils.ResponseWasNotFound(props.Response) { - return tf.ImportAsExistsError("azurerm_storage_blob", id) + if !response.WasNotFound(props.HttpResponse) { + return tf.ImportAsExistsError("azurerm_storage_blob", id.ID()) } } @@ -210,7 +219,7 @@ func resourceStorageBlobCreate(d *pluginsdk.ResourceData, meta interface{}) erro } } - log.Printf("[DEBUG] Creating Blob %q in Container %q within Storage Account %q..", name, containerName, accountName) + log.Printf("[DEBUG] Creating %s..", id) metaDataRaw := d.Get("metadata").(map[string]interface{}) blobInput := BlobUpload{ AccountName: accountName, @@ -229,12 +238,12 @@ func resourceStorageBlobCreate(d *pluginsdk.ResourceData, meta interface{}) erro SourceContent: d.Get("source_content").(string), SourceUri: d.Get("source_uri").(string), } - if err := blobInput.Create(ctx); err != nil { - return fmt.Errorf("creating Blob %q (Container %q / Account %q): %s", name, containerName, accountName, err) + if err = blobInput.Create(ctx); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } - log.Printf("[DEBUG] Created Blob %q in Container %q within Storage Account %q.", name, containerName, accountName) + log.Printf("[DEBUG] Created %s.", id) - d.SetId(id) + d.SetId(id.ID()) return resourceStorageBlobUpdate(d, meta) } @@ -244,69 +253,69 @@ func resourceStorageBlobUpdate(d *pluginsdk.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := blobs.ParseResourceID(d.Id()) + id, err := blobs.ParseBlobID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("parsing %q: %s", d.Id(), err) + return fmt.Errorf("parsing %q: %v", d.Id(), err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %v", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - blobsClient, err := storageClient.BlobsClient(ctx, *account) + blobsClient, err := storageClient.BlobsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Blobs Client: %s", err) + return fmt.Errorf("building Blobs Client: %v", err) } if d.HasChange("content_type") || d.HasChange("cache_control") { - log.Printf("[DEBUG] Updating Properties for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updating Properties for %s...", id) input := blobs.SetPropertiesInput{ ContentType: utils.String(d.Get("content_type").(string)), CacheControl: utils.String(d.Get("cache_control").(string)), } - // `content_md5` is `ForceNew` but must be included in the `SetPropertiesInput` update payload or it will be zeroed on the blob. + // `content_md5` is `ForceNew` but must be included in the `SetPropertiesInput` update payload, or it will be zeroed on the blob. if contentMD5 := d.Get("content_md5").(string); contentMD5 != "" { data, err := convertHexToBase64Encoding(contentMD5) if err != nil { - return fmt.Errorf("in converting hex to base64 encoding for content_md5: %s", err) + return fmt.Errorf("converting hex to base64 encoding for content_md5: %v", err) } input.ContentMD5 = utils.String(data) } - if _, err := blobsClient.SetProperties(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("updating Properties for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err = blobsClient.SetProperties(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("updating Properties for %s: %v", id, err) } - log.Printf("[DEBUG] Updated Properties for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updated Properties for %s", id) } if d.HasChange("metadata") { - log.Printf("[DEBUG] Updating MetaData for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updating MetaData for %s...", id) metaDataRaw := d.Get("metadata").(map[string]interface{}) input := blobs.SetMetaDataInput{ MetaData: ExpandMetaData(metaDataRaw), } - if _, err := blobsClient.SetMetaData(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("updating MetaData for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err = blobsClient.SetMetaData(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("updating MetaData for %s: %v", id, err) } - log.Printf("[DEBUG] Updated MetaData for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updated MetaData for %s", id) } if d.HasChange("access_tier") { // this is only applicable for Gen2/BlobStorage accounts - log.Printf("[DEBUG] Updating Access Tier for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updating Access Tier for %s...", id) accessTier := blobs.AccessTier(d.Get("access_tier").(string)) - if _, err := blobsClient.SetTier(ctx, id.AccountName, id.ContainerName, id.BlobName, accessTier); err != nil { - return fmt.Errorf("updating Access Tier for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err := blobsClient.SetTier(ctx, id.ContainerName, id.BlobName, blobs.SetTierInput{Tier: accessTier}); err != nil { + return fmt.Errorf("updating Access Tier for %s: %v", id, err) } - log.Printf("[DEBUG] Updated Access Tier for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updated Access Tier for %s", id) } return resourceStorageBlobRead(d, meta) @@ -317,42 +326,42 @@ func resourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := blobs.ParseResourceID(d.Id()) + id, err := blobs.ParseBlobID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("parsing %q: %s", d.Id(), err) + return fmt.Errorf("parsing %q: %v", d.Id(), err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %v", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - log.Printf("[DEBUG] Unable to locate Account %q for Blob %q (Container %q) - assuming removed & removing from state!", id.AccountName, id.BlobName, id.ContainerName) + log.Printf("[DEBUG] Unable to locate Account %q for Blob %q (Container %q) - assuming removed & removing from state!", id.AccountId.AccountName, id.BlobName, id.ContainerName) d.SetId("") return nil } - blobsClient, err := storageClient.BlobsClient(ctx, *account) + blobsClient, err := storageClient.BlobsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Blobs Client: %s", err) + return fmt.Errorf("building Blobs Client: %v", err) } - log.Printf("[INFO] Retrieving Storage Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[INFO] Retrieving %s", id) input := blobs.GetPropertiesInput{} - props, err := blobsClient.GetProperties(ctx, id.AccountName, id.ContainerName, id.BlobName, input) + props, err := blobsClient.GetProperties(ctx, id.ContainerName, id.BlobName, input) if err != nil { - if utils.ResponseWasNotFound(props.Response) { - log.Printf("[INFO] Blob %q was not found in Container %q / Account %q - assuming removed & removing from state...", id.BlobName, id.ContainerName, id.AccountName) + if response.WasNotFound(props.HttpResponse) { + log.Printf("[INFO] Blob %q was not found in Container %q / Account %q - assuming removed & removing from state...", id.BlobName, id.ContainerName, id.AccountId.AccountName) d.SetId("") return nil } - return fmt.Errorf("retrieving properties for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + return fmt.Errorf("retrieving properties for %s: %v", id, err) } d.Set("name", id.BlobName) d.Set("storage_container_name", id.ContainerName) - d.Set("storage_account_name", id.AccountName) + d.Set("storage_account_name", id.AccountId.AccountName) d.Set("access_tier", string(props.AccessTier)) d.Set("content_type", props.ContentType) @@ -363,7 +372,7 @@ func resourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) error if props.ContentMD5 != "" { contentMD5, err = convertBase64ToHexEncoding(props.ContentMD5) if err != nil { - return fmt.Errorf("in converting hex to base64 encoding for content_md5: %s", err) + return fmt.Errorf("converting hex to base64 encoding for content_md5: %v", err) } } d.Set("content_md5", contentMD5) @@ -371,8 +380,8 @@ func resourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) error d.Set("type", strings.TrimSuffix(string(props.BlobType), "Blob")) d.Set("url", d.Id()) - if err := d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { - return fmt.Errorf("setting `metadata`: %+v", err) + if err = d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { + return fmt.Errorf("setting `metadata`: %v", err) } // The CopySource is only returned if the blob hasn't been modified (e.g. metadata configured etc) // as such, we need to conditionally set this to ensure it's trackable if possible @@ -388,30 +397,29 @@ func resourceStorageBlobDelete(d *pluginsdk.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := blobs.ParseResourceID(d.Id()) + id, err := blobs.ParseBlobID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("parsing %q: %s", d.Id(), err) + return fmt.Errorf("parsing %q: %v", d.Id(), err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - blobsClient, err := storageClient.BlobsClient(ctx, *account) + blobsClient, err := storageClient.BlobsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Blobs Client: %s", err) + return fmt.Errorf("building Blobs Client: %v", err) } - log.Printf("[INFO] Deleting Blob %q from Container %q / Storage Account %q", id.BlobName, id.ContainerName, id.AccountName) input := blobs.DeleteInput{ DeleteSnapshots: true, } - if _, err := blobsClient.Delete(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("deleting Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err = blobsClient.Delete(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil diff --git a/internal/services/storage/storage_blob_resource_test.go b/internal/services/storage/storage_blob_resource_test.go index 8f050af524f5..9a0c6d3b2ba3 100644 --- a/internal/services/storage/storage_blob_resource_test.go +++ b/internal/services/storage/storage_blob_resource_test.go @@ -10,13 +10,15 @@ import ( "os" "regexp" "testing" + "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" ) type StorageBlobResource struct{} @@ -469,56 +471,62 @@ func TestAccStorageBlob_archive(t *testing.T) { } func (r StorageBlobResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := blobs.ParseResourceID(state.ID) + id, err := blobs.ParseBlobID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { return nil, err } if account == nil { - return nil, fmt.Errorf("unable to locate Account %q for Blob %q (Container %q)", id.AccountName, id.BlobName, id.ContainerName) + return nil, fmt.Errorf("unable to locate Account %q for Blob %q (Container %q)", id.AccountId.AccountName, id.BlobName, id.ContainerName) } - blobsClient, err := client.Storage.BlobsClient(ctx, *account) + blobsClient, err := client.Storage.BlobsDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Blobs Client: %+v", err) } input := blobs.GetPropertiesInput{} - resp, err := blobsClient.GetProperties(ctx, id.AccountName, id.ContainerName, id.BlobName, input) + resp, err := blobsClient.GetProperties(ctx, id.ContainerName, id.BlobName, input) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } - return nil, fmt.Errorf("retrieving Blob %q (Container %q / Account %q): %+v", id.BlobName, id.ContainerName, id.AccountName, err) + return nil, fmt.Errorf("retrieving Blob %q (Container %q / Account %q): %+v", id.BlobName, id.ContainerName, id.AccountId.AccountName, err) } return utils.Bool(true), nil } func (r StorageBlobResource) Destroy(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := blobs.ParseResourceID(state.ID) + id, err := blobs.ParseBlobID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrievign Account %q for Blob %q (Container %q): %+v", id.AccountName, id.BlobName, id.ContainerName, err) + return nil, fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %+v", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } - blobsClient, err := client.Storage.BlobsClient(ctx, *account) + blobsClient, err := client.Storage.BlobsDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Blobs Client: %+v", err) } input := blobs.DeleteInput{ DeleteSnapshots: false, } - if _, err := blobsClient.Delete(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return nil, fmt.Errorf("deleting Blob %q (Container %q / Account %q): %+v", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err = blobsClient.Delete(ctx, id.ContainerName, id.BlobName, input); err != nil { + return nil, fmt.Errorf("deleting Blob %q (Container %q / Account %q): %+v", id.BlobName, id.ContainerName, id.AccountId.AccountName, err) } return utils.Bool(true), nil } func (r StorageBlobResource) blobMatchesFile(kind blobs.BlobType, filePath string) func(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) error { return func(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) error { + if _, ok := ctx.Deadline(); !ok { + var cancel context.CancelFunc + ctx, cancel = context.WithDeadline(ctx, time.Now().Add(10*time.Minute)) + defer cancel() + } + name := state.Attributes["name"] containerName := state.Attributes["storage_container_name"] accountName := state.Attributes["storage_account_name"] @@ -531,14 +539,14 @@ func (r StorageBlobResource) blobMatchesFile(kind blobs.BlobType, filePath strin return fmt.Errorf("Unable to locate Storage Account %q!", accountName) } - client, err := clients.Storage.BlobsClient(ctx, *account) + client, err := clients.Storage.BlobsDataPlaneClient(ctx, *account, clients.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Blobs Client: %s", err) } // first check the type getPropsInput := blobs.GetPropertiesInput{} - props, err := client.GetProperties(ctx, accountName, containerName, name, getPropsInput) + props, err := client.GetProperties(ctx, containerName, name, getPropsInput) if err != nil { return fmt.Errorf("retrieving Properties for Blob %q (Container %q): %s", name, containerName, err) } @@ -549,20 +557,24 @@ func (r StorageBlobResource) blobMatchesFile(kind blobs.BlobType, filePath strin // then compare the content itself getInput := blobs.GetInput{} - actualProps, err := client.Get(ctx, accountName, containerName, name, getInput) + actualProps, err := client.Get(ctx, containerName, name, getInput) if err != nil { return fmt.Errorf("retrieving Blob %q (Container %q): %s", name, containerName, err) } actualContents := actualProps.Contents + if actualContents == nil { + return fmt.Errorf("Bad: Storage Blob %q (storage container: %q) returned nil contents", name, containerName) + } + // local file for comparison expectedContents, err := os.ReadFile(filePath) if err != nil { return err } - if string(actualContents) != string(expectedContents) { + if string(*actualContents) != string(expectedContents) { return fmt.Errorf("Bad: Storage Blob %q (storage container: %q) does not match contents", name, containerName) } diff --git a/internal/services/storage/storage_container_data_source.go b/internal/services/storage/storage_container_data_source.go index dc7a74da8ef0..30e99688f495 100644 --- a/internal/services/storage/storage_container_data_source.go +++ b/internal/services/storage/storage_container_data_source.go @@ -9,9 +9,11 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) func dataSourceStorageContainer() *pluginsdk.Resource { @@ -69,34 +71,47 @@ func dataSourceStorageContainerRead(d *pluginsdk.ResourceData, meta interface{}) account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", accountName, containerName, err) + return fmt.Errorf("retrieving Storage Account %q for Container %q: %v", accountName, containerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Account %q for Storage Container %q", accountName, containerName) + return fmt.Errorf("locating Storage Account %q for Container %q", accountName, containerName) } - client, err := storageClient.ContainersClient(ctx, *account) + containersDataPlaneClient, err := storageClient.ContainersDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", accountName, account.ResourceGroup, err) + return fmt.Errorf("building Containers Client: %v", err) } - id := parse.NewStorageContainerDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, containerName).ID() - d.SetId(id) + // Determine the blob endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeBlob) + if err != nil { + return fmt.Errorf("determining Blob endpoint: %v", err) + } - props, err := client.Get(ctx, account.ResourceGroup, accountName, containerName) + // Parse the blob endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %s", containerName, accountName, account.ResourceGroup, err) + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := containers.NewContainerID(*accountId, containerName) + + props, err := containersDataPlaneClient.Get(ctx, containerName) + if err != nil { + return fmt.Errorf("retrieving %s: %v", id, err) } if props == nil { - return fmt.Errorf("Container %q was not found in Account %q / Resource Group %q", containerName, accountName, account.ResourceGroup) + return fmt.Errorf("retrieving %s: result was nil", id) } + d.SetId(id.ID()) + d.Set("name", containerName) d.Set("storage_account_name", accountName) d.Set("container_access_type", flattenStorageContainerAccessLevel(props.AccessLevel)) - if err := d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { - return fmt.Errorf("setting `metadata`: %+v", err) + if err = d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { + return fmt.Errorf("setting `metadata`: %v", err) } d.Set("has_immutability_policy", props.HasImmutabilityPolicy) diff --git a/internal/services/storage/storage_container_resource.go b/internal/services/storage/storage_container_resource.go index c4dc99de623e..bf1db305ad27 100644 --- a/internal/services/storage/storage_container_resource.go +++ b/internal/services/storage/storage_container_resource.go @@ -11,13 +11,15 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) func resourceStorageContainer() *pluginsdk.Resource { @@ -27,8 +29,8 @@ func resourceStorageContainer() *pluginsdk.Resource { Delete: resourceStorageContainerDelete, Update: resourceStorageContainerUpdate, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.StorageContainerDataPlaneID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := containers.ParseContainerID(id, storageDomainSuffix) return err }), @@ -106,37 +108,51 @@ func resourceStorageContainerCreate(d *pluginsdk.ResourceData, meta interface{}) account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", accountName, containerName, err) + return fmt.Errorf("retrieving Account %q for Container %q: %v", accountName, containerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", accountName) + return fmt.Errorf("locating Storage Account %q", accountName) } - client, err := storageClient.ContainersClient(ctx, *account) + containersDataPlaneClient, err := storageClient.ContainersDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building storage client: %+v", err) + return fmt.Errorf("building storage client: %v", err) } - id := parse.NewStorageContainerDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, containerName).ID() - exists, err := client.Exists(ctx, account.ResourceGroup, accountName, containerName) + // Determine the blob endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeBlob) if err != nil { - return err + return fmt.Errorf("determining Blob endpoint: %v", err) + } + + // Parse the blob endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := containers.NewContainerID(*accountId, containerName) + + exists, err := containersDataPlaneClient.Exists(ctx, containerName) + if err != nil { + return fmt.Errorf("checking for existing %s: %v", id, err) } if exists != nil && *exists { - return tf.ImportAsExistsError("azurerm_storage_container", id) + return tf.ImportAsExistsError("azurerm_storage_container", id.ID()) } - log.Printf("[INFO] Creating Container %q in Storage Account %q", containerName, accountName) + log.Printf("[INFO] Creating %s", id) input := containers.CreateInput{ AccessLevel: accessLevel, MetaData: metaData, } - if err := client.Create(ctx, account.ResourceGroup, accountName, containerName, input); err != nil { - return fmt.Errorf("failed creating container: %+v", err) + if err = containersDataPlaneClient.Create(ctx, containerName, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } - d.SetId(id) + d.SetId(id.ID()) + return resourceStorageContainerRead(d, meta) } @@ -145,45 +161,54 @@ func resourceStorageContainerUpdate(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageContainerDataPlaneID(d.Id()) + id, err := containers.ParseContainerID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Container %q: %v", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) - } - client, err := storageClient.ContainersClient(ctx, *account) - if err != nil { - return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } if d.HasChange("container_access_type") { - log.Printf("[DEBUG] Updating the Access Control for Container %q (Storage Account %q / Resource Group %q)..", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updating Access Level for %s...", id) + + // Updating metadata does not work with AAD authentication, returns a cryptic 404 + client, err := storageClient.ContainersDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) + if err != nil { + return fmt.Errorf("building Containers Client: %v", err) + } + accessLevelRaw := d.Get("container_access_type").(string) accessLevel := expandStorageContainerAccessLevel(accessLevelRaw) - if err := client.UpdateAccessLevel(ctx, account.ResourceGroup, id.AccountName, id.Name, accessLevel); err != nil { - return fmt.Errorf("updating the Access Control for Container %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + if err = client.UpdateAccessLevel(ctx, id.ContainerName, accessLevel); err != nil { + return fmt.Errorf("updating Access Level for %s: %v", id, err) } - log.Printf("[DEBUG] Updated the Access Control for Container %q (Storage Account %q / Resource Group %q)", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updated Access Level for %s", id) } if d.HasChange("metadata") { - log.Printf("[DEBUG] Updating the MetaData for Container %q (Storage Account %q / Resource Group %q)..", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updating Metadata for %s...", id) + + client, err := storageClient.ContainersDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Containers Client: %v", err) + } + metaDataRaw := d.Get("metadata").(map[string]interface{}) metaData := ExpandMetaData(metaDataRaw) - if err := client.UpdateMetaData(ctx, account.ResourceGroup, id.AccountName, id.Name, metaData); err != nil { - return fmt.Errorf("updating the MetaData for Container %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + if err = client.UpdateMetaData(ctx, id.ContainerName, metaData); err != nil { + return fmt.Errorf("updating Metadata for %s: %v", id, err) } - log.Printf("[DEBUG] Updated the MetaData for Container %q (Storage Account %q / Resource Group %q)", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updated Metadata for %s", id) } return resourceStorageContainerRead(d, meta) @@ -195,48 +220,49 @@ func resourceStorageContainerRead(d *pluginsdk.ResourceData, meta interface{}) e ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageContainerDataPlaneID(d.Id()) + id, err := containers.ParseContainerID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Container %q: %v", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - log.Printf("[DEBUG] Unable to locate Account %q for Storage Container %q - assuming removed & removing from state", id.AccountName, id.Name) + log.Printf("[DEBUG] Unable to locate Account %q for Storage Container %q - assuming removed & removing from state", id.AccountId.AccountName, id.ContainerName) d.SetId("") return nil } - client, err := storageClient.ContainersClient(ctx, *account) + + client, err := storageClient.ContainersDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building Containers Client: %v", err) } - props, err := client.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + props, err := client.Get(ctx, id.ContainerName) if err != nil { - return fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %v", id, err) } if props == nil { - log.Printf("[DEBUG] Container %q was not found in Account %q / Resource Group %q - assuming removed & removing from state", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Container %q was not found in Account %q / Resource Group %q - assuming removed & removing from state", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup) d.SetId("") return nil } - d.Set("name", id.Name) - d.Set("storage_account_name", id.AccountName) + d.Set("name", id.ContainerName) + d.Set("storage_account_name", id.AccountId.AccountName) d.Set("container_access_type", flattenStorageContainerAccessLevel(props.AccessLevel)) - if err := d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { - return fmt.Errorf("setting `metadata`: %+v", err) + if err = d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { + return fmt.Errorf("setting `metadata`: %v", err) } d.Set("has_immutability_policy", props.HasImmutabilityPolicy) d.Set("has_legal_hold", props.HasLegalHold) - resourceManagerId := commonids.NewStorageContainerID(subscriptionId, account.ResourceGroup, id.AccountName, id.Name) + resourceManagerId := commonids.NewStorageContainerID(subscriptionId, account.ResourceGroup, id.AccountId.AccountName, id.ContainerName) d.Set("resource_manager_id", resourceManagerId.ID()) return nil @@ -247,25 +273,26 @@ func resourceStorageContainerDelete(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageContainerDataPlaneID(d.Id()) + id, err := containers.ParseContainerID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Container %q: %v", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.ContainersClient(ctx, *account) + + client, err := storageClient.ContainersDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building Containers Client: %v", err) } - if err := client.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return fmt.Errorf("deleting Container %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + if err = client.Delete(ctx, id.ContainerName); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil diff --git a/internal/services/storage/storage_container_resource_test.go b/internal/services/storage/storage_container_resource_test.go index cf0a8c0ae07b..623ac0ca36b5 100644 --- a/internal/services/storage/storage_container_resource_test.go +++ b/internal/services/storage/storage_container_resource_test.go @@ -12,10 +12,10 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) type StorageContainerResource struct{} @@ -96,14 +96,14 @@ func TestAccStorageContainer_update(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.update(data, "private"), + Config: r.update(data, "private", "yes"), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("container_access_type").HasValue("private"), ), }, { - Config: r.update(data, "container"), + Config: r.update(data, "container", "no"), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("container_access_type").HasValue("container"), @@ -187,48 +187,55 @@ func TestAccStorageContainer_web(t *testing.T) { } func (r StorageContainerResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageContainerDataPlaneID(state.ID) + id, err := containers.ParseContainerID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountName) + return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountId.AccountName) } - containersClient, err := client.Storage.ContainersClient(ctx, *account) + containersClient, err := client.Storage.ContainersDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Containers Client: %+v", err) } - prop, err := containersClient.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + + prop, err := containersClient.Get(ctx, id.ContainerName) if err != nil { - return nil, fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %+v", id.Name, id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %+v", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } + return utils.Bool(prop != nil), nil } func (r StorageContainerResource) Destroy(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageContainerDataPlaneID(state.ID) + id, err := containers.ParseContainerID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountName) + return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountId.AccountName) } - containersClient, err := client.Storage.ContainersClient(ctx, *account) + + containersClient, err := client.Storage.ContainersDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Containers Client: %+v", err) } - if err := containersClient.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return nil, fmt.Errorf("deleting Container %q (Account %q / Resource Group %q): %+v", id.Name, id.AccountName, account.ResourceGroup, err) + + if err = containersClient.Delete(ctx, id.ContainerName); err != nil { + return nil, fmt.Errorf("deleting Container %q (Account %q / Resource Group %q): %+v", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } + return utils.Bool(true), nil } @@ -290,7 +297,7 @@ resource "azurerm_storage_container" "import" { `, template) } -func (r StorageContainerResource) update(data acceptance.TestData, accessType string) string { +func (r StorageContainerResource) update(data acceptance.TestData, accessType, metadataVal string) string { template := r.template(data) return fmt.Sprintf(` %s @@ -299,8 +306,12 @@ resource "azurerm_storage_container" "test" { name = "vhds" storage_account_name = azurerm_storage_account.test.name container_access_type = "%s" + metadata = { + foo = "bar" + test = "%s" + } } -`, template, accessType) +`, template, accessType, metadataVal) } func (r StorageContainerResource) metaData(data acceptance.TestData) string { diff --git a/internal/services/storage/storage_containers_data_source.go b/internal/services/storage/storage_containers_data_source.go index 40c5ec7ff49a..05d62feac9b2 100644 --- a/internal/services/storage/storage_containers_data_source.go +++ b/internal/services/storage/storage_containers_data_source.go @@ -12,9 +12,11 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2023-01-01/blobcontainers" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) type storageContainersDataSource struct{} @@ -86,7 +88,7 @@ func (r storageContainersDataSource) Read() sdk.ResourceFunc { Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.Storage.ResourceManager.BlobContainers + blobContainersClient := metadata.Client.Storage.ResourceManager.BlobContainers var plan storageContainersDataSourceModel if err := metadata.Decode(&plan); err != nil { @@ -98,12 +100,32 @@ func (r storageContainersDataSource) Read() sdk.ResourceFunc { return err } - resp, err := client.ListCompleteMatchingPredicate(ctx, *id, blobcontainers.DefaultListOperationOptions(), blobcontainers.ListContainerItemOperationPredicate{}) + account, err := metadata.Client.Storage.FindAccount(ctx, id.StorageAccountName) + if err != nil { + return fmt.Errorf("retrieving Storage Account %q: %v", id.StorageAccountName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", id.StorageAccountName) + } + + // Determine the blob endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeBlob) + if err != nil { + return fmt.Errorf("determining Blob endpoint: %v", err) + } + + // Parse the blob endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, metadata.Client.Storage.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + resp, err := blobContainersClient.ListCompleteMatchingPredicate(ctx, *id, blobcontainers.DefaultListOperationOptions(), blobcontainers.ListContainerItemOperationPredicate{}) if err != nil { return fmt.Errorf("retrieving %s: %+v", id, err) } - plan.Containers = flattenStorageContainersContainers(resp.Items, id.StorageAccountName, metadata.Client.Storage.Environment.StorageEndpointSuffix, plan.NamePrefix) + plan.Containers = flattenStorageContainersContainers(resp.Items, *accountId, plan.NamePrefix) if err := metadata.Encode(&plan); err != nil { return fmt.Errorf("encoding %s: %+v", id, err) @@ -116,7 +138,7 @@ func (r storageContainersDataSource) Read() sdk.ResourceFunc { } } -func flattenStorageContainersContainers(l []blobcontainers.ListContainerItem, accountName, endpointSuffix, prefix string) []containerModel { +func flattenStorageContainersContainers(l []blobcontainers.ListContainerItem, accountId accounts.AccountId, prefix string) []containerModel { var output []containerModel for _, item := range l { var name string @@ -136,7 +158,7 @@ func flattenStorageContainersContainers(l []blobcontainers.ListContainerItem, ac output = append(output, containerModel{ Name: name, ResourceManagerId: mgmtId, - DataPlaneId: parse.NewStorageContainerDataPlaneId(accountName, endpointSuffix, name).ID(), + DataPlaneId: containers.NewContainerID(accountId, name).ID(), }) } diff --git a/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go b/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go index 4998f22fc693..f75fd303e9e6 100644 --- a/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go +++ b/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go @@ -10,16 +10,19 @@ import ( "regexp" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths" "github.com/tombuildsstuff/giovanni/storage/accesscontrol" ) @@ -30,23 +33,24 @@ func resourceStorageDataLakeGen2FileSystem() *pluginsdk.Resource { Update: resourceStorageDataLakeGen2FileSystemUpdate, Delete: resourceStorageDataLakeGen2FileSystemDelete, - Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := filesystems.ParseResourceID(id) + Importer: helpers.ImporterValidatingStorageResourceIdThen(func(id, storageDomainSuffix string) error { + _, err := filesystems.ParseFileSystemID(id, storageDomainSuffix) return err }, func(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}) ([]*pluginsdk.ResourceData, error) { - storageClients := meta.(*clients.Client).Storage - id, err := filesystems.ParseResourceID(d.Id()) + storageClient := meta.(*clients.Client).Storage + + id, err := filesystems.ParseFileSystemID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return []*pluginsdk.ResourceData{d}, fmt.Errorf("parsing ID %q for import of Data Lake Gen2 File System: %v", d.Id(), err) } // we then need to look up the Storage Account ID - account, err := storageClients.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving Account %q for Data Lake Gen2 File System %q: %s", id.AccountName, id.DirectoryName, err) + return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving Account %q for Data Lake Gen2 File System %q: %s", id.AccountId.AccountName, id.FileSystemName, err) } if account == nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return []*pluginsdk.ResourceData{d}, fmt.Errorf("unable to locate Storage Account: %q", id.AccountId.AccountName) } d.Set("storage_account_id", account.ID) @@ -127,62 +131,84 @@ func resourceStorageDataLakeGen2FileSystem() *pluginsdk.Resource { } func resourceStorageDataLakeGen2FileSystemCreate(d *pluginsdk.ResourceData, meta interface{}) error { - accountsClient := meta.(*clients.Client).Storage.AccountsClient - client := meta.(*clients.Client).Storage.FileSystemsClient - pathClient := meta.(*clients.Client).Storage.ADLSGen2PathsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() - storageID, err := commonids.ParseStorageAccountID(d.Get("storage_account_id").(string)) + filesystemName := d.Get("name").(string) + + // Parse the storage_account_id which is a resource manager ID + accountResourceManagerId, err := commonids.ParseStorageAccountID(d.Get("storage_account_id").(string)) if err != nil { return err } - aceRaw := d.Get("ace").(*pluginsdk.Set).List() - acl, err := ExpandDataLakeGen2AceList(aceRaw) + // Confirm the storage account exists and retrieve its properties + account, err := storageClient.FindAccount(ctx, accountResourceManagerId.StorageAccountName) if err != nil { - return fmt.Errorf("parsing ace list: %s", err) + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", accountResourceManagerId.StorageAccountName, filesystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", accountResourceManagerId.StorageAccountName) } - // confirm the storage account exists, otherwise Data Plane API requests will fail - storageAccount, err := accountsClient.GetProperties(ctx, storageID.ResourceGroupName, storageID.StorageAccountName, "") + // Build the data plane clients + dataPlaneFilesystemsClient, err := storageClient.DataLakeFilesystemsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - if utils.ResponseWasNotFound(storageAccount.Response) { - return fmt.Errorf("%s was not found", storageID) - } + return fmt.Errorf("building Data Lake Gen2 Filesystems Client: %v", err) + } + dataPlanePathsClient, err := storageClient.DataLakePathsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Data Lake Gen2 Paths Client: %v", err) + } - return fmt.Errorf("checking for existence of %s: %+v", storageID, err) + // Determine the dfs endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeDfs) + if err != nil { + return fmt.Errorf("determining Data Lake Gen2 Filesystems endpoint: %v", err) } - if acl != nil && (storageAccount.AccountProperties == nil || - storageAccount.AccountProperties.IsHnsEnabled == nil || - !*storageAccount.AccountProperties.IsHnsEnabled) { + // Parse the dfs endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + // Finally, build the data plane ID for this filesystem + id := filesystems.NewFileSystemID(*accountId, filesystemName) + + aceRaw := d.Get("ace").(*pluginsdk.Set).List() + acl, err := ExpandDataLakeGen2AceList(aceRaw) + if err != nil { + return fmt.Errorf("parsing ace list: %v", err) + } + + if acl != nil && (account.Properties == nil || + account.Properties.IsHnsEnabled == nil || + !*account.Properties.IsHnsEnabled) { return fmt.Errorf("ACL is enabled only when the Hierarchical Namespace (HNS) feature is turned ON") } - fileSystemName := d.Get("name").(string) propertiesRaw := d.Get("properties").(map[string]interface{}) properties := ExpandMetaData(propertiesRaw) - id := client.GetResourceID(storageID.StorageAccountName, fileSystemName) - - resp, err := client.GetProperties(ctx, storageID.StorageAccountName, fileSystemName) + resp, err := dataPlaneFilesystemsClient.GetProperties(ctx, id.FileSystemName) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("checking for existence of existing File System %q in %s: %+v", fileSystemName, storageID, err) + if !response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("checking for existence of existing File System %q in %s: %v", id.FileSystemName, accountId, err) } } - if !utils.ResponseWasNotFound(resp.Response) { - return tf.ImportAsExistsError("azurerm_storage_data_lake_gen2_filesystem", id) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_storage_data_lake_gen2_filesystem", id.ID()) } - log.Printf("[INFO] Creating File System %q in %s.", fileSystemName, storageID) + log.Printf("[INFO] Creating %s...", id) input := filesystems.CreateInput{ Properties: properties, } - if _, err := client.Create(ctx, storageID.StorageAccountName, fileSystemName, input); err != nil { - return fmt.Errorf("creating File System %q in %s: %+v", fileSystemName, storageID, err) + if _, err = dataPlaneFilesystemsClient.Create(ctx, id.FileSystemName, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } var owner *string @@ -199,7 +225,7 @@ func resourceStorageDataLakeGen2FileSystemCreate(d *pluginsdk.ResourceData, meta if acl != nil || owner != nil || group != nil { var aclString *string if acl != nil { - log.Printf("[INFO] Creating acl %q in File System %q in %s", acl, fileSystemName, storageID) + log.Printf("[INFO] Creating ACL %q for %s", acl, id) v := acl.String() aclString = &v } @@ -208,63 +234,66 @@ func resourceStorageDataLakeGen2FileSystemCreate(d *pluginsdk.ResourceData, meta Owner: owner, Group: group, } - if _, err := pathClient.SetAccessControl(ctx, storageID.StorageAccountName, fileSystemName, "/", accessControlInput); err != nil { - return fmt.Errorf("setting access control for root path in File System %q in %s: %+v", fileSystemName, storageID, err) + if _, err = dataPlanePathsClient.SetAccessControl(ctx, id.FileSystemName, "/", accessControlInput); err != nil { + return fmt.Errorf("setting access control for root path in File System %q in %s: %v", id.FileSystemName, accountId, err) } } - d.SetId(id) + d.SetId(id.ID()) + return resourceStorageDataLakeGen2FileSystemRead(d, meta) } func resourceStorageDataLakeGen2FileSystemUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - accountsClient := meta.(*clients.Client).Storage.AccountsClient - client := meta.(*clients.Client).Storage.FileSystemsClient - pathClient := meta.(*clients.Client).Storage.ADLSGen2PathsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := filesystems.ParseResourceID(d.Id()) + id, err := filesystems.ParseFileSystemID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - storageId, err := commonids.ParseStorageAccountID(d.Get("storage_account_id").(string)) + // Retrieve the storage account properties + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return err + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", id.AccountId.AccountName, id.FileSystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - aceRaw := d.Get("ace").(*pluginsdk.Set).List() - acl, err := ExpandDataLakeGen2AceList(aceRaw) + // Build the data plane clients + dataPlaneFilesystemsClient, err := storageClient.DataLakeFilesystemsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("parsing ace list: %s", err) + return fmt.Errorf("building Data Lake Gen2 Filesystems Client: %v", err) } - - // confirm the storage account exists, otherwise Data Plane API requests will fail - storageAccount, err := accountsClient.GetProperties(ctx, storageId.ResourceGroupName, storageId.StorageAccountName, "") + dataPlanePathsClient, err := storageClient.DataLakePathsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - if utils.ResponseWasNotFound(storageAccount.Response) { - return fmt.Errorf("%s was not found", storageId) - } + return fmt.Errorf("building Data Lake Gen2 Paths Client: %v", err) + } - return fmt.Errorf("checking for existence of %s: %+v", storageId, err) + aceRaw := d.Get("ace").(*pluginsdk.Set).List() + acl, err := ExpandDataLakeGen2AceList(aceRaw) + if err != nil { + return fmt.Errorf("parsing ace list: %v", err) } - if acl != nil && (storageAccount.AccountProperties == nil || - storageAccount.AccountProperties.IsHnsEnabled == nil || - !*storageAccount.AccountProperties.IsHnsEnabled) { + if acl != nil && (account.Properties == nil || + account.Properties.IsHnsEnabled == nil || + !*account.Properties.IsHnsEnabled) { return fmt.Errorf("ACL is enabled only when the Hierarchical Namespace (HNS) feature is turned ON") } propertiesRaw := d.Get("properties").(map[string]interface{}) properties := ExpandMetaData(propertiesRaw) - log.Printf("[INFO] Updating Properties for File System %q in Storage Account %q.", id.DirectoryName, id.AccountName) + log.Printf("[INFO] Updating Properties for %s...", id) input := filesystems.SetPropertiesInput{ Properties: properties, } - if _, err = client.SetProperties(ctx, id.AccountName, id.DirectoryName, input); err != nil { - return fmt.Errorf("updating Properties for File System %q in Storage Account %q: %s", id.DirectoryName, id.AccountName, err) + if _, err = dataPlaneFilesystemsClient.SetProperties(ctx, id.FileSystemName, input); err != nil { + return fmt.Errorf("updating Properties for %s: %v", id, err) } var owner *string @@ -281,7 +310,7 @@ func resourceStorageDataLakeGen2FileSystemUpdate(d *pluginsdk.ResourceData, meta if acl != nil || owner != nil || group != nil { var aclString *string if acl != nil { - log.Printf("[INFO] Creating acl %q in File System %q in Storage Account %q.", acl, id.DirectoryName, id.AccountName) + log.Printf("[INFO] Creating ACL %q for %s...", acl, id) v := acl.String() aclString = &v } @@ -290,8 +319,8 @@ func resourceStorageDataLakeGen2FileSystemUpdate(d *pluginsdk.ResourceData, meta Owner: owner, Group: group, } - if _, err := pathClient.SetAccessControl(ctx, id.AccountName, id.DirectoryName, "/", accessControlInput); err != nil { - return fmt.Errorf("setting access control for root path in File System %q in Storage Account %q: %s", id.DirectoryName, id.AccountName, err) + if _, err = dataPlanePathsClient.SetAccessControl(ctx, id.FileSystemName, "/", accessControlInput); err != nil { + return fmt.Errorf("setting access control for root path in File System %q in Storage Account %q: %v", id.FileSystemName, id.AccountId.AccountName, err) } } @@ -299,59 +328,59 @@ func resourceStorageDataLakeGen2FileSystemUpdate(d *pluginsdk.ResourceData, meta } func resourceStorageDataLakeGen2FileSystemRead(d *pluginsdk.ResourceData, meta interface{}) error { - accountsClient := meta.(*clients.Client).Storage.AccountsClient - client := meta.(*clients.Client).Storage.FileSystemsClient - pathClient := meta.(*clients.Client).Storage.ADLSGen2PathsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := filesystems.ParseResourceID(d.Id()) + id, err := filesystems.ParseFileSystemID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - storageID, err := commonids.ParseStorageAccountID(d.Get("storage_account_id").(string)) + // Retrieve the storage account properties + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return err + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", id.AccountId.AccountName, id.FileSystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - // confirm the storage account exists, otherwise Data Plane API requests will fail - storageAccount, err := accountsClient.GetProperties(ctx, storageID.ResourceGroupName, storageID.StorageAccountName, "") + // Build the data plane clients + dataPlaneFilesystemsClient, err := storageClient.DataLakeFilesystemsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - if utils.ResponseWasNotFound(storageAccount.Response) { - log.Printf("[INFO] Storage Account %q does not exist removing from state...", id.AccountName) - d.SetId("") - return nil - } - - return fmt.Errorf("checking for existence of %s for File System %q: %+v", storageID, id.DirectoryName, err) + return fmt.Errorf("building Data Lake Gen2 Filesystems Client: %v", err) + } + dataPlanePathsClient, err := storageClient.DataLakePathsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Data Lake Gen2 Paths Client: %v", err) } - resp, err := client.GetProperties(ctx, id.AccountName, id.DirectoryName) + resp, err := dataPlaneFilesystemsClient.GetProperties(ctx, id.FileSystemName) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[INFO] File System %q does not exist in Storage Account %q - removing from state...", id.DirectoryName, id.AccountName) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[INFO] File System %q does not exist in Storage Account %q - removing from state...", id.FileSystemName, id.AccountId.AccountName) d.SetId("") return nil } - return fmt.Errorf("retrieving File System %q in Storage Account %q: %+v", id.DirectoryName, id.AccountName, err) + return fmt.Errorf("retrieving %s: %v", id, err) } - d.Set("name", id.DirectoryName) + d.Set("name", id.FileSystemName) - if err := d.Set("properties", resp.Properties); err != nil { - return fmt.Errorf("setting `properties`: %+v", err) + if err = d.Set("properties", resp.Properties); err != nil { + return fmt.Errorf("setting `properties`: %v", err) } var ace []interface{} var owner, group string // acl is only enabled when `IsHnsEnabled` is true otherwise the rest api will report error - if storageAccount.AccountProperties != nil && storageAccount.AccountProperties.IsHnsEnabled != nil && - *storageAccount.AccountProperties.IsHnsEnabled { + if account.Properties != nil && account.Properties.IsHnsEnabled != nil && + *account.Properties.IsHnsEnabled { // The above `getStatus` API request doesn't return the ACLs // Have to make a `getAccessControl` request, but that doesn't return all fields either! - pathResponse, err := pathClient.GetProperties(ctx, id.AccountName, id.DirectoryName, "/", paths.GetPropertiesActionGetAccessControl) + pathResponse, err := dataPlanePathsClient.GetProperties(ctx, id.FileSystemName, "/", paths.GetPropertiesInput{Action: paths.GetPropertiesActionGetAccessControl}) if err == nil { acl, err := accesscontrol.ParseACL(pathResponse.ACL) if err != nil { @@ -370,19 +399,34 @@ func resourceStorageDataLakeGen2FileSystemRead(d *pluginsdk.ResourceData, meta i } func resourceStorageDataLakeGen2FileSystemDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Storage.FileSystemsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := filesystems.ParseResourceID(d.Id()) + id, err := filesystems.ParseFileSystemID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - resp, err := client.Delete(ctx, id.AccountName, id.DirectoryName) + // Retrieve the storage account properties + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) + if err != nil { + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", id.AccountId.AccountName, id.FileSystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) + } + + // Build the data plane client + dataPlaneFilesystemsClient, err := storageClient.DataLakeFilesystemsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Data Lake Gen2 Filesystems Client: %v", err) + } + + resp, err := dataPlaneFilesystemsClient.Delete(ctx, id.FileSystemName) if err != nil { - if !utils.ResponseWasNotFound(resp) { - return fmt.Errorf("deleting File System %q in Storage Account %q: %+v", id.DirectoryName, id.AccountName, err) + if !response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("deleting %s: %v", id, err) } } diff --git a/internal/services/storage/storage_data_lake_gen2_filesystem_resource_test.go b/internal/services/storage/storage_data_lake_gen2_filesystem_resource_test.go index 8399d2b0d212..90d1a441ede3 100644 --- a/internal/services/storage/storage_data_lake_gen2_filesystem_resource_test.go +++ b/internal/services/storage/storage_data_lake_gen2_filesystem_resource_test.go @@ -8,12 +8,13 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems" ) type StorageDataLakeGen2FileSystemResource struct{} @@ -147,28 +148,58 @@ func TestAccStorageDataLakeGen2FileSystem_withSuperUsers(t *testing.T) { } func (r StorageDataLakeGen2FileSystemResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := filesystems.ParseResourceID(state.ID) + id, err := filesystems.ParseFileSystemID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - resp, err := client.Storage.FileSystemsClient.GetProperties(ctx, id.AccountName, id.DirectoryName) + + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) + if err != nil { + return nil, fmt.Errorf("retrieving Account %q for Queue %q: %+v", id.AccountId, id.FileSystemName, err) + } + if account == nil { + return nil, fmt.Errorf("unable to determine Resource Group for Storage Queue %q (Account %q)", id.FileSystemName, id.AccountId.AccountName) + } + + filesystemsClient, err := client.Storage.DataLakeFilesystemsDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + return nil, fmt.Errorf("building Data Lake Gen2 Filesystems Client: %+v", err) + } + + resp, err := filesystemsClient.GetProperties(ctx, id.FileSystemName) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } - return nil, fmt.Errorf("retrieving File System %q (Account %q): %+v", id.DirectoryName, id.AccountName, err) + return nil, fmt.Errorf("retrieving File System %q (Account %q): %+v", id.FileSystemName, id.AccountId.AccountName, err) } + return utils.Bool(true), nil } func (r StorageDataLakeGen2FileSystemResource) Destroy(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := filesystems.ParseResourceID(state.ID) + id, err := filesystems.ParseFileSystemID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - if _, err := client.Storage.FileSystemsClient.Delete(ctx, id.AccountName, id.DirectoryName); err != nil { - return nil, fmt.Errorf("deleting File System %q (Account %q): %+v", id.DirectoryName, id.AccountName, err) + + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) + if err != nil { + return nil, fmt.Errorf("retrieving Account %q for Queue %q: %+v", id.AccountId, id.FileSystemName, err) + } + if account == nil { + return nil, fmt.Errorf("unable to determine Resource Group for Storage Queue %q (Account %q)", id.FileSystemName, id.AccountId.AccountName) } + + filesystemsClient, err := client.Storage.DataLakeFilesystemsDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return nil, fmt.Errorf("building Data Lake Gen2 Filesystems Client: %+v", err) + } + + if _, err = filesystemsClient.Delete(ctx, id.FileSystemName); err != nil { + return nil, fmt.Errorf("deleting File System %q (Account %q): %+v", id.FileSystemName, id.AccountId.AccountName, err) + } + return utils.Bool(true), nil } diff --git a/internal/services/storage/storage_data_lake_gen2_path_resource.go b/internal/services/storage/storage_data_lake_gen2_path_resource.go index 8457260a94c6..e398e9d696ad 100644 --- a/internal/services/storage/storage_data_lake_gen2_path_resource.go +++ b/internal/services/storage/storage_data_lake_gen2_path_resource.go @@ -9,15 +9,18 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths" "github.com/tombuildsstuff/giovanni/storage/accesscontrol" ) @@ -28,28 +31,34 @@ func resourceStorageDataLakeGen2Path() *pluginsdk.Resource { Update: resourceStorageDataLakeGen2PathUpdate, Delete: resourceStorageDataLakeGen2PathDelete, - Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := paths.ParseResourceID(id) + Importer: helpers.ImporterValidatingStorageResourceIdThen(func(id, storageDomainSuffix string) error { + _, err := paths.ParsePathID(id, storageDomainSuffix) return err }, func(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}) ([]*pluginsdk.ResourceData, error) { - storageClients := meta.(*clients.Client).Storage + storageClient := meta.(*clients.Client).Storage - id, err := paths.ParseResourceID(d.Id()) + id, err := paths.ParsePathID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return []*pluginsdk.ResourceData{d}, fmt.Errorf("parsing ID %q for import of Data Lake Gen2 Path: %v", d.Id(), err) } - // we then need to look up the Storage Account ID - account, err := storageClients.FindAccount(ctx, id.AccountName) + // Retrieve the storage account + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving Account %q for Data Lake Gen2 Path %q in File System %q: %s", id.AccountName, id.Path, id.FileSystemName, err) + return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving Account %q for Data Lake Gen2 Path %q in File System %q: %s", id.AccountId.AccountName, id.Path, id.FileSystemName, err) } if account == nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return []*pluginsdk.ResourceData{d}, fmt.Errorf("unable to locate Storage Account: %q", id.AccountId.AccountName) } - if _, err = storageClients.FileSystemsClient.GetProperties(ctx, id.AccountName, id.FileSystemName); err != nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving File System %q for Data Lake Gen 2 Path %q in Account %q: %s", id.FileSystemName, id.Path, id.AccountName, err) + // Build the data plane client + dataPlaneFilesystemsClient, err := storageClient.DataLakeFilesystemsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return []*pluginsdk.ResourceData{d}, fmt.Errorf("building Data Lake Gen2 Filesystems Client: %v", err) + } + + if _, err = dataPlaneFilesystemsClient.GetProperties(ctx, id.FileSystemName); err != nil { + return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving File System %q for Data Lake Gen2 Path %q in Account %q: %s", id.FileSystemName, id.Path, id.AccountId.AccountName, err) } d.Set("storage_account_id", account.ID) @@ -142,38 +151,56 @@ func resourceStorageDataLakeGen2Path() *pluginsdk.Resource { } func resourceStorageDataLakeGen2PathCreate(d *pluginsdk.ResourceData, meta interface{}) error { - accountsClient := meta.(*clients.Client).Storage.AccountsClient - client := meta.(*clients.Client).Storage.ADLSGen2PathsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() - storageID, err := commonids.ParseStorageAccountID(d.Get("storage_account_id").(string)) + filesystemName := d.Get("filesystem_name").(string) + path := d.Get("path").(string) + + // Parse the storage_account_id which is a resource manager ID + accountResourceManagerId, err := commonids.ParseStorageAccountID(d.Get("storage_account_id").(string)) if err != nil { return err } - // confirm the storage account exists, otherwise Data Plane API requests will fail - storageAccount, err := accountsClient.GetProperties(ctx, storageID.ResourceGroupName, storageID.StorageAccountName, "") + // Confirm the storage account exists and retrieve its properties + account, err := storageClient.FindAccount(ctx, accountResourceManagerId.StorageAccountName) if err != nil { - if utils.ResponseWasNotFound(storageAccount.Response) { - return fmt.Errorf("%s was not found", storageID) - } + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", accountResourceManagerId.StorageAccountName, filesystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", accountResourceManagerId.StorageAccountName) + } - return fmt.Errorf("checking for existence of %s: %+v", storageID, err) + // Build the data plane client + dataPlanePathsClient, err := storageClient.DataLakePathsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Data Lake Gen2 Paths Client: %v", err) } - fileSystemName := d.Get("filesystem_name").(string) - path := d.Get("path").(string) + // Determine the dfs endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeDfs) + if err != nil { + return fmt.Errorf("determining Data Lake Gen2 Filesystems endpoint: %v", err) + } + + // Parse the dfs endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := paths.NewPathID(*accountId, filesystemName, path) - id := client.GetResourceID(storageID.StorageAccountName, fileSystemName, path) - resp, err := client.GetProperties(ctx, storageID.StorageAccountName, fileSystemName, path, paths.GetPropertiesActionGetStatus) + resp, err := dataPlanePathsClient.GetProperties(ctx, filesystemName, path, paths.GetPropertiesInput{Action: paths.GetPropertiesActionGetStatus}) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("checking for existence of existing Path %q in File System %q in %s: %+v", path, fileSystemName, storageID, err) + if !response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("checking for existence of existing Path %q in File System %q in %s: %v", path, filesystemName, accountResourceManagerId, err) } } - if !utils.ResponseWasNotFound(resp.Response) { - return tf.ImportAsExistsError("azurerm_storage_data_lake_gen2_path", id) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_storage_data_lake_gen2_path", id.ID()) } resourceString := d.Get("resource").(string) @@ -182,12 +209,12 @@ func resourceStorageDataLakeGen2PathCreate(d *pluginsdk.ResourceData, meta inter case "directory": resource = paths.PathResourceDirectory default: - return fmt.Errorf("Unhandled resource type %q", resourceString) + return fmt.Errorf("unhandled resource type %q", resourceString) } aceRaw := d.Get("ace").(*pluginsdk.Set).List() acl, err := ExpandDataLakeGen2AceList(aceRaw) if err != nil { - return fmt.Errorf("parsing ace list: %s", err) + return fmt.Errorf("parsing ace list: %v", err) } var owner *string @@ -201,13 +228,13 @@ func resourceStorageDataLakeGen2PathCreate(d *pluginsdk.ResourceData, meta inter group = &sv } - log.Printf("[INFO] Creating Path %q in File System %q in %s.", path, fileSystemName, storageID) + log.Printf("[INFO] Creating %s...", id) input := paths.CreateInput{ Resource: resource, } - if _, err := client.Create(ctx, storageID.StorageAccountName, fileSystemName, path, input); err != nil { - return fmt.Errorf("creating Path %q in File System %q in %s: %+v", path, fileSystemName, storageID.StorageAccountName, err) + if _, err = dataPlanePathsClient.Create(ctx, filesystemName, path, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } if acl != nil || owner != nil || group != nil { @@ -221,29 +248,39 @@ func resourceStorageDataLakeGen2PathCreate(d *pluginsdk.ResourceData, meta inter Owner: owner, Group: group, } - if _, err := client.SetAccessControl(ctx, storageID.StorageAccountName, fileSystemName, path, accessControlInput); err != nil { - return fmt.Errorf("setting access control for Path %q in File System %q in %s: %+v", path, fileSystemName, storageID, err) + if _, err = dataPlanePathsClient.SetAccessControl(ctx, filesystemName, path, accessControlInput); err != nil { + return fmt.Errorf("setting access control for %s: %+v", id, err) } } - d.SetId(id) + d.SetId(id.ID()) + return resourceStorageDataLakeGen2PathRead(d, meta) } func resourceStorageDataLakeGen2PathUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - accountsClient := meta.(*clients.Client).Storage.AccountsClient - client := meta.(*clients.Client).Storage.ADLSGen2PathsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := paths.ParseResourceID(d.Id()) + id, err := paths.ParsePathID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - storageID, err := commonids.ParseStorageAccountID(d.Get("storage_account_id").(string)) + // Retrieve the storage account properties + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return err + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", id.AccountId.AccountName, id.FileSystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) + } + + // Build the data plane client + dataPlanePathsClient, err := storageClient.DataLakePathsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Data Lake Gen2 Paths Client: %v", err) } path := d.Get("path").(string) @@ -251,7 +288,7 @@ func resourceStorageDataLakeGen2PathUpdate(d *pluginsdk.ResourceData, meta inter aceRaw := d.Get("ace").(*pluginsdk.Set).List() acl, err := ExpandDataLakeGen2AceList(aceRaw) if err != nil { - return fmt.Errorf("parsing ace list: %s", err) + return fmt.Errorf("parsing ace list: %v", err) } var owner *string @@ -265,16 +302,6 @@ func resourceStorageDataLakeGen2PathUpdate(d *pluginsdk.ResourceData, meta inter group = &sv } - // confirm the storage account exists, otherwise Data Plane API requests will fail - storageAccount, err := accountsClient.GetProperties(ctx, storageID.ResourceGroupName, storageID.StorageAccountName, "") - if err != nil { - if utils.ResponseWasNotFound(storageAccount.Response) { - return fmt.Errorf("%s was not found", storageID) - } - - return fmt.Errorf("checking for existence of %s: %+v", storageID, err) - } - if acl != nil || owner != nil || group != nil { var aclString *string if acl != nil { @@ -286,8 +313,8 @@ func resourceStorageDataLakeGen2PathUpdate(d *pluginsdk.ResourceData, meta inter Owner: owner, Group: group, } - if _, err := client.SetAccessControl(ctx, id.AccountName, id.FileSystemName, path, accessControlInput); err != nil { - return fmt.Errorf("setting access control for Path %q in File System %q in Storage Account %q: %s", path, id.FileSystemName, id.AccountName, err) + if _, err = dataPlanePathsClient.SetAccessControl(ctx, id.FileSystemName, path, accessControlInput); err != nil { + return fmt.Errorf("setting access control for %s: %s", id, err) } } @@ -295,24 +322,39 @@ func resourceStorageDataLakeGen2PathUpdate(d *pluginsdk.ResourceData, meta inter } func resourceStorageDataLakeGen2PathRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Storage.ADLSGen2PathsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := paths.ParseResourceID(d.Id()) + id, err := paths.ParsePathID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - resp, err := client.GetProperties(ctx, id.AccountName, id.FileSystemName, id.Path, paths.GetPropertiesActionGetStatus) + // Retrieve the storage account properties + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) + if err != nil { + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", id.AccountId.AccountName, id.FileSystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) + } + + // Build the data plane client + dataPlanePathsClient, err := storageClient.DataLakePathsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[INFO] Path %q does not exist in File System %q in Storage Account %q - removing from state...", id.Path, id.FileSystemName, id.AccountName) + return fmt.Errorf("building Data Lake Gen2 Paths Client: %v", err) + } + + resp, err := dataPlanePathsClient.GetProperties(ctx, id.FileSystemName, id.Path, paths.GetPropertiesInput{Action: paths.GetPropertiesActionGetStatus}) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[INFO] Path %q does not exist in File System %q in Storage Account %q - removing from state...", id.Path, id.FileSystemName, id.AccountId.AccountName) d.SetId("") return nil } - return fmt.Errorf("retrieving Path %q in File System %q in Storage Account %q: %+v", id.Path, id.FileSystemName, id.AccountName, err) + return fmt.Errorf("retrieving %s: %v", id, err) } d.Set("path", id.Path) @@ -322,20 +364,20 @@ func resourceStorageDataLakeGen2PathRead(d *pluginsdk.ResourceData, meta interfa // The above `getStatus` API request doesn't return the ACLs // Have to make a `getAccessControl` request, but that doesn't return all fields either! - resp, err = client.GetProperties(ctx, id.AccountName, id.FileSystemName, id.Path, paths.GetPropertiesActionGetAccessControl) + resp, err = dataPlanePathsClient.GetProperties(ctx, id.FileSystemName, id.Path, paths.GetPropertiesInput{Action: paths.GetPropertiesActionGetAccessControl}) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[INFO] Path %q does not exist in File System %q in Storage Account %q - removing from state...", id.Path, id.FileSystemName, id.AccountName) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[INFO] Path %q does not exist in File System %q in Storage Account %q - removing from state...", id.Path, id.FileSystemName, id.AccountId.AccountName) d.SetId("") return nil } - return fmt.Errorf("retrieving ACLs for Path %q in File System %q in Storage Account %q: %+v", id.Path, id.FileSystemName, id.AccountName, err) + return fmt.Errorf("retrieving ACLs for %s: %v", id, err) } acl, err := accesscontrol.ParseACL(resp.ACL) if err != nil { - return fmt.Errorf("parsing response ACL %q: %s", resp.ACL, err) + return fmt.Errorf("parsing response ACL %q: %v", resp.ACL, err) } d.Set("ace", FlattenDataLakeGen2AceList(d, acl)) @@ -343,19 +385,34 @@ func resourceStorageDataLakeGen2PathRead(d *pluginsdk.ResourceData, meta interfa } func resourceStorageDataLakeGen2PathDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Storage.ADLSGen2PathsClient + storageClient := meta.(*clients.Client).Storage ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := paths.ParseResourceID(d.Id()) + id, err := paths.ParsePathID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - resp, err := client.Delete(ctx, id.AccountName, id.FileSystemName, id.Path) + // Retrieve the storage account properties + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) + if err != nil { + return fmt.Errorf("retrieving Account %q for Data Lake Gen2 Filesystem %q: %v", id.AccountId.AccountName, id.FileSystemName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) + } + + // Build the data plane client + dataPlanePathsClient, err := storageClient.DataLakePathsDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Data Lake Gen2 Paths Client: %v", err) + } + + resp, err := dataPlanePathsClient.Delete(ctx, id.FileSystemName, id.Path) if err != nil { - if !utils.ResponseWasNotFound(resp) { - return fmt.Errorf("deleting Path %q in File System %q in Storage Account %q: %+v", id.Path, id.FileSystemName, id.AccountName, err) + if !response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("deleting %s: %v", id, err) } } diff --git a/internal/services/storage/storage_data_lake_gen2_path_resource_test.go b/internal/services/storage/storage_data_lake_gen2_path_resource_test.go index b38158910a93..81d8130c5934 100644 --- a/internal/services/storage/storage_data_lake_gen2_path_resource_test.go +++ b/internal/services/storage/storage_data_lake_gen2_path_resource_test.go @@ -8,12 +8,13 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths" ) type StorageDataLakeGen2PathResource struct{} @@ -131,17 +132,32 @@ func TestAccStorageDataLakeGen2Path_withSuperUsers(t *testing.T) { } func (r StorageDataLakeGen2PathResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := paths.ParseResourceID(state.ID) + id, err := paths.ParsePathID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - resp, err := client.Storage.ADLSGen2PathsClient.GetProperties(ctx, id.AccountName, id.FileSystemName, id.Path, paths.GetPropertiesActionGetStatus) + + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) + if err != nil { + return nil, fmt.Errorf("retrieving Account %q for Queue %q: %+v", id.AccountId, id.FileSystemName, err) + } + if account == nil { + return nil, fmt.Errorf("unable to determine Resource Group for Storage Queue %q (Account %q)", id.FileSystemName, id.AccountId.AccountName) + } + + pathsClient, err := client.Storage.DataLakePathsDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + return nil, fmt.Errorf("building Data Lake Gen2 Paths Client: %+v", err) + } + + resp, err := pathsClient.GetProperties(ctx, id.FileSystemName, id.Path, paths.GetPropertiesInput{Action: paths.GetPropertiesActionGetStatus}) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } - return nil, fmt.Errorf("retrieving Path %q (File System %q / Account %q): %+v", id.Path, id.FileSystemName, id.AccountName, err) + return nil, fmt.Errorf("retrieving Path %q (File System %q / Account %q): %+v", id.Path, id.FileSystemName, id.AccountId.AccountName, err) } + return utils.Bool(true), nil } diff --git a/internal/services/storage/storage_queue_resource.go b/internal/services/storage/storage_queue_resource.go index 31b776bd0f1d..18753623b58d 100644 --- a/internal/services/storage/storage_queue_resource.go +++ b/internal/services/storage/storage_queue_resource.go @@ -10,11 +10,15 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues" ) func resourceStorageQueue() *pluginsdk.Resource { @@ -24,8 +28,8 @@ func resourceStorageQueue() *pluginsdk.Resource { Update: resourceStorageQueueUpdate, Delete: resourceStorageQueueDelete, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.StorageQueueDataPlaneID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := queues.ParseQueueID(id, storageDomainSuffix) return err }), @@ -79,32 +83,45 @@ func resourceStorageQueueCreate(d *pluginsdk.ResourceData, meta interface{}) err account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Queue %q: %s", accountName, queueName, err) + return fmt.Errorf("retrieving Account %q for Queue %q: %v", accountName, queueName, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q", accountName) + return fmt.Errorf("locating Storage Account %q", accountName) } - client, err := storageClient.QueuesClient(ctx, *account) + queuesDataPlaneClient, err := storageClient.QueuesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Queues Client: %s", err) + return fmt.Errorf("building Queues Client: %v", err) } - resourceId := parse.NewStorageQueueDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, queueName).ID() + // Determine the queue endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeTable) + if err != nil { + return fmt.Errorf("determining Queue endpoint: %v", err) + } - exists, err := client.Exists(ctx, account.ResourceGroup, accountName, queueName) + // Parse the queue endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("checking for presence of existing Queue %q (Storage Account %q): %s", queueName, accountName, err) + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := queues.NewQueueID(*accountId, queueName).ID() + + exists, err := queuesDataPlaneClient.Exists(ctx, queueName) + if err != nil { + return fmt.Errorf("checking for existing %s: %v", id, err) } if exists != nil && *exists { - return tf.ImportAsExistsError("azurerm_storage_queue", resourceId) + return tf.ImportAsExistsError("azurerm_storage_queue", id) } - if err := client.Create(ctx, account.ResourceGroup, accountName, queueName, metaData); err != nil { - return fmt.Errorf("creating Queue %q (Account %q): %+v", queueName, accountName, err) + if err = queuesDataPlaneClient.Create(ctx, queueName, metaData); err != nil { + return fmt.Errorf("creating %s: %+v", id, err) } - d.SetId(resourceId) + d.SetId(id) + return resourceStorageQueueRead(d, meta) } @@ -113,7 +130,7 @@ func resourceStorageQueueUpdate(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageQueueDataPlaneID(d.Id()) + id, err := queues.ParseQueueID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } @@ -121,21 +138,21 @@ func resourceStorageQueueUpdate(d *pluginsdk.ResourceData, meta interface{}) err metaDataRaw := d.Get("metadata").(map[string]interface{}) metaData := ExpandMetaData(metaDataRaw) - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Queue %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Queue %q: %v", id.AccountId.AccountName, id.QueueName, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.QueuesClient(ctx, *account) + client, err := storageClient.QueuesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Queues Client: %s", err) + return fmt.Errorf("building Queues Client: %v", err) } - if err := client.UpdateMetaData(ctx, account.ResourceGroup, id.AccountName, id.Name, metaData); err != nil { - return fmt.Errorf("updating MetaData for Queue %q (Storage Account %q): %s", id.Name, id.AccountName, err) + if err = client.UpdateMetaData(ctx, id.QueueName, metaData); err != nil { + return fmt.Errorf("updating MetaData for %s: %v", id, err) } return resourceStorageQueueRead(d, meta) @@ -147,44 +164,44 @@ func resourceStorageQueueRead(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageQueueDataPlaneID(d.Id()) + id, err := queues.ParseQueueID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Queue %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Queue %q: %v", id.AccountId.AccountName, id.QueueName, err) } if account == nil { - log.Printf("[WARN] Unable to determine Resource Group for Storage Queue %q (Account %s) - assuming removed & removing from state", id.Name, id.AccountName) + log.Printf("[WARN] Unable to determine Resource Group for Storage Queue %q (Account %s) - assuming removed & removing from state", id.QueueName, id.AccountId.AccountName) d.SetId("") return nil } - client, err := storageClient.QueuesClient(ctx, *account) + client, err := storageClient.QueuesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Queues Client: %s", err) + return fmt.Errorf("building Queues Client: %v", err) } - queue, err := client.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + queue, err := client.Get(ctx, id.QueueName) if err != nil { - return fmt.Errorf("retrieving Queue %q (Account %q): %+v", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving %s: %v", id, err) } if queue == nil { - log.Printf("[INFO] Storage Queue %q no longer exists, removing from state...", id.Name) + log.Printf("[INFO] Storage Queue %q no longer exists, removing from state...", id.QueueName) d.SetId("") return nil } - d.Set("name", id.Name) - d.Set("storage_account_name", id.AccountName) + d.Set("name", id.QueueName) + d.Set("storage_account_name", id.AccountId.AccountName) if err := d.Set("metadata", FlattenMetaData(queue.MetaData)); err != nil { return fmt.Errorf("setting `metadata`: %s", err) } - resourceManagerId := parse.NewStorageQueueResourceManagerID(subscriptionId, account.ResourceGroup, id.AccountName, "default", id.Name) + resourceManagerId := parse.NewStorageQueueResourceManagerID(subscriptionId, account.ResourceGroup, id.AccountId.AccountName, "default", id.QueueName) d.Set("resource_manager_id", resourceManagerId.ID()) return nil @@ -195,28 +212,28 @@ func resourceStorageQueueDelete(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageQueueDataPlaneID(d.Id()) + id, err := queues.ParseQueueID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Queue %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Queue %q: %s", id.AccountId.AccountName, id.QueueName, err) } if account == nil { - log.Printf("[WARN] Unable to determine Resource Group for Storage Queue %q (Account %s) - assuming removed & removing from state", id.Name, id.AccountName) + log.Printf("[WARN] Unable to determine Resource Group for Storage Queue %q (Account %s) - assuming removed & removing from state", id.QueueName, id.AccountId.AccountName) d.SetId("") return nil } - client, err := storageClient.QueuesClient(ctx, *account) + client, err := storageClient.QueuesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Queues Client: %s", err) + return fmt.Errorf("building Queues Client: %v", err) } - if err := client.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return fmt.Errorf("deleting Storage Queue %q (Account %q): %s", id.Name, id.AccountName, err) + if err = client.Delete(ctx, id.QueueName); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil diff --git a/internal/services/storage/storage_queue_resource_test.go b/internal/services/storage/storage_queue_resource_test.go index 178637af8368..70979503d6b0 100644 --- a/internal/services/storage/storage_queue_resource_test.go +++ b/internal/services/storage/storage_queue_resource_test.go @@ -11,9 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues" ) type StorageQueueResource struct{} @@ -86,24 +86,24 @@ func TestAccStorageQueue_metaData(t *testing.T) { } func (r StorageQueueResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageQueueDataPlaneID(state.ID) + id, err := queues.ParseQueueID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Queue %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Queue %q: %+v", id.AccountId.AccountName, id.QueueName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Resource Group for Storage Queue %q (Account %q)", id.Name, id.AccountName) + return nil, fmt.Errorf("unable to determine Resource Group for Storage Queue %q (Account %q)", id.QueueName, id.AccountId.AccountName) } - queuesClient, err := client.Storage.QueuesClient(ctx, *account) + queuesClient, err := client.Storage.QueuesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Queues Client: %+v", err) } - queue, err := queuesClient.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + queue, err := queuesClient.Get(ctx, id.QueueName) if err != nil { - return nil, fmt.Errorf("retrieving Queue %q (Account %q): %+v", id.Name, id.AccountName, err) + return nil, fmt.Errorf("retrieving Queue %q (Account %q): %+v", id.QueueName, id.AccountId.AccountName, err) } return utils.Bool(queue != nil), nil } diff --git a/internal/services/storage/storage_share_data_source.go b/internal/services/storage/storage_share_data_source.go index 76f0fc0d026b..9faace9ed9ae 100644 --- a/internal/services/storage/storage_share_data_source.go +++ b/internal/services/storage/storage_share_data_source.go @@ -8,9 +8,12 @@ import ( "time" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) func dataSourceStorageShare() *pluginsdk.Resource { @@ -90,36 +93,50 @@ func dataSourceStorageShareRead(d *pluginsdk.ResourceData, meta interface{}) err account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Share %q: %s", accountName, shareName, err) + return fmt.Errorf("retrieving Storage Account %q for Share %q: %s", accountName, shareName, err) } if account == nil { - return fmt.Errorf("unable to locate Account %q for Share %q", accountName, shareName) + return fmt.Errorf("locating Storage Account %q for Share %q", accountName, shareName) } - client, err := storageClient.FileSharesClient(ctx, *account) + // The files API does not support bearer tokens (@manicminer, 2024-02-15) + sharesDataPlaneClient, err := storageClient.FileSharesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) if err != nil { - return fmt.Errorf("building FileShares Client for Storage Account %q (Resource Group %q): %s", accountName, account.ResourceGroup, err) + return fmt.Errorf("building FileShares Client: %v", err) } - id := parse.NewStorageShareDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, shareName).ID() - props, err := client.Get(ctx, account.ResourceGroup, accountName, shareName) + // Determine the file endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeFile) if err != nil { - return fmt.Errorf("retrieving Share %q (Account %q / Resource Group %q): %s", shareName, accountName, account.ResourceGroup, err) + return fmt.Errorf("determining File endpoint: %v", err) + } + + // Parse the file endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := shares.NewShareID(*accountId, shareName).ID() + + props, err := sharesDataPlaneClient.Get(ctx, shareName) + if err != nil { + return fmt.Errorf("retrieving %s: %v", id, err) } if props == nil { - return fmt.Errorf("share %q was not found in Account %q / Resource Group %q", shareName, accountName, account.ResourceGroup) + return fmt.Errorf("%s was not found", id) } d.SetId(id) d.Set("name", shareName) d.Set("storage_account_name", accountName) d.Set("quota", props.QuotaGB) - if err := d.Set("acl", flattenStorageShareACLs(props.ACLs)); err != nil { - return fmt.Errorf("setting `acl`: %+v", err) + if err = d.Set("acl", flattenStorageShareACLs(props.ACLs)); err != nil { + return fmt.Errorf("setting `acl`: %v", err) } - if err := d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { - return fmt.Errorf("setting `metadata`: %+v", err) + if err = d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { + return fmt.Errorf("setting `metadata`: %v", err) } resourceManagerId := parse.NewStorageShareResourceManagerID(storageClient.SubscriptionId, account.ResourceGroup, accountName, "default", shareName) diff --git a/internal/services/storage/storage_share_directory_resource.go b/internal/services/storage/storage_share_directory_resource.go index 67f91fe22134..7629a44c0966 100644 --- a/internal/services/storage/storage_share_directory_resource.go +++ b/internal/services/storage/storage_share_directory_resource.go @@ -10,14 +10,19 @@ import ( "strconv" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) func resourceStorageShareDirectory() *pluginsdk.Resource { @@ -27,8 +32,8 @@ func resourceStorageShareDirectory() *pluginsdk.Resource { Update: resourceStorageShareDirectoryUpdate, Delete: resourceStorageShareDirectoryDelete, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := directories.ParseResourceID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := directories.ParseDirectoryID(id, storageDomainSuffix) return err }), @@ -46,17 +51,36 @@ func resourceStorageShareDirectory() *pluginsdk.Resource { ForceNew: true, ValidateFunc: validate.StorageShareDirectoryName, }, + + "storage_share_id": { + Type: pluginsdk.TypeString, + Optional: true, // TODO: make required and forcenew in v4.0 + Computed: true, // TODO: remove computed in v4.0 + ForceNew: true, + ConflictsWith: []string{"share_name", "storage_account_name"}, + ValidateFunc: validation.IsURLWithPath, // note: storage domain suffix cannot be determined at validation time, so just make sure it's a well-formed URL + }, + "share_name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, + Type: pluginsdk.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + Deprecated: "the `share_name` and `storage_account_name` properties have been superseded by the `storage_share_id` property and will be removed in version 4.0 of the AzureRM provider", + ConflictsWith: []string{"storage_share_id"}, + RequiredWith: []string{"storage_account_name"}, + ValidateFunc: validation.StringIsNotEmpty, }, + "storage_account_name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, + Type: pluginsdk.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + Deprecated: "the `share_name` and `storage_account_name` properties have been superseded by the `storage_share_id` property and will be removed in version 4.0 of the AzureRM provider", + ConflictsWith: []string{"storage_share_id"}, + RequiredWith: []string{"share_name"}, + ValidateFunc: validation.StringIsNotEmpty, }, "metadata": MetaDataSchema(), @@ -69,62 +93,103 @@ func resourceStorageShareDirectoryCreate(d *pluginsdk.ResourceData, meta interfa defer cancel() storageClient := meta.(*clients.Client).Storage - accountName := d.Get("storage_account_name").(string) - shareName := d.Get("share_name").(string) directoryName := d.Get("name").(string) - metaDataRaw := d.Get("metadata").(map[string]interface{}) metaData := ExpandMetaData(metaDataRaw) - account, err := storageClient.FindAccount(ctx, accountName) + var storageShareId *shares.ShareId + var err error + if v, ok := d.GetOk("storage_share_id"); ok && v.(string) != "" { + storageShareId, err = shares.ParseShareID(v.(string), storageClient.StorageDomainSuffix) + if err != nil { + return err + } + } else { + // TODO: this is needed until `share_name` / `storage_account_name` are removed in favor of `storage_share_id` in v4.0 + // we will retrieve the storage account twice but this will make it easier to refactor later + storageAccountName := d.Get("storage_account_name").(string) + + account, err := storageClient.FindAccount(ctx, storageAccountName) + if err != nil { + return fmt.Errorf("retrieving Account %q: %v", storageAccountName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", storageAccountName) + } + + // Determine the file endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeFile) + if err != nil { + return fmt.Errorf("determining File endpoint: %v", err) + } + + // Parse the file endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + storageShareId = pointer.To(shares.NewShareID(*accountId, d.Get("share_name").(string))) + } + + if storageShareId == nil { + return fmt.Errorf("determining storage share ID") + } + + account, err := storageClient.FindAccount(ctx, storageShareId.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %s", accountName, directoryName, shareName, err) + return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %v", storageShareId.AccountId.AccountName, directoryName, storageShareId.ShareName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", accountName) + return fmt.Errorf("locating Storage Account %q", storageShareId.AccountId.AccountName) + } + + accountId, err := accounts.ParseAccountID(storageShareId.ID(), storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) } - client, err := storageClient.FileShareDirectoriesClient(ctx, *account) + id := directories.NewDirectoryID(*accountId, storageShareId.ShareName, directoryName) + + client, err := storageClient.FileShareDirectoriesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building File Share Directories Client: %s", err) + return fmt.Errorf("building File Share Directories Client: %v", err) } - existing, err := client.Get(ctx, accountName, shareName, directoryName) + existing, err := client.Get(ctx, storageShareId.ShareName, directoryName) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing Directory %q (File Share %q / Storage Account %q / Resource Group %q): %s", directoryName, shareName, accountName, account.ResourceGroup, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for existing %s: %s", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - id := client.GetResourceID(accountName, shareName, directoryName) - return tf.ImportAsExistsError("azurerm_storage_share_directory", id) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_storage_share_directory", id.ID()) } input := directories.CreateDirectoryInput{ MetaData: metaData, } - if _, err := client.Create(ctx, accountName, shareName, directoryName, input); err != nil { - return fmt.Errorf("creating Directory %q (File Share %q / Account %q): %+v", directoryName, shareName, accountName, err) + if _, err = client.Create(ctx, storageShareId.ShareName, directoryName, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } // Storage Share Directories are eventually consistent - log.Printf("[DEBUG] Waiting for Directory %q (File Share %q / Account %q) to become available", directoryName, shareName, accountName) + log.Printf("[DEBUG] Waiting for %s to become available", id) stateConf := &pluginsdk.StateChangeConf{ Pending: []string{"404"}, Target: []string{"200"}, - Refresh: storageShareDirectoryRefreshFunc(ctx, client, accountName, shareName, directoryName), + Refresh: storageShareDirectoryRefreshFunc(ctx, client, id), MinTimeout: 10 * time.Second, ContinuousTargetOccurence: 5, Timeout: d.Timeout(pluginsdk.TimeoutCreate), } - if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for Directory %q (File Share %q / Account %q) to become available: %s", directoryName, shareName, accountName, err) + if _, err = stateConf.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for %s to become available: %v", id, err) } - resourceID := client.GetResourceID(accountName, shareName, directoryName) - d.SetId(resourceID) + d.SetId(id.ID()) return resourceStorageShareDirectoryRead(d, meta) } @@ -134,7 +199,7 @@ func resourceStorageShareDirectoryUpdate(d *pluginsdk.ResourceData, meta interfa defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := directories.ParseResourceID(d.Id()) + id, err := directories.ParseDirectoryID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } @@ -142,21 +207,21 @@ func resourceStorageShareDirectoryUpdate(d *pluginsdk.ResourceData, meta interfa metaDataRaw := d.Get("metadata").(map[string]interface{}) metaData := ExpandMetaData(metaDataRaw) - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %s", id.AccountName, id.DirectoryName, id.ShareName, err) + return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %v", id.AccountId.AccountName, id.DirectoryPath, id.ShareName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account: %q", id.AccountId.AccountName) } - client, err := storageClient.FileShareDirectoriesClient(ctx, *account) + client, err := storageClient.FileShareDirectoriesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building File Share Client: %s", err) + return fmt.Errorf("building File Share Client: %v", err) } - if _, err := client.SetMetaData(ctx, id.AccountName, id.ShareName, id.DirectoryName, metaData); err != nil { - return fmt.Errorf("updating MetaData for Directory %q (File Share %q / Account %q): %+v", id.DirectoryName, id.ShareName, id.AccountName, err) + if _, err = client.SetMetaData(ctx, id.ShareName, id.DirectoryPath, directories.SetMetaDataInput{MetaData: metaData}); err != nil { + return fmt.Errorf("updating Metadata for %s: %v", id, err) } return resourceStorageShareDirectoryRead(d, meta) @@ -167,37 +232,52 @@ func resourceStorageShareDirectoryRead(d *pluginsdk.ResourceData, meta interface defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := directories.ParseResourceID(d.Id()) + id, err := directories.ParseDirectoryID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %s", id.AccountName, id.DirectoryName, id.ShareName, err) + return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %v", id.AccountId.AccountName, id.DirectoryPath, id.ShareName, err) } if account == nil { - log.Printf("[WARN] Unable to determine Resource Group for Storage Share Directory %q (Share %s, Account %s) - assuming removed & removing from state", id.DirectoryName, id.ShareName, id.AccountName) + log.Printf("[WARN] Unable to determine Resource Group for Storage Share Directory %q (Share %s, Account %s) - assuming removed & removing from state", id.DirectoryPath, id.ShareName, id.AccountId.AccountName) d.SetId("") return nil } - client, err := storageClient.FileShareDirectoriesClient(ctx, *account) + // Determine the file endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeFile) + if err != nil { + return fmt.Errorf("determining File endpoint: %v", err) + } + + // Parse the file endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + storageShareId := shares.NewShareID(*accountId, id.ShareName) + + client, err := storageClient.FileShareDirectoriesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building File Share Client: %v", err) } - props, err := client.Get(ctx, id.AccountName, id.ShareName, id.DirectoryName) + props, err := client.Get(ctx, id.ShareName, id.DirectoryPath) if err != nil { - return fmt.Errorf("retrieving Storage Share %q (File Share %q / Account %q / Resource Group %q): %s", id.DirectoryName, id.ShareName, id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %v", id, err) } - d.Set("name", id.DirectoryName) + d.Set("name", id.DirectoryPath) + d.Set("storage_share_id", storageShareId.ID()) d.Set("share_name", id.ShareName) - d.Set("storage_account_name", id.AccountName) + d.Set("storage_account_name", id.AccountId.AccountName) - if err := d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { - return fmt.Errorf("setting `metadata`: %s", err) + if err = d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { + return fmt.Errorf("setting `metadata`: %v", err) } return nil @@ -208,38 +288,38 @@ func resourceStorageShareDirectoryDelete(d *pluginsdk.ResourceData, meta interfa defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := directories.ParseResourceID(d.Id()) + id, err := directories.ParseDirectoryID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %s", id.AccountName, id.DirectoryName, id.ShareName, err) + return fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %v", id.AccountId.AccountName, id.DirectoryPath, id.ShareName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.FileShareDirectoriesClient(ctx, *account) + client, err := storageClient.FileShareDirectoriesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building File Share Client: %v", err) } - if _, err := client.Delete(ctx, id.AccountName, id.ShareName, id.DirectoryName); err != nil { - return fmt.Errorf("deleting Storage Share %q (File Share %q / Account %q / Resource Group %q): %s", id.DirectoryName, id.ShareName, id.AccountName, account.ResourceGroup, err) + if _, err = client.Delete(ctx, id.ShareName, id.DirectoryPath); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil } -func storageShareDirectoryRefreshFunc(ctx context.Context, client *directories.Client, accountName, shareName, directoryName string) pluginsdk.StateRefreshFunc { +func storageShareDirectoryRefreshFunc(ctx context.Context, client *directories.Client, id directories.DirectoryId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.Get(ctx, accountName, shareName, directoryName) + res, err := client.Get(ctx, id.ShareName, id.DirectoryPath) if err != nil { - return nil, strconv.Itoa(res.StatusCode), fmt.Errorf("retrieving Directory %q (File Share %q / Account %q): %s", directoryName, shareName, accountName, err) + return nil, strconv.Itoa(res.HttpResponse.StatusCode), fmt.Errorf("retrieving %s: %v", id, err) } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } diff --git a/internal/services/storage/storage_share_directory_resource_test.go b/internal/services/storage/storage_share_directory_resource_test.go index f68cfde672fc..573a34b25a6c 100644 --- a/internal/services/storage/storage_share_directory_resource_test.go +++ b/internal/services/storage/storage_share_directory_resource_test.go @@ -8,12 +8,13 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories" ) type StorageShareDirectoryResource struct{} @@ -33,6 +34,67 @@ func TestAccStorageShareDirectory_basic(t *testing.T) { }) } +func TestAccStorageShareDirectory_basicAzureADAuth(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_storage_share_directory", "test") + r := StorageShareDirectoryResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicAzureADAuth(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccStorageShareDirectory_basicDeprecated(t *testing.T) { + // TODO: remove test in v4.0 + data := acceptance.BuildTestData(t, "azurerm_storage_share_directory", "test") + r := StorageShareDirectoryResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicDeprecated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccStorageShareDirectory_migrateStorageShareId(t *testing.T) { + // TODO: remove test in v4.0 + data := acceptance.BuildTestData(t, "azurerm_storage_share_directory", "test") + r := StorageShareDirectoryResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicDeprecated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basicDeprecated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccStorageShareDirectory_uppercase(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_share_directory", "test") r := StorageShareDirectoryResource{} @@ -119,27 +181,27 @@ func TestAccStorageShareDirectory_nested(t *testing.T) { } func (r StorageShareDirectoryResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := directories.ParseResourceID(state.ID) + id, err := directories.ParseDirectoryID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %s", id.AccountName, id.DirectoryName, id.ShareName, err) + return nil, fmt.Errorf("retrieving Account %q for Directory %q (Share %q): %s", id.AccountId.AccountName, id.DirectoryPath, id.ShareName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Resource Group for Storage Share Directory %q (Share %q / Account %q)", id.DirectoryName, id.ShareName, id.AccountName) + return nil, fmt.Errorf("unable to determine Resource Group for Storage Share Directory %q (Share %q / Account %q)", id.DirectoryPath, id.ShareName, id.AccountId.AccountName) } - dirClient, err := client.Storage.FileShareDirectoriesClient(ctx, *account) + dirClient, err := client.Storage.FileShareDirectoriesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return nil, fmt.Errorf("building File Share client for Storage Account %q (Resource Group %q): %+v", id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("building File Share client for Storage Account %q (Resource Group %q): %+v", id.AccountId.AccountName, account.ResourceGroup, err) } - resp, err := dirClient.Get(ctx, id.AccountName, id.ShareName, id.DirectoryName) + resp, err := dirClient.Get(ctx, id.ShareName, id.DirectoryPath) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } - return nil, fmt.Errorf("retrieving Storage Share %q (File Share %q / Account %q / Resource Group %q): %s", id.DirectoryName, id.ShareName, id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("retrieving Storage Share %q (File Share %q / Account %q / Resource Group %q): %s", id.DirectoryPath, id.ShareName, id.AccountId.AccountName, account.ResourceGroup, err) } return utils.Bool(true), nil } @@ -149,6 +211,51 @@ func (r StorageShareDirectoryResource) basic(data acceptance.TestData) string { return fmt.Sprintf(` %s +resource "azurerm_storage_share_directory" "test" { + name = "dir" + storage_share_id = azurerm_storage_share.test.id +} +`, template) +} + +func (r StorageShareDirectoryResource) basicAzureADAuth(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + storage_use_azuread = true + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "%[2]s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestsa%[3]s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_storage_share" "test" { + name = "fileshare" + storage_account_name = azurerm_storage_account.test.name + quota = 50 +} + +resource "azurerm_storage_share_directory" "test" { + name = "dir" + storage_share_id = azurerm_storage_share.test.id +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString) +} + +func (r StorageShareDirectoryResource) basicDeprecated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + resource "azurerm_storage_share_directory" "test" { name = "dir" share_name = azurerm_storage_share.test.name @@ -163,9 +270,8 @@ func (r StorageShareDirectoryResource) uppercase(data acceptance.TestData) strin %s resource "azurerm_storage_share_directory" "test" { - name = "UpperCaseCharacterS" - share_name = azurerm_storage_share.test.name - storage_account_name = azurerm_storage_account.test.name + name = "UpperCaseCharacterS" + storage_share_id = azurerm_storage_share.test.id } `, template) } @@ -176,9 +282,8 @@ func (r StorageShareDirectoryResource) requiresImport(data acceptance.TestData) %s resource "azurerm_storage_share_directory" "import" { - name = azurerm_storage_share_directory.test.name - share_name = azurerm_storage_share_directory.test.share_name - storage_account_name = azurerm_storage_share_directory.test.storage_account_name + name = azurerm_storage_share_directory.test.name + storage_share_id = azurerm_storage_share.test.id } `, template) } @@ -189,9 +294,8 @@ func (r StorageShareDirectoryResource) complete(data acceptance.TestData) string %s resource "azurerm_storage_share_directory" "test" { - name = "dir" - share_name = azurerm_storage_share.test.name - storage_account_name = azurerm_storage_account.test.name + name = "dir" + storage_share_id = azurerm_storage_share.test.id metadata = { hello = "world" @@ -206,9 +310,8 @@ func (r StorageShareDirectoryResource) updated(data acceptance.TestData) string %s resource "azurerm_storage_share_directory" "test" { - name = "dir" - share_name = azurerm_storage_share.test.name - storage_account_name = azurerm_storage_account.test.name + name = "dir" + storage_share_id = azurerm_storage_share.test.id metadata = { hello = "world" @@ -224,27 +327,23 @@ func (r StorageShareDirectoryResource) nested(data acceptance.TestData) string { %s resource "azurerm_storage_share_directory" "parent" { - name = "123--parent-dir" - share_name = azurerm_storage_share.test.name - storage_account_name = azurerm_storage_account.test.name + name = "123--parent-dir" + storage_share_id = azurerm_storage_share.test.id } resource "azurerm_storage_share_directory" "child_one" { - name = "${azurerm_storage_share_directory.parent.name}/child1" - share_name = azurerm_storage_share.test.name - storage_account_name = azurerm_storage_account.test.name + name = "${azurerm_storage_share_directory.parent.name}/child1" + storage_share_id = azurerm_storage_share.test.id } resource "azurerm_storage_share_directory" "child_two" { - name = "${azurerm_storage_share_directory.child_one.name}/childtwo--123" - share_name = azurerm_storage_share.test.name - storage_account_name = azurerm_storage_account.test.name + name = "${azurerm_storage_share_directory.child_one.name}/childtwo--123" + storage_share_id = azurerm_storage_share.test.id } resource "azurerm_storage_share_directory" "multiple_child_one" { - name = "${azurerm_storage_share_directory.parent.name}/c" - share_name = azurerm_storage_share.test.name - storage_account_name = azurerm_storage_account.test.name + name = "${azurerm_storage_share_directory.parent.name}/c" + storage_share_id = azurerm_storage_share.test.id } `, template) } diff --git a/internal/services/storage/storage_share_file_resource.go b/internal/services/storage/storage_share_file_resource.go index 48b4cf882332..7fc78dcccfa4 100644 --- a/internal/services/storage/storage_share_file_resource.go +++ b/internal/services/storage/storage_share_file_resource.go @@ -9,15 +9,18 @@ import ( "os" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" storageValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) func resourceStorageShareFile() *pluginsdk.Resource { @@ -27,8 +30,8 @@ func resourceStorageShareFile() *pluginsdk.Resource { Update: resourceStorageShareFileUpdate, Delete: resourceStorageShareFileDelete, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := files.ParseResourceID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := files.ParseFileID(id, storageDomainSuffix) return err }), @@ -45,12 +48,14 @@ func resourceStorageShareFile() *pluginsdk.Resource { Required: true, ForceNew: true, }, + "storage_share_id": { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: storageValidate.StorageShareID, + ValidateFunc: validation.IsURLWithPath, // note: storage domain suffix cannot be determined at validation time, so just make sure it's a well-formed URL }, + "path": { Type: pluginsdk.TypeString, ForceNew: true, @@ -106,7 +111,7 @@ func resourceStorageShareFileCreate(d *pluginsdk.ResourceData, meta interface{}) defer cancel() storageClient := meta.(*clients.Client).Storage - storageShareID, err := parse.StorageShareDataPlaneID(d.Get("storage_share_id").(string)) + storageShareId, err := shares.ParseShareID(d.Get("storage_share_id").(string), storageClient.StorageDomainSuffix) if err != nil { return err } @@ -114,42 +119,35 @@ func resourceStorageShareFileCreate(d *pluginsdk.ResourceData, meta interface{}) fileName := d.Get("name").(string) path := d.Get("path").(string) - account, err := storageClient.FindAccount(ctx, storageShareID.AccountName) + account, err := storageClient.FindAccount(ctx, storageShareId.AccountId.AccountName) if err != nil { - return fmt.Errorf("eretrieving Account %q for File %q (Share %q): %s", storageShareID.AccountName, fileName, storageShareID.Name, err) + return fmt.Errorf("retrieving Account %q for File %q (Share %q): %v", storageShareId.AccountId.AccountName, fileName, storageShareId.ShareName, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q!", storageShareID.AccountName) + return fmt.Errorf("locating Storage Account %q", storageShareId.AccountId.AccountName) } - fileSharesClient, err := storageClient.FileSharesClient(ctx, *account) + accountId, err := accounts.ParseAccountID(storageShareId.ID(), storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("building File Share Directories Client: %s", err) + return fmt.Errorf("parsing Account ID: %v", err) } - share, err := fileSharesClient.Get(ctx, account.ResourceGroup, storageShareID.AccountName, storageShareID.Name) - if err != nil { - return fmt.Errorf("retrieving Share %q for File %q: %s", storageShareID.Name, fileName, err) - } - if share == nil { - return fmt.Errorf("unable to locate Storage Share %q", storageShareID.Name) - } + id := files.NewFileID(*accountId, storageShareId.ShareName, path, fileName) - client, err := storageClient.FileShareFilesClient(ctx, *account) + client, err := storageClient.FileShareFilesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building File Share Directories Client: %s", err) } - existing, err := client.GetProperties(ctx, storageShareID.AccountName, storageShareID.Name, path, fileName) + existing, err := client.GetProperties(ctx, storageShareId.ShareName, path, fileName) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing File %q (File Share %q / Storage Account %q / Resource Group %q): %s", fileName, storageShareID.Name, storageShareID.AccountName, account.ResourceGroup, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for existing %s: %v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - id := client.GetResourceID(storageShareID.AccountName, storageShareID.Name, path, fileName) - return tf.ImportAsExistsError("azurerm_storage_share_file", id) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_storage_share_file", id.ID()) } input := files.CreateInput{ @@ -167,33 +165,32 @@ func resourceStorageShareFileCreate(d *pluginsdk.ResourceData, meta interface{}) if v, ok := d.GetOk("source"); ok { file, err = os.Open(v.(string)) if err != nil { - return fmt.Errorf("opening file : %s", err) + return fmt.Errorf("opening file: %s", err) } info, err := file.Stat() if err != nil { - return fmt.Errorf("'stat'-ing File %q (File Share %q / Account %q): %+v", fileName, storageShareID.Name, storageShareID.AccountName, err) + return fmt.Errorf("'stat'-ing File %q (File Share %q / Account %q): %v", fileName, storageShareId.ShareName, storageShareId.AccountId.AccountName, err) } if info.Size() == 0 { - return fmt.Errorf("file %q (File Share %q / Account %q) is empty", fileName, storageShareID.Name, storageShareID.AccountName) + return fmt.Errorf("file %q (File Share %q / Account %q) is empty", fileName, storageShareId.ShareName, storageShareId.AccountId.AccountName) } input.ContentLength = info.Size() } - if _, err := client.Create(ctx, storageShareID.AccountName, storageShareID.Name, path, fileName, input); err != nil { - return fmt.Errorf("creating File %q (File Share %q / Account %q): %+v", fileName, storageShareID.Name, storageShareID.AccountName, err) + if _, err = client.Create(ctx, storageShareId.ShareName, path, fileName, input); err != nil { + return fmt.Errorf("creating File %q (File Share %q / Account %q): %v", fileName, storageShareId.ShareName, storageShareId.AccountId.AccountName, err) } if file != nil { - if err := client.PutFile(ctx, storageShareID.AccountName, storageShareID.Name, path, fileName, file, 4); err != nil { - return fmt.Errorf("uploading File: %q (File Share %q / Account %q): %+v", fileName, storageShareID.Name, storageShareID.AccountName, err) + if err = client.PutFile(ctx, storageShareId.ShareName, path, fileName, file, 4); err != nil { + return fmt.Errorf("uploading File: %q (File Share %q / Account %q): %v", fileName, storageShareId.ShareName, storageShareId.AccountId.AccountName, err) } } - resourceID := client.GetResourceID(storageShareID.AccountName, storageShareID.Name, path, fileName) - d.SetId(resourceID) + d.SetId(id.ID()) return resourceStorageShareFileRead(d, meta) } @@ -203,41 +200,28 @@ func resourceStorageShareFileUpdate(d *pluginsdk.ResourceData, meta interface{}) defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := files.ParseResourceID(d.Id()) + id, err := files.ParseFileID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for File %q (Share %q): %s", id.AccountName, id.FileName, id.ShareName, err) + return fmt.Errorf("retrieving Account %q for %s: %v", id.AccountId.AccountName, id, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q!", id.AccountName) - } - - fileSharesClient, err := storageClient.FileSharesClient(ctx, *account) - if err != nil { - return fmt.Errorf("building File Share Directories Client: %s", err) - } - - share, err := fileSharesClient.Get(ctx, account.ResourceGroup, id.AccountName, id.ShareName) - if err != nil { - return fmt.Errorf("retrieving Share %q for File %q: %s", id.ShareName, id.FileName, err) - } - if share == nil { - return fmt.Errorf("unable to locate Storage Share %q", id.ShareName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.FileShareFilesClient(ctx, *account) + client, err := storageClient.FileShareFilesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building File Share Files Client: %s", err) + return fmt.Errorf("building File Share Files Client: %v", err) } - existing, err := client.GetProperties(ctx, id.AccountName, id.ShareName, id.DirectoryName, id.FileName) + existing, err := client.GetProperties(ctx, id.ShareName, id.DirectoryPath, id.FileName) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing File %q (File Share %q / Storage Account %q / Resource Group %q): %s", id.FileName, id.ShareName, id.AccountName, account.ResourceGroup, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %v", id, err) } } @@ -254,8 +238,8 @@ func resourceStorageShareFileUpdate(d *pluginsdk.ResourceData, meta interface{}) input.ContentMD5 = utils.String(v.(string)) } - if _, err := client.SetProperties(ctx, id.AccountName, id.ShareName, id.DirectoryName, id.FileName, input); err != nil { - return fmt.Errorf("creating File %q (File Share %q / Account %q): %+v", id.FileName, id.ShareName, id.AccountName, err) + if _, err = client.SetProperties(ctx, id.ShareName, id.DirectoryPath, id.FileName, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } } @@ -267,53 +251,38 @@ func resourceStorageShareFileRead(d *pluginsdk.ResourceData, meta interface{}) e defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := files.ParseResourceID(d.Id()) + id, err := files.ParseFileID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for File %q (Share %q): %s", id.AccountName, id.FileName, id.ShareName, err) + return fmt.Errorf("retrieving Account %q for File %q (Share %q): %s", id.AccountId.AccountName, id.FileName, id.ShareName, err) } if account == nil { - log.Printf("[WARN] Unable to determine Storage Account for Storage Share File %q (Share %s, Account %s) - assuming removed & removing from state", id.FileName, id.ShareName, id.AccountName) - d.SetId("") - return nil - } - - fileSharesClient, err := storageClient.FileSharesClient(ctx, *account) - if err != nil { - return fmt.Errorf("building File Share Directories Client: %s", err) - } - - share, err := fileSharesClient.Get(ctx, account.ResourceGroup, id.AccountName, id.ShareName) - if err != nil { - return fmt.Errorf("retrieving Share %q for File %q: %s", id.ShareName, id.FileName, err) - } - if share == nil { - log.Printf("[WARN] Unable to determine Storage Share for Storage Share File %q (Share %s, Account %s) - assuming removed & removing from state", id.FileName, id.ShareName, id.AccountName) + log.Printf("[WARN] Unable to determine Storage Account for %s - assuming removed & removing from state", id) d.SetId("") return nil } - client, err := storageClient.FileShareFilesClient(ctx, *account) + client, err := storageClient.FileShareFilesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building File Share Client for Storage Account %s: %s", id.AccountId, err) } - props, err := client.GetProperties(ctx, id.AccountName, id.ShareName, id.DirectoryName, id.FileName) + props, err := client.GetProperties(ctx, id.ShareName, id.DirectoryPath, id.FileName) if err != nil { - log.Printf("Retrieving Storage File Share file %q (Directory %q / File Share %q / Account %q / Resource Group %q): %s", id.FileName, id.DirectoryName, id.ShareName, id.AccountName, account.ResourceGroup, err) + log.Printf("retrieving %s: %s", id, err) d.SetId("") return nil } d.Set("name", id.FileName) - d.Set("path", id.DirectoryName) - d.Set("storage_share_id", parse.NewStorageShareDataPlaneId(id.AccountName, storageClient.Environment.StorageEndpointSuffix, id.ShareName).ID()) + d.Set("path", id.DirectoryPath) + d.Set("storage_share_id", shares.NewShareID(id.AccountId, id.ShareName).ID()) - if err := d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { + if err = d.Set("metadata", FlattenMetaData(props.MetaData)); err != nil { return fmt.Errorf("setting `metadata`: %s", err) } d.Set("content_type", props.ContentType) @@ -335,26 +304,26 @@ func resourceStorageShareFileDelete(d *pluginsdk.ResourceData, meta interface{}) defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := files.ParseResourceID(d.Id()) + id, err := files.ParseFileID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for File %q (Share %q): %s", id.AccountName, id.FileName, id.ShareName, err) + return fmt.Errorf("retrieving Account %q for File %q (Share %q): %v", id.AccountId.AccountName, id.FileName, id.ShareName, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.FileShareFilesClient(ctx, *account) + client, err := storageClient.FileShareFilesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building File Share File Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building File Share File Client for Storage Account %q (Resource Group %q): %v", id.AccountId.AccountName, account.ResourceGroup, err) } - if _, err := client.Delete(ctx, id.AccountName, id.ShareName, id.DirectoryName, id.FileName); err != nil { - return fmt.Errorf("deleting Storage Share File %q (File Share %q / Account %q / Resource Group %q): %s", id.FileName, id.ShareName, id.AccountName, account.ResourceGroup, err) + if _, err = client.Delete(ctx, id.ShareName, id.DirectoryPath, id.FileName); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil diff --git a/internal/services/storage/storage_share_file_resource_test.go b/internal/services/storage/storage_share_file_resource_test.go index 2a2b5b0b3d64..139af76c9d67 100644 --- a/internal/services/storage/storage_share_file_resource_test.go +++ b/internal/services/storage/storage_share_file_resource_test.go @@ -10,12 +10,13 @@ import ( "regexp" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files" ) type StorageShareFileResource struct{} @@ -35,6 +36,21 @@ func TestAccAzureRMStorageShareFile_basic(t *testing.T) { }) } +func TestAccAzureRMStorageShareFile_basicAzureADAuth(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_storage_share_file", "test") + r := StorageShareFileResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicAzureADAuth(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccAzureRMStorageShareFile_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_share_file", "test") r := StorageShareFileResource{} @@ -137,28 +153,28 @@ func TestAccAzureRMStorageShareFile_withEmptyFile(t *testing.T) { } func (StorageShareFileResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := files.ParseResourceID(state.ID) + id, err := files.ParseFileID(state.ID, clients.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := clients.Storage.FindAccount(ctx, id.AccountName) + account, err := clients.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for File %q (Share %q): %s", id.AccountName, id.FileName, id.ShareName, err) + return nil, fmt.Errorf("retrieving Account %q for File %q (Share %q): %s", id.AccountId.AccountName, id.FileName, id.ShareName, err) } if account == nil { return utils.Bool(false), nil } - client, err := clients.Storage.FileShareFilesClient(ctx, *account) + client, err := clients.Storage.FileShareFilesDataPlaneClient(ctx, *account, clients.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building File Share Files Client: %s", err) } - resp, err := client.GetProperties(ctx, id.AccountName, id.ShareName, id.DirectoryName, id.FileName) + resp, err := client.GetProperties(ctx, id.ShareName, id.DirectoryPath, id.FileName) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return nil, fmt.Errorf("checking for presence of existing File %q (File Share %q / Storage Account %q / Resource Group %q): %s", id.FileName, id.ShareName, id.AccountName, account.ResourceGroup, err) + if !response.WasNotFound(resp.HttpResponse) { + return nil, fmt.Errorf("checking for presence of existing File %q (File Share %q / Storage Account %q / Resource Group %q): %s", id.FileName, id.ShareName, id.AccountId.AccountName, account.ResourceGroup, err) } } @@ -207,6 +223,43 @@ resource "azurerm_storage_share_file" "test" { `, r.template(data)) } +func (r StorageShareFileResource) basicAzureADAuth(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + storage_use_azuread = true + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-storage-%[1]d" + location = "%[2]s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestsa%[3]s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_storage_share" "test" { + name = "fileshare" + storage_account_name = azurerm_storage_account.test.name + quota = 50 +} + +resource "azurerm_storage_share_file" "test" { + name = "dir" + storage_share_id = azurerm_storage_share.test.id + + metadata = { + hello = "world" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString) +} + func (r StorageShareFileResource) requiresImport(data acceptance.TestData) string { return fmt.Sprintf(` %s diff --git a/internal/services/storage/storage_share_resource.go b/internal/services/storage/storage_share_resource.go index 42c4f458f341..58b923dec4da 100644 --- a/internal/services/storage/storage_share_resource.go +++ b/internal/services/storage/storage_share_resource.go @@ -11,13 +11,16 @@ import ( "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage" // nolint: staticcheck "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) func resourceStorageShare() *pluginsdk.Resource { @@ -27,8 +30,8 @@ func resourceStorageShare() *pluginsdk.Resource { Update: resourceStorageShareUpdate, Delete: resourceStorageShareDelete, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.StorageShareDataPlaneID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := shares.ParseShareID(id, storageDomainSuffix) return err }), @@ -158,12 +161,26 @@ func resourceStorageShareCreate(d *pluginsdk.ResourceData, meta interface{}) err account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Share %q: %s", accountName, shareName, err) + return fmt.Errorf("retrieving Account %q for Share %q: %v", accountName, shareName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", accountName) + return fmt.Errorf("locating Storage Account %q", accountName) } + // Determine the file endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeFile) + if err != nil { + return fmt.Errorf("determining File endpoint: %v", err) + } + + // Parse the file endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := shares.NewShareID(*accountId, shareName) + protocol := shares.ShareProtocol(d.Get("enabled_protocol").(string)) if protocol == shares.NFS { // Only FileStorage (whose sku tier is Premium only) storage account is able to have NFS file shares. @@ -173,19 +190,18 @@ func resourceStorageShareCreate(d *pluginsdk.ResourceData, meta interface{}) err } } - client, err := storageClient.FileSharesClient(ctx, *account) + // The files API does not support bearer tokens (@manicminer, 2024-02-15) + client, err := storageClient.FileSharesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) if err != nil { - return fmt.Errorf("building File Share Client: %s", err) + return fmt.Errorf("building File Share Client: %v", err) } - id := parse.NewStorageShareDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, shareName).ID() - - exists, err := client.Exists(ctx, account.ResourceGroup, accountName, shareName) + exists, err := client.Exists(ctx, shareName) if err != nil { - return fmt.Errorf("checking for existence of existing Storage Share %q (Account %q / Resource Group %q): %+v", shareName, accountName, account.ResourceGroup, err) + return fmt.Errorf("checking for existing %s: %v", id, err) } if exists != nil && *exists { - return tf.ImportAsExistsError("azurerm_storage_share", id) + return tf.ImportAsExistsError("azurerm_storage_share", id.ID()) } log.Printf("[INFO] Creating Share %q in Storage Account %q", shareName, accountName) @@ -200,13 +216,14 @@ func resourceStorageShareCreate(d *pluginsdk.ResourceData, meta interface{}) err input.AccessTier = &tier } - if err := client.Create(ctx, account.ResourceGroup, accountName, shareName, input); err != nil { - return fmt.Errorf("creating Share %q (Account %q / Resource Group %q): %+v", shareName, accountName, account.ResourceGroup, err) + if err = client.Create(ctx, shareName, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } - d.SetId(id) - if err := client.UpdateACLs(ctx, account.ResourceGroup, accountName, shareName, acls); err != nil { - return fmt.Errorf("setting ACL's for Share %q (Account %q / Resource Group %q): %+v", shareName, accountName, account.ResourceGroup, err) + d.SetId(id.ID()) + + if err = client.UpdateACLs(ctx, shareName, shares.SetAclInput{SignedIdentifiers: acls}); err != nil { + return fmt.Errorf("setting ACLs for %s: %v", id, err) } return resourceStorageShareRead(d, meta) @@ -217,38 +234,39 @@ func resourceStorageShareRead(d *pluginsdk.ResourceData, meta interface{}) error defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := parse.StorageShareDataPlaneID(d.Id()) + id, err := shares.ParseShareID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Share %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Share %q: %v", id.AccountId.AccountName, id.ShareName, err) } if account == nil { - log.Printf("[WARN] Unable to determine Account %q for Storage Share %q - assuming removed & removing from state", id.AccountName, id.Name) + log.Printf("[WARN] Unable to determine Account %q for Storage Share %q - assuming removed & removing from state", id.AccountId.AccountName, id.ShareName) d.SetId("") return nil } - client, err := storageClient.FileSharesClient(ctx, *account) + // The files API does not support bearer tokens (@manicminer, 2024-02-15) + client, err := storageClient.FileSharesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) if err != nil { - return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %v", id.AccountId.AccountName, account.ResourceGroup, err) } - props, err := client.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + props, err := client.Get(ctx, id.ShareName) if err != nil { return err } if props == nil { - log.Printf("[DEBUG] File Share %q was not found in Account %q / Resource Group %q - assuming removed & removing from state", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] File Share %q was not found in Account %q / Resource Group %q - assuming removed & removing from state", id.ShareName, id.AccountId.AccountName, account.ResourceGroup) d.SetId("") return nil } - d.Set("name", id.Name) - d.Set("storage_account_name", id.AccountName) + d.Set("name", id.ShareName) + d.Set("storage_account_name", id.AccountId.AccountName) d.Set("quota", props.QuotaGB) d.Set("url", id.ID()) d.Set("enabled_protocol", string(props.EnabledProtocol)) @@ -267,7 +285,7 @@ func resourceStorageShareRead(d *pluginsdk.ResourceData, meta interface{}) error return fmt.Errorf("flattening `metadata`: %+v", err) } - resourceManagerId := parse.NewStorageShareResourceManagerID(storageClient.SubscriptionId, account.ResourceGroup, id.AccountName, "default", id.Name) + resourceManagerId := parse.NewStorageShareResourceManagerID(storageClient.SubscriptionId, account.ResourceGroup, id.AccountId.AccountName, "default", id.ShareName) d.Set("resource_manager_id", resourceManagerId.ID()) return nil @@ -278,70 +296,71 @@ func resourceStorageShareUpdate(d *pluginsdk.ResourceData, meta interface{}) err defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := parse.StorageShareDataPlaneID(d.Id()) + id, err := shares.ParseShareID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Share %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Share %q: %v", id.AccountId.AccountName, id.ShareName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.FileSharesClient(ctx, *account) + // The files API does not support bearer tokens (@manicminer, 2024-02-15) + client, err := storageClient.FileSharesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) if err != nil { - return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %v", id.AccountId.AccountName, account.ResourceGroup, err) } if d.HasChange("quota") { - log.Printf("[DEBUG] Updating the Quota for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updating the Quota for %s", id) quota := d.Get("quota").(int) - if err := client.UpdateQuota(ctx, account.ResourceGroup, id.AccountName, id.Name, quota); err != nil { - return fmt.Errorf("updating Quota for File Share %q (Storage Account %q): %s", id.Name, id.AccountName, err) + if err = client.UpdateQuota(ctx, id.ShareName, quota); err != nil { + return fmt.Errorf("updating Quota for %s: %v", id, err) } - log.Printf("[DEBUG] Updated the Quota for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updated the Quota for %s", id) } if d.HasChange("metadata") { - log.Printf("[DEBUG] Updating the MetaData for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updating the MetaData for %s", id) metaDataRaw := d.Get("metadata").(map[string]interface{}) metaData := ExpandMetaData(metaDataRaw) - if err := client.UpdateMetaData(ctx, account.ResourceGroup, id.AccountName, id.Name, metaData); err != nil { - return fmt.Errorf("updating MetaData for File Share %q (Storage Account %q): %s", id.Name, id.AccountName, err) + if err = client.UpdateMetaData(ctx, id.ShareName, metaData); err != nil { + return fmt.Errorf("updating MetaData for %s: %v", id, err) } - log.Printf("[DEBUG] Updated the MetaData for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updated the MetaData for %s", id) } if d.HasChange("acl") { - log.Printf("[DEBUG] Updating the ACL's for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updating the ACLs for %s", id) aclsRaw := d.Get("acl").(*pluginsdk.Set).List() acls := expandStorageShareACLs(aclsRaw) - if err := client.UpdateACLs(ctx, account.ResourceGroup, id.AccountName, id.Name, acls); err != nil { - return fmt.Errorf("updating ACL's for File Share %q (Storage Account %q): %s", id.Name, id.AccountName, err) + if err = client.UpdateACLs(ctx, id.ShareName, shares.SetAclInput{SignedIdentifiers: acls}); err != nil { + return fmt.Errorf("updating ACLs for %s: %v", id, err) } - log.Printf("[DEBUG] Updated the ACL's for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updated ACLs for %s", id) } if d.HasChange("access_tier") { - log.Printf("[DEBUG] Updating the Access Tier for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updating Access Tier for %s", id) tier := shares.AccessTier(d.Get("access_tier").(string)) - if err := client.UpdateTier(ctx, account.ResourceGroup, id.AccountName, id.Name, tier); err != nil { - return fmt.Errorf("updating Access Tier for File Share %q (Storage Account %q): %s", id.Name, id.AccountName, err) + if err = client.UpdateTier(ctx, id.ShareName, tier); err != nil { + return fmt.Errorf("updating Access Tier for %s: %v", id, err) } - log.Printf("[DEBUG] Updated the Access Tier for File Share %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updated Access Tier for %s", id) } return resourceStorageShareRead(d, meta) @@ -352,26 +371,27 @@ func resourceStorageShareDelete(d *pluginsdk.ResourceData, meta interface{}) err defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := parse.StorageShareDataPlaneID(d.Id()) + id, err := shares.ParseShareID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Share %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Share %q: %v", id.AccountId.AccountName, id.ShareName, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.FileSharesClient(ctx, *account) + // The files API does not support bearer tokens (@manicminer, 2024-02-15) + client, err := storageClient.FileSharesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) if err != nil { - return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %v", id.AccountId.AccountName, account.ResourceGroup, err) } - if err := client.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return fmt.Errorf("deleting File Share %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + if err = client.Delete(ctx, id.ShareName); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil diff --git a/internal/services/storage/storage_share_resource_test.go b/internal/services/storage/storage_share_resource_test.go index aec5733e28d2..0ebb64d4c9f0 100644 --- a/internal/services/storage/storage_share_resource_test.go +++ b/internal/services/storage/storage_share_resource_test.go @@ -11,9 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" ) type StorageShareResource struct{} @@ -271,52 +271,54 @@ func TestAccStorageShare_protocolUpdate(t *testing.T) { } func (r StorageShareResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageShareDataPlaneID(state.ID) + id, err := shares.ParseShareID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Share %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Share %q: %+v", id.AccountId.AccountName, id.ShareName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Account %q for Storage Share %q", id.AccountName, id.Name) + return nil, fmt.Errorf("unable to determine Account %q for Storage Share %q", id.AccountId.AccountName, id.ShareName) } - sharesClient, err := client.Storage.FileSharesClient(ctx, *account) + sharesClient, err := client.Storage.FileSharesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return nil, fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %+v", id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %+v", id.AccountId.AccountName, account.ResourceGroup, err) } - props, err := sharesClient.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + props, err := sharesClient.Get(ctx, id.ShareName) if err != nil { - return nil, fmt.Errorf("retrieving File Share %q (Account %q / Resource Group %q): %+v", id.Name, id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("retrieving File Share %q (Account %q / Resource Group %q): %+v", id.ShareName, id.AccountId.AccountName, account.ResourceGroup, err) } + return utils.Bool(props != nil), nil } func (r StorageShareResource) Destroy(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageShareDataPlaneID(state.ID) + id, err := shares.ParseShareID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Share %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Share %q: %+v", id.AccountId.AccountName, id.ShareName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Account %q for Storage Share %q", id.AccountName, id.Name) + return nil, fmt.Errorf("unable to determine Account %q for Storage Share %q", id.AccountId.AccountName, id.ShareName) } - sharesClient, err := client.Storage.FileSharesClient(ctx, *account) + sharesClient, err := client.Storage.FileSharesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return nil, fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %+v", id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("building File Share Client for Storage Account %q (Resource Group %q): %+v", id.AccountId.AccountName, account.ResourceGroup, err) } - if err := sharesClient.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return nil, fmt.Errorf("deleting File Share %q (Account %q / Resource Group %q): %+v", id.Name, id.AccountName, account.ResourceGroup, err) + if err := sharesClient.Delete(ctx, id.ShareName); err != nil { + return nil, fmt.Errorf("deleting File Share %q (Account %q / Resource Group %q): %+v", id.ShareName, id.AccountId.AccountName, account.ResourceGroup, err) } + return utils.Bool(true), nil } @@ -537,6 +539,7 @@ func (r StorageShareResource) accessTierStandard(data acceptance.TestData, tier return fmt.Sprintf(` provider "azurerm" { features {} + storage_use_azuread = true } resource "azurerm_resource_group" "test" { diff --git a/internal/services/storage/storage_table_entities_data_source.go b/internal/services/storage/storage_table_entities_data_source.go index 27fdb0bb954e..74b3aa7d1af6 100644 --- a/internal/services/storage/storage_table_entities_data_source.go +++ b/internal/services/storage/storage_table_entities_data_source.go @@ -15,7 +15,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities" ) type storageTableEntitiesDataSource struct{} @@ -23,14 +23,14 @@ type storageTableEntitiesDataSource struct{} var _ sdk.DataSource = storageTableEntitiesDataSource{} type TableEntitiesDataSourceModel struct { - TableName string `tfschema:"table_name"` - StorageAccountName string `tfschema:"storage_account_name"` - Filter string `tfschema:"filter"` - Select []string `tfschema:"select"` - Items []TableEntitiyDataSourceModel `tfschema:"items"` + TableName string `tfschema:"table_name"` + StorageAccountName string `tfschema:"storage_account_name"` + Filter string `tfschema:"filter"` + Select []string `tfschema:"select"` + Items []TableEntityDataSourceModel `tfschema:"items"` } -type TableEntitiyDataSourceModel struct { +type TableEntityDataSourceModel struct { PartitionKey string `tfschema:"partition_key"` RowKey string `tfschema:"row_key"` Properties map[string]interface{} `tfschema:"properties"` @@ -123,7 +123,7 @@ func (k storageTableEntitiesDataSource) Read() sdk.ResourceFunc { return fmt.Errorf("the parent Storage Account %s was not found", model.StorageAccountName) } - client, err := storageClient.TableEntityClient(ctx, *account) + client, err := storageClient.TableEntityDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Table Entity Client for Storage Account %q (Resource Group %q): %s", model.StorageAccountName, account.ResourceGroup, err) } @@ -138,14 +138,14 @@ func (k storageTableEntitiesDataSource) Read() sdk.ResourceFunc { input.PropertyNamesToSelect = &model.Select } - id := parse.NewStorageTableEntitiesId(model.StorageAccountName, storageClient.Environment.StorageEndpointSuffix, model.TableName, model.Filter) + id := parse.NewStorageTableEntitiesId(model.StorageAccountName, storageClient.StorageDomainSuffix, model.TableName, model.Filter) - result, err := client.Query(ctx, model.StorageAccountName, model.TableName, input) + result, err := client.Query(ctx, model.TableName, input) if err != nil { return fmt.Errorf("retrieving Entities (Filter %q) (Table %q / Storage Account %q / Resource Group %q): %s", model.Filter, model.TableName, model.StorageAccountName, account.ResourceGroup, err) } - var flattenedEntities []TableEntitiyDataSourceModel + var flattenedEntities []TableEntityDataSourceModel for _, entity := range result.Entities { flattenedEntity := flattenEntityWithMetadata(entity) if len(flattenedEntity.Properties) == 0 { @@ -163,10 +163,10 @@ func (k storageTableEntitiesDataSource) Read() sdk.ResourceFunc { } // The api returns extra information that we already have. We'll remove it here before setting it in state. -func flattenEntityWithMetadata(entity map[string]interface{}) TableEntitiyDataSourceModel { +func flattenEntityWithMetadata(entity map[string]interface{}) TableEntityDataSourceModel { delete(entity, "Timestamp") - result := TableEntitiyDataSourceModel{} + result := TableEntityDataSourceModel{} properties := map[string]interface{}{} for k, v := range entity { diff --git a/internal/services/storage/storage_table_entity_data_source.go b/internal/services/storage/storage_table_entity_data_source.go index 8cda4c4950f0..75ca7869a123 100644 --- a/internal/services/storage/storage_table_entity_data_source.go +++ b/internal/services/storage/storage_table_entity_data_source.go @@ -12,7 +12,8 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities" ) func dataSourceStorageTableEntity() *pluginsdk.Resource { @@ -64,25 +65,30 @@ func dataSourceStorageTableEntityRead(d *pluginsdk.ResourceData, meta interface{ defer cancel() storageClient := meta.(*clients.Client).Storage - storageAccountName := d.Get("storage_account_name").(string) + accountName := d.Get("storage_account_name").(string) tableName := d.Get("table_name").(string) partitionKey := d.Get("partition_key").(string) rowKey := d.Get("row_key").(string) - account, err := storageClient.FindAccount(ctx, storageAccountName) + account, err := storageClient.FindAccount(ctx, accountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Table %q: %s", storageAccountName, tableName, err) + return fmt.Errorf("retrieving Account %q for Table %q: %v", accountName, tableName, err) } if account == nil { - return fmt.Errorf("the parent Storage Account %s was not found", storageAccountName) + return fmt.Errorf("the parent Storage Account %s was not found", accountName) } - client, err := storageClient.TableEntityClient(ctx, *account) + client, err := storageClient.TableEntityDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Table Entity Client for Storage Account %q (Resource Group %q): %s", storageAccountName, account.ResourceGroup, err) + return fmt.Errorf("building Table Entity Client for Storage Account %q (Resource Group %q): %v", accountName, account.ResourceGroup, err) } - id := client.GetResourceID(storageAccountName, tableName, partitionKey, rowKey) + accountId, err := accounts.ParseAccountID(accountName, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := entities.NewEntityID(*accountId, tableName, partitionKey, rowKey) input := entities.GetEntityInput{ PartitionKey: partitionKey, @@ -90,19 +96,21 @@ func dataSourceStorageTableEntityRead(d *pluginsdk.ResourceData, meta interface{ MetaDataLevel: entities.NoMetaData, } - result, err := client.Get(ctx, storageAccountName, tableName, input) + result, err := client.Get(ctx, tableName, input) if err != nil { - return fmt.Errorf("retrieving Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %s", partitionKey, rowKey, tableName, storageAccountName, account.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %v", id, err) } - d.Set("storage_account_name", storageAccountName) + d.Set("storage_account_name", accountName) d.Set("table_name", tableName) d.Set("partition_key", partitionKey) d.Set("row_key", rowKey) - if err := d.Set("entity", flattenEntity(result.Entity)); err != nil { - return fmt.Errorf("setting `entity` for Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %s", partitionKey, rowKey, tableName, storageAccountName, account.ResourceGroup, err) + + if err = d.Set("entity", flattenEntity(result.Entity)); err != nil { + return fmt.Errorf("setting `entity` for %s: %v", id, err) } - d.SetId(id) + + d.SetId(id.ID()) return nil } diff --git a/internal/services/storage/storage_table_entity_resource.go b/internal/services/storage/storage_table_entity_resource.go index ae5d8e334577..8d61e74fa4f0 100644 --- a/internal/services/storage/storage_table_entity_resource.go +++ b/internal/services/storage/storage_table_entity_resource.go @@ -9,25 +9,30 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables" ) func resourceStorageTableEntity() *pluginsdk.Resource { return &pluginsdk.Resource{ - Create: resourceStorageTableEntityCreateUpdate, + Create: resourceStorageTableEntityCreate, Read: resourceStorageTableEntityRead, - Update: resourceStorageTableEntityCreateUpdate, + Update: resourceStorageTableEntityUpdate, Delete: resourceStorageTableEntityDelete, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := entities.ParseResourceID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := entities.ParseEntityID(id, storageDomainSuffix) return err }), @@ -39,30 +44,48 @@ func resourceStorageTableEntity() *pluginsdk.Resource { }, Schema: map[string]*pluginsdk.Schema{ + "storage_table_id": { + Type: pluginsdk.TypeString, + Optional: true, // TODO: make required and forcenew in v4.0 + Computed: true, // TODO: remove computed in v4.0 + ConflictsWith: []string{"table_name", "storage_account_name"}, + ValidateFunc: validation.IsURLWithPath, // note: storage domain suffix cannot be determined at validation time, so just make sure it's a well-formed URL + }, + "table_name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validate.StorageTableName, + Type: pluginsdk.TypeString, + Optional: true, + Computed: true, + Deprecated: "the `table_name` and `storage_account_name` properties have been superseded by the `storage_table_id` property and will be removed in version 4.0 of the AzureRM provider", + ConflictsWith: []string{"storage_table_id"}, + RequiredWith: []string{"storage_account_name"}, + ValidateFunc: validate.StorageTableName, }, + "storage_account_name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validate.StorageAccountName, + Type: pluginsdk.TypeString, + Optional: true, + Computed: true, + Deprecated: "the `table_name` and `storage_account_name` properties have been superseded by the `storage_table_id` property and will be removed in version 4.0 of the AzureRM provider", + ConflictsWith: []string{"storage_table_id"}, + RequiredWith: []string{"table_name"}, + ValidateFunc: validate.StorageAccountName, }, + "partition_key": { Type: pluginsdk.TypeString, Required: true, ForceNew: true, ValidateFunc: validation.StringIsNotEmpty, }, + "row_key": { Type: pluginsdk.TypeString, Required: true, ForceNew: true, ValidateFunc: validation.StringIsNotEmpty, }, + "entity": { Type: pluginsdk.TypeMap, Required: true, @@ -74,67 +97,142 @@ func resourceStorageTableEntity() *pluginsdk.Resource { } } -func resourceStorageTableEntityCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) +func resourceStorageTableEntityCreate(d *pluginsdk.ResourceData, meta interface{}) error { + ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() storageClient := meta.(*clients.Client).Storage - accountName := d.Get("storage_account_name").(string) - tableName := d.Get("table_name").(string) partitionKey := d.Get("partition_key").(string) rowKey := d.Get("row_key").(string) - entity := d.Get("entity").(map[string]interface{}) - account, err := storageClient.FindAccount(ctx, accountName) + var storageTableId *tables.TableId + var err error + if v, ok := d.GetOk("storage_table_id"); ok && v.(string) != "" { + storageTableId, err = tables.ParseTableID(v.(string), storageClient.StorageDomainSuffix) + if err != nil { + return err + } + } else { + // TODO: this is needed until `table_name` / `storage_account_name` are removed in favor of `storage_table_id` in v4.0 + // we will retrieve the storage account twice but this will make it easier to refactor later + storageAccountName := d.Get("storage_account_name").(string) + + account, err := storageClient.FindAccount(ctx, storageAccountName) + if err != nil { + return fmt.Errorf("retrieving Account %q: %v", storageAccountName, err) + } + if account == nil { + return fmt.Errorf("locating Storage Account %q", storageAccountName) + } + + // Determine the table endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeTable) + if err != nil { + return fmt.Errorf("determining Table endpoint: %v", err) + } + + // Parse the table endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) + if err != nil { + return fmt.Errorf("parsing Account ID: %v", err) + } + + storageTableId = pointer.To(tables.NewTableID(*accountId, d.Get("table_name").(string))) + } + + if storageTableId == nil { + return fmt.Errorf("determining storage table ID") + } + + account, err := storageClient.FindAccount(ctx, storageTableId.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Table %q: %s", accountName, tableName, err) + return fmt.Errorf("retrieving Account %q for Table %q: %v", storageTableId.AccountId.AccountName, storageTableId.TableName, err) } if account == nil { - if d.IsNewResource() { - return fmt.Errorf("Unable to locate Account %q for Storage Table %q", accountName, tableName) - } else { - log.Printf("[DEBUG] Unable to locate Account %q for Storage Table %q - assuming removed & removing from state", accountName, tableName) - d.SetId("") - return nil - } + return fmt.Errorf("locating Storage Account %q for Table %q", storageTableId.AccountId.AccountName, storageTableId.TableName) } - client, err := storageClient.TableEntityClient(ctx, *account) + accountId, err := accounts.ParseAccountID(storageTableId.ID(), storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("building Entity Client: %s", err) + return fmt.Errorf("parsing Account ID: %s", err) } - if d.IsNewResource() { - input := entities.GetEntityInput{ - PartitionKey: partitionKey, - RowKey: rowKey, - MetaDataLevel: entities.NoMetaData, - } - existing, err := client.Get(ctx, accountName, tableName, input) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %s", partitionKey, rowKey, tableName, accountName, account.ResourceGroup, err) - } - } + id := entities.NewEntityID(*accountId, storageTableId.TableName, partitionKey, rowKey) - if !utils.ResponseWasNotFound(existing.Response) { - id := client.GetResourceID(accountName, tableName, partitionKey, rowKey) - return tf.ImportAsExistsError("azurerm_storage_table_entity", id) + client, err := storageClient.TableEntityDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Entity Client: %v", err) + } + + getEntityInput := entities.GetEntityInput{ + PartitionKey: partitionKey, + RowKey: rowKey, + MetaDataLevel: entities.NoMetaData, + } + existing, err := client.Get(ctx, storageTableId.TableName, getEntityInput) + if err != nil { + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for existing %s: %v", id, err) } } + if !response.WasNotFound(existing.HttpResponse) && !response.WasForbidden(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_storage_table_entity", id.ID()) + } + input := entities.InsertOrMergeEntityInput{ PartitionKey: partitionKey, RowKey: rowKey, - Entity: entity, + Entity: d.Get("entity").(map[string]interface{}), + } + + if _, err = client.InsertOrMerge(ctx, storageTableId.TableName, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) + } + + d.SetId(id.ID()) + + return resourceStorageTableEntityRead(d, meta) +} + +func resourceStorageTableEntityUpdate(d *pluginsdk.ResourceData, meta interface{}) error { + ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + storageClient := meta.(*clients.Client).Storage + + id, err := entities.ParseEntityID(d.Id(), storageClient.StorageDomainSuffix) + if err != nil { + return err + } + + storageTableId := tables.NewTableID(id.AccountId, id.TableName) + + account, err := storageClient.FindAccount(ctx, storageTableId.AccountId.AccountName) + if err != nil { + return fmt.Errorf("retrieving Account %q for Table %q: %v", storageTableId.AccountId.AccountName, storageTableId.TableName, err) + } + if account == nil { + log.Printf("[DEBUG] Unable to locate Storage Account %q for Table %q - assuming removed & removing from state", storageTableId.AccountId.AccountName, storageTableId.TableName) + d.SetId("") + return nil } - if _, err := client.InsertOrMerge(ctx, accountName, tableName, input); err != nil { - return fmt.Errorf("creating Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %+v", partitionKey, rowKey, tableName, accountName, account.ResourceGroup, err) + client, err := storageClient.TableEntityDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) + if err != nil { + return fmt.Errorf("building Entity Client: %v", err) } - resourceID := client.GetResourceID(accountName, tableName, partitionKey, rowKey) - d.SetId(resourceID) + input := entities.InsertOrMergeEntityInput{ + PartitionKey: d.Get("partition_key").(string), + RowKey: d.Get("row_key").(string), + Entity: d.Get("entity").(map[string]interface{}), + } + + if _, err = client.InsertOrMerge(ctx, storageTableId.TableName, input); err != nil { + return fmt.Errorf("creating %s: %v", id, err) + } + + d.SetId(id.ID()) return resourceStorageTableEntityRead(d, meta) } @@ -144,24 +242,26 @@ func resourceStorageTableEntityRead(d *pluginsdk.ResourceData, meta interface{}) defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := entities.ParseResourceID(d.Id()) + id, err := entities.ParseEntityID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Table %q: %s", id.AccountName, id.TableName, err) + return fmt.Errorf("retrieving Account %q for Table %q: %s", id.AccountId.AccountName, id.TableName, err) } if account == nil { - log.Printf("[WARN] Unable to determine Resource Group for Storage Table %q (Account %s) - assuming removed & removing from state", id.TableName, id.AccountName) + log.Printf("[WARN] Unable to determine Resource Group for Storage Table %q (Account %s) - assuming removed & removing from state", id.TableName, id.AccountId.AccountName) d.SetId("") return nil } - client, err := storageClient.TableEntityClient(ctx, *account) + storageTableId := tables.NewTableID(id.AccountId, id.TableName) + + client, err := storageClient.TableEntityDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Table Entity Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building Table Entity Client for Storage Account %q (Resource Group %q): %s", id.AccountId.AccountName, account.ResourceGroup, err) } input := entities.GetEntityInput{ @@ -170,17 +270,19 @@ func resourceStorageTableEntityRead(d *pluginsdk.ResourceData, meta interface{}) MetaDataLevel: entities.FullMetaData, } - result, err := client.Get(ctx, id.AccountName, id.TableName, input) + result, err := client.Get(ctx, id.TableName, input) if err != nil { - return fmt.Errorf("retrieving Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %s", id.PartitionKey, id.RowKey, id.TableName, id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %v", id, err) } - d.Set("storage_account_name", id.AccountName) + d.Set("storage_table_id", storageTableId.ID()) + d.Set("storage_account_name", id.AccountId.AccountName) d.Set("table_name", id.TableName) d.Set("partition_key", id.PartitionKey) d.Set("row_key", id.RowKey) - if err := d.Set("entity", flattenEntity(result.Entity)); err != nil { - return fmt.Errorf("setting `entity` for Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %s", id.PartitionKey, id.RowKey, id.TableName, id.AccountName, account.ResourceGroup, err) + + if err = d.Set("entity", flattenEntity(result.Entity)); err != nil { + return fmt.Errorf("setting `entity` for %s: %v", id, err) } return nil @@ -191,22 +293,22 @@ func resourceStorageTableEntityDelete(d *pluginsdk.ResourceData, meta interface{ defer cancel() storageClient := meta.(*clients.Client).Storage - id, err := entities.ParseResourceID(d.Id()) + id, err := entities.ParseEntityID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Table %q: %s", id.AccountName, id.TableName, err) + return fmt.Errorf("retrieving Storage Account %q for Table %q: %s", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return fmt.Errorf("Storage Account %q was not found!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.TableEntityClient(ctx, *account) + client, err := storageClient.TableEntityDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Entity Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building Entity Client for Storage Account %q (Resource Group %q): %s", id.AccountId.AccountName, account.ResourceGroup, err) } input := entities.DeleteEntityInput{ @@ -214,8 +316,8 @@ func resourceStorageTableEntityDelete(d *pluginsdk.ResourceData, meta interface{ RowKey: id.RowKey, } - if _, err := client.Delete(ctx, id.AccountName, id.TableName, input); err != nil { - return fmt.Errorf("deleting Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %s", id.PartitionKey, id.RowKey, id.TableName, id.AccountName, account.ResourceGroup, err) + if _, err = client.Delete(ctx, id.TableName, input); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil diff --git a/internal/services/storage/storage_table_entity_resource_test.go b/internal/services/storage/storage_table_entity_resource_test.go index c2edacd39f65..def0633d6565 100644 --- a/internal/services/storage/storage_table_entity_resource_test.go +++ b/internal/services/storage/storage_table_entity_resource_test.go @@ -8,12 +8,13 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities" ) type StorageTableEntityResource struct{} @@ -33,6 +34,67 @@ func TestAccTableEntity_basic(t *testing.T) { }) } +func TestAccTableEntity_basicAzureADAuth(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_storage_table_entity", "test") + r := StorageTableEntityResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicAzureADAuth(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccTableEntity_basicDeprecated(t *testing.T) { + // TODO: remove test in v4.0 + data := acceptance.BuildTestData(t, "azurerm_storage_table_entity", "test") + r := StorageTableEntityResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicDeprecated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccTableEntity_migrateStorageTableId(t *testing.T) { + // TODO: remove test in v4.0 + data := acceptance.BuildTestData(t, "azurerm_storage_table_entity", "test") + r := StorageTableEntityResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicDeprecated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basicDeprecated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccTableEntity_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_table_entity", "test") r := StorageTableEntityResource{} @@ -70,7 +132,7 @@ func TestAccTableEntity_update(t *testing.T) { }) } -func TestAccTableEntity_update_typed(t *testing.T) { +func TestAccTableEntity_updateTyped(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_table_entity", "test") r := StorageTableEntityResource{} data.ResourceTest(t, r, []acceptance.TestStep{ @@ -82,32 +144,32 @@ func TestAccTableEntity_update_typed(t *testing.T) { }, data.ImportStep(), { - Config: r.updated_typed(data), + Config: r.updateType(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.updated_typedInt64(data), + Config: r.updatedTypeInt64(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, { - Config: r.updated_typedDouble(data), + Config: r.updatedTypeDouble(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, { - Config: r.updated_typedString(data), + Config: r.updateTypeString(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, { - Config: r.updated_typedBoolean(data), + Config: r.updateTypeBoolean(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -116,19 +178,19 @@ func TestAccTableEntity_update_typed(t *testing.T) { } func (r StorageTableEntityResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := entities.ParseResourceID(state.ID) + id, err := entities.ParseEntityID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountName, id.TableName, err) + return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return nil, fmt.Errorf("storage Account %q was not found", id.AccountName) + return nil, fmt.Errorf("storage Account %q was not found", id.AccountId.AccountName) } - entitiesClient, err := client.Storage.TableEntityClient(ctx, *account) + entitiesClient, err := client.Storage.TableEntityDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Table Entity Client: %+v", err) } @@ -138,12 +200,12 @@ func (r StorageTableEntityResource) Exists(ctx context.Context, client *clients. RowKey: id.RowKey, MetaDataLevel: entities.NoMetaData, } - resp, err := entitiesClient.Get(ctx, id.AccountName, id.TableName, input) + resp, err := entitiesClient.Get(ctx, id.TableName, input) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } - return nil, fmt.Errorf("retrieving Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %+v", id.PartitionKey, id.RowKey, id.TableName, id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("retrieving Entity (Partition Key %q / Row Key %q) (Table %q / Storage Account %q / Resource Group %q): %+v", id.PartitionKey, id.RowKey, id.TableName, id.AccountId.AccountName, account.ResourceGroup, err) } return utils.Bool(true), nil } @@ -151,129 +213,177 @@ func (r StorageTableEntityResource) Exists(ctx context.Context, client *clients. func (r StorageTableEntityResource) basic(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` -%s +%[1]s + +resource "azurerm_storage_table_entity" "test" { + storage_table_id = azurerm_storage_table.test.id + + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" + entity = { + Foo = "Bar" + } +} +`, template, data.RandomInteger) +} + +func (r StorageTableEntityResource) basicAzureADAuth(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + storage_use_azuread = true + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "%[2]s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestsa%[3]s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_storage_table" "test" { + name = "acctestst%[1]d" + storage_account_name = azurerm_storage_account.test.name +} + +resource "azurerm_storage_table_entity" "test" { + storage_table_id = azurerm_storage_table.test.id + + partition_key = "test_partition%[1]d" + row_key = "test_row%[1]d" + entity = { + Foo = "Bar" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString) +} + +func (r StorageTableEntityResource) basicDeprecated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%[1]s resource "azurerm_storage_table_entity" "test" { storage_account_name = azurerm_storage_account.test.name table_name = azurerm_storage_table.test.name - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = "Bar" } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } func (r StorageTableEntityResource) requiresImport(data acceptance.TestData) string { template := r.basic(data) return fmt.Sprintf(` -%s +%[1]s resource "azurerm_storage_table_entity" "import" { - storage_account_name = azurerm_storage_account.test.name - table_name = azurerm_storage_table.test.name + storage_table_id = azurerm_storage_table.test.id - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = "Bar" } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } func (r StorageTableEntityResource) updated(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` -%s +%[1]s resource "azurerm_storage_table_entity" "test" { - storage_account_name = azurerm_storage_account.test.name - table_name = azurerm_storage_table.test.name + storage_table_id = azurerm_storage_table.test.id - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = "Bar" Test = "Updated" } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } -func (r StorageTableEntityResource) updated_typed(data acceptance.TestData) string { +func (r StorageTableEntityResource) updateType(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` -%s +%[1]s resource "azurerm_storage_table_entity" "test" { - storage_account_name = azurerm_storage_account.test.name - table_name = azurerm_storage_table.test.name + storage_table_id = azurerm_storage_table.test.id - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = 123 "Foo@odata.type" = "Edm.Int32" Test = "Updated" } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } -func (r StorageTableEntityResource) updated_typedInt64(data acceptance.TestData) string { +func (r StorageTableEntityResource) updatedTypeInt64(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` -%s +%[1]s resource "azurerm_storage_table_entity" "test" { - storage_account_name = azurerm_storage_account.test.name - table_name = azurerm_storage_table.test.name + storage_table_id = azurerm_storage_table.test.id - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = 123 "Foo@odata.type" = "Edm.Int64" Test = "Updated" } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } -func (r StorageTableEntityResource) updated_typedDouble(data acceptance.TestData) string { +func (r StorageTableEntityResource) updatedTypeDouble(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` -%s +%[1]s resource "azurerm_storage_table_entity" "test" { - storage_account_name = azurerm_storage_account.test.name - table_name = azurerm_storage_table.test.name + storage_table_id = azurerm_storage_table.test.id - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = 123.123 "Foo@odata.type" = "Edm.Double" Test = "Updated" } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } -func (r StorageTableEntityResource) updated_typedString(data acceptance.TestData) string { +func (r StorageTableEntityResource) updateTypeString(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` -%s +%[1]s resource "azurerm_storage_table_entity" "test" { - storage_account_name = azurerm_storage_account.test.name - table_name = azurerm_storage_table.test.name + storage_table_id = azurerm_storage_table.test.id - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = "123.123" "Foo@odata.type" = "Edm.String" @@ -283,27 +393,26 @@ resource "azurerm_storage_table_entity" "test" { ignore_changes = [entity] } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } -func (r StorageTableEntityResource) updated_typedBoolean(data acceptance.TestData) string { +func (r StorageTableEntityResource) updateTypeBoolean(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` -%s +%[1]s resource "azurerm_storage_table_entity" "test" { - storage_account_name = azurerm_storage_account.test.name - table_name = azurerm_storage_table.test.name + storage_table_id = azurerm_storage_table.test.id - partition_key = "test_partition%d" - row_key = "test_row%d" + partition_key = "test_partition%[2]d" + row_key = "test_row%[2]d" entity = { Foo = "true" "Foo@odata.type" = "Edm.Boolean" Test = "Updated" } } -`, template, data.RandomInteger, data.RandomInteger) +`, template, data.RandomInteger) } func (r StorageTableEntityResource) template(data acceptance.TestData) string { @@ -313,12 +422,12 @@ provider "azurerm" { } resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" + name = "acctestRG-%[1]d" + location = "%[2]s" } resource "azurerm_storage_account" "test" { - name = "acctestsa%s" + name = "acctestsa%[3]s" resource_group_name = azurerm_resource_group.test.name location = azurerm_resource_group.test.location account_tier = "Standard" @@ -326,8 +435,8 @@ resource "azurerm_storage_account" "test" { } resource "azurerm_storage_table" "test" { - name = "acctestst%d" + name = "acctestst%[1]d" storage_account_name = azurerm_storage_account.test.name } -`, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomString) } diff --git a/internal/services/storage/storage_table_resource.go b/internal/services/storage/storage_table_resource.go index 21581f05798c..ef34a4cef454 100644 --- a/internal/services/storage/storage_table_resource.go +++ b/internal/services/storage/storage_table_resource.go @@ -10,13 +10,15 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables" ) func resourceStorageTable() *pluginsdk.Resource { @@ -26,8 +28,8 @@ func resourceStorageTable() *pluginsdk.Resource { Delete: resourceStorageTableDelete, Update: resourceStorageTableUpdate, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.StorageTableDataPlaneID(id) + Importer: helpers.ImporterValidatingStorageResourceId(func(id, storageDomainSuffix string) error { + _, err := tables.ParseTableID(id, storageDomainSuffix) return err }), @@ -114,32 +116,50 @@ func resourceStorageTableCreate(d *pluginsdk.ResourceData, meta interface{}) err return fmt.Errorf("retrieving Account %q for Table %q: %s", accountName, tableName, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q!", accountName) + return fmt.Errorf("locating Storage Account %q", accountName) } - client, err := storageClient.TablesClient(ctx, *account) + tablesDataPlaneClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Table Client: %s", err) + return fmt.Errorf("building Tables Client: %s", err) } - id := parse.NewStorageTableDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, tableName).ID() + // Determine the table endpoint, so we can build a data plane ID + endpoint, err := account.DataPlaneEndpoint(client.EndpointTypeTable) + if err != nil { + return fmt.Errorf("determining Tables endpoint: %v", err) + } - exists, err := client.Exists(ctx, account.ResourceGroup, accountName, tableName) + // Parse the table endpoint as a data plane account ID + accountId, err := accounts.ParseAccountID(*endpoint, storageClient.StorageDomainSuffix) if err != nil { - return fmt.Errorf("checking for existence of existing Storage Table %q (Account %q / Resource Group %q): %+v", tableName, accountName, account.ResourceGroup, err) + return fmt.Errorf("parsing Account ID: %v", err) + } + + id := tables.NewTableID(*accountId, tableName) + + exists, err := tablesDataPlaneClient.Exists(ctx, tableName) + if err != nil { + return fmt.Errorf("checking for existing %s: %v", id, err) } if exists != nil && *exists { - return tf.ImportAsExistsError("azurerm_storage_table", id) + return tf.ImportAsExistsError("azurerm_storage_table", id.ID()) + } + + if err = tablesDataPlaneClient.Create(ctx, tableName); err != nil { + return fmt.Errorf("creating %s: %v", id, err) } - log.Printf("[DEBUG] Creating Table %q in Storage Account %q.", tableName, accountName) - if err := client.Create(ctx, account.ResourceGroup, accountName, tableName); err != nil { - return fmt.Errorf("creating Table %q within Storage Account %q: %s", tableName, accountName, err) + d.SetId(id.ID()) + + // Setting ACLs only supports shared key authentication (@manicminer, 2024-02-29) + aclClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) + if err != nil { + return fmt.Errorf("building Tables Client: %v", err) } - d.SetId(id) - if err := client.UpdateACLs(ctx, account.ResourceGroup, accountName, tableName, acls); err != nil { - return fmt.Errorf("setting ACL's for Storage Table %q (Account %q / Resource Group %q): %+v", tableName, accountName, account.ResourceGroup, err) + if err = aclClient.UpdateACLs(ctx, tableName, acls); err != nil { + return fmt.Errorf("setting ACLs for %s: %v", id, err) } return resourceStorageTableRead(d, meta) @@ -150,46 +170,52 @@ func resourceStorageTableRead(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageTableDataPlaneID(d.Id()) + id, err := tables.ParseTableID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Table %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Storage Account %q for Table %q: %v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - log.Printf("Unable to determine Resource Group for Storage Storage Table %q (Account %s) - assuming removed & removing from state", id.Name, id.AccountName) + log.Printf("Unable to determine Resource Group for Storage Storage Table %q (Account %s) - assuming removed & removing from state", id.TableName, id.AccountId.AccountName) d.SetId("") return nil } - client, err := storageClient.TablesClient(ctx, *account) + client, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Table Client: %s", err) + return fmt.Errorf("building Tables Client: %v", err) } - exists, err := client.Exists(ctx, account.ResourceGroup, id.AccountName, id.Name) + exists, err := client.Exists(ctx, id.TableName) if err != nil { - return fmt.Errorf("retrieving Table %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %v", id, err) } if exists == nil || !*exists { - log.Printf("[DEBUG] Storage Account %q not found, removing table %q from state", id.AccountName, id.Name) + log.Printf("[DEBUG] %s not found, removing from state", id) d.SetId("") return nil } - acls, err := client.GetACLs(ctx, account.ResourceGroup, id.AccountName, id.Name) + // Retrieving ACLs only supports shared key authentication (@manicminer, 2024-02-29) + aclClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) if err != nil { - return fmt.Errorf("retrieving ACL's %q in Storage Account %q: %s", id.Name, id.AccountName, err) + return fmt.Errorf("building Tables Client: %v", err) } - d.Set("name", id.Name) - d.Set("storage_account_name", id.AccountName) + acls, err := aclClient.GetACLs(ctx, id.TableName) + if err != nil { + return fmt.Errorf("retrieving ACLs for %s: %v", id, err) + } - if err := d.Set("acl", flattenStorageTableACLs(acls)); err != nil { - return fmt.Errorf("flattening `acl`: %+v", err) + d.Set("name", id.TableName) + d.Set("storage_account_name", id.AccountId.AccountName) + + if err = d.Set("acl", flattenStorageTableACLs(acls)); err != nil { + return fmt.Errorf("setting `acl`: %v", err) } return nil @@ -200,27 +226,26 @@ func resourceStorageTableDelete(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageTableDataPlaneID(d.Id()) + id, err := tables.ParseTableID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Table %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Storage Account %q for Table %q: %v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } - client, err := storageClient.TablesClient(ctx, *account) + client, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { - return fmt.Errorf("building Table Client: %s", err) + return fmt.Errorf("building Tables Client: %v", err) } - log.Printf("[INFO] Deleting Table %q in Storage Account %q", id.Name, id.AccountName) - if err := client.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return fmt.Errorf("deleting Table %q from Storage Account %q: %s", id.Name, id.AccountName, err) + if err = client.Delete(ctx, id.TableName); err != nil { + return fmt.Errorf("deleting %s: %v", id, err) } return nil @@ -231,35 +256,36 @@ func resourceStorageTableUpdate(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageTableDataPlaneID(d.Id()) + id, err := tables.ParseTableID(d.Id(), storageClient.StorageDomainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Table %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Storage Account %q for Table %q: %v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return fmt.Errorf("unable to locate Storage Account %q!", id.AccountName) - } - - client, err := storageClient.TablesClient(ctx, *account) - if err != nil { - return fmt.Errorf("building Table Client: %s", err) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } if d.HasChange("acl") { - log.Printf("[DEBUG] Updating the ACL's for Storage Table %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updating ACLs for %s", id) aclsRaw := d.Get("acl").(*pluginsdk.Set).List() acls := expandStorageTableACLs(aclsRaw) - if err := client.UpdateACLs(ctx, account.ResourceGroup, id.AccountName, id.Name, acls); err != nil { - return fmt.Errorf("updating ACL's for Table %q (Storage Account %q): %s", id.Name, id.AccountName, err) + // Setting ACLs only supports shared key authentication (@manicminer, 2024-02-29) + aclClient, err := storageClient.TablesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingOnlySharedKeyAuth()) + if err != nil { + return fmt.Errorf("building Tables Client: %v", err) + } + + if err = aclClient.UpdateACLs(ctx, id.TableName, acls); err != nil { + return fmt.Errorf("updating ACLs for %s: %v", id, err) } - log.Printf("[DEBUG] Updated the ACL's for Storage Table %q (Storage Account %q)", id.Name, id.AccountName) + log.Printf("[DEBUG] Updated ACLs for %s", id) } return resourceStorageTableRead(d, meta) diff --git a/internal/services/storage/storage_table_resource_test.go b/internal/services/storage/storage_table_resource_test.go index 683ac23e0287..053d23d768d8 100644 --- a/internal/services/storage/storage_table_resource_test.go +++ b/internal/services/storage/storage_table_resource_test.go @@ -11,9 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables" ) type StorageTableResource struct{} @@ -83,51 +83,51 @@ func TestAccStorageTable_acl(t *testing.T) { } func (r StorageTableResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageTableDataPlaneID(state.ID) + id, err := tables.ParseTableID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Resource Group for Storage Storage Table %q (Account %q)", id.Name, id.AccountName) + return nil, fmt.Errorf("unable to determine Resource Group for Storage Storage Table %q (Account %q)", id.TableName, id.AccountId.AccountName) } - tablesClient, err := client.Storage.TablesClient(ctx, *account) + tablesClient, err := client.Storage.TablesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Table Client: %+v", err) } - return tablesClient.Exists(ctx, account.ResourceGroup, id.AccountName, id.Name) + return tablesClient.Exists(ctx, id.TableName) } func (r StorageTableResource) Destroy(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageTableDataPlaneID(state.ID) + id, err := tables.ParseTableID(state.ID, client.Storage.StorageDomainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Resource Group for Storage Storage Table %q (Account %q)", id.Name, id.AccountName) + return nil, fmt.Errorf("unable to determine Resource Group for Storage Storage Table %q (Account %q)", id.TableName, id.AccountId.AccountName) } - tablesClient, err := client.Storage.TablesClient(ctx, *account) + tablesClient, err := client.Storage.TablesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return nil, fmt.Errorf("building Table Client: %+v", err) } - exists, err := tablesClient.Exists(ctx, account.ResourceGroup, id.AccountName, id.Name) + exists, err := tablesClient.Exists(ctx, id.TableName) if err != nil { - return nil, fmt.Errorf("retrieving Table %q (Account %q): %+v", id.Name, id.AccountName, err) + return nil, fmt.Errorf("retrieving Table %q (Account %q): %+v", id.TableName, id.AccountId.AccountName, err) } if exists == nil || !*exists { - return nil, fmt.Errorf("table %q doesn't exist in Account %q so it can't be deleted", id.Name, id.AccountName) + return nil, fmt.Errorf("table %q doesn't exist in Account %q so it can't be deleted", id.TableName, id.AccountId.AccountName) } - if err := tablesClient.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return nil, fmt.Errorf("deleting Table %q (Account %q): %+v", id.Name, id.AccountName, err) + if err := tablesClient.Delete(ctx, id.TableName); err != nil { + return nil, fmt.Errorf("deleting Table %q (Account %q): %+v", id.TableName, id.AccountId.AccountName, err) } return utils.Bool(true), nil } diff --git a/internal/services/storage/validate/storage_blob_properties_default_service_version.go b/internal/services/storage/validate/storage_blob_properties_default_service_version.go index f6f3e8611411..6852d4bf1177 100644 --- a/internal/services/storage/validate/storage_blob_properties_default_service_version.go +++ b/internal/services/storage/validate/storage_blob_properties_default_service_version.go @@ -39,7 +39,7 @@ func BlobPropertiesDefaultServiceVersion(i interface{}, k string) (warnings []st "2020-02-10", "2020-04-08", "2020-06-12", - "2020-08-04", + "2023-11-03", "2020-10-02", "2020-12-06", "2021-02-12", diff --git a/internal/services/storage/validate/storage_container.go b/internal/services/storage/validate/storage_container.go index 365e785a3495..e2be952b4b8a 100644 --- a/internal/services/storage/validate/storage_container.go +++ b/internal/services/storage/validate/storage_container.go @@ -7,7 +7,9 @@ import ( "fmt" "regexp" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/client" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) func StorageContainerName(v interface{}, k string) (warnings []string, errors []error) { @@ -36,7 +38,11 @@ func StorageContainerDataPlaneID(input interface{}, key string) (warnings []stri return } - if _, err := parse.StorageContainerDataPlaneID(v); err != nil { + if client.StorageDomainSuffix == nil { + return validation.IsURLWithPath(input, key) + } + + if _, err := containers.ParseContainerID(v, *client.StorageDomainSuffix); err != nil { errors = append(errors, err) } diff --git a/internal/services/storage/validate/storage_share_name.go b/internal/services/storage/validate/storage_share_name.go index b79e4ee93606..d9a2a03dcf44 100644 --- a/internal/services/storage/validate/storage_share_name.go +++ b/internal/services/storage/validate/storage_share_name.go @@ -6,8 +6,6 @@ package validate import ( "fmt" "regexp" - - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" ) func StorageShareName(v interface{}, k string) (warnings []string, errors []error) { @@ -33,18 +31,3 @@ func StorageShareName(v interface{}, k string) (warnings []string, errors []erro } return warnings, errors } - -func StorageShareID(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) - return - } - - if _, err := parse.StorageShareDataPlaneID(v); err != nil { - errors = append(errors, fmt.Errorf("Can not parse %q as a resource id: %v", k, err)) - return - } - - return warnings, errors -} diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md index 2bd78667afbb..7ed347d3ad73 100644 --- a/vendor/github.com/google/uuid/CHANGELOG.md +++ b/vendor/github.com/google/uuid/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [1.4.0](https://github.com/google/uuid/compare/v1.3.1...v1.4.0) (2023-10-26) + + +### Features + +* UUIDs slice type with Strings() convenience method ([#133](https://github.com/google/uuid/issues/133)) ([cd5fbbd](https://github.com/google/uuid/commit/cd5fbbdd02f3e3467ac18940e07e062be1f864b4)) + +### Fixes + +* Clarify that Parse's job is to parse but not necessarily validate strings. (Documents current behavior) + ## [1.3.1](https://github.com/google/uuid/compare/v1.3.0...v1.3.1) (2023-08-18) diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md index 5566888726d9..a502fdc515ac 100644 --- a/vendor/github.com/google/uuid/CONTRIBUTING.md +++ b/vendor/github.com/google/uuid/CONTRIBUTING.md @@ -11,7 +11,7 @@ please explain why in the pull request description. ### Releasing -Commits that would precipitate a SemVer change, as desrcibed in the Conventional +Commits that would precipitate a SemVer change, as described in the Conventional Commits Specification, will trigger [`release-please`](https://github.com/google-github-actions/release-please-action) to create a release candidate pull request. Once submitted, `release-please` will create a release. diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go index a56138cc4bd0..dc75f7d99091 100644 --- a/vendor/github.com/google/uuid/uuid.go +++ b/vendor/github.com/google/uuid/uuid.go @@ -56,11 +56,15 @@ func IsInvalidLengthError(err error) bool { return ok } -// Parse decodes s into a UUID or returns an error. Both the standard UUID -// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the -// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex -// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx. +// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both +// the standard UUID forms defined in RFC 4122 +// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, +// Parse accepts non-standard strings such as the raw hex encoding +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, +// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are +// examined in the latter case. Parse should not be used to validate strings as +// it parses non-standard encodings as indicated above. func Parse(s string) (UUID, error) { var uuid UUID switch len(s) { @@ -294,3 +298,15 @@ func DisableRandPool() { poolMu.Lock() poolPos = randPoolSize } + +// UUIDs is a slice of UUID types. +type UUIDs []UUID + +// Strings returns a string slice containing the string form of each UUID in uuids. +func (uuids UUIDs) Strings() []string { + var uuidStrs = make([]string, len(uuids)) + for i, uuid := range uuids { + uuidStrs[i] = uuid.String() + } + return uuidStrs +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/client.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/client.go new file mode 100644 index 000000000000..5e0dd27d9f07 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/client.go @@ -0,0 +1,27 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package dataplane + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +var _ client.BaseClient = &Client{} + +type Client struct { + *client.Client + + // ApiVersion specifies the version of the API being used, which (by design) will be consistent across a client + // as we intentionally split out multiple API Versions into different clients, rather than using composite API + // Versions/packages which can cause confusion about which version is being used. + ApiVersion string +} + +func NewDataPlaneClient(baseUri string, serviceName, apiVersion string) *Client { + client := &Client{ + Client: client.NewClient(baseUri, serviceName, apiVersion), + ApiVersion: apiVersion, + } + return client +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage/client.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage/client.go new file mode 100644 index 000000000000..27dedf17c000 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage/client.go @@ -0,0 +1,73 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package storage + +import ( + "context" + "fmt" + "net/url" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane" +) + +var _ client.BaseClient = &Client{} + +var storageDefaultRetryFunctions = []client.RequestRetryFunc{ + // TODO: stuff n tings +} + +type Client struct { + *dataplane.Client +} + +func NewStorageClient(baseUri string, componentName, apiVersion string) (*Client, error) { + // NOTE: both the domain name _and_ the domain format can change entirely depending on the type of storage account being used + // when provisioned in an edge zone, and when AzureDNSZone is used, as such we require the baseUri is provided here + return &Client{ + Client: dataplane.NewDataPlaneClient(baseUri, fmt.Sprintf("storage/%s", componentName), apiVersion), + }, nil +} + +func (c *Client) NewRequest(ctx context.Context, input client.RequestOptions) (*client.Request, error) { + // TODO move these validations to base client method + if _, ok := ctx.Deadline(); !ok { + return nil, fmt.Errorf("internal-error: the context used must have a deadline attached for polling purposes, but got no deadline") + } + if err := input.Validate(); err != nil { + return nil, fmt.Errorf("internal-error: pre-validating request payload: %+v", err) + } + + req, err := c.Client.Client.NewRequest(ctx, input) + if err != nil { + return nil, fmt.Errorf("building %s request: %+v", input.HttpMethod, err) + } + + req.Client = c + req.Header.Add("x-ms-version", c.Client.ApiVersion) + + query := url.Values{} + if input.OptionsObject != nil { + if h := input.OptionsObject.ToHeaders(); h != nil { + for k, v := range h.Headers() { + req.Header[k] = v + } + } + + if q := input.OptionsObject.ToQuery(); q != nil { + query = q.Values() + } + + if o := input.OptionsObject.ToOData(); o != nil { + req.Header = o.AppendHeaders(req.Header) + query = o.AppendValues(query) + } + } + + req.URL.RawQuery = query.Encode() + req.RetryFunc = client.RequestRetryAny(append(storageDefaultRetryFunctions, input.RetryFunc)...) + req.ValidStatusCodes = input.ExpectedStatusCodes + + return req, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/client.go deleted file mode 100644 index 0162ebbb0c33..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package accounts - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Blob Storage Blobs. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithBaseURI creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/get_service_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/get_service_properties.go deleted file mode 100644 index e622fff3ba46..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/get_service_properties.go +++ /dev/null @@ -1,84 +0,0 @@ -package accounts - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetServicePropertiesResult struct { - autorest.Response - - ContentType string - StorageServiceProperties *StorageServiceProperties -} - -// GetServicePropertiesPreparer prepares the GetServiceProperties request. -func (client Client) GetServicePropertiesPreparer(ctx context.Context, accountName string) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "restype": "service", - "comp": "properties", - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -func (client Client) GetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -func (client Client) GetServicePropertiesResponder(resp *http.Response) (result GetServicePropertiesResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentType = resp.Header.Get("Content-Type") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result.StorageServiceProperties), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -func (client Client) GetServiceProperties(ctx context.Context, accountName string) (result GetServicePropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("accounts.Client", "GetServiceProperties", "`accountName` cannot be an empty string.") - } - - req, err := client.GetServicePropertiesPreparer(ctx, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "GetServiceProperties", nil, "Failure preparing request") - return - } - - resp, err := client.GetServicePropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "accounts.Client", "GetServiceProperties", resp, "Failure sending request") - return - } - - result, err = client.GetServicePropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "GetServiceProperties", resp, "Failure responding to request") - return - } - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/set_service_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/set_service_properties.go deleted file mode 100644 index 17b7bcc7e763..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/set_service_properties.go +++ /dev/null @@ -1,77 +0,0 @@ -package accounts - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// SetServicePropertiesSender sends the SetServiceProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetServicePropertiesPreparer prepares the SetServiceProperties request. -func (client Client) SetServicePropertiesPreparer(ctx context.Context, accountName string, input StorageServiceProperties) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "restype": "service", - "comp": "properties", - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithHeaders(headers), - autorest.WithXML(input), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetServicePropertiesResponder handles the response to the SetServiceProperties request. The method always -// closes the http.Response Body. -func (client Client) SetServicePropertiesResponder(resp *http.Response) (result SetServicePropertiesResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -func (client Client) SetServiceProperties(ctx context.Context, accountName string, input StorageServiceProperties) (result SetServicePropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("accounts.Client", "SetServiceProperties", "`accountName` cannot be an empty string.") - } - - req, err := client.SetServicePropertiesPreparer(ctx, accountName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "SetServiceProperties", nil, "Failure preparing request") - return - } - - resp, err := client.SetServicePropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "accounts.Client", "SetServiceProperties", resp, "Failure sending request") - return - } - - result, err = client.SetServicePropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "SetServiceProperties", resp, "Failure responding to request") - return - } - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/version.go deleted file mode 100644 index 3d6d01147003..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package accounts - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/api.go deleted file mode 100644 index 7e4f6494c2d1..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/api.go +++ /dev/null @@ -1,45 +0,0 @@ -package blobs - -import ( - "context" - "os" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageBlob interface { - AppendBlock(ctx context.Context, accountName, containerName, blobName string, input AppendBlockInput) (result AppendBlockResult, err error) - Copy(ctx context.Context, accountName, containerName, blobName string, input CopyInput) (result CopyResult, err error) - AbortCopy(ctx context.Context, accountName, containerName, blobName string, input AbortCopyInput) (result autorest.Response, err error) - CopyAndWait(ctx context.Context, accountName, containerName, blobName string, input CopyInput, pollingInterval time.Duration) error - Delete(ctx context.Context, accountName, containerName, blobName string, input DeleteInput) (result autorest.Response, err error) - DeleteSnapshot(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotInput) (result autorest.Response, err error) - DeleteSnapshots(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotsInput) (result autorest.Response, err error) - Get(ctx context.Context, accountName, containerName, blobName string, input GetInput) (result GetResult, err error) - GetBlockList(ctx context.Context, accountName, containerName, blobName string, input GetBlockListInput) (result GetBlockListResult, err error) - GetPageRanges(ctx context.Context, accountName, containerName, blobName string, input GetPageRangesInput) (result GetPageRangesResult, err error) - IncrementalCopyBlob(ctx context.Context, accountName, containerName, blobName string, input IncrementalCopyBlobInput) (result autorest.Response, err error) - AcquireLease(ctx context.Context, accountName, containerName, blobName string, input AcquireLeaseInput) (result AcquireLeaseResult, err error) - BreakLease(ctx context.Context, accountName, containerName, blobName string, input BreakLeaseInput) (result autorest.Response, err error) - ChangeLease(ctx context.Context, accountName, containerName, blobName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) - ReleaseLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) - RenewLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) - SetMetaData(ctx context.Context, accountName, containerName, blobName string, input SetMetaDataInput) (result autorest.Response, err error) - GetProperties(ctx context.Context, accountName, containerName, blobName string, input GetPropertiesInput) (result GetPropertiesResult, err error) - SetProperties(ctx context.Context, accountName, containerName, blobName string, input SetPropertiesInput) (result SetPropertiesResult, err error) - PutAppendBlob(ctx context.Context, accountName, containerName, blobName string, input PutAppendBlobInput) (result autorest.Response, err error) - PutBlock(ctx context.Context, accountName, containerName, blobName string, input PutBlockInput) (result PutBlockResult, err error) - PutBlockBlob(ctx context.Context, accountName, containerName, blobName string, input PutBlockBlobInput) (result autorest.Response, err error) - PutBlockBlobFromFile(ctx context.Context, accountName, containerName, blobName string, file *os.File, input PutBlockBlobInput) error - PutBlockList(ctx context.Context, accountName, containerName, blobName string, input PutBlockListInput) (result PutBlockListResult, err error) - PutBlockFromURL(ctx context.Context, accountName, containerName, blobName string, input PutBlockFromURLInput) (result PutBlockFromURLResult, err error) - PutPageBlob(ctx context.Context, accountName, containerName, blobName string, input PutPageBlobInput) (result autorest.Response, err error) - PutPageClear(ctx context.Context, accountName, containerName, blobName string, input PutPageClearInput) (result autorest.Response, err error) - PutPageUpdate(ctx context.Context, accountName, containerName, blobName string, input PutPageUpdateInput) (result PutPageUpdateResult, err error) - GetResourceID(accountName, containerName, blobName string) string - SetTier(ctx context.Context, accountName, containerName, blobName string, tier AccessTier) (result autorest.Response, err error) - Snapshot(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (result SnapshotResult, err error) - GetSnapshotProperties(ctx context.Context, accountName, containerName, blobName string, input GetSnapshotPropertiesInput) (result GetPropertiesResult, err error) - Undelete(ctx context.Context, accountName, containerName, blobName string) (result autorest.Response, err error) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/append_block.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/append_block.go deleted file mode 100644 index b7705c202518..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/append_block.go +++ /dev/null @@ -1,180 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type AppendBlockInput struct { - - // A number indicating the byte offset to compare. - // Append Block will succeed only if the append position is equal to this number. - // If it is not, the request will fail with an AppendPositionConditionNotMet - // error (HTTP status code 412 – Precondition Failed) - BlobConditionAppendPosition *int64 - - // The max length in bytes permitted for the append blob. - // If the Append Block operation would cause the blob to exceed that limit or if the blob size - // is already greater than the value specified in this header, the request will fail with - // an MaxBlobSizeConditionNotMet error (HTTP status code 412 – Precondition Failed). - BlobConditionMaxSize *int64 - - // The Bytes which should be appended to the end of this Append Blob. - // This can either be nil, which creates an empty blob, or a byte array - Content *[]byte - - // An MD5 hash of the block content. - // This hash is used to verify the integrity of the block during transport. - // When this header is specified, the storage service compares the hash of the content - // that has arrived with this header value. - // - // Note that this MD5 hash is not stored with the blob. - // If the two hashes do not match, the operation will fail with error code 400 (Bad Request). - ContentMD5 *string - - // Required if the blob has an active lease. - // To perform this operation on a blob with an active lease, specify the valid lease ID for this header. - LeaseID *string -} - -type AppendBlockResult struct { - autorest.Response - - BlobAppendOffset string - BlobCommittedBlockCount int64 - ContentMD5 string - ETag string - LastModified string -} - -// AppendBlock commits a new block of data to the end of an existing append blob. -func (client Client) AppendBlock(ctx context.Context, accountName, containerName, blobName string, input AppendBlockInput) (result AppendBlockResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "AppendBlock", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "AppendBlock", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "AppendBlock", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "AppendBlock", "`blobName` cannot be an empty string.") - } - if input.Content != nil && len(*input.Content) > (4*1024*1024) { - return result, validation.NewError("files.Client", "PutByteRange", "`input.Content` must be at most 4MB.") - } - - req, err := client.AppendBlockPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AppendBlock", nil, "Failure preparing request") - return - } - - resp, err := client.AppendBlockSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "AppendBlock", resp, "Failure sending request") - return - } - - result, err = client.AppendBlockResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AppendBlock", resp, "Failure responding to request") - return - } - - return -} - -// AppendBlockPreparer prepares the AppendBlock request. -func (client Client) AppendBlockPreparer(ctx context.Context, accountName, containerName, blobName string, input AppendBlockInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "appendblock"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.BlobConditionAppendPosition != nil { - headers["x-ms-blob-condition-appendpos"] = *input.BlobConditionAppendPosition - } - if input.BlobConditionMaxSize != nil { - headers["x-ms-blob-condition-maxsize"] = *input.BlobConditionMaxSize - } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - if input.Content != nil { - headers["Content-Length"] = int(len(*input.Content)) - } - - decorators := []autorest.PrepareDecorator{ - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - } - - if input.Content != nil { - decorators = append(decorators, autorest.WithBytes(input.Content)) - } - - preparer := autorest.CreatePreparer(decorators...) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AppendBlockSender sends the AppendBlock request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AppendBlockSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// AppendBlockResponder handles the response to the AppendBlock request. The method always -// closes the http.Response Body. -func (client Client) AppendBlockResponder(resp *http.Response) (result AppendBlockResult, err error) { - if resp != nil && resp.Header != nil { - result.BlobAppendOffset = resp.Header.Get("x-ms-blob-append-offset") - result.ContentMD5 = resp.Header.Get("ETag") - result.ETag = resp.Header.Get("ETag") - result.LastModified = resp.Header.Get("Last-Modified") - - if v := resp.Header.Get("x-ms-blob-committed-block-count"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) - return - } - - result.BlobCommittedBlockCount = int64(i) - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/client.go deleted file mode 100644 index db20391922bb..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package blobs - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Blob Storage Blobs. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithBaseURI creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_abort.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_abort.go deleted file mode 100644 index a992ff199bb1..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_abort.go +++ /dev/null @@ -1,110 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type AbortCopyInput struct { - // The Copy ID which should be aborted - CopyID string - - // The ID of the Lease - // This must be specified if a Lease is present on the Blob, else a 403 is returned - LeaseID *string -} - -// AbortCopy aborts a pending Copy Blob operation, and leaves a destination blob with zero length and full metadata. -func (client Client) AbortCopy(ctx context.Context, accountName, containerName, blobName string, input AbortCopyInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "AbortCopy", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`blobName` cannot be an empty string.") - } - if input.CopyID == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`input.CopyID` cannot be an empty string.") - } - - req, err := client.AbortCopyPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AbortCopy", nil, "Failure preparing request") - return - } - - resp, err := client.AbortCopySender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "AbortCopy", resp, "Failure sending request") - return - } - - result, err = client.AbortCopyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AbortCopy", resp, "Failure responding to request") - return - } - - return -} - -// AbortCopyPreparer prepares the AbortCopy request. -func (client Client) AbortCopyPreparer(ctx context.Context, accountName, containerName, blobName string, input AbortCopyInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "copy"), - "copyid": autorest.Encode("query", input.CopyID), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-action": "abort", - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AbortCopySender sends the AbortCopy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AbortCopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// AbortCopyResponder handles the response to the AbortCopy request. The method always -// closes the http.Response Body. -func (client Client) AbortCopyResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait.go deleted file mode 100644 index a1e7fa453dc0..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait.go +++ /dev/null @@ -1,41 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "time" -) - -// CopyAndWait copies a blob to a destination within the storage account and waits for it to finish copying. -func (client Client) CopyAndWait(ctx context.Context, accountName, containerName, blobName string, input CopyInput, pollingInterval time.Duration) error { - if _, err := client.Copy(ctx, accountName, containerName, blobName, input); err != nil { - return fmt.Errorf("Error copying: %s", err) - } - - for true { - getInput := GetPropertiesInput{ - LeaseID: input.LeaseID, - } - getResult, err := client.GetProperties(ctx, accountName, containerName, blobName, getInput) - if err != nil { - return fmt.Errorf("") - } - - switch getResult.CopyStatus { - case Aborted: - return fmt.Errorf("Copy was aborted: %s", getResult.CopyStatusDescription) - - case Failed: - return fmt.Errorf("Copy failed: %s", getResult.CopyStatusDescription) - - case Success: - return nil - - case Pending: - time.Sleep(pollingInterval) - continue - } - } - - return fmt.Errorf("Unexpected error waiting for the copy to complete") -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete.go deleted file mode 100644 index c1c642d7d781..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete.go +++ /dev/null @@ -1,105 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type DeleteInput struct { - // Should any Snapshots for this Blob also be deleted? - // If the Blob has Snapshots and this is set to False a 409 Conflict will be returned - DeleteSnapshots bool - - // The ID of the Lease - // This must be specified if a Lease is present on the Blob, else a 403 is returned - LeaseID *string -} - -// Delete marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. -func (client Client) Delete(ctx context.Context, accountName, containerName, blobName string, input DeleteInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Delete", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "Delete", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Delete", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "Delete", "`blobName` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, containerName, blobName string, input DeleteInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - if input.DeleteSnapshots { - headers["x-ms-delete-snapshots"] = "include" - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshot.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshot.go deleted file mode 100644 index 18c3d4cffe3f..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshot.go +++ /dev/null @@ -1,108 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type DeleteSnapshotInput struct { - // The ID of the Lease - // This must be specified if a Lease is present on the Blob, else a 403 is returned - LeaseID *string - - // The DateTime of the Snapshot which should be marked for Deletion - SnapshotDateTime string -} - -// DeleteSnapshot marks a single Snapshot of a Blob for Deletion based on it's DateTime, which will be deleted during the next Garbage Collection cycle. -func (client Client) DeleteSnapshot(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`blobName` cannot be an empty string.") - } - if input.SnapshotDateTime == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`input.SnapshotDateTime` cannot be an empty string.") - } - - req, err := client.DeleteSnapshotPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshot", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSnapshotSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshot", resp, "Failure sending request") - return - } - - result, err = client.DeleteSnapshotResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshot", resp, "Failure responding to request") - return - } - - return -} - -// DeleteSnapshotPreparer prepares the DeleteSnapshot request. -func (client Client) DeleteSnapshotPreparer(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "snapshot": autorest.Encode("query", input.SnapshotDateTime), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSnapshotSender sends the DeleteSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteSnapshotResponder handles the response to the DeleteSnapshot request. The method always -// closes the http.Response Body. -func (client Client) DeleteSnapshotResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshots.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshots.go deleted file mode 100644 index e7e2b664d74d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshots.go +++ /dev/null @@ -1,99 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type DeleteSnapshotsInput struct { - // The ID of the Lease - // This must be specified if a Lease is present on the Blob, else a 403 is returned - LeaseID *string -} - -// DeleteSnapshots marks all Snapshots of a Blob for Deletion, which will be deleted during the next Garbage Collection Cycle. -func (client Client) DeleteSnapshots(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotsInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`blobName` cannot be an empty string.") - } - - req, err := client.DeleteSnapshotsPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshots", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSnapshotsSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshots", resp, "Failure sending request") - return - } - - result, err = client.DeleteSnapshotsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshots", resp, "Failure responding to request") - return - } - - return -} - -// DeleteSnapshotsPreparer prepares the DeleteSnapshots request. -func (client Client) DeleteSnapshotsPreparer(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotsInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - // only delete the snapshots but leave the blob as-is - "x-ms-delete-snapshots": "only", - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSnapshotsSender sends the DeleteSnapshots request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSnapshotsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteSnapshotsResponder handles the response to the DeleteSnapshots request. The method always -// closes the http.Response Body. -func (client Client) DeleteSnapshotsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get.go deleted file mode 100644 index 7e0d6ee9fbd5..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get.go +++ /dev/null @@ -1,116 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetInput struct { - LeaseID *string - StartByte *int64 - EndByte *int64 -} - -type GetResult struct { - autorest.Response - - Contents []byte -} - -// Get reads or downloads a blob from the system, including its metadata and properties. -func (client Client) Get(ctx context.Context, accountName, containerName, blobName string, input GetInput) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Get", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "Get", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Get", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "Get", "`blobName` cannot be an empty string.") - } - if input.LeaseID != nil && *input.LeaseID == "" { - return result, validation.NewError("blobs.Client", "Get", "`input.LeaseID` should either be specified or nil, not an empty string.") - } - if (input.StartByte != nil && input.EndByte == nil) || input.StartByte == nil && input.EndByte != nil { - return result, validation.NewError("blobs.Client", "Get", "`input.StartByte` and `input.EndByte` must both be specified, or both be nil.") - } - - req, err := client.GetPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client Client) GetPreparer(ctx context.Context, accountName, containerName, blobName string, input GetInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.StartByte != nil && input.EndByte != nil { - headers["x-ms-range"] = fmt.Sprintf("bytes=%d-%d", *input.StartByte, *input.EndByte) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client Client) GetResponder(resp *http.Response) (result GetResult, err error) { - if resp != nil && int(resp.ContentLength) > 0 { - result.Contents = make([]byte, resp.ContentLength) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusPartialContent), - autorest.ByUnmarshallingBytes(&result.Contents), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_block_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_block_list.go deleted file mode 100644 index 9f8120c6c8c3..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_block_list.go +++ /dev/null @@ -1,140 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetBlockListInput struct { - BlockListType BlockListType - LeaseID *string -} - -type GetBlockListResult struct { - autorest.Response - - // The size of the blob in bytes - ContentLength *int64 - - // The Content Type of the blob - ContentType string - - // The ETag associated with this blob - ETag string - - // A list of blocks which have been committed - CommittedBlocks CommittedBlocks `xml:"CommittedBlocks,omitempty"` - - // A list of blocks which have not yet been committed - UncommittedBlocks UncommittedBlocks `xml:"UncommittedBlocks,omitempty"` -} - -// GetBlockList retrieves the list of blocks that have been uploaded as part of a block blob. -func (client Client) GetBlockList(ctx context.Context, accountName, containerName, blobName string, input GetBlockListInput) (result GetBlockListResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetBlockList", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "GetBlockList", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetBlockList", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "GetBlockList", "`blobName` cannot be an empty string.") - } - - req, err := client.GetBlockListPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetBlockList", nil, "Failure preparing request") - return - } - - resp, err := client.GetBlockListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetBlockList", resp, "Failure sending request") - return - } - - result, err = client.GetBlockListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetBlockList", resp, "Failure responding to request") - return - } - - return -} - -// GetBlockListPreparer prepares the GetBlockList request. -func (client Client) GetBlockListPreparer(ctx context.Context, accountName, containerName, blobName string, input GetBlockListInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "blocklisttype": autorest.Encode("query", string(input.BlockListType)), - "comp": autorest.Encode("query", "blocklist"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetBlockListSender sends the GetBlockList request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetBlockListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetBlockListResponder handles the response to the GetBlockList request. The method always -// closes the http.Response Body. -func (client Client) GetBlockListResponder(resp *http.Response) (result GetBlockListResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentType = resp.Header.Get("Content-Type") - result.ETag = resp.Header.Get("ETag") - - if v := resp.Header.Get("x-ms-blob-content-length"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) - return - } - - i64 := int64(i) - result.ContentLength = &i64 - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_page_ranges.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_page_ranges.go deleted file mode 100644 index 37abf631a28a..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_page_ranges.go +++ /dev/null @@ -1,152 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetPageRangesInput struct { - LeaseID *string - - StartByte *int64 - EndByte *int64 -} - -type GetPageRangesResult struct { - autorest.Response - - // The size of the blob in bytes - ContentLength *int64 - - // The Content Type of the blob - ContentType string - - // The ETag associated with this blob - ETag string - - PageRanges []PageRange `xml:"PageRange"` -} - -type PageRange struct { - // The start byte offset for this range, inclusive - Start int64 `xml:"Start"` - - // The end byte offset for this range, inclusive - End int64 `xml:"End"` -} - -// GetPageRanges returns the list of valid page ranges for a page blob or snapshot of a page blob. -func (client Client) GetPageRanges(ctx context.Context, accountName, containerName, blobName string, input GetPageRangesInput) (result GetPageRangesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`blobName` cannot be an empty string.") - } - if (input.StartByte != nil && input.EndByte == nil) || input.StartByte == nil && input.EndByte != nil { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`input.StartByte` and `input.EndByte` must both be specified, or both be nil.") - } - - req, err := client.GetPageRangesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetPageRanges", nil, "Failure preparing request") - return - } - - resp, err := client.GetPageRangesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetPageRanges", resp, "Failure sending request") - return - } - - result, err = client.GetPageRangesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetPageRanges", resp, "Failure responding to request") - return - } - - return -} - -// GetPageRangesPreparer prepares the GetPageRanges request. -func (client Client) GetPageRangesPreparer(ctx context.Context, accountName, containerName, blobName string, input GetPageRangesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "pagelist"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - if input.StartByte != nil && input.EndByte != nil { - headers["x-ms-range"] = fmt.Sprintf("bytes=%d-%d", *input.StartByte, *input.EndByte) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPageRangesSender sends the GetPageRanges request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPageRangesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPageRangesResponder handles the response to the GetPageRanges request. The method always -// closes the http.Response Body. -func (client Client) GetPageRangesResponder(resp *http.Response) (result GetPageRangesResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentType = resp.Header.Get("Content-Type") - result.ETag = resp.Header.Get("ETag") - - if v := resp.Header.Get("x-ms-blob-content-length"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) - return - } - - i64 := int64(i) - result.ContentLength = &i64 - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/incremental_copy_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/incremental_copy_blob.go deleted file mode 100644 index 7fb7e6b55489..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/incremental_copy_blob.go +++ /dev/null @@ -1,120 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type IncrementalCopyBlobInput struct { - CopySource string - IfModifiedSince *string - IfUnmodifiedSince *string - IfMatch *string - IfNoneMatch *string -} - -// IncrementalCopyBlob copies a snapshot of the source page blob to a destination page blob. -// The snapshot is copied such that only the differential changes between the previously copied -// snapshot are transferred to the destination. -// The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. -func (client Client) IncrementalCopyBlob(ctx context.Context, accountName, containerName, blobName string, input IncrementalCopyBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`blobName` cannot be an empty string.") - } - if input.CopySource == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`input.CopySource` cannot be an empty string.") - } - - req, err := client.IncrementalCopyBlobPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "IncrementalCopyBlob", nil, "Failure preparing request") - return - } - - resp, err := client.IncrementalCopyBlobSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "IncrementalCopyBlob", resp, "Failure sending request") - return - } - - result, err = client.IncrementalCopyBlobResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "IncrementalCopyBlob", resp, "Failure responding to request") - return - } - - return -} - -// IncrementalCopyBlobPreparer prepares the IncrementalCopyBlob request. -func (client Client) IncrementalCopyBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input IncrementalCopyBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "incrementalcopy"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": input.CopySource, - } - - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince - } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince - } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch - } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// IncrementalCopyBlobSender sends the IncrementalCopyBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) IncrementalCopyBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// IncrementalCopyBlobResponder handles the response to the IncrementalCopyBlob request. The method always -// closes the http.Response Body. -func (client Client) IncrementalCopyBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_acquire.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_acquire.go deleted file mode 100644 index c4b49d73ae71..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_acquire.go +++ /dev/null @@ -1,135 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type AcquireLeaseInput struct { - // The ID of the existing Lease, if leased - LeaseID *string - - // Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. - // A non-infinite lease can be between 15 and 60 seconds - LeaseDuration int - - // The Proposed new ID for the Lease - ProposedLeaseID *string -} - -type AcquireLeaseResult struct { - autorest.Response - - LeaseID string -} - -// AcquireLease establishes and manages a lock on a blob for write and delete operations. -func (client Client) AcquireLease(ctx context.Context, accountName, containerName, blobName string, input AcquireLeaseInput) (result AcquireLeaseResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "AcquireLease", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`blobName` cannot be an empty string.") - } - if input.LeaseID != nil && *input.LeaseID == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`input.LeaseID` cannot be an empty string, if specified.") - } - if input.ProposedLeaseID != nil && *input.ProposedLeaseID == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`input.ProposedLeaseID` cannot be an empty string, if specified.") - } - // An infinite lease duration is -1 seconds. A non-infinite lease can be between 15 and 60 seconds - if input.LeaseDuration != -1 && (input.LeaseDuration <= 15 || input.LeaseDuration >= 60) { - return result, validation.NewError("blobs.Client", "AcquireLease", "`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds.") - } - - req, err := client.AcquireLeasePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AcquireLease", nil, "Failure preparing request") - return - } - - resp, err := client.AcquireLeaseSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "AcquireLease", resp, "Failure sending request") - return - } - - result, err = client.AcquireLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AcquireLease", resp, "Failure responding to request") - return - } - - return -} - -// AcquireLeasePreparer prepares the AcquireLease request. -func (client Client) AcquireLeasePreparer(ctx context.Context, accountName, containerName, blobName string, input AcquireLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "acquire", - "x-ms-lease-duration": input.LeaseDuration, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - if input.ProposedLeaseID != nil { - headers["x-ms-proposed-lease-id"] = *input.ProposedLeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AcquireLeaseSender sends the AcquireLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AcquireLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// AcquireLeaseResponder handles the response to the AcquireLease request. The method always -// closes the http.Response Body. -func (client Client) AcquireLeaseResponder(resp *http.Response) (result AcquireLeaseResult, err error) { - if resp != nil && resp.Header != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_break.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_break.go deleted file mode 100644 index d5642045d20d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_break.go +++ /dev/null @@ -1,124 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type BreakLeaseInput struct { - // For a break operation, proposed duration the lease should continue - // before it is broken, in seconds, between 0 and 60. - // This break period is only used if it is shorter than the time remaining on the lease. - // If longer, the time remaining on the lease is used. - // A new lease will not be available before the break period has expired, - // but the lease may be held for longer than the break period. - // If this header does not appear with a break operation, a fixed-duration lease breaks - // after the remaining lease period elapses, and an infinite lease breaks immediately. - BreakPeriod *int - - LeaseID string -} - -type BreakLeaseResponse struct { - autorest.Response - - // Approximate time remaining in the lease period, in seconds. - // If the break is immediate, 0 is returned. - LeaseTime int -} - -// BreakLease breaks an existing lock on a blob using the LeaseID. -func (client Client) BreakLease(ctx context.Context, accountName, containerName, blobName string, input BreakLeaseInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "BreakLease", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`blobName` cannot be an empty string.") - } - if input.LeaseID == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`input.LeaseID` cannot be an empty string.") - } - - req, err := client.BreakLeasePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "BreakLease", nil, "Failure preparing request") - return - } - - resp, err := client.BreakLeaseSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "BreakLease", resp, "Failure sending request") - return - } - - result, err = client.BreakLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "BreakLease", resp, "Failure responding to request") - return - } - - return -} - -// BreakLeasePreparer prepares the BreakLease request. -func (client Client) BreakLeasePreparer(ctx context.Context, accountName, containerName, blobName string, input BreakLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "break", - "x-ms-lease-id": input.LeaseID, - } - - if input.BreakPeriod != nil { - headers["x-ms-lease-break-period"] = *input.BreakPeriod - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BreakLeaseSender sends the BreakLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) BreakLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// BreakLeaseResponder handles the response to the BreakLease request. The method always -// closes the http.Response Body. -func (client Client) BreakLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_change.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_change.go deleted file mode 100644 index c57f9db875b0..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_change.go +++ /dev/null @@ -1,117 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type ChangeLeaseInput struct { - ExistingLeaseID string - ProposedLeaseID string -} - -type ChangeLeaseResponse struct { - autorest.Response - - LeaseID string -} - -// ChangeLease changes an existing lock on a blob for another lock. -func (client Client) ChangeLease(ctx context.Context, accountName, containerName, blobName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "ChangeLease", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`blobName` cannot be an empty string.") - } - if input.ExistingLeaseID == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`input.ExistingLeaseID` cannot be an empty string.") - } - if input.ProposedLeaseID == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`input.ProposedLeaseID` cannot be an empty string.") - } - - req, err := client.ChangeLeasePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ChangeLease", nil, "Failure preparing request") - return - } - - resp, err := client.ChangeLeaseSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "ChangeLease", resp, "Failure sending request") - return - } - - result, err = client.ChangeLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ChangeLease", resp, "Failure responding to request") - return - } - - return -} - -// ChangeLeasePreparer prepares the ChangeLease request. -func (client Client) ChangeLeasePreparer(ctx context.Context, accountName, containerName, blobName string, input ChangeLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "change", - "x-ms-lease-id": input.ExistingLeaseID, - "x-ms-proposed-lease-id": input.ProposedLeaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ChangeLeaseSender sends the ChangeLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ChangeLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ChangeLeaseResponder handles the response to the ChangeLease request. The method always -// closes the http.Response Body. -func (client Client) ChangeLeaseResponder(resp *http.Response) (result ChangeLeaseResponse, err error) { - if resp != nil && resp.Header != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_release.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_release.go deleted file mode 100644 index 0226cdf37552..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_release.go +++ /dev/null @@ -1,98 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// ReleaseLease releases a lock based on the Lease ID. -func (client Client) ReleaseLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`blobName` cannot be an empty string.") - } - if leaseID == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`leaseID` cannot be an empty string.") - } - - req, err := client.ReleaseLeasePreparer(ctx, accountName, containerName, blobName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ReleaseLease", nil, "Failure preparing request") - return - } - - resp, err := client.ReleaseLeaseSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "ReleaseLease", resp, "Failure sending request") - return - } - - result, err = client.ReleaseLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ReleaseLease", resp, "Failure responding to request") - return - } - - return -} - -// ReleaseLeasePreparer prepares the ReleaseLease request. -func (client Client) ReleaseLeasePreparer(ctx context.Context, accountName, containerName, blobName, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "release", - "x-ms-lease-id": leaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReleaseLeaseSender sends the ReleaseLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ReleaseLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ReleaseLeaseResponder handles the response to the ReleaseLease request. The method always -// closes the http.Response Body. -func (client Client) ReleaseLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_renew.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_renew.go deleted file mode 100644 index 69c495bd9898..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_renew.go +++ /dev/null @@ -1,97 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -func (client Client) RenewLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "RenewLease", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`blobName` cannot be an empty string.") - } - if leaseID == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`leaseID` cannot be an empty string.") - } - - req, err := client.RenewLeasePreparer(ctx, accountName, containerName, blobName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "RenewLease", nil, "Failure preparing request") - return - } - - resp, err := client.RenewLeaseSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "RenewLease", resp, "Failure sending request") - return - } - - result, err = client.RenewLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "RenewLease", resp, "Failure responding to request") - return - } - - return -} - -// RenewLeasePreparer prepares the RenewLease request. -func (client Client) RenewLeasePreparer(ctx context.Context, accountName, containerName, blobName, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "renew", - "x-ms-lease-id": leaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RenewLeaseSender sends the RenewLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) RenewLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// RenewLeaseResponder handles the response to the RenewLease request. The method always -// closes the http.Response Body. -func (client Client) RenewLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/metadata_set.go deleted file mode 100644 index ec69152a5f98..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/metadata_set.go +++ /dev/null @@ -1,113 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type SetMetaDataInput struct { - // The ID of the Lease - // This must be specified if a Lease is present on the Blob, else a 403 is returned - LeaseID *string - - // Any metadata which should be added to this blob - MetaData map[string]string -} - -// SetMetaData marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. -func (client Client) SetMetaData(ctx context.Context, accountName, containerName, blobName string, input SetMetaDataInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`blobName` cannot be an empty string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "GetProperties", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.SetMetaDataPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.SetMetaDataSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "SetMetaData", resp, "Failure sending request") - return - } - - result, err = client.SetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, containerName, blobName string, input SetMetaDataInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_set.go deleted file mode 100644 index a8c0ed8cba95..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_set.go +++ /dev/null @@ -1,156 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type SetPropertiesInput struct { - CacheControl *string - ContentType *string - ContentMD5 *string - ContentEncoding *string - ContentLanguage *string - LeaseID *string - ContentDisposition *string - ContentLength *int64 - SequenceNumberAction *SequenceNumberAction - BlobSequenceNumber *string -} - -type SetPropertiesResult struct { - autorest.Response - - BlobSequenceNumber string - Etag string -} - -// SetProperties sets system properties on the blob. -func (client Client) SetProperties(ctx context.Context, accountName, containerName, blobName string, input SetPropertiesInput) (result SetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "SetProperties", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "SetProperties", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "SetProperties", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "SetProperties", "`blobName` cannot be an empty string.") - } - - req, err := client.SetPropertiesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.SetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "SetProperties", resp, "Failure sending request") - return - } - - result, err = client.SetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetProperties", resp, "Failure responding to request") - return - } - - return -} - -type SequenceNumberAction string - -var ( - Increment SequenceNumberAction = "increment" - Max SequenceNumberAction = "max" - Update SequenceNumberAction = "update" -) - -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName, containerName, blobName string, input SetPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "properties"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl - } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition - } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding - } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage - } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 - } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType - } - if input.ContentLength != nil { - headers["x-ms-blob-content-length"] = *input.ContentLength - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - if input.SequenceNumberAction != nil { - headers["x-ms-sequence-number-action"] = string(*input.SequenceNumberAction) - } - if input.BlobSequenceNumber != nil { - headers["x-ms-blob-sequence-number"] = *input.BlobSequenceNumber - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result SetPropertiesResult, err error) { - if resp != nil && resp.Header != nil { - result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") - result.Etag = resp.Header.Get("Etag") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_append_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_append_blob.go deleted file mode 100644 index ef2c5025d606..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_append_blob.go +++ /dev/null @@ -1,134 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type PutAppendBlobInput struct { - CacheControl *string - ContentDisposition *string - ContentEncoding *string - ContentLanguage *string - ContentMD5 *string - ContentType *string - LeaseID *string - MetaData map[string]string -} - -// PutAppendBlob is a wrapper around the Put API call (with a stricter input object) -// which creates a new append blob, or updates the content of an existing blob. -func (client Client) PutAppendBlob(ctx context.Context, accountName, containerName, blobName string, input PutAppendBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`blobName` cannot be an empty string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "PutAppendBlob", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.PutAppendBlobPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutAppendBlob", nil, "Failure preparing request") - return - } - - resp, err := client.PutAppendBlobSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutAppendBlob", resp, "Failure sending request") - return - } - - result, err = client.PutAppendBlobResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutAppendBlob", resp, "Failure responding to request") - return - } - - return -} - -// PutAppendBlobPreparer prepares the PutAppendBlob request. -func (client Client) PutAppendBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input PutAppendBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-blob-type": string(AppendBlob), - "x-ms-version": APIVersion, - - // For a page blob or an append blob, the value of this header must be set to zero, - // as Put Blob is used only to initialize the blob - "Content-Length": 0, - } - - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl - } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition - } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding - } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage - } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 - } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutAppendBlobSender sends the PutAppendBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutAppendBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutAppendBlobResponder handles the response to the PutAppendBlob request. The method always -// closes the http.Response Body. -func (client Client) PutAppendBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block.go deleted file mode 100644 index 6d41bda13b55..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block.go +++ /dev/null @@ -1,126 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type PutBlockInput struct { - BlockID string - Content []byte - ContentMD5 *string - LeaseID *string -} - -type PutBlockResult struct { - autorest.Response - - ContentMD5 string -} - -// PutBlock creates a new block to be committed as part of a blob. -func (client Client) PutBlock(ctx context.Context, accountName, containerName, blobName string, input PutBlockInput) (result PutBlockResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlock", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`blobName` cannot be an empty string.") - } - if input.BlockID == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`input.BlockID` cannot be an empty string.") - } - if len(input.Content) == 0 { - return result, validation.NewError("blobs.Client", "PutBlock", "`input.Content` cannot be empty.") - } - - req, err := client.PutBlockPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlock", nil, "Failure preparing request") - return - } - - resp, err := client.PutBlockSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlock", resp, "Failure sending request") - return - } - - result, err = client.PutBlockResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlock", resp, "Failure responding to request") - return - } - - return -} - -// PutBlockPreparer prepares the PutBlock request. -func (client Client) PutBlockPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "block"), - "blockid": autorest.Encode("query", input.BlockID), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Content-Length": int(len(input.Content)), - } - - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithBytes(&input.Content)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutBlockSender sends the PutBlock request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutBlockResponder handles the response to the PutBlock request. The method always -// closes the http.Response Body. -func (client Client) PutBlockResponder(resp *http.Response) (result PutBlockResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentMD5 = resp.Header.Get("Content-MD5") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob.go deleted file mode 100644 index f5c1a971b306..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob.go +++ /dev/null @@ -1,144 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type PutBlockBlobInput struct { - CacheControl *string - Content *[]byte - ContentDisposition *string - ContentEncoding *string - ContentLanguage *string - ContentMD5 *string - ContentType *string - LeaseID *string - MetaData map[string]string -} - -// PutBlockBlob is a wrapper around the Put API call (with a stricter input object) -// which creates a new block append blob, or updates the content of an existing block blob. -func (client Client) PutBlockBlob(ctx context.Context, accountName, containerName, blobName string, input PutBlockBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`blobName` cannot be an empty string.") - } - if input.Content != nil && len(*input.Content) == 0 { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`input.Content` must either be nil or not empty.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "PutBlockBlob", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.PutBlockBlobPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockBlob", nil, "Failure preparing request") - return - } - - resp, err := client.PutBlockBlobSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockBlob", resp, "Failure sending request") - return - } - - result, err = client.PutBlockBlobResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockBlob", resp, "Failure responding to request") - return - } - - return -} - -// PutBlockBlobPreparer prepares the PutBlockBlob request. -func (client Client) PutBlockBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-blob-type": string(BlockBlob), - "x-ms-version": APIVersion, - } - - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl - } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition - } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding - } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage - } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 - } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - if input.Content != nil { - headers["Content-Length"] = int(len(*input.Content)) - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - decorators := []autorest.PrepareDecorator{ - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - } - - if input.Content != nil { - decorators = append(decorators, autorest.WithBytes(input.Content)) - } - - preparer := autorest.CreatePreparer(decorators...) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutBlockBlobSender sends the PutBlockBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutBlockBlobResponder handles the response to the PutBlockBlob request. The method always -// closes the http.Response Body. -func (client Client) PutBlockBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_list.go deleted file mode 100644 index f80524790be5..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_list.go +++ /dev/null @@ -1,157 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type BlockList struct { - CommittedBlockIDs []BlockID `xml:"Committed,omitempty"` - UncommittedBlockIDs []BlockID `xml:"Uncommitted,omitempty"` - LatestBlockIDs []BlockID `xml:"Latest,omitempty"` -} - -type BlockID struct { - Value string `xml:",chardata"` -} - -type PutBlockListInput struct { - BlockList BlockList - CacheControl *string - ContentDisposition *string - ContentEncoding *string - ContentLanguage *string - ContentMD5 *string - ContentType *string - MetaData map[string]string - LeaseID *string -} - -type PutBlockListResult struct { - autorest.Response - - ContentMD5 string - ETag string - LastModified string -} - -// PutBlockList writes a blob by specifying the list of block IDs that make up the blob. -// In order to be written as part of a blob, a block must have been successfully written -// to the server in a prior Put Block operation. -func (client Client) PutBlockList(ctx context.Context, accountName, containerName, blobName string, input PutBlockListInput) (result PutBlockListResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlockList", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlockList", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlockList", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlockList", "`blobName` cannot be an empty string.") - } - - req, err := client.PutBlockListPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockList", nil, "Failure preparing request") - return - } - - resp, err := client.PutBlockListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockList", resp, "Failure sending request") - return - } - - result, err = client.PutBlockListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockList", resp, "Failure responding to request") - return - } - - return -} - -// PutBlockListPreparer prepares the PutBlockList request. -func (client Client) PutBlockListPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockListInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "blocklist"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl - } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition - } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding - } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage - } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 - } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithXML(input.BlockList)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutBlockListSender sends the PutBlockList request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutBlockListResponder handles the response to the PutBlockList request. The method always -// closes the http.Response Body. -func (client Client) PutBlockListResponder(resp *http.Response) (result PutBlockListResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.ETag = resp.Header.Get("ETag") - result.LastModified = resp.Header.Get("Last-Modified") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_url.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_url.go deleted file mode 100644 index 95ad974698bd..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_url.go +++ /dev/null @@ -1,129 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type PutBlockFromURLInput struct { - BlockID string - CopySource string - - ContentMD5 *string - LeaseID *string - Range *string -} - -type PutBlockFromURLResult struct { - autorest.Response - ContentMD5 string -} - -// PutBlockFromURL creates a new block to be committed as part of a blob where the contents are read from a URL -func (client Client) PutBlockFromURL(ctx context.Context, accountName, containerName, blobName string, input PutBlockFromURLInput) (result PutBlockFromURLResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`blobName` cannot be an empty string.") - } - if input.BlockID == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`input.BlockID` cannot be an empty string.") - } - if input.CopySource == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`input.CopySource` cannot be an empty string.") - } - - req, err := client.PutBlockFromURLPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockFromURL", nil, "Failure preparing request") - return - } - - resp, err := client.PutBlockFromURLSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockFromURL", resp, "Failure sending request") - return - } - - result, err = client.PutBlockFromURLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockFromURL", resp, "Failure responding to request") - return - } - - return -} - -// PutBlockFromURLPreparer prepares the PutBlockFromURL request. -func (client Client) PutBlockFromURLPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockFromURLInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "block"), - "blockid": autorest.Encode("query", input.BlockID), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": input.CopySource, - } - - if input.ContentMD5 != nil { - headers["x-ms-source-content-md5"] = *input.ContentMD5 - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - if input.Range != nil { - headers["x-ms-source-range"] = *input.Range - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutBlockFromURLSender sends the PutBlockFromURL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockFromURLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutBlockFromURLResponder handles the response to the PutBlockFromURL request. The method always -// closes the http.Response Body. -func (client Client) PutBlockFromURLResponder(resp *http.Response) (result PutBlockFromURLResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentMD5 = resp.Header.Get("Content-MD5") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_blob.go deleted file mode 100644 index 4cfba95ae37b..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_blob.go +++ /dev/null @@ -1,148 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type PutPageBlobInput struct { - CacheControl *string - ContentDisposition *string - ContentEncoding *string - ContentLanguage *string - ContentMD5 *string - ContentType *string - LeaseID *string - MetaData map[string]string - - BlobContentLengthBytes int64 - BlobSequenceNumber *int64 - AccessTier *AccessTier -} - -// PutPageBlob is a wrapper around the Put API call (with a stricter input object) -// which creates a new block blob, or updates the content of an existing page blob. -func (client Client) PutPageBlob(ctx context.Context, accountName, containerName, blobName string, input PutPageBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`blobName` cannot be an empty string.") - } - if input.BlobContentLengthBytes == 0 || input.BlobContentLengthBytes%512 != 0 { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`input.BlobContentLengthBytes` must be aligned to a 512-byte boundary.") - } - - req, err := client.PutPageBlobPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageBlob", nil, "Failure preparing request") - return - } - - resp, err := client.PutPageBlobSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageBlob", resp, "Failure sending request") - return - } - - result, err = client.PutPageBlobResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageBlob", resp, "Failure responding to request") - return - } - - return -} - -// PutPageBlobPreparer prepares the PutPageBlob request. -func (client Client) PutPageBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input PutPageBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-blob-type": string(PageBlob), - "x-ms-version": APIVersion, - - // For a page blob or an page blob, the value of this header must be set to zero, - // as Put Blob is used only to initialize the blob - "Content-Length": 0, - - // This header specifies the maximum size for the page blob, up to 8 TB. - // The page blob size must be aligned to a 512-byte boundary. - "x-ms-blob-content-length": input.BlobContentLengthBytes, - } - - if input.AccessTier != nil { - headers["x-ms-access-tier"] = string(*input.AccessTier) - } - if input.BlobSequenceNumber != nil { - headers["x-ms-blob-sequence-number"] = *input.BlobSequenceNumber - } - - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl - } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition - } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding - } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage - } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 - } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType - } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutPageBlobSender sends the PutPageBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutPageBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutPageBlobResponder handles the response to the PutPageBlob request. The method always -// closes the http.Response Body. -func (client Client) PutPageBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_clear.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_clear.go deleted file mode 100644 index 59feaa5d93d0..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_clear.go +++ /dev/null @@ -1,113 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type PutPageClearInput struct { - StartByte int64 - EndByte int64 - - LeaseID *string -} - -// PutPageClear clears a range of pages within a page blob. -func (client Client) PutPageClear(ctx context.Context, accountName, containerName, blobName string, input PutPageClearInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutPageClear", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutPageClear", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutPageClear", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutPageClear", "`blobName` cannot be an empty string.") - } - if input.StartByte < 0 { - return result, validation.NewError("blobs.Client", "PutPageClear", "`input.StartByte` must be greater than or equal to 0.") - } - if input.EndByte <= 0 { - return result, validation.NewError("blobs.Client", "PutPageClear", "`input.EndByte` must be greater than 0.") - } - - req, err := client.PutPageClearPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageClear", nil, "Failure preparing request") - return - } - - resp, err := client.PutPageClearSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageClear", resp, "Failure sending request") - return - } - - result, err = client.PutPageClearResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageClear", resp, "Failure responding to request") - return - } - - return -} - -// PutPageClearPreparer prepares the PutPageClear request. -func (client Client) PutPageClearPreparer(ctx context.Context, accountName, containerName, blobName string, input PutPageClearInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "page"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-page-write": "clear", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartByte, input.EndByte), - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutPageClearSender sends the PutPageClear request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutPageClearSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutPageClearResponder handles the response to the PutPageClear request. The method always -// closes the http.Response Body. -func (client Client) PutPageClearResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_update.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_update.go deleted file mode 100644 index 3799381e5525..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_update.go +++ /dev/null @@ -1,164 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type PutPageUpdateInput struct { - StartByte int64 - EndByte int64 - Content []byte - - IfSequenceNumberEQ *string - IfSequenceNumberLE *string - IfSequenceNumberLT *string - IfModifiedSince *string - IfUnmodifiedSince *string - IfMatch *string - IfNoneMatch *string - LeaseID *string -} - -type PutPageUpdateResult struct { - autorest.Response - - BlobSequenceNumber string - ContentMD5 string - LastModified string -} - -// PutPageUpdate writes a range of pages to a page blob. -func (client Client) PutPageUpdate(ctx context.Context, accountName, containerName, blobName string, input PutPageUpdateInput) (result PutPageUpdateResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`blobName` cannot be an empty string.") - } - if input.StartByte < 0 { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`input.StartByte` must be greater than or equal to 0.") - } - if input.EndByte <= 0 { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`input.EndByte` must be greater than 0.") - } - - expectedSize := (input.EndByte - input.StartByte) + 1 - actualSize := int64(len(input.Content)) - if expectedSize != actualSize { - return result, validation.NewError("blobs.Client", "PutPageUpdate", fmt.Sprintf("Content Size was defined as %d but got %d.", expectedSize, actualSize)) - } - - req, err := client.PutPageUpdatePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.PutPageUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageUpdate", resp, "Failure sending request") - return - } - - result, err = client.PutPageUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageUpdate", resp, "Failure responding to request") - return - } - - return -} - -// PutPageUpdatePreparer prepares the PutPageUpdate request. -func (client Client) PutPageUpdatePreparer(ctx context.Context, accountName, containerName, blobName string, input PutPageUpdateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "page"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-page-write": "update", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartByte, input.EndByte), - "Content-Length": int(len(input.Content)), - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - if input.IfSequenceNumberEQ != nil { - headers["x-ms-if-sequence-number-eq"] = *input.IfSequenceNumberEQ - } - if input.IfSequenceNumberLE != nil { - headers["x-ms-if-sequence-number-le"] = *input.IfSequenceNumberLE - } - if input.IfSequenceNumberLT != nil { - headers["x-ms-if-sequence-number-lt"] = *input.IfSequenceNumberLT - } - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince - } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince - } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch - } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithBytes(&input.Content)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutPageUpdateSender sends the PutPageUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutPageUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutPageUpdateResponder handles the response to the PutPageUpdate request. The method always -// closes the http.Response Body. -func (client Client) PutPageUpdateResponder(resp *http.Response) (result PutPageUpdateResult, err error) { - if resp != nil && resp.Header != nil { - result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.LastModified = resp.Header.Get("Last-Modified") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/resource_id.go deleted file mode 100644 index 4057cf275676..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/resource_id.go +++ /dev/null @@ -1,56 +0,0 @@ -package blobs - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Blob -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, containerName, blobName string) string { - domain := endpoints.GetBlobEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s", domain, containerName, blobName) -} - -type ResourceID struct { - AccountName string - ContainerName string - BlobName string -} - -// ParseResourceID parses the Resource ID and returns an object which can be used -// to interact with the Blob Resource -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.blob.core.windows.net/Bar/example.vhd - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - path := strings.TrimPrefix(uri.Path, "/") - segments := strings.Split(path, "/") - if len(segments) == 0 { - return nil, fmt.Errorf("Expected the path to contain segments but got none") - } - - containerName := segments[0] - blobName := strings.TrimPrefix(path, containerName) - blobName = strings.TrimPrefix(blobName, "/") - return &ResourceID{ - AccountName: *accountName, - ContainerName: containerName, - BlobName: blobName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/set_tier.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/set_tier.go deleted file mode 100644 index dd0f0b8782b1..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/set_tier.go +++ /dev/null @@ -1,93 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// SetTier sets the tier on a blob. -func (client Client) SetTier(ctx context.Context, accountName, containerName, blobName string, tier AccessTier) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "SetTier", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "SetTier", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "SetTier", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "SetTier", "`blobName` cannot be an empty string.") - } - - req, err := client.SetTierPreparer(ctx, accountName, containerName, blobName, tier) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetTier", nil, "Failure preparing request") - return - } - - resp, err := client.SetTierSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "SetTier", resp, "Failure sending request") - return - } - - result, err = client.SetTierResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetTier", resp, "Failure responding to request") - return - } - - return -} - -// SetTierPreparer prepares the SetTier request. -func (client Client) SetTierPreparer(ctx context.Context, accountName, containerName, blobName string, tier AccessTier) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "tier"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-access-tier": string(tier), - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetTierSender sends the SetTier request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetTierSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetTierResponder handles the response to the SetTier request. The method always -// closes the http.Response Body. -func (client Client) SetTierResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot.go deleted file mode 100644 index 180070b29469..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot.go +++ /dev/null @@ -1,163 +0,0 @@ -package blobs - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type SnapshotInput struct { - // The ID of the Lease - // This must be specified if a Lease is present on the Blob, else a 403 is returned - LeaseID *string - - // MetaData is a user-defined name-value pair associated with the blob. - // If no name-value pairs are specified, the operation will copy the base blob metadata to the snapshot. - // If one or more name-value pairs are specified, the snapshot is created with the specified metadata, - // and metadata is not copied from the base blob. - MetaData map[string]string - - // A DateTime value which will only snapshot the blob if it has been modified since the specified date/time - // If the base blob has not been modified, the Blob service returns status code 412 (Precondition Failed). - IfModifiedSince *string - - // A DateTime value which will only snapshot the blob if it has not been modified since the specified date/time - // If the base blob has been modified, the Blob service returns status code 412 (Precondition Failed). - IfUnmodifiedSince *string - - // An ETag value to snapshot the blob only if its ETag value matches the value specified. - // If the values do not match, the Blob service returns status code 412 (Precondition Failed). - IfMatch *string - - // An ETag value for this conditional header to snapshot the blob only if its ETag value - // does not match the value specified. - // If the values are identical, the Blob service returns status code 412 (Precondition Failed). - IfNoneMatch *string -} - -type SnapshotResult struct { - autorest.Response - - // The ETag of the snapshot - ETag string - - // A DateTime value that uniquely identifies the snapshot. - // The value of this header indicates the snapshot version, - // and may be used in subsequent requests to access the snapshot. - SnapshotDateTime string -} - -// Snapshot captures a Snapshot of a given Blob -func (client Client) Snapshot(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (result SnapshotResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Snapshot", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "Snapshot", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Snapshot", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "Snapshot", "`blobName` cannot be an empty string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "Snapshot", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.SnapshotPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", nil, "Failure preparing request") - return - } - - resp, err := client.SnapshotSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", resp, "Failure sending request") - return - } - - result, err = client.SnapshotResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", resp, "Failure responding to request") - return - } - - return -} - -// SnapshotPreparer prepares the Snapshot request. -func (client Client) SnapshotPreparer(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "snapshot"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince - } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince - } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch - } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SnapshotSender sends the Snapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SnapshotResponder handles the response to the Snapshot request. The method always -// closes the http.Response Body. -func (client Client) SnapshotResponder(resp *http.Response) (result SnapshotResult, err error) { - if resp != nil && resp.Header != nil { - result.ETag = resp.Header.Get("ETag") - result.SnapshotDateTime = resp.Header.Get("x-ms-snapshot") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot_get_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot_get_properties.go deleted file mode 100644 index fe1be63ab216..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot_get_properties.go +++ /dev/null @@ -1,90 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetSnapshotPropertiesInput struct { - // The ID of the Lease - // This must be specified if a Lease is present on the Blob, else a 403 is returned - LeaseID *string - - // The ID of the Snapshot which should be retrieved - SnapshotID string -} - -// GetSnapshotProperties returns all user-defined metadata, standard HTTP properties, and system properties for -// the specified snapshot of a blob -func (client Client) GetSnapshotProperties(ctx context.Context, accountName, containerName, blobName string, input GetSnapshotPropertiesInput) (result GetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`blobName` cannot be an empty string.") - } - if input.SnapshotID == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`input.SnapshotID` cannot be an empty string.") - } - - req, err := client.GetSnapshotPropertiesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetSnapshotProperties", nil, "Failure preparing request") - return - } - - // we re-use the GetProperties methods since this is otherwise the same - resp, err := client.GetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetSnapshotProperties", resp, "Failure sending request") - return - } - - result, err = client.GetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetSnapshotProperties", resp, "Failure responding to request") - return - } - - return -} - -// GetSnapshotPreparer prepares the GetSnapshot request. -func (client Client) GetSnapshotPropertiesPreparer(ctx context.Context, accountName, containerName, blobName string, input GetSnapshotPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "snapshot": autorest.Encode("query", input.SnapshotID), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/undelete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/undelete.go deleted file mode 100644 index 9be2f81a66f2..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/undelete.go +++ /dev/null @@ -1,92 +0,0 @@ -package blobs - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Undelete restores the contents and metadata of soft deleted blob and any associated soft deleted snapshots. -func (client Client) Undelete(ctx context.Context, accountName, containerName, blobName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Undelete", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("blobs.Client", "Undelete", "`containerName` cannot be an empty string.") - } - if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Undelete", "`containerName` must be a lower-cased string.") - } - if blobName == "" { - return result, validation.NewError("blobs.Client", "Undelete", "`blobName` cannot be an empty string.") - } - - req, err := client.UndeletePreparer(ctx, accountName, containerName, blobName) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Undelete", nil, "Failure preparing request") - return - } - - resp, err := client.UndeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Undelete", resp, "Failure sending request") - return - } - - result, err = client.UndeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Undelete", resp, "Failure responding to request") - return - } - - return -} - -// UndeletePreparer prepares the Undelete request. -func (client Client) UndeletePreparer(ctx context.Context, accountName, containerName, blobName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "undelete"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UndeleteSender sends the Undelete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) UndeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// UndeleteResponder handles the response to the Undelete request. The method always -// closes the http.Response Body. -func (client Client) UndeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/version.go deleted file mode 100644 index b6d69e2233b5..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package blobs - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/api.go deleted file mode 100644 index 622f2b00eed7..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/api.go +++ /dev/null @@ -1,25 +0,0 @@ -package containers - -import ( - "context" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageContainer interface { - Create(ctx context.Context, accountName, containerName string, input CreateInput) (result CreateResponse, err error) - Delete(ctx context.Context, accountName, containerName string) (result autorest.Response, err error) - GetProperties(ctx context.Context, accountName, containerName string) (ContainerProperties, error) - GetPropertiesWithLeaseID(ctx context.Context, accountName, containerName, leaseID string) (result ContainerProperties, err error) - AcquireLease(ctx context.Context, accountName, containerName string, input AcquireLeaseInput) (result AcquireLeaseResponse, err error) - BreakLease(ctx context.Context, accountName, containerName string, input BreakLeaseInput) (result BreakLeaseResponse, err error) - ChangeLease(ctx context.Context, accountName, containerName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) - ReleaseLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) - RenewLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) - ListBlobs(ctx context.Context, accountName, containerName string, input ListBlobsInput) (result ListBlobsResult, err error) - GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, containerName string) string - SetAccessControl(ctx context.Context, accountName, containerName string, level AccessLevel) (autorest.Response, error) - SetAccessControlWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, level AccessLevel) (result autorest.Response, err error) - SetMetaData(ctx context.Context, accountName, containerName string, metaData map[string]string) (autorest.Response, error) - SetMetaDataWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, metaData map[string]string) (result autorest.Response, err error) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/client.go deleted file mode 100644 index 7bf494734484..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/client.go +++ /dev/null @@ -1,34 +0,0 @@ -package containers - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Blob Storage Containers. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithBaseURI creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} - -func (client Client) setAccessLevelIntoHeaders(headers map[string]interface{}, level AccessLevel) map[string]interface{} { - // If this header is not included in the request, container data is private to the account owner. - if level != Private { - headers["x-ms-blob-public-access"] = string(level) - } - - return headers -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/create.go deleted file mode 100644 index 84c2887d7d1a..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/create.go +++ /dev/null @@ -1,123 +0,0 @@ -package containers - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type CreateInput struct { - // Specifies whether data in the container may be accessed publicly and the level of access - AccessLevel AccessLevel - - // A name-value pair to associate with the container as metadata. - MetaData map[string]string -} - -type CreateResponse struct { - autorest.Response - Error *ErrorResponse `xml:"Error"` -} - -// Create creates a new container under the specified account. -// If the container with the same name already exists, the operation fails. -func (client Client) Create(ctx context.Context, accountName, containerName string, input CreateInput) (result CreateResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "Create", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "Create", "`containerName` cannot be an empty string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("containers.Client", "Create", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.CreatePreparer(ctx, accountName, containerName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, containerName string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = client.setAccessLevelIntoHeaders(headers, input.AccessLevel) - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result CreateResponse, err error) { - successfulStatusCodes := []int{ - http.StatusCreated, - } - if autorest.ResponseHasStatusCode(resp, successfulStatusCodes...) { - // when successful there's no response - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(successfulStatusCodes...), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - } else { - // however when there's an error the error's in the response - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(successfulStatusCodes...), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - } - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/delete.go deleted file mode 100644 index 30958295388e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/delete.go +++ /dev/null @@ -1,85 +0,0 @@ -package containers - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete marks the specified container for deletion. -// The container and any blobs contained within it are later deleted during garbage collection. -func (client Client) Delete(ctx context.Context, accountName, containerName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "Delete", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "Delete", "`containerName` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, containerName) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, containerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/get_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/get_properties.go deleted file mode 100644 index 1e308da67c55..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/get_properties.go +++ /dev/null @@ -1,124 +0,0 @@ -package containers - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -// GetProperties returns the properties for this Container without a Lease -func (client Client) GetProperties(ctx context.Context, accountName, containerName string) (ContainerProperties, error) { - // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. - // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - return client.GetPropertiesWithLeaseID(ctx, accountName, containerName, "") -} - -// GetPropertiesWithLeaseID returns the properties for this Container using the specified LeaseID -func (client Client) GetPropertiesWithLeaseID(ctx context.Context, accountName, containerName, leaseID string) (result ContainerProperties, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "GetPropertiesWithLeaseID", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "GetPropertiesWithLeaseID", "`containerName` cannot be an empty string.") - } - - req, err := client.GetPropertiesWithLeaseIDPreparer(ctx, accountName, containerName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "GetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.GetPropertiesWithLeaseIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "GetProperties", resp, "Failure sending request") - return - } - - result, err = client.GetPropertiesWithLeaseIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "GetProperties", resp, "Failure responding to request") - return - } - - return -} - -// GetPropertiesWithLeaseIDPreparer prepares the GetPropertiesWithLeaseID request. -func (client Client) GetPropertiesWithLeaseIDPreparer(ctx context.Context, accountName, containerName, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. - // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - if leaseID != "" { - headers["x-ms-lease-id"] = leaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesWithLeaseIDSender sends the GetPropertiesWithLeaseID request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesWithLeaseIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesWithLeaseIDResponder handles the response to the GetPropertiesWithLeaseID request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesWithLeaseIDResponder(resp *http.Response) (result ContainerProperties, err error) { - if resp != nil { - result.LeaseStatus = LeaseStatus(resp.Header.Get("x-ms-lease-status")) - result.LeaseState = LeaseState(resp.Header.Get("x-ms-lease-state")) - if result.LeaseStatus == Locked { - duration := LeaseDuration(resp.Header.Get("x-ms-lease-duration")) - result.LeaseDuration = &duration - } - - // If this header is not returned in the response, the container is private to the account owner. - accessLevel := resp.Header.Get("x-ms-blob-public-access") - if accessLevel != "" { - result.AccessLevel = AccessLevel(accessLevel) - } else { - result.AccessLevel = Private - } - - // we can't necessarily use strconv.ParseBool here since this could be nil (only in some API versions) - result.HasImmutabilityPolicy = strings.EqualFold(resp.Header.Get("x-ms-has-immutability-policy"), "true") - result.HasLegalHold = strings.EqualFold(resp.Header.Get("x-ms-has-legal-hold"), "true") - - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_acquire.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_acquire.go deleted file mode 100644 index 061c863c43f9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_acquire.go +++ /dev/null @@ -1,115 +0,0 @@ -package containers - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type AcquireLeaseInput struct { - // Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. - // A non-infinite lease can be between 15 and 60 seconds - LeaseDuration int - - ProposedLeaseID string -} - -type AcquireLeaseResponse struct { - autorest.Response - - LeaseID string -} - -// AcquireLease establishes and manages a lock on a container for delete operations. -func (client Client) AcquireLease(ctx context.Context, accountName, containerName string, input AcquireLeaseInput) (result AcquireLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "AcquireLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "AcquireLease", "`containerName` cannot be an empty string.") - } - // An infinite lease duration is -1 seconds. A non-infinite lease can be between 15 and 60 seconds - if input.LeaseDuration != -1 && (input.LeaseDuration <= 15 || input.LeaseDuration >= 60) { - return result, validation.NewError("containers.Client", "AcquireLease", "`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds.") - } - - req, err := client.AcquireLeasePreparer(ctx, accountName, containerName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "AcquireLease", nil, "Failure preparing request") - return - } - - resp, err := client.AcquireLeaseSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "AcquireLease", resp, "Failure sending request") - return - } - - result, err = client.AcquireLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "AcquireLease", resp, "Failure responding to request") - return - } - - return -} - -// AcquireLeasePreparer prepares the AcquireLease request. -func (client Client) AcquireLeasePreparer(ctx context.Context, accountName string, containerName string, input AcquireLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "acquire", - "x-ms-lease-duration": input.LeaseDuration, - } - - if input.ProposedLeaseID != "" { - headers["x-ms-proposed-lease-id"] = input.ProposedLeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AcquireLeaseSender sends the AcquireLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AcquireLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// AcquireLeaseResponder handles the response to the AcquireLease request. The method always -// closes the http.Response Body. -func (client Client) AcquireLeaseResponder(resp *http.Response) (result AcquireLeaseResponse, err error) { - if resp != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_break.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_break.go deleted file mode 100644 index 08acfb7a3116..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_break.go +++ /dev/null @@ -1,129 +0,0 @@ -package containers - -import ( - "context" - "net/http" - "strconv" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type BreakLeaseInput struct { - // For a break operation, proposed duration the lease should continue - // before it is broken, in seconds, between 0 and 60. - // This break period is only used if it is shorter than the time remaining on the lease. - // If longer, the time remaining on the lease is used. - // A new lease will not be available before the break period has expired, - // but the lease may be held for longer than the break period. - // If this header does not appear with a break operation, a fixed-duration lease breaks - // after the remaining lease period elapses, and an infinite lease breaks immediately. - BreakPeriod *int - - LeaseID string -} - -type BreakLeaseResponse struct { - autorest.Response - - // Approximate time remaining in the lease period, in seconds. - // If the break is immediate, 0 is returned. - LeaseTime int -} - -// BreakLease breaks a lock based on it's Lease ID -func (client Client) BreakLease(ctx context.Context, accountName, containerName string, input BreakLeaseInput) (result BreakLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "BreakLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "BreakLease", "`containerName` cannot be an empty string.") - } - if input.LeaseID == "" { - return result, validation.NewError("containers.Client", "BreakLease", "`input.LeaseID` cannot be an empty string.") - } - - req, err := client.BreakLeasePreparer(ctx, accountName, containerName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "BreakLease", nil, "Failure preparing request") - return - } - - resp, err := client.BreakLeaseSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "BreakLease", resp, "Failure sending request") - return - } - - result, err = client.BreakLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "BreakLease", resp, "Failure responding to request") - return - } - - return -} - -// BreakLeasePreparer prepares the BreakLease request. -func (client Client) BreakLeasePreparer(ctx context.Context, accountName string, containerName string, input BreakLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "break", - "x-ms-lease-id": input.LeaseID, - } - - if input.BreakPeriod != nil { - headers["x-ms-lease-break-period"] = *input.BreakPeriod - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BreakLeaseSender sends the BreakLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) BreakLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// BreakLeaseResponder handles the response to the BreakLease request. The method always -// closes the http.Response Body. -func (client Client) BreakLeaseResponder(resp *http.Response) (result BreakLeaseResponse, err error) { - if resp != nil { - leaseRaw := resp.Header.Get("x-ms-lease-time") - if leaseRaw != "" { - i, err := strconv.Atoi(leaseRaw) - if err == nil { - result.LeaseTime = i - } - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_change.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_change.go deleted file mode 100644 index dfbcb132dae3..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_change.go +++ /dev/null @@ -1,111 +0,0 @@ -package containers - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type ChangeLeaseInput struct { - ExistingLeaseID string - ProposedLeaseID string -} - -type ChangeLeaseResponse struct { - autorest.Response - - LeaseID string -} - -// ChangeLease changes the lock from one Lease ID to another Lease ID -func (client Client) ChangeLease(ctx context.Context, accountName, containerName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`containerName` cannot be an empty string.") - } - if input.ExistingLeaseID == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`input.ExistingLeaseID` cannot be an empty string.") - } - if input.ProposedLeaseID == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`input.ProposedLeaseID` cannot be an empty string.") - } - - req, err := client.ChangeLeasePreparer(ctx, accountName, containerName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ChangeLease", nil, "Failure preparing request") - return - } - - resp, err := client.ChangeLeaseSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "ChangeLease", resp, "Failure sending request") - return - } - - result, err = client.ChangeLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ChangeLease", resp, "Failure responding to request") - return - } - - return -} - -// ChangeLeasePreparer prepares the ChangeLease request. -func (client Client) ChangeLeasePreparer(ctx context.Context, accountName string, containerName string, input ChangeLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "change", - "x-ms-lease-id": input.ExistingLeaseID, - "x-ms-proposed-lease-id": input.ProposedLeaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ChangeLeaseSender sends the ChangeLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ChangeLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ChangeLeaseResponder handles the response to the ChangeLease request. The method always -// closes the http.Response Body. -func (client Client) ChangeLeaseResponder(resp *http.Response) (result ChangeLeaseResponse, err error) { - if resp != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_release.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_release.go deleted file mode 100644 index fafcf98f1e67..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_release.go +++ /dev/null @@ -1,92 +0,0 @@ -package containers - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// ReleaseLease releases the lock based on the Lease ID -func (client Client) ReleaseLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "ReleaseLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "ReleaseLease", "`containerName` cannot be an empty string.") - } - if leaseID == "" { - return result, validation.NewError("containers.Client", "ReleaseLease", "`leaseID` cannot be an empty string.") - } - - req, err := client.ReleaseLeasePreparer(ctx, accountName, containerName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ReleaseLease", nil, "Failure preparing request") - return - } - - resp, err := client.ReleaseLeaseSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "ReleaseLease", resp, "Failure sending request") - return - } - - result, err = client.ReleaseLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ReleaseLease", resp, "Failure responding to request") - return - } - - return -} - -// ReleaseLeasePreparer prepares the ReleaseLease request. -func (client Client) ReleaseLeasePreparer(ctx context.Context, accountName string, containerName string, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "release", - "x-ms-lease-id": leaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReleaseLeaseSender sends the ReleaseLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ReleaseLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ReleaseLeaseResponder handles the response to the ReleaseLease request. The method always -// closes the http.Response Body. -func (client Client) ReleaseLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_renew.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_renew.go deleted file mode 100644 index cab50bff9d21..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_renew.go +++ /dev/null @@ -1,92 +0,0 @@ -package containers - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// RenewLease renews the lock based on the Lease ID -func (client Client) RenewLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "RenewLease", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "RenewLease", "`containerName` cannot be an empty string.") - } - if leaseID == "" { - return result, validation.NewError("containers.Client", "RenewLease", "`leaseID` cannot be an empty string.") - } - - req, err := client.RenewLeasePreparer(ctx, accountName, containerName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "RenewLease", nil, "Failure preparing request") - return - } - - resp, err := client.RenewLeaseSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "RenewLease", resp, "Failure sending request") - return - } - - result, err = client.RenewLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "RenewLease", resp, "Failure responding to request") - return - } - - return -} - -// RenewLeasePreparer prepares the RenewLease request. -func (client Client) RenewLeasePreparer(ctx context.Context, accountName string, containerName string, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "renew", - "x-ms-lease-id": leaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RenewLeaseSender sends the RenewLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) RenewLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// RenewLeaseResponder handles the response to the RenewLease request. The method always -// closes the http.Response Body. -func (client Client) RenewLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/list_blobs.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/list_blobs.go deleted file mode 100644 index 82797d091d36..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/list_blobs.go +++ /dev/null @@ -1,179 +0,0 @@ -package containers - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type ListBlobsInput struct { - Delimiter *string - Include *[]Dataset - Marker *string - MaxResults *int - Prefix *string -} - -type ListBlobsResult struct { - autorest.Response - - Delimiter string `xml:"Delimiter"` - Marker string `xml:"Marker"` - MaxResults int `xml:"MaxResults"` - NextMarker *string `xml:"NextMarker,omitempty"` - Prefix string `xml:"Prefix"` - Blobs Blobs `xml:"Blobs"` -} - -type Blobs struct { - Blobs []BlobDetails `xml:"Blob"` - BlobPrefix *BlobPrefix `xml:"BlobPrefix"` -} - -type BlobDetails struct { - Name string `xml:"Name"` - Deleted bool `xml:"Deleted,omitempty"` - MetaData map[string]interface{} `map:"Metadata,omitempty"` - Properties *BlobProperties `xml:"Properties,omitempty"` - Snapshot *string `xml:"Snapshot,omitempty"` -} - -type BlobProperties struct { - AccessTier *string `xml:"AccessTier,omitempty"` - AccessTierInferred *bool `xml:"AccessTierInferred,omitempty"` - AccessTierChangeTime *string `xml:"AccessTierChangeTime,omitempty"` - BlobType *string `xml:"BlobType,omitempty"` - BlobSequenceNumber *string `xml:"x-ms-blob-sequence-number,omitempty"` - CacheControl *string `xml:"Cache-Control,omitempty"` - ContentEncoding *string `xml:"ContentEncoding,omitempty"` - ContentLanguage *string `xml:"Content-Language,omitempty"` - ContentLength *int64 `xml:"Content-Length,omitempty"` - ContentMD5 *string `xml:"Content-MD5,omitempty"` - ContentType *string `xml:"Content-Type,omitempty"` - CopyCompletionTime *string `xml:"CopyCompletionTime,omitempty"` - CopyId *string `xml:"CopyId,omitempty"` - CopyStatus *string `xml:"CopyStatus,omitempty"` - CopySource *string `xml:"CopySource,omitempty"` - CopyProgress *string `xml:"CopyProgress,omitempty"` - CopyStatusDescription *string `xml:"CopyStatusDescription,omitempty"` - CreationTime *string `xml:"CreationTime,omitempty"` - ETag *string `xml:"Etag,omitempty"` - DeletedTime *string `xml:"DeletedTime,omitempty"` - IncrementalCopy *bool `xml:"IncrementalCopy,omitempty"` - LastModified *string `xml:"Last-Modified,omitempty"` - LeaseDuration *string `xml:"LeaseDuration,omitempty"` - LeaseState *string `xml:"LeaseState,omitempty"` - LeaseStatus *string `xml:"LeaseStatus,omitempty"` - RemainingRetentionDays *string `xml:"RemainingRetentionDays,omitempty"` - ServerEncrypted *bool `xml:"ServerEncrypted,omitempty"` -} - -type BlobPrefix struct { - Name string `xml:"Name"` -} - -// ListBlobs lists the blobs matching the specified query within the specified Container -func (client Client) ListBlobs(ctx context.Context, accountName, containerName string, input ListBlobsInput) (result ListBlobsResult, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "ListBlobs", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "ListBlobs", "`containerName` cannot be an empty string.") - } - if input.MaxResults != nil && (*input.MaxResults <= 0 || *input.MaxResults > 5000) { - return result, validation.NewError("containers.Client", "ListBlobs", "`input.MaxResults` can either be nil or between 0 and 5000.") - } - - req, err := client.ListBlobsPreparer(ctx, accountName, containerName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ListBlobs", nil, "Failure preparing request") - return - } - - resp, err := client.ListBlobsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "ListBlobs", resp, "Failure sending request") - return - } - - result, err = client.ListBlobsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ListBlobs", resp, "Failure responding to request") - return - } - - return -} - -// ListBlobsPreparer prepares the ListBlobs request. -func (client Client) ListBlobsPreparer(ctx context.Context, accountName, containerName string, input ListBlobsInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "list"), - "restype": autorest.Encode("query", "container"), - } - - if input.Delimiter != nil { - queryParameters["delimiter"] = autorest.Encode("query", *input.Delimiter) - } - if input.Include != nil { - vals := make([]string, 0) - for _, v := range *input.Include { - vals = append(vals, string(v)) - } - include := strings.Join(vals, ",") - queryParameters["include"] = autorest.Encode("query", include) - } - if input.Marker != nil { - queryParameters["marker"] = autorest.Encode("query", *input.Marker) - } - if input.MaxResults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *input.MaxResults) - } - if input.Prefix != nil { - queryParameters["prefix"] = autorest.Encode("query", *input.Prefix) - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBlobsSender sends the ListBlobs request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ListBlobsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListBlobsResponder handles the response to the ListBlobs request. The method always -// closes the http.Response Body. -func (client Client) ListBlobsResponder(resp *http.Response) (result ListBlobsResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/resource_id.go deleted file mode 100644 index d35674a7868d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/resource_id.go +++ /dev/null @@ -1,53 +0,0 @@ -package containers - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Container -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, containerName string) string { - domain := endpoints.GetBlobEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, containerName) -} - -// GetResourceManagerResourceID returns the Resource Manager specific -// ResourceID for a specific Storage Container -func (client Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, containerName string) string { - fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/blobServices/default/containers/%s" - return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, containerName) -} - -type ResourceID struct { - AccountName string - ContainerName string -} - -// ParseResourceID parses the Resource ID and returns an object which can be used -// to interact with the Container Resource -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.blob.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - containerName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, - ContainerName: containerName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_acl.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_acl.go deleted file mode 100644 index fcf4e1056fa4..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_acl.go +++ /dev/null @@ -1,100 +0,0 @@ -package containers - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// SetAccessControl sets the Access Control for a Container without a Lease ID -func (client Client) SetAccessControl(ctx context.Context, accountName, containerName string, level AccessLevel) (autorest.Response, error) { - return client.SetAccessControlWithLeaseID(ctx, accountName, containerName, "", level) -} - -// SetAccessControlWithLeaseID sets the Access Control for a Container using the specified Lease ID -func (client Client) SetAccessControlWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, level AccessLevel) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "SetAccessControl", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "SetAccessControl", "`containerName` cannot be an empty string.") - } - - req, err := client.SetAccessControlWithLeaseIDPreparer(ctx, accountName, containerName, leaseID, level) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetAccessControl", nil, "Failure preparing request") - return - } - - resp, err := client.SetAccessControlWithLeaseIDSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "SetAccessControl", resp, "Failure sending request") - return - } - - result, err = client.SetAccessControlWithLeaseIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetAccessControl", resp, "Failure responding to request") - return - } - - return -} - -// SetAccessControlWithLeaseIDPreparer prepares the SetAccessControlWithLeaseID request. -func (client Client) SetAccessControlWithLeaseIDPreparer(ctx context.Context, accountName, containerName, leaseID string, level AccessLevel) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "acl"), - "restype": autorest.Encode("path", "container"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = client.setAccessLevelIntoHeaders(headers, level) - - // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. - // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - if leaseID != "" { - headers["x-ms-lease-id"] = leaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetAccessControlWithLeaseIDSender sends the SetAccessControlWithLeaseID request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetAccessControlWithLeaseIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetAccessControlWithLeaseIDResponder handles the response to the SetAccessControlWithLeaseID request. The method always -// closes the http.Response Body. -func (client Client) SetAccessControlWithLeaseIDResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_metadata.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_metadata.go deleted file mode 100644 index fb9e07fdefa9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_metadata.go +++ /dev/null @@ -1,105 +0,0 @@ -package containers - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -// SetMetaData sets the specified MetaData on the Container without a Lease ID -func (client Client) SetMetaData(ctx context.Context, accountName, containerName string, metaData map[string]string) (autorest.Response, error) { - return client.SetMetaDataWithLeaseID(ctx, accountName, containerName, "", metaData) -} - -// SetMetaDataWithLeaseID sets the specified MetaData on the Container using the specified Lease ID -func (client Client) SetMetaDataWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } - if containerName == "" { - return result, validation.NewError("containers.Client", "SetMetaData", "`containerName` cannot be an empty string.") - } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("containers.Client", "SetMetaData", fmt.Sprintf("`metaData` is not valid: %s.", err)) - } - - req, err := client.SetMetaDataWithLeaseIDPreparer(ctx, accountName, containerName, leaseID, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.SetMetaDataWithLeaseIDSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "SetMetaData", resp, "Failure sending request") - return - } - - result, err = client.SetMetaDataWithLeaseIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// SetMetaDataWithLeaseIDPreparer prepares the SetMetaDataWithLeaseID request. -func (client Client) SetMetaDataWithLeaseIDPreparer(ctx context.Context, accountName, containerName, leaseID string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "metadata"), - "restype": autorest.Encode("path", "container"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, metaData) - - // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. - // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - if leaseID != "" { - headers["x-ms-lease-id"] = leaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetMetaDataWithLeaseIDSender sends the SetMetaDataWithLeaseID request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataWithLeaseIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetMetaDataWithLeaseIDResponder handles the response to the SetMetaDataWithLeaseID request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataWithLeaseIDResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/version.go deleted file mode 100644 index d3138cb35875..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package containers - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/README.md deleted file mode 100644 index be6fb76139d5..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/README.md +++ /dev/null @@ -1,84 +0,0 @@ -## Data Lake Storage Gen2 File Systems SDK for API version 2020-08-04 - -This package allows you to interact with the Data Lake Storage Gen2 File Systems API - -### Supported Authorizers - -* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) - -### Example Usage - -```go -package main - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/go-azure-helpers/authentication" - "github.com/hashicorp/go-azure-helpers/sender" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems" -) - -func Example() error { - accountName := "storageaccount1" - fileSystemName := "filesystem1" - - builder := &authentication.Builder{ - SubscriptionID: os.Getenv("ARM_SUBSCRIPTION_ID"), - ClientID: os.Getenv("ARM_CLIENT_ID"), - ClientSecret: os.Getenv("ARM_CLIENT_SECRET"), - TenantID: os.Getenv("ARM_TENANT_ID"), - Environment: os.Getenv("ARM_ENVIRONMENT"), - - // Feature Toggles - SupportsClientSecretAuth: true, - } - - c, err := builder.Build() - if err != nil { - return fmt.Errorf("Error building AzureRM Client: %s", err) - } - - env, err := authentication.DetermineEnvironment(c.Environment) - if err != nil { - return err - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) - if err != nil { - return err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) - } - - sender := sender.BuildSender("AzureRM") - ctx := context.Background() - - storageAuth, err := config.GetAuthorizationToken(sender, oauthConfig, "https://storage.azure.com/") - if err != nil { - return fmt.Errorf("Error retrieving Authorization Token") - } - - - fileSystemsClient := filesystems.NewWithEnvironment(env) - fileSystemsClient.Client.Authorizer = storageAuth - - input := filesystems.CreateInput{ - Properties: map[string]string{}, - } - if _, err = fileSystemsClient.Create(ctx, accountName, fileSystemName, input); err != nil { - return fmt.Errorf("Error creating: %s", err) - } - - return nil -} -``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/client.go deleted file mode 100644 index 91d3fe1cf45e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package filesystems - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Data Lake Storage FileSystem -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Data Lake Storage FileSystem client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Data Lake Storage FileSystem client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/create.go deleted file mode 100644 index 4217cb80af0e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/create.go +++ /dev/null @@ -1,94 +0,0 @@ -package filesystems - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type CreateInput struct { - // A map of base64-encoded strings to store as user-defined properties with the File System - // Note that items may only contain ASCII characters in the ISO-8859-1 character set. - // This automatically gets converted to a comma-separated list of name and - // value pairs before sending to the API - Properties map[string]string -} - -// Create creates a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) Create(ctx context.Context, accountName string, fileSystemName string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.CreatePreparer(ctx, accountName, fileSystemName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure responding to request") - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, fileSystemName string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } - - headers := map[string]interface{}{ - "x-ms-properties": buildProperties(input.Properties), - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/delete.go deleted file mode 100644 index fabc589da940..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/delete.go +++ /dev/null @@ -1,85 +0,0 @@ -package filesystems - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete deletes a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) Delete(ctx context.Context, accountName string, fileSystemName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, fileSystemName) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, fileSystemName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_get.go deleted file mode 100644 index 0b96c95edd52..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_get.go +++ /dev/null @@ -1,112 +0,0 @@ -package filesystems - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetPropertiesResponse struct { - autorest.Response - - // A map of base64-encoded strings to store as user-defined properties with the File System - // Note that items may only contain ASCII characters in the ISO-8859-1 character set. - // This automatically gets converted to a comma-separated list of name and - // value pairs before sending to the API - Properties map[string]string - - // Is Hierarchical Namespace Enabled? - NamespaceEnabled bool -} - -// GetProperties gets the properties for a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) GetProperties(ctx context.Context, accountName string, fileSystemName string) (result GetPropertiesResponse, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.GetPropertiesPreparer(ctx, accountName, fileSystemName) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.GetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure sending request") - return - } - - result, err = client.GetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure responding to request") - } - - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName string, fileSystemName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResponse, err error) { - if resp != nil && resp.Header != nil { - - propertiesRaw := resp.Header.Get("x-ms-properties") - var properties *map[string]string - properties, err = parseProperties(propertiesRaw) - if err != nil { - return - } - - result.Properties = *properties - result.NamespaceEnabled = strings.EqualFold(resp.Header.Get("x-ms-namespace-enabled"), "tru") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_set.go deleted file mode 100644 index dde02a4455b9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_set.go +++ /dev/null @@ -1,109 +0,0 @@ -package filesystems - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type SetPropertiesInput struct { - // A map of base64-encoded strings to store as user-defined properties with the File System - // Note that items may only contain ASCII characters in the ISO-8859-1 character set. - // This automatically gets converted to a comma-separated list of name and - // value pairs before sending to the API - Properties map[string]string - - // Optional - A date and time value. - // Specify this header to perform the operation only if the resource has been modified since the specified date and time. - IfModifiedSince *string - - // Optional - A date and time value. - // Specify this header to perform the operation only if the resource has not been modified since the specified date and time. - IfUnmodifiedSince *string -} - -// SetProperties sets the Properties for a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) SetProperties(ctx context.Context, accountName string, fileSystemName string, input SetPropertiesInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "SetProperties", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "SetProperties", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.SetPropertiesPreparer(ctx, accountName, fileSystemName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.SetPropertiesSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetProperties", resp, "Failure sending request") - return - } - - result, err = client.SetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetProperties", resp, "Failure responding to request") - } - - return -} - -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName string, fileSystemName string, input SetPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } - - headers := map[string]interface{}{ - "x-ms-properties": buildProperties(input.Properties), - "x-ms-version": APIVersion, - } - - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince - } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince - } - - preparer := autorest.CreatePreparer( - autorest.AsPatch(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/resource_id.go deleted file mode 100644 index 34797b20b7a9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/resource_id.go +++ /dev/null @@ -1,46 +0,0 @@ -package filesystems - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Data Lake Storage FileSystem -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName string) string { - domain := endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, shareName) -} - -type ResourceID struct { - AccountName string - DirectoryName string -} - -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with the Data Lake Storage FileSystem API's -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.dfs.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - directoryName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, - DirectoryName: directoryName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/version.go deleted file mode 100644 index 7447ea9ade09..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package filesystems - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/client.go deleted file mode 100644 index 3fb087bf8c8d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package paths - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Data Lake Storage Path -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Data Lake Storage Path client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Data Lake Storage Path client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/create.go deleted file mode 100644 index 600bd75a9a87..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/create.go +++ /dev/null @@ -1,95 +0,0 @@ -package paths - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type PathResource string - -const PathResourceFile PathResource = "file" -const PathResourceDirectory PathResource = "directory" - -type CreateInput struct { - Resource PathResource -} - -// Create creates a Data Lake Store Gen2 Path within a Storage Account -func (client Client) Create(ctx context.Context, accountName string, fileSystemName string, path string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.CreatePreparer(ctx, accountName, fileSystemName, path, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure responding to request") - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, fileSystemName string, path string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", input.Resource), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/delete.go deleted file mode 100644 index 078be57915af..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/delete.go +++ /dev/null @@ -1,81 +0,0 @@ -package paths - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete deletes a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) Delete(ctx context.Context, accountName string, fileSystemName string, path string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, fileSystemName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, fileSystemName string, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_get.go deleted file mode 100644 index 263dc53ed95b..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_get.go +++ /dev/null @@ -1,134 +0,0 @@ -package paths - -import ( - "context" - "net/http" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetPropertiesResponse struct { - autorest.Response - - ETag string - LastModified time.Time - // ResourceType is only returned for GetPropertiesActionGetStatus requests - ResourceType PathResource - Owner string - Group string - // ACL is only returned for GetPropertiesActionGetAccessControl requests - ACL string -} - -type GetPropertiesAction string - -const ( - GetPropertiesActionGetStatus GetPropertiesAction = "getStatus" - GetPropertiesActionGetAccessControl GetPropertiesAction = "getAccessControl" -) - -// GetProperties gets the properties for a Data Lake Store Gen2 Path in a FileSystem within a Storage Account -func (client Client) GetProperties(ctx context.Context, accountName string, fileSystemName string, path string, action GetPropertiesAction) (result GetPropertiesResponse, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.GetPropertiesPreparer(ctx, accountName, fileSystemName, path, action) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.GetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure sending request") - return - } - - result, err = client.GetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure responding to request") - } - - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName string, fileSystemName string, path string, action GetPropertiesAction) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "action": autorest.Encode("query", string(action)), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResponse, err error) { - result = GetPropertiesResponse{} - if resp != nil && resp.Header != nil { - - resourceTypeRaw := resp.Header.Get("x-ms-resource-type") - var resourceType PathResource - if resourceTypeRaw != "" { - resourceType, err = parsePathResource(resourceTypeRaw) - if err != nil { - return GetPropertiesResponse{}, err - } - result.ResourceType = resourceType - } - result.ETag = resp.Header.Get("ETag") - - if lastModifiedRaw := resp.Header.Get("Last-Modified"); lastModifiedRaw != "" { - lastModified, err := time.Parse(time.RFC1123, lastModifiedRaw) - if err != nil { - return GetPropertiesResponse{}, err - } - result.LastModified = lastModified - } - - result.Owner = resp.Header.Get("x-ms-owner") - result.Group = resp.Header.Get("x-ms-group") - result.ACL = resp.Header.Get("x-ms-acl") - } - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return result, err -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_set.go deleted file mode 100644 index 7c0d677647d0..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_set.go +++ /dev/null @@ -1,116 +0,0 @@ -package paths - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type SetAccessControlInput struct { - Owner *string - Group *string - ACL *string - - // Optional - A date and time value. - // Specify this header to perform the operation only if the resource has been modified since the specified date and time. - IfModifiedSince *string - - // Optional - A date and time value. - // Specify this header to perform the operation only if the resource has not been modified since the specified date and time. - IfUnmodifiedSince *string -} - -// SetProperties sets the access control properties for a Data Lake Store Gen2 Path within a Storage Account File System -func (client Client) SetAccessControl(ctx context.Context, accountName string, fileSystemName string, path string, input SetAccessControlInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "SetAccessControl", "`accountName` cannot be an empty string.") - } - if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "SetAccessControl", "`fileSystemName` cannot be an empty string.") - } - - req, err := client.SetAccessControlPreparer(ctx, accountName, fileSystemName, path, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetAccessControl", nil, "Failure preparing request") - return - } - - resp, err := client.SetAccessControlSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetAccessControl", resp, "Failure sending request") - return - } - - result, err = client.SetAccessControlResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetAccessControl", resp, "Failure responding to request") - } - - return -} - -// SetAccessControlPreparer prepares the SetAccessControl request. -func (client Client) SetAccessControlPreparer(ctx context.Context, accountName string, fileSystemName string, path string, input SetAccessControlInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "action": autorest.Encode("query", "setAccessControl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.Owner != nil { - headers["x-ms-owner"] = *input.Owner - } - if input.Group != nil { - headers["x-ms-group"] = *input.Group - } - if input.ACL != nil { - headers["x-ms-acl"] = *input.ACL - } - - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince - } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince - } - - preparer := autorest.CreatePreparer( - autorest.AsPatch(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetAccessControlSender sends the SetAccessControl request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetAccessControlSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetAccessControlResponder handles the response to the SetAccessControl request. The method always -// closes the http.Response Body. -func (client Client) SetAccessControlResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/resource_id.go deleted file mode 100644 index c32841877067..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/resource_id.go +++ /dev/null @@ -1,57 +0,0 @@ -package paths - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Data Lake Storage FileSystem -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, fileSystemName, path string) string { - domain := endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s", domain, fileSystemName, path) -} - -type ResourceID struct { - AccountName string - FileSystemName string - Path string -} - -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with the Data Lake Storage FileSystem API's -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.dfs.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - fileSystemAndPath := strings.TrimPrefix(uri.Path, "/") - separatorIndex := strings.Index(fileSystemAndPath, "/") - var fileSystem, path string - if separatorIndex < 0 { - fileSystem = fileSystemAndPath - path = "" - } else { - fileSystem = fileSystemAndPath[0:separatorIndex] - path = fileSystemAndPath[separatorIndex+1:] - } - return &ResourceID{ - AccountName: *accountName, - FileSystemName: fileSystem, - Path: path, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/version.go deleted file mode 100644 index 3ca5674ec31e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package paths - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/README.md deleted file mode 100644 index 25474c8bc44d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/README.md +++ /dev/null @@ -1,48 +0,0 @@ -## File Storage Directories SDK for API version 2020-08-04 - -This package allows you to interact with the Directories File Storage API - -### Supported Authorizers - -* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) -* SharedKeyLite (Blob, File & Queue) - -### Limitations - -* At this time the headers `x-ms-file-permission` and `x-ms-file-attributes` are hard-coded (to `inherit` and `None`, respectively). - -### Example Usage - -```go -package main - -import ( - "context" - "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories" -) - -func Example() error { - accountName := "storageaccount1" - storageAccountKey := "ABC123...." - shareName := "myshare" - directoryName := "myfiles" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - directoriesClient := directories.New() - directoriesClient.Client.Authorizer = storageAuth - - ctx := context.TODO() - metadata := map[string]string{ - "hello": "world", - } - if _, err := directoriesClient.Create(ctx, accountName, shareName, directoryName, metadata); err != nil { - return fmt.Errorf("Error creating Directory: %s", err) - } - - return nil -} -``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/api.go deleted file mode 100644 index 2699e668022d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/api.go +++ /dev/null @@ -1,16 +0,0 @@ -package directories - -import ( - "context" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageDirectory interface { - Delete(ctx context.Context, accountName, shareName, path string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, shareName, path string) (result GetMetaDataResult, err error) - SetMetaData(ctx context.Context, accountName, shareName, path string, metaData map[string]string) (result autorest.Response, err error) - Create(ctx context.Context, accountName, shareName, path string, input CreateDirectoryInput) (result autorest.Response, err error) - GetResourceID(accountName, shareName, directoryName string) string - Get(ctx context.Context, accountName, shareName, path string) (result GetResult, err error) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/client.go deleted file mode 100644 index bf2d315a524d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package directories - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for File Storage Shares. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/create.go deleted file mode 100644 index 37298319be85..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/create.go +++ /dev/null @@ -1,131 +0,0 @@ -package directories - -import ( - "context" - "fmt" - "net/http" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type CreateDirectoryInput struct { - // The time at which this file was created at - if omitted, this'll be set to "now" - // This maps to the `x-ms-file-creation-time` field. - // ... Yes I know it says File not Directory, I didn't design the API. - CreatedAt *time.Time - - // The time at which this file was last modified - if omitted, this'll be set to "now" - // This maps to the `x-ms-file-last-write-time` field. - // ... Yes I know it says File not Directory, I didn't design the API. - LastModified *time.Time - - // MetaData is a mapping of key value pairs which should be assigned to this directory - MetaData map[string]string -} - -// Create creates a new directory under the specified share or parent directory. -func (client Client) Create(ctx context.Context, accountName, shareName, path string, input CreateDirectoryInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "Create", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("directories.Client", "Create", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "Create", "`shareName` must be a lower-cased string.") - } - if path == "" { - return result, validation.NewError("directories.Client", "Create", "`path` cannot be an empty string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("directories.Client", "Create", fmt.Sprintf("`metadata` is not valid: %s.", err)) - } - - req, err := client.CreatePreparer(ctx, accountName, shareName, path, input) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, shareName, path string, input CreateDirectoryInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - } - - var coalesceDate = func(input *time.Time, defaultVal string) string { - if input == nil { - return defaultVal - } - - return input.Format(time.RFC1123) - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - - // ... Yes I know these say File not Directory, I didn't design the API. - "x-ms-file-permission": "inherit", // TODO: expose this in future - "x-ms-file-attributes": "None", // TODO: expose this in future - "x-ms-file-creation-time": coalesceDate(input.CreatedAt, "now"), - "x-ms-file-last-write-time": coalesceDate(input.LastModified, "now"), - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/delete.go deleted file mode 100644 index 9443c2592983..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/delete.go +++ /dev/null @@ -1,95 +0,0 @@ -package directories - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete removes the specified empty directory -// Note that the directory must be empty before it can be deleted. -func (client Client) Delete(ctx context.Context, accountName, shareName, path string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "Delete", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("directories.Client", "Delete", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "Delete", "`shareName` must be a lower-cased string.") - } - if path == "" { - return result, validation.NewError("directories.Client", "Delete", "`path` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, shareName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, shareName, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/get.go deleted file mode 100644 index 817d680b3fca..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/get.go +++ /dev/null @@ -1,112 +0,0 @@ -package directories - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetResult struct { - autorest.Response - - // A set of name-value pairs that contain metadata for the directory. - MetaData map[string]string - - // The value of this header is set to true if the directory metadata is completely - // encrypted using the specified algorithm. Otherwise, the value is set to false. - DirectoryMetaDataEncrypted bool -} - -// Get returns all system properties for the specified directory, -// and can also be used to check the existence of a directory. -func (client Client) Get(ctx context.Context, accountName, shareName, path string) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "Get", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("directories.Client", "Get", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "Get", "`shareName` must be a lower-cased string.") - } - if path == "" { - return result, validation.NewError("directories.Client", "Get", "`path` cannot be an empty string.") - } - - req, err := client.GetPreparer(ctx, accountName, shareName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client Client) GetPreparer(ctx context.Context, accountName, shareName, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client Client) GetResponder(resp *http.Response) (result GetResult, err error) { - if resp != nil && resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - result.DirectoryMetaDataEncrypted = strings.EqualFold(resp.Header.Get("x-ms-server-encrypted"), "true") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_get.go deleted file mode 100644 index 173716de7400..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_get.go +++ /dev/null @@ -1,106 +0,0 @@ -package directories - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetMetaDataResult struct { - autorest.Response - - MetaData map[string]string -} - -// GetMetaData returns all user-defined metadata for the specified directory -func (client Client) GetMetaData(ctx context.Context, accountName, shareName, path string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("directories.Client", "GetMetaData", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "GetMetaData", "`shareName` must be a lower-cased string.") - } - if path == "" { - return result, validation.NewError("directories.Client", "GetMetaData", "`path` cannot be an empty string.") - } - - req, err := client.GetMetaDataPreparer(ctx, accountName, shareName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "GetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.GetMetaDataSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "GetMetaData", resp, "Failure sending request") - return - } - - result, err = client.GetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "GetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, shareName, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp != nil && resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_set.go deleted file mode 100644 index cb133127da00..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_set.go +++ /dev/null @@ -1,102 +0,0 @@ -package directories - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -// SetMetaData updates user defined metadata for the specified directory -func (client Client) SetMetaData(ctx context.Context, accountName, shareName, path string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("directories.Client", "SetMetaData", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "SetMetaData", "`shareName` must be a lower-cased string.") - } - if path == "" { - return result, validation.NewError("directories.Client", "SetMetaData", "`path` cannot be an empty string.") - } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("directories.Client", "SetMetaData", fmt.Sprintf("`metaData` is not valid: %s.", err)) - } - - req, err := client.SetMetaDataPreparer(ctx, accountName, shareName, path, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "SetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.SetMetaDataSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "SetMetaData", resp, "Failure sending request") - return - } - - result, err = client.SetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "SetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, shareName, path string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/resource_id.go deleted file mode 100644 index 712ed3a00c39..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/resource_id.go +++ /dev/null @@ -1,56 +0,0 @@ -package directories - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Directory -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName, directoryName string) string { - domain := endpoints.GetFileEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s", domain, shareName, directoryName) -} - -type ResourceID struct { - AccountName string - DirectoryName string - ShareName string -} - -// ParseResourceID parses the Resource ID into an Object -// which can be used to interact with the Directory within the File Share -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.file.core.windows.net/Bar/Folder - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - path := strings.TrimPrefix(uri.Path, "/") - segments := strings.Split(path, "/") - if len(segments) == 0 { - return nil, fmt.Errorf("Expected the path to contain segments but got none") - } - - shareName := segments[0] - directoryName := strings.TrimPrefix(path, shareName) - directoryName = strings.TrimPrefix(directoryName, "/") - return &ResourceID{ - AccountName: *accountName, - ShareName: shareName, - DirectoryName: directoryName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/version.go deleted file mode 100644 index 8446be29ebb2..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package directories - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/api.go deleted file mode 100644 index 96a0491e70da..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/api.go +++ /dev/null @@ -1,28 +0,0 @@ -package files - -import ( - "context" - "os" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageFile interface { - PutByteRange(ctx context.Context, accountName, shareName, path, fileName string, input PutByteRangeInput) (result autorest.Response, err error) - GetByteRange(ctx context.Context, accountName, shareName, path, fileName string, input GetByteRangeInput) (result GetByteRangeResult, err error) - ClearByteRange(ctx context.Context, accountName, shareName, path, fileName string, input ClearByteRangeInput) (result autorest.Response, err error) - SetProperties(ctx context.Context, accountName, shareName, path, fileName string, input SetPropertiesInput) (result autorest.Response, err error) - PutFile(ctx context.Context, accountName, shareName, path, fileName string, file *os.File, parallelism int) error - Copy(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput) (result CopyResult, err error) - SetMetaData(ctx context.Context, accountName, shareName, path, fileName string, metaData map[string]string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, shareName, path, fileName string) (result GetMetaDataResult, err error) - AbortCopy(ctx context.Context, accountName, shareName, path, fileName, copyID string) (result autorest.Response, err error) - GetFile(ctx context.Context, accountName, shareName, path, fileName string, parallelism int) (result autorest.Response, outputBytes []byte, err error) - GetResourceID(accountName, shareName, directoryName, filePath string) string - ListRanges(ctx context.Context, accountName, shareName, path, fileName string) (result ListRangesResult, err error) - GetProperties(ctx context.Context, accountName, shareName, path, fileName string) (result GetResult, err error) - Delete(ctx context.Context, accountName, shareName, path, fileName string) (result autorest.Response, err error) - Create(ctx context.Context, accountName, shareName, path, fileName string, input CreateInput) (result autorest.Response, err error) - CopyAndWait(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput, pollDuration time.Duration) (result CopyResult, err error) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/client.go deleted file mode 100644 index ecca81586b5a..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package files - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for File Storage Shares. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy.go deleted file mode 100644 index 31768b3d52b7..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy.go +++ /dev/null @@ -1,132 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type CopyInput struct { - // Specifies the URL of the source file or blob, up to 2 KB in length. - // - // To copy a file to another file within the same storage account, you may use Shared Key to authenticate - // the source file. If you are copying a file from another storage account, or if you are copying a blob from - // the same storage account or another storage account, then you must authenticate the source file or blob using a - // shared access signature. If the source is a public blob, no authentication is required to perform the copy - // operation. A file in a share snapshot can also be specified as a copy source. - CopySource string - - MetaData map[string]string -} - -type CopyResult struct { - autorest.Response - - // The CopyID, which can be passed to AbortCopy to abort the copy. - CopyID string - - // Either `success` or `pending` - CopySuccess string -} - -// Copy copies a blob or file to a destination file within the storage account asynchronously. -func (client Client) Copy(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput) (result CopyResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "Copy", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "Copy", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "Copy", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "Copy", "`fileName` cannot be an empty string.") - } - if input.CopySource == "" { - return result, validation.NewError("files.Client", "Copy", "`input.CopySource` cannot be an empty string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("files.Client", "Copy", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.CopyPreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Copy", nil, "Failure preparing request") - return - } - - resp, err := client.CopySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "Copy", resp, "Failure sending request") - return - } - - result, err = client.CopyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Copy", resp, "Failure responding to request") - return - } - - return -} - -// CopyPreparer prepares the Copy request. -func (client Client) CopyPreparer(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": input.CopySource, - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CopySender sends the Copy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CopyResponder handles the response to the Copy request. The method always -// closes the http.Response Body. -func (client Client) CopyResponder(resp *http.Response) (result CopyResult, err error) { - if resp != nil && resp.Header != nil { - result.CopyID = resp.Header.Get("x-ms-copy-id") - result.CopySuccess = resp.Header.Get("x-ms-copy-status") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_abort.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_abort.go deleted file mode 100644 index 2f0913185888..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_abort.go +++ /dev/null @@ -1,104 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// AbortCopy aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata -func (client Client) AbortCopy(ctx context.Context, accountName, shareName, path, fileName, copyID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "AbortCopy", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`fileName` cannot be an empty string.") - } - if copyID == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`copyID` cannot be an empty string.") - } - - req, err := client.AbortCopyPreparer(ctx, accountName, shareName, path, fileName, copyID) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "AbortCopy", nil, "Failure preparing request") - return - } - - resp, err := client.AbortCopySender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "AbortCopy", resp, "Failure sending request") - return - } - - result, err = client.AbortCopyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "AbortCopy", resp, "Failure responding to request") - return - } - - return -} - -// AbortCopyPreparer prepares the AbortCopy request. -func (client Client) AbortCopyPreparer(ctx context.Context, accountName, shareName, path, fileName, copyID string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "copy"), - "copyid": autorest.Encode("query", copyID), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-action": "abort", - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AbortCopySender sends the AbortCopy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AbortCopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// AbortCopyResponder handles the response to the AbortCopy request. The method always -// closes the http.Response Body. -func (client Client) AbortCopyResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_wait.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_wait.go deleted file mode 100644 index e6a646b1017b..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_wait.go +++ /dev/null @@ -1,55 +0,0 @@ -package files - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -type CopyAndWaitResult struct { - autorest.Response - - CopyID string -} - -const DefaultCopyPollDuration = 15 * time.Second - -// CopyAndWait is a convenience method which doesn't exist in the API, which copies the file and then waits for the copy to complete -func (client Client) CopyAndWait(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput, pollDuration time.Duration) (result CopyResult, err error) { - copy, e := client.Copy(ctx, accountName, shareName, path, fileName, input) - if err != nil { - result.Response = copy.Response - err = fmt.Errorf("Error copying: %s", e) - return - } - - result.CopyID = copy.CopyID - - // since the API doesn't return a LRO, this is a hack which also polls every 10s, but should be sufficient - for true { - props, e := client.GetProperties(ctx, accountName, shareName, path, fileName) - if e != nil { - result.Response = copy.Response - err = fmt.Errorf("Error waiting for copy: %s", e) - return - } - - switch strings.ToLower(props.CopyStatus) { - case "pending": - time.Sleep(pollDuration) - continue - - case "success": - return - - default: - err = fmt.Errorf("Unexpected CopyState %q", e) - return - } - } - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/create.go deleted file mode 100644 index d2b4ff358120..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/create.go +++ /dev/null @@ -1,169 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type CreateInput struct { - // This header specifies the maximum size for the file, up to 1 TiB. - ContentLength int64 - - // The MIME content type of the file - // If not specified, the default type is application/octet-stream. - ContentType *string - - // Specifies which content encodings have been applied to the file. - // This value is returned to the client when the Get File operation is performed - // on the file resource and can be used to decode file content. - ContentEncoding *string - - // Specifies the natural languages used by this resource. - ContentLanguage *string - - // The File service stores this value but does not use or modify it. - CacheControl *string - - // Sets the file's MD5 hash. - ContentMD5 *string - - // Sets the file’s Content-Disposition header. - ContentDisposition *string - - // The time at which this file was created at - if omitted, this'll be set to "now" - // This maps to the `x-ms-file-creation-time` field. - CreatedAt *time.Time - - // The time at which this file was last modified - if omitted, this'll be set to "now" - // This maps to the `x-ms-file-last-write-time` field. - LastModified *time.Time - - // MetaData is a mapping of key value pairs which should be assigned to this file - MetaData map[string]string -} - -// Create creates a new file or replaces a file. -func (client Client) Create(ctx context.Context, accountName, shareName, path, fileName string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "Create", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "Create", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "Create", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "Create", "`fileName` cannot be an empty string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("files.Client", "Create", "`input.MetaData` cannot be an empty string.") - } - - req, err := client.CreatePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, shareName, path, fileName string, input CreateInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - var coalesceDate = func(input *time.Time, defaultVal string) string { - if input == nil { - return defaultVal - } - - return input.Format(time.RFC1123) - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-content-length": input.ContentLength, - "x-ms-type": "file", - - "x-ms-file-permission": "inherit", // TODO: expose this in future - "x-ms-file-attributes": "None", // TODO: expose this in future - "x-ms-file-creation-time": coalesceDate(input.CreatedAt, "now"), - "x-ms-file-last-write-time": coalesceDate(input.LastModified, "now"), - } - - if input.ContentDisposition != nil { - headers["x-ms-content-disposition"] = *input.ContentDisposition - } - - if input.ContentEncoding != nil { - headers["x-ms-content-encoding"] = *input.ContentEncoding - } - - if input.ContentMD5 != nil { - headers["x-ms-content-md5"] = *input.ContentMD5 - } - - if input.ContentType != nil { - headers["x-ms-content-type"] = *input.ContentType - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/delete.go deleted file mode 100644 index 5debd767d1fd..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/delete.go +++ /dev/null @@ -1,94 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete immediately deletes the file from the File Share. -func (client Client) Delete(ctx context.Context, accountName, shareName, path, fileName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "Delete", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "Delete", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "Delete", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "Delete", "`fileName` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_get.go deleted file mode 100644 index fd62f90aec8f..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_get.go +++ /dev/null @@ -1,111 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetMetaDataResult struct { - autorest.Response - - MetaData map[string]string -} - -// GetMetaData returns the MetaData for the specified File. -func (client Client) GetMetaData(ctx context.Context, accountName, shareName, path, fileName string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "GetMetaData", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "GetMetaData", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "GetMetaData", "`fileName` cannot be an empty string.") - } - - req, err := client.GetMetaDataPreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.GetMetaDataSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "GetMetaData", resp, "Failure sending request") - return - } - - result, err = client.GetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp != nil && resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - //metadata.ByParsingFromHeaders(&result.MetaData), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_set.go deleted file mode 100644 index 41e3ffcb8ff9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_set.go +++ /dev/null @@ -1,105 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -// SetMetaData updates the specified File to have the specified MetaData. -func (client Client) SetMetaData(ctx context.Context, accountName, shareName, path, fileName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "SetMetaData", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "SetMetaData", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "SetMetaData", "`fileName` cannot be an empty string.") - } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("files.Client", "SetMetaData", fmt.Sprintf("`metaData` is not valid: %s.", err)) - } - - req, err := client.SetMetaDataPreparer(ctx, accountName, shareName, path, fileName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.SetMetaDataSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "SetMetaData", resp, "Failure sending request") - return - } - - result, err = client.SetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, shareName, path, fileName string, metaData map[string]string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_get.go deleted file mode 100644 index 0300b1ce5ec6..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_get.go +++ /dev/null @@ -1,144 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetResult struct { - autorest.Response - - CacheControl string - ContentDisposition string - ContentEncoding string - ContentLanguage string - ContentLength *int64 - ContentMD5 string - ContentType string - CopyID string - CopyStatus string - CopySource string - CopyProgress string - CopyStatusDescription string - CopyCompletionTime string - Encrypted bool - - MetaData map[string]string -} - -// GetProperties returns the Properties for the specified file -func (client Client) GetProperties(ctx context.Context, accountName, shareName, path, fileName string) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "GetProperties", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "GetProperties", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "GetProperties", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "GetProperties", "`fileName` cannot be an empty string.") - } - - req, err := client.GetPropertiesPreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.GetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "GetProperties", resp, "Failure sending request") - return - } - - result, err = client.GetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetProperties", resp, "Failure responding to request") - return - } - - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetResult, err error) { - if resp != nil && resp.Header != nil { - result.CacheControl = resp.Header.Get("Cache-Control") - result.ContentDisposition = resp.Header.Get("Content-Disposition") - result.ContentEncoding = resp.Header.Get("Content-Encoding") - result.ContentLanguage = resp.Header.Get("Content-Language") - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.ContentType = resp.Header.Get("Content-Type") - result.CopyID = resp.Header.Get("x-ms-copy-id") - result.CopyProgress = resp.Header.Get("x-ms-copy-progress") - result.CopySource = resp.Header.Get("x-ms-copy-source") - result.CopyStatus = resp.Header.Get("x-ms-copy-status") - result.CopyStatusDescription = resp.Header.Get("x-ms-copy-status-description") - result.CopyCompletionTime = resp.Header.Get("x-ms-copy-completion-time") - result.Encrypted = strings.EqualFold(resp.Header.Get("x-ms-server-encrypted"), "true") - result.MetaData = metadata.ParseFromHeaders(resp.Header) - - contentLengthRaw := resp.Header.Get("Content-Length") - if contentLengthRaw != "" { - contentLength, err := strconv.Atoi(contentLengthRaw) - if err != nil { - return result, fmt.Errorf("Error parsing %q for Content-Length as an integer: %s", contentLengthRaw, err) - } - contentLengthI64 := int64(contentLength) - result.ContentLength = &contentLengthI64 - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_set.go deleted file mode 100644 index 521b1bba7be7..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_set.go +++ /dev/null @@ -1,186 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type SetPropertiesInput struct { - // Resizes a file to the specified size. - // If the specified byte value is less than the current size of the file, - // then all ranges above the specified byte value are cleared. - ContentLength int64 - - // Modifies the cache control string for the file. - // If this property is not specified on the request, then the property will be cleared for the file. - // Subsequent calls to Get File Properties will not return this property, - // unless it is explicitly set on the file again. - ContentControl *string - - // Sets the file’s Content-Disposition header. - // If this property is not specified on the request, then the property will be cleared for the file. - // Subsequent calls to Get File Properties will not return this property, - // unless it is explicitly set on the file again. - ContentDisposition *string - - // Sets the file's content encoding. - // If this property is not specified on the request, then the property will be cleared for the file. - // Subsequent calls to Get File Properties will not return this property, - // unless it is explicitly set on the file again. - ContentEncoding *string - - // Sets the file's content language. - // If this property is not specified on the request, then the property will be cleared for the file. - // Subsequent calls to Get File Properties will not return this property, - // unless it is explicitly set on the file again. - ContentLanguage *string - - // Sets the file's MD5 hash. - // If this property is not specified on the request, then the property will be cleared for the file. - // Subsequent calls to Get File Properties will not return this property, - // unless it is explicitly set on the file again. - ContentMD5 *string - - // Sets the file's content type. - // If this property is not specified on the request, then the property will be cleared for the file. - // Subsequent calls to Get File Properties will not return this property, - // unless it is explicitly set on the file again. - ContentType *string - - // The time at which this file was created at - if omitted, this'll be set to "now" - // This maps to the `x-ms-file-creation-time` field. - CreatedAt *time.Time - - // The time at which this file was last modified - if omitted, this'll be set to "now" - // This maps to the `x-ms-file-last-write-time` field. - LastModified *time.Time - - // MetaData is a mapping of key value pairs which should be assigned to this file - MetaData map[string]string -} - -// SetProperties sets the specified properties on the specified File -func (client Client) SetProperties(ctx context.Context, accountName, shareName, path, fileName string, input SetPropertiesInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "SetProperties", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "SetProperties", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "SetProperties", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "SetProperties", "`fileName` cannot be an empty string.") - } - - req, err := client.SetPropertiesPreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.SetPropertiesSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "SetProperties", resp, "Failure sending request") - return - } - - result, err = client.SetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetProperties", resp, "Failure responding to request") - return - } - - return -} - -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName, shareName, path, fileName string, input SetPropertiesInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - var coalesceDate = func(input *time.Time, defaultVal string) string { - if input == nil { - return defaultVal - } - - return input.Format(time.RFC1123) - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-type": "file", - - "x-ms-content-length": input.ContentLength, - "x-ms-file-permission": "inherit", // TODO: expose this in future - "x-ms-file-attributes": "None", // TODO: expose this in future - "x-ms-file-creation-time": coalesceDate(input.CreatedAt, "now"), - "x-ms-file-last-write-time": coalesceDate(input.LastModified, "now"), - } - - if input.ContentControl != nil { - headers["x-ms-cache-control"] = *input.ContentControl - } - if input.ContentDisposition != nil { - headers["x-ms-content-disposition"] = *input.ContentDisposition - } - if input.ContentEncoding != nil { - headers["x-ms-content-encoding"] = *input.ContentEncoding - } - if input.ContentLanguage != nil { - headers["x-ms-content-language"] = *input.ContentLanguage - } - if input.ContentMD5 != nil { - headers["x-ms-content-md5"] = *input.ContentMD5 - } - if input.ContentType != nil { - headers["x-ms-content-type"] = *input.ContentType - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_clear.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_clear.go deleted file mode 100644 index 5d8145fae422..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_clear.go +++ /dev/null @@ -1,112 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type ClearByteRangeInput struct { - StartBytes int64 - EndBytes int64 -} - -// ClearByteRange clears the specified Byte Range from within the specified File -func (client Client) ClearByteRange(ctx context.Context, accountName, shareName, path, fileName string, input ClearByteRangeInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "ClearByteRange", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "ClearByteRange", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "ClearByteRange", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "ClearByteRange", "`fileName` cannot be an empty string.") - } - if input.StartBytes < 0 { - return result, validation.NewError("files.Client", "ClearByteRange", "`input.StartBytes` must be greater or equal to 0.") - } - if input.EndBytes <= 0 { - return result, validation.NewError("files.Client", "ClearByteRange", "`input.EndBytes` must be greater than 0.") - } - - req, err := client.ClearByteRangePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ClearByteRange", nil, "Failure preparing request") - return - } - - resp, err := client.ClearByteRangeSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "ClearByteRange", resp, "Failure sending request") - return - } - - result, err = client.ClearByteRangeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ClearByteRange", resp, "Failure responding to request") - return - } - - return -} - -// ClearByteRangePreparer prepares the ClearByteRange request. -func (client Client) ClearByteRangePreparer(ctx context.Context, accountName, shareName, path, fileName string, input ClearByteRangeInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "range"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-write": "clear", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartBytes, input.EndBytes), - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ClearByteRangeSender sends the ClearByteRange request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ClearByteRangeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ClearByteRangeResponder handles the response to the ClearByteRange request. The method always -// closes the http.Response Body. -func (client Client) ClearByteRangeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get.go deleted file mode 100644 index 733d3f525105..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get.go +++ /dev/null @@ -1,121 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetByteRangeInput struct { - StartBytes int64 - EndBytes int64 -} - -type GetByteRangeResult struct { - autorest.Response - - Contents []byte -} - -// GetByteRange returns the specified Byte Range from the specified File. -func (client Client) GetByteRange(ctx context.Context, accountName, shareName, path, fileName string, input GetByteRangeInput) (result GetByteRangeResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "GetByteRange", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "GetByteRange", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "GetByteRange", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "GetByteRange", "`fileName` cannot be an empty string.") - } - if input.StartBytes < 0 { - return result, validation.NewError("files.Client", "GetByteRange", "`input.StartBytes` must be greater or equal to 0.") - } - if input.EndBytes <= 0 { - return result, validation.NewError("files.Client", "GetByteRange", "`input.EndBytes` must be greater than 0.") - } - expectedBytes := input.EndBytes - input.StartBytes - if expectedBytes < (4 * 1024) { - return result, validation.NewError("files.Client", "GetByteRange", "Requested Byte Range must be at least 4KB.") - } - if expectedBytes > (4 * 1024 * 1024) { - return result, validation.NewError("files.Client", "GetByteRange", "Requested Byte Range must be at most 4MB.") - } - - req, err := client.GetByteRangePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetByteRange", nil, "Failure preparing request") - return - } - - resp, err := client.GetByteRangeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "GetByteRange", resp, "Failure sending request") - return - } - - result, err = client.GetByteRangeResponder(resp, expectedBytes) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetByteRange", resp, "Failure responding to request") - return - } - - return -} - -// GetByteRangePreparer prepares the GetByteRange request. -func (client Client) GetByteRangePreparer(ctx context.Context, accountName, shareName, path, fileName string, input GetByteRangeInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartBytes, input.EndBytes-1), - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetByteRangeSender sends the GetByteRange request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetByteRangeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetByteRangeResponder handles the response to the GetByteRange request. The method always -// closes the http.Response Body. -func (client Client) GetByteRangeResponder(resp *http.Response, length int64) (result GetByteRangeResult, err error) { - result.Contents = make([]byte, length) - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusPartialContent), - autorest.ByUnmarshallingBytes(&result.Contents), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put.go deleted file mode 100644 index 20e4d398d590..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put.go +++ /dev/null @@ -1,127 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type PutByteRangeInput struct { - StartBytes int64 - EndBytes int64 - - // Content is the File Contents for the specified range - // which can be at most 4MB - Content []byte -} - -// PutByteRange puts the specified Byte Range in the specified File. -func (client Client) PutByteRange(ctx context.Context, accountName, shareName, path, fileName string, input PutByteRangeInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "PutByteRange", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "PutByteRange", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "PutByteRange", "`shareName` must be a lower-cased string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "PutByteRange", "`fileName` cannot be an empty string.") - } - if input.StartBytes < 0 { - return result, validation.NewError("files.Client", "PutByteRange", "`input.StartBytes` must be greater or equal to 0.") - } - if input.EndBytes <= 0 { - return result, validation.NewError("files.Client", "PutByteRange", "`input.EndBytes` must be greater than 0.") - } - - expectedBytes := input.EndBytes - input.StartBytes - actualBytes := len(input.Content) - if expectedBytes != int64(actualBytes) { - return result, validation.NewError("files.Client", "PutByteRange", fmt.Sprintf("The specified byte-range (%d) didn't match the content size (%d).", expectedBytes, actualBytes)) - } - - if expectedBytes > (4 * 1024 * 1024) { - return result, validation.NewError("files.Client", "PutByteRange", "Specified Byte Range must be at most 4MB.") - } - - req, err := client.PutByteRangePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "PutByteRange", nil, "Failure preparing request") - return - } - - resp, err := client.PutByteRangeSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "PutByteRange", resp, "Failure sending request") - return - } - - result, err = client.PutByteRangeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "PutByteRange", resp, "Failure responding to request") - return - } - - return -} - -// PutByteRangePreparer prepares the PutByteRange request. -func (client Client) PutByteRangePreparer(ctx context.Context, accountName, shareName, path, fileName string, input PutByteRangeInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "range"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-write": "update", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartBytes, input.EndBytes-1), - "Content-Length": int(len(input.Content)), - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters), - autorest.WithBytes(&input.Content)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutByteRangeSender sends the PutByteRange request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutByteRangeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// PutByteRangeResponder handles the response to the PutByteRange request. The method always -// closes the http.Response Body. -func (client Client) PutByteRangeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/ranges_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/ranges_list.go deleted file mode 100644 index ea309f97ddb2..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/ranges_list.go +++ /dev/null @@ -1,114 +0,0 @@ -package files - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type ListRangesResult struct { - autorest.Response - - Ranges []Range `xml:"Range"` -} - -type Range struct { - Start string `xml:"Start"` - End string `xml:"End"` -} - -// ListRanges returns the list of valid ranges for the specified File. -func (client Client) ListRanges(ctx context.Context, accountName, shareName, path, fileName string) (result ListRangesResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "ListRanges", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("files.Client", "ListRanges", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "ListRanges", "`shareName` must be a lower-cased string.") - } - if path == "" { - return result, validation.NewError("files.Client", "ListRanges", "`path` cannot be an empty string.") - } - if fileName == "" { - return result, validation.NewError("files.Client", "ListRanges", "`fileName` cannot be an empty string.") - } - - req, err := client.ListRangesPreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ListRanges", nil, "Failure preparing request") - return - } - - resp, err := client.ListRangesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "ListRanges", resp, "Failure sending request") - return - } - - result, err = client.ListRangesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ListRanges", resp, "Failure responding to request") - return - } - - return -} - -// ListRangesPreparer prepares the ListRanges request. -func (client Client) ListRangesPreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "rangelist"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRangesSender sends the ListRanges request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ListRangesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListRangesResponder handles the response to the ListRanges request. The method always -// closes the http.Response Body. -func (client Client) ListRangesResponder(resp *http.Response) (result ListRangesResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/resource_id.go deleted file mode 100644 index f18e702e81d9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/resource_id.go +++ /dev/null @@ -1,64 +0,0 @@ -package files - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given File -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName, directoryName, filePath string) string { - domain := endpoints.GetFileEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s/%s", domain, shareName, directoryName, filePath) -} - -type ResourceID struct { - AccountName string - DirectoryName string - FileName string - ShareName string -} - -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with Files within a Storage Share. -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://account1.file.core.chinacloudapi.cn/share1/directory1/file1.txt - // example: https://account1.file.core.chinacloudapi.cn/share1/directory1/directory2/file1.txt - - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - path := strings.TrimPrefix(uri.Path, "/") - segments := strings.Split(path, "/") - if len(segments) == 0 { - return nil, fmt.Errorf("Expected the path to contain segments but got none") - } - - shareName := segments[0] - fileName := segments[len(segments)-1] - - directoryName := strings.TrimPrefix(path, shareName) - directoryName = strings.TrimPrefix(directoryName, "/") - directoryName = strings.TrimSuffix(directoryName, fileName) - directoryName = strings.TrimSuffix(directoryName, "/") - return &ResourceID{ - AccountName: *accountName, - ShareName: shareName, - DirectoryName: directoryName, - FileName: fileName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/version.go deleted file mode 100644 index 7c8231033703..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package files - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/README.md deleted file mode 100644 index ecc0f13ae9bb..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/README.md +++ /dev/null @@ -1,43 +0,0 @@ -## File Storage Shares SDK for API version 2020-08-04 - -This package allows you to interact with the Shares File Storage API - -### Supported Authorizers - -* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) -* SharedKeyLite (Blob, File & Queue) - -### Example Usage - -```go -package main - -import ( - "context" - "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" -) - -func Example() error { - accountName := "storageaccount1" - storageAccountKey := "ABC123...." - shareName := "myshare" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - sharesClient := shares.New() - sharesClient.Client.Authorizer = storageAuth - - ctx := context.TODO() - input := shares.CreateInput{ - QuotaInGB: 2, - } - if _, err := sharesClient.Create(ctx, accountName, shareName, input); err != nil { - return fmt.Errorf("Error creating Share: %s", err) - } - - return nil -} -``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_get.go deleted file mode 100644 index ea6ff4c2dd26..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_get.go +++ /dev/null @@ -1,98 +0,0 @@ -package shares - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetACLResult struct { - autorest.Response - - SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` -} - -// GetACL get the Access Control List for the specified Storage Share -func (client Client) GetACL(ctx context.Context, accountName, shareName string) (result GetACLResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetACL", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "GetACL", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetACL", "`shareName` must be a lower-cased string.") - } - - req, err := client.GetACLPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetACL", nil, "Failure preparing request") - return - } - - resp, err := client.GetACLSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetACL", resp, "Failure sending request") - return - } - - result, err = client.GetACLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetACL", resp, "Failure responding to request") - return - } - - return -} - -// GetACLPreparer prepares the GetACL request. -func (client Client) GetACLPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "acl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetACLSender sends the GetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetACLResponder handles the response to the GetACL request. The method always -// closes the http.Response Body. -func (client Client) GetACLResponder(resp *http.Response) (result GetACLResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_set.go deleted file mode 100644 index 18d1788a2ee4..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_set.go +++ /dev/null @@ -1,103 +0,0 @@ -package shares - -import ( - "context" - "encoding/xml" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type setAcl struct { - SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` - - XMLName xml.Name `xml:"SignedIdentifiers"` -} - -// SetACL sets the specified Access Control List on the specified Storage Share -func (client Client) SetACL(ctx context.Context, accountName, shareName string, acls []SignedIdentifier) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "SetACL", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "SetACL", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "SetACL", "`shareName` must be a lower-cased string.") - } - - req, err := client.SetACLPreparer(ctx, accountName, shareName, acls) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetACL", nil, "Failure preparing request") - return - } - - resp, err := client.SetACLSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "SetACL", resp, "Failure sending request") - return - } - - result, err = client.SetACLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetACL", resp, "Failure responding to request") - return - } - - return -} - -// SetACLPreparer prepares the SetACL request. -func (client Client) SetACLPreparer(ctx context.Context, accountName, shareName string, acls []SignedIdentifier) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "acl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - input := setAcl{ - SignedIdentifiers: acls, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithXML(&input)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetACLSender sends the SetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetACLResponder handles the response to the SetACL request. The method always -// closes the http.Response Body. -func (client Client) SetACLResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/api.go deleted file mode 100644 index 91645912dfb6..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/api.go +++ /dev/null @@ -1,24 +0,0 @@ -package shares - -import ( - "context" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageShare interface { - SetACL(ctx context.Context, accountName, shareName string, acls []SignedIdentifier) (result autorest.Response, err error) - GetSnapshot(ctx context.Context, accountName, shareName, snapshotShare string) (result GetSnapshotPropertiesResult, err error) - GetStats(ctx context.Context, accountName, shareName string) (result GetStatsResult, err error) - GetACL(ctx context.Context, accountName, shareName string) (result GetACLResult, err error) - SetMetaData(ctx context.Context, accountName, shareName string, metaData map[string]string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, shareName string) (result GetMetaDataResult, err error) - SetProperties(ctx context.Context, accountName, shareName string, properties ShareProperties) (result autorest.Response, err error) - DeleteSnapshot(ctx context.Context, accountName, shareName string, shareSnapshot string) (result autorest.Response, err error) - CreateSnapshot(ctx context.Context, accountName, shareName string, input CreateSnapshotInput) (result CreateSnapshotResult, err error) - GetResourceID(accountName, shareName string) string - GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, shareName string) string - GetProperties(ctx context.Context, accountName, shareName string) (result GetPropertiesResult, err error) - Delete(ctx context.Context, accountName, shareName string, deleteSnapshots bool) (result autorest.Response, err error) - Create(ctx context.Context, accountName, shareName string, input CreateInput) (result autorest.Response, err error) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/client.go deleted file mode 100644 index 4f3a6f9f99d0..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package shares - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for File Storage Shares. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/create.go deleted file mode 100644 index 10a1148f0368..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/create.go +++ /dev/null @@ -1,134 +0,0 @@ -package shares - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type AccessTier string - -const ( - TransactionOptimizedAccessTier AccessTier = "TransactionOptimized" - HotAccessTier AccessTier = "Hot" - CoolAccessTier AccessTier = "Cool" - PremiumAccessTier AccessTier = "Premium" -) - -type CreateInput struct { - // Specifies the maximum size of the share, in gigabytes. - // Must be greater than 0, and less than or equal to 5TB (5120). - QuotaInGB int - - // Specifies the enabled protocols on the share. If not specified, the default is SMB. - EnabledProtocol ShareProtocol - - MetaData map[string]string - - // Specifies the access tier of the share. - AccessTier *AccessTier -} - -// Create creates the specified Storage Share within the specified Storage Account -func (client Client) Create(ctx context.Context, accountName, shareName string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "Create", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "Create", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "Create", "`shareName` must be a lower-cased string.") - } - if input.QuotaInGB <= 0 || input.QuotaInGB > 102400 { - return result, validation.NewError("shares.Client", "Create", "`input.QuotaInGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("shares.Client", "Create", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.CreatePreparer(ctx, accountName, shareName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, shareName string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "share"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-share-quota": input.QuotaInGB, - } - - protocol := SMB - if input.EnabledProtocol != "" { - protocol = input.EnabledProtocol - } - headers["x-ms-enabled-protocols"] = protocol - - if input.AccessTier != nil { - headers["x-ms-access-tier"] = string(*input.AccessTier) - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/delete.go deleted file mode 100644 index 70ef985d23bb..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/delete.go +++ /dev/null @@ -1,94 +0,0 @@ -package shares - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete deletes the specified Storage Share from within a Storage Account -func (client Client) Delete(ctx context.Context, accountName, shareName string, deleteSnapshots bool) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "Delete", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "Delete", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "Delete", "`shareName` must be a lower-cased string.") - } - - req, err := client.DeletePreparer(ctx, accountName, shareName, deleteSnapshots) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, shareName string, deleteSnapshots bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "share"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if deleteSnapshots { - headers["x-ms-delete-snapshots"] = "include" - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_get.go deleted file mode 100644 index 9fa4d9f07ed8..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_get.go +++ /dev/null @@ -1,102 +0,0 @@ -package shares - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetMetaDataResult struct { - autorest.Response - - MetaData map[string]string -} - -// GetMetaData returns the MetaData associated with the specified Storage Share -func (client Client) GetMetaData(ctx context.Context, accountName, shareName string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "GetMetaData", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetMetaData", "`shareName` must be a lower-cased string.") - } - - req, err := client.GetMetaDataPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.GetMetaDataSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetMetaData", resp, "Failure sending request") - return - } - - result, err = client.GetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_set.go deleted file mode 100644 index 7e64e60aca15..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_set.go +++ /dev/null @@ -1,97 +0,0 @@ -package shares - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -// SetMetaData sets the MetaData on the specified Storage Share -func (client Client) SetMetaData(ctx context.Context, accountName, shareName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "SetMetaData", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "SetMetaData", "`shareName` must be a lower-cased string.") - } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("shares.Client", "SetMetaData", fmt.Sprintf("`metadata` is not valid: %s.", err)) - } - - req, err := client.SetMetaDataPreparer(ctx, accountName, shareName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.SetMetaDataSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "SetMetaData", resp, "Failure sending request") - return - } - - result, err = client.SetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, shareName string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetPropertiesSetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_get.go deleted file mode 100644 index 28e36e6d3eaf..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_get.go +++ /dev/null @@ -1,126 +0,0 @@ -package shares - -import ( - "context" - "fmt" - "net/http" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetPropertiesResult struct { - autorest.Response - - MetaData map[string]string - QuotaInGB int - EnabledProtocol ShareProtocol - AccessTier *AccessTier -} - -// GetProperties returns the properties about the specified Storage Share -func (client Client) GetProperties(ctx context.Context, accountName, shareName string) (result GetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetProperties", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "GetProperties", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetProperties", "`shareName` must be a lower-cased string.") - } - - req, err := client.GetPropertiesPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.GetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetProperties", resp, "Failure sending request") - return - } - - result, err = client.GetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetProperties", resp, "Failure responding to request") - return - } - - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResult, err error) { - if resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - - quotaRaw := resp.Header.Get("x-ms-share-quota") - if quotaRaw != "" { - quota, e := strconv.Atoi(quotaRaw) - if e != nil { - return result, fmt.Errorf("Error converting %q to an integer: %s", quotaRaw, err) - } - result.QuotaInGB = quota - } - - protocol := SMB - if protocolRaw := resp.Header.Get("x-ms-enabled-protocols"); protocolRaw != "" { - protocol = ShareProtocol(protocolRaw) - } - - if accessTierRaw := resp.Header.Get("x-ms-access-tier"); accessTierRaw != "" { - tier := AccessTier(accessTierRaw) - result.AccessTier = &tier - } - result.EnabledProtocol = protocol - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_set.go deleted file mode 100644 index 70953c73e102..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_set.go +++ /dev/null @@ -1,106 +0,0 @@ -package shares - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type ShareProperties struct { - QuotaInGb *int - AccessTier *AccessTier -} - -// SetProperties lets you update the Quota for the specified Storage Share -func (client Client) SetProperties(ctx context.Context, accountName, shareName string, properties ShareProperties) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "SetProperties", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "SetProperties", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "SetProperties", "`shareName` must be a lower-cased string.") - } - if newQuotaGB := properties.QuotaInGb; newQuotaGB != nil && (*newQuotaGB <= 0 || *newQuotaGB > 102400) { - return result, validation.NewError("shares.Client", "SetProperties", "`newQuotaGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") - } - - req, err := client.SetPropertiesPreparer(ctx, accountName, shareName, properties) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetProperties", nil, "Failure preparing request") - return - } - - resp, err := client.SetPropertiesSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "SetProperties", resp, "Failure sending request") - return - } - - result, err = client.SetPropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetProperties", resp, "Failure responding to request") - return - } - - return -} - -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName, shareName string, properties ShareProperties) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "properties"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - if properties.QuotaInGb != nil { - headers["x-ms-share-quota"] = *properties.QuotaInGb - } - - if properties.AccessTier != nil { - headers["x-ms-access-tier"] = string(*properties.AccessTier) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/resource_id.go deleted file mode 100644 index c51d399ca062..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/resource_id.go +++ /dev/null @@ -1,53 +0,0 @@ -package shares - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given File Share -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName string) string { - domain := endpoints.GetFileEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, shareName) -} - -// GetResourceManagerResourceID returns the Resource Manager specific -// ResourceID for a specific Storage Share -func (client Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, shareName string) string { - fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/fileServices/default/shares/%s" - return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, shareName) -} - -type ResourceID struct { - AccountName string - ShareName string -} - -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with the Storage Shares SDK -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.file.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - shareName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, - ShareName: shareName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_create.go deleted file mode 100644 index 0ded38b1975a..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_create.go +++ /dev/null @@ -1,115 +0,0 @@ -package shares - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type CreateSnapshotInput struct { - MetaData map[string]string -} - -type CreateSnapshotResult struct { - autorest.Response - - // This header is a DateTime value that uniquely identifies the share snapshot. - // The value of this header may be used in subsequent requests to access the share snapshot. - // This value is opaque. - SnapshotDateTime string -} - -// CreateSnapshot creates a read-only snapshot of the share -// A share can support creation of 200 share snapshots. Attempting to create more than 200 share snapshots fails with 409 (Conflict). -// Attempting to create a share snapshot while a previous Snapshot Share operation is in progress fails with 409 (Conflict). -func (client Client) CreateSnapshot(ctx context.Context, accountName, shareName string, input CreateSnapshotInput) (result CreateSnapshotResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "CreateSnapshot", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "CreateSnapshot", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "CreateSnapshot", "`shareName` must be a lower-cased string.") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("shares.Client", "CreateSnapshot", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) - } - - req, err := client.CreateSnapshotPreparer(ctx, accountName, shareName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "CreateSnapshot", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSnapshotSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "CreateSnapshot", resp, "Failure sending request") - return - } - - result, err = client.CreateSnapshotResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "CreateSnapshot", resp, "Failure responding to request") - return - } - - return -} - -// CreateSnapshotPreparer prepares the CreateSnapshot request. -func (client Client) CreateSnapshotPreparer(ctx context.Context, accountName, shareName string, input CreateSnapshotInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "snapshot"), - "restype": autorest.Encode("query", "share"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSnapshotSender sends the CreateSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateSnapshotResponder handles the response to the CreateSnapshot request. The method always -// closes the http.Response Body. -func (client Client) CreateSnapshotResponder(resp *http.Response) (result CreateSnapshotResult, err error) { - result.SnapshotDateTime = resp.Header.Get("x-ms-snapshot") - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_delete.go deleted file mode 100644 index 1f5d665cb104..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_delete.go +++ /dev/null @@ -1,94 +0,0 @@ -package shares - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// DeleteSnapshot deletes the specified Snapshot of a Storage Share -func (client Client) DeleteSnapshot(ctx context.Context, accountName, shareName string, shareSnapshot string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`shareName` must be a lower-cased string.") - } - if shareSnapshot == "" { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`shareSnapshot` cannot be an empty string.") - } - - req, err := client.DeleteSnapshotPreparer(ctx, accountName, shareName, shareSnapshot) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "DeleteSnapshot", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSnapshotSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "DeleteSnapshot", resp, "Failure sending request") - return - } - - result, err = client.DeleteSnapshotResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "DeleteSnapshot", resp, "Failure responding to request") - return - } - - return -} - -// DeleteSnapshotPreparer prepares the DeleteSnapshot request. -func (client Client) DeleteSnapshotPreparer(ctx context.Context, accountName, shareName string, shareSnapshot string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "share"), - "sharesnapshot": autorest.Encode("query", shareSnapshot), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSnapshotSender sends the DeleteSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteSnapshotResponder handles the response to the DeleteSnapshot request. The method always -// closes the http.Response Body. -func (client Client) DeleteSnapshotResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_get.go deleted file mode 100644 index 2cf5f16f618e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_get.go +++ /dev/null @@ -1,105 +0,0 @@ -package shares - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetSnapshotPropertiesResult struct { - autorest.Response - - MetaData map[string]string -} - -// GetSnapshot gets information about the specified Snapshot of the specified Storage Share -func (client Client) GetSnapshot(ctx context.Context, accountName, shareName, snapshotShare string) (result GetSnapshotPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetSnapshot", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "GetSnapshot", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetSnapshot", "`shareName` must be a lower-cased string.") - } - if snapshotShare == "" { - return result, validation.NewError("shares.Client", "GetSnapshot", "`snapshotShare` cannot be an empty string.") - } - - req, err := client.GetSnapshotPreparer(ctx, accountName, shareName, snapshotShare) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetSnapshot", nil, "Failure preparing request") - return - } - - resp, err := client.GetSnapshotSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetSnapshot", resp, "Failure sending request") - return - } - - result, err = client.GetSnapshotResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetSnapshot", resp, "Failure responding to request") - return - } - - return -} - -// GetSnapshotPreparer prepares the GetSnapshot request. -func (client Client) GetSnapshotPreparer(ctx context.Context, accountName, shareName, snapshotShare string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "snapshot": autorest.Encode("query", snapshotShare), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSnapshotSender sends the GetSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetSnapshotResponder handles the response to the GetSnapshot request. The method always -// closes the http.Response Body. -func (client Client) GetSnapshotResponder(resp *http.Response) (result GetSnapshotPropertiesResult, err error) { - if resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/stats.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/stats.go deleted file mode 100644 index 3539eccbcd0e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/stats.go +++ /dev/null @@ -1,100 +0,0 @@ -package shares - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetStatsResult struct { - autorest.Response - - // The approximate size of the data stored on the share. - // Note that this value may not include all recently created or recently resized files. - ShareUsageBytes int64 `xml:"ShareUsageBytes"` -} - -// GetStats returns information about the specified Storage Share -func (client Client) GetStats(ctx context.Context, accountName, shareName string) (result GetStatsResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetStats", "`accountName` cannot be an empty string.") - } - if shareName == "" { - return result, validation.NewError("shares.Client", "GetStats", "`shareName` cannot be an empty string.") - } - if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetStats", "`shareName` must be a lower-cased string.") - } - - req, err := client.GetStatsPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetStats", nil, "Failure preparing request") - return - } - - resp, err := client.GetStatsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetStats", resp, "Failure sending request") - return - } - - result, err = client.GetStatsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetStats", resp, "Failure responding to request") - return - } - - return -} - -// GetStatsPreparer prepares the GetStats request. -func (client Client) GetStatsPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "stats"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetStatsSender sends the GetStats request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetStatsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetStatsResponder handles the response to the GetStats request. The method always -// closes the http.Response Body. -func (client Client) GetStatsResponder(resp *http.Response) (result GetStatsResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/version.go deleted file mode 100644 index 653693959b6f..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package shares - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/README.md deleted file mode 100644 index b8b84a3799a8..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/README.md +++ /dev/null @@ -1,43 +0,0 @@ -## Queue Storage Queues SDK for API version 2020-08-04 - -This package allows you to interact with the Queues Queue Storage API - -### Supported Authorizers - -* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) -* SharedKeyLite (Blob, File & Queue) - -### Example Usage - -```go -package main - -import ( - "context" - "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" -) - -func Example() error { - accountName := "storageaccount1" - storageAccountKey := "ABC123...." - queueName := "myqueue" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - queuesClient := queues.New() - queuesClient.Client.Authorizer = storageAuth - - ctx := context.TODO() - metadata := map[string]string{ - "hello": "world", - } - if _, err := queuesClient.Create(ctx, accountName, queueName, metadata); err != nil { - return fmt.Errorf("Error creating Queue: %s", err) - } - - return nil -} -``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/api.go deleted file mode 100644 index e4c14220b68c..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/api.go +++ /dev/null @@ -1,17 +0,0 @@ -package queues - -import ( - "context" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageQueue interface { - Delete(ctx context.Context, accountName, queueName string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, queueName string) (result GetMetaDataResult, err error) - SetMetaData(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) - Create(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) - GetResourceID(accountName, queueName string) string - SetServiceProperties(ctx context.Context, accountName string, properties StorageServiceProperties) (result autorest.Response, err error) - GetServiceProperties(ctx context.Context, accountName string) (result StorageServicePropertiesResponse, err error) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/client.go deleted file mode 100644 index 2f8008582b93..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package queues - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Queue Storage Shares. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/create.go deleted file mode 100644 index f18910a88d9e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/create.go +++ /dev/null @@ -1,92 +0,0 @@ -package queues - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -// Create creates the specified Queue within the specified Storage Account -func (client Client) Create(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "Create", "`accountName` cannot be an empty string.") - } - if queueName == "" { - return result, validation.NewError("queues.Client", "Create", "`queueName` cannot be an empty string.") - } - if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "Create", "`queueName` must be a lower-cased string.") - } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("queues.Client", "Create", fmt.Sprintf("`metadata` is not valid: %s.", err)) - } - - req, err := client.CreatePreparer(ctx, accountName, queueName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, queueName string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/delete.go deleted file mode 100644 index 5f705959c446..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/delete.go +++ /dev/null @@ -1,85 +0,0 @@ -package queues - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete deletes the specified Queue within the specified Storage Account -func (client Client) Delete(ctx context.Context, accountName, queueName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "Delete", "`accountName` cannot be an empty string.") - } - if queueName == "" { - return result, validation.NewError("queues.Client", "Delete", "`queueName` cannot be an empty string.") - } - if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "Delete", "`queueName` must be a lower-cased string.") - } - - req, err := client.DeletePreparer(ctx, accountName, queueName) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, queueName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_get.go deleted file mode 100644 index 9c230b613ad3..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_get.go +++ /dev/null @@ -1,101 +0,0 @@ -package queues - -import ( - "context" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -type GetMetaDataResult struct { - autorest.Response - - MetaData map[string]string -} - -// GetMetaData returns the metadata for this Queue -func (client Client) GetMetaData(ctx context.Context, accountName, queueName string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } - if queueName == "" { - return result, validation.NewError("queues.Client", "GetMetaData", "`queueName` cannot be an empty string.") - } - if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "GetMetaData", "`queueName` must be a lower-cased string.") - } - - req, err := client.GetMetaDataPreparer(ctx, accountName, queueName) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.GetMetaDataSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "GetMetaData", resp, "Failure sending request") - return - } - - result, err = client.GetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, queueName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_set.go deleted file mode 100644 index 51154a5c4334..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_set.go +++ /dev/null @@ -1,97 +0,0 @@ -package queues - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" - "github.com/tombuildsstuff/giovanni/storage/internal/metadata" -) - -// SetMetaData returns the metadata for this Queue -func (client Client) SetMetaData(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } - if queueName == "" { - return result, validation.NewError("queues.Client", "SetMetaData", "`queueName` cannot be an empty string.") - } - if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "SetMetaData", "`queueName` must be a lower-cased string.") - } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("queues.Client", "SetMetaData", fmt.Sprintf("`metadata` is not valid: %s.", err)) - } - - req, err := client.SetMetaDataPreparer(ctx, accountName, queueName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetMetaData", nil, "Failure preparing request") - return - } - - resp, err := client.SetMetaDataSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "SetMetaData", resp, "Failure sending request") - return - } - - result, err = client.SetMetaDataResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetMetaData", resp, "Failure responding to request") - return - } - - return -} - -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, queueName string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_get.go deleted file mode 100644 index a0e51ad34354..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_get.go +++ /dev/null @@ -1,86 +0,0 @@ -package queues - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type StorageServicePropertiesResponse struct { - StorageServiceProperties - autorest.Response -} - -// SetServiceProperties gets the properties for this queue -func (client Client) GetServiceProperties(ctx context.Context, accountName string) (result StorageServicePropertiesResponse, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "GetServiceProperties", "`accountName` cannot be an empty string.") - } - - req, err := client.GetServicePropertiesPreparer(ctx, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetServiceProperties", nil, "Failure preparing request") - return - } - - resp, err := client.GetServicePropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "GetServiceProperties", resp, "Failure sending request") - return - } - - result, err = client.GetServicePropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetServiceProperties", resp, "Failure responding to request") - return - } - - return -} - -// GetServicePropertiesPreparer prepares the GetServiceProperties request. -func (client Client) GetServicePropertiesPreparer(ctx context.Context, accountName string) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "properties"), - "restype": autorest.Encode("path", "service"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/"), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetServicePropertiesSender sends the GetServiceProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetServicePropertiesResponder handles the response to the GetServiceProperties request. The method always -// closes the http.Response Body. -func (client Client) GetServicePropertiesResponder(resp *http.Response) (result StorageServicePropertiesResponse, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_set.go deleted file mode 100644 index 33dd40b3da1f..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_set.go +++ /dev/null @@ -1,81 +0,0 @@ -package queues - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// SetServiceProperties sets the properties for this queue -func (client Client) SetServiceProperties(ctx context.Context, accountName string, properties StorageServiceProperties) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "SetServiceProperties", "`accountName` cannot be an empty string.") - } - - req, err := client.SetServicePropertiesPreparer(ctx, accountName, properties) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetServiceProperties", nil, "Failure preparing request") - return - } - - resp, err := client.SetServicePropertiesSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "SetServiceProperties", resp, "Failure sending request") - return - } - - result, err = client.SetServicePropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetServiceProperties", resp, "Failure responding to request") - return - } - - return -} - -// SetServicePropertiesPreparer prepares the SetServiceProperties request. -func (client Client) SetServicePropertiesPreparer(ctx context.Context, accountName string, properties StorageServiceProperties) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "properties"), - "restype": autorest.Encode("path", "service"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/"), - autorest.WithQueryParameters(queryParameters), - autorest.WithXML(properties), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetServicePropertiesSender sends the SetServiceProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetServicePropertiesResponder handles the response to the SetServiceProperties request. The method always -// closes the http.Response Body. -func (client Client) SetServicePropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/resource_id.go deleted file mode 100644 index 912923abca0d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/resource_id.go +++ /dev/null @@ -1,46 +0,0 @@ -package queues - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Queue -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, queueName string) string { - domain := endpoints.GetQueueEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, queueName) -} - -type ResourceID struct { - AccountName string - QueueName string -} - -// ParseResourceID parses the Resource ID and returns an Object which -// can be used to interact with a Queue within a Storage Account -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.queue.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - queueName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, - QueueName: queueName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/version.go deleted file mode 100644 index 9d3e68949fec..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package queues - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/README.md deleted file mode 100644 index e59b5a28335a..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/README.md +++ /dev/null @@ -1,48 +0,0 @@ -## Table Storage Entities SDK for API version 2020-08-04 - -This package allows you to interact with the Entities Table Storage API - -### Supported Authorizers - -* SharedKeyLite (Table) - -### Example Usage - -```go -package main - -import ( - "context" - "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities" -) - -func Example() error { - accountName := "storageaccount1" - storageAccountKey := "ABC123...." - tableName := "mytable" - - storageAuth := autorest.NewSharedKeyLiteTableAuthorizer(accountName, storageAccountKey) - entitiesClient := entities.New() - entitiesClient.Client.Authorizer = storageAuth - - ctx := context.TODO() - input := entities.InsertEntityInput{ - PartitionKey: "abc", - RowKey: "123", - MetaDataLevel: entities.NoMetaData, - Entity: map[string]interface{}{ - "title": "Don't Kill My Vibe", - "artist": "Sigrid", - }, - } - if _, err := entitiesClient.Insert(ctx, accountName, tableName, input); err != nil { - return fmt.Errorf("Error creating Entity: %s", err) - } - - return nil -} -``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/api.go deleted file mode 100644 index d4d20a723457..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/api.go +++ /dev/null @@ -1,17 +0,0 @@ -package entities - -import ( - "context" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageTableEntity interface { - Delete(ctx context.Context, accountName, tableName string, input DeleteEntityInput) (result autorest.Response, err error) - Insert(ctx context.Context, accountName, tableName string, input InsertEntityInput) (result autorest.Response, err error) - InsertOrReplace(ctx context.Context, accountName, tableName string, input InsertOrReplaceEntityInput) (result autorest.Response, err error) - InsertOrMerge(ctx context.Context, accountName, tableName string, input InsertOrMergeEntityInput) (result autorest.Response, err error) - Query(ctx context.Context, accountName, tableName string, input QueryEntitiesInput) (result QueryEntitiesResult, err error) - Get(ctx context.Context, accountName, tableName string, input GetEntityInput) (result GetEntityResult, err error) - GetResourceID(accountName, tableName, partitionKey, rowKey string) string -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/client.go deleted file mode 100644 index 17e9d759fb9e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package entities - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Table Storage Shares. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/delete.go deleted file mode 100644 index 83e9188e5e9e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/delete.go +++ /dev/null @@ -1,99 +0,0 @@ -package entities - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type DeleteEntityInput struct { - // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. - // Together, these properties form the primary key and must be unique within the table. - // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. - // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, - // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. - RowKey string - PartitionKey string -} - -// Delete deletes an existing entity in a table. -func (client Client) Delete(ctx context.Context, accountName, tableName string, input DeleteEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Delete", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("entities.Client", "Delete", "`tableName` cannot be an empty string.") - } - if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "Delete", "`input.PartitionKey` cannot be an empty string.") - } - if input.RowKey == "" { - return result, validation.NewError("entities.Client", "Delete", "`input.RowKey` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, tableName string, input DeleteEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } - - headers := map[string]interface{}{ - // TODO: support for eTags - "If-Match": "*", - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}', RowKey='{rowKey}')", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/get.go deleted file mode 100644 index bdb40180b54d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/get.go +++ /dev/null @@ -1,108 +0,0 @@ -package entities - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetEntityInput struct { - PartitionKey string - RowKey string - - // The Level of MetaData which should be returned - MetaDataLevel MetaDataLevel -} - -type GetEntityResult struct { - autorest.Response - - Entity map[string]interface{} -} - -// Get queries entities in a table and includes the $filter and $select options. -func (client Client) Get(ctx context.Context, accountName, tableName string, input GetEntityInput) (result GetEntityResult, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Get", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("entities.Client", "Get", "`tableName` cannot be an empty string.") - } - if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "Get", "`input.PartitionKey` cannot be an empty string.") - } - if input.RowKey == "" { - return result, validation.NewError("entities.Client", "Get", "`input.RowKey` cannot be an empty string.") - } - - req, err := client.GetPreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client Client) GetPreparer(ctx context.Context, accountName, tableName string, input GetEntityInput) (*http.Request, error) { - - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", input.MetaDataLevel), - "DataServiceVersion": "3.0;NetFx", - "MaxDataServiceVersion": "3.0;NetFx", - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}',RowKey='{rowKey}')", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client Client) GetResponder(resp *http.Response) (result GetEntityResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Entity), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert.go deleted file mode 100644 index 92b05cef5499..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert.go +++ /dev/null @@ -1,112 +0,0 @@ -package entities - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type InsertEntityInput struct { - // The level of MetaData provided for this Entity - MetaDataLevel MetaDataLevel - - // The Entity which should be inserted, by default all values are strings - // To explicitly type a property, specify the appropriate OData data type by setting - // the m:type attribute within the property definition - Entity map[string]interface{} - - // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. - // Together, these properties form the primary key and must be unique within the table. - // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. - // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, - // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. - RowKey string - PartitionKey string -} - -// Insert inserts a new entity into a table. -func (client Client) Insert(ctx context.Context, accountName, tableName string, input InsertEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Insert", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("entities.Client", "Insert", "`tableName` cannot be an empty string.") - } - if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "Insert", "`input.PartitionKey` cannot be an empty string.") - } - if input.RowKey == "" { - return result, validation.NewError("entities.Client", "Insert", "`input.RowKey` cannot be an empty string.") - } - - req, err := client.InsertPreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Insert", nil, "Failure preparing request") - return - } - - resp, err := client.InsertSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Insert", resp, "Failure sending request") - return - } - - result, err = client.InsertResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Insert", resp, "Failure responding to request") - return - } - - return -} - -// InsertPreparer prepares the Insert request. -func (client Client) InsertPreparer(ctx context.Context, accountName, tableName string, input InsertEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", input.MetaDataLevel), - "Prefer": "return-no-content", - } - - input.Entity["PartitionKey"] = input.PartitionKey - input.Entity["RowKey"] = input.RowKey - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsPost(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}", pathParameters), - autorest.WithJSON(input.Entity), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// InsertSender sends the Insert request. The method will close the -// http.Response Body if it receives an error. -func (client Client) InsertSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// InsertResponder handles the response to the Insert request. The method always -// closes the http.Response Body. -func (client Client) InsertResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_merge.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_merge.go deleted file mode 100644 index 1fb4ed3df164..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_merge.go +++ /dev/null @@ -1,108 +0,0 @@ -package entities - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type InsertOrMergeEntityInput struct { - // The Entity which should be inserted, by default all values are strings - // To explicitly type a property, specify the appropriate OData data type by setting - // the m:type attribute within the property definition - Entity map[string]interface{} - - // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. - // Together, these properties form the primary key and must be unique within the table. - // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. - // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, - // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. - RowKey string - PartitionKey string -} - -// InsertOrMerge updates an existing entity or inserts a new entity if it does not exist in the table. -// Because this operation can insert or update an entity, it is also known as an upsert operation. -func (client Client) InsertOrMerge(ctx context.Context, accountName, tableName string, input InsertOrMergeEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`tableName` cannot be an empty string.") - } - if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`input.PartitionKey` cannot be an empty string.") - } - if input.RowKey == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`input.RowKey` cannot be an empty string.") - } - - req, err := client.InsertOrMergePreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrMerge", nil, "Failure preparing request") - return - } - - resp, err := client.InsertOrMergeSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrMerge", resp, "Failure sending request") - return - } - - result, err = client.InsertOrMergeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrMerge", resp, "Failure responding to request") - return - } - - return -} - -// InsertOrMergePreparer prepares the InsertOrMerge request. -func (client Client) InsertOrMergePreparer(ctx context.Context, accountName, tableName string, input InsertOrMergeEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": "application/json", - "Prefer": "return-no-content", - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsMerge(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}', RowKey='{rowKey}')", pathParameters), - autorest.WithJSON(input.Entity), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// InsertOrMergeSender sends the InsertOrMerge request. The method will close the -// http.Response Body if it receives an error. -func (client Client) InsertOrMergeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// InsertOrMergeResponder handles the response to the InsertOrMerge request. The method always -// closes the http.Response Body. -func (client Client) InsertOrMergeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_replace.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_replace.go deleted file mode 100644 index 036ba5de5fe7..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_replace.go +++ /dev/null @@ -1,108 +0,0 @@ -package entities - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type InsertOrReplaceEntityInput struct { - // The Entity which should be inserted, by default all values are strings - // To explicitly type a property, specify the appropriate OData data type by setting - // the m:type attribute within the property definition - Entity map[string]interface{} - - // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. - // Together, these properties form the primary key and must be unique within the table. - // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. - // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, - // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. - RowKey string - PartitionKey string -} - -// InsertOrReplace replaces an existing entity or inserts a new entity if it does not exist in the table. -// Because this operation can insert or update an entity, it is also known as an upsert operation. -func (client Client) InsertOrReplace(ctx context.Context, accountName, tableName string, input InsertOrReplaceEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`tableName` cannot be an empty string.") - } - if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`input.PartitionKey` cannot be an empty string.") - } - if input.RowKey == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`input.RowKey` cannot be an empty string.") - } - - req, err := client.InsertOrReplacePreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrReplace", nil, "Failure preparing request") - return - } - - resp, err := client.InsertOrReplaceSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrReplace", resp, "Failure sending request") - return - } - - result, err = client.InsertOrReplaceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrReplace", resp, "Failure responding to request") - return - } - - return -} - -// InsertOrReplacePreparer prepares the InsertOrReplace request. -func (client Client) InsertOrReplacePreparer(ctx context.Context, accountName, tableName string, input InsertOrReplaceEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": "application/json", - "Prefer": "return-no-content", - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsMerge(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}', RowKey='{rowKey}')", pathParameters), - autorest.WithJSON(input.Entity), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// InsertOrReplaceSender sends the InsertOrReplace request. The method will close the -// http.Response Body if it receives an error. -func (client Client) InsertOrReplaceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// InsertOrReplaceResponder handles the response to the InsertOrReplace request. The method always -// closes the http.Response Body. -func (client Client) InsertOrReplaceResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/query.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/query.go deleted file mode 100644 index c1ba3706be7d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/query.go +++ /dev/null @@ -1,162 +0,0 @@ -package entities - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type QueryEntitiesInput struct { - // An optional OData filter - Filter *string - - // An optional comma-separated - PropertyNamesToSelect *[]string - - // An optional OData top - Top *int - - PartitionKey string - RowKey string - - // The Level of MetaData which should be returned - MetaDataLevel MetaDataLevel - - // The Next Partition Key used to load data from a previous point - NextPartitionKey *string - - // The Next Row Key used to load data from a previous point - NextRowKey *string -} - -type QueryEntitiesResult struct { - autorest.Response - - NextPartitionKey string - NextRowKey string - - MetaData string `json:"odata.metadata,omitempty"` - Entities []map[string]interface{} `json:"value"` -} - -// Query queries entities in a table and includes the $filter and $select options. -func (client Client) Query(ctx context.Context, accountName, tableName string, input QueryEntitiesInput) (result QueryEntitiesResult, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Query", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("entities.Client", "Query", "`tableName` cannot be an empty string.") - } - - req, err := client.QueryPreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Query", nil, "Failure preparing request") - return - } - - resp, err := client.QuerySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Query", resp, "Failure sending request") - return - } - - result, err = client.QueryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Query", resp, "Failure responding to request") - return - } - - return -} - -// QueryPreparer prepares the Query request. -func (client Client) QueryPreparer(ctx context.Context, accountName, tableName string, input QueryEntitiesInput) (*http.Request, error) { - - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "additionalParameters": "", - } - - //PartitionKey='',RowKey='' - additionalParams := make([]string, 0) - if input.PartitionKey != "" { - additionalParams = append(additionalParams, fmt.Sprintf("PartitionKey='%s'", input.PartitionKey)) - } - if input.RowKey != "" { - additionalParams = append(additionalParams, fmt.Sprintf("RowKey='%s'", input.RowKey)) - } - if len(additionalParams) > 0 { - pathParameters["additionalParameters"] = autorest.Encode("path", strings.Join(additionalParams, ",")) - } - - queryParameters := map[string]interface{}{} - - if input.Filter != nil { - queryParameters["$filter"] = autorest.Encode("query", *input.Filter) - } - - if input.PropertyNamesToSelect != nil { - queryParameters["$select"] = autorest.Encode("query", strings.Join(*input.PropertyNamesToSelect, ",")) - } - - if input.Top != nil { - queryParameters["$top"] = autorest.Encode("query", *input.Top) - } - - if input.NextPartitionKey != nil { - queryParameters["NextPartitionKey"] = *input.NextPartitionKey - } - - if input.NextRowKey != nil { - queryParameters["NextRowKey"] = *input.NextRowKey - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", input.MetaDataLevel), - "DataServiceVersion": "3.0;NetFx", - "MaxDataServiceVersion": "3.0;NetFx", - } - - // GET /myaccount/Customers()?$filter=(Rating%20ge%203)%20and%20(Rating%20le%206)&$select=PartitionKey,RowKey,Address,CustomerSince - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}({additionalParameters})", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// QuerySender sends the Query request. The method will close the -// http.Response Body if it receives an error. -func (client Client) QuerySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// QueryResponder handles the response to the Query request. The method always -// closes the http.Response Body. -func (client Client) QueryResponder(resp *http.Response) (result QueryEntitiesResult, err error) { - if resp != nil && resp.Header != nil { - result.NextPartitionKey = resp.Header.Get("x-ms-continuation-NextPartitionKey") - result.NextRowKey = resp.Header.Get("x-ms-continuation-NextRowKey") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/resource_id.go deleted file mode 100644 index 249671dc91bf..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/resource_id.go +++ /dev/null @@ -1,91 +0,0 @@ -package entities - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Entity -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, tableName, partitionKey, rowKey string) string { - domain := endpoints.GetTableEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s(PartitionKey='%s',RowKey='%s')", domain, tableName, partitionKey, rowKey) -} - -type ResourceID struct { - AccountName string - TableName string - PartitionKey string - RowKey string -} - -// ParseResourceID parses the specified Resource ID and returns an object which -// can be used to look up the specified Entity within the specified Table -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://account1.table.core.chinacloudapi.cn/table1(PartitionKey='partition1',RowKey='row1') - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - // assume there a `Table('')` - path := strings.TrimPrefix(uri.Path, "/") - if !strings.Contains(uri.Path, "(") || !strings.HasSuffix(uri.Path, ")") { - return nil, fmt.Errorf("Expected the Table Name to be in the format `tables(PartitionKey='',RowKey='')` but got %q", path) - } - - // NOTE: honestly this could probably be a RegEx, but this seemed like the simplest way to - // allow these two fields to be specified in either order - indexOfBracket := strings.IndexByte(path, '(') - tableName := path[0:indexOfBracket] - - // trim off the brackets - temp := strings.TrimPrefix(path, fmt.Sprintf("%s(", tableName)) - temp = strings.TrimSuffix(temp, ")") - - dictionary := strings.Split(temp, ",") - partitionKey := "" - rowKey := "" - for _, v := range dictionary { - split := strings.Split(v, "=") - if len(split) != 2 { - return nil, fmt.Errorf("Expected 2 segments but got %d for %q", len(split), v) - } - - key := split[0] - value := strings.TrimSuffix(strings.TrimPrefix(split[1], "'"), "'") - if strings.EqualFold(key, "PartitionKey") { - partitionKey = value - } else if strings.EqualFold(key, "RowKey") { - rowKey = value - } else { - return nil, fmt.Errorf("Unexpected Key %q", key) - } - } - - if partitionKey == "" { - return nil, fmt.Errorf("Expected a PartitionKey but didn't get one") - } - if rowKey == "" { - return nil, fmt.Errorf("Expected a RowKey but didn't get one") - } - - return &ResourceID{ - AccountName: *accountName, - TableName: tableName, - PartitionKey: partitionKey, - RowKey: rowKey, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/version.go deleted file mode 100644 index 6270953c7923..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package entities - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/README.md deleted file mode 100644 index 40ec34959a79..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/README.md +++ /dev/null @@ -1,39 +0,0 @@ -## Table Storage Tables SDK for API version 2020-08-04 - -This package allows you to interact with the Tables Table Storage API - -### Supported Authorizers - -* SharedKeyLite (Table) - -### Example Usage - -```go -package main - -import ( - "context" - "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" -) - -func Example() error { - accountName := "storageaccount1" - storageAccountKey := "ABC123...." - tableName := "mytable" - - storageAuth := autorest.NewSharedKeyLiteTableAuthorizer(accountName, storageAccountKey) - tablesClient := tables.New() - tablesClient.Client.Authorizer = storageAuth - - ctx := context.TODO() - if _, err := tablesClient.Insert(ctx, accountName, tableName); err != nil { - return fmt.Errorf("Error creating Table: %s", err) - } - - return nil -} -``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_get.go deleted file mode 100644 index 0ef00006530f..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_get.go +++ /dev/null @@ -1,93 +0,0 @@ -package tables - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetACLResult struct { - autorest.Response - - SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` -} - -// GetACL returns the Access Control List for the specified Table -func (client Client) GetACL(ctx context.Context, accountName, tableName string) (result GetACLResult, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "GetACL", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("tables.Client", "GetACL", "`tableName` cannot be an empty string.") - } - - req, err := client.GetACLPreparer(ctx, accountName, tableName) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "GetACL", nil, "Failure preparing request") - return - } - - resp, err := client.GetACLSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "GetACL", resp, "Failure sending request") - return - } - - result, err = client.GetACLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "GetACL", resp, "Failure responding to request") - return - } - - return -} - -// GetACLPreparer prepares the GetACL request. -func (client Client) GetACLPreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "acl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetACLSender sends the GetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetACLResponder handles the response to the GetACL request. The method always -// closes the http.Response Body. -func (client Client) GetACLResponder(resp *http.Response) (result GetACLResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_set.go deleted file mode 100644 index c26bffc834d1..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_set.go +++ /dev/null @@ -1,98 +0,0 @@ -package tables - -import ( - "context" - "encoding/xml" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type setAcl struct { - SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` - - XMLName xml.Name `xml:"SignedIdentifiers"` -} - -// SetACL sets the specified Access Control List for the specified Table -func (client Client) SetACL(ctx context.Context, accountName, tableName string, acls []SignedIdentifier) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "SetACL", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("tables.Client", "SetACL", "`tableName` cannot be an empty string.") - } - - req, err := client.SetACLPreparer(ctx, accountName, tableName, acls) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "SetACL", nil, "Failure preparing request") - return - } - - resp, err := client.SetACLSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "SetACL", resp, "Failure sending request") - return - } - - result, err = client.SetACLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "SetACL", resp, "Failure responding to request") - return - } - - return -} - -// SetACLPreparer prepares the SetACL request. -func (client Client) SetACLPreparer(ctx context.Context, accountName, tableName string, acls []SignedIdentifier) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "acl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - input := setAcl{ - SignedIdentifiers: acls, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithXML(&input)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetACLSender sends the SetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// SetACLResponder handles the response to the SetACL request. The method always -// closes the http.Response Body. -func (client Client) SetACLResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/api.go deleted file mode 100644 index d869819ff21e..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/api.go +++ /dev/null @@ -1,17 +0,0 @@ -package tables - -import ( - "context" - - "github.com/Azure/go-autorest/autorest" -) - -type StorageTable interface { - Delete(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) - Exists(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) - GetACL(ctx context.Context, accountName, tableName string) (result GetACLResult, err error) - Create(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) - GetResourceID(accountName, tableName string) string - Query(ctx context.Context, accountName string, metaDataLevel MetaDataLevel) (result GetResult, err error) - SetACL(ctx context.Context, accountName, tableName string, acls []SignedIdentifier) (result autorest.Response, err error) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/client.go deleted file mode 100644 index 56724b9202c9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/client.go +++ /dev/null @@ -1,25 +0,0 @@ -package tables - -import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Client is the base client for Table Storage Shares. -type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, - } -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/create.go deleted file mode 100644 index 561f57460daf..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/create.go +++ /dev/null @@ -1,90 +0,0 @@ -package tables - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type createTableRequest struct { - TableName string `json:"TableName"` -} - -// Create creates a new table in the storage account. -func (client Client) Create(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Create", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("tables.Client", "Create", "`tableName` cannot be an empty string.") - } - - req, err := client.CreatePreparer(ctx, accountName, tableName) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - // NOTE: we could support returning metadata here, but it doesn't appear to be directly useful - // vs making a request using the Get methods as-necessary? - "Accept": "application/json;odata=nometadata", - "Prefer": "return-no-content", - } - - body := createTableRequest{ - TableName: tableName, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsPost(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/Tables"), - autorest.WithJSON(body), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/delete.go deleted file mode 100644 index 5b5ec86d9ca9..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/delete.go +++ /dev/null @@ -1,79 +0,0 @@ -package tables - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Delete deletes the specified table and any data it contains. -func (client Client) Delete(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Delete", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("tables.Client", "Delete", "`tableName` cannot be an empty string.") - } - - req, err := client.DeletePreparer(ctx, accountName, tableName) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - // NOTE: whilst the API documentation says that API Version is Optional - // apparently specifying it causes an "invalid content type" to always be returned - // as such we omit it here :shrug: - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/Tables('{tableName}')", pathParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/exists.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/exists.go deleted file mode 100644 index 6abe4f0bbd42..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/exists.go +++ /dev/null @@ -1,86 +0,0 @@ -package tables - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// Exists checks that the specified table exists -func (client Client) Exists(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Exists", "`accountName` cannot be an empty string.") - } - if tableName == "" { - return result, validation.NewError("tables.Client", "Exists", "`tableName` cannot be an empty string.") - } - - req, err := client.ExistsPreparer(ctx, accountName, tableName) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Exists", nil, "Failure preparing request") - return - } - - resp, err := client.ExistsSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Exists", resp, "Failure sending request") - return - } - - result, err = client.ExistsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Exists", resp, "Failure responding to request") - return - } - - return -} - -// ExistsPreparer prepares the Exists request. -func (client Client) ExistsPreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": "application/json;odata=nometadata", - } - - // NOTE: whilst the API documentation says that API Version is Optional - // apparently specifying it causes an "invalid content type" to always be returned - // as such we omit it here :shrug: - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.AsContentType("application/json"), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/Tables('{tableName}')", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ExistsSender sends the Exists request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ExistsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ExistsResponder handles the response to the Exists request. The method always -// closes the http.Response Body. -func (client Client) ExistsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/query.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/query.go deleted file mode 100644 index 475370f0cbd5..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/query.go +++ /dev/null @@ -1,87 +0,0 @@ -package tables - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -type GetResult struct { - autorest.Response - - MetaData string `json:"odata.metadata,omitempty"` - Tables []GetResultItem `json:"value"` -} - -// Query returns a list of tables under the specified account. -func (client Client) Query(ctx context.Context, accountName string, metaDataLevel MetaDataLevel) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Query", "`accountName` cannot be an empty string.") - } - - req, err := client.QueryPreparer(ctx, accountName, metaDataLevel) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Query", nil, "Failure preparing request") - return - } - - resp, err := client.QuerySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Query", resp, "Failure sending request") - return - } - - result, err = client.QueryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Query", resp, "Failure responding to request") - return - } - - return -} - -// QueryPreparer prepares the Query request. -func (client Client) QueryPreparer(ctx context.Context, accountName string, metaDataLevel MetaDataLevel) (*http.Request, error) { - // NOTE: whilst this supports ContinuationTokens and 'Top' - // it appears that 'Skip' returns a '501 Not Implemented' - // as such, we intentionally don't support those right now - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", metaDataLevel), - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/Tables"), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// QuerySender sends the Query request. The method will close the -// http.Response Body if it receives an error. -func (client Client) QuerySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// QueryResponder handles the response to the Query request. The method always -// closes the http.Response Body. -func (client Client) QueryResponder(resp *http.Response) (result GetResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/resource_id.go deleted file mode 100644 index 4ceae10150e0..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/resource_id.go +++ /dev/null @@ -1,54 +0,0 @@ -package tables - -import ( - "fmt" - "net/url" - "strings" - - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" -) - -// GetResourceID returns the Resource ID for the given Table -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, tableName string) string { - domain := endpoints.GetTableEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/Tables('%s')", domain, tableName) -} - -type ResourceID struct { - AccountName string - TableName string -} - -// ParseResourceID parses the Resource ID and returns an object which -// can be used to interact with the Table within the specified Storage Account -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.table.core.windows.net/Table('foo') - if id == "" { - return nil, fmt.Errorf("`id` was empty") - } - - uri, err := url.Parse(id) - if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) - } - - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) - if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) - } - - // assume there a `Table('')` - path := strings.TrimPrefix(uri.Path, "/") - if !strings.HasPrefix(path, "Tables('") || !strings.HasSuffix(path, "')") { - return nil, fmt.Errorf("Expected the Table Name to be in the format `Tables('name')` but got %q", path) - } - - // strip off the `Table('')` - tableName := strings.TrimPrefix(uri.Path, "/Tables('") - tableName = strings.TrimSuffix(tableName, "')") - return &ResourceID{ - AccountName: *accountName, - TableName: tableName, - }, nil -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/version.go deleted file mode 100644 index 05a61a8a7c9d..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/version.go +++ /dev/null @@ -1,14 +0,0 @@ -package tables - -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/README.md similarity index 87% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/README.md rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/README.md index 5fa24a74e9bb..01fdc3f22ded 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/README.md @@ -1,4 +1,4 @@ -## Blob Storage Account SDK for API version 2020-08-04 +## Blob Storage Account SDK for API version 2023-11-03 This package allows you to interact with the Accounts Blob Storage API @@ -16,8 +16,7 @@ import ( "fmt" "time" - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" ) func Example() error { diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/client.go new file mode 100644 index 000000000000..df5fa1d722ea --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/client.go @@ -0,0 +1,22 @@ +package accounts + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Blob Storage Blobs. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/get_service_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/get_service_properties.go new file mode 100644 index 000000000000..f230f16a83d7 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/get_service_properties.go @@ -0,0 +1,54 @@ +package accounts + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type GetServicePropertiesResult struct { + StorageServiceProperties + HttpResponse *http.Response +} + +func (c Client) GetServiceProperties(ctx context.Context, accountName string) (result GetServicePropertiesResult, err error) { + if accountName == "" { + return result, fmt.Errorf("`accountName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: servicePropertiesOptions{}, + Path: "/", + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/models.go similarity index 97% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/models.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/models.go index 3a2891439bee..c36d45ecb8c5 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/models.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/models.go @@ -1,11 +1,5 @@ package accounts -import "github.com/Azure/go-autorest/autorest" - -type SetServicePropertiesResult struct { - autorest.Response -} - type StorageServiceProperties struct { // Cors - Specifies CORS rules for the Blob service. You can include up to five CorsRule elements in the request. If no CorsRule elements are included in the request body, all CORS rules will be deleted, and CORS will be disabled for the Blob service. Cors *CorsRules `xml:"Cors,omitempty"` diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/resource_id.go new file mode 100644 index 000000000000..e6c6303f9f79 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/resource_id.go @@ -0,0 +1,155 @@ +package accounts + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type SubDomainType string + +const ( + BlobSubDomainType SubDomainType = "blob" + DataLakeStoreSubDomainType SubDomainType = "dfs" + FileSubDomainType SubDomainType = "file" + QueueSubDomainType SubDomainType = "queue" + TableSubDomainType SubDomainType = "table" +) + +func PossibleValuesForSubDomainType() []SubDomainType { + return []SubDomainType{ + BlobSubDomainType, + DataLakeStoreSubDomainType, + FileSubDomainType, + QueueSubDomainType, + TableSubDomainType, + } +} + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = AccountId{} + +type AccountId struct { + AccountName string + ZoneName *string + SubDomainType SubDomainType + DomainSuffix string + IsEdgeZone bool +} + +func (a AccountId) ID() string { + components := []string{ + a.AccountName, + } + if a.IsEdgeZone { + // Storage Accounts hosted in an Edge Zone + // `{accountname}.{component}.{edgezone}.edgestorage.azure.net` + components = append(components, string(a.SubDomainType)) + if a.ZoneName != nil { + components = append(components, *a.ZoneName) + } + } else { + // Storage Accounts using a DNS Zone + // `{accountname}.{dnszone}.{component}.storage.azure.net` + // or a Regular Storage Account + // `{accountname}.{component}.core.windows.net` + if a.ZoneName != nil { + components = append(components, *a.ZoneName) + } + components = append(components, string(a.SubDomainType)) + } + components = append(components, a.DomainSuffix) + return fmt.Sprintf("https://%s", strings.Join(components, ".")) +} + +func (a AccountId) String() string { + components := []string{ + fmt.Sprintf("IsEdgeZone %t", a.IsEdgeZone), + fmt.Sprintf("ZoneName %q", pointer.From(a.ZoneName)), + fmt.Sprintf("Subdomain Type %q", string(a.SubDomainType)), + fmt.Sprintf("DomainSuffix %q", a.DomainSuffix), + } + return fmt.Sprintf("Account %q (%s)", a.AccountName, strings.Join(components, " / ")) +} + +func ParseAccountID(input, domainSuffix string) (*AccountId, error) { + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a URL: %s", input, err) + } + + if !strings.HasSuffix(uri.Host, domainSuffix) { + return nil, fmt.Errorf("expected the account %q to use a domain suffix of %q", uri.Host, domainSuffix) + } + + // There's 3 different types of Storage Account ID: + // 1. Regular ol' Storage Accounts + // `{name}.{component}.core.windows.net` (e.g. `example1.blob.core.windows.net`) + // 2. Storage Accounts using a DNS Zone + // `{accountname}.{dnszone}.{component}.storage.azure.net` + // 3. Storage Accounts hosted in an Edge Zone + // `{accountname}.{component}.{edgezone}.edgestorage.azure.net` + // since both `dnszone` and `edgezone` are the only two identifiers, we need to check if `domainSuffix` includes `edge` + // to know how to treat these + + hostName := strings.TrimSuffix(uri.Host, fmt.Sprintf(".%s", domainSuffix)) + components := strings.Split(hostName, ".") + accountId := AccountId{ + DomainSuffix: domainSuffix, + IsEdgeZone: strings.Contains(strings.ToLower(domainSuffix), "edge"), + } + + if len(components) == 2 { + // this will be a regular Storage Account (e.g. `example1.blob.core.windows.net`) + accountId.AccountName = components[0] + subDomainType, err := parseSubDomainType(components[1]) + if err != nil { + return nil, err + } + accountId.SubDomainType = *subDomainType + return &accountId, nil + } + + if len(components) == 3 { + // This can either be a Zone'd Storage Account or a Storage Account within an Edge Zone + accountName := "" + subDomainTypeRaw := "" + zone := "" + if accountId.IsEdgeZone { + // `{accountname}.{component}.{edgezone}.edgestorage.azure.net` + accountName = components[0] + subDomainTypeRaw = components[1] + zone = components[2] + } else { + // `{accountname}.{dnszone}.{component}.storage.azure.net` + accountName = components[0] + zone = components[1] + subDomainTypeRaw = components[2] + } + + accountId.AccountName = accountName + subDomainType, err := parseSubDomainType(subDomainTypeRaw) + if err != nil { + return nil, err + } + accountId.SubDomainType = *subDomainType + accountId.ZoneName = pointer.To(zone) + return &accountId, nil + } + + return nil, fmt.Errorf("unknown storage account domain type %q", input) +} + +func parseSubDomainType(input string) (*SubDomainType, error) { + for _, k := range PossibleValuesForSubDomainType() { + if strings.EqualFold(input, string(k)) { + return pointer.To(k), nil + } + } + + return nil, fmt.Errorf("expected the subdomain type to be one of [%+v] but got %q", PossibleValuesForSubDomainType(), input) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/service_properties_shared.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/service_properties_shared.go new file mode 100644 index 000000000000..3019155f9183 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/service_properties_shared.go @@ -0,0 +1,26 @@ +package accounts + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = servicePropertiesOptions{} + +type servicePropertiesOptions struct { +} + +func (servicePropertiesOptions) ToHeaders() *client.Headers { + return nil +} + +func (servicePropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (servicePropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "properties") + out.Append("restype", "service") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/set_service_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/set_service_properties.go new file mode 100644 index 000000000000..d881b049fa5c --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/set_service_properties.go @@ -0,0 +1,52 @@ +package accounts + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type SetServicePropertiesResult struct { + HttpResponse *http.Response +} + +func (c Client) SetServiceProperties(ctx context.Context, accountName string, input StorageServiceProperties) (result SetServicePropertiesResult, err error) { + if accountName == "" { + return result, fmt.Errorf("`accountName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: servicePropertiesOptions{}, + Path: "/", + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + if err = req.Marshal(&input); err != nil { + err = fmt.Errorf("marshaling request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/version.go new file mode 100644 index 000000000000..427d66da7364 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts/version.go @@ -0,0 +1,4 @@ +package accounts + +const apiVersion = "2023-11-03" +const componentName = "blob/accounts" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/README.md similarity index 51% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/README.md rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/README.md index 19218cf9fd85..0b26e1cd140f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/README.md @@ -1,4 +1,4 @@ -## Blob Storage Blobs SDK for API version 2020-08-04 +## Blob Storage Blobs SDK for API version 2023-11-03 This package allows you to interact with the Blobs Blob Storage API @@ -17,26 +17,34 @@ import ( "fmt" "time" - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs" ) func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." containerName := "mycontainer" + domainSuffix := "core.windows.net" fileName := "example-large-file.iso" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - blobClient := blobs.New() - blobClient.Client.Authorizer = storageAuth + + blobClient, err := blobs.NewWithBaseUri(fmt.Sprintf("https://%s.blob.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %v", err) + } + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + blobClient.Client.SetAuthorizer(auth) ctx := context.TODO() copyInput := blobs.CopyInput{ CopySource: "http://releases.ubuntu.com/14.04/ubuntu-14.04.6-desktop-amd64.iso", } refreshInterval := 5 * time.Second - if err := blobClient.CopyAndWait(ctx, accountName, containerName, fileName, copyInput, refreshInterval); err != nil { + if err := blobClient.CopyAndWait(ctx, containerName, fileName, copyInput, refreshInterval); err != nil { return fmt.Errorf("Error copying: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/api.go new file mode 100644 index 000000000000..167240825039 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/api.go @@ -0,0 +1,41 @@ +package blobs + +import ( + "context" + "os" +) + +type StorageBlob interface { + AppendBlock(ctx context.Context, containerName string, blobName string, input AppendBlockInput) (AppendBlockResponse, error) + Copy(ctx context.Context, containerName string, blobName string, input CopyInput) (CopyResponse, error) + AbortCopy(ctx context.Context, containerName string, blobName string, input AbortCopyInput) (CopyAbortResponse, error) + CopyAndWait(ctx context.Context, containerName string, blobName string, input CopyInput) error + Delete(ctx context.Context, containerName string, blobName string, input DeleteInput) (DeleteResponse, error) + DeleteSnapshot(ctx context.Context, containerName string, blobName string, input DeleteSnapshotInput) (DeleteSnapshotResponse, error) + DeleteSnapshots(ctx context.Context, containerName string, blobName string, input DeleteSnapshotsInput) (DeleteSnapshotsResponse, error) + Get(ctx context.Context, containerName string, blobName string, input GetInput) (GetResponse, error) + GetBlockList(ctx context.Context, containerName string, blobName string, input GetBlockListInput) (GetBlockListResponse, error) + GetPageRanges(ctx context.Context, containerName, blobName string, input GetPageRangesInput) (GetPageRangesResponse, error) + IncrementalCopyBlob(ctx context.Context, containerName string, blobName string, input IncrementalCopyBlobInput) (IncrementalCopyBlob, error) + AcquireLease(ctx context.Context, containerName string, blobName string, input AcquireLeaseInput) (AcquireLeaseResponse, error) + BreakLease(ctx context.Context, containerName string, blobName string, input BreakLeaseInput) (BreakLeaseResponse, error) + ChangeLease(ctx context.Context, containerName string, blobName string, input ChangeLeaseInput) (ChangeLeaseResponse, error) + ReleaseLease(ctx context.Context, containerName string, blobName string, input ReleaseLeaseInput) (ReleaseLeaseResponse, error) + RenewLease(ctx context.Context, containerName string, blobName string, input RenewLeaseInput) (RenewLeaseResponse, error) + SetMetaData(ctx context.Context, containerName string, blobName string, input SetMetaDataInput) (SetMetaDataResponse, error) + GetProperties(ctx context.Context, containerName string, blobName string, input GetPropertiesInput) (GetPropertiesResponse, error) + SetProperties(ctx context.Context, containerName string, blobName string, input SetPropertiesInput) (SetPropertiesResponse, error) + PutAppendBlob(ctx context.Context, containerName string, blobName string, input PutAppendBlobInput) (PutAppendBlobResponse, error) + PutBlock(ctx context.Context, containerName string, blobName string, input PutBlockInput) (PutBlockResponse, error) + PutBlockBlob(ctx context.Context, containerName string, blobName string, input PutBlockBlobInput) (PutBlockBlobResponse, error) + PutBlockBlobFromFile(ctx context.Context, containerName string, blobName string, file *os.File, input PutBlockBlobInput) error + PutBlockList(ctx context.Context, containerName string, blobName string, input PutBlockListInput) (PutBlockListResponse, error) + PutBlockFromURL(ctx context.Context, containerName string, blobName string, input PutBlockFromURLInput) (PutBlockFromURLResponse, error) + PutPageBlob(ctx context.Context, containerName string, blobName string, input PutPageBlobInput) (PutPageBlobResponse, error) + PutPageClear(ctx context.Context, containerName string, blobName string, input PutPageClearInput) (PutPageClearResponse, error) + PutPageUpdate(ctx context.Context, containerName string, blobName string, input PutPageUpdateInput) (PutPageUpdateResponse, error) + SetTier(ctx context.Context, containerName string, blobName string, input SetTierInput) (SetTierResponse, error) + Snapshot(ctx context.Context, containerName string, blobName string, input SnapshotInput) (SnapshotResponse, error) + GetSnapshotProperties(ctx context.Context, containerName string, blobName string, input GetSnapshotPropertiesInput) (GetPropertiesResponse, error) + Undelete(ctx context.Context, containerName string, blobName string) (UndeleteResponse, error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/append_block.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/append_block.go new file mode 100644 index 000000000000..b82558f937d3 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/append_block.go @@ -0,0 +1,167 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type AppendBlockInput struct { + // A number indicating the byte offset to compare. + // Append Block will succeed only if the append position is equal to this number. + // If it is not, the request will fail with an AppendPositionConditionNotMet + // error (HTTP status code 412 – Precondition Failed) + BlobConditionAppendPosition *int64 + + // The max length in bytes permitted for the append blob. + // If the Append Block operation would cause the blob to exceed that limit or if the blob size + // is already greater than the value specified in this header, the request will fail with + // an MaxBlobSizeConditionNotMet error (HTTP status code 412 – Precondition Failed). + BlobConditionMaxSize *int64 + + // The Bytes which should be appended to the end of this Append Blob. + // This can either be nil, which creates an empty blob, or a byte array + Content *[]byte + + // An MD5 hash of the block content. + // This hash is used to verify the integrity of the block during transport. + // When this header is specified, the storage service compares the hash of the content + // that has arrived with this header value. + // + // Note that this MD5 hash is not stored with the blob. + // If the two hashes do not match, the operation will fail with error code 400 (Bad Request). + ContentMD5 *string + + // Required if the blob has an active lease. + // To perform this operation on a blob with an active lease, specify the valid lease ID for this header. + LeaseID *string + + // The encryption scope to set for the request content. + EncryptionScope *string +} + +type AppendBlockResponse struct { + HttpResponse *http.Response + + BlobAppendOffset string + BlobCommittedBlockCount int64 + ContentMD5 string + ETag string + LastModified string +} + +// AppendBlock commits a new block of data to the end of an existing append blob. +func (c Client) AppendBlock(ctx context.Context, containerName, blobName string, input AppendBlockInput) (result AppendBlockResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.Content != nil && len(*input.Content) > (4*1024*1024) { + err = fmt.Errorf("`input.Content` must be at most 4MB") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: appendBlockOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + err = req.Marshal(input.Content) + if err != nil { + err = fmt.Errorf("marshalling request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.BlobAppendOffset = resp.Header.Get("x-ms-blob-append-offset") + result.ContentMD5 = resp.Header.Get("Content-MD5") + result.ETag = resp.Header.Get("ETag") + result.LastModified = resp.Header.Get("Last-Modified") + + if v := resp.Header.Get("x-ms-blob-committed-block-count"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-blob-committed-block-count` header value %q: %+v", v, innerErr) + return + } + result.BlobCommittedBlockCount = int64(i) + } + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type appendBlockOptions struct { + input AppendBlockInput +} + +func (a appendBlockOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if a.input.BlobConditionAppendPosition != nil { + headers.Append("x-ms-blob-condition-appendpos", strconv.Itoa(int(*a.input.BlobConditionAppendPosition))) + } + if a.input.BlobConditionMaxSize != nil { + headers.Append("x-ms-blob-condition-maxsize", strconv.Itoa(int(*a.input.BlobConditionMaxSize))) + } + if a.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *a.input.ContentMD5) + } + if a.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *a.input.LeaseID) + } + if a.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *a.input.EncryptionScope) + } + if a.input.Content != nil { + headers.Append("Content-Length", strconv.Itoa(len(*a.input.Content))) + } + return headers +} + +func (a appendBlockOptions) ToOData() *odata.Query { + return nil +} + +func (a appendBlockOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "appendblock") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/client.go new file mode 100644 index 000000000000..4bb762b5d18c --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/client.go @@ -0,0 +1,22 @@ +package blobs + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Blob Storage Blobs. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy.go similarity index 57% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy.go index febaab5f9a91..68bf1d816a99 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -104,132 +103,136 @@ type CopyInput struct { // If the source blob has been modified, the Blob service returns status code 412 (Precondition Failed). // This header cannot be specified if the source is an Azure File. SourceIfUnmodifiedSince *string + + // The encryption scope to set for the request content. + EncryptionScope *string } -type CopyResult struct { - autorest.Response +type CopyResponse struct { + HttpResponse *http.Response CopyID string CopyStatus string } // Copy copies a blob to a destination within the storage account asynchronously. -func (client Client) Copy(ctx context.Context, accountName, containerName, blobName string, input CopyInput) (result CopyResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Copy", "`accountName` cannot be an empty string.") - } +func (c Client) Copy(ctx context.Context, containerName, blobName string, input CopyInput) (result CopyResponse, err error) { if containerName == "" { - return result, validation.NewError("blobs.Client", "Copy", "`containerName` cannot be an empty string.") + return result, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Copy", "`containerName` must be a lower-cased string.") + return result, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "Copy", "`blobName` cannot be an empty string.") + return result, fmt.Errorf("`blobName` cannot be an empty string") } + if input.CopySource == "" { - return result, validation.NewError("blobs.Client", "Copy", "`input.CopySource` cannot be an empty string.") + return result, fmt.Errorf("`input.CopySource` cannot be an empty string") } - req, err := client.CopyPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Copy", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: copyOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.CopySender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Copy", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.CopyResponder(resp) + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.CopyID = resp.Header.Get("x-ms-copy-id") + result.CopyStatus = resp.Header.Get("x-ms-copy-status") + } + } if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Copy", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// CopyPreparer prepares the Copy request. -func (client Client) CopyPreparer(ctx context.Context, accountName, containerName, blobName string, input CopyInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type copyOptions struct { + input CopyInput +} + +func (c copyOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-copy-source", c.input.CopySource) - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": autorest.Encode("header", input.CopySource), + if c.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *c.input.LeaseID) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if c.input.SourceLeaseID != nil { + headers.Append("x-ms-source-lease-id", *c.input.SourceLeaseID) } - if input.SourceLeaseID != nil { - headers["x-ms-source-lease-id"] = *input.SourceLeaseID + + if c.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*c.input.AccessTier)) } - if input.AccessTier != nil { - headers["x-ms-access-tier"] = string(*input.AccessTier) + + if c.input.IfMatch != nil { + headers.Append("If-Match", *c.input.IfMatch) } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch + if c.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *c.input.IfNoneMatch) } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch + + if c.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *c.input.IfUnmodifiedSince) } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince + + if c.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *c.input.IfModifiedSince) } - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince + + if c.input.SourceIfMatch != nil { + headers.Append("x-ms-source-if-match", *c.input.SourceIfMatch) } - if input.SourceIfMatch != nil { - headers["x-ms-source-if-match"] = *input.SourceIfMatch + if c.input.SourceIfNoneMatch != nil { + headers.Append("x-ms-source-if-none-match", *c.input.SourceIfNoneMatch) } - if input.SourceIfNoneMatch != nil { - headers["x-ms-source-if-none-match"] = *input.SourceIfNoneMatch + + if c.input.SourceIfModifiedSince != nil { + headers.Append("x-ms-source-if-modified-since", *c.input.SourceIfModifiedSince) } - if input.SourceIfModifiedSince != nil { - headers["x-ms-source-if-modified-since"] = *input.SourceIfModifiedSince + + if c.input.SourceIfUnmodifiedSince != nil { + headers.Append("x-ms-source-if-unmodified-since", *c.input.SourceIfUnmodifiedSince) } - if input.SourceIfUnmodifiedSince != nil { - headers["x-ms-source-if-unmodified-since"] = *input.SourceIfUnmodifiedSince + + if c.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *c.input.EncryptionScope) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// CopySender sends the Copy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c copyOptions) ToOData() *odata.Query { + return nil } -// CopyResponder handles the response to the Copy request. The method always -// closes the http.Response Body. -func (client Client) CopyResponder(resp *http.Response) (result CopyResult, err error) { - if resp != nil && resp.Header != nil { - result.CopyID = resp.Header.Get("x-ms-copy-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return +func (c copyOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_abort.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_abort.go new file mode 100644 index 000000000000..5d9469a5097c --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_abort.go @@ -0,0 +1,101 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type AbortCopyInput struct { + // The Copy ID which should be aborted + CopyID string + + // The ID of the Lease + // This must be specified if a Lease is present on the Blob, else a 403 is returned + LeaseID *string +} + +type CopyAbortResponse struct { + HttpResponse *http.Response +} + +// AbortCopy aborts a pending Copy Blob operation, and leaves a destination blob with zero length and full metadata. +func (c Client) AbortCopy(ctx context.Context, containerName, blobName string, input AbortCopyInput) (result CopyAbortResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.CopyID == "" { + err = fmt.Errorf("`input.CopyID` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: copyAbortOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type copyAbortOptions struct { + input AbortCopyInput +} + +func (c copyAbortOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-copy-action", "abort") + if c.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *c.input.LeaseID) + } + + return headers +} + +func (c copyAbortOptions) ToOData() *odata.Query { + return nil +} + +func (c copyAbortOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "copy") + out.Append("copyid", c.input.CopyID) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_and_wait.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_and_wait.go new file mode 100644 index 000000000000..5ec7c239fe32 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_and_wait.go @@ -0,0 +1,28 @@ +package blobs + +import ( + "context" + "fmt" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" +) + +// CopyAndWait copies a blob to a destination within the storage account and waits for it to finish copying. +func (c Client) CopyAndWait(ctx context.Context, containerName, blobName string, input CopyInput) error { + if _, err := c.Copy(ctx, containerName, blobName, input); err != nil { + return fmt.Errorf("error copying: %s", err) + } + + getInput := GetPropertiesInput{ + LeaseID: input.LeaseID, + } + + pollerType := NewCopyAndWaitPoller(&c, containerName, blobName, getInput) + poller := pollers.NewPoller(pollerType, 10*time.Second, pollers.DefaultNumberOfDroppedConnectionsToAllow) + if err := poller.PollUntilDone(ctx); err != nil { + return fmt.Errorf("waiting for file to copy: %+v", err) + } + + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_and_wait_poller.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_and_wait_poller.go new file mode 100644 index 000000000000..313f4863206e --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/copy_and_wait_poller.go @@ -0,0 +1,48 @@ +package blobs + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" +) + +var _ pollers.PollerType = ©AndWaitPoller{} + +func NewCopyAndWaitPoller(client *Client, containerName, blobName string, getPropertiesInput GetPropertiesInput) *copyAndWaitPoller { + return ©AndWaitPoller{ + client: client, + containerName: containerName, + blobName: blobName, + getPropertiesInput: getPropertiesInput, + } +} + +type copyAndWaitPoller struct { + client *Client + containerName string + blobName string + getPropertiesInput GetPropertiesInput +} + +func (p *copyAndWaitPoller) Poll(ctx context.Context) (*pollers.PollResult, error) { + props, err := p.client.GetProperties(ctx, p.containerName, p.blobName, p.getPropertiesInput) + if err != nil { + return nil, fmt.Errorf("retrieving properties (container: %s blob: %s) : %+v", p.containerName, p.blobName, err) + } + + if strings.EqualFold(string(props.CopyStatus), string(Success)) { + return &pollers.PollResult{ + Status: pollers.PollingStatusSucceeded, + PollInterval: 10 * time.Second, + }, nil + } + + // Processing + return &pollers.PollResult{ + Status: pollers.PollingStatusInProgress, + PollInterval: 10 * time.Second, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete.go new file mode 100644 index 000000000000..80c1e4332389 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete.go @@ -0,0 +1,95 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type DeleteInput struct { + // Should any Snapshots for this Blob also be deleted? + // If the Blob has Snapshots and this is set to False a 409 Conflict will be returned + DeleteSnapshots bool + + // The ID of the Lease + // This must be specified if a Lease is present on the Blob, else a 403 is returned + LeaseID *string +} + +type DeleteResponse struct { + HttpResponse *http.Response +} + +// Delete marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. +func (c Client) Delete(ctx context.Context, containerName, blobName string, input DeleteInput) (result DeleteResponse, err error) { + if containerName == "" { + return result, fmt.Errorf("`containerName` cannot be an empty string") + } + + if strings.ToLower(containerName) != containerName { + return result, fmt.Errorf("`containerName` must be a lower-cased string") + } + + if blobName == "" { + return result, fmt.Errorf("`blobName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type deleteOptions struct { + input DeleteInput +} + +func (d deleteOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if d.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *d.input.LeaseID) + } + + if d.input.DeleteSnapshots { + headers.Append("x-ms-delete-snapshots", "include") + } + + return headers +} + +func (d deleteOptions) ToOData() *odata.Query { + return nil +} + +func (d deleteOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete_snapshot.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete_snapshot.go new file mode 100644 index 000000000000..e5cfa3c8f0b6 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete_snapshot.go @@ -0,0 +1,99 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type DeleteSnapshotInput struct { + // The ID of the Lease + // This must be specified if a Lease is present on the Blob, else a 403 is returned + LeaseID *string + + // The DateTime of the Snapshot which should be marked for Deletion + SnapshotDateTime string +} + +type DeleteSnapshotResponse struct { + HttpResponse *http.Response +} + +// DeleteSnapshot marks a single Snapshot of a Blob for Deletion based on it's DateTime, which will be deleted during the next Garbage Collection cycle. +func (c Client) DeleteSnapshot(ctx context.Context, containerName, blobName string, input DeleteSnapshotInput) (result DeleteSnapshotResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.SnapshotDateTime == "" { + err = fmt.Errorf("`input.SnapshotDateTime` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteSnapshotOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type deleteSnapshotOptions struct { + input DeleteSnapshotInput +} + +func (d deleteSnapshotOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if d.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *d.input.LeaseID) + } + + return headers +} + +func (d deleteSnapshotOptions) ToOData() *odata.Query { + return nil +} + +func (d deleteSnapshotOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("snapshot", d.input.SnapshotDateTime) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete_snapshots.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete_snapshots.go new file mode 100644 index 000000000000..dd0ce7be20fc --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/delete_snapshots.go @@ -0,0 +1,90 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type DeleteSnapshotsInput struct { + // The ID of the Lease + // This must be specified if a Lease is present on the Blob, else a 403 is returned + LeaseID *string +} + +type DeleteSnapshotsResponse struct { + HttpResponse *http.Response +} + +// DeleteSnapshots marks all Snapshots of a Blob for Deletion, which will be deleted during the next Garbage Collection Cycle. +func (c Client) DeleteSnapshots(ctx context.Context, containerName, blobName string, input DeleteSnapshotsInput) (result DeleteSnapshotsResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteSnapshotsOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type deleteSnapshotsOptions struct { + input DeleteSnapshotsInput +} + +func (d deleteSnapshotsOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-delete-snapshots", "only") + + if d.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *d.input.LeaseID) + } + return headers +} + +func (d deleteSnapshotsOptions) ToOData() *odata.Query { + return nil +} + +func (d deleteSnapshotsOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get.go new file mode 100644 index 000000000000..5829324459f5 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get.go @@ -0,0 +1,104 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetInput struct { + LeaseID *string + StartByte *int64 + EndByte *int64 +} + +type GetResponse struct { + HttpResponse *http.Response + + Contents *[]byte +} + +// Get reads or downloads a blob from the system, including its metadata and properties. +func (c Client) Get(ctx context.Context, containerName, blobName string, input GetInput) (result GetResponse, err error) { + if containerName == "" { + return result, fmt.Errorf("`containerName` cannot be an empty string") + } + + if strings.ToLower(containerName) != containerName { + return result, fmt.Errorf("`containerName` must be a lower-cased string") + } + + if blobName == "" { + return result, fmt.Errorf("`blobName` cannot be an empty string") + } + + if input.LeaseID != nil && *input.LeaseID == "" { + return result, fmt.Errorf("`input.LeaseID` should either be specified or nil, not an empty string") + } + + if (input.StartByte != nil && input.EndByte == nil) || input.StartByte == nil && input.EndByte != nil { + return result, fmt.Errorf("`input.StartByte` and `input.EndByte` must both be specified, or both be nil") + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + http.StatusPartialContent, + }, + HttpMethod: http.MethodGet, + OptionsObject: getOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.Contents = &[]byte{} + result.HttpResponse = resp.Response + + err = resp.Unmarshal(result.Contents) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type getOptions struct { + input GetInput +} + +func (g getOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if g.input.StartByte != nil && g.input.EndByte != nil { + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", *g.input.StartByte, *g.input.EndByte)) + } + return headers + +} + +func (g getOptions) ToOData() *odata.Query { + return nil +} + +func (g getOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get_block_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get_block_list.go new file mode 100644 index 000000000000..b7c4037d88f0 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get_block_list.go @@ -0,0 +1,125 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetBlockListInput struct { + BlockListType BlockListType + LeaseID *string +} + +type GetBlockListResponse struct { + HttpResponse *http.Response + + // The size of the blob in bytes + BlobContentLength *int64 + + // The Content Type of the blob + ContentType string + + // The ETag associated with this blob + ETag string + + // A list of blocks which have been committed + CommittedBlocks CommittedBlocks `xml:"CommittedBlocks,omitempty"` + + // A list of blocks which have not yet been committed + UncommittedBlocks UncommittedBlocks `xml:"UncommittedBlocks,omitempty"` +} + +// GetBlockList retrieves the list of blocks that have been uploaded as part of a block blob. +func (c Client) GetBlockList(ctx context.Context, containerName, blobName string, input GetBlockListInput) (result GetBlockListResponse, err error) { + if containerName == "" { + return result, fmt.Errorf("`containerName` cannot be an empty string") + } + + if strings.ToLower(containerName) != containerName { + return result, fmt.Errorf("`containerName` must be a lower-cased string") + } + + if blobName == "" { + return result, fmt.Errorf("`blobName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getBlockListOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.ContentType = resp.Header.Get("Content-Type") + result.ETag = resp.Header.Get("ETag") + + if v := resp.Header.Get("x-ms-blob-content-length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-blob-content-length` header value %q: %s", v, innerErr) + return + } + + i64 := int64(i) + result.BlobContentLength = &i64 + } + } + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type getBlockListOptions struct { + input GetBlockListInput +} + +func (g getBlockListOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if g.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *g.input.LeaseID) + } + return headers +} + +func (g getBlockListOptions) ToOData() *odata.Query { + return nil +} + +func (g getBlockListOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("blocklisttype", string(g.input.BlockListType)) + out.Append("comp", "blocklist") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get_page_ranges.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get_page_ranges.go new file mode 100644 index 000000000000..fe83294cc0b3 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/get_page_ranges.go @@ -0,0 +1,140 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetPageRangesInput struct { + LeaseID *string + + StartByte *int64 + EndByte *int64 +} + +type GetPageRangesResponse struct { + HttpResponse *http.Response + + // The size of the blob in bytes + ContentLength *int64 + + // The Content Type of the blob + ContentType string + + // The ETag associated with this blob + ETag string + + PageRanges []PageRange `xml:"PageRange"` +} + +type PageRange struct { + // The start byte offset for this range, inclusive + Start int64 `xml:"Start"` + + // The end byte offset for this range, inclusive + End int64 `xml:"End"` +} + +// GetPageRanges returns the list of valid page ranges for a page blob or snapshot of a page blob. +func (c Client) GetPageRanges(ctx context.Context, containerName, blobName string, input GetPageRangesInput) (result GetPageRangesResponse, err error) { + if containerName == "" { + return result, fmt.Errorf("`containerName` cannot be an empty string") + } + + if strings.ToLower(containerName) != containerName { + return result, fmt.Errorf("`containerName` must be a lower-cased string") + } + + if blobName == "" { + return result, fmt.Errorf("`blobName` cannot be an empty string") + } + + if (input.StartByte != nil && input.EndByte == nil) || (input.StartByte == nil && input.EndByte != nil) { + return result, fmt.Errorf("`input.StartByte` and `input.EndByte` must both be specified, or both be nil") + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getPageRangesOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.ContentType = resp.Header.Get("Content-Type") + result.ETag = resp.Header.Get("ETag") + + if v := resp.Header.Get("x-ms-blob-content-length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-blob-content-length` header value %q: %+v", v, innerErr) + return + } + + i64 := int64(i) + result.ContentLength = &i64 + } + } + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type getPageRangesOptions struct { + input GetPageRangesInput +} + +func (g getPageRangesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if g.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *g.input.LeaseID) + } + + if g.input.StartByte != nil && g.input.EndByte != nil { + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", *g.input.StartByte, *g.input.EndByte)) + } + + return headers +} + +func (g getPageRangesOptions) ToOData() *odata.Query { + return nil +} + +func (g getPageRangesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "pagelist") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/incremental_copy_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/incremental_copy_blob.go new file mode 100644 index 000000000000..0423c0f99e22 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/incremental_copy_blob.go @@ -0,0 +1,112 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type IncrementalCopyBlobInput struct { + CopySource string + IfModifiedSince *string + IfUnmodifiedSince *string + IfMatch *string + IfNoneMatch *string +} + +type IncrementalCopyBlob struct { + HttpResponse *http.Response +} + +// IncrementalCopyBlob copies a snapshot of the source page blob to a destination page blob. +// The snapshot is copied such that only the differential changes between the previously copied +// snapshot are transferred to the destination. +// The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. +func (c Client) IncrementalCopyBlob(ctx context.Context, containerName, blobName string, input IncrementalCopyBlobInput) (result IncrementalCopyBlob, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.CopySource == "" { + err = fmt.Errorf("`input.CopySource` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: incrementalCopyBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type incrementalCopyBlobOptions struct { + input IncrementalCopyBlobInput +} + +func (i incrementalCopyBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + headers.Append("x-ms-copy-source", i.input.CopySource) + + if i.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *i.input.IfModifiedSince) + } + if i.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *i.input.IfUnmodifiedSince) + } + if i.input.IfMatch != nil { + headers.Append("If-Match", *i.input.IfMatch) + } + if i.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *i.input.IfNoneMatch) + } + return headers +} + +func (i incrementalCopyBlobOptions) ToOData() *odata.Query { + return nil +} + +func (i incrementalCopyBlobOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "incrementalcopy") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_acquire.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_acquire.go new file mode 100644 index 000000000000..d4477564eacc --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_acquire.go @@ -0,0 +1,127 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type AcquireLeaseInput struct { + // The ID of the existing Lease, if leased + LeaseID *string + + // Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. + // A non-infinite lease can be between 15 and 60 seconds + LeaseDuration int + + // The Proposed new ID for the Lease + ProposedLeaseID *string +} + +type AcquireLeaseResponse struct { + HttpResponse *http.Response + + LeaseID string +} + +// AcquireLease establishes and manages a lock on a blob for write and delete operations. +func (c Client) AcquireLease(ctx context.Context, containerName, blobName string, input AcquireLeaseInput) (result AcquireLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.LeaseID != nil && *input.LeaseID == "" { + err = fmt.Errorf("`input.LeaseID` cannot be an empty string, if specified") + return + } + + if input.ProposedLeaseID != nil && *input.ProposedLeaseID == "" { + err = fmt.Errorf("`input.ProposedLeaseID` cannot be an empty string, if specified") + return + } + // An infinite lease duration is -1 seconds. A non-infinite lease can be between 15 and 60 seconds + if input.LeaseDuration != -1 && (input.LeaseDuration <= 15 || input.LeaseDuration >= 60) { + err = fmt.Errorf("`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: acquireLeaseOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.LeaseID = resp.Header.Get("x-ms-lease-id") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type acquireLeaseOptions struct { + input AcquireLeaseInput +} + +func (a acquireLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + headers.Append("x-ms-lease-action", "acquire") + headers.Append("x-ms-lease-duration", strconv.Itoa(a.input.LeaseDuration)) + + if a.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *a.input.LeaseID) + } + + if a.input.ProposedLeaseID != nil { + headers.Append("x-ms-proposed-lease-id", *a.input.ProposedLeaseID) + } + + return headers +} + +func (a acquireLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (a acquireLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_break.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_break.go new file mode 100644 index 000000000000..74e689106694 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_break.go @@ -0,0 +1,113 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type BreakLeaseInput struct { + // For a break operation, proposed duration the lease should continue + // before it is broken, in seconds, between 0 and 60. + // This break period is only used if it is shorter than the time remaining on the lease. + // If longer, the time remaining on the lease is used. + // A new lease will not be available before the break period has expired, + // but the lease may be held for longer than the break period. + // If this header does not appear with a break operation, a fixed-duration lease breaks + // after the remaining lease period elapses, and an infinite lease breaks immediately. + BreakPeriod *int + + LeaseID string +} + +type BreakLeaseResponse struct { + HttpResponse *http.Response + + // Approximate time remaining in the lease period, in seconds. + // If the break is immediate, 0 is returned. + LeaseTime int +} + +// BreakLease breaks an existing lock on a blob using the LeaseID. +func (c Client) BreakLease(ctx context.Context, containerName, blobName string, input BreakLeaseInput) (result BreakLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.LeaseID == "" { + err = fmt.Errorf("`input.LeaseID` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: breakLeaseOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type breakLeaseOptions struct { + input BreakLeaseInput +} + +func (b breakLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + headers.Append("x-ms-lease-action", "break") + headers.Append("x-ms-lease-id", b.input.LeaseID) + + if b.input.BreakPeriod != nil { + headers.Append("x-ms-lease-break-period", strconv.Itoa(*b.input.BreakPeriod)) + } + + return headers +} + +func (b breakLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (b breakLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_change.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_change.go new file mode 100644 index 000000000000..f983d1dd9c6c --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_change.go @@ -0,0 +1,105 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ChangeLeaseInput struct { + ExistingLeaseID string + ProposedLeaseID string +} + +type ChangeLeaseResponse struct { + HttpResponse *http.Response + + LeaseID string +} + +// ChangeLease changes an existing lock on a blob for another lock. +func (c Client) ChangeLease(ctx context.Context, containerName, blobName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.ExistingLeaseID == "" { + err = fmt.Errorf("`input.ExistingLeaseID` cannot be an empty string") + return + } + + if input.ProposedLeaseID == "" { + err = fmt.Errorf("`input.ProposedLeaseID` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: changeLeaseOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.LeaseID = resp.Header.Get("x-ms-lease-id") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type changeLeaseOptions struct { + input ChangeLeaseInput +} + +func (c changeLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-lease-action", "change") + headers.Append("x-ms-lease-id", c.input.ExistingLeaseID) + headers.Append("x-ms-proposed-lease-id", c.input.ProposedLeaseID) + return headers +} + +func (c changeLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (c changeLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_release.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_release.go new file mode 100644 index 000000000000..2101828b24e1 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_release.go @@ -0,0 +1,92 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ReleaseLeaseResponse struct { + HttpResponse *http.Response +} + +type ReleaseLeaseInput struct { + LeaseID string +} + +// ReleaseLease releases a lock based on the Lease ID. +func (c Client) ReleaseLease(ctx context.Context, containerName, blobName string, input ReleaseLeaseInput) (result ReleaseLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.LeaseID == "" { + err = fmt.Errorf("`input.LeaseID` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: releaseLeaseOptions{ + leaseID: input.LeaseID, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type releaseLeaseOptions struct { + leaseID string +} + +func (r releaseLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-lease-action", "release") + headers.Append("x-ms-lease-id", r.leaseID) + return headers +} + +func (r releaseLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (r releaseLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_renew.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_renew.go new file mode 100644 index 000000000000..e43a12d96ea9 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/lease_renew.go @@ -0,0 +1,91 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type RenewLeaseResponse struct { + HttpResponse *http.Response +} + +type RenewLeaseInput struct { + LeaseID string +} + +func (c Client) RenewLease(ctx context.Context, containerName, blobName string, input RenewLeaseInput) (result RenewLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.LeaseID == "" { + err = fmt.Errorf("`input.LeaseID` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: renewLeaseOptions{ + leaseID: input.LeaseID, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type renewLeaseOptions struct { + leaseID string +} + +func (r renewLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-lease-action", "renew") + headers.Append("x-ms-lease-id", r.leaseID) + return headers +} + +func (r renewLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (r renewLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/metadata_set.go new file mode 100644 index 000000000000..ce6c047d0256 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/metadata_set.go @@ -0,0 +1,100 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SetMetaDataInput struct { + // The ID of the Lease + // This must be specified if a Lease is present on the Blob, else a 403 is returned + LeaseID *string + + // Any metadata which should be added to this blob + MetaData map[string]string +} + +type SetMetaDataResponse struct { + HttpResponse *http.Response +} + +// SetMetaData marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. +func (c Client) SetMetaData(ctx context.Context, containerName, blobName string, input SetMetaDataInput) (result SetMetaDataResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setMetadataOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type setMetadataOptions struct { + input SetMetaDataInput +} + +func (s setMetadataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) + } + headers.Merge(metadata.SetMetaDataHeaders(s.input.MetaData)) + return headers +} + +func (s setMetadataOptions) ToOData() *odata.Query { + return nil +} + +func (s setMetadataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/models.go similarity index 100% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/models.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/models.go diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/properties_get.go similarity index 55% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_get.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/properties_get.go index 5640687d6d92..3edfa8900845 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/properties_get.go @@ -7,10 +7,8 @@ import ( "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -20,8 +18,8 @@ type GetPropertiesInput struct { LeaseID *string } -type GetPropertiesResult struct { - autorest.Response +type GetPropertiesResponse struct { + HttpResponse *http.Response // The tier of page blob on a premium storage account or tier of block blob on blob storage or general purpose v2 account. AccessTier AccessTier @@ -160,151 +158,138 @@ type GetPropertiesResult struct { // Is the Storage Account encrypted using server-side encryption? This should always return true ServerEncrypted bool + + // The encryption scope for the request content. + EncryptionScope string } // GetProperties returns all user-defined metadata, standard HTTP properties, and system properties for the blob -func (client Client) GetProperties(ctx context.Context, accountName, containerName, blobName string, input GetPropertiesInput) (result GetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) GetProperties(ctx context.Context, containerName, blobName string, input GetPropertiesInput) (result GetPropertiesResponse, err error) { if containerName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` cannot be an empty string.") + err = fmt.Errorf("`containerName` cannot be an empty string") + return } if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` must be a lower-cased string.") + err = fmt.Errorf("`containerName` must be a lower-cased string") + return } if blobName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`blobName` cannot be an empty string.") + err = fmt.Errorf("`blobName` cannot be an empty string") + return } - req, err := client.GetPropertiesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: getPropertiesOptions{ + leaseID: input.LeaseID, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.GetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetPropertiesResponder(resp) + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.AccessTier = AccessTier(resp.Header.Get("x-ms-access-tier")) + result.AccessTierChangeTime = resp.Header.Get("x-ms-access-tier-change-time") + result.ArchiveStatus = ArchiveStatus(resp.Header.Get("x-ms-archive-status")) + result.BlobCommittedBlockCount = resp.Header.Get("x-ms-blob-committed-block-count") + result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") + result.BlobType = BlobType(resp.Header.Get("x-ms-blob-type")) + result.CacheControl = resp.Header.Get("Cache-Control") + result.ContentDisposition = resp.Header.Get("Content-Disposition") + result.ContentEncoding = resp.Header.Get("Content-Encoding") + result.ContentLanguage = resp.Header.Get("Content-Language") + result.ContentMD5 = resp.Header.Get("Content-MD5") + result.ContentType = resp.Header.Get("Content-Type") + result.CopyCompletionTime = resp.Header.Get("x-ms-copy-completion-time") + result.CopyDestinationSnapshot = resp.Header.Get("x-ms-copy-destination-snapshot") + result.CopyID = resp.Header.Get("x-ms-copy-id") + result.CopyProgress = resp.Header.Get("x-ms-copy-progress") + result.CopySource = resp.Header.Get("x-ms-copy-source") + result.CopyStatus = CopyStatus(resp.Header.Get("x-ms-copy-status")) + result.CopyStatusDescription = resp.Header.Get("x-ms-copy-status-description") + result.CreationTime = resp.Header.Get("x-ms-creation-time") + result.ETag = resp.Header.Get("Etag") + result.LastModified = resp.Header.Get("Last-Modified") + result.LeaseDuration = LeaseDuration(resp.Header.Get("x-ms-lease-duration")) + result.LeaseState = LeaseState(resp.Header.Get("x-ms-lease-state")) + result.LeaseStatus = LeaseStatus(resp.Header.Get("x-ms-lease-status")) + result.EncryptionScope = resp.Header.Get("x-ms-encryption-scope") + result.MetaData = metadata.ParseFromHeaders(resp.Header) + + if v := resp.Header.Get("x-ms-access-tier-inferred"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-access-tier-inferred` header value %q: %s", v, innerErr) + return + } + result.AccessTierInferred = b + } + + if v := resp.Header.Get("Content-Length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("parsing `Content-Length` header value %q: %s", v, innerErr) + } + result.ContentLength = int64(i) + } + + if v := resp.Header.Get("x-ms-incremental-copy"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-incremental-copy` header value %q: %s", v, innerErr) + return + } + result.IncrementalCopy = b + } + + if v := resp.Header.Get("x-ms-server-encrypted"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-server-encrypted` header value %q: %s", v, innerErr) + return + } + result.ServerEncrypted = b + } + } + } if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName, containerName, blobName string, input GetPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type getPropertiesOptions struct { + leaseID *string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +func (g getPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if g.leaseID != nil { + headers.Append("x-ms-lease-id", *g.leaseID) } - - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getPropertiesOptions) ToOData() *odata.Query { + return nil } -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResult, err error) { - if resp != nil && resp.Header != nil { - result.AccessTier = AccessTier(resp.Header.Get("x-ms-access-tier")) - result.AccessTierChangeTime = resp.Header.Get(" x-ms-access-tier-change-time") - result.ArchiveStatus = ArchiveStatus(resp.Header.Get(" x-ms-archive-status")) - result.BlobCommittedBlockCount = resp.Header.Get("x-ms-blob-committed-block-count") - result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") - result.BlobType = BlobType(resp.Header.Get("x-ms-blob-type")) - result.CacheControl = resp.Header.Get("Cache-Control") - result.ContentDisposition = resp.Header.Get("Content-Disposition") - result.ContentEncoding = resp.Header.Get("Content-Encoding") - result.ContentLanguage = resp.Header.Get("Content-Language") - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.ContentType = resp.Header.Get("Content-Type") - result.CopyCompletionTime = resp.Header.Get("x-ms-copy-completion-time") - result.CopyDestinationSnapshot = resp.Header.Get("x-ms-copy-destination-snapshot") - result.CopyID = resp.Header.Get("x-ms-copy-id") - result.CopyProgress = resp.Header.Get("x-ms-copy-progress") - result.CopySource = resp.Header.Get("x-ms-copy-source") - result.CopyStatus = CopyStatus(resp.Header.Get("x-ms-copy-status")) - result.CopyStatusDescription = resp.Header.Get("x-ms-copy-status-description") - result.CreationTime = resp.Header.Get("x-ms-creation-time") - result.ETag = resp.Header.Get("Etag") - result.LastModified = resp.Header.Get("Last-Modified") - result.LeaseDuration = LeaseDuration(resp.Header.Get("x-ms-lease-duration")) - result.LeaseState = LeaseState(resp.Header.Get("x-ms-lease-state")) - result.LeaseStatus = LeaseStatus(resp.Header.Get("x-ms-lease-status")) - result.MetaData = metadata.ParseFromHeaders(resp.Header) - - if v := resp.Header.Get("x-ms-access-tier-inferred"); v != "" { - b, innerErr := strconv.ParseBool(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as a bool: %s", v, innerErr) - return - } - - result.AccessTierInferred = b - } - - if v := resp.Header.Get("Content-Length"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) - } - - result.ContentLength = int64(i) - } - - if v := resp.Header.Get("x-ms-incremental-copy"); v != "" { - b, innerErr := strconv.ParseBool(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as a bool: %s", v, innerErr) - return - } - - result.IncrementalCopy = b - } - - if v := resp.Header.Get("x-ms-server-encrypted"); v != "" { - b, innerErr := strconv.ParseBool(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as a bool: %s", v, innerErr) - return - } - - result.IncrementalCopy = b - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return +func (g getPropertiesOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/properties_set.go new file mode 100644 index 000000000000..73b417f04540 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/properties_set.go @@ -0,0 +1,135 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type SetPropertiesInput struct { + CacheControl *string + ContentType *string + ContentMD5 *string + ContentEncoding *string + ContentLanguage *string + LeaseID *string + ContentDisposition *string + ContentLength *int64 + SequenceNumberAction *SequenceNumberAction + BlobSequenceNumber *string +} + +type SetPropertiesResponse struct { + HttpResponse *http.Response + + BlobSequenceNumber string + Etag string +} + +// SetProperties sets system properties on the blob. +func (c Client) SetProperties(ctx context.Context, containerName, blobName string, input SetPropertiesInput) (result SetPropertiesResponse, err error) { + if containerName == "" { + return result, fmt.Errorf("`containerName` cannot be an empty string") + } + + if strings.ToLower(containerName) != containerName { + return result, fmt.Errorf("`containerName` must be a lower-cased string") + } + + if blobName == "" { + return result, fmt.Errorf("`blobName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setPropertiesOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type SequenceNumberAction string + +var ( + Increment SequenceNumberAction = "increment" + Max SequenceNumberAction = "max" + Update SequenceNumberAction = "update" +) + +type setPropertiesOptions struct { + input SetPropertiesInput +} + +func (s setPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if s.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *s.input.CacheControl) + } + if s.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *s.input.ContentDisposition) + } + if s.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *s.input.ContentEncoding) + } + if s.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *s.input.ContentLanguage) + } + if s.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *s.input.ContentMD5) + } + if s.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *s.input.ContentType) + } + if s.input.ContentLength != nil { + headers.Append("x-ms-blob-content-length", strconv.Itoa(int(*s.input.ContentLength))) + } + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) + } + if s.input.SequenceNumberAction != nil { + headers.Append("x-ms-sequence-number-action", string(*s.input.SequenceNumberAction)) + } + if s.input.BlobSequenceNumber != nil { + headers.Append("x-ms-blob-sequence-number", *s.input.BlobSequenceNumber) + } + + return headers +} + +func (s setPropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (s setPropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "properties") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_append_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_append_blob.go new file mode 100644 index 000000000000..8cc53001882f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_append_blob.go @@ -0,0 +1,128 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type PutAppendBlobInput struct { + CacheControl *string + ContentDisposition *string + ContentEncoding *string + ContentLanguage *string + ContentMD5 *string + ContentType *string + LeaseID *string + EncryptionScope *string + MetaData map[string]string +} + +type PutAppendBlobResponse struct { + HttpResponse *http.Response +} + +// PutAppendBlob is a wrapper around the Put API call (with a stricter input object) +// which creates a new append blob, or updates the content of an existing blob. +func (c Client) PutAppendBlob(ctx context.Context, containerName, blobName string, input PutAppendBlobInput) (result PutAppendBlobResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putAppendBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putAppendBlobOptions struct { + input PutAppendBlobInput +} + +func (p putAppendBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + headers.Append("x-ms-blob-type", string(AppendBlob)) + headers.Append("Content-Length", "0") + + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) + } + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) + } + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) + } + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) + } + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) + } + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) + } + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) + return headers +} + +func (p putAppendBlobOptions) ToOData() *odata.Query { + return nil +} + +func (p putAppendBlobOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block.go new file mode 100644 index 000000000000..f261ddec3140 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block.go @@ -0,0 +1,119 @@ +package blobs + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type PutBlockInput struct { + BlockID string + Content []byte + ContentMD5 *string + LeaseID *string + EncryptionScope *string +} + +type PutBlockResponse struct { + HttpResponse *http.Response + ContentMD5 string +} + +// PutBlock creates a new block to be committed as part of a blob. +func (c Client) PutBlock(ctx context.Context, containerName, blobName string, input PutBlockInput) (result PutBlockResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.BlockID == "" { + err = fmt.Errorf("`input.BlockID` cannot be an empty string") + return + } + + if len(input.Content) == 0 { + err = fmt.Errorf("`input.Content` cannot be empty") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + req.ContentLength = int64(len(input.Content)) + req.Body = io.NopCloser(bytes.NewReader(input.Content)) + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putBlockOptions struct { + input PutBlockInput +} + +func (p putBlockOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Content-Length", strconv.Itoa(len(p.input.Content))) + + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) + } + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + + return headers +} + +func (p putBlockOptions) ToOData() *odata.Query { + return nil +} + +func (p putBlockOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "block") + out.Append("blockid", p.input.BlockID) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_blob.go new file mode 100644 index 000000000000..d5d677393c9e --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_blob.go @@ -0,0 +1,147 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type PutBlockBlobInput struct { + CacheControl *string + Content *[]byte + ContentDisposition *string + ContentEncoding *string + ContentLanguage *string + ContentMD5 *string + ContentType *string + LeaseID *string + EncryptionScope *string + MetaData map[string]string +} + +type PutBlockBlobResponse struct { + HttpResponse *http.Response +} + +// PutBlockBlob is a wrapper around the Put API call (with a stricter input object) +// which creates a new block append blob, or updates the content of an existing block blob. +func (c Client) PutBlockBlob(ctx context.Context, containerName, blobName string, input PutBlockBlobInput) (result PutBlockBlobResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.Content != nil && len(*input.Content) == 0 { + err = fmt.Errorf("`input.Content` must either be nil or not empty") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + if input.ContentType != nil { + opts.ContentType = *input.ContentType + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + err = req.Marshal(input.Content) + if err != nil { + err = fmt.Errorf("marshalling request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putBlockBlobOptions struct { + input PutBlockBlobInput +} + +func (p putBlockBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-blob-type", string(BlockBlob)) + + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) + } + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) + } + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) + } + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) + } + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) + } + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) + } + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + if p.input.Content != nil { + headers.Append("Content-Length", strconv.Itoa(len(*p.input.Content))) + } + + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) + + return headers +} + +func (p putBlockBlobOptions) ToOData() *odata.Query { + return nil +} + +func (p putBlockBlobOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob_file.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_blob_file.go similarity index 50% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob_file.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_blob_file.go index b7499498aeca..f5f21b0736ed 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob_file.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_blob_file.go @@ -8,10 +8,10 @@ import ( ) // PutBlockBlobFromFile is a helper method which takes a file, and automatically chunks it up, rather than having to do this yourself -func (client Client) PutBlockBlobFromFile(ctx context.Context, accountName, containerName, blobName string, file *os.File, input PutBlockBlobInput) error { +func (c Client) PutBlockBlobFromFile(ctx context.Context, containerName, blobName string, file *os.File, input PutBlockBlobInput) error { fileInfo, err := file.Stat() if err != nil { - return fmt.Errorf("Error loading file info: %s", err) + return fmt.Errorf("loading file info: %s", err) } fileSize := fileInfo.Size() @@ -20,14 +20,14 @@ func (client Client) PutBlockBlobFromFile(ctx context.Context, accountName, cont _, err = file.ReadAt(bytes, 0) if err != nil { if err != io.EOF { - return fmt.Errorf("Error reading bytes: %s", err) + return fmt.Errorf("reading bytes: %s", err) } } input.Content = &bytes - if _, err = client.PutBlockBlob(ctx, accountName, containerName, blobName, input); err != nil { - return fmt.Errorf("Error putting bytes: %s", err) + if _, err = c.PutBlockBlob(ctx, containerName, blobName, input); err != nil { + return fmt.Errorf("putting bytes: %s", err) } return nil diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_list.go new file mode 100644 index 000000000000..a600fdbe369a --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_list.go @@ -0,0 +1,151 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type BlockList struct { + CommittedBlockIDs []BlockID `xml:"Committed,omitempty"` + UncommittedBlockIDs []BlockID `xml:"Uncommitted,omitempty"` + LatestBlockIDs []BlockID `xml:"Latest,omitempty"` +} + +type BlockID struct { + Value string `xml:",chardata"` +} + +type PutBlockListInput struct { + BlockList BlockList + CacheControl *string + ContentDisposition *string + ContentEncoding *string + ContentLanguage *string + ContentMD5 *string + ContentType *string + LeaseID *string + EncryptionScope *string + MetaData map[string]string +} + +type PutBlockListResponse struct { + HttpResponse *http.Response + + ContentMD5 string + ETag string + LastModified string +} + +// PutBlockList writes a blob by specifying the list of block IDs that make up the blob. +// In order to be written as part of a blob, a block must have been successfully written +// to the server in a prior Put Block operation. +func (c Client) PutBlockList(ctx context.Context, containerName, blobName string, input PutBlockListInput) (result PutBlockListResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockListOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + err = req.Marshal(&input.BlockList) + if err != nil { + err = fmt.Errorf("marshalling request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.ContentMD5 = resp.Header.Get("Content-MD5") + result.ETag = resp.Header.Get("ETag") + result.LastModified = resp.Header.Get("Last-Modified") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putBlockListOptions struct { + input PutBlockListInput +} + +func (p putBlockListOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) + } + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) + } + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) + } + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) + } + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) + } + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) + } + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) + + return headers +} + +func (p putBlockListOptions) ToOData() *odata.Query { + return nil +} + +func (p putBlockListOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "blocklist") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_url.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_url.go new file mode 100644 index 000000000000..088742367bea --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_block_url.go @@ -0,0 +1,122 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type PutBlockFromURLInput struct { + BlockID string + CopySource string + + ContentMD5 *string + LeaseID *string + Range *string + EncryptionScope *string +} + +type PutBlockFromURLResponse struct { + ContentMD5 string + HttpResponse *http.Response +} + +// PutBlockFromURL creates a new block to be committed as part of a blob where the contents are read from a URL +func (c Client) PutBlockFromURL(ctx context.Context, containerName, blobName string, input PutBlockFromURLInput) (result PutBlockFromURLResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.BlockID == "" { + err = fmt.Errorf("`input.BlockID` cannot be an empty string") + return + } + + if input.CopySource == "" { + err = fmt.Errorf("`input.CopySource` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockUrlOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.ContentMD5 = resp.Header.Get("Content-MD5") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putBlockUrlOptions struct { + input PutBlockFromURLInput +} + +func (p putBlockUrlOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + headers.Append("x-ms-copy-source", p.input.CopySource) + + if p.input.ContentMD5 != nil { + headers.Append("x-ms-source-content-md5", *p.input.ContentMD5) + } + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + if p.input.Range != nil { + headers.Append("x-ms-source-range", *p.input.Range) + } + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + return headers +} + +func (p putBlockUrlOptions) ToOData() *odata.Query { + return nil +} + +func (p putBlockUrlOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "block") + out.Append("blockid", p.input.BlockID) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_blob.go new file mode 100644 index 000000000000..74bfc6b2b260 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_blob.go @@ -0,0 +1,155 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type PutPageBlobInput struct { + CacheControl *string + ContentDisposition *string + ContentEncoding *string + ContentLanguage *string + ContentMD5 *string + ContentType *string + LeaseID *string + EncryptionScope *string + MetaData map[string]string + + BlobContentLengthBytes int64 + BlobSequenceNumber *int64 + AccessTier *AccessTier +} + +type PutPageBlobResponse struct { + HttpResponse *http.Response +} + +// PutPageBlob is a wrapper around the Put API call (with a stricter input object) +// which creates a new block blob, or updates the content of an existing page blob. +func (c Client) PutPageBlob(ctx context.Context, containerName, blobName string, input PutPageBlobInput) (result PutPageBlobResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.BlobContentLengthBytes == 0 || input.BlobContentLengthBytes%512 != 0 { + err = fmt.Errorf("`input.BlobContentLengthBytes` must be aligned to a 512-byte boundary") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putPageBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putPageBlobOptions struct { + input PutPageBlobInput +} + +func (p putPageBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + headers.Append("x-ms-blob-type", string(PageBlob)) + + // For a page blob or an page blob, the value of this header must be set to zero, + // as Put Blob is used only to initialize the blob + headers.Append("Content-Length", "0") + + // This header specifies the maximum size for the page blob, up to 8 TB. + // The page blob size must be aligned to a 512-byte boundary. + headers.Append("x-ms-blob-content-length", strconv.Itoa(int(p.input.BlobContentLengthBytes))) + + if p.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*p.input.AccessTier)) + } + + if p.input.BlobSequenceNumber != nil { + headers.Append("x-ms-blob-sequence-number", strconv.Itoa(int(*p.input.BlobSequenceNumber))) + } + + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) + } + + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) + } + + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) + } + + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) + } + + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) + } + + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) + } + + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) + return headers +} + +func (p putPageBlobOptions) ToOData() *odata.Query { + return nil +} + +func (p putPageBlobOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_clear.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_clear.go new file mode 100644 index 000000000000..45e0499e431d --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_clear.go @@ -0,0 +1,110 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type PutPageClearInput struct { + StartByte int64 + EndByte int64 + + LeaseID *string + EncryptionScope *string +} + +type PutPageClearResponse struct { + HttpResponse *http.Response +} + +// PutPageClear clears a range of pages within a page blob. +func (c Client) PutPageClear(ctx context.Context, containerName, blobName string, input PutPageClearInput) (result PutPageClearResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.StartByte < 0 { + err = fmt.Errorf("`input.StartByte` must be greater than or equal to 0") + return + } + + if input.EndByte <= 0 { + err = fmt.Errorf("`input.EndByte` must be greater than 0") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putPageClearOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putPageClearOptions struct { + input PutPageClearInput +} + +func (p putPageClearOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + headers.Append("x-ms-page-write", "clear") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", p.input.StartByte, p.input.EndByte)) + + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + + return headers +} + +func (p putPageClearOptions) ToOData() *odata.Query { + return nil +} + +func (p putPageClearOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "page") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_update.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_update.go new file mode 100644 index 000000000000..ab5f258373e3 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/put_page_update.go @@ -0,0 +1,171 @@ +package blobs + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type PutPageUpdateInput struct { + StartByte int64 + EndByte int64 + Content []byte + + IfSequenceNumberEQ *string + IfSequenceNumberLE *string + IfSequenceNumberLT *string + IfModifiedSince *string + IfUnmodifiedSince *string + IfMatch *string + IfNoneMatch *string + LeaseID *string + EncryptionScope *string +} + +type PutPageUpdateResponse struct { + HttpResponse *http.Response + + BlobSequenceNumber string + ContentMD5 string + LastModified string +} + +// PutPageUpdate writes a range of pages to a page blob. +func (c Client) PutPageUpdate(ctx context.Context, containerName, blobName string, input PutPageUpdateInput) (result PutPageUpdateResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.StartByte < 0 { + err = fmt.Errorf("`input.StartByte` must be greater than or equal to 0") + return + } + + if input.EndByte <= 0 { + err = fmt.Errorf("`input.EndByte` must be greater than 0") + return + } + + expectedSize := (input.EndByte - input.StartByte) + 1 + actualSize := int64(len(input.Content)) + if expectedSize != actualSize { + err = fmt.Errorf(fmt.Sprintf("Content Size was defined as %d but got %d.", expectedSize, actualSize)) + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putPageUpdateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + // this is needed to avoid `Content-Length: 0` in the request + req.Body = io.NopCloser(bytes.NewReader(input.Content)) + req.ContentLength = int64(len(input.Content)) + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") + result.ContentMD5 = resp.Header.Get("Content-MD5") + result.LastModified = resp.Header.Get("Last-Modified") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type putPageUpdateOptions struct { + input PutPageUpdateInput +} + +func (p putPageUpdateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-page-write", "update") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", p.input.StartByte, p.input.EndByte)) + headers.Append("Content-Length", strconv.Itoa(len(p.input.Content))) + + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } + + if p.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *p.input.EncryptionScope) + } + + if p.input.IfSequenceNumberEQ != nil { + headers.Append("x-ms-if-sequence-number-eq", *p.input.IfSequenceNumberEQ) + } + + if p.input.IfSequenceNumberLE != nil { + headers.Append("x-ms-if-sequence-number-le", *p.input.IfSequenceNumberLE) + } + + if p.input.IfSequenceNumberLT != nil { + headers.Append("x-ms-if-sequence-number-lt", *p.input.IfSequenceNumberLT) + } + + if p.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *p.input.IfModifiedSince) + } + + if p.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *p.input.IfUnmodifiedSince) + } + + if p.input.IfMatch != nil { + headers.Append("If-Match", *p.input.IfMatch) + } + + if p.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *p.input.IfNoneMatch) + } + + return headers +} + +func (p putPageUpdateOptions) ToOData() *odata.Query { + return nil +} + +func (p putPageUpdateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "page") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/resource_id.go new file mode 100644 index 000000000000..95b78f5ca780 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/resource_id.go @@ -0,0 +1,83 @@ +package blobs + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = BlobId{} + +type BlobId struct { + // AccountId specifies the ID of the Storage Account where this Blob exists. + AccountId accounts.AccountId + + // ContainerName specifies the name of the Container within this Storage Account where this + // Blob exists. + ContainerName string + + // BlobName specifies the name of this Blob. + BlobName string +} + +func NewBlobID(accountId accounts.AccountId, containerName, blobName string) BlobId { + return BlobId{ + AccountId: accountId, + ContainerName: containerName, + BlobName: blobName, + } +} + +func (b BlobId) ID() string { + return fmt.Sprintf("%s/%s/%s", b.AccountId.ID(), b.ContainerName, b.BlobName) +} + +func (b BlobId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + fmt.Sprintf("Container Name %q", b.ContainerName), + } + return fmt.Sprintf("Blob %q (%s)", b.BlobName, strings.Join(components, " / ")) +} + +// ParseBlobID parses `input` into a Blob ID using a known `domainSuffix` +func ParseBlobID(input, domainSuffix string) (*BlobId, error) { + // example: https://foo.blob.core.windows.net/Bar/example.vhd + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.BlobSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.BlobSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 2 { + return nil, fmt.Errorf("expected the path to contain 2 segments but got %d", len(segments)) + } + + containerName := segments[0] + blobName := strings.TrimPrefix(path, containerName) + blobName = strings.TrimPrefix(blobName, "/") + return &BlobId{ + AccountId: *account, + ContainerName: containerName, + BlobName: blobName, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/set_tier.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/set_tier.go new file mode 100644 index 000000000000..66b9d64884ae --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/set_tier.go @@ -0,0 +1,87 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type SetTierInput struct { + Tier AccessTier +} + +type SetTierResponse struct { + HttpResponse *http.Response +} + +// SetTier sets the tier on a blob. +func (c Client) SetTier(ctx context.Context, containerName, blobName string, input SetTierInput) (result SetTierResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: setTierOptions{ + tier: input.Tier, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type setTierOptions struct { + tier AccessTier +} + +func (s setTierOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-access-tier", string(s.tier)) + return headers +} + +func (s setTierOptions) ToOData() *odata.Query { + return nil +} + +func (s setTierOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "tier") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/snapshot.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/snapshot.go new file mode 100644 index 000000000000..ebbcb2011220 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/snapshot.go @@ -0,0 +1,158 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SnapshotInput struct { + // The ID of the Lease + // This must be specified if a Lease is present on the Blob, else a 403 is returned + LeaseID *string + + // The encryption scope to set for the request content. + EncryptionScope *string + + // MetaData is a user-defined name-value pair associated with the blob. + // If no name-value pairs are specified, the operation will copy the base blob metadata to the snapshot. + // If one or more name-value pairs are specified, the snapshot is created with the specified metadata, + // and metadata is not copied from the base blob. + MetaData map[string]string + + // A DateTime value which will only snapshot the blob if it has been modified since the specified date/time + // If the base blob has not been modified, the Blob service returns status code 412 (Precondition Failed). + IfModifiedSince *string + + // A DateTime value which will only snapshot the blob if it has not been modified since the specified date/time + // If the base blob has been modified, the Blob service returns status code 412 (Precondition Failed). + IfUnmodifiedSince *string + + // An ETag value to snapshot the blob only if its ETag value matches the value specified. + // If the values do not match, the Blob service returns status code 412 (Precondition Failed). + IfMatch *string + + // An ETag value for this conditional header to snapshot the blob only if its ETag value + // does not match the value specified. + // If the values are identical, the Blob service returns status code 412 (Precondition Failed). + IfNoneMatch *string +} + +type SnapshotResponse struct { + HttpResponse *http.Response + + // The ETag of the snapshot + ETag string + + // A DateTime value that uniquely identifies the snapshot. + // The value of this header indicates the snapshot version, + // and may be used in subsequent requests to access the snapshot. + SnapshotDateTime string +} + +// Snapshot captures a Snapshot of a given Blob +func (c Client) Snapshot(ctx context.Context, containerName, blobName string, input SnapshotInput) (result SnapshotResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: snapshotOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.ETag = resp.Header.Get("ETag") + result.SnapshotDateTime = resp.Header.Get("x-ms-snapshot") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type snapshotOptions struct { + input SnapshotInput +} + +func (s snapshotOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) + } + + if s.input.EncryptionScope != nil { + headers.Append("x-ms-encryption-scope", *s.input.EncryptionScope) + } + + if s.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *s.input.IfModifiedSince) + } + + if s.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *s.input.IfUnmodifiedSince) + } + + if s.input.IfMatch != nil { + headers.Append("If-Match", *s.input.IfMatch) + } + + if s.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *s.input.IfNoneMatch) + } + + headers.Merge(metadata.SetMetaDataHeaders(s.input.MetaData)) + return headers +} + +func (s snapshotOptions) ToOData() *odata.Query { + return nil +} + +func (s snapshotOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "snapshot") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/snapshot_get_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/snapshot_get_properties.go new file mode 100644 index 000000000000..09e53cf43f19 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/snapshot_get_properties.go @@ -0,0 +1,168 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetSnapshotPropertiesInput struct { + // The ID of the Lease + // This must be specified if a Lease is present on the Blob, else a 403 is returned + LeaseID *string + + // The ID of the Snapshot which should be retrieved + SnapshotID string +} + +// GetSnapshotProperties returns all user-defined metadata, standard HTTP properties, and system properties for +// the specified snapshot of a blob +func (c Client) GetSnapshotProperties(ctx context.Context, containerName, blobName string, input GetSnapshotPropertiesInput) (result GetPropertiesResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + if input.SnapshotID == "" { + err = fmt.Errorf("`input.SnapshotID` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: snapshotGetPropertiesOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.AccessTier = AccessTier(resp.Header.Get("x-ms-access-tier")) + result.AccessTierChangeTime = resp.Header.Get("x-ms-access-tier-change-time") + result.ArchiveStatus = ArchiveStatus(resp.Header.Get("x-ms-archive-status")) + result.BlobCommittedBlockCount = resp.Header.Get("x-ms-blob-committed-block-count") + result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") + result.BlobType = BlobType(resp.Header.Get("x-ms-blob-type")) + result.CacheControl = resp.Header.Get("Cache-Control") + result.ContentDisposition = resp.Header.Get("Content-Disposition") + result.ContentEncoding = resp.Header.Get("Content-Encoding") + result.ContentLanguage = resp.Header.Get("Content-Language") + result.ContentMD5 = resp.Header.Get("Content-MD5") + result.ContentType = resp.Header.Get("Content-Type") + result.CopyCompletionTime = resp.Header.Get("x-ms-copy-completion-time") + result.CopyDestinationSnapshot = resp.Header.Get("x-ms-copy-destination-snapshot") + result.CopyID = resp.Header.Get("x-ms-copy-id") + result.CopyProgress = resp.Header.Get("x-ms-copy-progress") + result.CopySource = resp.Header.Get("x-ms-copy-source") + result.CopyStatus = CopyStatus(resp.Header.Get("x-ms-copy-status")) + result.CopyStatusDescription = resp.Header.Get("x-ms-copy-status-description") + result.CreationTime = resp.Header.Get("x-ms-creation-time") + result.ETag = resp.Header.Get("Etag") + result.LastModified = resp.Header.Get("Last-Modified") + result.LeaseDuration = LeaseDuration(resp.Header.Get("x-ms-lease-duration")) + result.LeaseState = LeaseState(resp.Header.Get("x-ms-lease-state")) + result.LeaseStatus = LeaseStatus(resp.Header.Get("x-ms-lease-status")) + result.MetaData = metadata.ParseFromHeaders(resp.Header) + + if v := resp.Header.Get("Content-Length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("parsing `Content-Length` header value %q: %+v", v, innerErr) + } + + result.ContentLength = int64(i) + } + + if v := resp.Header.Get("x-ms-access-tier-inferred"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-access-tier-inferred` header value %q: %+v", v, innerErr) + return + } + + result.AccessTierInferred = b + } + + if v := resp.Header.Get("x-ms-incremental-copy"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("parsing `x-ms-incremental-copy` header value %q: %+v", v, innerErr) + return + } + + result.IncrementalCopy = b + } + + if v := resp.Header.Get("x-ms-server-encrypted"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("parsing `\"x-ms-server-encrypted` header value %q: %+v", v, innerErr) + return + } + + result.ServerEncrypted = b + } + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + if result.HttpResponse != nil { + } + + return +} + +type snapshotGetPropertiesOptions struct { + input GetSnapshotPropertiesInput +} + +func (s snapshotGetPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) + } + return headers +} + +func (s snapshotGetPropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (s snapshotGetPropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("snapshot", s.input.SnapshotID) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/undelete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/undelete.go new file mode 100644 index 000000000000..149971fc1035 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/undelete.go @@ -0,0 +1,76 @@ +package blobs + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type UndeleteResponse struct { + HttpResponse *http.Response +} + +// Undelete restores the contents and metadata of soft deleted blob and any associated soft deleted snapshots. +func (c Client) Undelete(ctx context.Context, containerName, blobName string) (result UndeleteResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + if strings.ToLower(containerName) != containerName { + err = fmt.Errorf("`containerName` must be a lower-cased string") + return + } + + if blobName == "" { + err = fmt.Errorf("`blobName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: undeleteOptions{}, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type undeleteOptions struct{} + +func (u undeleteOptions) ToHeaders() *client.Headers { + return nil +} + +func (u undeleteOptions) ToOData() *odata.Query { + return nil +} + +func (u undeleteOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "undelete") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/version.go new file mode 100644 index 000000000000..da934d3c1001 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs/version.go @@ -0,0 +1,5 @@ +package blobs + +// APIVersion is the version of the API used for all Storage API Operations +const apiVersion = "2023-11-03" +const componentName = "blob/blobs" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/README.md similarity index 50% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/README.md rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/README.md index 9d375483ee8e..6283cd7f7113 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/README.md @@ -1,4 +1,4 @@ -## Blob Storage Container SDK for API version 2020-08-04 +## Blob Storage Container SDK for API version 2023-11-03 This package allows you to interact with the Containers Blob Storage API @@ -17,26 +17,33 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers" ) func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." containerName := "mycontainer" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - containersClient := containers.New() - containersClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + containersClient, err := containers.NewWithBaseUri(fmt.Sprintf("https://%s.blob.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + containersClient.Client.SetAuthorizer(auth) ctx := context.TODO() createInput := containers.CreateInput{ AccessLevel: containers.Private, } - if _, err := containersClient.Create(ctx, accountName, containerName, createInput); err != nil { + if _, err := containersClient.Create(ctx, containerName, createInput); err != nil { return fmt.Errorf("Error creating Container: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/api.go new file mode 100644 index 000000000000..0c6b65a274b5 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/api.go @@ -0,0 +1,20 @@ +package containers + +import ( + "context" +) + +type StorageContainer interface { + Create(ctx context.Context, containerName string, input CreateInput) (CreateResponse, error) + Delete(ctx context.Context, containerName string) (DeleteResponse, error) + GetProperties(ctx context.Context, containerName string, input GetPropertiesInput) (GetPropertiesResponse, error) + AcquireLease(ctx context.Context, containerName string, input AcquireLeaseInput) (AcquireLeaseResponse, error) + BreakLease(ctx context.Context, containerName string, input BreakLeaseInput) (BreakLeaseResponse, error) + ChangeLease(ctx context.Context, containerName string, input ChangeLeaseInput) (ChangeLeaseResponse, error) + ReleaseLease(ctx context.Context, containerName string, input ReleaseLeaseInput) (ReleaseLeaseResponse, error) + RenewLease(ctx context.Context, containerName string, input RenewLeaseInput) (RenewLeaseResponse, error) + ListBlobs(ctx context.Context, containerName string, input ListBlobsInput) (ListBlobsResponse, error) + GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, containerName string) string + SetAccessControl(ctx context.Context, containerName string, input SetAccessControlInput) (SetAccessControlResponse, error) + SetMetaData(ctx context.Context, containerName string, metaData SetMetaDataInput) (SetMetaDataResponse, error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/client.go new file mode 100644 index 000000000000..ae8c43a21d22 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/client.go @@ -0,0 +1,22 @@ +package containers + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Blob Storage Containers. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/create.go new file mode 100644 index 000000000000..f47c4cf1f422 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/create.go @@ -0,0 +1,135 @@ +package containers + +import ( + "bytes" + "context" + "encoding/xml" + "fmt" + "io" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type CreateInput struct { + // Specifies whether data in the container may be accessed publicly and the level of access + AccessLevel AccessLevel + + // The encryption scope to set as the default on the container. + DefaultEncryptionScope string + + // Setting this to ture indicates that every blob that's uploaded to this container uses the default encryption scope. + EncryptionScopeOverrideDisabled bool + + // A name-value pair to associate with the container as metadata. + MetaData map[string]string +} + +type CreateResponse struct { + HttpResponse *http.Response +} + +// Create creates a new container under the specified account. +// If the container with the same name already exists, the operation fails. +func (c Client) Create(ctx context.Context, containerName string, input CreateInput) (result CreateResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %+v", err) + return + } + + // Retry the container creation if a conflicting container is still in the process of being deleted + retryFunc := func(resp *http.Response, _ *odata.OData) (bool, error) { + if resp != nil { + if response.WasStatusCode(resp, http.StatusConflict) { + // TODO: move this error response parsing to a common helper function + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return false, fmt.Errorf("could not parse response body") + } + resp.Body.Close() + respBody = bytes.TrimPrefix(respBody, []byte("\xef\xbb\xbf")) + res := ErrorResponse{} + if err = xml.Unmarshal(respBody, &res); err != nil { + return false, err + } + resp.Body = io.NopCloser(bytes.NewBuffer(respBody)) + if res.Code != nil { + return strings.Contains(*res.Code, "ContainerBeingDeleted"), nil + } + } + } + return false, nil + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: createOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s", containerName), + RetryFunc: retryFunc, + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = createOptions{} + +type createOptions struct { + input CreateInput +} + +func (o createOptions) ToHeaders() *client.Headers { + headers := containerOptions{ + metaData: o.input.MetaData, + }.ToHeaders() + + // If this header is not included in the request, container data is private to the account owner. + if o.input.AccessLevel != Private { + headers.Append("x-ms-blob-public-access", string(o.input.AccessLevel)) + } + + if o.input.DefaultEncryptionScope != "" { + // These two headers must be used together. + headers.Append("x-ms-default-encryption-scope", o.input.DefaultEncryptionScope) + headers.Append("x-ms-deny-encryption-scope-override", fmt.Sprintf("%t", o.input.EncryptionScopeOverrideDisabled)) + } + + return headers +} + +func (createOptions) ToOData() *odata.Query { + return nil +} + +func (createOptions) ToQuery() *client.QueryParams { + return containerOptions{}.ToQuery() +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/delete.go new file mode 100644 index 000000000000..d654e4aba8a7 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/delete.go @@ -0,0 +1,50 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type DeleteResponse struct { + HttpResponse *http.Response +} + +// Delete marks the specified container for deletion. +// The container and any blobs contained within it are later deleted during garbage collection. +func (c Client) Delete(ctx context.Context, containerName string) (result DeleteResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: containerOptions{}, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/get_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/get_properties.go new file mode 100644 index 000000000000..ca97cf83a7f9 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/get_properties.go @@ -0,0 +1,110 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetPropertiesInput struct { + LeaseId string +} + +type GetPropertiesResponse struct { + ContainerProperties + HttpResponse *http.Response +} + +// GetProperties returns the properties for this Container without a Lease +func (c Client) GetProperties(ctx context.Context, containerName string, input GetPropertiesInput) (result GetPropertiesResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getPropertiesOptions{ + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.DefaultEncryptionScope = resp.Header.Get("x-ms-default-encryption-scope") + result.LeaseStatus = LeaseStatus(resp.Header.Get("x-ms-lease-status")) + result.LeaseState = LeaseState(resp.Header.Get("x-ms-lease-state")) + if result.LeaseStatus == Locked { + duration := LeaseDuration(resp.Header.Get("x-ms-lease-duration")) + result.LeaseDuration = &duration + } + + // If this header is not returned in the response, the container is private to the account owner. + accessLevel := resp.Header.Get("x-ms-blob-public-access") + if accessLevel != "" { + result.AccessLevel = AccessLevel(accessLevel) + } else { + result.AccessLevel = Private + } + + // we can't necessarily use strconv.ParseBool here since this could be nil (only in some API versions) + result.EncryptionScopeOverrideDisabled = strings.EqualFold(resp.Header.Get("x-ms-deny-encryption-scope-override"), "true") + result.HasImmutabilityPolicy = strings.EqualFold(resp.Header.Get("x-ms-has-immutability-policy"), "true") + result.HasLegalHold = strings.EqualFold(resp.Header.Get("x-ms-has-legal-hold"), "true") + + result.MetaData = metadata.ParseFromHeaders(resp.Header) + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = getPropertiesOptions{} + +type getPropertiesOptions struct { + leaseId string +} + +func (o getPropertiesOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. + // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. + if o.leaseId != "" { + headers.Append("x-ms-lease-id", o.leaseId) + } + + return headers +} + +func (getPropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (getPropertiesOptions) ToQuery() *client.QueryParams { + return containerOptions{}.ToQuery() +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_acquire.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_acquire.go new file mode 100644 index 000000000000..a863c1498247 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_acquire.go @@ -0,0 +1,103 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type AcquireLeaseInput struct { + // Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. + // A non-infinite lease can be between 15 and 60 seconds + LeaseDuration int + + ProposedLeaseID string +} + +type AcquireLeaseResponse struct { + AcquireLeaseModel + HttpResponse *http.Response +} + +type AcquireLeaseModel struct { + LeaseID string +} + +// AcquireLease establishes and manages a lock on a container for delete operations. +func (c Client) AcquireLease(ctx context.Context, containerName string, input AcquireLeaseInput) (result AcquireLeaseResponse, err error) { + if containerName == "" { + return result, fmt.Errorf("`containerName` cannot be an empty string") + } + // An infinite lease duration is -1 seconds. A non-infinite lease can be between 15 and 60 seconds + if input.LeaseDuration != -1 && (input.LeaseDuration <= 15 || input.LeaseDuration >= 60) { + return result, fmt.Errorf("`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: acquireLeaseOptions{ + leaseDuration: input.LeaseDuration, + proposedLeaseId: input.ProposedLeaseID, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.LeaseID = resp.Header.Get("x-ms-lease-id") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = acquireLeaseOptions{} + +type acquireLeaseOptions struct { + leaseDuration int + proposedLeaseId string +} + +func (o acquireLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + headers.Append("x-ms-lease-action", "acquire") + headers.Append("x-ms-lease-duration", fmt.Sprintf("%d", o.leaseDuration)) + + if o.proposedLeaseId != "" { + headers.Append("x-ms-proposed-lease-id", o.proposedLeaseId) + } + + return headers +} + +func (o acquireLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (o acquireLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_break.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_break.go new file mode 100644 index 000000000000..b141e2582f00 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_break.go @@ -0,0 +1,114 @@ +package containers + +import ( + "context" + "fmt" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "net/http" + "strconv" +) + +type BreakLeaseInput struct { + // For a break operation, proposed duration the lease should continue + // before it is broken, in seconds, between 0 and 60. + // This break period is only used if it is shorter than the time remaining on the lease. + // If longer, the time remaining on the lease is used. + // A new lease will not be available before the break period has expired, + // but the lease may be held for longer than the break period. + // If this header does not appear with a break operation, a fixed-duration lease breaks + // after the remaining lease period elapses, and an infinite lease breaks immediately. + BreakPeriod *int + + LeaseID string +} + +type BreakLeaseResponse struct { + BreakLeaseModel + HttpResponse *http.Response +} + +type BreakLeaseModel struct { + // Approximate time remaining in the lease period, in seconds. + // If the break is immediate, 0 is returned. + LeaseTime int +} + +// BreakLease breaks a lock based on it's Lease ID +func (c Client) BreakLease(ctx context.Context, containerName string, input BreakLeaseInput) (result BreakLeaseResponse, err error) { + if containerName == "" { + return result, fmt.Errorf("`containerName` cannot be an empty string") + } + if input.LeaseID == "" { + return result, fmt.Errorf("`input.LeaseID` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: breakLeaseOptions{ + breakPeriod: input.BreakPeriod, + leaseId: input.LeaseID, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + if leaseTimeRaw := resp.Header.Get("x-ms-lease-time"); leaseTimeRaw != "" { + if leaseTime, err := strconv.Atoi(leaseTimeRaw); err == nil { + result.LeaseTime = leaseTime + } + } + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = breakLeaseOptions{} + +type breakLeaseOptions struct { + breakPeriod *int + leaseId string +} + +func (o breakLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + headers.Append("x-ms-lease-action", "break") + headers.Append("x-ms-lease-id", o.leaseId) + + if o.breakPeriod != nil { + headers.Append("x-ms-lease-break-period", fmt.Sprintf("%d", *o.breakPeriod)) + } + + return headers +} + +func (o breakLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (o breakLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_change.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_change.go new file mode 100644 index 000000000000..1c1d7321066d --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_change.go @@ -0,0 +1,102 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ChangeLeaseInput struct { + ExistingLeaseID string + ProposedLeaseID string +} + +type ChangeLeaseResponse struct { + ChangeLeaseModel + HttpResponse *http.Response +} + +type ChangeLeaseModel struct { + LeaseID string +} + +// ChangeLease changes the lock from one Lease ID to another Lease ID +func (c Client) ChangeLease(ctx context.Context, containerName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + if input.ExistingLeaseID == "" { + err = fmt.Errorf("`input.ExistingLeaseID` cannot be an empty string") + return + } + if input.ProposedLeaseID == "" { + err = fmt.Errorf("`input.ProposedLeaseID` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: changeLeaseOptions{ + existingLeaseId: input.ExistingLeaseID, + proposedLeaseId: input.ProposedLeaseID, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.LeaseID = resp.Header.Get("x-ms-lease-id") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = changeLeaseOptions{} + +type changeLeaseOptions struct { + existingLeaseId string + proposedLeaseId string +} + +func (o changeLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + headers.Append("x-ms-lease-action", "change") + headers.Append("x-ms-lease-id", o.existingLeaseId) + headers.Append("x-ms-proposed-lease-id", o.proposedLeaseId) + + return headers +} + +func (o changeLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (o changeLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_release.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_release.go new file mode 100644 index 000000000000..cdff4e2cf9ce --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_release.go @@ -0,0 +1,85 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ReleaseLeaseInput struct { + LeaseId string +} + +type ReleaseLeaseResponse struct { + HttpResponse *http.Response +} + +// ReleaseLease releases the lock based on the Lease ID +func (c Client) ReleaseLease(ctx context.Context, containerName string, input ReleaseLeaseInput) (result ReleaseLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + if input.LeaseId == "" { + err = fmt.Errorf("`input.LeaseId` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: releaseLeaseOptions{ + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = releaseLeaseOptions{} + +type releaseLeaseOptions struct { + leaseId string +} + +func (o releaseLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + headers.Append("x-ms-lease-action", "release") + headers.Append("x-ms-lease-id", o.leaseId) + + return headers +} + +func (o releaseLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (o releaseLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_renew.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_renew.go new file mode 100644 index 000000000000..38c948689996 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/lease_renew.go @@ -0,0 +1,85 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type RenewLeaseInput struct { + LeaseId string +} + +type RenewLeaseResponse struct { + HttpResponse *http.Response +} + +// RenewLease renews the lock based on the Lease ID +func (c Client) RenewLease(ctx context.Context, containerName string, input RenewLeaseInput) (result RenewLeaseResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + if input.LeaseId == "" { + err = fmt.Errorf("`input.LeaseId` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: renewLeaseOptions{ + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = renewLeaseOptions{} + +type renewLeaseOptions struct { + leaseId string +} + +func (o renewLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + headers.Append("x-ms-lease-action", "renew") + headers.Append("x-ms-lease-id", o.leaseId) + + return headers +} + +func (o renewLeaseOptions) ToOData() *odata.Query { + return nil +} + +func (o renewLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/list_blobs.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/list_blobs.go new file mode 100644 index 000000000000..86ddc7c0a9df --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/list_blobs.go @@ -0,0 +1,177 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ListBlobsInput struct { + Delimiter *string + Include *[]Dataset + Marker *string + MaxResults *int + Prefix *string +} + +type ListBlobsResponse struct { + ListBlobsResult + + HttpResponse *http.Response +} + +type ListBlobsResult struct { + Delimiter string `xml:"Delimiter"` + Marker string `xml:"Marker"` + MaxResults int `xml:"MaxResults"` + NextMarker *string `xml:"NextMarker,omitempty"` + Prefix string `xml:"Prefix"` + Blobs Blobs `xml:"Blobs"` +} + +type Blobs struct { + Blobs []BlobDetails `xml:"Blob"` + BlobPrefix *BlobPrefix `xml:"BlobPrefix"` +} + +type BlobDetails struct { + Name string `xml:"Name"` + Deleted bool `xml:"Deleted,omitempty"` + MetaData map[string]interface{} `map:"Metadata,omitempty"` + Properties *BlobProperties `xml:"Properties,omitempty"` + Snapshot *string `xml:"Snapshot,omitempty"` +} + +type BlobProperties struct { + AccessTier *string `xml:"AccessTier,omitempty"` + AccessTierInferred *bool `xml:"AccessTierInferred,omitempty"` + AccessTierChangeTime *string `xml:"AccessTierChangeTime,omitempty"` + BlobType *string `xml:"BlobType,omitempty"` + BlobSequenceNumber *string `xml:"x-ms-blob-sequence-number,omitempty"` + CacheControl *string `xml:"Cache-Control,omitempty"` + ContentEncoding *string `xml:"ContentEncoding,omitempty"` + ContentLanguage *string `xml:"Content-Language,omitempty"` + ContentLength *int64 `xml:"Content-Length,omitempty"` + ContentMD5 *string `xml:"Content-MD5,omitempty"` + ContentType *string `xml:"Content-Type,omitempty"` + CopyCompletionTime *string `xml:"CopyCompletionTime,omitempty"` + CopyId *string `xml:"CopyId,omitempty"` + CopyStatus *string `xml:"CopyStatus,omitempty"` + CopySource *string `xml:"CopySource,omitempty"` + CopyProgress *string `xml:"CopyProgress,omitempty"` + CopyStatusDescription *string `xml:"CopyStatusDescription,omitempty"` + CreationTime *string `xml:"CreationTime,omitempty"` + ETag *string `xml:"Etag,omitempty"` + DeletedTime *string `xml:"DeletedTime,omitempty"` + IncrementalCopy *bool `xml:"IncrementalCopy,omitempty"` + LastModified *string `xml:"Last-Modified,omitempty"` + LeaseDuration *string `xml:"LeaseDuration,omitempty"` + LeaseState *string `xml:"LeaseState,omitempty"` + LeaseStatus *string `xml:"LeaseStatus,omitempty"` + RemainingRetentionDays *string `xml:"RemainingRetentionDays,omitempty"` + ServerEncrypted *bool `xml:"ServerEncrypted,omitempty"` +} + +type BlobPrefix struct { + Name string `xml:"Name"` +} + +// ListBlobs lists the blobs matching the specified query within the specified Container +func (c Client) ListBlobs(ctx context.Context, containerName string, input ListBlobsInput) (result ListBlobsResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + if input.MaxResults != nil && (*input.MaxResults <= 0 || *input.MaxResults > 5000) { + err = fmt.Errorf("`input.MaxResults` can either be nil or between 0 and 5000") + return + } + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: listBlobsOptions{ + delimiter: input.Delimiter, + include: input.Include, + marker: input.Marker, + maxResults: input.MaxResults, + prefix: input.Prefix, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = listBlobsOptions{} + +type listBlobsOptions struct { + delimiter *string + include *[]Dataset + marker *string + maxResults *int + prefix *string +} + +func (o listBlobsOptions) ToHeaders() *client.Headers { + return nil +} + +func (o listBlobsOptions) ToOData() *odata.Query { + return nil +} + +func (o listBlobsOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "list") + + if o.delimiter != nil { + query.Append("delimiter", *o.delimiter) + } + if o.include != nil { + vals := make([]string, 0) + for _, v := range *o.include { + vals = append(vals, string(v)) + } + include := strings.Join(vals, ",") + query.Append("include", include) + } + if o.marker != nil { + query.Append("marker", *o.marker) + } + if o.maxResults != nil { + query.Append("maxresults", fmt.Sprintf("%d", *o.maxResults)) + } + if o.prefix != nil { + query.Append("prefix", *o.prefix) + } + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/models.go similarity index 74% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/models.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/models.go index adba36818aa1..94c3b86b2916 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/models.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/models.go @@ -1,6 +1,6 @@ package containers -import "github.com/Azure/go-autorest/autorest" +import "encoding/xml" type AccessLevel string @@ -21,15 +21,15 @@ var ( ) type ContainerProperties struct { - autorest.Response - - AccessLevel AccessLevel - LeaseStatus LeaseStatus - LeaseState LeaseState - LeaseDuration *LeaseDuration - MetaData map[string]string - HasImmutabilityPolicy bool - HasLegalHold bool + AccessLevel AccessLevel + DefaultEncryptionScope string + EncryptionScopeOverrideDisabled bool + LeaseStatus LeaseStatus + LeaseState LeaseState + LeaseDuration *LeaseDuration + MetaData map[string]string + HasImmutabilityPolicy bool + HasLegalHold bool } type Dataset string @@ -43,8 +43,9 @@ var ( ) type ErrorResponse struct { - Code *string `xml:"Code"` - Message *string `xml:"Message"` + XMLName xml.Name `xml:"Error"` + Code *string `xml:"Code"` + Message *string `xml:"Message"` } type LeaseDuration string diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/options.go new file mode 100644 index 000000000000..73fadf16ae8f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/options.go @@ -0,0 +1,35 @@ +package containers + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +var _ client.Options = containerOptions{} + +type containerOptions struct { + metaData map[string]string +} + +func (o containerOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + metaDataHeaders := make(map[string]interface{}) + metadata.SetIntoHeaders(metaDataHeaders, o.metaData) + for k, v := range metaDataHeaders { + headers.Append(k, v.(string)) + } + + return headers +} + +func (containerOptions) ToOData() *odata.Query { + return nil +} + +func (containerOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "container") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/resource_id.go new file mode 100644 index 000000000000..691360246ed8 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/resource_id.go @@ -0,0 +1,81 @@ +package containers + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// GetResourceManagerResourceID returns the Resource Manager specific +// ResourceID for a specific Storage Container +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, containerName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/blobServices/default/containers/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, containerName) +} + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = ContainerId{} + +type ContainerId struct { + // AccountId specifies the ID of the Storage Account where this Container exists. + AccountId accounts.AccountId + + // ContainerName specifies the name of this Container. + ContainerName string +} + +func NewContainerID(accountId accounts.AccountId, containerName string) ContainerId { + return ContainerId{ + AccountId: accountId, + ContainerName: containerName, + } +} + +func (b ContainerId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.ContainerName) +} + +func (b ContainerId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Container %q (%s)", b.ContainerName, strings.Join(components, " / ")) +} + +// ParseContainerID parses `input` into a Container ID using a known `domainSuffix` +func ParseContainerID(input, domainSuffix string) (*ContainerId, error) { + // example: https://foo.blob.core.windows.net/Bar + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.BlobSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.BlobSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) + } + + containerName := strings.TrimPrefix(uri.Path, "/") + return &ContainerId{ + AccountId: *account, + ContainerName: containerName, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/set_acl.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/set_acl.go new file mode 100644 index 000000000000..280ad4e391ff --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/set_acl.go @@ -0,0 +1,93 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type SetAccessControlInput struct { + AccessLevel AccessLevel + LeaseId string +} + +type SetAccessControlResponse struct { + HttpResponse *http.Response +} + +// SetAccessControl sets the Access Control for a Container without a Lease ID +// NOTE: The SetAccessControl operation only supports Shared Key authorization. +func (c Client) SetAccessControl(ctx context.Context, containerName string, input SetAccessControlInput) (result SetAccessControlResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setAccessControlListOptions{ + accessLevel: input.AccessLevel, + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = setAccessControlListOptions{} + +type setAccessControlListOptions struct { + accessLevel AccessLevel + leaseId string +} + +func (o setAccessControlListOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + // If this header is not included in the request, container data is private to the account owner. + if o.accessLevel != Private { + headers.Append("x-ms-blob-public-access", string(o.accessLevel)) + } + + // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. + // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. + if o.leaseId != "" { + headers.Append("x-ms-lease-id", o.leaseId) + } + + return headers +} + +func (o setAccessControlListOptions) ToOData() *odata.Query { + return nil +} + +func (o setAccessControlListOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "acl") + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/set_metadata.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/set_metadata.go new file mode 100644 index 000000000000..3f8bb07e2819 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/set_metadata.go @@ -0,0 +1,94 @@ +package containers + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SetMetaDataInput struct { + MetaData map[string]string + LeaseId string +} + +type SetMetaDataResponse struct { + HttpResponse *http.Response +} + +// SetMetaData sets the specified MetaData on the Container without a Lease ID +func (c Client) SetMetaData(ctx context.Context, containerName string, input SetMetaDataInput) (result SetMetaDataResponse, err error) { + if containerName == "" { + err = fmt.Errorf("`containerName` cannot be an empty string") + return + } + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %s", err) + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setMetaDataOptions{ + metaData: input.MetaData, + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +var _ client.Options = setMetaDataOptions{} + +type setMetaDataOptions struct { + metaData map[string]string + leaseId string +} + +func (o setMetaDataOptions) ToHeaders() *client.Headers { + headers := containerOptions{ + metaData: o.metaData, + }.ToHeaders() + + // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. + // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. + if o.leaseId != "" { + headers.Append("x-ms-lease-id", o.leaseId) + } + + return headers +} + +func (o setMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (o setMetaDataOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "metadata") + return query +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/version.go new file mode 100644 index 000000000000..1806c68f4143 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers/version.go @@ -0,0 +1,4 @@ +package containers + +const apiVersion = "2023-11-03" +const componentName = "blob/containers" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/README.md new file mode 100644 index 000000000000..ac35149dab39 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/README.md @@ -0,0 +1,53 @@ +## Data Lake Storage Gen2 File Systems SDK for API version 2023-11-03 + +This package allows you to interact with the Data Lake Storage Gen2 File Systems API + +### Supported Authorizers + +* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) + +### Example Usage + +```go +package main + +import ( + "context" + "fmt" + + "github.com/hashicorp/go-azure-helpers/authentication" + "github.com/hashicorp/go-azure-helpers/sender" + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems" +) + +func Example() error { + accountName := "storageaccount1" + fileSystemName := "filesystem1" + storageAccountKey := "ABC123...." + domainSuffix := "core.windows.net" + + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + fileSystemsClient, err := filesystems.NewWithBaseUri(fmt.Sprintf("https://%s.dfs.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + fileSystemsClient.Client.SetAuthorizer(auth) + + input := filesystems.CreateInput{ + Properties: map[string]string{}, + } + + ctx := context.Background() + if _, err = fileSystemsClient.Create(ctx, fileSystemName, input); err != nil { + return fmt.Errorf("Error creating: %s", err) + } + + return nil +} +``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/client.go new file mode 100644 index 000000000000..a1217334bdcc --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/client.go @@ -0,0 +1,23 @@ +package filesystems + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Data Lake Store Filesystems. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/create.go new file mode 100644 index 000000000000..5bf1b66b5251 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/create.go @@ -0,0 +1,83 @@ +package filesystems + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type CreateInput struct { + // A map of base64-encoded strings to store as user-defined properties with the File System + // Note that items may only contain ASCII characters in the ISO-8859-1 character set. + // This automatically gets converted to a comma-separated list of name and + // value pairs before sending to the API + Properties map[string]string +} + +type CreateResponse struct { + HttpResponse *http.Response +} + +// Create creates a Data Lake Store Gen2 FileSystem within a Storage Account +func (c Client) Create(ctx context.Context, fileSystemName string, input CreateInput) (result CreateResponse, err error) { + if fileSystemName == "" { + err = fmt.Errorf("`fileSystemName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: createOptions{ + properties: input.Properties, + }, + + Path: fmt.Sprintf("/%s", fileSystemName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type createOptions struct { + properties map[string]string +} + +func (o createOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + props := buildProperties(o.properties) + if props != "" { + headers.Append("x-ms-properties", props) + } + + return headers +} + +func (createOptions) ToOData() *odata.Query { + return nil +} + +func (createOptions) ToQuery() *client.QueryParams { + return fileSystemOptions{}.ToQuery() +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/delete.go new file mode 100644 index 000000000000..6900f2899d35 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/delete.go @@ -0,0 +1,49 @@ +package filesystems + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type DeleteResponse struct { + HttpResponse *http.Response +} + +// Delete deletes a Data Lake Store Gen2 FileSystem within a Storage Account +func (c Client) Delete(ctx context.Context, fileSystemName string) (result DeleteResponse, err error) { + if fileSystemName == "" { + err = fmt.Errorf("`fileSystemName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: fileSystemOptions{}, + Path: fmt.Sprintf("/%s", fileSystemName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/helpers.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/helpers.go similarity index 90% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/helpers.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/helpers.go index 605ed425929d..7822a128154e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/helpers.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/helpers.go @@ -29,7 +29,7 @@ func parseProperties(input string) (*map[string]string, error) { // as such we can't string split on that -_- position := strings.Index(propertyRaw, "=") if position < 0 { - return nil, fmt.Errorf("Expected there to be an equals in the key value pair: %q", propertyRaw) + return nil, fmt.Errorf("expected an equal sign in the key value pair: %q", propertyRaw) } key := propertyRaw[0:position] diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/options.go new file mode 100644 index 000000000000..aee33a0c4595 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/options.go @@ -0,0 +1,32 @@ +package filesystems + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = fileSystemOptions{} + +type fileSystemOptions struct { + properties map[string]string +} + +func (o fileSystemOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + props := buildProperties(o.properties) + if props != "" { + headers.Append("x-ms-properties", props) + } + + return headers +} + +func (fileSystemOptions) ToOData() *odata.Query { + return nil +} + +func (fileSystemOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("resource", "filesystem") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/properties_get.go new file mode 100644 index 000000000000..47f394ab6dd2 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/properties_get.go @@ -0,0 +1,71 @@ +package filesystems + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type GetPropertiesResponse struct { + HttpResponse *http.Response + + // A map of base64-encoded strings to store as user-defined properties with the File System + // Note that items may only contain ASCII characters in the ISO-8859-1 character set. + // This automatically gets converted to a comma-separated list of name and + // value pairs before sending to the API + Properties map[string]string + + // Is Hierarchical Namespace Enabled? + NamespaceEnabled bool +} + +// GetProperties gets the properties for a Data Lake Store Gen2 FileSystem within a Storage Account +func (c Client) GetProperties(ctx context.Context, fileSystemName string) (result GetPropertiesResponse, err error) { + if fileSystemName == "" { + err = fmt.Errorf("`fileSystemName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: fileSystemOptions{}, + Path: fmt.Sprintf("/%s", fileSystemName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + propertiesRaw := resp.Header.Get("x-ms-properties") + var properties *map[string]string + properties, err = parseProperties(propertiesRaw) + if err != nil { + return + } + + result.Properties = *properties + result.NamespaceEnabled = strings.EqualFold(resp.Header.Get("x-ms-namespace-enabled"), "true") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/properties_set.go new file mode 100644 index 000000000000..775807aeb338 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/properties_set.go @@ -0,0 +1,103 @@ +package filesystems + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type SetPropertiesInput struct { + // A map of base64-encoded strings to store as user-defined properties with the File System + // Note that items may only contain ASCII characters in the ISO-8859-1 character set. + // This automatically gets converted to a comma-separated list of name and + // value pairs before sending to the API + Properties map[string]string + + // Optional - A date and time value. + // Specify this header to perform the operation only if the resource has been modified since the specified date and time. + IfModifiedSince *string + + // Optional - A date and time value. + // Specify this header to perform the operation only if the resource has not been modified since the specified date and time. + IfUnmodifiedSince *string +} + +type SetPropertiesResponse struct { + HttpResponse *http.Response +} + +// SetProperties sets the Properties for a Data Lake Store Gen2 FileSystem within a Storage Account +func (c Client) SetProperties(ctx context.Context, fileSystemName string, input SetPropertiesInput) (result SetPropertiesResponse, err error) { + if fileSystemName == "" { + err = fmt.Errorf("`fileSystemName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPatch, + OptionsObject: setPropertiesOptions{ + properties: input.Properties, + ifUnmodifiedSince: input.IfUnmodifiedSince, + ifModifiedSince: input.IfModifiedSince, + }, + + Path: fmt.Sprintf("/%s", fileSystemName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type setPropertiesOptions struct { + properties map[string]string + ifModifiedSince *string + ifUnmodifiedSince *string +} + +func (o setPropertiesOptions) ToHeaders() *client.Headers { + + headers := &client.Headers{} + props := buildProperties(o.properties) + if props != "" { + headers.Append("x-ms-properties", props) + } + + if o.ifModifiedSince != nil { + headers.Append("If-Modified-Since", *o.ifModifiedSince) + } + if o.ifUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *o.ifUnmodifiedSince) + } + + return headers +} + +func (setPropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (setPropertiesOptions) ToQuery() *client.QueryParams { + return fileSystemOptions{}.ToQuery() +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/resource_id.go new file mode 100644 index 000000000000..60670df684a1 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/resource_id.go @@ -0,0 +1,81 @@ +package filesystems + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// GetResourceManagerResourceID returns the Resource Manager specific +// ResourceID for a specific Data Lake FileSystem +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, fileSystemName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/blobServices/default/containers/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, fileSystemName) +} + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = FileSystemId{} + +type FileSystemId struct { + // AccountId specifies the ID of the Storage Account where this Data Lake FileSystem exists. + AccountId accounts.AccountId + + // FileSystemName specifies the name of this Data Lake FileSystem. + FileSystemName string +} + +func NewFileSystemID(accountId accounts.AccountId, fileSystemName string) FileSystemId { + return FileSystemId{ + AccountId: accountId, + FileSystemName: fileSystemName, + } +} + +func (b FileSystemId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.FileSystemName) +} + +func (b FileSystemId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("File System %q (%s)", b.FileSystemName, strings.Join(components, " / ")) +} + +// ParseFileSystemID parses `input` into a File System ID using a known `domainSuffix` +func ParseFileSystemID(input, domainSuffix string) (*FileSystemId, error) { + // example: https://foo.dfs.core.windows.net/Bar + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.DataLakeStoreSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.DataLakeStoreSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) + } + + fileSystemName := segments[0] + return &FileSystemId{ + AccountId: *account, + FileSystemName: fileSystemName, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/version.go new file mode 100644 index 000000000000..954c9cac5a64 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems/version.go @@ -0,0 +1,4 @@ +package filesystems + +const apiVersion = "2023-11-03" +const componentName = "datalakestore/filesystems" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/client.go new file mode 100644 index 000000000000..e0cb42776bf5 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/client.go @@ -0,0 +1,22 @@ +package paths + +import ( + "fmt" + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Data Lake Storage Path +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/create.go new file mode 100644 index 000000000000..8db9b66413eb --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/create.go @@ -0,0 +1,77 @@ +package paths + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type PathResource string + +const PathResourceFile PathResource = "file" +const PathResourceDirectory PathResource = "directory" + +type CreateInput struct { + Resource PathResource +} + +type CreateResponse struct { + HttpResponse *http.Response +} + +// Create creates a Data Lake Store Gen2 Path within a Storage Account +func (c Client) Create(ctx context.Context, fileSystemName string, path string, input CreateInput) (result CreateResponse, err error) { + + if fileSystemName == "" { + return result, fmt.Errorf("`fileSystemName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateInput{ + Resource: input.Resource, + }, + + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return result, err + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return result, err + } + + return +} + +func (c CreateInput) ToHeaders() *client.Headers { + return nil +} + +func (c CreateInput) ToOData() *odata.Query { + return nil +} + +func (c CreateInput) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("resource", string(c.Resource)) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/delete.go new file mode 100644 index 000000000000..990be5157dc9 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/delete.go @@ -0,0 +1,48 @@ +package paths + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type DeleteResponse struct { + HttpResponse *http.Response +} + +// Delete deletes a Data Lake Store Gen2 FileSystem within a Storage Account +func (c Client) Delete(ctx context.Context, fileSystemName string, path string) (result DeleteResponse, err error) { + + if fileSystemName == "" { + return result, fmt.Errorf("`fileSystemName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodDelete, + OptionsObject: nil, + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), + } + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/helpers.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/helpers.go similarity index 77% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/helpers.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/helpers.go index e6ef6f4bfb9f..08d893c2b81d 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/helpers.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/helpers.go @@ -11,5 +11,5 @@ func parsePathResource(input string) (PathResource, error) { case "directory": return PathResourceDirectory, nil } - return "", fmt.Errorf("Unhandled path resource type %q", input) + return "", fmt.Errorf("unhandled path resource type %q", input) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/properties_get.go new file mode 100644 index 000000000000..f5dcb782a5a4 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/properties_get.go @@ -0,0 +1,109 @@ +package paths + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetPropertiesResponse struct { + HttpResponse *http.Response + + ETag string + LastModified time.Time + // ResourceType is only returned for GetPropertiesActionGetStatus requests + ResourceType PathResource + Owner string + Group string + // ACL is only returned for GetPropertiesActionGetAccessControl requests + ACL string +} + +type GetPropertiesInput struct { + Action GetPropertiesAction +} + +type GetPropertiesAction string + +const ( + GetPropertiesActionGetStatus GetPropertiesAction = "getStatus" + GetPropertiesActionGetAccessControl GetPropertiesAction = "getAccessControl" +) + +// GetProperties gets the properties for a Data Lake Store Gen2 Path in a FileSystem within a Storage Account +func (c Client) GetProperties(ctx context.Context, fileSystemName string, path string, input GetPropertiesInput) (result GetPropertiesResponse, err error) { + if fileSystemName == "" { + err = fmt.Errorf("`fileSystemName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: getPropertyOptions{ + action: input.Action, + }, + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return result, err + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.ResourceType = PathResource(resp.Header.Get("x-ms-resource-type")) + result.ETag = resp.Header.Get("ETag") + + if lastModifiedRaw := resp.Header.Get("Last-Modified"); lastModifiedRaw != "" { + lastModified, err := time.Parse(time.RFC1123, lastModifiedRaw) + if err != nil { + return GetPropertiesResponse{}, err + } + result.LastModified = lastModified + } + + result.Owner = resp.Header.Get("x-ms-owner") + result.Group = resp.Header.Get("x-ms-group") + result.ACL = resp.Header.Get("x-ms-acl") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return result, err + } + + return +} + +type getPropertyOptions struct { + action GetPropertiesAction +} + +func (g getPropertyOptions) ToHeaders() *client.Headers { + return nil +} + +func (g getPropertyOptions) ToOData() *odata.Query { + return nil +} + +func (g getPropertyOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("action", string(g.action)) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/properties_set.go new file mode 100644 index 000000000000..826e0ef46ce9 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/properties_set.go @@ -0,0 +1,107 @@ +package paths + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type SetAccessControlInput struct { + Owner *string + Group *string + ACL *string + + // Optional - A date and time value. + // Specify this header to perform the operation only if the resource has been modified since the specified date and time. + IfModifiedSince *string + + // Optional - A date and time value. + // Specify this header to perform the operation only if the resource has not been modified since the specified date and time. + IfUnmodifiedSince *string +} + +type SetPropertiesResponse struct { + HttpResponse *http.Response +} + +// SetProperties sets the access control properties for a Data Lake Store Gen2 Path within a Storage Account File System +func (c Client) SetAccessControl(ctx context.Context, fileSystemName string, path string, input SetAccessControlInput) (result SetPropertiesResponse, err error) { + if fileSystemName == "" { + err = fmt.Errorf("`fileSystemName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPatch, + OptionsObject: setPropertyOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return result, err + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return result, err + } + + return +} + +type setPropertyOptions struct { + input SetAccessControlInput +} + +func (s setPropertyOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if s.input.ACL != nil { + headers.Append("x-ms-acl", *s.input.ACL) + } + + if s.input.Owner != nil { + headers.Append("x-ms-owner", *s.input.Owner) + } + + if s.input.Group != nil { + headers.Append("x-ms-group", *s.input.Group) + } + + if s.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *s.input.IfModifiedSince) + } + + if s.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *s.input.IfUnmodifiedSince) + } + + return headers +} + +func (s setPropertyOptions) ToOData() *odata.Query { + return nil +} + +func (s setPropertyOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("action", "setAccessControl") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/resource_id.go new file mode 100644 index 000000000000..58570e6abd35 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/resource_id.go @@ -0,0 +1,80 @@ +package paths + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = PathId{} + +type PathId struct { + // AccountId specifies the ID of the Storage Account where this path exists. + AccountId accounts.AccountId + + // FileSystemName specifies the name of the Data Lake FileSystem where this Path exists. + FileSystemName string + + // Path specifies the path in question. + Path string +} + +func NewPathID(accountId accounts.AccountId, fileSystemName, path string) PathId { + return PathId{ + AccountId: accountId, + FileSystemName: fileSystemName, + Path: path, + } +} + +func (b PathId) ID() string { + return fmt.Sprintf("%s/%s/%s", b.AccountId.ID(), b.FileSystemName, b.Path) +} + +func (b PathId) String() string { + components := []string{ + fmt.Sprintf("File System %q", b.FileSystemName), + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Path %q (%s)", b.Path, strings.Join(components, " / ")) +} + +// ParsePathID parses `input` into a Path ID using a known `domainSuffix` +func ParsePathID(input, domainSuffix string) (*PathId, error) { + // example: https://foo.dfs.core.windows.net/Bar/some/path + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.DataLakeStoreSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.DataLakeStoreSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + uriPath := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(uriPath, "/") + if len(segments) < 2 { + return nil, fmt.Errorf("expected the path to contain at least 2 segments but got %d", len(segments)) + } + fileSystemName := segments[0] + path := strings.Join(segments[1:], "/") + return &PathId{ + AccountId: *account, + FileSystemName: fileSystemName, + Path: path, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/version.go new file mode 100644 index 000000000000..70c22f9a4ac0 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths/version.go @@ -0,0 +1,4 @@ +package paths + +const apiVersion = "2023-11-03" +const componentName = "datalakestore/paths" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/README.md new file mode 100644 index 000000000000..d81f7b0c581a --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/README.md @@ -0,0 +1,59 @@ +## File Storage Directories SDK for API version 2023-11-03 + +This package allows you to interact with the Directories File Storage API + +### Supported Authorizers + +* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) +* SharedKeyLite (Blob, File & Queue) + +### Limitations + +* At this time the headers `x-ms-file-permission` and `x-ms-file-attributes` are hard-coded (to `inherit` and `None`, respectively). + +### Example Usage + +```go +package main + +import ( + "context" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories" +) + +func Example() error { + accountName := "storageaccount1" + storageAccountKey := "ABC123...." + shareName := "myshare" + directoryName := "myfiles" + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + directoriesClient, err := directories.NewWithBaseUri(fmt.Sprintf("https://%s.dfs.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + directoriesClient.Client.SetAuthorizer(auth) + + ctx := context.TODO() + metadata := map[string]string{ + "hello": "world", + } + + input := directories.CreateDirectoryInput{ + MetaData: metadata, + } + if _, err := directoriesClient.Create(ctx, shareName, directoryName, input); err != nil { + return fmt.Errorf("Error creating Directory: %s", err) + } + + return nil +} +``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/api.go new file mode 100644 index 000000000000..e46265705c07 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/api.go @@ -0,0 +1,13 @@ +package directories + +import ( + "context" +) + +type StorageDirectory interface { + Delete(ctx context.Context, shareName, path string) (resp DeleteResponse, err error) + GetMetaData(ctx context.Context, shareName, path string) (resp GetMetaDataResponse, err error) + SetMetaData(ctx context.Context, shareName, path string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) + Create(ctx context.Context, shareName, path string, input CreateDirectoryInput) (resp CreateDirectoryResponse, err error) + Get(ctx context.Context, shareName, path string) (resp GetResponse, err error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/client.go new file mode 100644 index 000000000000..9f6af5a1d43f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/client.go @@ -0,0 +1,39 @@ +package directories + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for File Storage Shares. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + + baseClient.Client.AuthorizeRequest = func(ctx context.Context, req *http.Request, authorizer auth.Authorizer) error { + if err := auth.SetAuthHeader(ctx, req, authorizer); err != nil { + return fmt.Errorf("authorizing request: %+v", err) + } + + // Only set this header if OAuth is being used (i.e. not shared key authentication) + if _, ok := authorizer.(*auth.SharedKeyAuthorizer); !ok { + req.Header.Set("x-ms-file-request-intent", "backup") + } + + return nil + } + + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/create.go new file mode 100644 index 000000000000..fdca3cf3f9a9 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/create.go @@ -0,0 +1,123 @@ +package directories + +import ( + "context" + "fmt" + "net/http" + "strings" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type CreateDirectoryInput struct { + // The time at which this file was created at - if omitted, this'll be set to "now" + // This maps to the `x-ms-file-creation-time` field. + // ... Yes I know it says File not Directory, I didn't design the API. + CreatedAt *time.Time + + // The time at which this file was last modified - if omitted, this'll be set to "now" + // This maps to the `x-ms-file-last-write-time` field. + // ... Yes I know it says File not Directory, I didn't design the API. + LastModified *time.Time + + // MetaData is a mapping of key value pairs which should be assigned to this directory + MetaData map[string]string +} + +type CreateDirectoryResponse struct { + HttpResponse *http.Response +} + +// Create creates a new directory under the specified share or parent directory. +func (c Client) Create(ctx context.Context, shareName, path string, input CreateDirectoryInput) (result CreateDirectoryResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %s", err) + return + } + + if path == "" { + err = fmt.Errorf("`path` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", shareName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type CreateOptions struct { + input CreateDirectoryInput +} + +func (c CreateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) + } + + var coalesceDate = func(input *time.Time, defaultVal string) string { + if input == nil { + return defaultVal + } + return input.Format(time.RFC1123) + } + + // ... Yes I know these say File not Directory, I didn't design the API. + headers.Append("x-ms-file-permission", "inherit") // TODO: expose this in future + headers.Append("x-ms-file-attributes", "None") // TODO: expose this in future + headers.Append("x-ms-file-creation-time", coalesceDate(c.input.CreatedAt, "now")) + headers.Append("x-ms-file-last-write-time", coalesceDate(c.input.LastModified, "now")) + + return headers +} + +func (c CreateOptions) ToOData() *odata.Query { + return nil +} + +func (c CreateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/delete.go new file mode 100644 index 000000000000..35b7298307ae --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/delete.go @@ -0,0 +1,62 @@ +package directories + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type DeleteResponse struct { + HttpResponse *http.Response +} + +// Delete removes the specified empty directory +// Note that the directory must be empty before it can be deleted. +func (c Client) Delete(ctx context.Context, shareName, path string) (result DeleteResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if path == "" { + err = fmt.Errorf("`path` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: directoriesOptions{}, + Path: fmt.Sprintf("/%s/%s", shareName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/get.go new file mode 100644 index 000000000000..2aeb03186f08 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/get.go @@ -0,0 +1,74 @@ +package directories + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetResponse struct { + HttpResponse *http.Response + + // A set of name-value pairs that contain metadata for the directory. + MetaData map[string]string + + // The value of this header is set to true if the directory metadata is completely + // encrypted using the specified algorithm. Otherwise, the value is set to false. + DirectoryMetaDataEncrypted bool +} + +// Get returns all system properties for the specified directory, +// and can also be used to check the existence of a directory. +func (c Client) Get(ctx context.Context, shareName, path string) (result GetResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if path == "" { + err = fmt.Errorf("`path` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: directoriesOptions{}, + Path: fmt.Sprintf("/%s/%s", shareName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.DirectoryMetaDataEncrypted = strings.EqualFold(resp.Header.Get("x-ms-server-encrypted"), "true") + result.MetaData = metadata.ParseFromHeaders(resp.Header) + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/metadata_get.go new file mode 100644 index 000000000000..cfefeb5d5726 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/metadata_get.go @@ -0,0 +1,85 @@ +package directories + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetMetaDataResponse struct { + HttpResponse *http.Response + + MetaData map[string]string +} + +// GetMetaData returns all user-defined metadata for the specified directory +func (c Client) GetMetaData(ctx context.Context, shareName, path string) (result GetMetaDataResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if path == "" { + err = fmt.Errorf("`path` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetMetaDataOptions{}, + Path: fmt.Sprintf("/%s/%s", shareName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.MetaData = metadata.ParseFromHeaders(resp.Header) + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type GetMetaDataOptions struct{} + +func (g GetMetaDataOptions) ToHeaders() *client.Headers { + return nil +} + +func (g GetMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (g GetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/metadata_set.go new file mode 100644 index 000000000000..8aa9097d3ef9 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/metadata_set.go @@ -0,0 +1,98 @@ +package directories + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SetMetaDataResponse struct { + HttpResponse *http.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + +// SetMetaData updates user defined metadata for the specified directory +func (c Client) SetMetaData(ctx context.Context, shareName, path string, input SetMetaDataInput) (result SetMetaDataResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`metadata` is not valid: %s", err) + return + } + + if path == "" { + err = fmt.Errorf("`path` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetMetaDataOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("/%s/%s", shareName, path), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type SetMetaDataOptions struct { + metaData map[string]string +} + +func (s SetMetaDataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if len(s.metaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(s.metaData)) + } + return headers +} + +func (s SetMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (s SetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/options.go new file mode 100644 index 000000000000..9b324d54fbed --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/options.go @@ -0,0 +1,24 @@ +package directories + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = directoriesOptions{} + +type directoriesOptions struct{} + +func (o directoriesOptions) ToHeaders() *client.Headers { + return &client.Headers{} +} + +func (directoriesOptions) ToOData() *odata.Query { + return nil +} + +func (directoriesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/resource_id.go new file mode 100644 index 000000000000..b49c41ade78b --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/resource_id.go @@ -0,0 +1,80 @@ +package directories + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = DirectoryId{} + +type DirectoryId struct { + // AccountId specifies the ID of the Storage Account where this Directory exists. + AccountId accounts.AccountId + + // ShareName specifies the name of the File Share containing this Directory. + ShareName string + + // DirectoryPath specifies the path representing this Directory. + DirectoryPath string +} + +func NewDirectoryID(accountId accounts.AccountId, shareName, directoryPath string) DirectoryId { + return DirectoryId{ + AccountId: accountId, + ShareName: shareName, + DirectoryPath: directoryPath, + } +} + +func (b DirectoryId) ID() string { + return fmt.Sprintf("%s/%s/%s", b.AccountId.ID(), b.ShareName, b.DirectoryPath) +} + +func (b DirectoryId) String() string { + components := []string{ + fmt.Sprintf("Share Name %q", b.ShareName), + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Directory Path %q (%s)", b.DirectoryPath, strings.Join(components, " / ")) +} + +// ParseDirectoryID parses `input` into a Directory ID using a known `domainSuffix` +func ParseDirectoryID(input, domainSuffix string) (*DirectoryId, error) { + // example: https://foo.file.core.windows.net/Bar/some/directory + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.FileSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.FileSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) < 2 { + return nil, fmt.Errorf("expected the path to contain at least 2 segments but got %d", len(segments)) + } + shareName := segments[0] + directoryPath := strings.Join(segments[1:], "/") + return &DirectoryId{ + AccountId: *account, + ShareName: shareName, + DirectoryPath: directoryPath, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/version.go new file mode 100644 index 000000000000..785860cbd092 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories/version.go @@ -0,0 +1,5 @@ +package directories + +// APIVersion is the version of the API used for all Storage API Operations +const apiVersion = "2023-11-03" +const componentName = "file/directories" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/README.md similarity index 52% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/README.md rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/README.md index 6ce6bbb13f96..0ac6146b88cc 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/README.md @@ -1,4 +1,4 @@ -## File Storage Files SDK for API version 2020-08-04 +## File Storage Files SDK for API version 2023-11-03 This package allows you to interact with the Files File Storage API @@ -19,10 +19,9 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files" ) func Example() error { @@ -31,14 +30,22 @@ func Example() error { shareName := "myshare" directoryName := "myfiles" fileName := "example.txt" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - filesClient := files.New() - filesClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + filesClient, err := files.NewWithBaseUri(fmt.Sprintf("https://%s.file.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + filesClient.Client.SetAuthorizer(auth) ctx := context.TODO() input := files.CreateInput{} - if _, err := filesClient.Create(ctx, accountName, shareName, directoryName, fileName, input); err != nil { + if _, err := filesClient.Create(ctx, shareName, directoryName, fileName, input); err != nil { return fmt.Errorf("Error creating File: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/api.go new file mode 100644 index 000000000000..f28a708ded3a --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/api.go @@ -0,0 +1,24 @@ +package files + +import ( + "context" + "os" +) + +type StorageFile interface { + PutByteRange(ctx context.Context, shareName string, path string, fileName string, input PutByteRangeInput) (PutRangeResponse, error) + GetByteRange(ctx context.Context, shareName string, path string, fileName string, input GetByteRangeInput) (GetByteRangeResponse, error) + ClearByteRange(ctx context.Context, shareName string, path string, fileName string, input ClearByteRangeInput) (ClearByteRangeResponse, error) + SetProperties(ctx context.Context, shareName string, path string, fileName string, input SetPropertiesInput) (SetPropertiesResponse, error) + PutFile(ctx context.Context, shareName string, path string, fileName string, file *os.File, parallelism int) error + Copy(ctx context.Context, shareName, path, fileName string, input CopyInput) (CopyResponse, error) + SetMetaData(ctx context.Context, shareName string, path string, fileName string, input SetMetaDataInput) (SetMetaDataResponse, error) + GetMetaData(ctx context.Context, shareName string, path string, fileName string) (GetMetaDataResponse, error) + AbortCopy(ctx context.Context, shareName string, path string, fileName string, input CopyAbortInput) (CopyAbortResponse, error) + GetFile(ctx context.Context, shareName string, path string, fileName string, input GetFileInput) (GetFileResponse, error) + ListRanges(ctx context.Context, shareName, path, fileName string) (ListRangesResponse, error) + GetProperties(ctx context.Context, shareName string, path string, fileName string) (GetResponse, error) + Delete(ctx context.Context, shareName string, path string, fileName string) (DeleteResponse, error) + Create(ctx context.Context, shareName string, path string, fileName string, input CreateInput) (CreateResponse, error) + CopyAndWait(ctx context.Context, shareName, path, fileName string, input CopyInput) (CopyResponse, error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/client.go new file mode 100644 index 000000000000..39b02e7f2782 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/client.go @@ -0,0 +1,39 @@ +package files + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for File Storage Shares. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + + baseClient.Client.AuthorizeRequest = func(ctx context.Context, req *http.Request, authorizer auth.Authorizer) error { + if err := auth.SetAuthHeader(ctx, req, authorizer); err != nil { + return fmt.Errorf("authorizing request: %+v", err) + } + + // Only set this header if OAuth is being used (i.e. not shared key authentication) + if _, ok := authorizer.(*auth.SharedKeyAuthorizer); !ok { + req.Header.Set("x-ms-file-request-intent", "backup") + } + + return nil + } + + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy.go new file mode 100644 index 000000000000..d8351395df86 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy.go @@ -0,0 +1,124 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type CopyInput struct { + // Specifies the URL of the source file or blob, up to 2 KB in length. + // + // To copy a file to another file within the same storage account, you may use Shared Key to authenticate + // the source file. If you are copying a file from another storage account, or if you are copying a blob from + // the same storage account or another storage account, then you must authenticate the source file or blob using a + // shared access signature. If the source is a public blob, no authentication is required to perform the copy + // operation. A file in a share snapshot can also be specified as a copy source. + CopySource string + + MetaData map[string]string +} + +type CopyResponse struct { + HttpResponse *http.Response + + // The CopyID, which can be passed to AbortCopy to abort the copy. + CopyID string + + // Either `success` or `pending` + CopySuccess string +} + +// Copy copies a blob or file to a destination file within the storage account asynchronously. +func (c Client) Copy(ctx context.Context, shareName, path, fileName string, input CopyInput) (result CopyResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if input.CopySource == "" { + err = fmt.Errorf("`input.CopySource` cannot be an empty string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %s", err) + return + } + + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: CopyOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.CopyID = resp.Header.Get("x-ms-copy-id") + result.CopySuccess = resp.Header.Get("x-ms-copy-status") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type CopyOptions struct { + input CopyInput +} + +func (c CopyOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) + } + headers.Append("x-ms-copy-source", c.input.CopySource) + return headers +} + +func (c CopyOptions) ToOData() *odata.Query { + return nil +} + +func (c CopyOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_abort.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_abort.go new file mode 100644 index 000000000000..191929b8dab5 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_abort.go @@ -0,0 +1,98 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type CopyAbortInput struct { + copyID string +} + +type CopyAbortResponse struct { + HttpResponse *http.Response +} + +// AbortCopy aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata +func (c Client) AbortCopy(ctx context.Context, shareName, path, fileName string, input CopyAbortInput) (result CopyAbortResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if input.copyID == "" { + err = fmt.Errorf("`copyID` cannot be an empty string") + return + } + + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: CopyAbortOptions{ + copyId: input.copyID, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type CopyAbortOptions struct { + copyId string +} + +func (c CopyAbortOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-copy-action", "abort") + return headers +} + +func (c CopyAbortOptions) ToOData() *odata.Query { + return nil +} + +func (c CopyAbortOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "copy") + out.Append("copyid", c.copyId) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_and_wait_poller.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_and_wait_poller.go new file mode 100644 index 000000000000..9d6e8afcfcfb --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_and_wait_poller.go @@ -0,0 +1,48 @@ +package files + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" +) + +var _ pollers.PollerType = ©AndWaitPoller{} + +func NewCopyAndWaitPoller(client *Client, shareName, path, fileName string) *copyAndWaitPoller { + return ©AndWaitPoller{ + client: client, + shareName: shareName, + path: path, + fileName: fileName, + } +} + +type copyAndWaitPoller struct { + client *Client + shareName string + path string + fileName string +} + +func (p *copyAndWaitPoller) Poll(ctx context.Context) (*pollers.PollResult, error) { + props, err := p.client.GetProperties(ctx, p.shareName, p.path, p.fileName) + if err != nil { + return nil, fmt.Errorf("retrieving copy (shareName: %s path: %s fileName: %s) : %+v", p.shareName, p.path, p.fileName, err) + } + + if strings.EqualFold(props.CopyStatus, "success") { + return &pollers.PollResult{ + Status: pollers.PollingStatusSucceeded, + PollInterval: 10 * time.Second, + }, nil + } + + // Processing + return &pollers.PollResult{ + Status: pollers.PollingStatusInProgress, + PollInterval: 10 * time.Second, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_wait.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_wait.go new file mode 100644 index 000000000000..9223f54331ae --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/copy_wait.go @@ -0,0 +1,29 @@ +package files + +import ( + "context" + "fmt" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" +) + +// CopyAndWait is a convenience method which doesn't exist in the API, which copies the file and then waits for the copy to complete +func (c Client) CopyAndWait(ctx context.Context, shareName, path, fileName string, input CopyInput) (result CopyResponse, err error) { + fileCopy, e := c.Copy(ctx, shareName, path, fileName, input) + if err != nil { + result.HttpResponse = fileCopy.HttpResponse + err = fmt.Errorf("copying: %s", e) + return + } + + result.CopyID = fileCopy.CopyID + + pollerType := NewCopyAndWaitPoller(&c, shareName, path, fileName) + poller := pollers.NewPoller(pollerType, 10*time.Second, pollers.DefaultNumberOfDroppedConnectionsToAllow) + if err = poller.PollUntilDone(ctx); err != nil { + return result, fmt.Errorf("waiting for file to copy: %+v", err) + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/create.go new file mode 100644 index 000000000000..5fb8e97d2e8b --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/create.go @@ -0,0 +1,166 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type CreateInput struct { + // This header specifies the maximum size for the file, up to 1 TiB. + ContentLength int64 + + // The MIME content type of the file + // If not specified, the default type is application/octet-stream. + ContentType *string + + // Specifies which content encodings have been applied to the file. + // This value is returned to the client when the Get File operation is performed + // on the file resource and can be used to decode file content. + ContentEncoding *string + + // Specifies the natural languages used by this resource. + ContentLanguage *string + + // The File service stores this value but does not use or modify it. + CacheControl *string + + // Sets the file's MD5 hash. + ContentMD5 *string + + // Sets the file’s Content-Disposition header. + ContentDisposition *string + + // The time at which this file was created at - if omitted, this'll be set to "now" + // This maps to the `x-ms-file-creation-time` field. + CreatedAt *time.Time + + // The time at which this file was last modified - if omitted, this'll be set to "now" + // This maps to the `x-ms-file-last-write-time` field. + LastModified *time.Time + + // MetaData is a mapping of key value pairs which should be assigned to this file + MetaData map[string]string +} + +type CreateResponse struct { + HttpResponse *http.Response +} + +// Create creates a new file or replaces a file. +func (c Client) Create(ctx context.Context, shareName, path, fileName string, input CreateInput) (result CreateResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %s", err) + return + } + + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type CreateOptions struct { + input CreateInput +} + +func (c CreateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + var coalesceDate = func(input *time.Time, defaultVal string) string { + if input == nil { + return defaultVal + } + + return input.Format(time.RFC1123) + } + + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) + } + + headers.Append("x-ms-content-length", strconv.Itoa(int(c.input.ContentLength))) + headers.Append("x-ms-type", "file") + + headers.Append("x-ms-file-permission", "inherit") // TODO: expose this in future + headers.Append("x-ms-file-attributes", "None") // TODO: expose this in future + headers.Append("x-ms-file-creation-time", coalesceDate(c.input.CreatedAt, "now")) + headers.Append("x-ms-file-last-write-time", coalesceDate(c.input.LastModified, "now")) + + if c.input.ContentDisposition != nil { + headers.Append("x-ms-content-disposition", *c.input.ContentDisposition) + } + + if c.input.ContentEncoding != nil { + headers.Append("x-ms-content-encoding", *c.input.ContentEncoding) + } + + if c.input.ContentMD5 != nil { + headers.Append("x-ms-content-md5", *c.input.ContentMD5) + } + + if c.input.ContentType != nil { + headers.Append("x-ms-content-type", *c.input.ContentType) + } + + return headers +} + +func (c CreateOptions) ToOData() *odata.Query { + return nil +} + +func (c CreateOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/delete.go new file mode 100644 index 000000000000..f3841fa0427d --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/delete.go @@ -0,0 +1,65 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type DeleteResponse struct { + HttpResponse *http.Response +} + +// Delete immediately deletes the file from the File Share. +func (c Client) Delete(ctx context.Context, shareName, path, fileName string) (result DeleteResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if path != "" { + path = fmt.Sprintf("/%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: nil, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/metadata_get.go new file mode 100644 index 000000000000..a4d1cc9ef532 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/metadata_get.go @@ -0,0 +1,88 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetMetaDataResponse struct { + HttpResponse *http.Response + + MetaData map[string]string +} + +// GetMetaData returns the MetaData for the specified File. +func (c Client) GetMetaData(ctx context.Context, shareName, path, fileName string) (result GetMetaDataResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetMetadataOptions{}, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.MetaData = metadata.ParseFromHeaders(resp.Header) + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type GetMetadataOptions struct{} + +func (m GetMetadataOptions) ToHeaders() *client.Headers { + return nil +} + +func (m GetMetadataOptions) ToOData() *odata.Query { + return nil +} + +func (m GetMetadataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/metadata_set.go new file mode 100644 index 000000000000..3a51a1086bfd --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/metadata_set.go @@ -0,0 +1,100 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SetMetaDataResponse struct { + HttpResponse *http.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + +// SetMetaData updates the specified File to have the specified MetaData. +func (c Client) SetMetaData(ctx context.Context, shareName, path, fileName string, input SetMetaDataInput) (result SetMetaDataResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %s", err) + return + } + + if path != "" { + path = fmt.Sprintf("/%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetMetaDataOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type SetMetaDataOptions struct { + metaData map[string]string +} + +func (s SetMetaDataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if len(s.metaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(s.metaData)) + } + return headers +} + +func (s SetMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (s SetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/properties_get.go new file mode 100644 index 000000000000..2ea1f633efe8 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/properties_get.go @@ -0,0 +1,112 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetResponse struct { + HttpResponse *http.Response + + CacheControl string + ContentDisposition string + ContentEncoding string + ContentLanguage string + ContentLength *int64 + ContentMD5 string + ContentType string + CopyID string + CopyStatus string + CopySource string + CopyProgress string + CopyStatusDescription string + CopyCompletionTime string + Encrypted bool + + MetaData map[string]string +} + +// GetProperties returns the Properties for the specified file +func (c Client) GetProperties(ctx context.Context, shareName, path, fileName string) (result GetResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if path != "" { + path = fmt.Sprintf("/%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: nil, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.CacheControl = resp.Header.Get("Cache-Control") + result.ContentDisposition = resp.Header.Get("Content-Disposition") + result.ContentEncoding = resp.Header.Get("Content-Encoding") + result.ContentLanguage = resp.Header.Get("Content-Language") + result.ContentMD5 = resp.Header.Get("Content-MD5") + result.ContentType = resp.Header.Get("Content-Type") + result.CopyCompletionTime = resp.Header.Get("x-ms-copy-completion-time") + result.CopyID = resp.Header.Get("x-ms-copy-id") + result.CopyProgress = resp.Header.Get("x-ms-copy-progress") + result.CopySource = resp.Header.Get("x-ms-copy-source") + result.CopyStatus = resp.Header.Get("x-ms-copy-status") + result.CopyStatusDescription = resp.Header.Get("x-ms-copy-status-description") + result.Encrypted = strings.EqualFold(resp.Header.Get("x-ms-server-encrypted"), "true") + result.MetaData = metadata.ParseFromHeaders(resp.Header) + + contentLengthRaw := resp.Header.Get("Content-Length") + if contentLengthRaw != "" { + var contentLength int + contentLength, err = strconv.Atoi(contentLengthRaw) + if err != nil { + err = fmt.Errorf("parsing `Content-Length` header value %q: %s", contentLengthRaw, err) + return + } + contentLengthI64 := int64(contentLength) + result.ContentLength = &contentLengthI64 + } + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/properties_set.go new file mode 100644 index 000000000000..83bd84118eb5 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/properties_set.go @@ -0,0 +1,180 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SetPropertiesInput struct { + // Resizes a file to the specified size. + // If the specified byte value is less than the current size of the file, + // then all ranges above the specified byte value are cleared. + ContentLength int64 + + // Modifies the cache control string for the file. + // If this property is not specified on the request, then the property will be cleared for the file. + // Subsequent calls to Get File Properties will not return this property, + // unless it is explicitly set on the file again. + ContentControl *string + + // Sets the file’s Content-Disposition header. + // If this property is not specified on the request, then the property will be cleared for the file. + // Subsequent calls to Get File Properties will not return this property, + // unless it is explicitly set on the file again. + ContentDisposition *string + + // Sets the file's content encoding. + // If this property is not specified on the request, then the property will be cleared for the file. + // Subsequent calls to Get File Properties will not return this property, + // unless it is explicitly set on the file again. + ContentEncoding *string + + // Sets the file's content language. + // If this property is not specified on the request, then the property will be cleared for the file. + // Subsequent calls to Get File Properties will not return this property, + // unless it is explicitly set on the file again. + ContentLanguage *string + + // Sets the file's MD5 hash. + // If this property is not specified on the request, then the property will be cleared for the file. + // Subsequent calls to Get File Properties will not return this property, + // unless it is explicitly set on the file again. + ContentMD5 *string + + // Sets the file's content type. + // If this property is not specified on the request, then the property will be cleared for the file. + // Subsequent calls to Get File Properties will not return this property, + // unless it is explicitly set on the file again. + ContentType *string + + // The time at which this file was created at - if omitted, this'll be set to "now" + // This maps to the `x-ms-file-creation-time` field. + CreatedAt *time.Time + + // The time at which this file was last modified - if omitted, this'll be set to "now" + // This maps to the `x-ms-file-last-write-time` field. + LastModified *time.Time + + // MetaData is a mapping of key value pairs which should be assigned to this file + MetaData map[string]string +} + +type SetPropertiesResponse struct { + HttpResponse *http.Response +} + +// SetProperties sets the specified properties on the specified File +func (c Client) SetProperties(ctx context.Context, shareName, path, fileName string, input SetPropertiesInput) (result SetPropertiesResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if path != "" { + path = fmt.Sprintf("/%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetPropertiesOptions{ + input: input, + }, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type SetPropertiesOptions struct { + input SetPropertiesInput +} + +func (s SetPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + var coalesceDate = func(input *time.Time, defaultVal string) string { + if input == nil { + return defaultVal + } + + return input.Format(time.RFC1123) + } + + headers.Append("x-ms-type", "file") + + headers.Append("x-ms-content-length", strconv.Itoa(int(s.input.ContentLength))) + headers.Append("x-ms-file-permission", "inherit") // TODO: expose this in future + headers.Append("x-ms-file-attributes", "None") // TODO: expose this in future + headers.Append("x-ms-file-creation-time", coalesceDate(s.input.CreatedAt, "now")) + headers.Append("x-ms-file-last-write-time", coalesceDate(s.input.LastModified, "now")) + + if s.input.ContentControl != nil { + headers.Append("x-ms-cache-control", *s.input.ContentControl) + } + if s.input.ContentDisposition != nil { + headers.Append("x-ms-content-disposition", *s.input.ContentDisposition) + } + if s.input.ContentEncoding != nil { + headers.Append("x-ms-content-encoding", *s.input.ContentEncoding) + } + if s.input.ContentLanguage != nil { + headers.Append("x-ms-content-language", *s.input.ContentLanguage) + } + if s.input.ContentMD5 != nil { + headers.Append("x-ms-content-md5", *s.input.ContentMD5) + } + if s.input.ContentType != nil { + headers.Append("x-ms-content-type", *s.input.ContentType) + } + + if len(s.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(s.input.MetaData)) + } + + return headers +} + +func (s SetPropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (s SetPropertiesOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_clear.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_clear.go new file mode 100644 index 000000000000..0a1e8149ed73 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_clear.go @@ -0,0 +1,104 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ClearByteRangeInput struct { + StartBytes int64 + EndBytes int64 +} + +type ClearByteRangeResponse struct { + HttpResponse *http.Response +} + +// ClearByteRange clears the specified Byte Range from within the specified File +func (c Client) ClearByteRange(ctx context.Context, shareName, path, fileName string, input ClearByteRangeInput) (result ClearByteRangeResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if input.StartBytes < 0 { + err = fmt.Errorf("`input.StartBytes` must be greater or equal to 0") + return + } + + if input.EndBytes <= 0 { + err = fmt.Errorf("`input.EndBytes` must be greater than 0") + return + } + + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: ClearByteRangeOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type ClearByteRangeOptions struct { + input ClearByteRangeInput +} + +func (c ClearByteRangeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-write", "clear") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", c.input.StartBytes, c.input.EndBytes)) + return headers +} + +func (c ClearByteRangeOptions) ToOData() *odata.Query { + return nil +} + +func (c ClearByteRangeOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "range") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_get.go new file mode 100644 index 000000000000..f8b40b87d1a7 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_get.go @@ -0,0 +1,119 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetByteRangeInput struct { + StartBytes int64 + EndBytes int64 +} + +type GetByteRangeResponse struct { + HttpResponse *http.Response + Contents *[]byte +} + +// GetByteRange returns the specified Byte Range from the specified File. +func (c Client) GetByteRange(ctx context.Context, shareName, path, fileName string, input GetByteRangeInput) (result GetByteRangeResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if input.StartBytes < 0 { + err = fmt.Errorf("`input.StartBytes` must be greater or equal to 0") + return + } + + if input.EndBytes <= 0 { + err = fmt.Errorf("`input.EndBytes` must be greater than 0") + return + } + + expectedBytes := input.EndBytes - input.StartBytes + if expectedBytes < (4 * 1024) { + err = fmt.Errorf("requested Byte Range must be at least 4KB") + return + } + if expectedBytes > (4 * 1024 * 1024) { + err = fmt.Errorf("requested Byte Range must be at most 4MB") + return + } + + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + http.StatusPartialContent, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetByteRangeOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.Contents = &[]byte{} + result.HttpResponse = resp.Response + + err = resp.Unmarshal(result.Contents) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type GetByteRangeOptions struct { + input GetByteRangeInput +} + +func (g GetByteRangeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", g.input.StartBytes, g.input.EndBytes-1)) + return headers +} + +func (g GetByteRangeOptions) ToOData() *odata.Query { + return nil +} + +func (g GetByteRangeOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get_file.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_get_file.go similarity index 65% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get_file.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_get_file.go index 9e5be17f85fc..e923eb31f3b0 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get_file.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_get_file.go @@ -5,38 +5,47 @@ import ( "fmt" "log" "math" + "net/http" "runtime" "sync" - - "github.com/Azure/go-autorest/autorest" ) +type GetFileInput struct { + Parallelism int +} + +type GetFileResponse struct { + HttpResponse *http.Response + OutputBytes *[]byte +} + // GetFile is a helper method to download a file by chunking it automatically -func (client Client) GetFile(ctx context.Context, accountName, shareName, path, fileName string, parallelism int) (result autorest.Response, outputBytes []byte, err error) { +func (c Client) GetFile(ctx context.Context, shareName, path, fileName string, input GetFileInput) (result GetFileResponse, err error) { // first look up the file and check out how many bytes it is - file, e := client.GetProperties(ctx, accountName, shareName, path, fileName) + file, e := c.GetProperties(ctx, shareName, path, fileName) if err != nil { - result = file.Response + result.HttpResponse = file.HttpResponse err = e return } if file.ContentLength == nil { - err = fmt.Errorf("Content-Length was nil!") + err = fmt.Errorf("Content-Length was nil") return } - length := int64(*file.ContentLength) + result.HttpResponse = file.HttpResponse + length := *file.ContentLength chunkSize := int64(4 * 1024 * 1024) // 4MB if chunkSize > length { chunkSize = length } - // then split that up into chunks and retrieve it retrieve it into the 'results' set + // then split that up into chunks and retrieve it into the 'results' set chunks := int(math.Ceil(float64(length) / float64(chunkSize))) - workerCount := parallelism * runtime.NumCPU() + workerCount := input.Parallelism * runtime.NumCPU() if workerCount > chunks { workerCount = chunks } @@ -57,7 +66,7 @@ func (client Client) GetFile(ctx context.Context, accountName, shareName, path, fileSize: length, } - result, err := client.downloadFileChunk(ctx, accountName, shareName, path, fileName, dfci) + result, err := c.downloadFileChunk(ctx, shareName, path, fileName, dfci) if err != nil { errors <- err waitGroup.Done() @@ -81,10 +90,10 @@ func (client Client) GetFile(ctx context.Context, accountName, shareName, path, // then finally put it all together, in order and return it output := make([]byte, length) for _, v := range results { - copy(output[v.startBytes:v.endBytes], v.bytes) + copy(output[v.startBytes:v.endBytes], *v.bytes) } - outputBytes = output + *result.OutputBytes = output return } @@ -97,10 +106,10 @@ type downloadFileChunkInput struct { type downloadFileChunkResult struct { startBytes int64 endBytes int64 - bytes []byte + bytes *[]byte } -func (client Client) downloadFileChunk(ctx context.Context, accountName, shareName, path, fileName string, input downloadFileChunkInput) (*downloadFileChunkResult, error) { +func (c Client) downloadFileChunk(ctx context.Context, shareName, path, fileName string, input downloadFileChunkInput) (*downloadFileChunkResult, error) { startBytes := input.chunkSize * int64(input.thisChunk) endBytes := startBytes + input.chunkSize @@ -114,9 +123,9 @@ func (client Client) downloadFileChunk(ctx context.Context, accountName, shareNa StartBytes: startBytes, EndBytes: endBytes, } - result, err := client.GetByteRange(ctx, accountName, shareName, path, fileName, getInput) + result, err := c.GetByteRange(ctx, shareName, path, fileName, getInput) if err != nil { - return nil, fmt.Errorf("Error putting bytes: %s", err) + return nil, fmt.Errorf("error putting bytes: %s", err) } output := downloadFileChunkResult{ diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_put.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_put.go new file mode 100644 index 000000000000..58e6f9bb0cff --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_put.go @@ -0,0 +1,124 @@ +package files + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type PutByteRangeInput struct { + StartBytes int64 + EndBytes int64 + + // Content is the File Contents for the specified range + // which can be at most 4MB + Content []byte +} + +type PutRangeResponse struct { + HttpResponse *http.Response +} + +// PutByteRange puts the specified Byte Range in the specified File. +func (c Client) PutByteRange(ctx context.Context, shareName, path, fileName string, input PutByteRangeInput) (result PutRangeResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if input.StartBytes < 0 { + err = fmt.Errorf("`input.StartBytes` must be greater or equal to 0") + return + } + if input.EndBytes <= 0 { + err = fmt.Errorf("`input.EndBytes` must be greater than 0") + return + } + + expectedBytes := input.EndBytes - input.StartBytes + actualBytes := len(input.Content) + if expectedBytes != int64(actualBytes) { + err = fmt.Errorf(fmt.Sprintf("The specified byte-range (%d) didn't match the content size (%d).", expectedBytes, actualBytes)) + return + } + + if expectedBytes > (4 * 1024 * 1024) { + err = fmt.Errorf("specified Byte Range must be at most 4MB") + return + } + + if path != "" { + path = fmt.Sprintf("/%s/", path) + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: PutRangeOptions{ + input: input, + }, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + req.Body = io.NopCloser(bytes.NewReader(input.Content)) + req.ContentLength = int64(len(input.Content)) + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type PutRangeOptions struct { + input PutByteRangeInput +} + +func (p PutRangeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-write", "update") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", p.input.StartBytes, p.input.EndBytes-1)) + headers.Append("Content-Length", strconv.Itoa(len(p.input.Content))) + return headers +} + +func (p PutRangeOptions) ToOData() *odata.Query { + return nil +} + +func (p PutRangeOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "range") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put_file.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_put_file.go similarity index 70% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put_file.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_put_file.go index a74845dd61ca..660122c1aa8f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put_file.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/range_put_file.go @@ -8,15 +8,16 @@ import ( "math" "os" "sync" - - "github.com/Azure/go-autorest/autorest" ) // PutFile is a helper method which takes a file, and automatically chunks it up, rather than having to do this yourself -func (client Client) PutFile(ctx context.Context, accountName, shareName, path, fileName string, file *os.File, parallelism int) error { +func (c Client) PutFile(ctx context.Context, shareName, path, fileName string, file *os.File, parallelism int) error { fileInfo, err := file.Stat() if err != nil { - return fmt.Errorf("Error loading file info: %s", err) + return fmt.Errorf("error loading file info: %s", err) + } + if fileInfo.Size() == 0 { + return fmt.Errorf("file is empty which is not supported") } fileSize := fileInfo.Size() @@ -48,7 +49,7 @@ func (client Client) PutFile(ctx context.Context, accountName, shareName, path, fileSize: fileSize, } - _, err := client.uploadChunk(ctx, accountName, shareName, path, fileName, uci, file) + _, err := c.uploadChunk(ctx, shareName, path, fileName, uci, file) if err != nil { errors <- err } @@ -65,7 +66,7 @@ func (client Client) PutFile(ctx context.Context, accountName, shareName, path, // TODO: we should switch to hashicorp/multi-error here if len(errors) > 0 { - return fmt.Errorf("Error uploading file: %s", <-errors) + return fmt.Errorf("uploading file: %s", <-errors) } return nil @@ -77,7 +78,7 @@ type uploadChunkInput struct { fileSize int64 } -func (client Client) uploadChunk(ctx context.Context, accountName, shareName, path, fileName string, input uploadChunkInput, file *os.File) (result autorest.Response, err error) { +func (c Client) uploadChunk(ctx context.Context, shareName, path, fileName string, input uploadChunkInput, file *os.File) (result PutRangeResponse, err error) { startBytes := int64(input.chunkSize * input.thisChunk) endBytes := startBytes + int64(input.chunkSize) @@ -93,7 +94,7 @@ func (client Client) uploadChunk(ctx context.Context, accountName, shareName, pa _, err = file.ReadAt(bytes, startBytes) if err != nil { if err != io.EOF { - return result, fmt.Errorf("Error reading bytes: %s", err) + return result, fmt.Errorf("reading bytes: %s", err) } } @@ -102,9 +103,9 @@ func (client Client) uploadChunk(ctx context.Context, accountName, shareName, pa EndBytes: endBytes, Content: bytes, } - result, err = client.PutByteRange(ctx, accountName, shareName, path, fileName, putBytesInput) + result, err = c.PutByteRange(ctx, shareName, path, fileName, putBytesInput) if err != nil { - return result, fmt.Errorf("Error putting bytes: %s", err) + return result, fmt.Errorf("putting bytes: %s", err) } return diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/ranges_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/ranges_list.go new file mode 100644 index 000000000000..0b89e6c1a110 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/ranges_list.go @@ -0,0 +1,99 @@ +package files + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ListRangesResponse struct { + HttpResponse *http.Response + + Ranges []Range `xml:"Range"` +} + +type Range struct { + Start string `xml:"Start"` + End string `xml:"End"` +} + +// ListRanges returns the list of valid ranges for the specified File. +func (c Client) ListRanges(ctx context.Context, shareName, path, fileName string) (result ListRangesResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if path == "" { + err = fmt.Errorf("`path` cannot be an empty string") + return + } + + if fileName == "" { + err = fmt.Errorf("`fileName` cannot be an empty string") + return + } + + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: ListRangeOptions{}, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type ListRangeOptions struct{} + +func (l ListRangeOptions) ToHeaders() *client.Headers { + return nil +} + +func (l ListRangeOptions) ToOData() *odata.Query { + return nil +} + +func (l ListRangeOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "rangelist") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/resource_id.go new file mode 100644 index 000000000000..492889780e31 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/resource_id.go @@ -0,0 +1,87 @@ +package files + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = FileId{} + +type FileId struct { + // AccountId specifies the ID of the Storage Account where this File exists. + AccountId accounts.AccountId + + // ShareName specifies the name of the File Share containing this File. + ShareName string + + // DirectoryPath specifies the path representing the Directory where this File exists. + DirectoryPath string + + // FileName specifies the name of the File. + FileName string +} + +func NewFileID(accountId accounts.AccountId, shareName, directoryPath, fileName string) FileId { + return FileId{ + AccountId: accountId, + ShareName: shareName, + DirectoryPath: directoryPath, + FileName: fileName, + } +} + +func (b FileId) ID() string { + return fmt.Sprintf("%s/%s/%s/%s", b.AccountId.ID(), b.ShareName, b.DirectoryPath, b.FileName) +} + +func (b FileId) String() string { + components := []string{ + fmt.Sprintf("Directory Path %q", b.DirectoryPath), + fmt.Sprintf("Share Name %q", b.ShareName), + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("File %q (%s)", b.FileName, strings.Join(components, " / ")) +} + +// ParseFileID parses `input` into a File ID using a known `domainSuffix` +func ParseFileID(input, domainSuffix string) (*FileId, error) { + // example: https://foo.file.core.windows.net/Bar/some/directory/some-file.txt + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.FileSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.FileSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) < 3 { + return nil, fmt.Errorf("expected the path to contain at least 3 segments but got %d", len(segments)) + } + shareName := segments[0] + directoryPath := strings.Join(segments[1:len(segments)-1], "/") + fileName := segments[len(segments)-1] + return &FileId{ + AccountId: *account, + ShareName: shareName, + DirectoryPath: directoryPath, + FileName: fileName, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/version.go new file mode 100644 index 000000000000..1d4bc38bea91 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files/version.go @@ -0,0 +1,4 @@ +package files + +const apiVersion = "2023-11-03" +const componentName = "file/files" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/README.md new file mode 100644 index 000000000000..5ec0fb4f8fc0 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/README.md @@ -0,0 +1,50 @@ +## File Storage Shares SDK for API version 2023-11-03 + +This package allows you to interact with the Shares File Storage API + +### Supported Authorizers + +* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) +* SharedKeyLite (Blob, File & Queue) + +### Example Usage + +```go +package main + +import ( + "context" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares" +) + +func Example() error { + accountName := "storageaccount1" + storageAccountKey := "ABC123...." + shareName := "myshare" + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + sharesClient, err := shares.NewWithBaseUri(fmt.Sprintf("https://%s.file.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + sharesClient.Client.SetAuthorizer(auth) + + ctx := context.TODO() + input := shares.CreateInput{ + QuotaInGB: 2, + } + if _, err := sharesClient.Create(ctx, shareName, input); err != nil { + return fmt.Errorf("Error creating Share: %s", err) + } + + return nil +} +``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/acl_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/acl_get.go new file mode 100644 index 000000000000..8add483a5e3e --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/acl_get.go @@ -0,0 +1,81 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetACLResult struct { + HttpResponse *http.Response + + SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` +} + +// GetACL get the Access Control List for the specified Storage Share +func (c Client) GetACL(ctx context.Context, shareName string) (result GetACLResult, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getAclOptions{}, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type getAclOptions struct { +} + +func (g getAclOptions) ToHeaders() *client.Headers { + return nil +} + +func (g getAclOptions) ToOData() *odata.Query { + return nil +} + +func (g getAclOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "acl") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/acl_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/acl_set.go new file mode 100644 index 000000000000..216d714eb2ac --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/acl_set.go @@ -0,0 +1,95 @@ +package shares + +import ( + "bytes" + "context" + "encoding/xml" + "fmt" + "io" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type SetAclResponse struct { + HttpResponse *http.Response +} + +type SetAclInput struct { + SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` + XMLName xml.Name `xml:"SignedIdentifiers"` +} + +// SetACL sets the specified Access Control List on the specified Storage Share +func (c Client) SetACL(ctx context.Context, shareName string, input SetAclInput) (result SetAclResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setAclOptions{}, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + b, err := xml.Marshal(&input) + if err != nil { + err = fmt.Errorf("marshalling input: %+v", err) + return + } + withHeader := xml.Header + string(b) + bytesWithHeader := []byte(withHeader) + req.ContentLength = int64(len(bytesWithHeader)) + req.Header.Set("Content-Length", strconv.Itoa(len(bytesWithHeader))) + req.Body = io.NopCloser(bytes.NewReader(bytesWithHeader)) + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type setAclOptions struct { + SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` +} + +func (s setAclOptions) ToHeaders() *client.Headers { + return nil +} + +func (s setAclOptions) ToOData() *odata.Query { + return nil +} + +func (s setAclOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "acl") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/api.go new file mode 100644 index 000000000000..553fb4899e46 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/api.go @@ -0,0 +1,21 @@ +package shares + +import ( + "context" +) + +type StorageShare interface { + SetACL(ctx context.Context, shareName string, input SetAclInput) (SetAclResponse, error) + GetSnapshot(ctx context.Context, shareName string, input GetSnapshotPropertiesInput) (GetSnapshotPropertiesResponse, error) + GetStats(ctx context.Context, shareName string) (GetStatsResponse, error) + GetACL(ctx context.Context, shareName string) (GetACLResult, error) + SetMetaData(ctx context.Context, shareName string, input SetMetaDataInput) (SetMetaDataResponse, error) + GetMetaData(ctx context.Context, shareName string) (GetMetaDataResponse, error) + SetProperties(ctx context.Context, shareName string, properties ShareProperties) (SetPropertiesResponse, error) + DeleteSnapshot(ctx context.Context, accountName string, shareName string, shareSnapshot string) (DeleteSnapshotResponse, error) + CreateSnapshot(ctx context.Context, shareName string, input CreateSnapshotInput) (CreateSnapshotResponse, error) + GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, shareName string) string + GetProperties(ctx context.Context, shareName string) (GetPropertiesResult, error) + Delete(ctx context.Context, shareName string, input DeleteInput) (DeleteResponse, error) + Create(ctx context.Context, shareName string, input CreateInput) (CreateResponse, error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/client.go new file mode 100644 index 000000000000..7d6516f76ed8 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/client.go @@ -0,0 +1,22 @@ +package shares + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for File Storage Shares. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/create.go new file mode 100644 index 000000000000..46e8757466fc --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/create.go @@ -0,0 +1,158 @@ +package shares + +import ( + "bytes" + "context" + "encoding/xml" + "fmt" + "io" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type AccessTier string + +const ( + TransactionOptimizedAccessTier AccessTier = "TransactionOptimized" + HotAccessTier AccessTier = "Hot" + CoolAccessTier AccessTier = "Cool" + PremiumAccessTier AccessTier = "Premium" +) + +type CreateInput struct { + // Specifies the maximum size of the share, in gigabytes. + // Must be greater than 0, and less than or equal to 5TB (5120). + QuotaInGB int + + // Specifies the enabled protocols on the share. If not specified, the default is SMB. + EnabledProtocol ShareProtocol + + MetaData map[string]string + + // Specifies the access tier of the share. + AccessTier *AccessTier +} + +type CreateResponse struct { + HttpResponse *http.Response +} + +// Create creates the specified Storage Share within the specified Storage Account +func (c Client) Create(ctx context.Context, shareName string, input CreateInput) (result CreateResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if input.QuotaInGB <= 0 || input.QuotaInGB > 102400 { + err = fmt.Errorf("`input.QuotaInGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %s", err) + return + } + + // Retry the share creation if a conflicting share is still in the process of being deleted + retryFunc := func(resp *http.Response, _ *odata.OData) (bool, error) { + if resp != nil { + if response.WasStatusCode(resp, http.StatusConflict) { + // TODO: move this error response parsing to a common helper function + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return false, fmt.Errorf("could not parse response body") + } + resp.Body.Close() + respBody = bytes.TrimPrefix(respBody, []byte("\xef\xbb\xbf")) + res := ErrorResponse{} + if err = xml.Unmarshal(respBody, &res); err != nil { + return false, err + } + resp.Body = io.NopCloser(bytes.NewBuffer(respBody)) + if res.Code != nil { + return strings.Contains(*res.Code, "ShareBeingDeleted"), nil + } + } + } + return false, nil + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s", shareName), + RetryFunc: retryFunc, + } + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type CreateOptions struct { + input CreateInput +} + +func (c CreateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) + } + + protocol := SMB + if c.input.EnabledProtocol != "" { + protocol = c.input.EnabledProtocol + } + headers.Append("x-ms-enabled-protocols", string(protocol)) + + if c.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*c.input.AccessTier)) + } + + headers.Append("x-ms-share-quota", strconv.Itoa(c.input.QuotaInGB)) + + return headers +} + +func (c CreateOptions) ToOData() *odata.Query { + return nil +} + +func (c CreateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/delete.go new file mode 100644 index 000000000000..84667f68a3ef --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/delete.go @@ -0,0 +1,83 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type DeleteResponse struct { + HttpResponse *http.Response +} + +type DeleteInput struct { + DeleteSnapshots bool +} + +// Delete deletes the specified Storage Share from within a Storage Account +func (c Client) Delete(ctx context.Context, shareName string, input DeleteInput) (result DeleteResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: DeleteOptions{ + deleteSnapshots: input.DeleteSnapshots, + }, + Path: fmt.Sprintf("/%s", shareName), + } + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type DeleteOptions struct { + deleteSnapshots bool +} + +func (d DeleteOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if d.deleteSnapshots { + headers.Append("x-ms-delete-snapshots", "include") + } + return headers +} + +func (d DeleteOptions) ToOData() *odata.Query { + return nil +} + +func (d DeleteOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/metadata_get.go new file mode 100644 index 000000000000..eeb8b4d1e7dc --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/metadata_get.go @@ -0,0 +1,77 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetMetaDataResponse struct { + HttpResponse *http.Response + + MetaData map[string]string +} + +// GetMetaData returns the MetaData associated with the specified Storage Share +func (c Client) GetMetaData(ctx context.Context, shareName string) (result GetMetaDataResponse, err error) { + if shareName == "" { + return result, fmt.Errorf("`shareName` cannot be an empty string") + } + if strings.ToLower(shareName) != shareName { + return result, fmt.Errorf("`shareName` must be a lower-cased string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetMetaDataOptions{}, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.MetaData = metadata.ParseFromHeaders(resp.Header) + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type GetMetaDataOptions struct{} + +func (g GetMetaDataOptions) ToHeaders() *client.Headers { + return nil +} + +func (g GetMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (g GetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/metadata_set.go new file mode 100644 index 000000000000..55bf1d4bedfc --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/metadata_set.go @@ -0,0 +1,89 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SetMetaDataResponse struct { + HttpResponse *http.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + +// SetMetaData sets the MetaData on the specified Storage Share +func (c Client) SetMetaData(ctx context.Context, shareName string, input SetMetaDataInput) (result SetMetaDataResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`metadata` is not valid: %+v", err) + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetMetaDataOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type SetMetaDataOptions struct { + metaData map[string]string +} + +func (s SetMetaDataOptions) ToHeaders() *client.Headers { + headers := metadata.SetMetaDataHeaders(s.metaData) + return &headers +} + +func (s SetMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (s SetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/models.go similarity index 78% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/models.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/models.go index 32727164cc83..61c3be66ae47 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/models.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/models.go @@ -1,5 +1,7 @@ package shares +import "encoding/xml" + type SignedIdentifier struct { Id string `xml:"Id"` AccessPolicy AccessPolicy `xml:"AccessPolicy"` @@ -20,3 +22,9 @@ const ( // NFS indicates the share can be accessed by NFSv4.1. A premium account is required for this option. NFS ShareProtocol = "NFS" ) + +type ErrorResponse struct { + XMLName xml.Name `xml:"Error"` + Code *string `xml:"Code"` + Message *string `xml:"Message"` +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/options.go new file mode 100644 index 000000000000..e2c1d5c9b4cd --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/options.go @@ -0,0 +1,24 @@ +package shares + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = sharesOptions{} + +type sharesOptions struct{} + +func (o sharesOptions) ToHeaders() *client.Headers { + return &client.Headers{} +} + +func (sharesOptions) ToOData() *odata.Query { + return nil +} + +func (sharesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/properties_get.go new file mode 100644 index 000000000000..fb153628fd09 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/properties_get.go @@ -0,0 +1,87 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetPropertiesResult struct { + HttpResponse *http.Response + + MetaData map[string]string + QuotaInGB int + EnabledProtocol ShareProtocol + AccessTier *AccessTier +} + +// GetProperties returns the properties about the specified Storage Share +func (c Client) GetProperties(ctx context.Context, shareName string) (result GetPropertiesResult, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: sharesOptions{}, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.MetaData = metadata.ParseFromHeaders(resp.Header) + + quotaRaw := resp.Header.Get("x-ms-share-quota") + if quotaRaw != "" { + quota, e := strconv.Atoi(quotaRaw) + if e != nil { + err = fmt.Errorf("error converting %q to an integer: %s", quotaRaw, err) + return + } + result.QuotaInGB = quota + } + + protocol := SMB + if protocolRaw := resp.Header.Get("x-ms-enabled-protocols"); protocolRaw != "" { + protocol = ShareProtocol(protocolRaw) + } + + if accessTierRaw := resp.Header.Get("x-ms-access-tier"); accessTierRaw != "" { + tier := AccessTier(accessTierRaw) + result.AccessTier = &tier + } + result.EnabledProtocol = protocol + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/properties_set.go new file mode 100644 index 000000000000..f80df4fdce1c --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/properties_set.go @@ -0,0 +1,94 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type ShareProperties struct { + QuotaInGb *int + AccessTier *AccessTier +} + +type SetPropertiesResponse struct { + HttpResponse *http.Response +} + +// SetProperties lets you update the Quota for the specified Storage Share +func (c Client) SetProperties(ctx context.Context, shareName string, properties ShareProperties) (result SetPropertiesResponse, err error) { + + if shareName == "" { + return result, fmt.Errorf("`shareName` cannot be an empty string") + } + + if strings.ToLower(shareName) != shareName { + return result, fmt.Errorf("`shareName` must be a lower-cased string") + } + + if newQuotaGB := properties.QuotaInGb; newQuotaGB != nil && (*newQuotaGB <= 0 || *newQuotaGB > 102400) { + return result, fmt.Errorf("`newQuotaGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetPropertiesOptions{ + input: properties, + }, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type SetPropertiesOptions struct { + input ShareProperties +} + +func (s SetPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if s.input.QuotaInGb != nil { + headers.Append("x-ms-share-quota", strconv.Itoa(*s.input.QuotaInGb)) + } + + if s.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*s.input.AccessTier)) + } + return headers +} + +func (s SetPropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (s SetPropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "properties") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/resource_id.go new file mode 100644 index 000000000000..c46092b4400f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/resource_id.go @@ -0,0 +1,81 @@ +package shares + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// GetResourceManagerResourceID returns the Resource Manager specific +// ResourceID for a specific Storage Share +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, shareName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/fileServices/default/shares/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, shareName) +} + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = ShareId{} + +type ShareId struct { + // AccountId specifies the ID of the Storage Account where this File Share exists. + AccountId accounts.AccountId + + // ShareName specifies the name of this File Share. + ShareName string +} + +func NewShareID(accountId accounts.AccountId, shareName string) ShareId { + return ShareId{ + AccountId: accountId, + ShareName: shareName, + } +} + +func (b ShareId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.ShareName) +} + +func (b ShareId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("File Share %q (%s)", b.ShareName, strings.Join(components, " / ")) +} + +// ParseShareID parses `input` into a Share ID using a known `domainSuffix` +func ParseShareID(input, domainSuffix string) (*ShareId, error) { + // example: https://foo.file.core.windows.net/Bar + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.FileSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.FileSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) == 0 { + return nil, fmt.Errorf("Expected the path to contain segments but got none") + } + + shareName := strings.TrimPrefix(uri.Path, "/") + return &ShareId{ + AccountId: *account, + ShareName: shareName, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_create.go new file mode 100644 index 000000000000..d4dff0328043 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_create.go @@ -0,0 +1,100 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type CreateSnapshotInput struct { + MetaData map[string]string +} + +type CreateSnapshotResponse struct { + HttpResponse *http.Response + + // This header is a DateTime value that uniquely identifies the share snapshot. + // The value of this header may be used in subsequent requests to access the share snapshot. + // This value is opaque. + SnapshotDateTime string +} + +// CreateSnapshot creates a read-only snapshot of the share +// A share can support creation of 200 share snapshots. Attempting to create more than 200 share snapshots fails with 409 (Conflict). +// Attempting to create a share snapshot while a previous Snapshot Share operation is in progress fails with 409 (Conflict). +func (c Client) CreateSnapshot(ctx context.Context, shareName string, input CreateSnapshotInput) (result CreateSnapshotResponse, err error) { + + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if err = metadata.Validate(input.MetaData); err != nil { + err = fmt.Errorf("`input.MetaData` is not valid: %+v", err) + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: snapShotCreateOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.SnapshotDateTime = resp.Header.Get("x-ms-snapshot") + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type snapShotCreateOptions struct { + metaData map[string]string +} + +func (s snapShotCreateOptions) ToHeaders() *client.Headers { + headers := metadata.SetMetaDataHeaders(s.metaData) + return &headers +} + +func (s snapShotCreateOptions) ToOData() *odata.Query { + return nil +} + +func (s snapShotCreateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "snapshot") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_delete.go new file mode 100644 index 000000000000..64dd532068a0 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_delete.go @@ -0,0 +1,80 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type DeleteSnapshotResponse struct { + HttpResponse *http.Response +} + +// DeleteSnapshot deletes the specified Snapshot of a Storage Share +func (c Client) DeleteSnapshot(ctx context.Context, accountName, shareName string, shareSnapshot string) (result DeleteSnapshotResponse, err error) { + + if shareName == "" { + return result, fmt.Errorf("`shareName` cannot be an empty string") + } + + if strings.ToLower(shareName) != shareName { + return result, fmt.Errorf("`shareName` must be a lower-cased string") + } + + if shareSnapshot == "" { + return result, fmt.Errorf("`shareSnapshot` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: snapShotDeleteOptions{ + shareSnapShot: shareSnapshot, + }, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type snapShotDeleteOptions struct { + shareSnapShot string +} + +func (s snapShotDeleteOptions) ToHeaders() *client.Headers { + return nil +} + +func (s snapShotDeleteOptions) ToOData() *odata.Query { + return nil +} + +func (s snapShotDeleteOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("sharesnapshot", s.shareSnapShot) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_get.go new file mode 100644 index 000000000000..e4aee485b016 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/snapshot_get.go @@ -0,0 +1,93 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetSnapshotPropertiesResponse struct { + HttpResponse *http.Response + + MetaData map[string]string +} + +type GetSnapshotPropertiesInput struct { + snapshotShare string +} + +// GetSnapshot gets information about the specified Snapshot of the specified Storage Share +func (c Client) GetSnapshot(ctx context.Context, shareName string, input GetSnapshotPropertiesInput) (result GetSnapshotPropertiesResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + if input.snapshotShare == "" { + err = fmt.Errorf("`snapshotShare` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: snapShotGetOptions{ + snapshotShare: input.snapshotShare, + }, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.MetaData = metadata.ParseFromHeaders(resp.Header) + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type snapShotGetOptions struct { + snapshotShare string +} + +func (s snapShotGetOptions) ToHeaders() *client.Headers { + return nil +} + +func (s snapShotGetOptions) ToOData() *odata.Query { + return nil +} + +func (s snapShotGetOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("snapshot", s.snapshotShare) + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/stats.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/stats.go new file mode 100644 index 000000000000..d375d837ed7e --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/stats.go @@ -0,0 +1,83 @@ +package shares + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetStatsResponse struct { + HttpResponse *http.Response + + // The approximate size of the data stored on the share. + // Note that this value may not include all recently created or recently resized files. + ShareUsageBytes int64 `xml:"ShareUsageBytes"` +} + +// GetStats returns information about the specified Storage Share +func (c Client) GetStats(ctx context.Context, shareName string) (result GetStatsResponse, err error) { + if shareName == "" { + err = fmt.Errorf("`shareName` cannot be an empty string") + return + } + + if strings.ToLower(shareName) != shareName { + err = fmt.Errorf("`shareName` must be a lower-cased string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: statsOptions{}, + Path: shareName, + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type statsOptions struct{} + +func (s statsOptions) ToHeaders() *client.Headers { + return nil +} + +func (s statsOptions) ToOData() *odata.Query { + return nil +} + +func (s statsOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "stats") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/version.go new file mode 100644 index 000000000000..6f62a9bdaf85 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares/version.go @@ -0,0 +1,4 @@ +package shares + +const apiVersion = "2023-11-03" +const componentName = "file/shares" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/README.md new file mode 100644 index 000000000000..745cc6d70ca5 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/README.md @@ -0,0 +1,53 @@ +## Queue Storage Queues SDK for API version 2023-11-03 + +This package allows you to interact with the Queues Queue Storage API + +### Supported Authorizers + +* Azure Active Directory (for the Resource Endpoint `https://storage.azure.com`) +* SharedKeyLite (Blob, File & Queue) + +### Example Usage + +```go +package main + +import ( + "context" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues" +) + +func Example() error { + accountName := "storageaccount1" + storageAccountKey := "ABC123...." + queueName := "myqueue" + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + queuesClient, err := queues.NewWithBaseUri(fmt.Sprintf("https://%s.queue.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + queuesClient.Client.SetAuthorizer(auth) + + ctx := context.TODO() + metadata := map[string]string{ + "hello": "world", + } + input := queues.CreateInput{ + Metadata: metadata, + } + if _, err := queuesClient.Create(ctx, queueName, input); err != nil { + return fmt.Errorf("Error creating Queue: %s", err) + } + + return nil +} +``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/api.go new file mode 100644 index 000000000000..e051453e47f0 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/api.go @@ -0,0 +1,15 @@ +package queues + +import ( + "context" +) + +type StorageQueue interface { + Delete(ctx context.Context, queueName string) (DeleteResponse, error) + GetMetaData(ctx context.Context, queueName string) (GetMetaDataResponse, error) + SetMetaData(ctx context.Context, queueName string, input SetMetaDataInput) (SetMetaDataResponse, error) + Create(ctx context.Context, queueName string, input CreateInput) (CreateResponse, error) + GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, queueName string) string + SetServiceProperties(ctx context.Context, input SetStorageServicePropertiesInput) (SetStorageServicePropertiesResponse, error) + GetServiceProperties(ctx context.Context) (GetStorageServicePropertiesResponse, error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/client.go new file mode 100644 index 000000000000..4497f0eb748c --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/client.go @@ -0,0 +1,24 @@ +package queues + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Queue Storage Shares. + +// Client is the base client for Messages. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/create.go new file mode 100644 index 000000000000..f548088ce288 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/create.go @@ -0,0 +1,87 @@ +package queues + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type CreateInput struct { + MetaData map[string]string +} + +type CreateResponse struct { + HttpResponse *http.Response +} + +// Create creates the specified Queue within the specified Storage Account +func (c Client) Create(ctx context.Context, queueName string, input CreateInput) (result CreateResponse, err error) { + + if queueName == "" { + return result, fmt.Errorf("`queueName` cannot be an empty string") + } + + if strings.ToLower(queueName) != queueName { + return result, fmt.Errorf("`queueName` must be a lower-cased string") + } + + if err := metadata.Validate(input.MetaData); err != nil { + return result, fmt.Errorf("`metadata` is not valid: %s", err) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: createOptions{ + metadata: input.MetaData, + }, + Path: fmt.Sprintf("/%s", queueName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type createOptions struct { + metadata map[string]string +} + +func (c createOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if len(c.metadata) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.metadata)) + } + return headers +} + +func (c createOptions) ToOData() *odata.Query { + return nil +} + +func (c createOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/delete.go new file mode 100644 index 000000000000..e8d7babb12fe --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/delete.go @@ -0,0 +1,54 @@ +package queues + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type DeleteResponse struct { + HttpResponse *http.Response +} + +// Delete deletes the specified Queue within the specified Storage Account +func (c Client) Delete(ctx context.Context, queueName string) (result DeleteResponse, err error) { + + if queueName == "" { + return result, fmt.Errorf("`queueName` cannot be an empty string") + } + + if strings.ToLower(queueName) != queueName { + return result, fmt.Errorf("`queueName` must be a lower-cased string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodDelete, + OptionsObject: nil, + Path: fmt.Sprintf("/%s", queueName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/metadata_get.go new file mode 100644 index 000000000000..c8a259f451ba --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/metadata_get.go @@ -0,0 +1,84 @@ +package queues + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type GetMetaDataResponse struct { + HttpResponse *http.Response + + MetaData map[string]string +} + +// GetMetaData returns the metadata for this Queue +func (c Client) GetMetaData(ctx context.Context, queueName string) (result GetMetaDataResponse, err error) { + + if queueName == "" { + return result, fmt.Errorf("`queueName` cannot be an empty string") + } + + if strings.ToLower(queueName) != queueName { + return result, fmt.Errorf("`queueName` must be a lower-cased string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getMetaDataOptions{}, + Path: fmt.Sprintf("/%s", queueName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + if resp.Header != nil { + result.MetaData = metadata.ParseFromHeaders(resp.Header) + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + if result.HttpResponse != nil { + if result.HttpResponse.Header != nil { + result.MetaData = metadata.ParseFromHeaders(result.HttpResponse.Header) + } + } + + return +} + +type getMetaDataOptions struct{} + +func (g getMetaDataOptions) ToHeaders() *client.Headers { + return nil +} + +func (g getMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (g getMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/metadata_set.go new file mode 100644 index 000000000000..6ab770de1f52 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/metadata_set.go @@ -0,0 +1,86 @@ +package queues + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +type SetMetaDataResponse struct { + HttpResponse *http.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + +// SetMetaData returns the metadata for this Queue +func (c Client) SetMetaData(ctx context.Context, queueName string, input SetMetaDataInput) (result SetMetaDataResponse, err error) { + + if queueName == "" { + return result, fmt.Errorf("`queueName` cannot be an empty string") + } + + if strings.ToLower(queueName) != queueName { + return result, fmt.Errorf("`queueName` must be a lower-cased string") + } + + if err := metadata.Validate(input.MetaData); err != nil { + return result, fmt.Errorf("`metadata` is not valid: %+v", err) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: setMetaDataOptions{ + metadata: input.MetaData, + }, + Path: fmt.Sprintf("/%s", queueName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type setMetaDataOptions struct { + metadata map[string]string +} + +func (s setMetaDataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Merge(metadata.SetMetaDataHeaders(s.metadata)) + return headers +} + +func (s setMetaDataOptions) ToOData() *odata.Query { + return nil +} + +func (s setMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/models.go similarity index 96% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/models.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/models.go index 2195244fa44b..fbbbce9634c4 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/models.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/models.go @@ -36,7 +36,7 @@ type Cors struct { type CorsRule struct { AllowedOrigins string `xml:"AllowedOrigins"` AllowedMethods string `xml:"AllowedMethods"` - AllowedHeaders string `xml:"AllowedHeaders` + AllowedHeaders string `xml:"AllowedHeaders"` ExposedHeaders string `xml:"ExposedHeaders"` MaxAgeInSeconds int `xml:"MaxAgeInSeconds"` } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/properties_get.go new file mode 100644 index 000000000000..0647f26d1b8f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/properties_get.go @@ -0,0 +1,70 @@ +package queues + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetStorageServicePropertiesResponse struct { + StorageServiceProperties + HttpResponse *http.Response +} + +// GetServiceProperties gets the properties for this queue +func (c Client) GetServiceProperties(ctx context.Context) (result GetStorageServicePropertiesResponse, err error) { + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getStorageServicePropertiesOptions{}, + Path: "/", + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type getStorageServicePropertiesOptions struct{} + +func (g getStorageServicePropertiesOptions) ToHeaders() *client.Headers { + return nil +} + +func (g getStorageServicePropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (g getStorageServicePropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "properties") + out.Append("restype", "service") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/properties_set.go new file mode 100644 index 000000000000..d80b6728b398 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/properties_set.go @@ -0,0 +1,80 @@ +package queues + +import ( + "bytes" + "context" + "encoding/xml" + "fmt" + "io" + "net/http" + "strconv" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type SetStorageServicePropertiesResponse struct { + HttpResponse *http.Response +} + +type SetStorageServicePropertiesInput struct { + Properties StorageServiceProperties +} + +// SetServiceProperties sets the properties for this queue +func (c Client) SetServiceProperties(ctx context.Context, input SetStorageServicePropertiesInput) (result SetStorageServicePropertiesResponse, err error) { + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: setStorageServicePropertiesOptions{}, + Path: "/", + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + marshalledProps, err := xml.Marshal(&input.Properties) + if err != nil { + return result, fmt.Errorf("marshalling request: %+v", err) + } + body := xml.Header + string(marshalledProps) + req.Body = io.NopCloser(bytes.NewReader([]byte(body))) + req.ContentLength = int64(len(body)) + req.Header.Set("Content-Length", strconv.Itoa(len(body))) + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type setStorageServicePropertiesOptions struct{} + +func (s setStorageServicePropertiesOptions) ToHeaders() *client.Headers { + return nil +} + +func (s setStorageServicePropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (s setStorageServicePropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "service") + out.Append("comp", "properties") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/resource_id.go new file mode 100644 index 000000000000..8acd0bb0ae74 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/resource_id.go @@ -0,0 +1,81 @@ +package queues + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// GetResourceManagerResourceID returns the Resource Manager ID for the given Queue +// This can be useful when, for example, you're using this as a unique identifier +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, queueName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/queueServices/default/queues/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, queueName) +} + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = QueueId{} + +type QueueId struct { + // AccountId specifies the ID of the Storage Account where this Queue exists. + AccountId accounts.AccountId + + // QueueName specifies the name of this Queue. + QueueName string +} + +func NewQueueID(accountId accounts.AccountId, queueName string) QueueId { + return QueueId{ + AccountId: accountId, + QueueName: queueName, + } +} + +func (b QueueId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.QueueName) +} + +func (b QueueId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Queue %q (%s)", b.QueueName, strings.Join(components, " / ")) +} + +// ParseQueueID parses `input` into a Queue ID using a known `domainSuffix` +func ParseQueueID(input, domainSuffix string) (*QueueId, error) { + // example: https://foo.queue.core.windows.net/Bar + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.QueueSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.QueueSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) + } + + queueName := strings.TrimPrefix(uri.Path, "/") + return &QueueId{ + AccountId: *account, + QueueName: queueName, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/version.go new file mode 100644 index 000000000000..c22267eb6e7d --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues/version.go @@ -0,0 +1,5 @@ +package queues + +// APIVersion is the version of the API used for all Storage API Operations +const apiVersion = "2023-11-03" +const componentName = "queue/queues" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/README.md new file mode 100644 index 000000000000..06b519b89423 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/README.md @@ -0,0 +1,55 @@ +## Table Storage Entities SDK for API version 2023-11-03 + +This package allows you to interact with the Entities Table Storage API + +### Supported Authorizers + +* SharedKeyLite (Table) + +### Example Usage + +```go +package main + +import ( + "context" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities" +) + +func Example() error { + accountName := "storageaccount1" + storageAccountKey := "ABC123...." + tableName := "mytable" + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKeyTable) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + entitiesClient, err := entities.NewWithBaseUri(fmt.Sprintf("https://%s.table.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + entitiesClient.Client.SetAuthorizer(auth) + + ctx := context.TODO() + input := entities.InsertEntityInput{ + PartitionKey: "abc", + RowKey: "123", + MetaDataLevel: entities.NoMetaData, + Entity: map[string]interface{}{ + "title": "Don't Kill My Vibe", + "artist": "Sigrid", + }, + } + if _, err := entitiesClient.Insert(ctx, tableName, input); err != nil { + return fmt.Errorf("Error creating Entity: %s", err) + } + + return nil +} +``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/api.go new file mode 100644 index 000000000000..bb0e9809e3c9 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/api.go @@ -0,0 +1,14 @@ +package entities + +import ( + "context" +) + +type StorageTableEntity interface { + Delete(ctx context.Context, tableName string, input DeleteEntityInput) (resp DeleteEntityResponse, err error) + Insert(ctx context.Context, tableName string, input InsertEntityInput) (resp InsertResponse, err error) + InsertOrReplace(ctx context.Context, tableName string, input InsertOrReplaceEntityInput) (resp InsertOrReplaceResponse, err error) + InsertOrMerge(ctx context.Context, tableName string, input InsertOrMergeEntityInput) (resp InsertOrMergeResponse, err error) + Query(ctx context.Context, tableName string, input QueryEntitiesInput) (resp QueryEntitiesResponse, err error) + Get(ctx context.Context, tableName string, input GetEntityInput) (resp GetEntityResponse, err error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/client.go new file mode 100644 index 000000000000..e190af69d108 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/client.go @@ -0,0 +1,23 @@ +package entities + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Table Storage Shares. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/delete.go new file mode 100644 index 000000000000..61e7c712ac5e --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/delete.go @@ -0,0 +1,84 @@ +package entities + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type DeleteEntityInput struct { + // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. + // Together, these properties form the primary key and must be unique within the table. + // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. + // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, + // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. + RowKey string + PartitionKey string +} + +type DeleteEntityResponse struct { + HttpResponse *http.Response +} + +// Delete deletes an existing entity in a table. +func (c Client) Delete(ctx context.Context, tableName string, input DeleteEntityInput) (result DeleteEntityResponse, err error) { + + if tableName == "" { + return result, fmt.Errorf("`tableName` cannot be an empty string") + } + + if input.PartitionKey == "" { + return result, fmt.Errorf("`input.PartitionKey` cannot be an empty string") + } + + if input.RowKey == "" { + return result, fmt.Errorf("`input.RowKey` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteEntitiesOptions{}, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + return +} + +type deleteEntitiesOptions struct{} + +func (d deleteEntitiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + headers.Append("If-Match", "*") + return headers +} + +func (d deleteEntitiesOptions) ToOData() *odata.Query { + return nil +} + +func (d deleteEntitiesOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/get.go new file mode 100644 index 000000000000..daf428acdffa --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/get.go @@ -0,0 +1,94 @@ +package entities + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetEntityInput struct { + PartitionKey string + RowKey string + + // The Level of MetaData which should be returned + MetaDataLevel MetaDataLevel +} + +type GetEntityResponse struct { + HttpResponse *http.Response + + Entity map[string]interface{} +} + +// Get queries entities in a table and includes the $filter and $select options. +func (c Client) Get(ctx context.Context, tableName string, input GetEntityInput) (result GetEntityResponse, err error) { + if tableName == "" { + return result, fmt.Errorf("`tableName` cannot be an empty string") + } + + if input.PartitionKey == "" { + return result, fmt.Errorf("`input.PartitionKey` cannot be an empty string") + } + + if input.RowKey == "" { + return result, fmt.Errorf("`input.RowKey` cannot be an empty string") + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getEntitiesOptions{ + MetaDataLevel: input.MetaDataLevel, + }, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result.Entity) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type getEntitiesOptions struct { + MetaDataLevel MetaDataLevel +} + +func (g getEntitiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", g.MetaDataLevel)) + headers.Append("DataServiceVersion", "3.0;NetFx") + headers.Append("MaxDataServiceVersion", "3.0;NetFx") + return headers +} + +func (g getEntitiesOptions) ToOData() *odata.Query { + return nil +} + +func (g getEntitiesOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert.go new file mode 100644 index 000000000000..1996ba8b9cef --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert.go @@ -0,0 +1,104 @@ +package entities + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type InsertEntityInput struct { + // The level of MetaData provided for this Entity + MetaDataLevel MetaDataLevel + + // The Entity which should be inserted, by default all values are strings + // To explicitly type a property, specify the appropriate OData data type by setting + // the m:type attribute within the property definition + Entity map[string]interface{} + + // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. + // Together, these properties form the primary key and must be unique within the table. + // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. + // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, + // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. + RowKey string + PartitionKey string +} + +type InsertResponse struct { + HttpResponse *http.Response +} + +// Insert inserts a new entity into a table. +func (c Client) Insert(ctx context.Context, tableName string, input InsertEntityInput) (result InsertResponse, err error) { + if tableName == "" { + return result, fmt.Errorf("`tableName` cannot be an empty string") + } + + if input.PartitionKey == "" { + return result, fmt.Errorf("`input.PartitionKey` cannot be an empty string") + } + + if input.RowKey == "" { + return result, fmt.Errorf("`input.RowKey` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPost, + OptionsObject: insertOptions{ + MetaDataLevel: input.MetaDataLevel, + }, + Path: fmt.Sprintf("/%s", tableName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + input.Entity["PartitionKey"] = input.PartitionKey + input.Entity["RowKey"] = input.RowKey + + err = req.Marshal(&input.Entity) + if err != nil { + return result, fmt.Errorf("marshalling request: %+v", err) + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type insertOptions struct { + MetaDataLevel MetaDataLevel +} + +func (i insertOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", i.MetaDataLevel)) + headers.Append("Prefer", "return-no-content") + return headers +} + +func (i insertOptions) ToOData() *odata.Query { + return nil +} + +func (i insertOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert_or_merge.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert_or_merge.go new file mode 100644 index 000000000000..8ec8191f6ea5 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert_or_merge.go @@ -0,0 +1,98 @@ +package entities + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type InsertOrMergeEntityInput struct { + // The Entity which should be inserted, by default all values are strings + // To explicitly type a property, specify the appropriate OData data type by setting + // the m:type attribute within the property definition + Entity map[string]interface{} + + // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. + // Together, these properties form the primary key and must be unique within the table. + // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. + // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, + // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. + RowKey string + PartitionKey string +} + +type InsertOrMergeResponse struct { + HttpResponse *http.Response +} + +// InsertOrMerge updates an existing entity or inserts a new entity if it does not exist in the table. +// Because this operation can insert or update an entity, it is also known as an upsert operation. +func (c Client) InsertOrMerge(ctx context.Context, tableName string, input InsertOrMergeEntityInput) (result InsertOrMergeResponse, err error) { + if tableName == "" { + return result, fmt.Errorf("`tableName` cannot be an empty string") + } + + if input.PartitionKey == "" { + return result, fmt.Errorf("`input.PartitionKey` cannot be an empty string") + } + + if input.RowKey == "" { + return result, fmt.Errorf("`input.RowKey` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: "MERGE", + OptionsObject: insertOrMergeOptions{}, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + input.Entity["PartitionKey"] = input.PartitionKey + input.Entity["RowKey"] = input.RowKey + + err = req.Marshal(&input.Entity) + if err != nil { + return result, fmt.Errorf("marshalling request: %+v", err) + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type insertOrMergeOptions struct{} + +func (i insertOrMergeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + headers.Append("Prefer", "return-no-content") + return headers +} + +func (i insertOrMergeOptions) ToOData() *odata.Query { + return nil +} + +func (i insertOrMergeOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert_or_replace.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert_or_replace.go new file mode 100644 index 000000000000..269437c06cae --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/insert_or_replace.go @@ -0,0 +1,98 @@ +package entities + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type InsertOrReplaceEntityInput struct { + // The Entity which should be inserted, by default all values are strings + // To explicitly type a property, specify the appropriate OData data type by setting + // the m:type attribute within the property definition + Entity map[string]interface{} + + // When inserting an entity into a table, you must specify values for the PartitionKey and RowKey system properties. + // Together, these properties form the primary key and must be unique within the table. + // Both the PartitionKey and RowKey values must be string values; each key value may be up to 64 KB in size. + // If you are using an integer value for the key value, you should convert the integer to a fixed-width string, + // because they are canonically sorted. For example, you should convert the value 1 to 0000001 to ensure proper sorting. + RowKey string + PartitionKey string +} + +type InsertOrReplaceResponse struct { + HttpResponse *http.Response +} + +// InsertOrReplace replaces an existing entity or inserts a new entity if it does not exist in the table. +// Because this operation can insert or update an entity, it is also known as an upsert operation. +func (c Client) InsertOrReplace(ctx context.Context, tableName string, input InsertOrReplaceEntityInput) (result InsertOrReplaceResponse, err error) { + if tableName == "" { + return result, fmt.Errorf("`tableName` cannot be an empty string") + } + + if input.PartitionKey == "" { + return result, fmt.Errorf("`input.PartitionKey` cannot be an empty string") + } + + if input.RowKey == "" { + return result, fmt.Errorf("`input.RowKey` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: "MERGE", + OptionsObject: insertOrReplaceOptions{}, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + input.Entity["PartitionKey"] = input.PartitionKey + input.Entity["RowKey"] = input.RowKey + + err = req.Marshal(&input.Entity) + if err != nil { + return result, fmt.Errorf("marshalling request: %+v", err) + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type insertOrReplaceOptions struct{} + +func (i insertOrReplaceOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + headers.Append("Prefer", "return-no-content") + return headers +} + +func (i insertOrReplaceOptions) ToOData() *odata.Query { + return nil +} + +func (i insertOrReplaceOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/models.go similarity index 100% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/models.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/models.go diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/query.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/query.go new file mode 100644 index 000000000000..57b411a55bf6 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/query.go @@ -0,0 +1,143 @@ +package entities + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type QueryEntitiesInput struct { + // An optional OData filter + Filter *string + + // An optional comma-separated + PropertyNamesToSelect *[]string + + // An optional OData top + Top *int + + PartitionKey string + RowKey string + + // The Level of MetaData which should be returned + MetaDataLevel MetaDataLevel + + // The Next Partition Key used to load data from a previous point + NextPartitionKey *string + + // The Next Row Key used to load data from a previous point + NextRowKey *string +} + +type QueryEntitiesResponse struct { + HttpResponse *http.Response + + NextPartitionKey string + NextRowKey string + + MetaData string `json:"odata.metadata,omitempty"` + Entities []map[string]interface{} `json:"value"` +} + +// Query queries entities in a table and includes the $filter and $select options. +func (c Client) Query(ctx context.Context, tableName string, input QueryEntitiesInput) (result QueryEntitiesResponse, err error) { + if tableName == "" { + return result, fmt.Errorf("`tableName` cannot be an empty string") + } + + additionalParameters := make([]string, 0) + if input.PartitionKey != "" { + additionalParameters = append(additionalParameters, "PartitionKey='%s'", input.PartitionKey) + } + + if input.RowKey != "" { + additionalParameters = append(additionalParameters, "RowKey='%s'", input.RowKey) + } + + path := fmt.Sprintf("/%s", tableName) + if len(additionalParameters) > 0 { + path += fmt.Sprintf("(%s)", strings.Join(additionalParameters, ",")) + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: queryOptions{ + input: input, + }, + Path: path, + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type queryOptions struct { + input QueryEntitiesInput +} + +func (q queryOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", q.input.MetaDataLevel)) + headers.Append("DataServiceVersion", "3.0;NetFx") + headers.Append("MaxDataServiceVersion", "3.0;NetFx") + return headers +} + +func (q queryOptions) ToOData() *odata.Query { + return nil +} + +func (q queryOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + + if q.input.Filter != nil { + out.Append("$filter", *q.input.Filter) + } + + if q.input.PropertyNamesToSelect != nil { + out.Append("$select", strings.Join(*q.input.PropertyNamesToSelect, ",")) + } + + if q.input.Top != nil { + out.Append("$top", strconv.Itoa(*q.input.Top)) + } + + if q.input.NextPartitionKey != nil { + out.Append("NextPartitionKey", *q.input.NextPartitionKey) + } + + if q.input.NextRowKey != nil { + out.Append("NextRowKey", *q.input.NextRowKey) + } + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/resource_id.go new file mode 100644 index 000000000000..741c24bfc5ca --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/resource_id.go @@ -0,0 +1,127 @@ +package entities + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = EntityId{} + +type EntityId struct { + // AccountId specifies the ID of the Storage Account where this Entity exists. + AccountId accounts.AccountId + + // TableName specifies the name of the Table where this Entity exists. + TableName string + + // PartitionKey specifies the Partition Key for this Entity. + PartitionKey string + + // RowKey specifies the Row Key for this Entity. + RowKey string +} + +func NewEntityID(accountId accounts.AccountId, tableName, partitionKey, rowKey string) EntityId { + return EntityId{ + AccountId: accountId, + TableName: tableName, + PartitionKey: partitionKey, + RowKey: rowKey, + } +} + +func (b EntityId) ID() string { + return fmt.Sprintf("%s/%s(PartitionKey='%s',RowKey='%s')", b.AccountId.ID(), b.TableName, b.PartitionKey, b.RowKey) +} + +func (b EntityId) String() string { + components := []string{ + fmt.Sprintf("Partition Key %q", b.PartitionKey), + fmt.Sprintf("Row Key %q", b.RowKey), + fmt.Sprintf("Table Name %q", b.TableName), + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Entity (%s)", strings.Join(components, " / ")) +} + +// ParseEntityID parses `input` into a Entity ID using a known `domainSuffix` +func ParseEntityID(input, domainSuffix string) (*EntityId, error) { + // example: https://foo.table.core.windows.net/bar(PartitionKey='partition1',RowKey='row1') + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.TableSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.TableSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) + } + + // Tables and Table Entities are similar with table being `table1` and entities + // being `table1(PartitionKey='samplepartition',RowKey='samplerow')` so we need to validate this is a table + slug := strings.TrimPrefix(uri.Path, "/") + if strings.HasPrefix(slug, "Tables('") && strings.HasSuffix(slug, "')") { + // Ensure we do not parse a Table ID in the format: https://foo.table.core.windows.net/Table('foo') + return nil, fmt.Errorf("expected the path to be an entity name but got a table name: %q", slug) + } else if !strings.Contains(slug, "(") || !strings.HasSuffix(slug, ")") { + // Ensure we do not try to parse a bare table name + return nil, fmt.Errorf("expected the path to be an entity name but got an invalid format, possibly a table name: %q", slug) + } + + indexOfFirstBracket := strings.Index(slug, "(") + tableName := slug[0:indexOfFirstBracket] + componentString := slug[indexOfFirstBracket:] + componentString = strings.TrimPrefix(componentString, "(") + componentString = strings.TrimSuffix(componentString, ")") + components := strings.Split(componentString, ",") + if len(components) != 2 { + return nil, fmt.Errorf("expected the path to be an entity name but got %q", slug) + } + + partitionKey := parseValueFromKey(components[0], "PartitionKey") + rowKey := parseValueFromKey(components[1], "RowKey") + + return &EntityId{ + AccountId: *account, + TableName: tableName, + PartitionKey: *partitionKey, + RowKey: *rowKey, + }, nil +} + +func parseValueFromKey(input, expectedKey string) *string { + components := strings.Split(input, "=") + if len(components) != 2 { + return nil + } + key := components[0] + value := components[1] + if key != expectedKey { + return nil + } + + // the value is surrounded in single quotes, remove those + value = strings.TrimPrefix(value, "'") + value = strings.TrimSuffix(value, "'") + return &value +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/version.go new file mode 100644 index 000000000000..5eae649209e3 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities/version.go @@ -0,0 +1,4 @@ +package entities + +const apiVersion = "2023-11-03" +const componentName = "table/entities" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/README.md new file mode 100644 index 000000000000..65a459f79dcd --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/README.md @@ -0,0 +1,45 @@ +## Table Storage Tables SDK for API version 2023-11-03 + +This package allows you to interact with the Tables Table Storage API + +### Supported Authorizers + +* SharedKeyLite (Table) + +### Example Usage + +```go +package main + +import ( + "context" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables" +) + +func Example() error { + accountName := "storageaccount1" + storageAccountKey := "ABC123...." + tableName := "mytable" + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKeyTable) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + tablesClient, err := tables.NewWithBaseUri(fmt.Sprintf("https://%s.table.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + tablesClient.Client.SetAuthorizer(auth) + + ctx := context.TODO() + if _, err := tablesClient.Create(ctx, tableName); err != nil { + return fmt.Errorf("Error creating Table: %s", err) + } + + return nil +} +``` \ No newline at end of file diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/acl_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/acl_get.go new file mode 100644 index 000000000000..3f2f2a18692f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/acl_get.go @@ -0,0 +1,75 @@ +package tables + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetACLResponse struct { + HttpResponse *http.Response + + SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` +} + +// GetACL returns the Access Control List for the specified Table +func (c Client) GetACL(ctx context.Context, tableName string) (result GetACLResponse, err error) { + + if tableName == "" { + err = fmt.Errorf("`tableName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getAclTableOptions{}, + Path: fmt.Sprintf("/%s", tableName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type getAclTableOptions struct{} + +func (g getAclTableOptions) ToHeaders() *client.Headers { + return nil +} + +func (g getAclTableOptions) ToOData() *odata.Query { + return nil +} + +func (g getAclTableOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "acl") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/acl_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/acl_set.go new file mode 100644 index 000000000000..9749bd062c5f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/acl_set.go @@ -0,0 +1,79 @@ +package tables + +import ( + "context" + "encoding/xml" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type setAcl struct { + SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` + + XMLName xml.Name `xml:"SignedIdentifiers"` +} + +type SetACLResponse struct { + HttpResponse *http.Response +} + +// SetACL sets the specified Access Control List for the specified Table +func (c Client) SetACL(ctx context.Context, tableName string, acls []SignedIdentifier) (result SetACLResponse, err error) { + if tableName == "" { + err = fmt.Errorf("`tableName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: setAclTableOptions{}, + Path: fmt.Sprintf("/%s", tableName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + err = req.Marshal(setAcl{SignedIdentifiers: acls}) + if err != nil { + err = fmt.Errorf("marshalling request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type setAclTableOptions struct{} + +func (s setAclTableOptions) ToHeaders() *client.Headers { + return nil +} + +func (s setAclTableOptions) ToOData() *odata.Query { + return nil +} + +func (s setAclTableOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "acl") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/api.go new file mode 100644 index 000000000000..75c1de621410 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/api.go @@ -0,0 +1,15 @@ +package tables + +import ( + "context" +) + +type StorageTable interface { + Delete(ctx context.Context, tableName string) (resp DeleteTableResponse, err error) + Exists(ctx context.Context, tableName string) (resp TableExistsResponse, err error) + GetACL(ctx context.Context, tableName string) (resp GetACLResponse, err error) + Create(ctx context.Context, tableName string) (resp CreateTableResponse, err error) + GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, tableName string) string + Query(ctx context.Context, input QueryInput) (resp GetResponse, err error) + SetACL(ctx context.Context, tableName string, acls []SignedIdentifier) (resp SetACLResponse, err error) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/client.go new file mode 100644 index 000000000000..49c714dcdd82 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/client.go @@ -0,0 +1,23 @@ +package tables + +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" +) + +// Client is the base client for Table Storage Shares. +type Client struct { + Client *storage.Client +} + +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewStorageClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) + } + + return &Client{ + Client: baseClient, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/create.go new file mode 100644 index 000000000000..6adfd5ab5e36 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/create.go @@ -0,0 +1,76 @@ +package tables + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type createTableRequest struct { + TableName string `json:"TableName"` +} + +type CreateTableResponse struct { + HttpResponse *http.Response +} + +// Create creates a new table in the storage account. +func (c Client) Create(ctx context.Context, tableName string) (result CreateTableResponse, err error) { + if tableName == "" { + err = fmt.Errorf("`tableName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPost, + OptionsObject: createTableOptions{}, + Path: "/Tables", + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + err = req.Marshal(&createTableRequest{TableName: tableName}) + if err != nil { + return result, fmt.Errorf("marshalling request") + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type createTableOptions struct{} + +func (c createTableOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json;odata=nometadata") + headers.Append("Prefer", "return-no-content") + return headers +} + +func (c createTableOptions) ToOData() *odata.Query { + return nil +} + +func (c createTableOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/delete.go new file mode 100644 index 000000000000..b1fab65b30c0 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/delete.go @@ -0,0 +1,67 @@ +package tables + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type DeleteTableResponse struct { + HttpResponse *http.Response +} + +// Delete deletes the specified table and any data it contains. +func (c Client) Delete(ctx context.Context, tableName string) (result DeleteTableResponse, err error) { + if tableName == "" { + err = fmt.Errorf("`tableName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteOptions{}, + Path: fmt.Sprintf("/Tables('%s')", tableName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type deleteOptions struct { +} + +func (d deleteOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + return headers +} + +func (d deleteOptions) ToOData() *odata.Query { + return nil +} + +func (d deleteOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/exists.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/exists.go new file mode 100644 index 000000000000..dc8a43ae3716 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/exists.go @@ -0,0 +1,66 @@ +package tables + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type TableExistsResponse struct { + HttpResponse *http.Response +} + +// Exists checks that the specified table exists +func (c Client) Exists(ctx context.Context, tableName string) (result TableExistsResponse, err error) { + if tableName == "" { + err = fmt.Errorf("`tableName` cannot be an empty string") + return + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: tableExistsOptions{}, + Path: fmt.Sprintf("/Tables('%s')", tableName), + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type tableExistsOptions struct{} + +func (t tableExistsOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json;odata=nometadata") + return headers +} + +func (t tableExistsOptions) ToOData() *odata.Query { + return nil +} + +func (t tableExistsOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/models.go similarity index 100% rename from vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/models.go rename to vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/models.go diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/query.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/query.go new file mode 100644 index 000000000000..4cc07ead352e --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/query.go @@ -0,0 +1,81 @@ +package tables + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +type GetResponse struct { + HttpResponse *http.Response + + MetaData string `json:"odata.metadata,omitempty"` + Tables []GetResultItem `json:"value"` +} + +type QueryInput struct { + MetaDataLevel MetaDataLevel +} + +// Query returns a list of tables under the specified account. +func (c Client) Query(ctx context.Context, input QueryInput) (result GetResponse, err error) { + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: queryOptions{ + metaDataLevel: input.MetaDataLevel, + }, + Path: "/Tables", + } + + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { + err = fmt.Errorf("building request: %+v", err) + return + } + + var resp *client.Response + resp, err = req.Execute(ctx) + if resp != nil { + result.HttpResponse = resp.Response + + err = resp.Unmarshal(&result) + if err != nil { + err = fmt.Errorf("unmarshalling response: %+v", err) + return + } + } + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return + } + + return +} + +type queryOptions struct { + metaDataLevel MetaDataLevel +} + +func (q queryOptions) ToHeaders() *client.Headers { + // NOTE: whilst this supports ContinuationTokens and 'Top' + // it appears that 'Skip' returns a '501 Not Implemented' + // as such, we intentionally don't support those right now + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", q.metaDataLevel)) + return headers +} + +func (q queryOptions) ToOData() *odata.Query { + return nil +} + +func (q queryOptions) ToQuery() *client.QueryParams { + return nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/resource_id.go new file mode 100644 index 000000000000..2dcf79f670ac --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/resource_id.go @@ -0,0 +1,101 @@ +package tables + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts" +) + +// GetResourceManagerResourceID returns the Resource ID for the given Table +// This can be useful when, for example, you're using this as a unique identifier +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, tableName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/tableServices/default/tables/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, tableName) +} + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = TableId{} + +type TableId struct { + // AccountId specifies the ID of the Storage Account where this Table exists. + AccountId accounts.AccountId + + // TableName specifies the name of this Table. + TableName string +} + +func NewTableID(accountId accounts.AccountId, tableName string) TableId { + return TableId{ + AccountId: accountId, + TableName: tableName, + } +} + +func (b TableId) ID() string { + return fmt.Sprintf("%s/Tables('%s')", b.AccountId.ID(), b.TableName) +} + +func (b TableId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Table %q (%s)", b.TableName, strings.Join(components, " / ")) +} + +// ParseTableID parses `input` into a Table ID using a known `domainSuffix` +func ParseTableID(input, domainSuffix string) (*TableId, error) { + // example: https://foo.table.core.windows.net/Table('bar') + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) + if err != nil { + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.TableSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.TableSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) + } + + // Tables and Table Entities are similar however Tables use a reserved namespace, for example: + // Table('tableName') + // whereas Entities begin with the actual table name, for example: + // tableName(PartitionKey='samplepartition',RowKey='samplerow') + // However, there was a period of time when Table IDs did not use the reserved namespace, so we attempt to parse + // both forms for maximum compatibility. + var tableName string + slug := strings.TrimPrefix(uri.Path, "/") + if strings.HasPrefix(slug, "Tables('") && strings.HasSuffix(slug, "')") { + // Ensure both prefix and suffix are present before trimming them out + tableName = strings.TrimSuffix(strings.TrimPrefix(slug, "Tables('"), "')") + } else if !strings.Contains(slug, "(") && !strings.HasSuffix(slug, ")") { + // Also accept a bare table name + tableName = slug + } else { + return nil, fmt.Errorf("expected the path to a table name and not an entity name but got %q", tableName) + } + if tableName == "" { + return nil, fmt.Errorf("expected the path to a table name but the path was empty") + } + + return &TableId{ + AccountId: *account, + TableName: tableName, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/version.go new file mode 100644 index 000000000000..63c317fdfa2c --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables/version.go @@ -0,0 +1,4 @@ +package tables + +const apiVersion = "2023-11-03" +const componentName = "table/tables" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/endpoints/endpoints.go b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/endpoints/endpoints.go deleted file mode 100644 index 2c58e8f69b03..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/endpoints/endpoints.go +++ /dev/null @@ -1,39 +0,0 @@ -package endpoints - -import ( - "fmt" - "strings" -) - -func GetAccountNameFromEndpoint(endpoint string) (*string, error) { - segments := strings.Split(endpoint, ".") - if len(segments) == 0 { - return nil, fmt.Errorf("The Endpoint contained no segments") - } - return &segments[0], nil -} - -// GetBlobEndpoint returns the endpoint for Blob API Operations on this storage account -func GetBlobEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.blob.%s", accountName, baseUri) -} - -// GetDataLakeStoreEndpoint returns the endpoint for Data Lake Store API Operations on this storage account -func GetDataLakeStoreEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.dfs.%s", accountName, baseUri) -} - -// GetFileEndpoint returns the endpoint for File Share API Operations on this storage account -func GetFileEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.file.%s", accountName, baseUri) -} - -// GetQueueEndpoint returns the endpoint for Queue API Operations on this storage account -func GetQueueEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.queue.%s", accountName, baseUri) -} - -// GetTableEndpoint returns the endpoint for Table API Operations on this storage account -func GetTableEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.table.%s", accountName, baseUri) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go index 1880d409a7db..5f613ab7d15b 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go @@ -5,16 +5,19 @@ import ( "strings" ) -// ParseFromHeaders parses the meta data from the headers +// ParseFromHeaders parses the metadata from the headers func ParseFromHeaders(headers http.Header) map[string]string { metaData := make(map[string]string, 0) + prefix := "x-ms-meta-" for k, v := range headers { key := strings.ToLower(k) - prefix := "x-ms-meta-" if !strings.HasPrefix(key, prefix) { continue } + // TODO: update this to support case-insensitive headers when the base layer is changed to `hashicorp/go-azure-sdk` + // (e.g. trim off the first 10 characters, but this can't be done until the base layer is updated, since + // `Azure/go-autorest` canonicalizes the header keys) key = strings.TrimPrefix(key, prefix) metaData[key] = v[0] } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go index d88fbd766b63..6006159f78cf 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go @@ -1,6 +1,10 @@ package metadata -import "fmt" +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) // SetIntoHeaders sets the provided MetaData into the headers func SetIntoHeaders(headers map[string]interface{}, metaData map[string]string) map[string]interface{} { @@ -11,3 +15,13 @@ func SetIntoHeaders(headers map[string]interface{}, metaData map[string]string) return headers } + +// SetMetaDataHeaders sets the provided MetaData into the headers +func SetMetaDataHeaders(metaData map[string]string) client.Headers { + headers := client.Headers{} + for k, v := range metaData { + key := fmt.Sprintf("x-ms-meta-%s", k) + headers.Append(key, v) + } + return headers +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/version/version.go b/vendor/github.com/tombuildsstuff/giovanni/version/version.go deleted file mode 100644 index 45a0da69aa76..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/version/version.go +++ /dev/null @@ -1,3 +0,0 @@ -package version - -const Number = "v0.17.0" diff --git a/vendor/modules.txt b/vendor/modules.txt index fd2a11a5e9a6..6c387386f3c4 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -127,7 +127,7 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/google/uuid v1.3.1 +# github.com/google/uuid v1.4.0 ## explicit github.com/google/uuid # github.com/hashicorp/errwrap v1.1.0 @@ -1063,6 +1063,8 @@ github.com/hashicorp/go-azure-sdk/sdk/auth github.com/hashicorp/go-azure-sdk/sdk/auth/autorest github.com/hashicorp/go-azure-sdk/sdk/claims github.com/hashicorp/go-azure-sdk/sdk/client +github.com/hashicorp/go-azure-sdk/sdk/client/dataplane +github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage github.com/hashicorp/go-azure-sdk/sdk/client/msgraph github.com/hashicorp/go-azure-sdk/sdk/client/pollers github.com/hashicorp/go-azure-sdk/sdk/client/resourcemanager @@ -1254,23 +1256,21 @@ github.com/rickb777/plural # github.com/sergi/go-diff v1.2.0 ## explicit; go 1.12 github.com/sergi/go-diff/diffmatchpatch -# github.com/tombuildsstuff/giovanni v0.20.0 -## explicit; go 1.13 -github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts -github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs -github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers -github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems -github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths -github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories -github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files -github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares -github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues -github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities -github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables +# github.com/tombuildsstuff/giovanni v0.25.1 +## explicit; go 1.21 +github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/accounts +github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/blobs +github.com/tombuildsstuff/giovanni/storage/2023-11-03/blob/containers +github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/filesystems +github.com/tombuildsstuff/giovanni/storage/2023-11-03/datalakestore/paths +github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/directories +github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/files +github.com/tombuildsstuff/giovanni/storage/2023-11-03/file/shares +github.com/tombuildsstuff/giovanni/storage/2023-11-03/queue/queues +github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/entities +github.com/tombuildsstuff/giovanni/storage/2023-11-03/table/tables github.com/tombuildsstuff/giovanni/storage/accesscontrol -github.com/tombuildsstuff/giovanni/storage/internal/endpoints github.com/tombuildsstuff/giovanni/storage/internal/metadata -github.com/tombuildsstuff/giovanni/version # github.com/tombuildsstuff/kermit v0.20240122.1123108 ## explicit; go 1.18 github.com/tombuildsstuff/kermit/sdk/appconfiguration/1.0/appconfiguration diff --git a/website/docs/d/storage_share.html.markdown b/website/docs/d/storage_share.html.markdown index 20763c76e730..d4e0bbbdda16 100644 --- a/website/docs/d/storage_share.html.markdown +++ b/website/docs/d/storage_share.html.markdown @@ -10,6 +10,8 @@ description: |- Use this data source to access information about an existing File Share. +~> **Note on Authentication** Shared Key authentication will always be used for this data source, as AzureAD authentication is not supported by the Storage API for files. + ## Example Usage ```hcl diff --git a/website/docs/index.html.markdown b/website/docs/index.html.markdown index 9555c1bf6ad6..8a9f14886329 100644 --- a/website/docs/index.html.markdown +++ b/website/docs/index.html.markdown @@ -201,7 +201,7 @@ For some advanced scenarios, such as where more granular permissions are necessa ~> **Note:** This requires that the User/Service Principal being used has the associated `Storage` roles - which are added to new Contributor/Owner role-assignments, but **have not** been backported by Azure to existing role-assignments. -~> **Note:** The Files & Table Storage API's do not support authenticating via AzureAD and will continue to use a SharedKey to access the API's. +~> **Note:** The Files Storage API does not support authenticating via AzureAD and will continue to use a SharedKey when AAD authentication is enabled. * `use_msal` - (Optional) When `true`, and when using service principal authentication, the provider will obtain [v2 authentication tokens](https://docs.microsoft.com/azure/active-directory/develop/access-tokens#token-formats-and-ownership) from the Microsoft Identity Platform. Has no effect when authenticating via Managed Identity or the Azure CLI. Can also be set via the `ARM_USE_MSAL` or `ARM_USE_MSGRAPH` environment variables. diff --git a/website/docs/r/storage_container.html.markdown b/website/docs/r/storage_container.html.markdown index 33465c9183f4..2136d1f4fdca 100644 --- a/website/docs/r/storage_container.html.markdown +++ b/website/docs/r/storage_container.html.markdown @@ -47,6 +47,8 @@ The following arguments are supported: * `container_access_type` - (Optional) The Access Level configured for this Container. Possible values are `blob`, `container` or `private`. Defaults to `private`. +~> **Note** When updating `container_access_type` for an existing storage container resource, Shared Key authentication will always be used, as AzureAD authentication is not supported. + * `metadata` - (Optional) A mapping of MetaData for this Container. All metadata keys should be lowercase. ## Attributes Reference diff --git a/website/docs/r/storage_share.html.markdown b/website/docs/r/storage_share.html.markdown index e79dc16d0f6d..7fd0544df73d 100644 --- a/website/docs/r/storage_share.html.markdown +++ b/website/docs/r/storage_share.html.markdown @@ -10,7 +10,9 @@ description: |- Manages a File Share within Azure Storage. -~> **Note:** The storage share supports two storage tiers: premium and standard. Standard file shares are created in general purpose (GPv1 or GPv2) storage accounts and premium file shares are created in FileStorage storage accounts. For further information, refer to the section "What storage tiers are supported in Azure Files?" of [documentation](https://docs.microsoft.com/azure/storage/files/storage-files-faq#general). +~> **Note** The storage share supports two storage tiers: premium and standard. Standard file shares are created in general purpose (GPv1 or GPv2) storage accounts and premium file shares are created in FileStorage storage accounts. For further information, refer to the section "What storage tiers are supported in Azure Files?" of [documentation](https://docs.microsoft.com/azure/storage/files/storage-files-faq#general). + +~> **Note on Authentication** Shared Key authentication will always be used for this resource, as AzureAD authentication is not supported by the Storage API for files. ## Example Usage diff --git a/website/docs/r/storage_share_directory.html.markdown b/website/docs/r/storage_share_directory.html.markdown index e758c74abe46..8cba5456992a 100644 --- a/website/docs/r/storage_share_directory.html.markdown +++ b/website/docs/r/storage_share_directory.html.markdown @@ -33,9 +33,8 @@ resource "azurerm_storage_share" "example" { } resource "azurerm_storage_share_directory" "example" { - name = "example" - share_name = azurerm_storage_share.example.name - storage_account_name = azurerm_storage_account.example.name + name = "example" + storage_share_id = azurerm_storage_share.example.id } ``` @@ -45,9 +44,7 @@ The following arguments are supported: * `name` - (Required) The name (or path) of the Directory that should be created within this File Share. Changing this forces a new resource to be created. -* `share_name` - (Required) The name of the File Share where this Directory should be created. Changing this forces a new resource to be created. - -* `storage_account_name` - (Required) The name of the Storage Account within which the File Share is located. Changing this forces a new resource to be created. +* `storage_share_id` - (Required) The Storage Share ID in which this file will be placed into. Changing this forces a new resource to be created. * `metadata` - (Optional) A mapping of metadata to assign to this Directory. diff --git a/website/docs/r/storage_table.html.markdown b/website/docs/r/storage_table.html.markdown index 22b7ffefa569..3235526402cb 100644 --- a/website/docs/r/storage_table.html.markdown +++ b/website/docs/r/storage_table.html.markdown @@ -10,6 +10,8 @@ description: |- Manages a Table within an Azure Storage Account. +~> **Note on Authentication** Shared Key authentication will always be used for this resource, as AzureAD authentication is not supported when setting or retrieving ACLs for Tables. + ## Example Usage ```hcl diff --git a/website/docs/r/storage_table_entity.html.markdown b/website/docs/r/storage_table_entity.html.markdown index ba0b2e63cee5..c8614b2f8fed 100644 --- a/website/docs/r/storage_table_entity.html.markdown +++ b/website/docs/r/storage_table_entity.html.markdown @@ -32,8 +32,7 @@ resource "azurerm_storage_table" "example" { } resource "azurerm_storage_table_entity" "example" { - storage_account_name = azurerm_storage_account.example.name - table_name = azurerm_storage_table.example.name + storage_table_id = azurerm_storage_table.example.id partition_key = "examplepartition" row_key = "examplerow" @@ -48,13 +47,11 @@ resource "azurerm_storage_table_entity" "example" { The following arguments are supported: -* `storage_account_name` - (Required) Specifies the storage account in which to create the storage table entity. Changing this forces a new resource to be created. - -* `table_name` - (Required) The name of the storage table in which to create the storage table entity. Changing this forces a new resource to be created. +* `storage_table_id` - (Required) The Storage Share ID in which this file will be placed into. Changing this forces a new resource to be created. -* `partition_key` - (Required) The key for the partition where the entity will be inserted/merged. Changing this forces a new resource. +* `partition_key` - (Required) The key for the partition where the entity will be inserted/merged. Changing this forces a new resource to be created. -* `row_key` - (Required) The key for the row where the entity will be inserted/merged. Changing this forces a new resource. +* `row_key` - (Required) The key for the row where the entity will be inserted/merged. Changing this forces a new resource to be created. * `entity` - (Required) A map of key/value pairs that describe the entity to be inserted/merged in to the storage table.