diff --git a/go.mod b/go.mod index e6d1999b1..40551ca2f 100644 --- a/go.mod +++ b/go.mod @@ -6,8 +6,8 @@ toolchain go1.21.4 require ( github.com/Azure/azure-sdk-for-go v68.0.0+incompatible - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault v1.4.0 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0 @@ -29,24 +29,24 @@ require ( golang.org/x/net v0.21.0 google.golang.org/grpc v1.59.0 google.golang.org/protobuf v1.32.0 - k8s.io/api v0.29.0 - k8s.io/apimachinery v0.29.0 - k8s.io/client-go v0.29.0 + k8s.io/api v0.29.2 + k8s.io/apimachinery v0.29.2 + k8s.io/client-go v0.29.2 k8s.io/component-base v0.29.0 k8s.io/klog/v2 v2.120.1 k8s.io/kubernetes v1.29.0 k8s.io/mount-utils v0.29.0 k8s.io/utils v0.0.0-20231127182322-b307cd553661 - sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240108181414-3a9c6084f8a5 - sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231208022044-b9ede3fc98e9 + sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240220055818-b76605c9c708 + sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20240220055818-b76605c9c708 sigs.k8s.io/yaml v1.4.0 ) require ( - github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 // indirect - github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.4.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.5.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.6.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.7.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 v4.3.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns v1.2.0 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect @@ -56,7 +56,7 @@ require ( github.com/Azure/go-autorest/autorest/validation v0.3.1 // indirect github.com/Azure/go-autorest/logger v0.2.1 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect - github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 // indirect github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230305170008-8188dc5388df // indirect github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a // indirect @@ -68,7 +68,7 @@ require ( github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect - github.com/evanphx/json-patch v5.7.0+incompatible // indirect + github.com/evanphx/json-patch v5.9.0+incompatible // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-ini/ini v1.67.0 @@ -80,14 +80,14 @@ require ( github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-jwt/jwt/v4 v4.5.0 // indirect - github.com/golang-jwt/jwt/v5 v5.0.0 // indirect + github.com/golang-jwt/jwt/v5 v5.2.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/google/cel-go v0.17.7 // indirect github.com/google/gnostic-models v0.6.8 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/pprof v0.0.0-20230602010524-ada837c32108 // indirect - github.com/google/uuid v1.5.0 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 // indirect github.com/imdario/mergo v0.3.9 // indirect @@ -104,7 +104,7 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/selinux v1.11.0 // indirect - github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.16.0 // indirect github.com/prometheus/client_model v0.4.0 // indirect @@ -156,7 +156,7 @@ require ( k8s.io/kubelet v0.29.0 // indirect k8s.io/pod-security-admission v0.29.0 sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.28.0 // indirect - sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240105075710-c4d4895a970b + sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240218020800-ba9f211f36bf sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect ) diff --git a/go.sum b/go.sum index 6349770f2..9e716da1b 100644 --- a/go.sum +++ b/go.sum @@ -5,18 +5,18 @@ cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGB cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 h1:lGlwhPtrX6EVml1hO0ivjkUxsSyl4dsiw9qcA1k/3IQ= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1/go.mod h1:RKUqNu35KJYcVG/fqTRqmuXJZYNhYkBrnC/hX7yGbTA= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0 h1:BMAjVKJM0U/CYF27gA0ZMmXGkOcvfFtD0oHVZ1TIPRI= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0/go.mod h1:1fXstnBMas5kzG+S3q8UoJcmyU6nUeunJcMDHcRYHhs= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 h1:6oNBlSdi1QqM1PNW7FPA6xOGA5UNsXnkaYZz9vdPGhA= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.4.0 h1:QfV5XZt6iNa2aWMAt96CZEbfJ7kgG/qYIpq465Shr5E= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.4.0/go.mod h1:uYt4CfhkJA9o0FN7jfE5minm/i4nUE4MjGUJkzB6Zs8= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2 h1:c4k2FIYIh4xtwqrQwV0Ct1v5+ehlNXj5NI/MWVsiTkQ= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2/go.mod h1:5FDJtLEO/GxwNgUxbwrY3LP0pEoThTQJtk2oysdXHxM= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 h1:sO0/P7g68FrryJzljemN+6GTssUXdANk6aJ7T1ZxnsQ= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1/go.mod h1:h8hyGFDsU5HMivxiS2iYFZsgDbU9OnnJ163x5UGVKYo= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 h1:LqbJ/WzJUwBf8UiaSzgX7aMclParm9/5Vgp+TY51uBQ= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.5.0 h1:MxA59PGoCFb+vCwRQi3PhQEwHj4+r2dhuv9HG+vM7iM= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.5.0/go.mod h1:uYt4CfhkJA9o0FN7jfE5minm/i4nUE4MjGUJkzB6Zs8= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0 h1:DWlwvVV5r/Wy1561nZ3wrpI1/vDIBRY/Wd1HWaRBZWA= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0/go.mod h1:E7ltexgRDmeJ0fJWv0D/HLwY2xbDdN+uv+X2uZtOx3w= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.6.0 h1:AAIdAyPkFff6XTct2lQCxOWN/+LnA41S7kIkzKaMbyE= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.6.0/go.mod h1:noQIdW75SiQFB3mSFJBr4iRRH83S9skaFiBv4C0uEs0= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.7.0 h1:g65N4m1sAjm0BkjIJYtp5qnJlkoFtd6oqfa27KO9fI4= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.7.0/go.mod h1:noQIdW75SiQFB3mSFJBr4iRRH83S9skaFiBv4C0uEs0= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v2 v2.0.0 h1:PTFGRSlMKCQelWwxUyYVEUqseBJVemLyqWJjvMyt0do= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v2 v2.0.0/go.mod h1:LRr2FzBTQlONPPa5HREE5+RjSCTXl7BwOvYOaWTqCaI= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault v1.4.0 h1:HlZMUZW8S4P9oob1nCHxCCKrytxyLc+24nUJGssoEto= @@ -53,8 +53,8 @@ github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+Z 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= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= -github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0 h1:hVeq+yCyUi+MsoO/CU95yqCIcdzra5ovzk8Q2BBpV2M= -github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230305170008-8188dc5388df h1:7RFfzj4SSt6nnvCPbCqijJi1nWCd+TqAT3bYCStRC18= @@ -96,8 +96,8 @@ github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxER github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/protoc-gen-validate v1.0.2 h1:QkIBuU5k+x7/QXPvPPnWXWlCdaBFApVqftFV6k087DA= github.com/envoyproxy/protoc-gen-validate v1.0.2/go.mod h1:GpiZQP3dDbg4JouG/NNS7QWXpgx6x8QiMKdmN72jogE= -github.com/evanphx/json-patch v5.7.0+incompatible h1:vgGkfT/9f8zE6tvSCe74nfpAVDQ2tG6yudJd8LBksgI= -github.com/evanphx/json-patch v5.7.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch v5.9.0+incompatible h1:fBXyNpNMuTTDdquAq/uisOr2lShz4oaXpDTX2bLe7ls= +github.com/evanphx/json-patch v5.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= @@ -128,8 +128,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE= -github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw= +github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/glog v1.1.2 h1:DVjP2PbBOzHyzA+dn3WhHIq4NdVu3Q+pvivFICf/7fo= github.com/golang/glog v1.1.2/go.mod h1:zR+okUeTbrL6EL3xHUDxZuEtGv04p5shwip1+mL/rLQ= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= @@ -155,8 +155,8 @@ github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/pprof v0.0.0-20230602010524-ada837c32108 h1:y+JfwMOPwQwIrnh3TUPwwtOAhONoppkHiSa4sQBoK2k= github.com/google/pprof v0.0.0-20230602010524-ada837c32108/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= -github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -221,8 +221,8 @@ github.com/pborman/uuid v1.2.1 h1:+ZZIw58t/ozdjRaXh/3awHfmWRbzYxJoAdNJxe/3pvw= github.com/pborman/uuid v1.2.1/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= -github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -360,9 +360,9 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -466,12 +466,12 @@ k8s.io/utils v0.0.0-20231127182322-b307cd553661 h1:FepOBzJ0GXm8t0su67ln2wAZjbQ6R k8s.io/utils v0.0.0-20231127182322-b307cd553661/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.28.0 h1:TgtAeesdhpm2SGwkQasmbeqDo8th5wOBA5h/AjTKA4I= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.28.0/go.mod h1:VHVDI/KrK4fjnV61bE2g3sA7tiETLn8sooImelsCx3Y= -sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240108181414-3a9c6084f8a5 h1:omR8VXOIPc20bbG2zxImx9WHLPnTXK2uo9q3LNPanMg= -sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240108181414-3a9c6084f8a5/go.mod h1:0WCrYlWxqk3/AptztkqPk1r9Gr3IULSHat7LipAA1sI= -sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240105075710-c4d4895a970b h1:onCsa2FoC9HGIgW+eQYJI8/IZnefwCcU9rF7ZKtD7f0= -sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240105075710-c4d4895a970b/go.mod h1:seH99Elt7KgWOOonCmzRcB1yLouqK7B7+l8RoSbqaYE= -sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231208022044-b9ede3fc98e9 h1:0XsdZlKjVI0UZYhvg3VbXCPFRRQS5VL1idrTKgzJjnc= -sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231208022044-b9ede3fc98e9/go.mod h1:dDc0Ixf5VI01TkTj83ENW1hH5jImGJsdKhQgFRyQsyA= +sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240220055818-b76605c9c708 h1:Hs8BBRzo/V4Qe8m1NG997vaavBb0WSPzKsxdXtjfUpg= +sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240220055818-b76605c9c708/go.mod h1:GJ+Crn1rYpKB21TNlnJQKsRWvIHva7oMApx2RhubFao= +sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240218020800-ba9f211f36bf h1:pyQe3MFQp1Hb8iya4LaZiBEh3M0RgZ/yv0/ws5memP4= +sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240218020800-ba9f211f36bf/go.mod h1:cyVxBbpj/UR4Vi4KhxO3vhzBB2JcN08TngoPQ0J0aWc= +sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20240220055818-b76605c9c708 h1:dKAXbaoIRkknnvirDOb4BZLocx4UVtshb9zg3dgZxaE= +sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20240220055818-b76605c9c708/go.mod h1:8Y2dnp0FlQcoFllRnUgTZjMykhMAUF7NrPLgw30Ae4I= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4= diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md index 5c8411cb5..7a0a524e3 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.9.2 (2024-02-06) + +### Bugs Fixed + +* `runtime.MarshalAsByteArray` and `runtime.MarshalAsJSON` will preserve the preexisting value of the `Content-Type` header. + +### Other Changes + +* Update to latest version of `internal`. + ## 1.9.1 (2023-12-11) ### Bugs Fixed diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go index 659f2a7d2..8d1ae213c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go @@ -125,46 +125,11 @@ func (req *Request) OperationValue(value interface{}) bool { // SetBody sets the specified ReadSeekCloser as the HTTP request body, and sets Content-Type and Content-Length // accordingly. If the ReadSeekCloser is nil or empty, Content-Length won't be set. If contentType is "", -// Content-Type won't be set. +// Content-Type won't be set, and if it was set, will be deleted. // Use streaming.NopCloser to turn an io.ReadSeeker into an io.ReadSeekCloser. func (req *Request) SetBody(body io.ReadSeekCloser, contentType string) error { - var err error - var size int64 - if body != nil { - size, err = body.Seek(0, io.SeekEnd) // Seek to the end to get the stream's size - if err != nil { - return err - } - } - if size == 0 { - // treat an empty stream the same as a nil one: assign req a nil body - body = nil - // RFC 9110 specifies a client shouldn't set Content-Length on a request containing no content - // (Del is a no-op when the header has no value) - req.req.Header.Del(shared.HeaderContentLength) - } else { - _, err = body.Seek(0, io.SeekStart) - if err != nil { - return err - } - req.req.Header.Set(shared.HeaderContentLength, strconv.FormatInt(size, 10)) - req.Raw().GetBody = func() (io.ReadCloser, error) { - _, err := body.Seek(0, io.SeekStart) // Seek back to the beginning of the stream - return body, err - } - } - // keep a copy of the body argument. this is to handle cases - // where req.Body is replaced, e.g. httputil.DumpRequest and friends. - req.body = body - req.req.Body = body - req.req.ContentLength = size - if contentType == "" { - // Del is a no-op when the header has no value - req.req.Header.Del(shared.HeaderContentType) - } else { - req.req.Header.Set(shared.HeaderContentType, contentType) - } - return nil + // clobber the existing Content-Type to preserve behavior + return SetBody(req, body, contentType, true) } // RewindBody seeks the request's Body stream back to the beginning so it can be resent when retrying an operation. @@ -211,3 +176,48 @@ type PolicyFunc func(*Request) (*http.Response, error) func (pf PolicyFunc) Do(req *Request) (*http.Response, error) { return pf(req) } + +// SetBody sets the specified ReadSeekCloser as the HTTP request body, and sets Content-Type and Content-Length accordingly. +// - req is the request to modify +// - body is the request body; if nil or empty, Content-Length won't be set +// - contentType is the value for the Content-Type header; if empty, Content-Type will be deleted +// - clobberContentType when true, will overwrite the existing value of Content-Type with contentType +func SetBody(req *Request, body io.ReadSeekCloser, contentType string, clobberContentType bool) error { + var err error + var size int64 + if body != nil { + size, err = body.Seek(0, io.SeekEnd) // Seek to the end to get the stream's size + if err != nil { + return err + } + } + if size == 0 { + // treat an empty stream the same as a nil one: assign req a nil body + body = nil + // RFC 9110 specifies a client shouldn't set Content-Length on a request containing no content + // (Del is a no-op when the header has no value) + req.req.Header.Del(shared.HeaderContentLength) + } else { + _, err = body.Seek(0, io.SeekStart) + if err != nil { + return err + } + req.req.Header.Set(shared.HeaderContentLength, strconv.FormatInt(size, 10)) + req.Raw().GetBody = func() (io.ReadCloser, error) { + _, err := body.Seek(0, io.SeekStart) // Seek back to the beginning of the stream + return body, err + } + } + // keep a copy of the body argument. this is to handle cases + // where req.Body is replaced, e.g. httputil.DumpRequest and friends. + req.body = body + req.req.Body = body + req.req.ContentLength = size + if contentType == "" { + // Del is a no-op when the header has no value + req.req.Header.Del(shared.HeaderContentType) + } else if req.req.Header.Get(shared.HeaderContentType) == "" || clobberContentType { + req.req.Header.Set(shared.HeaderContentType, contentType) + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go index bb93daee6..8f749f48d 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go @@ -40,5 +40,5 @@ const ( Module = "azcore" // Version is the semantic version (see http://semver.org) of this module. - Version = "v1.9.1" + Version = "v1.9.2" ) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go index e97223da2..5d1569c8d 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go @@ -97,7 +97,8 @@ func EncodeByteArray(v []byte, format Base64Encoding) string { func MarshalAsByteArray(req *policy.Request, v []byte, format Base64Encoding) error { // send as a JSON string encode := fmt.Sprintf("\"%s\"", EncodeByteArray(v, format)) - return req.SetBody(exported.NopCloser(strings.NewReader(encode)), shared.ContentTypeAppJSON) + // tsp generated code can set Content-Type so we must prefer that + return exported.SetBody(req, exported.NopCloser(strings.NewReader(encode)), shared.ContentTypeAppJSON, false) } // MarshalAsJSON calls json.Marshal() to get the JSON encoding of v then calls SetBody. @@ -106,7 +107,8 @@ func MarshalAsJSON(req *policy.Request, v interface{}) error { if err != nil { return fmt.Errorf("error marshalling type %T: %s", v, err) } - return req.SetBody(exported.NopCloser(bytes.NewReader(b)), shared.ContentTypeAppJSON) + // tsp generated code can set Content-Type so we must prefer that + return exported.SetBody(req, exported.NopCloser(bytes.NewReader(b)), shared.ContentTypeAppJSON, false) } // MarshalAsXML calls xml.Marshal() to get the XML encoding of v then calls SetBody. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md index 7ea119ab3..71dcb5f3e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md @@ -1,5 +1,38 @@ # Release History +## 1.5.1 (2024-01-17) + +### Bugs Fixed +* `InteractiveBrowserCredential` handles `AdditionallyAllowedTenants` correctly + +## 1.5.0 (2024-01-16) + +### Breaking Changes +> These changes affect only code written against a beta version such as v1.5.0-beta.1 +* Removed persistent token caching. It will return in v1.6.0-beta.1 + +### Bugs Fixed +* Credentials now preserve MSAL headers e.g. X-Client-Sku + +### Other Changes +* Upgraded dependencies + +## 1.5.0-beta.2 (2023-11-07) + +### Features Added +* `DefaultAzureCredential` and `ManagedIdentityCredential` support Azure ML managed identity +* Added spans for distributed tracing. + +## 1.5.0-beta.1 (2023-10-10) + +### Features Added +* Optional persistent token caching for most credentials. Set `TokenCachePersistenceOptions` + on a credential's options to enable and configure this. See the package documentation for + this version and [TOKEN_CACHING.md](https://aka.ms/azsdk/go/identity/caching) for more + details. +* `AzureDeveloperCLICredential` authenticates with the Azure Developer CLI (`azd`). This + credential is also part of the `DefaultAzureCredential` authentication flow. + ## 1.4.0 (2023-10-10) ### Bugs Fixed @@ -94,14 +127,14 @@ ### Features Added * By default, credentials set client capability "CP1" to enable support for [Continuous Access Evaluation (CAE)](https://docs.microsoft.com/azure/active-directory/develop/app-resilience-continuous-access-evaluation). - This indicates to Azure Active Directory that your application can handle CAE claims challenges. + This indicates to Microsoft Entra ID that your application can handle CAE claims challenges. You can disable this behavior by setting the environment variable "AZURE_IDENTITY_DISABLE_CP1" to "true". * `InteractiveBrowserCredentialOptions.LoginHint` enables pre-populating the login prompt with a username ([#15599](https://github.com/Azure/azure-sdk-for-go/pull/15599)) * Service principal and user credentials support ADFS authentication on Azure Stack. Specify "adfs" as the credential's tenant. * Applications running in private or disconnected clouds can prevent credentials from - requesting Azure AD instance metadata by setting the `DisableInstanceDiscovery` + requesting Microsoft Entra instance metadata by setting the `DisableInstanceDiscovery` field on credential options. * Many credentials can now be configured to authenticate in multiple tenants. The options types for these credentials have an `AdditionallyAllowedTenants` field @@ -454,4 +487,4 @@ ## 0.1.0 (2020-07-23) ### Features Added -* Initial Release. Azure Identity library that provides Azure Active Directory token authentication support for the SDK. +* Initial Release. Azure Identity library that provides Microsoft Entra token authentication support for the SDK. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md index 4ac53eb7b..1a6492023 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md @@ -1,6 +1,6 @@ # Migrating from autorest/adal to azidentity -`azidentity` provides Azure Active Directory (Azure AD) authentication for the newest Azure SDK modules (`github.com/azure-sdk-for-go/sdk/...`). Older Azure SDK packages (`github.com/azure-sdk-for-go/services/...`) use types from `github.com/go-autorest/autorest/adal` instead. +`azidentity` provides Microsoft Entra ID ([formerly Azure Active Directory](https://learn.microsoft.com/azure/active-directory/fundamentals/new-name)) authentication for the newest Azure SDK modules (`github.com/azure-sdk-for-go/sdk/...`). Older Azure SDK packages (`github.com/azure-sdk-for-go/services/...`) use types from `github.com/go-autorest/autorest/adal` instead. This guide shows common authentication code using `autorest/adal` and its equivalent using `azidentity`. @@ -18,7 +18,7 @@ This guide shows common authentication code using `autorest/adal` and its equiva ### `autorest/adal` -Token providers require a token audience (resource identifier) and an instance of `adal.OAuthConfig`, which requires an Azure AD endpoint and tenant: +Token providers require a token audience (resource identifier) and an instance of `adal.OAuthConfig`, which requires a Microsoft Entra endpoint and tenant: ```go import "github.com/Azure/go-autorest/autorest/adal" @@ -284,7 +284,7 @@ if err == nil { } ``` -Note that `azidentity` credentials use the Azure AD v2.0 endpoint, which requires OAuth 2 scopes instead of the resource identifiers `autorest/adal` expects. For more information, see [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent). +Note that `azidentity` credentials use the Microsoft Entra endpoint, which requires OAuth 2 scopes instead of the resource identifiers `autorest/adal` expects. For more information, see [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/permissions-consent-overview). ## Use azidentity credentials with older packages diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md index da0baa9ad..b6ad2d39f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md @@ -1,9 +1,9 @@ # Azure Identity Client Module for Go -The Azure Identity module provides Azure Active Directory (Azure AD) token authentication support across the Azure SDK. It includes a set of `TokenCredential` implementations, which can be used with Azure SDK clients supporting token authentication. +The Azure Identity module provides Microsoft Entra ID ([formerly Azure Active Directory](https://learn.microsoft.com/azure/active-directory/fundamentals/new-name)) token authentication support across the Azure SDK. It includes a set of `TokenCredential` implementations, which can be used with Azure SDK clients supporting token authentication. [![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/azidentity)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) -| [Azure Active Directory documentation](https://docs.microsoft.com/azure/active-directory/) +| [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/) | [Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity) # Getting started @@ -35,6 +35,12 @@ signed in to the [Azure CLI](https://docs.microsoft.com/cli/azure). To sign in t When no default browser is available, `az login` will use the device code authentication flow. This can also be selected manually by running `az login --use-device-code`. +#### Authenticate via the Azure Developer CLI + +Developers coding outside of an IDE can also use the [Azure Developer CLI](https://aka.ms/azure-dev) to authenticate. Applications using the `DefaultAzureCredential` or the `AzureDeveloperCLICredential` can use the account logged in to the Azure Developer CLI to authenticate calls in their application when running locally. + +To authenticate with the Azure Developer CLI, run `azd auth login`. On a system with a default web browser, `azd` will launch the browser to authenticate. On systems without a default web browser, run `azd auth login --use-device-code` to use the device code authentication flow. + ## Key concepts ### Credentials @@ -44,9 +50,7 @@ service client to authenticate requests. Service clients across the Azure SDK accept a credential instance when they are constructed, and use that credential to authenticate requests. -The `azidentity` module focuses on OAuth authentication with Azure Active -Directory (AAD). It offers a variety of credential types capable of acquiring -an Azure AD access token. See [Credential Types](#credential-types "Credential Types") for a list of this module's credential types. +The `azidentity` module focuses on OAuth authentication with Microsoft Entra ID. It offers a variety of credential types capable of acquiring a Microsoft Entra access token. See [Credential Types](#credential-types "Credential Types") for a list of this module's credential types. ### DefaultAzureCredential @@ -58,6 +62,7 @@ an Azure AD access token. See [Credential Types](#credential-types "Credential T 1. **Workload Identity** - If the app is deployed on Kubernetes with environment variables set by the workload identity webhook, `DefaultAzureCredential` will authenticate the configured identity. 1. **Managed Identity** - If the app is deployed to an Azure host with managed identity enabled, `DefaultAzureCredential` will authenticate with it. 1. **Azure CLI** - If a user or service principal has authenticated via the Azure CLI `az login` command, `DefaultAzureCredential` will authenticate that identity. +1. **Azure Developer CLI** - If the developer has authenticated via the Azure Developer CLI `azd auth login` command, the `DefaultAzureCredential` will authenticate with that account. > Note: `DefaultAzureCredential` is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types. @@ -152,6 +157,7 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) |Credential|Usage |-|- |[AzureCLICredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureCLICredential)|Authenticate as the user signed in to the Azure CLI +|[`AzureDeveloperCLICredential`](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureDeveloperCLICredential)|Authenticates as the user signed in to the Azure Developer CLI ## Environment Variables @@ -161,16 +167,16 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) |variable name|value |-|- -|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application -|`AZURE_TENANT_ID`|ID of the application's Azure Active Directory tenant +|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application +|`AZURE_TENANT_ID`|ID of the application's Microsoft Entra tenant |`AZURE_CLIENT_SECRET`|one of the application's client secrets #### Service principal with certificate |variable name|value |-|- -|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application -|`AZURE_TENANT_ID`|ID of the application's Azure Active Directory tenant +|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application +|`AZURE_TENANT_ID`|ID of the application's Microsoft Entra tenant |`AZURE_CLIENT_CERTIFICATE_PATH`|path to a certificate file including private key |`AZURE_CLIENT_CERTIFICATE_PASSWORD`|password of the certificate file, if any @@ -178,22 +184,30 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) |variable name|value |-|- -|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application +|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application |`AZURE_USERNAME`|a username (usually an email address) |`AZURE_PASSWORD`|that user's password Configuration is attempted in the above order. For example, if values for a client secret and certificate are both present, the client secret will be used. +## Token caching + +Token caching is an `azidentity` feature that allows apps to: + +* Cache tokens in memory (default) or on disk (opt-in). +* Improve resilience and performance. +* Reduce the number of requests made to Microsoft Entra ID to obtain access tokens. + +For more details, see the [token caching documentation](https://aka.ms/azsdk/go/identity/caching). + ## Troubleshooting ### Error Handling Credentials return an `error` when they fail to authenticate or lack data they require to authenticate. For guidance on resolving errors from specific credential types, see the [troubleshooting guide](https://aka.ms/azsdk/go/identity/troubleshoot). -For more details on handling specific Azure Active Directory errors please refer to the -Azure Active Directory -[error code documentation](https://docs.microsoft.com/azure/active-directory/develop/reference-aadsts-error-codes). +For more details on handling specific Microsoft Entra errors, see the Microsoft Entra [error code documentation](https://learn.microsoft.com/azure/active-directory/develop/reference-error-codes). ### Logging diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD new file mode 100644 index 000000000..c0d660146 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD @@ -0,0 +1,70 @@ +## Token caching in the Azure Identity client module + +*Token caching* is a feature provided by the Azure Identity library that allows apps to: + +- Improve their resilience and performance. +- Reduce the number of requests made to Microsoft Entra ID to obtain access tokens. +- Reduce the number of times the user is prompted to authenticate. + +When an app needs to access a protected Azure resource, it typically needs to obtain an access token from Entra ID. Obtaining that token involves sending a request to Entra ID and may also involve prompting the user. Entra ID then validates the credentials provided in the request and issues an access token. + +Token caching, via the Azure Identity library, allows the app to store this access token [in memory](#in-memory-token-caching), where it's accessible to the current process, or [on disk](#persistent-token-caching) where it can be accessed across application or process invocations. The token can then be retrieved quickly and easily the next time the app needs to access the same resource. The app can avoid making another request to Entra ID, which reduces network traffic and improves resilience. Additionally, in scenarios where the app is authenticating users, token caching also avoids prompting the user each time new tokens are requested. + +### In-memory token caching + +*In-memory token caching* is the default option provided by the Azure Identity library. This caching approach allows apps to store access tokens in memory. With in-memory token caching, the library first determines if a valid access token for the requested resource is already stored in memory. If a valid token is found, it's returned to the app without the need to make another request to Entra ID. If a valid token isn't found, the library will automatically acquire a token by sending a request to Entra ID. The in-memory token cache provided by the Azure Identity library is thread-safe. + +**Note:** When Azure Identity library credentials are used with Azure service libraries (for example, Azure Blob Storage), the in-memory token caching is active in the `Pipeline` layer as well. All `TokenCredential` implementations are supported there, including custom implementations external to the Azure Identity library. + +#### Caching cannot be disabled + +As there are many levels of caching, it's not possible disable in-memory caching. However, the in-memory cache may be cleared by creating a new credential instance. + +### Persistent token caching + +> Only azidentity v1.5.0-beta versions support persistent token caching + +*Persistent disk token caching* is an opt-in feature in the Azure Identity library. The feature allows apps to cache access tokens in an encrypted, persistent storage mechanism. As indicated in the following table, the storage mechanism differs across operating systems. + +| Operating system | Storage mechanism | +|------------------|---------------------------------------| +| Linux | kernel key retention service (keyctl) | +| macOS | Keychain | +| Windows | DPAPI | + +By default the token cache will protect any data which is persisted using the user data protection APIs available on the current platform. +However, there are cases where no data protection is available, and applications may choose to allow storing the token cache in an unencrypted state by setting `TokenCachePersistenceOptions.AllowUnencryptedStorage` to `true`. This allows a credential to fall back to unencrypted storage if it can't encrypt the cache. However, we do not recommend using this storage method due to its significantly lower security measures. In addition, tokens are not encrypted solely to the current user, which could potentially allow unauthorized access to the cache by individuals with machine access. + +With persistent disk token caching enabled, the library first determines if a valid access token for the requested resource is already stored in the persistent cache. If a valid token is found, it's returned to the app without the need to make another request to Entra ID. Additionally, the tokens are preserved across app runs, which: + +- Makes the app more resilient to failures. +- Ensures the app can continue to function during an Entra ID outage or disruption. +- Avoids having to prompt users to authenticate each time the process is restarted. + +>IMPORTANT! The token cache contains sensitive data and **MUST** be protected to prevent compromising accounts. All application decisions regarding the persistence of the token cache must consider that a breach of its content will fully compromise all the accounts it contains. + +#### Example code + +See the [package documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity@v1.5.0-beta.1#pkg-overview) for code examples demonstrating how to configure persistent caching and access cached data. + +### Credentials supporting token caching + +The following table indicates the state of in-memory and persistent caching in each credential type. + +**Note:** In-memory caching is activated by default. Persistent token caching needs to be enabled as shown in [this example](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity@v1.5.0-beta.1#example-package-PersistentCache). + +| Credential | In-memory token caching | Persistent token caching | +|--------------------------------|---------------------------------------------------------------------|--------------------------| +| `AzureCLICredential` | Not Supported | Not Supported | +| `AzureDeveloperCLICredential` | Not Supported | Not Supported | +| `ClientAssertionCredential` | Supported | Supported | +| `ClientCertificateCredential` | Supported | Supported | +| `ClientSecretCredential` | Supported | Supported | +| `DefaultAzureCredential` | Supported if the target credential in the default chain supports it | Not Supported | +| `DeviceCodeCredential` | Supported | Supported | +| `EnvironmentCredential` | Supported | Not Supported | +| `InteractiveBrowserCredential` | Supported | Supported | +| `ManagedIdentityCredential` | Supported | Not Supported | +| `OnBehalfOfCredential` | Supported | Supported | +| `UsernamePasswordCredential` | Supported | Supported | +| `WorkloadIdentityCredential` | Supported | Supported | diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md index fef099813..832c599eb 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md @@ -8,7 +8,8 @@ This troubleshooting guide covers failure investigation techniques, common error - [Permission issues](#permission-issues) - [Find relevant information in errors](#find-relevant-information-in-errors) - [Enable and configure logging](#enable-and-configure-logging) -- [Troubleshoot AzureCliCredential authentication issues](#troubleshoot-azureclicredential-authentication-issues) +- [Troubleshoot AzureCLICredential authentication issues](#troubleshoot-azureclicredential-authentication-issues) +- [Troubleshoot AzureDeveloperCLICredential authentication issues](#troubleshoot-azuredeveloperclicredential-authentication-issues) - [Troubleshoot ClientCertificateCredential authentication issues](#troubleshoot-clientcertificatecredential-authentication-issues) - [Troubleshoot ClientSecretCredential authentication issues](#troubleshoot-clientsecretcredential-authentication-issues) - [Troubleshoot DefaultAzureCredential authentication issues](#troubleshoot-defaultazurecredential-authentication-issues) @@ -23,7 +24,7 @@ This troubleshooting guide covers failure investigation techniques, common error ## Handle azidentity errors -Any service client method that makes a request to the service may return an error due to authentication failure. This is because the credential authenticates on the first call to the service and on any subsequent call that needs to refresh an access token. Authentication errors include a description of the failure and possibly an error message from Azure Active Directory (Azure AD). Depending on the application, these errors may or may not be recoverable. +Any service client method that makes a request to the service may return an error due to authentication failure. This is because the credential authenticates on the first call to the service and on any subsequent call that needs to refresh an access token. Authentication errors include a description of the failure and possibly an error message from Microsoft Entra ID. Depending on the application, these errors may or may not be recoverable. ### Permission issues @@ -31,7 +32,7 @@ Service client errors with a status code of 401 or 403 often indicate that authe ## Find relevant information in errors -Authentication errors can include responses from Azure AD and often contain information helpful in diagnosis. Consider the following error message: +Authentication errors can include responses from Microsoft Entra ID and often contain information helpful in diagnosis. Consider the following error message: ``` ClientSecretCredential authentication failed @@ -57,9 +58,9 @@ This error contains several pieces of information: - __Failing Credential Type__: The type of credential that failed to authenticate. This can be helpful when diagnosing issues with chained credential types such as `DefaultAzureCredential` or `ChainedTokenCredential`. -- __Azure AD Error Code and Message__: The error code and message returned by Azure AD. This can give insight into the specific reason the request failed. For instance, in this case authentication failed because the provided client secret is incorrect. [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/reference-aadsts-error-codes#aadsts-error-codes) has more information on AADSTS error codes. +- __Microsoft Entra ID Error Code and Message__: The error code and message returned by Microsoft Entra ID. This can give insight into the specific reason the request failed. For instance, in this case authentication failed because the provided client secret is incorrect. [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/reference-error-codes#aadsts-error-codes) has more information on AADSTS error codes. -- __Correlation ID and Timestamp__: The correlation ID and timestamp identify the request in server-side logs. This information can be useful to support engineers diagnosing unexpected Azure AD failures. +- __Correlation ID and Timestamp__: The correlation ID and timestamp identify the request in server-side logs. This information can be useful to support engineers diagnosing unexpected Microsoft Entra failures. ### Enable and configure logging @@ -96,17 +97,17 @@ azlog.SetEvents(azidentity.EventAuthentication) | Error Code | Issue | Mitigation | |---|---|---| -|AADSTS7000215|An invalid client secret was provided.|Ensure the secret provided to the credential constructor is valid. If unsure, create a new client secret using the Azure portal. Details on creating a new client secret are in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| -|AADSTS7000222|An expired client secret was provided.|Create a new client secret using the Azure portal. Details on creating a new client secret are in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| -|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Azure AD instructions](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| +|AADSTS7000215|An invalid client secret was provided.|Ensure the secret provided to the credential constructor is valid. If unsure, create a new client secret using the Azure portal. Details on creating a new client secret are in [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| +|AADSTS7000222|An expired client secret was provided.|Create a new client secret using the Azure portal. Details on creating a new client secret are in [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| +|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Microsoft Entra ID instructions](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| ## Troubleshoot ClientCertificateCredential authentication issues | Error Code | Description | Mitigation | |---|---|---| -|AADSTS700027|Client assertion contains an invalid signature.|Ensure the specified certificate has been uploaded to the application registration as described in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-1-upload-a-certificate).| -|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Azure AD instructions](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| +|AADSTS700027|Client assertion contains an invalid signature.|Ensure the specified certificate has been uploaded to the application registration as described in [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-1-upload-a-certificate).| +|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Microsoft Entra ID instructions](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| ## Troubleshoot UsernamePasswordCredential authentication issues @@ -172,7 +173,7 @@ curl "$IDENTITY_ENDPOINT?resource=https://management.core.windows.net&api-versio |"no azure identity found for request clientID"|The application attempted to authenticate before an identity was assigned to its pod|Verify the pod is labeled correctly. This also occurs when a correctly labeled pod authenticates before the identity is ready. To prevent initialization races, configure NMI to set the Retry-After header in its responses as described in [Pod Identity documentation](https://azure.github.io/aad-pod-identity/docs/configure/feature_flags/#set-retry-after-header-in-nmi-response). -## Troubleshoot AzureCliCredential authentication issues +## Troubleshoot AzureCLICredential authentication issues | Error Message |Description| Mitigation | |---|---|---| @@ -195,6 +196,29 @@ az account get-access-token --output json --resource https://management.core.win > This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security. + +## Troubleshoot AzureDeveloperCLICredential authentication issues + +| Error Message |Description| Mitigation | +|---|---|---| +|Azure Developer CLI not found on path|The Azure Developer CLI isn't installed or couldn't be found.|| +|Please run "azd auth login"|No account is logged into the Azure Developer CLI, or the login has expired.|| + +#### Verify the Azure Developer CLI can obtain tokens + +You can manually verify that the Azure Developer CLI is properly authenticated and can obtain tokens. First, use the `config` command to verify the account that is currently logged in to the Azure Developer CLI. + +```sh +azd config list +``` + +Once you've verified the Azure Developer CLI is using correct account, you can validate that it's able to obtain tokens for this account. + +```sh +azd auth token --output json --scope https://management.core.windows.net/.default +``` +>Note that output of this command will contain a valid access token, and SHOULD NOT BE SHARED to avoid compromising account security. + ## Troubleshoot `WorkloadIdentityCredential` authentication issues diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json index 47e77f88e..173ce2b3c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "go", "TagPrefix": "go/azidentity", - "Tag": "go/azidentity_6225ab0470" + "Tag": "go/azidentity_db4a26f583" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/authentication_record.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/authentication_record.go new file mode 100644 index 000000000..ada4d6501 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/authentication_record.go @@ -0,0 +1,95 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" +) + +var supportedAuthRecordVersions = []string{"1.0"} + +// authenticationRecord is non-secret account information about an authenticated user that user credentials such as +// [DeviceCodeCredential] and [InteractiveBrowserCredential] can use to access previously cached authentication +// data. Call these credentials' Authenticate method to get an authenticationRecord for a user. +type authenticationRecord struct { + // Authority is the URL of the authority that issued the token. + Authority string `json:"authority"` + + // ClientID is the ID of the application that authenticated the user. + ClientID string `json:"clientId"` + + // HomeAccountID uniquely identifies the account. + HomeAccountID string `json:"homeAccountId"` + + // TenantID identifies the tenant in which the user authenticated. + TenantID string `json:"tenantId"` + + // Username is the user's preferred username. + Username string `json:"username"` + + // Version of the AuthenticationRecord. + Version string `json:"version"` +} + +// UnmarshalJSON implements json.Unmarshaler for AuthenticationRecord +func (a *authenticationRecord) UnmarshalJSON(b []byte) error { + // Default unmarshaling is fine but we want to return an error if the record's version isn't supported i.e., we + // want to inspect the unmarshalled values before deciding whether to return an error. Unmarshaling a formally + // different type enables this by assigning all the fields without recursing into this method. + type r authenticationRecord + err := json.Unmarshal(b, (*r)(a)) + if err != nil { + return err + } + if a.Version == "" { + return errors.New("AuthenticationRecord must have a version") + } + for _, v := range supportedAuthRecordVersions { + if a.Version == v { + return nil + } + } + return fmt.Errorf("unsupported AuthenticationRecord version %q. This module supports %v", a.Version, supportedAuthRecordVersions) +} + +// account returns the AuthenticationRecord as an MSAL Account. The account is zero-valued when the AuthenticationRecord is zero-valued. +func (a *authenticationRecord) account() public.Account { + return public.Account{ + Environment: a.Authority, + HomeAccountID: a.HomeAccountID, + PreferredUsername: a.Username, + } +} + +func newAuthenticationRecord(ar public.AuthResult) (authenticationRecord, error) { + u, err := url.Parse(ar.IDToken.Issuer) + if err != nil { + return authenticationRecord{}, fmt.Errorf("Authenticate expected a URL issuer but got %q", ar.IDToken.Issuer) + } + tenant := ar.IDToken.TenantID + if tenant == "" { + tenant = strings.Trim(u.Path, "/") + } + username := ar.IDToken.PreferredUsername + if username == "" { + username = ar.IDToken.UPN + } + return authenticationRecord{ + Authority: fmt.Sprintf("%s://%s", u.Scheme, u.Host), + ClientID: ar.IDToken.Audience, + HomeAccountID: ar.Account.HomeAccountID, + TenantID: tenant, + Username: username, + Version: "1.0", + }, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go index 10b742ce1..c3bcfb56c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go @@ -15,12 +15,12 @@ import ( "net/http" "net/url" "os" - "regexp" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" ) @@ -41,6 +41,10 @@ const ( organizationsTenantID = "organizations" developerSignOnClientID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" defaultSuffix = "/.default" + + traceNamespace = "Microsoft.Entra" + traceOpGetToken = "GetToken" + traceOpAuthenticate = "Authenticate" ) var ( @@ -49,6 +53,9 @@ var ( errInvalidTenantID = errors.New("invalid tenantID. You can locate your tenantID by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names") ) +// tokenCachePersistenceOptions contains options for persistent token caching +type tokenCachePersistenceOptions = internal.TokenCachePersistenceOptions + // setAuthorityHost initializes the authority host for credentials. Precedence is: // 1. cloud.Configuration.ActiveDirectoryAuthorityHost value set by user // 2. value of AZURE_AUTHORITY_HOST @@ -109,29 +116,20 @@ func resolveTenant(defaultTenant, specified, credName string, additionalTenants return "", fmt.Errorf(`%s isn't configured to acquire tokens for tenant %q. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add "*" to allow acquiring tokens for any tenant`, credName, specified) } -// validTenantID return true is it receives a valid tenantID, returns false otherwise -func validTenantID(tenantID string) bool { - match, err := regexp.MatchString("^[0-9a-zA-Z-.]+$", tenantID) - if err != nil { - return false - } - return match -} - -func newPipelineAdapter(opts *azcore.ClientOptions) pipelineAdapter { - pl := runtime.NewPipeline(component, version, runtime.PipelineOptions{}, opts) - return pipelineAdapter{pl: pl} -} - -type pipelineAdapter struct { - pl runtime.Pipeline +func alphanumeric(r rune) bool { + return ('0' <= r && r <= '9') || ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') } -func (p pipelineAdapter) CloseIdleConnections() { - // do nothing +func validTenantID(tenantID string) bool { + for _, r := range tenantID { + if !(alphanumeric(r) || r == '.' || r == '-') { + return false + } + } + return true } -func (p pipelineAdapter) Do(r *http.Request) (*http.Response, error) { +func doForClient(client *azcore.Client, r *http.Request) (*http.Response, error) { req, err := runtime.NewRequest(r.Context(), r.Method, r.URL.String()) if err != nil { return nil, err @@ -153,7 +151,18 @@ func (p pipelineAdapter) Do(r *http.Request) (*http.Response, error) { return nil, err } } - resp, err := p.pl.Do(req) + + // copy headers to the new request, ignoring any for which the new request has a value + h := req.Raw().Header + for key, vals := range r.Header { + if _, has := h[key]; !has { + for _, val := range vals { + h.Add(key, val) + } + } + } + + resp, err := client.Pipeline().Do(req) if err != nil { return nil, err } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go index 55a0d6543..43577ab3c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go @@ -14,7 +14,6 @@ import ( "fmt" "os" "os/exec" - "regexp" "runtime" "strings" "sync" @@ -25,13 +24,9 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/internal/log" ) -const ( - credNameAzureCLI = "AzureCLICredential" - timeoutCLIRequest = 10 * time.Second -) +const credNameAzureCLI = "AzureCLICredential" -// used by tests to fake invoking the CLI -type azureCLITokenProvider func(ctx context.Context, resource string, tenantID string) ([]byte, error) +type azTokenProvider func(ctx context.Context, scopes []string, tenant, subscription string) ([]byte, error) // AzureCLICredentialOptions contains optional parameters for AzureCLICredential. type AzureCLICredentialOptions struct { @@ -39,17 +34,25 @@ type AzureCLICredentialOptions struct { // to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the // logged in account can access. AdditionallyAllowedTenants []string + + // subscription is the name or ID of a subscription. Set this to acquire tokens for an account other + // than the Azure CLI's current account. + subscription string + // TenantID identifies the tenant the credential should authenticate in. // Defaults to the CLI's default tenant, which is typically the home tenant of the logged in user. TenantID string - tokenProvider azureCLITokenProvider + // inDefaultChain is true when the credential is part of DefaultAzureCredential + inDefaultChain bool + // tokenProvider is used by tests to fake invoking az + tokenProvider azTokenProvider } // init returns an instance of AzureCLICredentialOptions initialized with default values. func (o *AzureCLICredentialOptions) init() { if o.tokenProvider == nil { - o.tokenProvider = defaultTokenProvider + o.tokenProvider = defaultAzTokenProvider } } @@ -65,6 +68,14 @@ func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredent if options != nil { cp = *options } + for _, r := range cp.subscription { + if !(alphanumeric(r) || r == '-' || r == '_' || r == ' ' || r == '.') { + return nil, fmt.Errorf("%s: invalid Subscription %q", credNameAzureCLI, cp.subscription) + } + } + if cp.TenantID != "" && !validTenantID(cp.TenantID) { + return nil, errInvalidTenantID + } cp.init() cp.AdditionallyAllowedTenants = resolveAdditionalTenants(cp.AdditionallyAllowedTenants) return &AzureCLICredential{mu: &sync.Mutex{}, opts: cp}, nil @@ -73,50 +84,51 @@ func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredent // GetToken requests a token from the Azure CLI. This credential doesn't cache tokens, so every call invokes the CLI. // This method is called automatically by Azure SDK clients. func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + at := azcore.AccessToken{} if len(opts.Scopes) != 1 { - return azcore.AccessToken{}, errors.New(credNameAzureCLI + ": GetToken() requires exactly one scope") + return at, errors.New(credNameAzureCLI + ": GetToken() requires exactly one scope") + } + if !validScope(opts.Scopes[0]) { + return at, fmt.Errorf("%s.GetToken(): invalid scope %q", credNameAzureCLI, opts.Scopes[0]) } tenant, err := resolveTenant(c.opts.TenantID, opts.TenantID, credNameAzureCLI, c.opts.AdditionallyAllowedTenants) if err != nil { - return azcore.AccessToken{}, err + return at, err } - // pass the CLI an AAD v1 resource because we don't know which CLI version is installed and older ones don't support v2 scopes - opts.Scopes = []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)} c.mu.Lock() defer c.mu.Unlock() - b, err := c.opts.tokenProvider(ctx, opts.Scopes[0], tenant) - if err != nil { - return azcore.AccessToken{}, err + b, err := c.opts.tokenProvider(ctx, opts.Scopes, tenant, c.opts.subscription) + if err == nil { + at, err = c.createAccessToken(b) } - at, err := c.createAccessToken(b) if err != nil { - return azcore.AccessToken{}, err + err = unavailableIfInChain(err, c.opts.inDefaultChain) + return at, err } msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", credNameAzureCLI, strings.Join(opts.Scopes, ", ")) log.Write(EventAuthentication, msg) return at, nil } -var defaultTokenProvider azureCLITokenProvider = func(ctx context.Context, resource string, tenantID string) ([]byte, error) { - match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource) - if err != nil { - return nil, err - } - if !match { - return nil, fmt.Errorf(`%s: unexpected scope "%s". Only alphanumeric characters and ".", ";", "-", and "/" are allowed`, credNameAzureCLI, resource) - } - +// defaultAzTokenProvider invokes the Azure CLI to acquire a token. It assumes +// callers have verified that all string arguments are safe to pass to the CLI. +var defaultAzTokenProvider azTokenProvider = func(ctx context.Context, scopes []string, tenantID, subscription string) ([]byte, error) { + // pass the CLI a Microsoft Entra ID v1 resource because we don't know which CLI version is installed and older ones don't support v2 scopes + resource := strings.TrimSuffix(scopes[0], defaultSuffix) // set a default timeout for this authentication iff the application hasn't done so already var cancel context.CancelFunc if _, hasDeadline := ctx.Deadline(); !hasDeadline { - ctx, cancel = context.WithTimeout(ctx, timeoutCLIRequest) + ctx, cancel = context.WithTimeout(ctx, cliTimeout) defer cancel() } - commandLine := "az account get-access-token -o json --resource " + resource if tenantID != "" { commandLine += " --tenant " + tenantID } + if subscription != "" { + // subscription needs quotes because it may contain spaces + commandLine += ` --subscription "` + subscription + `"` + } var cliCmd *exec.Cmd if runtime.GOOS == "windows" { dir := os.Getenv("SYSTEMROOT") diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go new file mode 100644 index 000000000..cbe7c4c2d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go @@ -0,0 +1,169 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +const credNameAzureDeveloperCLI = "AzureDeveloperCLICredential" + +type azdTokenProvider func(ctx context.Context, scopes []string, tenant string) ([]byte, error) + +// AzureDeveloperCLICredentialOptions contains optional parameters for AzureDeveloperCLICredential. +type AzureDeveloperCLICredentialOptions struct { + // AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition + // to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the + // logged in account can access. + AdditionallyAllowedTenants []string + + // TenantID identifies the tenant the credential should authenticate in. Defaults to the azd environment, + // which is the tenant of the selected Azure subscription. + TenantID string + + // inDefaultChain is true when the credential is part of DefaultAzureCredential + inDefaultChain bool + // tokenProvider is used by tests to fake invoking azd + tokenProvider azdTokenProvider +} + +// AzureDeveloperCLICredential authenticates as the identity logged in to the [Azure Developer CLI]. +// +// [Azure Developer CLI]: https://learn.microsoft.com/azure/developer/azure-developer-cli/overview +type AzureDeveloperCLICredential struct { + mu *sync.Mutex + opts AzureDeveloperCLICredentialOptions +} + +// NewAzureDeveloperCLICredential constructs an AzureDeveloperCLICredential. Pass nil to accept default options. +func NewAzureDeveloperCLICredential(options *AzureDeveloperCLICredentialOptions) (*AzureDeveloperCLICredential, error) { + cp := AzureDeveloperCLICredentialOptions{} + if options != nil { + cp = *options + } + if cp.TenantID != "" && !validTenantID(cp.TenantID) { + return nil, errInvalidTenantID + } + if cp.tokenProvider == nil { + cp.tokenProvider = defaultAzdTokenProvider + } + return &AzureDeveloperCLICredential{mu: &sync.Mutex{}, opts: cp}, nil +} + +// GetToken requests a token from the Azure Developer CLI. This credential doesn't cache tokens, so every call invokes azd. +// This method is called automatically by Azure SDK clients. +func (c *AzureDeveloperCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + at := azcore.AccessToken{} + if len(opts.Scopes) == 0 { + return at, errors.New(credNameAzureDeveloperCLI + ": GetToken() requires at least one scope") + } + for _, scope := range opts.Scopes { + if !validScope(scope) { + return at, fmt.Errorf("%s.GetToken(): invalid scope %q", credNameAzureDeveloperCLI, scope) + } + } + tenant, err := resolveTenant(c.opts.TenantID, opts.TenantID, credNameAzureDeveloperCLI, c.opts.AdditionallyAllowedTenants) + if err != nil { + return at, err + } + c.mu.Lock() + defer c.mu.Unlock() + b, err := c.opts.tokenProvider(ctx, opts.Scopes, tenant) + if err == nil { + at, err = c.createAccessToken(b) + } + if err != nil { + err = unavailableIfInChain(err, c.opts.inDefaultChain) + return at, err + } + msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", credNameAzureDeveloperCLI, strings.Join(opts.Scopes, ", ")) + log.Write(EventAuthentication, msg) + return at, nil +} + +// defaultAzTokenProvider invokes the Azure Developer CLI to acquire a token. It assumes +// callers have verified that all string arguments are safe to pass to the CLI. +var defaultAzdTokenProvider azdTokenProvider = func(ctx context.Context, scopes []string, tenant string) ([]byte, error) { + // set a default timeout for this authentication iff the application hasn't done so already + var cancel context.CancelFunc + if _, hasDeadline := ctx.Deadline(); !hasDeadline { + ctx, cancel = context.WithTimeout(ctx, cliTimeout) + defer cancel() + } + commandLine := "azd auth token -o json" + if tenant != "" { + commandLine += " --tenant-id " + tenant + } + for _, scope := range scopes { + commandLine += " --scope " + scope + } + var cliCmd *exec.Cmd + if runtime.GOOS == "windows" { + dir := os.Getenv("SYSTEMROOT") + if dir == "" { + return nil, newCredentialUnavailableError(credNameAzureDeveloperCLI, "environment variable 'SYSTEMROOT' has no value") + } + cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine) + cliCmd.Dir = dir + } else { + cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine) + cliCmd.Dir = "/bin" + } + cliCmd.Env = os.Environ() + var stderr bytes.Buffer + cliCmd.Stderr = &stderr + output, err := cliCmd.Output() + if err != nil { + msg := stderr.String() + var exErr *exec.ExitError + if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'azd' is not recognized") { + msg = "Azure Developer CLI not found on path" + } else if strings.Contains(msg, "azd auth login") { + msg = `please run "azd auth login" from a command prompt to authenticate before using this credential` + } + if msg == "" { + msg = err.Error() + } + return nil, newCredentialUnavailableError(credNameAzureDeveloperCLI, msg) + } + return output, nil +} + +func (c *AzureDeveloperCLICredential) createAccessToken(tk []byte) (azcore.AccessToken, error) { + t := struct { + AccessToken string `json:"token"` + ExpiresOn string `json:"expiresOn"` + }{} + err := json.Unmarshal(tk, &t) + if err != nil { + return azcore.AccessToken{}, err + } + exp, err := time.Parse("2006-01-02T15:04:05Z", t.ExpiresOn) + if err != nil { + return azcore.AccessToken{}, fmt.Errorf("error parsing token expiration time %q: %v", t.ExpiresOn, err) + } + return azcore.AccessToken{ + ExpiresOn: exp.UTC(), + Token: t.AccessToken, + }, nil +} + +var _ azcore.TokenCredential = (*AzureDeveloperCLICredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml index 9002ea0b0..d077682c5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml @@ -25,6 +25,7 @@ stages: - template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml parameters: RunLiveTests: true + UsePipelineProxy: false ServiceDirectory: 'azidentity' CloudConfig: Public: diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go index 303d5fc09..fc3df68eb 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go @@ -12,6 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" ) @@ -20,9 +21,9 @@ const credNameAssertion = "ClientAssertionCredential" // ClientAssertionCredential authenticates an application with assertions provided by a callback function. // This credential is for advanced scenarios. [ClientCertificateCredential] has a more convenient API for // the most common assertion scenario, authenticating a service principal with a certificate. See -// [Azure AD documentation] for details of the assertion format. +// [Microsoft Entra ID documentation] for details of the assertion format. // -// [Azure AD documentation]: https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#assertion-format +// [Microsoft Entra ID documentation]: https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#assertion-format type ClientAssertionCredential struct { client *confidentialClient } @@ -35,11 +36,15 @@ type ClientAssertionCredentialOptions struct { // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the // application is registered. AdditionallyAllowedTenants []string + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions } // NewClientAssertionCredential constructs a ClientAssertionCredential. The getAssertion function must be thread safe. Pass nil for options to accept defaults. @@ -56,9 +61,10 @@ func NewClientAssertionCredential(tenantID, clientID string, getAssertion func(c }, ) msalOpts := confidentialClientOptions{ - AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, - ClientOptions: options.ClientOptions, - DisableInstanceDiscovery: options.DisableInstanceDiscovery, + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + tokenCachePersistenceOptions: options.tokenCachePersistenceOptions, } c, err := newConfidentialClient(tenantID, clientID, credNameAssertion, cred, msalOpts) if err != nil { @@ -67,9 +73,13 @@ func NewClientAssertionCredential(tenantID, clientID string, getAssertion func(c return &ClientAssertionCredential{client: c}, nil } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (c *ClientAssertionCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return c.client.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameAssertion+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err } var _ azcore.TokenCredential = (*ClientAssertionCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go index d3300e305..607533f48 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go @@ -15,6 +15,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" "golang.org/x/crypto/pkcs12" ) @@ -29,15 +30,20 @@ type ClientCertificateCredentialOptions struct { // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the // application is registered. AdditionallyAllowedTenants []string + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool + // SendCertificateChain controls whether the credential sends the public certificate chain in the x5c // header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. // Defaults to False. SendCertificateChain bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions } // ClientCertificateCredential authenticates a service principal with a certificate. @@ -58,10 +64,11 @@ func NewClientCertificateCredential(tenantID string, clientID string, certs []*x return nil, err } msalOpts := confidentialClientOptions{ - AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, - ClientOptions: options.ClientOptions, - DisableInstanceDiscovery: options.DisableInstanceDiscovery, - SendX5C: options.SendCertificateChain, + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + SendX5C: options.SendCertificateChain, + tokenCachePersistenceOptions: options.tokenCachePersistenceOptions, } c, err := newConfidentialClient(tenantID, clientID, credNameCert, cred, msalOpts) if err != nil { @@ -70,9 +77,13 @@ func NewClientCertificateCredential(tenantID string, clientID string, certs []*x return &ClientCertificateCredential{client: c}, nil } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return c.client.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameCert+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err } // ParseCertificates loads certificates and a private key, in PEM or PKCS12 format, for use with NewClientCertificateCredential. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go index d2ff7582b..9e6772e9b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go @@ -11,6 +11,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" ) @@ -24,11 +25,15 @@ type ClientSecretCredentialOptions struct { // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the // application is registered. AdditionallyAllowedTenants []string + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions } // ClientSecretCredential authenticates an application with a client secret. @@ -46,20 +51,25 @@ func NewClientSecretCredential(tenantID string, clientID string, clientSecret st return nil, err } msalOpts := confidentialClientOptions{ - AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, - ClientOptions: options.ClientOptions, - DisableInstanceDiscovery: options.DisableInstanceDiscovery, + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + tokenCachePersistenceOptions: options.tokenCachePersistenceOptions, } c, err := newConfidentialClient(tenantID, clientID, credNameSecret, cred, msalOpts) if err != nil { return nil, err } - return &ClientSecretCredential{c}, nil + return &ClientSecretCredential{client: c}, nil } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (c *ClientSecretCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return c.client.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameSecret+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err } var _ azcore.TokenCredential = (*ClientSecretCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go index 4853a9a00..854267bdb 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go @@ -10,6 +10,7 @@ import ( "context" "errors" "fmt" + "net/http" "os" "strings" "sync" @@ -17,6 +18,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal" "github.com/Azure/azure-sdk-for-go/sdk/internal/log" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" ) @@ -28,6 +30,7 @@ type confidentialClientOptions struct { // Assertion for on-behalf-of authentication Assertion string DisableInstanceDiscovery, SendX5C bool + tokenCachePersistenceOptions *tokenCachePersistenceOptions } // confidentialClient wraps the MSAL confidential client @@ -40,6 +43,7 @@ type confidentialClient struct { name string opts confidentialClientOptions region string + azClient *azcore.Client } func newConfidentialClient(tenantID, clientID, name string, cred confidential.Credential, opts confidentialClientOptions) (*confidentialClient, error) { @@ -50,6 +54,14 @@ func newConfidentialClient(tenantID, clientID, name string, cred confidential.Cr if err != nil { return nil, err } + client, err := azcore.NewClient(module, version, runtime.PipelineOptions{ + Tracing: runtime.TracingOptions{ + Namespace: traceNamespace, + }, + }, &opts.ClientOptions) + if err != nil { + return nil, err + } opts.AdditionallyAllowedTenants = resolveAdditionalTenants(opts.AdditionallyAllowedTenants) return &confidentialClient{ caeMu: &sync.Mutex{}, @@ -62,6 +74,7 @@ func newConfidentialClient(tenantID, clientID, name string, cred confidential.Cr opts: opts, region: os.Getenv(azureRegionalAuthorityName), tenantID: tenantID, + azClient: client, }, nil } @@ -132,10 +145,15 @@ func (c *confidentialClient) client(ctx context.Context, tro policy.TokenRequest } func (c *confidentialClient) newMSALClient(enableCAE bool) (msalConfidentialClient, error) { + cache, err := internal.NewCache(c.opts.tokenCachePersistenceOptions, enableCAE) + if err != nil { + return nil, err + } authority := runtime.JoinPaths(c.host, c.tenantID) o := []confidential.Option{ confidential.WithAzureRegion(c.region), - confidential.WithHTTPClient(newPipelineAdapter(&c.opts.ClientOptions)), + confidential.WithCache(cache), + confidential.WithHTTPClient(c), } if enableCAE { o = append(o, confidential.WithClientCapabilities(cp1)) @@ -149,8 +167,18 @@ func (c *confidentialClient) newMSALClient(enableCAE bool) (msalConfidentialClie return confidential.New(authority, c.clientID, c.cred, o...) } -// resolveTenant returns the correct tenant for a token request given the client's +// resolveTenant returns the correct WithTenantID() argument for a token request given the client's // configuration, or an error when that configuration doesn't allow the specified tenant func (c *confidentialClient) resolveTenant(specified string) (string, error) { return resolveTenant(c.tenantID, specified, c.name, c.opts.AdditionallyAllowedTenants) } + +// these methods satisfy the MSAL ops.HTTPClient interface + +func (c *confidentialClient) CloseIdleConnections() { + // do nothing +} + +func (c *confidentialClient) Do(r *http.Request) (*http.Response, error) { + return doForClient(c.azClient, r) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go index 7647c60b1..35aeef867 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go @@ -30,7 +30,7 @@ type DefaultAzureCredentialOptions struct { // set as a semicolon delimited list of tenants in the environment variable AZURE_ADDITIONALLY_ALLOWED_TENANTS. AdditionallyAllowedTenants []string // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool @@ -49,6 +49,7 @@ type DefaultAzureCredentialOptions struct { // more control over its configuration. // - [ManagedIdentityCredential] // - [AzureCLICredential] +// - [AzureDeveloperCLICredential] // // Consult the documentation for these credential types for more information on how they authenticate. // Once a credential has successfully authenticated, DefaultAzureCredential will use that credential for @@ -117,6 +118,17 @@ func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*Default creds = append(creds, &defaultCredentialErrorReporter{credType: credNameAzureCLI, err: err}) } + azdCred, err := NewAzureDeveloperCLICredential(&AzureDeveloperCLICredentialOptions{ + AdditionallyAllowedTenants: additionalTenants, + TenantID: options.TenantID, + }) + if err == nil { + creds = append(creds, azdCred) + } else { + errorMessages = append(errorMessages, credNameAzureDeveloperCLI+": "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: credNameAzureDeveloperCLI, err: err}) + } + if len(errorMessages) > 0 { log.Writef(EventAuthentication, "NewDefaultAzureCredential failed to initialize some credentials:\n\t%s", strings.Join(errorMessages, "\n\t")) } @@ -129,7 +141,7 @@ func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*Default return &DefaultAzureCredential{chain: chain}, nil } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (c *DefaultAzureCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { return c.chain.GetToken(ctx, opts) } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/developer_credential_util.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/developer_credential_util.go new file mode 100644 index 000000000..d8b952f53 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/developer_credential_util.go @@ -0,0 +1,38 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "errors" + "time" +) + +// cliTimeout is the default timeout for authentication attempts via CLI tools +const cliTimeout = 10 * time.Second + +// unavailableIfInChain returns err or, if the credential was invoked by DefaultAzureCredential, a +// credentialUnavailableError having the same message. This ensures DefaultAzureCredential will try +// the next credential in its chain (another developer credential). +func unavailableIfInChain(err error, inDefaultChain bool) error { + if err != nil && inDefaultChain { + var unavailableErr *credentialUnavailableError + if !errors.As(err, &unavailableErr) { + err = newCredentialUnavailableError(credNameAzureDeveloperCLI, err.Error()) + } + } + return err +} + +// validScope is for credentials authenticating via external tools. The authority validates scopes for all other credentials. +func validScope(scope string) bool { + for _, r := range scope { + if !(alphanumeric(r) || r == '.' || r == '-' || r == '_' || r == '/' || r == ':') { + return false + } + } + return true +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go index d245c269a..1b7a28370 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go @@ -12,6 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" ) const credNameDeviceCode = "DeviceCodeCredential" @@ -23,19 +24,34 @@ type DeviceCodeCredentialOptions struct { // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. AdditionallyAllowedTenants []string + + // authenticationRecord returned by a call to a credential's Authenticate method. Set this option + // to enable the credential to use data from a previous authentication. + authenticationRecord authenticationRecord + // ClientID is the ID of the application users will authenticate to. // Defaults to the ID of an Azure development application. ClientID string + + // disableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate. + // When this option is true, [DeviceCodeCredential.GetToken] will return [ErrAuthenticationRequired] when user + // interaction is necessary to acquire a token. + disableAutomaticAuthentication bool + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool - // TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the + + // TenantID is the Microsoft Entra tenant the credential authenticates in. Defaults to the // "organizations" tenant, which can authenticate work and school accounts. Required for single-tenant // applications. TenantID string + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions + // UserPrompt controls how the credential presents authentication instructions. The credential calls // this function with authentication details when it receives a device code. By default, the credential // prints these details to stdout. @@ -63,14 +79,14 @@ type DeviceCodeMessage struct { UserCode string `json:"user_code"` // VerificationURL is the URL at which the user must authenticate. VerificationURL string `json:"verification_uri"` - // Message is user instruction from Azure Active Directory. + // Message is user instruction from Microsoft Entra ID. Message string `json:"message"` } // DeviceCodeCredential acquires tokens for a user via the device code flow, which has the -// user browse to an Azure Active Directory URL, enter a code, and authenticate. It's useful +// user browse to a Microsoft Entra URL, enter a code, and authenticate. It's useful // for authenticating a user in an environment without a web browser, such as an SSH session. -// If a web browser is available, InteractiveBrowserCredential is more convenient because it +// If a web browser is available, [InteractiveBrowserCredential] is more convenient because it // automatically opens a browser to the login page. type DeviceCodeCredential struct { client *publicClient @@ -84,10 +100,13 @@ func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeC } cp.init() msalOpts := publicClientOptions{ - AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants, - ClientOptions: cp.ClientOptions, - DeviceCodePrompt: cp.UserPrompt, - DisableInstanceDiscovery: cp.DisableInstanceDiscovery, + AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants, + ClientOptions: cp.ClientOptions, + DeviceCodePrompt: cp.UserPrompt, + DisableAutomaticAuthentication: cp.disableAutomaticAuthentication, + DisableInstanceDiscovery: cp.DisableInstanceDiscovery, + Record: cp.authenticationRecord, + TokenCachePersistenceOptions: cp.tokenCachePersistenceOptions, } c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameDeviceCode, msalOpts) if err != nil { @@ -97,10 +116,23 @@ func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeC return &DeviceCodeCredential{client: c}, nil } -// GetToken requests an access token from Azure Active Directory. It will begin the device code flow and poll until the user completes authentication. +// Authenticate a user via the device code flow. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. +func (c *DeviceCodeCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameDeviceCode+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.Authenticate(ctx, opts) + return tk, err +} + +// GetToken requests an access token from Microsoft Entra ID. It will begin the device code flow and poll until the user completes authentication. // This method is called automatically by Azure SDK clients. func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return c.client.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameDeviceCode+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err } var _ azcore.TokenCredential = (*DeviceCodeCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go index 7ecd928e0..42f84875e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go @@ -25,7 +25,7 @@ type EnvironmentCredentialOptions struct { azcore.ClientOptions // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool @@ -156,7 +156,7 @@ func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*Environme return nil, errors.New("incomplete environment variable configuration. Only AZURE_TENANT_ID and AZURE_CLIENT_ID are set") } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (c *EnvironmentCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { return c.cred.GetToken(ctx, opts) } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go index e1a21e003..335d2b7dc 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go @@ -18,6 +18,10 @@ import ( msal "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" ) +// errAuthenticationRequired indicates a credential's Authenticate method must be called to acquire a token +// because user interaction is required and the credential is configured not to automatically prompt the user. +var errAuthenticationRequired error = &credentialUnavailableError{"can't acquire a token without user interaction. Call Authenticate to interactively authenticate a user"} + // getResponseFromError retrieves the response carried by // an AuthenticationFailedError or MSAL CallErr, if any func getResponseFromError(err error) *http.Response { @@ -53,7 +57,13 @@ func (e *AuthenticationFailedError) Error() string { } msg := &bytes.Buffer{} fmt.Fprintf(msg, e.credType+" authentication failed\n") - fmt.Fprintf(msg, "%s %s://%s%s\n", e.RawResponse.Request.Method, e.RawResponse.Request.URL.Scheme, e.RawResponse.Request.URL.Host, e.RawResponse.Request.URL.Path) + if e.RawResponse.Request != nil { + fmt.Fprintf(msg, "%s %s://%s%s\n", e.RawResponse.Request.Method, e.RawResponse.Request.URL.Scheme, e.RawResponse.Request.URL.Host, e.RawResponse.Request.URL.Path) + } else { + // this happens when the response is created from a custom HTTP transporter, + // which doesn't guarantee to bind the original request to the response + fmt.Fprintln(msg, "Request information not available") + } fmt.Fprintln(msg, "--------------------------------------------------------------------------------") fmt.Fprintf(msg, "RESPONSE %s\n", e.RawResponse.Status) fmt.Fprintln(msg, "--------------------------------------------------------------------------------") @@ -74,6 +84,8 @@ func (e *AuthenticationFailedError) Error() string { switch e.credType { case credNameAzureCLI: anchor = "azure-cli" + case credNameAzureDeveloperCLI: + anchor = "azd" case credNameCert: anchor = "client-cert" case credNameSecret: diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work new file mode 100644 index 000000000..04ea962b4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work @@ -0,0 +1,6 @@ +go 1.18 + +use ( + . + ./cache +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work.sum b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work.sum new file mode 100644 index 000000000..7cd86b001 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work.sum @@ -0,0 +1,39 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0-beta.1 h1:ODs3brnqQM99Tq1PffODpAViYv3Bf8zOg464MU7p5ew= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0-beta.1/go.mod h1:3Ug6Qzto9anB6mGlEdgYMDF5zHQ+wwhEaYR4s17PHMw= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0 h1:fb8kj/Dh4CSwgsOzHeZY4Xh68cFVbzXx+ONXGMY//4w= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0/go.mod h1:uReU2sSxZExRPBAg3qKzmAucSi51+SP1OhohieR821Q= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go index 08f3efbf3..bd8296983 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go @@ -11,6 +11,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" ) const credNameBrowser = "InteractiveBrowserCredential" @@ -22,26 +23,40 @@ type InteractiveBrowserCredentialOptions struct { // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. AdditionallyAllowedTenants []string + + // authenticationRecord returned by a call to a credential's Authenticate method. Set this option + // to enable the credential to use data from a previous authentication. + authenticationRecord authenticationRecord + // ClientID is the ID of the application users will authenticate to. // Defaults to the ID of an Azure development application. ClientID string + // disableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate. + // When this option is true, [InteractiveBrowserCredential.GetToken] will return [ErrAuthenticationRequired] when + // user interaction is necessary to acquire a token. + disableAutomaticAuthentication bool + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool // LoginHint pre-populates the account prompt with a username. Users may choose to authenticate a different account. LoginHint string - // RedirectURL is the URL Azure Active Directory will redirect to with the access token. This is required + + // RedirectURL is the URL Microsoft Entra ID will redirect to with the access token. This is required // only when setting ClientID, and must match a redirect URI in the application's registration. // Applications which have registered "http://localhost" as a redirect URI need not set this option. RedirectURL string - // TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the + // TenantID is the Microsoft Entra tenant the credential authenticates in. Defaults to the // "organizations" tenant, which can authenticate work and school accounts. TenantID string + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions } func (o *InteractiveBrowserCredentialOptions) init() { @@ -66,10 +81,14 @@ func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOption } cp.init() msalOpts := publicClientOptions{ - ClientOptions: cp.ClientOptions, - DisableInstanceDiscovery: cp.DisableInstanceDiscovery, - LoginHint: cp.LoginHint, - RedirectURL: cp.RedirectURL, + AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants, + ClientOptions: cp.ClientOptions, + DisableAutomaticAuthentication: cp.disableAutomaticAuthentication, + DisableInstanceDiscovery: cp.DisableInstanceDiscovery, + LoginHint: cp.LoginHint, + Record: cp.authenticationRecord, + RedirectURL: cp.RedirectURL, + TokenCachePersistenceOptions: cp.tokenCachePersistenceOptions, } c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameBrowser, msalOpts) if err != nil { @@ -78,9 +97,22 @@ func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOption return &InteractiveBrowserCredential{client: c}, nil } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// Authenticate a user via the default browser. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. +func (c *InteractiveBrowserCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameBrowser+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.Authenticate(ctx, opts) + return tk, err +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return c.client.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameBrowser+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err } var _ azcore.TokenCredential = (*InteractiveBrowserCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/exported.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/exported.go new file mode 100644 index 000000000..b1b4d5c8b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/exported.go @@ -0,0 +1,18 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package internal + +// TokenCachePersistenceOptions contains options for persistent token caching +type TokenCachePersistenceOptions struct { + // AllowUnencryptedStorage controls whether the cache should fall back to storing its data in plain text + // when encryption isn't possible. Setting this true doesn't disable encryption. The cache always attempts + // encryption before falling back to plaintext storage. + AllowUnencryptedStorage bool + + // Name identifies the cache. Set this to isolate data from other applications. + Name string +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/internal.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/internal.go new file mode 100644 index 000000000..c1498b464 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/internal.go @@ -0,0 +1,31 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package internal + +import ( + "errors" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" +) + +var errMissingImport = errors.New("import github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache to enable persistent caching") + +// NewCache constructs a persistent token cache when "o" isn't nil. Applications that intend to +// use a persistent cache must first import the cache module, which will replace this function +// with a platform-specific implementation. +var NewCache = func(o *TokenCachePersistenceOptions, enableCAE bool) (cache.ExportReplace, error) { + if o == nil { + return nil, nil + } + return nil, errMissingImport +} + +// CacheFilePath returns the path to the cache file for the given name. +// Defining it in this package makes it available to azidentity tests. +var CacheFilePath = func(name string) (string, error) { + return "", errMissingImport +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go index fdc3c1f67..7c25cb8bd 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go @@ -28,12 +28,14 @@ import ( const ( arcIMDSEndpoint = "IMDS_ENDPOINT" + defaultIdentityClientID = "DEFAULT_IDENTITY_CLIENT_ID" identityEndpoint = "IDENTITY_ENDPOINT" identityHeader = "IDENTITY_HEADER" identityServerThumbprint = "IDENTITY_SERVER_THUMBPRINT" headerMetadata = "Metadata" imdsEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" msiEndpoint = "MSI_ENDPOINT" + msiSecret = "MSI_SECRET" imdsAPIVersion = "2018-02-01" azureArcAPIVersion = "2019-08-15" serviceFabricAPIVersion = "2019-07-01-preview" @@ -47,6 +49,7 @@ type msiType int const ( msiTypeAppService msiType = iota msiTypeAzureArc + msiTypeAzureML msiTypeCloudShell msiTypeIMDS msiTypeServiceFabric @@ -55,7 +58,7 @@ const ( // managedIdentityClient provides the base for authenticating in managed identity environments // This type includes an runtime.Pipeline and TokenCredentialOptions. type managedIdentityClient struct { - pipeline runtime.Pipeline + azClient *azcore.Client msiType msiType endpoint string id ManagedIDKind @@ -135,13 +138,27 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*manag c.msiType = msiTypeAzureArc } } else if endpoint, ok := os.LookupEnv(msiEndpoint); ok { - env = "Cloud Shell" c.endpoint = endpoint - c.msiType = msiTypeCloudShell + if _, ok := os.LookupEnv(msiSecret); ok { + env = "Azure ML" + c.msiType = msiTypeAzureML + } else { + env = "Cloud Shell" + c.msiType = msiTypeCloudShell + } } else { setIMDSRetryOptionDefaults(&cp.Retry) } - c.pipeline = runtime.NewPipeline(component, version, runtime.PipelineOptions{}, &cp) + + client, err := azcore.NewClient(module, version, runtime.PipelineOptions{ + Tracing: runtime.TracingOptions{ + Namespace: traceNamespace, + }, + }, &cp) + if err != nil { + return nil, err + } + c.azClient = client if log.Should(EventAuthentication) { log.Writef(EventAuthentication, "Managed Identity Credential will use %s managed identity", env) @@ -168,7 +185,7 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi return azcore.AccessToken{}, err } - resp, err := c.pipeline.Do(msg) + resp, err := c.azClient.Pipeline().Do(msg) if err != nil { return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, err.Error(), nil, err) } @@ -247,6 +264,8 @@ func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id Manage return nil, newAuthenticationFailedError(credNameManagedIdentity, msg, nil, err) } return c.createAzureArcAuthRequest(ctx, id, scopes, key) + case msiTypeAzureML: + return c.createAzureMLAuthRequest(ctx, id, scopes) case msiTypeServiceFabric: return c.createServiceFabricAuthRequest(ctx, id, scopes) case msiTypeCloudShell: @@ -296,6 +315,29 @@ func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context, return request, nil } +func (c *managedIdentityClient) createAzureMLAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set("secret", os.Getenv(msiSecret)) + q := request.Raw().URL.Query() + q.Add("api-version", "2017-09-01") + q.Add("resource", strings.Join(scopes, " ")) + q.Add("clientid", os.Getenv(defaultIdentityClientID)) + if id != nil { + if id.idKind() == miResourceID { + log.Write(EventAuthentication, "WARNING: Azure ML doesn't support specifying a managed identity by resource ID") + q.Set("clientid", "") + q.Set(qpResID, id.String()) + } else { + q.Set("clientid", id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) if err != nil { @@ -330,7 +372,7 @@ func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resour q.Add("resource", strings.Join(resources, " ")) request.Raw().URL.RawQuery = q.Encode() // send the initial request to get the short-lived secret key - response, err := c.pipeline.Do(request) + response, err := c.azClient.Pipeline().Do(request) if err != nil { return "", err } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go index 35c5e6725..dcd278bef 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go @@ -13,6 +13,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" ) @@ -67,8 +68,8 @@ type ManagedIdentityCredentialOptions struct { // ManagedIdentityCredential authenticates an Azure managed identity in any hosting environment supporting managed identities. // This credential authenticates a system-assigned identity by default. Use ManagedIdentityCredentialOptions.ID to specify a -// user-assigned identity. See Azure Active Directory documentation for more information about managed identities: -// https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview +// user-assigned identity. See Microsoft Entra ID documentation for more information about managed identities: +// https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview type ManagedIdentityCredential struct { client *confidentialClient mic *managedIdentityClient @@ -92,7 +93,9 @@ func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*M clientID = options.ID.String() } // similarly, it's okay to give MSAL an incorrect tenant because MSAL won't use the value - c, err := newConfidentialClient("common", clientID, credNameManagedIdentity, cred, confidentialClientOptions{}) + c, err := newConfidentialClient("common", clientID, credNameManagedIdentity, cred, confidentialClientOptions{ + ClientOptions: options.ClientOptions, + }) if err != nil { return nil, err } @@ -101,13 +104,18 @@ func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*M // GetToken requests an access token from the hosting environment. This method is called automatically by Azure SDK clients. func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameManagedIdentity+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + if len(opts.Scopes) != 1 { - err := fmt.Errorf("%s.GetToken() requires exactly one scope", credNameManagedIdentity) + err = fmt.Errorf("%s.GetToken() requires exactly one scope", credNameManagedIdentity) return azcore.AccessToken{}, err } - // managed identity endpoints require an AADv1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here + // managed identity endpoints require a Microsoft Entra ID v1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here opts.Scopes = []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)} - return c.client.GetToken(ctx, opts) + tk, err := c.client.GetToken(ctx, opts) + return tk, err } var _ azcore.TokenCredential = (*ManagedIdentityCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/on_behalf_of_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/on_behalf_of_credential.go index 2b360b681..5e67cf021 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/on_behalf_of_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/on_behalf_of_credential.go @@ -13,6 +13,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" ) @@ -21,9 +22,9 @@ const credNameOBO = "OnBehalfOfCredential" // OnBehalfOfCredential authenticates a service principal via the on-behalf-of flow. This is typically used by // middle-tier services that authorize requests to other services with a delegated user identity. Because this // is not an interactive authentication flow, an application using it must have admin consent for any delegated -// permissions before requesting tokens for them. See [Azure Active Directory documentation] for more details. +// permissions before requesting tokens for them. See [Microsoft Entra ID documentation] for more details. // -// [Azure Active Directory documentation]: https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow +// [Microsoft Entra ID documentation]: https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow type OnBehalfOfCredential struct { client *confidentialClient } @@ -36,11 +37,13 @@ type OnBehalfOfCredentialOptions struct { // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the // application is registered. AdditionallyAllowedTenants []string + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool + // SendCertificateChain applies only when the credential is configured to authenticate with a certificate. // This setting controls whether the credential sends the public certificate chain in the x5c header of each // token request's JWT. This is required for, and only used in, Subject Name/Issuer (SNI) authentication. @@ -84,9 +87,13 @@ func newOnBehalfOfCredential(tenantID, clientID, userAssertion string, cred conf return &OnBehalfOfCredential{c}, nil } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (o *OnBehalfOfCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return o.client.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameOBO+"."+traceOpGetToken, o.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := o.client.GetToken(ctx, opts) + return tk, err } var _ azcore.TokenCredential = (*OnBehalfOfCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go index 6512d3e25..63c31190d 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go @@ -8,38 +8,52 @@ package azidentity import ( "context" + "errors" "fmt" + "net/http" "strings" "sync" "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal" "github.com/Azure/azure-sdk-for-go/sdk/internal/log" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" + + // this import ensures well-known configurations in azcore/cloud have ARM audiences for Authenticate() + _ "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" ) type publicClientOptions struct { azcore.ClientOptions - AdditionallyAllowedTenants []string - DeviceCodePrompt func(context.Context, DeviceCodeMessage) error - DisableInstanceDiscovery bool - LoginHint, RedirectURL string - Username, Password string + AdditionallyAllowedTenants []string + DeviceCodePrompt func(context.Context, DeviceCodeMessage) error + DisableAutomaticAuthentication bool + DisableInstanceDiscovery bool + LoginHint, RedirectURL string + Record authenticationRecord + TokenCachePersistenceOptions *tokenCachePersistenceOptions + Username, Password string } // publicClient wraps the MSAL public client type publicClient struct { - account public.Account cae, noCAE msalPublicClient caeMu, noCAEMu, clientMu *sync.Mutex clientID, tenantID string + defaultScope []string host string name string opts publicClientOptions + record authenticationRecord + azClient *azcore.Client } +var errScopeRequired = errors.New("authenticating in this environment requires specifying a scope in TokenRequestOptions") + func newPublicClient(tenantID, clientID, name string, o publicClientOptions) (*publicClient, error) { if !validTenantID(tenantID) { return nil, errInvalidTenantID @@ -48,19 +62,76 @@ func newPublicClient(tenantID, clientID, name string, o publicClientOptions) (*p if err != nil { return nil, err } + // if the application specified a cloud configuration, use its ARM audience as the default scope for Authenticate() + audience := o.Cloud.Services[cloud.ResourceManager].Audience + if audience == "" { + // no cloud configuration, or no ARM audience, specified; try to map the host to a well-known one (all of which have a trailing slash) + if !strings.HasSuffix(host, "/") { + host += "/" + } + switch host { + case cloud.AzureChina.ActiveDirectoryAuthorityHost: + audience = cloud.AzureChina.Services[cloud.ResourceManager].Audience + case cloud.AzureGovernment.ActiveDirectoryAuthorityHost: + audience = cloud.AzureGovernment.Services[cloud.ResourceManager].Audience + case cloud.AzurePublic.ActiveDirectoryAuthorityHost: + audience = cloud.AzurePublic.Services[cloud.ResourceManager].Audience + } + } + // if we didn't come up with an audience, the application will have to specify a scope for Authenticate() + var defaultScope []string + if audience != "" { + defaultScope = []string{audience + defaultSuffix} + } + client, err := azcore.NewClient(module, version, runtime.PipelineOptions{ + Tracing: runtime.TracingOptions{ + Namespace: traceNamespace, + }, + }, &o.ClientOptions) + if err != nil { + return nil, err + } o.AdditionallyAllowedTenants = resolveAdditionalTenants(o.AdditionallyAllowedTenants) return &publicClient{ - caeMu: &sync.Mutex{}, - clientID: clientID, - clientMu: &sync.Mutex{}, - host: host, - name: name, - noCAEMu: &sync.Mutex{}, - opts: o, - tenantID: tenantID, + caeMu: &sync.Mutex{}, + clientID: clientID, + clientMu: &sync.Mutex{}, + defaultScope: defaultScope, + host: host, + name: name, + noCAEMu: &sync.Mutex{}, + opts: o, + record: o.Record, + tenantID: tenantID, + azClient: client, }, nil } +func (p *publicClient) Authenticate(ctx context.Context, tro *policy.TokenRequestOptions) (authenticationRecord, error) { + if tro == nil { + tro = &policy.TokenRequestOptions{} + } + if len(tro.Scopes) == 0 { + if p.defaultScope == nil { + return authenticationRecord{}, errScopeRequired + } + tro.Scopes = p.defaultScope + } + client, mu, err := p.client(*tro) + if err != nil { + return authenticationRecord{}, err + } + mu.Lock() + defer mu.Unlock() + _, err = p.reqToken(ctx, client, *tro) + if err == nil { + scope := strings.Join(tro.Scopes, ", ") + msg := fmt.Sprintf("%s.Authenticate() acquired a token for scope %q", p.name, scope) + log.Write(EventAuthentication, msg) + } + return p.record, err +} + // GetToken requests an access token from MSAL, checking the cache first. func (p *publicClient) GetToken(ctx context.Context, tro policy.TokenRequestOptions) (azcore.AccessToken, error) { if len(tro.Scopes) < 1 { @@ -76,10 +147,13 @@ func (p *publicClient) GetToken(ctx context.Context, tro policy.TokenRequestOpti } mu.Lock() defer mu.Unlock() - ar, err := client.AcquireTokenSilent(ctx, tro.Scopes, public.WithSilentAccount(p.account), public.WithClaims(tro.Claims), public.WithTenantID(tenant)) + ar, err := client.AcquireTokenSilent(ctx, tro.Scopes, public.WithSilentAccount(p.record.account()), public.WithClaims(tro.Claims), public.WithTenantID(tenant)) if err == nil { return p.token(ar, err) } + if p.opts.DisableAutomaticAuthentication { + return azcore.AccessToken{}, errAuthenticationRequired + } at, err := p.reqToken(ctx, client, tro) if err == nil { msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", p.name, strings.Join(ar.GrantedScopes, ", ")) @@ -148,9 +222,14 @@ func (p *publicClient) client(tro policy.TokenRequestOptions) (msalPublicClient, } func (p *publicClient) newMSALClient(enableCAE bool) (msalPublicClient, error) { + cache, err := internal.NewCache(p.opts.TokenCachePersistenceOptions, enableCAE) + if err != nil { + return nil, err + } o := []public.Option{ public.WithAuthority(runtime.JoinPaths(p.host, p.tenantID)), - public.WithHTTPClient(newPipelineAdapter(&p.opts.ClientOptions)), + public.WithCache(cache), + public.WithHTTPClient(p), } if enableCAE { o = append(o, public.WithClientCapabilities(cp1)) @@ -163,7 +242,7 @@ func (p *publicClient) newMSALClient(enableCAE bool) (msalPublicClient, error) { func (p *publicClient) token(ar public.AuthResult, err error) (azcore.AccessToken, error) { if err == nil { - p.account = ar.Account + p.record, err = newAuthenticationRecord(ar) } else { res := getResponseFromError(err) err = newAuthenticationFailedError(p.name, err.Error(), res, err) @@ -171,8 +250,24 @@ func (p *publicClient) token(ar public.AuthResult, err error) (azcore.AccessToke return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err } -// resolveTenant returns the correct tenant for a token request given the client's +// resolveTenant returns the correct WithTenantID() argument for a token request given the client's // configuration, or an error when that configuration doesn't allow the specified tenant func (p *publicClient) resolveTenant(specified string) (string, error) { - return resolveTenant(p.tenantID, specified, p.name, p.opts.AdditionallyAllowedTenants) + t, err := resolveTenant(p.tenantID, specified, p.name, p.opts.AdditionallyAllowedTenants) + if t == p.tenantID { + // callers pass this value to MSAL's WithTenantID(). There's no need to redundantly specify + // the client's default tenant and doing so is an error when that tenant is "organizations" + t = "" + } + return t, err +} + +// these methods satisfy the MSAL ops.HTTPClient interface + +func (p *publicClient) CloseIdleConnections() { + // do nothing +} + +func (p *publicClient) Do(r *http.Request) (*http.Response, error) { + return doForClient(p.azClient, r) } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go index f787ec0ce..294ed81e9 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go @@ -11,6 +11,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" ) const credNameUserPassword = "UsernamePasswordCredential" @@ -23,11 +24,19 @@ type UsernamePasswordCredentialOptions struct { // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the // application is registered. AdditionallyAllowedTenants []string + + // authenticationRecord returned by a call to a credential's Authenticate method. Set this option + // to enable the credential to use data from a previous authentication. + authenticationRecord authenticationRecord + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions } // UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication, @@ -45,11 +54,13 @@ func NewUsernamePasswordCredential(tenantID string, clientID string, username st options = &UsernamePasswordCredentialOptions{} } opts := publicClientOptions{ - AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, - ClientOptions: options.ClientOptions, - DisableInstanceDiscovery: options.DisableInstanceDiscovery, - Password: password, - Username: username, + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + Password: password, + Record: options.authenticationRecord, + TokenCachePersistenceOptions: options.tokenCachePersistenceOptions, + Username: username, } c, err := newPublicClient(tenantID, clientID, credNameUserPassword, opts) if err != nil { @@ -58,9 +69,22 @@ func NewUsernamePasswordCredential(tenantID string, clientID string, username st return &UsernamePasswordCredential{client: c}, err } -// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +// Authenticate the user. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. +func (c *UsernamePasswordCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameUserPassword+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.Authenticate(ctx, opts) + return tk, err +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return c.client.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameUserPassword+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err } var _ azcore.TokenCredential = (*UsernamePasswordCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go index 65e74e31e..e8caeea71 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go @@ -10,6 +10,9 @@ const ( // UserAgent is the string to be used in the user agent string when making requests. component = "azidentity" + // module is the fully qualified name of the module used in telemetry and distributed tracing. + module = "github.com/Azure/azure-sdk-for-go/sdk/" + component + // Version is the semantic version (see http://semver.org) of this module. - version = "v1.4.0" + version = "v1.5.1" ) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/workload_identity.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/workload_identity.go index 7e016324d..3e43e788e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/workload_identity.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/workload_identity.go @@ -15,6 +15,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" ) const credNameWorkloadIdentity = "WorkloadIdentityCredential" @@ -41,7 +42,7 @@ type WorkloadIdentityCredentialOptions struct { // ClientID of the service principal. Defaults to the value of the environment variable AZURE_CLIENT_ID. ClientID string // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or - // private clouds such as Azure Stack. It determines whether the credential requests Azure AD instance metadata + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool @@ -93,9 +94,13 @@ func NewWorkloadIdentityCredential(options *WorkloadIdentityCredentialOptions) ( return &w, nil } -// GetToken requests an access token from Azure Active Directory. Azure SDK clients call this method automatically. +// GetToken requests an access token from Microsoft Entra ID. Azure SDK clients call this method automatically. func (w *WorkloadIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { - return w.cred.GetToken(ctx, opts) + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameWorkloadIdentity+"."+traceOpGetToken, w.cred.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := w.cred.GetToken(ctx, opts) + return tk, err } // getAssertion returns the specified file's content, which is expected to be a Kubernetes service account token. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/exported/exported.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/exported/exported.go index d4ed6ccc8..9948f604b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/exported/exported.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/exported/exported.go @@ -39,6 +39,11 @@ type PayloadOptions struct { // Subsequent reads will access the cached value. // Exported as runtime.Payload() WITHOUT the opts parameter. func Payload(resp *http.Response, opts *PayloadOptions) ([]byte, error) { + if resp.Body == nil { + // this shouldn't happen in real-world scenarios as a + // response with no body should set it to http.NoBody + return nil, nil + } modifyBytes := func(b []byte) []byte { return b } if opts != nil && opts.BytesModifier != nil { modifyBytes = opts.BytesModifier diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/CHANGELOG.md index b19244d46..836f84817 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/CHANGELOG.md @@ -1,5 +1,13 @@ # Release History +## 5.5.0 (2024-01-26) +### Features Added + +- New value `DiskSecurityTypesConfidentialVMNonPersistedTPM` added to enum type `DiskSecurityTypes` +- New enum type `ProvisionedBandwidthCopyOption` with values `ProvisionedBandwidthCopyOptionEnhanced`, `ProvisionedBandwidthCopyOptionNone` +- New field `ProvisionedBandwidthCopySpeed` in struct `CreationData` + + ## 5.4.0 (2023-12-22) ### Features Added diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/README.md index 7c8d1e3e1..c4bf8ab34 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/README.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/README.md @@ -57,7 +57,7 @@ clientFactory, err := armcompute.NewClientFactory(, cred, &opti A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. ```go -client := clientFactory.NewLogAnalyticsClient() +client := clientFactory.NewAvailabilitySetsClient() ``` ## Fakes diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/assets.json index 1feae4c5c..f8177c784 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/assets.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "go", "TagPrefix": "go/resourcemanager/compute/armcompute", - "Tag": "go/resourcemanager/compute/armcompute_323718962d" + "Tag": "go/resourcemanager/compute/armcompute_444bc7d3bc" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/autorest.md index 9d88c8a6d..3e856c7d2 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/autorest.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/autorest.md @@ -5,9 +5,9 @@ ``` yaml azure-arm: true require: -- https://github.com/Azure/azure-rest-api-specs/blob/60679ee3db06e93eb73faa0587fed93ed843d6dc/specification/compute/resource-manager/readme.md -- https://github.com/Azure/azure-rest-api-specs/blob/60679ee3db06e93eb73faa0587fed93ed843d6dc/specification/compute/resource-manager/readme.go.md +- https://github.com/Azure/azure-rest-api-specs/blob/41e4538ed7bb3ceac3c1322c9455a0812ed110ac/specification/compute/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/41e4538ed7bb3ceac3c1322c9455a0812ed110ac/specification/compute/resource-manager/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 5.4.0 -tag: package-2023-09-01 +module-version: 5.5.0 +tag: package-2023-10-02 ``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/constants.go index d635d4f51..e4858a588 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/constants.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/constants.go @@ -10,7 +10,7 @@ package armcompute const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute" - moduleVersion = "v5.4.0" + moduleVersion = "v5.5.0" ) type AccessLevel string @@ -543,6 +543,9 @@ const ( // DiskSecurityTypesConfidentialVMDiskEncryptedWithPlatformKey - Indicates Confidential VM disk with both OS disk and VM guest // state encrypted with a platform managed key DiskSecurityTypesConfidentialVMDiskEncryptedWithPlatformKey DiskSecurityTypes = "ConfidentialVM_DiskEncryptedWithPlatformKey" + // DiskSecurityTypesConfidentialVMNonPersistedTPM - Indicates Confidential VM disk with a ephemeral vTPM. vTPM state is not + // persisted across VM reboots. + DiskSecurityTypesConfidentialVMNonPersistedTPM DiskSecurityTypes = "ConfidentialVM_NonPersistedTPM" // DiskSecurityTypesConfidentialVMVmguestStateOnlyEncryptedWithPlatformKey - Indicates Confidential VM disk with only VM guest // state encrypted DiskSecurityTypesConfidentialVMVmguestStateOnlyEncryptedWithPlatformKey DiskSecurityTypes = "ConfidentialVM_VMGuestStateOnlyEncryptedWithPlatformKey" @@ -556,6 +559,7 @@ func PossibleDiskSecurityTypesValues() []DiskSecurityTypes { return []DiskSecurityTypes{ DiskSecurityTypesConfidentialVMDiskEncryptedWithCustomerKey, DiskSecurityTypesConfidentialVMDiskEncryptedWithPlatformKey, + DiskSecurityTypesConfidentialVMNonPersistedTPM, DiskSecurityTypesConfidentialVMVmguestStateOnlyEncryptedWithPlatformKey, DiskSecurityTypesTrustedLaunch, } @@ -1500,6 +1504,23 @@ func PossibleProtocolTypesValues() []ProtocolTypes { } } +// ProvisionedBandwidthCopyOption - If this field is set on a snapshot and createOption is CopyStart, the snapshot will be +// copied at a quicker speed. +type ProvisionedBandwidthCopyOption string + +const ( + ProvisionedBandwidthCopyOptionEnhanced ProvisionedBandwidthCopyOption = "Enhanced" + ProvisionedBandwidthCopyOptionNone ProvisionedBandwidthCopyOption = "None" +) + +// PossibleProvisionedBandwidthCopyOptionValues returns the possible values for the ProvisionedBandwidthCopyOption const type. +func PossibleProvisionedBandwidthCopyOptionValues() []ProvisionedBandwidthCopyOption { + return []ProvisionedBandwidthCopyOption{ + ProvisionedBandwidthCopyOptionEnhanced, + ProvisionedBandwidthCopyOptionNone, + } +} + // ProximityPlacementGroupType - Specifies the type of the proximity placement group. Possible values are: Standard : Co-locate // resources within an Azure region or Availability Zone. Ultra : For future use. type ProximityPlacementGroupType string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskaccesses_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskaccesses_client.go index b189a0340..0bea05f3e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskaccesses_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskaccesses_client.go @@ -47,7 +47,7 @@ func NewDiskAccessesClient(subscriptionID string, credential azcore.TokenCredent // BeginCreateOrUpdate - Creates or updates a disk access resource // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -75,7 +75,7 @@ func (client *DiskAccessesClient) BeginCreateOrUpdate(ctx context.Context, resou // CreateOrUpdate - Creates or updates a disk access resource // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskAccessesClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccess, options *DiskAccessesClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "DiskAccessesClient.BeginCreateOrUpdate" @@ -117,7 +117,7 @@ func (client *DiskAccessesClient) createOrUpdateCreateRequest(ctx context.Contex return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, diskAccess); err != nil { @@ -129,7 +129,7 @@ func (client *DiskAccessesClient) createOrUpdateCreateRequest(ctx context.Contex // BeginDelete - Deletes a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -156,7 +156,7 @@ func (client *DiskAccessesClient) BeginDelete(ctx context.Context, resourceGroup // Delete - Deletes a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskAccessesClient) deleteOperation(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "DiskAccessesClient.BeginDelete" @@ -198,7 +198,7 @@ func (client *DiskAccessesClient) deleteCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -207,7 +207,7 @@ func (client *DiskAccessesClient) deleteCreateRequest(ctx context.Context, resou // BeginDeleteAPrivateEndpointConnection - Deletes a private endpoint connection under a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -235,7 +235,7 @@ func (client *DiskAccessesClient) BeginDeleteAPrivateEndpointConnection(ctx cont // DeleteAPrivateEndpointConnection - Deletes a private endpoint connection under a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskAccessesClient) deleteAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions) (*http.Response, error) { var err error const operationName = "DiskAccessesClient.BeginDeleteAPrivateEndpointConnection" @@ -281,7 +281,7 @@ func (client *DiskAccessesClient) deleteAPrivateEndpointConnectionCreateRequest( return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -290,7 +290,7 @@ func (client *DiskAccessesClient) deleteAPrivateEndpointConnectionCreateRequest( // Get - Gets information about a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -338,7 +338,7 @@ func (client *DiskAccessesClient) getCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -356,7 +356,7 @@ func (client *DiskAccessesClient) getHandleResponse(resp *http.Response) (DiskAc // GetAPrivateEndpointConnection - Gets information about a private endpoint connection under a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -410,7 +410,7 @@ func (client *DiskAccessesClient) getAPrivateEndpointConnectionCreateRequest(ctx return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -428,7 +428,7 @@ func (client *DiskAccessesClient) getAPrivateEndpointConnectionHandleResponse(re // GetPrivateLinkResources - Gets the private link resources possible under disk access resource // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -477,7 +477,7 @@ func (client *DiskAccessesClient) getPrivateLinkResourcesCreateRequest(ctx conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -494,7 +494,7 @@ func (client *DiskAccessesClient) getPrivateLinkResourcesHandleResponse(resp *ht // NewListPager - Lists all the disk access resources under a subscription. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - options - DiskAccessesClientListOptions contains the optional parameters for the DiskAccessesClient.NewListPager method. func (client *DiskAccessesClient) NewListPager(options *DiskAccessesClientListOptions) *runtime.Pager[DiskAccessesClientListResponse] { return runtime.NewPager(runtime.PagingHandler[DiskAccessesClientListResponse]{ @@ -531,7 +531,7 @@ func (client *DiskAccessesClient) listCreateRequest(ctx context.Context, options return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -548,7 +548,7 @@ func (client *DiskAccessesClient) listHandleResponse(resp *http.Response) (DiskA // NewListByResourceGroupPager - Lists all the disk access resources under a resource group. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - options - DiskAccessesClientListByResourceGroupOptions contains the optional parameters for the DiskAccessesClient.NewListByResourceGroupPager // method. @@ -591,7 +591,7 @@ func (client *DiskAccessesClient) listByResourceGroupCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -608,7 +608,7 @@ func (client *DiskAccessesClient) listByResourceGroupHandleResponse(resp *http.R // NewListPrivateEndpointConnectionsPager - List information about private endpoint connections under a disk access resource // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -658,7 +658,7 @@ func (client *DiskAccessesClient) listPrivateEndpointConnectionsCreateRequest(ct return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -676,7 +676,7 @@ func (client *DiskAccessesClient) listPrivateEndpointConnectionsHandleResponse(r // BeginUpdate - Updates (patches) a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -704,7 +704,7 @@ func (client *DiskAccessesClient) BeginUpdate(ctx context.Context, resourceGroup // Update - Updates (patches) a disk access resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskAccessesClient) update(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccessUpdate, options *DiskAccessesClientBeginUpdateOptions) (*http.Response, error) { var err error const operationName = "DiskAccessesClient.BeginUpdate" @@ -746,7 +746,7 @@ func (client *DiskAccessesClient) updateCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, diskAccess); err != nil { @@ -759,7 +759,7 @@ func (client *DiskAccessesClient) updateCreateRequest(ctx context.Context, resou // can't be used to create a new private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption // set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The @@ -790,7 +790,7 @@ func (client *DiskAccessesClient) BeginUpdateAPrivateEndpointConnection(ctx cont // be used to create a new private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskAccessesClient) updateAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions) (*http.Response, error) { var err error const operationName = "DiskAccessesClient.BeginUpdateAPrivateEndpointConnection" @@ -836,7 +836,7 @@ func (client *DiskAccessesClient) updateAPrivateEndpointConnectionCreateRequest( return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, privateEndpointConnection); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskencryptionsets_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskencryptionsets_client.go index 9306f9c0d..59d34d1e2 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskencryptionsets_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskencryptionsets_client.go @@ -47,7 +47,7 @@ func NewDiskEncryptionSetsClient(subscriptionID string, credential azcore.TokenC // BeginCreateOrUpdate - Creates or updates a disk encryption set // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the // disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum @@ -75,7 +75,7 @@ func (client *DiskEncryptionSetsClient) BeginCreateOrUpdate(ctx context.Context, // CreateOrUpdate - Creates or updates a disk encryption set // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskEncryptionSetsClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSet, options *DiskEncryptionSetsClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "DiskEncryptionSetsClient.BeginCreateOrUpdate" @@ -117,7 +117,7 @@ func (client *DiskEncryptionSetsClient) createOrUpdateCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, diskEncryptionSet); err != nil { @@ -129,7 +129,7 @@ func (client *DiskEncryptionSetsClient) createOrUpdateCreateRequest(ctx context. // BeginDelete - Deletes a disk encryption set. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the // disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum @@ -156,7 +156,7 @@ func (client *DiskEncryptionSetsClient) BeginDelete(ctx context.Context, resourc // Delete - Deletes a disk encryption set. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskEncryptionSetsClient) deleteOperation(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "DiskEncryptionSetsClient.BeginDelete" @@ -198,7 +198,7 @@ func (client *DiskEncryptionSetsClient) deleteCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -207,7 +207,7 @@ func (client *DiskEncryptionSetsClient) deleteCreateRequest(ctx context.Context, // Get - Gets information about a disk encryption set. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the // disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum @@ -255,7 +255,7 @@ func (client *DiskEncryptionSetsClient) getCreateRequest(ctx context.Context, re return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -272,7 +272,7 @@ func (client *DiskEncryptionSetsClient) getHandleResponse(resp *http.Response) ( // NewListPager - Lists all the disk encryption sets under a subscription. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - options - DiskEncryptionSetsClientListOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListPager // method. func (client *DiskEncryptionSetsClient) NewListPager(options *DiskEncryptionSetsClientListOptions) *runtime.Pager[DiskEncryptionSetsClientListResponse] { @@ -310,7 +310,7 @@ func (client *DiskEncryptionSetsClient) listCreateRequest(ctx context.Context, o return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -327,7 +327,7 @@ func (client *DiskEncryptionSetsClient) listHandleResponse(resp *http.Response) // NewListAssociatedResourcesPager - Lists all resources that are encrypted with this disk encryption set. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the // disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum @@ -377,7 +377,7 @@ func (client *DiskEncryptionSetsClient) listAssociatedResourcesCreateRequest(ctx return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -394,7 +394,7 @@ func (client *DiskEncryptionSetsClient) listAssociatedResourcesHandleResponse(re // NewListByResourceGroupPager - Lists all the disk encryption sets under a resource group. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - options - DiskEncryptionSetsClientListByResourceGroupOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListByResourceGroupPager // method. @@ -437,7 +437,7 @@ func (client *DiskEncryptionSetsClient) listByResourceGroupCreateRequest(ctx con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -455,7 +455,7 @@ func (client *DiskEncryptionSetsClient) listByResourceGroupHandleResponse(resp * // BeginUpdate - Updates (patches) a disk encryption set. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the // disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum @@ -483,7 +483,7 @@ func (client *DiskEncryptionSetsClient) BeginUpdate(ctx context.Context, resourc // Update - Updates (patches) a disk encryption set. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskEncryptionSetsClient) update(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsClientBeginUpdateOptions) (*http.Response, error) { var err error const operationName = "DiskEncryptionSetsClient.BeginUpdate" @@ -525,7 +525,7 @@ func (client *DiskEncryptionSetsClient) updateCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, diskEncryptionSet); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskrestorepoint_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskrestorepoint_client.go index 54b576957..43307ca04 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskrestorepoint_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskrestorepoint_client.go @@ -47,7 +47,7 @@ func NewDiskRestorePointClient(subscriptionID string, credential azcore.TokenCre // Get - Get disk restorePoint resource // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. // - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. @@ -103,7 +103,7 @@ func (client *DiskRestorePointClient) getCreateRequest(ctx context.Context, reso return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -121,7 +121,7 @@ func (client *DiskRestorePointClient) getHandleResponse(resp *http.Response) (Di // BeginGrantAccess - Grants access to a diskRestorePoint. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. // - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. @@ -150,7 +150,7 @@ func (client *DiskRestorePointClient) BeginGrantAccess(ctx context.Context, reso // GrantAccess - Grants access to a diskRestorePoint. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskRestorePointClient) grantAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, grantAccessData GrantAccessData, options *DiskRestorePointClientBeginGrantAccessOptions) (*http.Response, error) { var err error const operationName = "DiskRestorePointClient.BeginGrantAccess" @@ -200,7 +200,7 @@ func (client *DiskRestorePointClient) grantAccessCreateRequest(ctx context.Conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil { @@ -211,7 +211,7 @@ func (client *DiskRestorePointClient) grantAccessCreateRequest(ctx context.Conte // NewListByRestorePointPager - Lists diskRestorePoints under a vmRestorePoint. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. // - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. @@ -264,7 +264,7 @@ func (client *DiskRestorePointClient) listByRestorePointCreateRequest(ctx contex return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -282,7 +282,7 @@ func (client *DiskRestorePointClient) listByRestorePointHandleResponse(resp *htt // BeginRevokeAccess - Revokes access to a diskRestorePoint. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. // - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. @@ -310,7 +310,7 @@ func (client *DiskRestorePointClient) BeginRevokeAccess(ctx context.Context, res // RevokeAccess - Revokes access to a diskRestorePoint. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DiskRestorePointClient) revokeAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientBeginRevokeAccessOptions) (*http.Response, error) { var err error const operationName = "DiskRestorePointClient.BeginRevokeAccess" @@ -360,7 +360,7 @@ func (client *DiskRestorePointClient) revokeAccessCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/disks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/disks_client.go index 854a8ffd6..a0ffa752b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/disks_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/disks_client.go @@ -47,7 +47,7 @@ func NewDisksClient(subscriptionID string, credential azcore.TokenCredential, op // BeginCreateOrUpdate - Creates or updates a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported // characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 @@ -75,7 +75,7 @@ func (client *DisksClient) BeginCreateOrUpdate(ctx context.Context, resourceGrou // CreateOrUpdate - Creates or updates a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DisksClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskName string, disk Disk, options *DisksClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "DisksClient.BeginCreateOrUpdate" @@ -117,7 +117,7 @@ func (client *DisksClient) createOrUpdateCreateRequest(ctx context.Context, reso return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, disk); err != nil { @@ -129,7 +129,7 @@ func (client *DisksClient) createOrUpdateCreateRequest(ctx context.Context, reso // BeginDelete - Deletes a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported // characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 @@ -155,7 +155,7 @@ func (client *DisksClient) BeginDelete(ctx context.Context, resourceGroupName st // Delete - Deletes a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DisksClient) deleteOperation(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "DisksClient.BeginDelete" @@ -197,7 +197,7 @@ func (client *DisksClient) deleteCreateRequest(ctx context.Context, resourceGrou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() return req, nil } @@ -205,7 +205,7 @@ func (client *DisksClient) deleteCreateRequest(ctx context.Context, resourceGrou // Get - Gets information about a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported // characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 @@ -253,7 +253,7 @@ func (client *DisksClient) getCreateRequest(ctx context.Context, resourceGroupNa return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -271,7 +271,7 @@ func (client *DisksClient) getHandleResponse(resp *http.Response) (DisksClientGe // BeginGrantAccess - Grants access to a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported // characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 @@ -299,7 +299,7 @@ func (client *DisksClient) BeginGrantAccess(ctx context.Context, resourceGroupNa // GrantAccess - Grants access to a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DisksClient) grantAccess(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData, options *DisksClientBeginGrantAccessOptions) (*http.Response, error) { var err error const operationName = "DisksClient.BeginGrantAccess" @@ -341,7 +341,7 @@ func (client *DisksClient) grantAccessCreateRequest(ctx context.Context, resourc return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil { @@ -352,7 +352,7 @@ func (client *DisksClient) grantAccessCreateRequest(ctx context.Context, resourc // NewListPager - Lists all the disks under a subscription. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - options - DisksClientListOptions contains the optional parameters for the DisksClient.NewListPager method. func (client *DisksClient) NewListPager(options *DisksClientListOptions) *runtime.Pager[DisksClientListResponse] { return runtime.NewPager(runtime.PagingHandler[DisksClientListResponse]{ @@ -389,7 +389,7 @@ func (client *DisksClient) listCreateRequest(ctx context.Context, options *Disks return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -406,7 +406,7 @@ func (client *DisksClient) listHandleResponse(resp *http.Response) (DisksClientL // NewListByResourceGroupPager - Lists all the disks under a resource group. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - options - DisksClientListByResourceGroupOptions contains the optional parameters for the DisksClient.NewListByResourceGroupPager // method. @@ -449,7 +449,7 @@ func (client *DisksClient) listByResourceGroupCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -467,7 +467,7 @@ func (client *DisksClient) listByResourceGroupHandleResponse(resp *http.Response // BeginRevokeAccess - Revokes access to a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported // characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 @@ -494,7 +494,7 @@ func (client *DisksClient) BeginRevokeAccess(ctx context.Context, resourceGroupN // RevokeAccess - Revokes access to a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DisksClient) revokeAccess(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginRevokeAccessOptions) (*http.Response, error) { var err error const operationName = "DisksClient.BeginRevokeAccess" @@ -536,7 +536,7 @@ func (client *DisksClient) revokeAccessCreateRequest(ctx context.Context, resour return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() return req, nil } @@ -544,7 +544,7 @@ func (client *DisksClient) revokeAccessCreateRequest(ctx context.Context, resour // BeginUpdate - Updates (patches) a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported // characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 @@ -571,7 +571,7 @@ func (client *DisksClient) BeginUpdate(ctx context.Context, resourceGroupName st // Update - Updates (patches) a disk. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *DisksClient) update(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate, options *DisksClientBeginUpdateOptions) (*http.Response, error) { var err error const operationName = "DisksClient.BeginUpdate" @@ -613,7 +613,7 @@ func (client *DisksClient) updateCreateRequest(ctx context.Context, resourceGrou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, disk); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models.go index 5b5a3197b..ffba7145d 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models.go @@ -1037,6 +1037,9 @@ type CreationData struct { // disabled after enabled. PerformancePlus *bool + // If this field is set on a snapshot and createOption is CopyStart, the snapshot will be copied at a quicker speed. + ProvisionedBandwidthCopySpeed *ProvisionedBandwidthCopyOption + // If createOption is ImportSecure, this is the URI of a blob to be imported into VM guest state. SecurityDataURI *string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models_serde.go index 3c63478d0..077f40dd3 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models_serde.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models_serde.go @@ -2404,6 +2404,7 @@ func (c CreationData) MarshalJSON() ([]byte, error) { populate(objectMap, "imageReference", c.ImageReference) populate(objectMap, "logicalSectorSize", c.LogicalSectorSize) populate(objectMap, "performancePlus", c.PerformancePlus) + populate(objectMap, "provisionedBandwidthCopySpeed", c.ProvisionedBandwidthCopySpeed) populate(objectMap, "securityDataUri", c.SecurityDataURI) populate(objectMap, "sourceResourceId", c.SourceResourceID) populate(objectMap, "sourceUri", c.SourceURI) @@ -2440,6 +2441,9 @@ func (c *CreationData) UnmarshalJSON(data []byte) error { case "performancePlus": err = unpopulate(val, "PerformancePlus", &c.PerformancePlus) delete(rawMsg, key) + case "provisionedBandwidthCopySpeed": + err = unpopulate(val, "ProvisionedBandwidthCopySpeed", &c.ProvisionedBandwidthCopySpeed) + delete(rawMsg, key) case "securityDataUri": err = unpopulate(val, "SecurityDataURI", &c.SecurityDataURI) delete(rawMsg, key) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/snapshots_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/snapshots_client.go index a0d263613..8c73f7709 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/snapshots_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/snapshots_client.go @@ -47,7 +47,7 @@ func NewSnapshotsClient(subscriptionID string, credential azcore.TokenCredential // BeginCreateOrUpdate - Creates or updates a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. // Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 @@ -75,7 +75,7 @@ func (client *SnapshotsClient) BeginCreateOrUpdate(ctx context.Context, resource // CreateOrUpdate - Creates or updates a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *SnapshotsClient) createOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot, options *SnapshotsClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "SnapshotsClient.BeginCreateOrUpdate" @@ -117,7 +117,7 @@ func (client *SnapshotsClient) createOrUpdateCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, snapshot); err != nil { @@ -129,7 +129,7 @@ func (client *SnapshotsClient) createOrUpdateCreateRequest(ctx context.Context, // BeginDelete - Deletes a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. // Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 @@ -155,7 +155,7 @@ func (client *SnapshotsClient) BeginDelete(ctx context.Context, resourceGroupNam // Delete - Deletes a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *SnapshotsClient) deleteOperation(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "SnapshotsClient.BeginDelete" @@ -197,7 +197,7 @@ func (client *SnapshotsClient) deleteCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() return req, nil } @@ -205,7 +205,7 @@ func (client *SnapshotsClient) deleteCreateRequest(ctx context.Context, resource // Get - Gets information about a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. // Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 @@ -253,7 +253,7 @@ func (client *SnapshotsClient) getCreateRequest(ctx context.Context, resourceGro return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -271,7 +271,7 @@ func (client *SnapshotsClient) getHandleResponse(resp *http.Response) (Snapshots // BeginGrantAccess - Grants access to a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. // Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 @@ -300,7 +300,7 @@ func (client *SnapshotsClient) BeginGrantAccess(ctx context.Context, resourceGro // GrantAccess - Grants access to a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *SnapshotsClient) grantAccess(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, options *SnapshotsClientBeginGrantAccessOptions) (*http.Response, error) { var err error const operationName = "SnapshotsClient.BeginGrantAccess" @@ -342,7 +342,7 @@ func (client *SnapshotsClient) grantAccessCreateRequest(ctx context.Context, res return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil { @@ -353,7 +353,7 @@ func (client *SnapshotsClient) grantAccessCreateRequest(ctx context.Context, res // NewListPager - Lists snapshots under a subscription. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - options - SnapshotsClientListOptions contains the optional parameters for the SnapshotsClient.NewListPager method. func (client *SnapshotsClient) NewListPager(options *SnapshotsClientListOptions) *runtime.Pager[SnapshotsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[SnapshotsClientListResponse]{ @@ -390,7 +390,7 @@ func (client *SnapshotsClient) listCreateRequest(ctx context.Context, options *S return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -407,7 +407,7 @@ func (client *SnapshotsClient) listHandleResponse(resp *http.Response) (Snapshot // NewListByResourceGroupPager - Lists snapshots under a resource group. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - options - SnapshotsClientListByResourceGroupOptions contains the optional parameters for the SnapshotsClient.NewListByResourceGroupPager // method. @@ -450,7 +450,7 @@ func (client *SnapshotsClient) listByResourceGroupCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -468,7 +468,7 @@ func (client *SnapshotsClient) listByResourceGroupHandleResponse(resp *http.Resp // BeginRevokeAccess - Revokes access to a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. // Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 @@ -496,7 +496,7 @@ func (client *SnapshotsClient) BeginRevokeAccess(ctx context.Context, resourceGr // RevokeAccess - Revokes access to a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *SnapshotsClient) revokeAccess(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginRevokeAccessOptions) (*http.Response, error) { var err error const operationName = "SnapshotsClient.BeginRevokeAccess" @@ -538,7 +538,7 @@ func (client *SnapshotsClient) revokeAccessCreateRequest(ctx context.Context, re return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() return req, nil } @@ -546,7 +546,7 @@ func (client *SnapshotsClient) revokeAccessCreateRequest(ctx context.Context, re // BeginUpdate - Updates (patches) a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 // - resourceGroupName - The name of the resource group. // - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. // Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 @@ -573,7 +573,7 @@ func (client *SnapshotsClient) BeginUpdate(ctx context.Context, resourceGroupNam // Update - Updates (patches) a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-04-02 +// Generated from API version 2023-10-02 func (client *SnapshotsClient) update(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, options *SnapshotsClientBeginUpdateOptions) (*http.Response, error) { var err error const operationName = "SnapshotsClient.BeginUpdate" @@ -615,7 +615,7 @@ func (client *SnapshotsClient) updateCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-04-02") + reqQP.Set("api-version", "2023-10-02") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, snapshot); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md index 837482870..acc2e104c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md @@ -1,5 +1,110 @@ # Release History +## 4.7.0 (2024-01-26) +### Features Added + +- New field `NodeSoakDurationInMinutes` in struct `AgentPoolUpgradeSettings` + + +## 4.7.0-beta.1 (2023-12-22) +### Features Added + +- New value `AgentPoolTypeVirtualMachines` added to enum type `AgentPoolType` +- New value `NetworkPolicyNone` added to enum type `NetworkPolicy` +- New value `NodeOSUpgradeChannelSecurityPatch` added to enum type `NodeOSUpgradeChannel` +- New value `OSSKUMariner`, `OSSKUWindowsAnnual` added to enum type `OSSKU` +- New value `PublicNetworkAccessSecuredByPerimeter` added to enum type `PublicNetworkAccess` +- New value `SnapshotTypeManagedCluster` added to enum type `SnapshotType` +- New value `WorkloadRuntimeKataMshvVMIsolation` added to enum type `WorkloadRuntime` +- New enum type `AddonAutoscaling` with values `AddonAutoscalingDisabled`, `AddonAutoscalingEnabled` +- New enum type `AgentPoolSSHAccess` with values `AgentPoolSSHAccessDisabled`, `AgentPoolSSHAccessLocalUser` +- New enum type `GuardrailsSupport` with values `GuardrailsSupportPreview`, `GuardrailsSupportStable` +- New enum type `IpvsScheduler` with values `IpvsSchedulerLeastConnection`, `IpvsSchedulerRoundRobin` +- New enum type `Level` with values `LevelEnforcement`, `LevelOff`, `LevelWarning` +- New enum type `Mode` with values `ModeIPTABLES`, `ModeIPVS` +- New enum type `NodeProvisioningMode` with values `NodeProvisioningModeAuto`, `NodeProvisioningModeManual` +- New enum type `RestrictionLevel` with values `RestrictionLevelReadOnly`, `RestrictionLevelUnrestricted` +- New function `*AgentPoolsClient.BeginDeleteMachines(context.Context, string, string, string, AgentPoolDeleteMachinesParameter, *AgentPoolsClientBeginDeleteMachinesOptions) (*runtime.Poller[AgentPoolsClientDeleteMachinesResponse], error)` +- New function `*ClientFactory.NewMachinesClient() *MachinesClient` +- New function `*ClientFactory.NewManagedClusterSnapshotsClient() *ManagedClusterSnapshotsClient` +- New function `*ClientFactory.NewOperationStatusResultClient() *OperationStatusResultClient` +- New function `NewMachinesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*MachinesClient, error)` +- New function `*MachinesClient.Get(context.Context, string, string, string, string, *MachinesClientGetOptions) (MachinesClientGetResponse, error)` +- New function `*MachinesClient.NewListPager(string, string, string, *MachinesClientListOptions) *runtime.Pager[MachinesClientListResponse]` +- New function `NewManagedClusterSnapshotsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagedClusterSnapshotsClient, error)` +- New function `*ManagedClusterSnapshotsClient.CreateOrUpdate(context.Context, string, string, ManagedClusterSnapshot, *ManagedClusterSnapshotsClientCreateOrUpdateOptions) (ManagedClusterSnapshotsClientCreateOrUpdateResponse, error)` +- New function `*ManagedClusterSnapshotsClient.Delete(context.Context, string, string, *ManagedClusterSnapshotsClientDeleteOptions) (ManagedClusterSnapshotsClientDeleteResponse, error)` +- New function `*ManagedClusterSnapshotsClient.Get(context.Context, string, string, *ManagedClusterSnapshotsClientGetOptions) (ManagedClusterSnapshotsClientGetResponse, error)` +- New function `*ManagedClusterSnapshotsClient.NewListByResourceGroupPager(string, *ManagedClusterSnapshotsClientListByResourceGroupOptions) *runtime.Pager[ManagedClusterSnapshotsClientListByResourceGroupResponse]` +- New function `*ManagedClusterSnapshotsClient.NewListPager(*ManagedClusterSnapshotsClientListOptions) *runtime.Pager[ManagedClusterSnapshotsClientListResponse]` +- New function `*ManagedClusterSnapshotsClient.UpdateTags(context.Context, string, string, TagsObject, *ManagedClusterSnapshotsClientUpdateTagsOptions) (ManagedClusterSnapshotsClientUpdateTagsResponse, error)` +- New function `*ManagedClustersClient.GetGuardrailsVersions(context.Context, string, string, *ManagedClustersClientGetGuardrailsVersionsOptions) (ManagedClustersClientGetGuardrailsVersionsResponse, error)` +- New function `*ManagedClustersClient.NewListGuardrailsVersionsPager(string, *ManagedClustersClientListGuardrailsVersionsOptions) *runtime.Pager[ManagedClustersClientListGuardrailsVersionsResponse]` +- New function `NewOperationStatusResultClient(string, azcore.TokenCredential, *arm.ClientOptions) (*OperationStatusResultClient, error)` +- New function `*OperationStatusResultClient.Get(context.Context, string, string, string, *OperationStatusResultClientGetOptions) (OperationStatusResultClientGetResponse, error)` +- New function `*OperationStatusResultClient.GetByAgentPool(context.Context, string, string, string, string, *OperationStatusResultClientGetByAgentPoolOptions) (OperationStatusResultClientGetByAgentPoolResponse, error)` +- New function `*OperationStatusResultClient.NewListPager(string, string, *OperationStatusResultClientListOptions) *runtime.Pager[OperationStatusResultClientListResponse]` +- New struct `AgentPoolArtifactStreamingProfile` +- New struct `AgentPoolDeleteMachinesParameter` +- New struct `AgentPoolGPUProfile` +- New struct `AgentPoolSecurityProfile` +- New struct `AgentPoolWindowsProfile` +- New struct `ErrorAdditionalInfo` +- New struct `ErrorDetail` +- New struct `GuardrailsAvailableVersion` +- New struct `GuardrailsAvailableVersionsList` +- New struct `GuardrailsAvailableVersionsProperties` +- New struct `GuardrailsProfile` +- New struct `Machine` +- New struct `MachineIPAddress` +- New struct `MachineListResult` +- New struct `MachineNetworkProperties` +- New struct `MachineProperties` +- New struct `ManagedClusterAIToolchainOperatorProfile` +- New struct `ManagedClusterAzureMonitorProfileAppMonitoring` +- New struct `ManagedClusterAzureMonitorProfileAppMonitoringOpenTelemetryMetrics` +- New struct `ManagedClusterAzureMonitorProfileContainerInsights` +- New struct `ManagedClusterAzureMonitorProfileLogs` +- New struct `ManagedClusterAzureMonitorProfileWindowsHostLogs` +- New struct `ManagedClusterCostAnalysis` +- New struct `ManagedClusterIngressProfile` +- New struct `ManagedClusterIngressProfileWebAppRouting` +- New struct `ManagedClusterMetricsProfile` +- New struct `ManagedClusterNodeProvisioningProfile` +- New struct `ManagedClusterNodeResourceGroupProfile` +- New struct `ManagedClusterPropertiesForSnapshot` +- New struct `ManagedClusterSecurityProfileImageIntegrity` +- New struct `ManagedClusterSecurityProfileNodeRestriction` +- New struct `ManagedClusterSnapshot` +- New struct `ManagedClusterSnapshotListResult` +- New struct `ManagedClusterSnapshotProperties` +- New struct `ManualScaleProfile` +- New struct `NetworkMonitoring` +- New struct `NetworkProfileForSnapshot` +- New struct `NetworkProfileKubeProxyConfig` +- New struct `NetworkProfileKubeProxyConfigIpvsConfig` +- New struct `OperationStatusResult` +- New struct `OperationStatusResultList` +- New struct `ScaleProfile` +- New struct `VirtualMachineNodes` +- New struct `VirtualMachinesProfile` +- New field `NodeSoakDurationInMinutes` in struct `AgentPoolUpgradeSettings` +- New field `IgnorePodDisruptionBudget` in struct `AgentPoolsClientBeginDeleteOptions` +- New field `EnableVnetIntegration`, `SubnetID` in struct `ManagedClusterAPIServerAccessProfile` +- New field `ArtifactStreamingProfile`, `EnableCustomCATrust`, `GpuProfile`, `MessageOfTheDay`, `NodeInitializationTaints`, `SecurityProfile`, `VirtualMachineNodesStatus`, `VirtualMachinesProfile`, `WindowsProfile` in struct `ManagedClusterAgentPoolProfile` +- New field `ArtifactStreamingProfile`, `EnableCustomCATrust`, `GpuProfile`, `MessageOfTheDay`, `NodeInitializationTaints`, `SecurityProfile`, `VirtualMachineNodesStatus`, `VirtualMachinesProfile`, `WindowsProfile` in struct `ManagedClusterAgentPoolProfileProperties` +- New field `Logs` in struct `ManagedClusterAzureMonitorProfile` +- New field `AppMonitoringOpenTelemetryMetrics` in struct `ManagedClusterAzureMonitorProfileMetrics` +- New field `EffectiveNoProxy` in struct `ManagedClusterHTTPProxyConfig` +- New field `AiToolchainOperatorProfile`, `CreationData`, `EnableNamespaceResources`, `GuardrailsProfile`, `IngressProfile`, `MetricsProfile`, `NodeProvisioningProfile`, `NodeResourceGroupProfile` in struct `ManagedClusterProperties` +- New field `DaemonsetEvictionForEmptyNodes`, `DaemonsetEvictionForOccupiedNodes`, `IgnoreDaemonsetsUtilization` in struct `ManagedClusterPropertiesAutoScalerProfile` +- New field `CustomCATrustCertificates`, `ImageIntegrity`, `NodeRestriction` in struct `ManagedClusterSecurityProfile` +- New field `Version` in struct `ManagedClusterStorageProfileDiskCSIDriver` +- New field `AddonAutoscaling` in struct `ManagedClusterWorkloadAutoScalerProfileVerticalPodAutoscaler` +- New field `IgnorePodDisruptionBudget` in struct `ManagedClustersClientBeginDeleteOptions` +- New field `KubeProxyConfig`, `Monitoring` in struct `NetworkProfile` + + ## 4.6.0 (2023-11-24) ### Features Added diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/README.md index 7cdd0c92e..44d307082 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/README.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/README.md @@ -1,6 +1,6 @@ # Azure Container Service Module for Go -[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v2)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v2) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4) The `armcontainerservice` module provides operations for working with Azure Container Service. @@ -20,7 +20,7 @@ This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for ve Install the Azure Container Service module: ```sh -go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v2 +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 ``` ## Authorization @@ -57,7 +57,7 @@ clientFactory, err := armcontainerservice.NewClientFactory(, cr A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. ```go -client := clientFactory.NewSnapshotsClient() +client := clientFactory.NewAgentPoolsClient() ``` ## Fakes diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go index bf2e9c712..ba8dcb84c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go @@ -48,7 +48,7 @@ func NewAgentPoolsClient(subscriptionID string, credential azcore.TokenCredentia // before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -77,7 +77,7 @@ func (client *AgentPoolsClient) BeginAbortLatestOperation(ctx context.Context, r // before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *AgentPoolsClient) abortLatestOperation(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, options *AgentPoolsClientBeginAbortLatestOperationOptions) (*http.Response, error) { var err error const operationName = "AgentPoolsClient.BeginAbortLatestOperation" @@ -123,7 +123,7 @@ func (client *AgentPoolsClient) abortLatestOperationCreateRequest(ctx context.Co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -132,7 +132,7 @@ func (client *AgentPoolsClient) abortLatestOperationCreateRequest(ctx context.Co // BeginCreateOrUpdate - Creates or updates an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -159,7 +159,7 @@ func (client *AgentPoolsClient) BeginCreateOrUpdate(ctx context.Context, resourc // CreateOrUpdate - Creates or updates an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *AgentPoolsClient) createOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, parameters AgentPool, options *AgentPoolsClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "AgentPoolsClient.BeginCreateOrUpdate" @@ -205,7 +205,7 @@ func (client *AgentPoolsClient) createOrUpdateCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -217,7 +217,7 @@ func (client *AgentPoolsClient) createOrUpdateCreateRequest(ctx context.Context, // BeginDelete - Deletes an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -242,7 +242,7 @@ func (client *AgentPoolsClient) BeginDelete(ctx context.Context, resourceGroupNa // Delete - Deletes an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *AgentPoolsClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "AgentPoolsClient.BeginDelete" @@ -288,7 +288,7 @@ func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourc return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -297,7 +297,7 @@ func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourc // Get - Gets the specified managed cluster agent pool. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -348,7 +348,7 @@ func (client *AgentPoolsClient) getCreateRequest(ctx context.Context, resourceGr return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -367,7 +367,7 @@ func (client *AgentPoolsClient) getHandleResponse(resp *http.Response) (AgentPoo // for more details about the version lifecycle. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - AgentPoolsClientGetAvailableAgentPoolVersionsOptions contains the optional parameters for the AgentPoolsClient.GetAvailableAgentPoolVersions @@ -414,7 +414,7 @@ func (client *AgentPoolsClient) getAvailableAgentPoolVersionsCreateRequest(ctx c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -432,7 +432,7 @@ func (client *AgentPoolsClient) getAvailableAgentPoolVersionsHandleResponse(resp // GetUpgradeProfile - Gets the upgrade profile for an agent pool. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -484,7 +484,7 @@ func (client *AgentPoolsClient) getUpgradeProfileCreateRequest(ctx context.Conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -501,7 +501,7 @@ func (client *AgentPoolsClient) getUpgradeProfileHandleResponse(resp *http.Respo // NewListPager - Gets a list of agent pools in the specified managed cluster. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - AgentPoolsClientListOptions contains the optional parameters for the AgentPoolsClient.NewListPager method. @@ -548,7 +548,7 @@ func (client *AgentPoolsClient) listCreateRequest(ctx context.Context, resourceG return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -568,7 +568,7 @@ func (client *AgentPoolsClient) listHandleResponse(resp *http.Response) (AgentPo // versions, see: https://docs.microsoft.com/azure/aks/node-image-upgrade // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -597,7 +597,7 @@ func (client *AgentPoolsClient) BeginUpgradeNodeImageVersion(ctx context.Context // versions, see: https://docs.microsoft.com/azure/aks/node-image-upgrade // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *AgentPoolsClient) upgradeNodeImageVersion(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, options *AgentPoolsClientBeginUpgradeNodeImageVersionOptions) (*http.Response, error) { var err error const operationName = "AgentPoolsClient.BeginUpgradeNodeImageVersion" @@ -643,7 +643,7 @@ func (client *AgentPoolsClient) upgradeNodeImageVersionCreateRequest(ctx context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json index f0727b781..d8f19405a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "go", "TagPrefix": "go/resourcemanager/containerservice/armcontainerservice", - "Tag": "go/resourcemanager/containerservice/armcontainerservice_2822db81dc" + "Tag": "go/resourcemanager/containerservice/armcontainerservice_d09553bfda" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md index 9fccdcc2c..65197fe3f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md @@ -5,9 +5,9 @@ ``` yaml azure-arm: true require: -- https://github.com/Azure/azure-rest-api-specs/blob/c1ba9df47907f9012ae14ca4616aed9e5665f9e5/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.md -- https://github.com/Azure/azure-rest-api-specs/blob/c1ba9df47907f9012ae14ca4616aed9e5665f9e5/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.go.md +- https://github.com/Azure/azure-rest-api-specs/blob/8b5618d760532b69d6f7434f57172ea52e109c79/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/8b5618d760532b69d6f7434f57172ea52e109c79/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 4.6.0 -tag: package-2023-10 +module-version: 4.7.0 +tag: package-2023-11 ``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go index 23f7875b1..a8f2d989b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go @@ -10,7 +10,7 @@ package armcontainerservice const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice" - moduleVersion = "v4.6.0" + moduleVersion = "v4.7.0" ) // AgentPoolMode - A cluster must have at least one 'System' Agent Pool at all times. For additional information on agent diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go index 6eb21b54b..9ddd6bdbf 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go @@ -46,7 +46,7 @@ func NewMaintenanceConfigurationsClient(subscriptionID string, credential azcore // CreateOrUpdate - Creates or updates a maintenance configuration in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - configName - The name of the maintenance configuration. @@ -99,7 +99,7 @@ func (client *MaintenanceConfigurationsClient) createOrUpdateCreateRequest(ctx c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -120,7 +120,7 @@ func (client *MaintenanceConfigurationsClient) createOrUpdateHandleResponse(resp // Delete - Deletes a maintenance configuration. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - configName - The name of the maintenance configuration. @@ -171,7 +171,7 @@ func (client *MaintenanceConfigurationsClient) deleteCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -180,7 +180,7 @@ func (client *MaintenanceConfigurationsClient) deleteCreateRequest(ctx context.C // Get - Gets the specified maintenance configuration of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - configName - The name of the maintenance configuration. @@ -232,7 +232,7 @@ func (client *MaintenanceConfigurationsClient) getCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -249,7 +249,7 @@ func (client *MaintenanceConfigurationsClient) getHandleResponse(resp *http.Resp // NewListByManagedClusterPager - Gets a list of maintenance configurations in the specified managed cluster. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - MaintenanceConfigurationsClientListByManagedClusterOptions contains the optional parameters for the MaintenanceConfigurationsClient.NewListByManagedClusterPager @@ -297,7 +297,7 @@ func (client *MaintenanceConfigurationsClient) listByManagedClusterCreateRequest return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go index 04dfeda1c..4bcbed44a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go @@ -48,7 +48,7 @@ func NewManagedClustersClient(subscriptionID string, credential azcore.TokenCred // completes before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginAbortLatestOperationOptions contains the optional parameters for the ManagedClustersClient.BeginAbortLatestOperation @@ -76,7 +76,7 @@ func (client *ManagedClustersClient) BeginAbortLatestOperation(ctx context.Conte // completes before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) abortLatestOperation(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginAbortLatestOperationOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginAbortLatestOperation" @@ -118,7 +118,7 @@ func (client *ManagedClustersClient) abortLatestOperationCreateRequest(ctx conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -127,7 +127,7 @@ func (client *ManagedClustersClient) abortLatestOperationCreateRequest(ctx conte // BeginCreateOrUpdate - Creates or updates a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The managed cluster to create or update. @@ -153,7 +153,7 @@ func (client *ManagedClustersClient) BeginCreateOrUpdate(ctx context.Context, re // CreateOrUpdate - Creates or updates a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) createOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, parameters ManagedCluster, options *ManagedClustersClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginCreateOrUpdate" @@ -195,7 +195,7 @@ func (client *ManagedClustersClient) createOrUpdateCreateRequest(ctx context.Con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -207,7 +207,7 @@ func (client *ManagedClustersClient) createOrUpdateCreateRequest(ctx context.Con // BeginDelete - Deletes a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginDeleteOptions contains the optional parameters for the ManagedClustersClient.BeginDelete @@ -232,7 +232,7 @@ func (client *ManagedClustersClient) BeginDelete(ctx context.Context, resourceGr // Delete - Deletes a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginDelete" @@ -274,7 +274,7 @@ func (client *ManagedClustersClient) deleteCreateRequest(ctx context.Context, re return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -283,7 +283,7 @@ func (client *ManagedClustersClient) deleteCreateRequest(ctx context.Context, re // Get - Gets a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientGetOptions contains the optional parameters for the ManagedClustersClient.Get method. @@ -329,7 +329,7 @@ func (client *ManagedClustersClient) getCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -349,7 +349,7 @@ func (client *ManagedClustersClient) getHandleResponse(resp *http.Response) (Man // [https://docs.microsoft.com/rest/api/aks/managedclusters/listclusteradmincredentials] . // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - roleName - The name of the role for managed cluster accessProfile resource. @@ -401,7 +401,7 @@ func (client *ManagedClustersClient) getAccessProfileCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -419,7 +419,7 @@ func (client *ManagedClustersClient) getAccessProfileHandleResponse(resp *http.R // GetCommandResult - Gets the results of a command which has been run on the Managed Cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - commandID - Id of the command. @@ -471,7 +471,7 @@ func (client *ManagedClustersClient) getCommandResultCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -493,7 +493,7 @@ func (client *ManagedClustersClient) getCommandResultHandleResponse(resp *http.R // and available upgrades // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - location - The name of the Azure region. // - mode - The mode of the mesh. // - options - ManagedClustersClientGetMeshRevisionProfileOptions contains the optional parameters for the ManagedClustersClient.GetMeshRevisionProfile @@ -540,7 +540,7 @@ func (client *ManagedClustersClient) getMeshRevisionProfileCreateRequest(ctx con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -558,7 +558,7 @@ func (client *ManagedClustersClient) getMeshRevisionProfileHandleResponse(resp * // GetMeshUpgradeProfile - Gets available upgrades for a service mesh in a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - mode - The mode of the mesh. @@ -610,7 +610,7 @@ func (client *ManagedClustersClient) getMeshUpgradeProfileCreateRequest(ctx cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -628,7 +628,7 @@ func (client *ManagedClustersClient) getMeshUpgradeProfileHandleResponse(resp *h // GetOSOptions - Gets supported OS options in the specified subscription. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - location - The name of the Azure region. // - options - ManagedClustersClientGetOSOptionsOptions contains the optional parameters for the ManagedClustersClient.GetOSOptions // method. @@ -670,7 +670,7 @@ func (client *ManagedClustersClient) getOSOptionsCreateRequest(ctx context.Conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") if options != nil && options.ResourceType != nil { reqQP.Set("resource-type", *options.ResourceType) } @@ -691,7 +691,7 @@ func (client *ManagedClustersClient) getOSOptionsHandleResponse(resp *http.Respo // GetUpgradeProfile - Gets the upgrade profile of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientGetUpgradeProfileOptions contains the optional parameters for the ManagedClustersClient.GetUpgradeProfile @@ -738,7 +738,7 @@ func (client *ManagedClustersClient) getUpgradeProfileCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -755,7 +755,7 @@ func (client *ManagedClustersClient) getUpgradeProfileHandleResponse(resp *http. // NewListPager - Gets a list of managed clusters in the specified subscription. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - options - ManagedClustersClientListOptions contains the optional parameters for the ManagedClustersClient.NewListPager // method. func (client *ManagedClustersClient) NewListPager(options *ManagedClustersClientListOptions) *runtime.Pager[ManagedClustersClientListResponse] { @@ -793,7 +793,7 @@ func (client *ManagedClustersClient) listCreateRequest(ctx context.Context, opti return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -810,7 +810,7 @@ func (client *ManagedClustersClient) listHandleResponse(resp *http.Response) (Ma // NewListByResourceGroupPager - Lists managed clusters in the specified subscription and resource group. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - options - ManagedClustersClientListByResourceGroupOptions contains the optional parameters for the ManagedClustersClient.NewListByResourceGroupPager // method. @@ -853,7 +853,7 @@ func (client *ManagedClustersClient) listByResourceGroupCreateRequest(ctx contex return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -871,7 +871,7 @@ func (client *ManagedClustersClient) listByResourceGroupHandleResponse(resp *htt // ListClusterAdminCredentials - Lists the admin credentials of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListClusterAdminCredentialsOptions contains the optional parameters for the ManagedClustersClient.ListClusterAdminCredentials @@ -918,7 +918,7 @@ func (client *ManagedClustersClient) listClusterAdminCredentialsCreateRequest(ct return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") if options != nil && options.ServerFqdn != nil { reqQP.Set("server-fqdn", *options.ServerFqdn) } @@ -939,7 +939,7 @@ func (client *ManagedClustersClient) listClusterAdminCredentialsHandleResponse(r // ListClusterMonitoringUserCredentials - Lists the cluster monitoring user credentials of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListClusterMonitoringUserCredentialsOptions contains the optional parameters for the ManagedClustersClient.ListClusterMonitoringUserCredentials @@ -986,7 +986,7 @@ func (client *ManagedClustersClient) listClusterMonitoringUserCredentialsCreateR return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") if options != nil && options.ServerFqdn != nil { reqQP.Set("server-fqdn", *options.ServerFqdn) } @@ -1007,7 +1007,7 @@ func (client *ManagedClustersClient) listClusterMonitoringUserCredentialsHandleR // ListClusterUserCredentials - Lists the user credentials of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListClusterUserCredentialsOptions contains the optional parameters for the ManagedClustersClient.ListClusterUserCredentials @@ -1054,7 +1054,7 @@ func (client *ManagedClustersClient) listClusterUserCredentialsCreateRequest(ctx return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") if options != nil && options.ServerFqdn != nil { reqQP.Set("server-fqdn", *options.ServerFqdn) } @@ -1079,7 +1079,7 @@ func (client *ManagedClustersClient) listClusterUserCredentialsHandleResponse(re // upgrades, and details on preview status of the version // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - location - The name of the Azure region. // - options - ManagedClustersClientListKubernetesVersionsOptions contains the optional parameters for the ManagedClustersClient.ListKubernetesVersions // method. @@ -1121,7 +1121,7 @@ func (client *ManagedClustersClient) listKubernetesVersionsCreateRequest(ctx con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1139,7 +1139,7 @@ func (client *ManagedClustersClient) listKubernetesVersionsHandleResponse(resp * // NewListMeshRevisionProfilesPager - Contains extra metadata on each revision, including supported revisions, cluster compatibility // and available upgrades // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - location - The name of the Azure region. // - options - ManagedClustersClientListMeshRevisionProfilesOptions contains the optional parameters for the ManagedClustersClient.NewListMeshRevisionProfilesPager // method. @@ -1182,7 +1182,7 @@ func (client *ManagedClustersClient) listMeshRevisionProfilesCreateRequest(ctx c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1199,7 +1199,7 @@ func (client *ManagedClustersClient) listMeshRevisionProfilesHandleResponse(resp // NewListMeshUpgradeProfilesPager - Lists available upgrades for all service meshes in a specific cluster. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListMeshUpgradeProfilesOptions contains the optional parameters for the ManagedClustersClient.NewListMeshUpgradeProfilesPager @@ -1247,7 +1247,7 @@ func (client *ManagedClustersClient) listMeshUpgradeProfilesCreateRequest(ctx co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1265,7 +1265,7 @@ func (client *ManagedClustersClient) listMeshUpgradeProfilesHandleResponse(resp // NewListOutboundNetworkDependenciesEndpointsPager - Gets a list of egress endpoints (network endpoints of all outbound dependencies) // in the specified managed cluster. The operation returns properties of each egress endpoint. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListOutboundNetworkDependenciesEndpointsOptions contains the optional parameters for the @@ -1313,7 +1313,7 @@ func (client *ManagedClustersClient) listOutboundNetworkDependenciesEndpointsCre return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1332,7 +1332,7 @@ func (client *ManagedClustersClient) listOutboundNetworkDependenciesEndpointsHan // [https://aka.ms/aks-managed-aad] to update your cluster with AKS-managed Azure AD. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The AAD profile to set on the Managed Cluster @@ -1360,7 +1360,7 @@ func (client *ManagedClustersClient) BeginResetAADProfile(ctx context.Context, r // to update your cluster with AKS-managed Azure AD. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) resetAADProfile(ctx context.Context, resourceGroupName string, resourceName string, parameters ManagedClusterAADProfile, options *ManagedClustersClientBeginResetAADProfileOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginResetAADProfile" @@ -1402,7 +1402,7 @@ func (client *ManagedClustersClient) resetAADProfileCreateRequest(ctx context.Co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -1414,7 +1414,7 @@ func (client *ManagedClustersClient) resetAADProfileCreateRequest(ctx context.Co // BeginResetServicePrincipalProfile - This action cannot be performed on a cluster that is not using a service principal // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The service principal profile to set on the managed cluster. @@ -1441,7 +1441,7 @@ func (client *ManagedClustersClient) BeginResetServicePrincipalProfile(ctx conte // ResetServicePrincipalProfile - This action cannot be performed on a cluster that is not using a service principal // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) resetServicePrincipalProfile(ctx context.Context, resourceGroupName string, resourceName string, parameters ManagedClusterServicePrincipalProfile, options *ManagedClustersClientBeginResetServicePrincipalProfileOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginResetServicePrincipalProfile" @@ -1483,7 +1483,7 @@ func (client *ManagedClustersClient) resetServicePrincipalProfileCreateRequest(c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -1496,7 +1496,7 @@ func (client *ManagedClustersClient) resetServicePrincipalProfileCreateRequest(c // more details about rotating managed cluster certificates. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginRotateClusterCertificatesOptions contains the optional parameters for the ManagedClustersClient.BeginRotateClusterCertificates @@ -1523,7 +1523,7 @@ func (client *ManagedClustersClient) BeginRotateClusterCertificates(ctx context. // details about rotating managed cluster certificates. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) rotateClusterCertificates(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginRotateClusterCertificatesOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginRotateClusterCertificates" @@ -1565,7 +1565,7 @@ func (client *ManagedClustersClient) rotateClusterCertificatesCreateRequest(ctx return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1574,7 +1574,7 @@ func (client *ManagedClustersClient) rotateClusterCertificatesCreateRequest(ctx // BeginRotateServiceAccountSigningKeys - Rotates the service account signing keys of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginRotateServiceAccountSigningKeysOptions contains the optional parameters for the ManagedClustersClient.BeginRotateServiceAccountSigningKeys @@ -1600,7 +1600,7 @@ func (client *ManagedClustersClient) BeginRotateServiceAccountSigningKeys(ctx co // RotateServiceAccountSigningKeys - Rotates the service account signing keys of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) rotateServiceAccountSigningKeys(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginRotateServiceAccountSigningKeysOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginRotateServiceAccountSigningKeys" @@ -1642,7 +1642,7 @@ func (client *ManagedClustersClient) rotateServiceAccountSigningKeysCreateReques return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1653,7 +1653,7 @@ func (client *ManagedClustersClient) rotateServiceAccountSigningKeysCreateReques // [https://docs.microsoft.com/azure/aks/private-clusters#aks-run-command-preview]. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - requestPayload - The run command request @@ -1682,7 +1682,7 @@ func (client *ManagedClustersClient) BeginRunCommand(ctx context.Context, resour // [https://docs.microsoft.com/azure/aks/private-clusters#aks-run-command-preview]. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) runCommand(ctx context.Context, resourceGroupName string, resourceName string, requestPayload RunCommandRequest, options *ManagedClustersClientBeginRunCommandOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginRunCommand" @@ -1724,7 +1724,7 @@ func (client *ManagedClustersClient) runCommandCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestPayload); err != nil { @@ -1737,7 +1737,7 @@ func (client *ManagedClustersClient) runCommandCreateRequest(ctx context.Context // a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginStartOptions contains the optional parameters for the ManagedClustersClient.BeginStart @@ -1764,7 +1764,7 @@ func (client *ManagedClustersClient) BeginStart(ctx context.Context, resourceGro // a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) start(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginStartOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginStart" @@ -1806,7 +1806,7 @@ func (client *ManagedClustersClient) startCreateRequest(ctx context.Context, res return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1818,7 +1818,7 @@ func (client *ManagedClustersClient) startCreateRequest(ctx context.Context, res // for more details about stopping a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginStopOptions contains the optional parameters for the ManagedClustersClient.BeginStop @@ -1847,7 +1847,7 @@ func (client *ManagedClustersClient) BeginStop(ctx context.Context, resourceGrou // for more details about stopping a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) stop(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginStopOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginStop" @@ -1889,7 +1889,7 @@ func (client *ManagedClustersClient) stopCreateRequest(ctx context.Context, reso return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1898,7 +1898,7 @@ func (client *ManagedClustersClient) stopCreateRequest(ctx context.Context, reso // BeginUpdateTags - Updates tags on a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - Parameters supplied to the Update Managed Cluster Tags operation. @@ -1924,7 +1924,7 @@ func (client *ManagedClustersClient) BeginUpdateTags(ctx context.Context, resour // UpdateTags - Updates tags on a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *ManagedClustersClient) updateTags(ctx context.Context, resourceGroupName string, resourceName string, parameters TagsObject, options *ManagedClustersClientBeginUpdateTagsOptions) (*http.Response, error) { var err error const operationName = "ManagedClustersClient.BeginUpdateTags" @@ -1966,7 +1966,7 @@ func (client *ManagedClustersClient) updateTagsCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go index 53ce459f7..e4480e0ba 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go @@ -144,6 +144,10 @@ type AgentPoolUpgradeSettings struct { // practices, see: // https://docs.microsoft.com/azure/aks/upgrade-cluster#customize-node-surge-upgrade MaxSurge *string + + // The amount of time (in minutes) to wait after draining a node and before reimaging it and moving on to next node. If not + // specified, the default is 0 minutes. + NodeSoakDurationInMinutes *int32 } // AzureKeyVaultKms - Azure Key Vault key management service settings for the security profile. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go index 5a3eeac7a..da9690495 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go @@ -394,6 +394,7 @@ func (a AgentPoolUpgradeSettings) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "drainTimeoutInMinutes", a.DrainTimeoutInMinutes) populate(objectMap, "maxSurge", a.MaxSurge) + populate(objectMap, "nodeSoakDurationInMinutes", a.NodeSoakDurationInMinutes) return json.Marshal(objectMap) } @@ -412,6 +413,9 @@ func (a *AgentPoolUpgradeSettings) UnmarshalJSON(data []byte) error { case "maxSurge": err = unpopulate(val, "MaxSurge", &a.MaxSurge) delete(rawMsg, key) + case "nodeSoakDurationInMinutes": + err = unpopulate(val, "NodeSoakDurationInMinutes", &a.NodeSoakDurationInMinutes) + delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", a, err) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go index 7275bdd49..4f3e48455 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go @@ -39,7 +39,7 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO // NewListPager - Gets a list of operations. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ @@ -73,7 +73,7 @@ func (client *OperationsClient) listCreateRequest(ctx context.Context, options * return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go index c82074711..22bd5990e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go @@ -46,7 +46,7 @@ func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcor // BeginDelete - Deletes a private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - privateEndpointConnectionName - The name of the private endpoint connection. @@ -72,7 +72,7 @@ func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, // Delete - Deletes a private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "PrivateEndpointConnectionsClient.BeginDelete" @@ -118,7 +118,7 @@ func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -127,7 +127,7 @@ func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context. // Get - To learn more about private clusters, see: https://docs.microsoft.com/azure/aks/private-clusters // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - privateEndpointConnectionName - The name of the private endpoint connection. @@ -179,7 +179,7 @@ func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -197,7 +197,7 @@ func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Res // List - To learn more about private clusters, see: https://docs.microsoft.com/azure/aks/private-clusters // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.List @@ -244,7 +244,7 @@ func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -262,7 +262,7 @@ func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Re // Update - Updates a private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - privateEndpointConnectionName - The name of the private endpoint connection. @@ -315,7 +315,7 @@ func (client *PrivateEndpointConnectionsClient) updateCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go index a9e0940b0..9a9f09811 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go @@ -46,7 +46,7 @@ func NewPrivateLinkResourcesClient(subscriptionID string, credential azcore.Toke // List - To learn more about private clusters, see: https://docs.microsoft.com/azure/aks/private-clusters // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - PrivateLinkResourcesClientListOptions contains the optional parameters for the PrivateLinkResourcesClient.List @@ -93,7 +93,7 @@ func (client *PrivateLinkResourcesClient) listCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go index bec89442e..f95952e40 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go @@ -46,7 +46,7 @@ func NewResolvePrivateLinkServiceIDClient(subscriptionID string, credential azco // POST - Gets the private link service ID for the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - Parameters required in order to resolve a private link service ID. @@ -94,7 +94,7 @@ func (client *ResolvePrivateLinkServiceIDClient) postCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go index c0a7182fd..6043d81e1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go @@ -46,7 +46,7 @@ func NewSnapshotsClient(subscriptionID string, credential azcore.TokenCredential // CreateOrUpdate - Creates or updates a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The snapshot to create or update. @@ -94,7 +94,7 @@ func (client *SnapshotsClient) createOrUpdateCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -115,7 +115,7 @@ func (client *SnapshotsClient) createOrUpdateHandleResponse(resp *http.Response) // Delete - Deletes a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - SnapshotsClientDeleteOptions contains the optional parameters for the SnapshotsClient.Delete method. @@ -160,7 +160,7 @@ func (client *SnapshotsClient) deleteCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -169,7 +169,7 @@ func (client *SnapshotsClient) deleteCreateRequest(ctx context.Context, resource // Get - Gets a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - SnapshotsClientGetOptions contains the optional parameters for the SnapshotsClient.Get method. @@ -215,7 +215,7 @@ func (client *SnapshotsClient) getCreateRequest(ctx context.Context, resourceGro return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -232,7 +232,7 @@ func (client *SnapshotsClient) getHandleResponse(resp *http.Response) (Snapshots // NewListPager - Gets a list of snapshots in the specified subscription. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - options - SnapshotsClientListOptions contains the optional parameters for the SnapshotsClient.NewListPager method. func (client *SnapshotsClient) NewListPager(options *SnapshotsClientListOptions) *runtime.Pager[SnapshotsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[SnapshotsClientListResponse]{ @@ -269,7 +269,7 @@ func (client *SnapshotsClient) listCreateRequest(ctx context.Context, options *S return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -286,7 +286,7 @@ func (client *SnapshotsClient) listHandleResponse(resp *http.Response) (Snapshot // NewListByResourceGroupPager - Lists snapshots in the specified subscription and resource group. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - options - SnapshotsClientListByResourceGroupOptions contains the optional parameters for the SnapshotsClient.NewListByResourceGroupPager // method. @@ -329,7 +329,7 @@ func (client *SnapshotsClient) listByResourceGroupCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -347,7 +347,7 @@ func (client *SnapshotsClient) listByResourceGroupHandleResponse(resp *http.Resp // UpdateTags - Updates tags on a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - Parameters supplied to the Update snapshot Tags operation. @@ -394,7 +394,7 @@ func (client *SnapshotsClient) updateTagsCreateRequest(ctx context.Context, reso return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessrolebindings_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessrolebindings_client.go index 5dcd89d6a..8509aed09 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessrolebindings_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessrolebindings_client.go @@ -46,7 +46,7 @@ func NewTrustedAccessRoleBindingsClient(subscriptionID string, credential azcore // BeginCreateOrUpdate - Create or update a trusted access role binding // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - trustedAccessRoleBindingName - The name of trusted access role binding. @@ -73,7 +73,7 @@ func (client *TrustedAccessRoleBindingsClient) BeginCreateOrUpdate(ctx context.C // CreateOrUpdate - Create or update a trusted access role binding // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *TrustedAccessRoleBindingsClient) createOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, trustedAccessRoleBindingName string, trustedAccessRoleBinding TrustedAccessRoleBinding, options *TrustedAccessRoleBindingsClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "TrustedAccessRoleBindingsClient.BeginCreateOrUpdate" @@ -119,7 +119,7 @@ func (client *TrustedAccessRoleBindingsClient) createOrUpdateCreateRequest(ctx c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, trustedAccessRoleBinding); err != nil { @@ -131,7 +131,7 @@ func (client *TrustedAccessRoleBindingsClient) createOrUpdateCreateRequest(ctx c // BeginDelete - Delete a trusted access role binding. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - trustedAccessRoleBindingName - The name of trusted access role binding. @@ -157,7 +157,7 @@ func (client *TrustedAccessRoleBindingsClient) BeginDelete(ctx context.Context, // Delete - Delete a trusted access role binding. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 func (client *TrustedAccessRoleBindingsClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceName string, trustedAccessRoleBindingName string, options *TrustedAccessRoleBindingsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "TrustedAccessRoleBindingsClient.BeginDelete" @@ -203,7 +203,7 @@ func (client *TrustedAccessRoleBindingsClient) deleteCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -212,7 +212,7 @@ func (client *TrustedAccessRoleBindingsClient) deleteCreateRequest(ctx context.C // Get - Get a trusted access role binding. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - trustedAccessRoleBindingName - The name of trusted access role binding. @@ -264,7 +264,7 @@ func (client *TrustedAccessRoleBindingsClient) getCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -281,7 +281,7 @@ func (client *TrustedAccessRoleBindingsClient) getHandleResponse(resp *http.Resp // NewListPager - List trusted access role bindings. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - TrustedAccessRoleBindingsClientListOptions contains the optional parameters for the TrustedAccessRoleBindingsClient.NewListPager @@ -329,7 +329,7 @@ func (client *TrustedAccessRoleBindingsClient) listCreateRequest(ctx context.Con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessroles_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessroles_client.go index 587e9b2bd..bfc856a4b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessroles_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/trustedaccessroles_client.go @@ -45,7 +45,7 @@ func NewTrustedAccessRolesClient(subscriptionID string, credential azcore.TokenC // NewListPager - List supported trusted access roles. // -// Generated from API version 2023-10-01 +// Generated from API version 2023-11-01 // - location - The name of the Azure region. // - options - TrustedAccessRolesClientListOptions contains the optional parameters for the TrustedAccessRolesClient.NewListPager // method. @@ -88,7 +88,7 @@ func (client *TrustedAccessRolesClient) listCreateRequest(ctx context.Context, l return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-10-01") + reqQP.Set("api-version", "2023-11-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go index 11263822b..2221e60c4 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go @@ -82,6 +82,39 @@ func isMatchingScopes(scopesOne []string, scopesTwo string) bool { return scopeCounter == len(scopesOne) } +// needsUpgrade returns true if the given key follows the v1.0 schema i.e., +// it contains an uppercase character (v1.1+ keys are all lowercase) +func needsUpgrade(key string) bool { + for _, r := range key { + if 'A' <= r && r <= 'Z' { + return true + } + } + return false +} + +// upgrade a v1.0 cache item by adding a v1.1+ item having the same value and deleting +// the v1.0 item. Callers must hold an exclusive lock on m. +func upgrade[T any](m map[string]T, k string) T { + v1_1Key := strings.ToLower(k) + v, ok := m[k] + if !ok { + // another goroutine did the upgrade while this one was waiting for the write lock + return m[v1_1Key] + } + if v2, ok := m[v1_1Key]; ok { + // cache has an equivalent v1.1+ item, which we prefer because we know it was added + // by a newer version of the module and is therefore more likely to remain valid. + // The v1.0 item may have expired because only v1.0 or earlier would update it. + v = v2 + } else { + // add an equivalent item according to the v1.1 schema + m[v1_1Key] = v + } + delete(m, k) + return v +} + // Read reads a storage token from the cache if it exists. func (m *Manager) Read(ctx context.Context, authParameters authority.AuthParams) (TokenResponse, error) { tr := TokenResponse{} @@ -255,21 +288,25 @@ func (m *Manager) aadMetadata(ctx context.Context, authorityInfo authority.Info) func (m *Manager) readAccessToken(homeID string, envAliases []string, realm, clientID string, scopes []string, tokenType, authnSchemeKeyID string) AccessToken { m.contractMu.RLock() - defer m.contractMu.RUnlock() // TODO: linear search (over a map no less) is slow for a large number (thousands) of tokens. // this shows up as the dominating node in a profile. for real-world scenarios this likely isn't // an issue, however if it does become a problem then we know where to look. - for _, at := range m.contract.AccessTokens { + for k, at := range m.contract.AccessTokens { if at.HomeAccountID == homeID && at.Realm == realm && at.ClientID == clientID { - if (at.TokenType == tokenType && at.AuthnSchemeKeyID == authnSchemeKeyID) || (at.TokenType == "" && (tokenType == "" || tokenType == "Bearer")) { - if checkAlias(at.Environment, envAliases) { - if isMatchingScopes(scopes, at.Scopes) { - return at + if (strings.EqualFold(at.TokenType, tokenType) && at.AuthnSchemeKeyID == authnSchemeKeyID) || (at.TokenType == "" && (tokenType == "" || tokenType == "Bearer")) { + if checkAlias(at.Environment, envAliases) && isMatchingScopes(scopes, at.Scopes) { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + at = upgrade(m.contract.AccessTokens, k) } + return at } } } } + m.contractMu.RUnlock() return AccessToken{} } @@ -310,15 +347,21 @@ func (m *Manager) readRefreshToken(homeID string, envAliases []string, familyID, // If app is part of the family or if we DO NOT KNOW if it's part of the family, search by family ID, then by client_id (we will know if an app is part of the family after the first token response). // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/311fe8b16e7c293462806f397e189a6aa1159769/src/client/Microsoft.Identity.Client/Internal/Requests/Silent/CacheSilentStrategy.cs#L95 m.contractMu.RLock() - defer m.contractMu.RUnlock() for _, matcher := range matchers { - for _, rt := range m.contract.RefreshTokens { + for k, rt := range m.contract.RefreshTokens { if matcher(rt) { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + rt = upgrade(m.contract.RefreshTokens, k) + } return rt, nil } } } + m.contractMu.RUnlock() return accesstokens.RefreshToken{}, fmt.Errorf("refresh token not found") } @@ -340,14 +383,20 @@ func (m *Manager) writeRefreshToken(refreshToken accesstokens.RefreshToken) erro func (m *Manager) readIDToken(homeID string, envAliases []string, realm, clientID string) (IDToken, error) { m.contractMu.RLock() - defer m.contractMu.RUnlock() - for _, idt := range m.contract.IDTokens { + for k, idt := range m.contract.IDTokens { if idt.HomeAccountID == homeID && idt.Realm == realm && idt.ClientID == clientID { if checkAlias(idt.Environment, envAliases) { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + idt = upgrade(m.contract.IDTokens, k) + } return idt, nil } } } + m.contractMu.RUnlock() return IDToken{}, fmt.Errorf("token not found") } @@ -386,7 +435,6 @@ func (m *Manager) Account(homeAccountID string) shared.Account { func (m *Manager) readAccount(homeAccountID string, envAliases []string, realm string) (shared.Account, error) { m.contractMu.RLock() - defer m.contractMu.RUnlock() // You might ask why, if cache.Accounts is a map, we would loop through all of these instead of using a key. // We only use a map because the storage contract shared between all language implementations says use a map. @@ -394,11 +442,18 @@ func (m *Manager) readAccount(homeAccountID string, envAliases []string, realm s // a match in multiple envs (envAlias). That means we either need to hash each possible keyand do the lookup // or just statically check. Since the design is to have a storage.Manager per user, the amount of keys stored // is really low (say 2). Each hash is more expensive than the entire iteration. - for _, acc := range m.contract.Accounts { + for k, acc := range m.contract.Accounts { if acc.HomeAccountID == homeAccountID && checkAlias(acc.Environment, envAliases) && acc.Realm == realm { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + acc = upgrade(m.contract.Accounts, k) + } return acc, nil } } + m.contractMu.RUnlock() return shared.Account{}, fmt.Errorf("account not found") } @@ -412,13 +467,18 @@ func (m *Manager) writeAccount(account shared.Account) error { func (m *Manager) readAppMetaData(envAliases []string, clientID string) (AppMetaData, error) { m.contractMu.RLock() - defer m.contractMu.RUnlock() - - for _, app := range m.contract.AppMetaData { + for k, app := range m.contract.AppMetaData { if checkAlias(app.Environment, envAliases) && app.ClientID == clientID { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + app = upgrade(m.contract.AppMetaData, k) + } return app, nil } } + m.contractMu.RUnlock() return AppMetaData{}, fmt.Errorf("not found") } diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go index 2221b3d33..e346ff3df 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go @@ -51,7 +51,7 @@ type AuthenticationScheme = authority.AuthenticationScheme type Account = shared.Account -var errNoAccount = errors.New("no account was specified with public.WithAccount(), or the specified account is invalid") +var errNoAccount = errors.New("no account was specified with public.WithSilentAccount(), or the specified account is invalid") // clientOptions configures the Client's behavior. type clientOptions struct { diff --git a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md index 6ad1c22bb..ff9c57e1d 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md +++ b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md @@ -17,7 +17,7 @@ and corresponding updates for existing programs. ## Parsing and Validation Options -Under the hood, a new `validator` struct takes care of validating the claims. A +Under the hood, a new `Validator` struct takes care of validating the claims. A long awaited feature has been the option to fine-tune the validation of tokens. This is now possible with several `ParserOption` functions that can be appended to most `Parse` functions, such as `ParseWithClaims`. The most important options @@ -68,6 +68,16 @@ type Claims interface { } ``` +Users that previously directly called the `Valid` function on their claims, +e.g., to perform validation independently of parsing/verifying a token, can now +use the `jwt.NewValidator` function to create a `Validator` independently of the +`Parser`. + +```go +var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second)) +v.Validate(myClaims) +``` + ### Supported Claim Types and Removal of `StandardClaims` The two standard claim types supported by this library, `MapClaims` and @@ -169,7 +179,7 @@ be a drop-in replacement, if you're having troubles migrating, please open an issue. You can replace all occurrences of `github.com/dgrijalva/jwt-go` or -`github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v5`, either manually +`github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually or by using tools such as `sed` or `gofmt`. And then you'd typically run: diff --git a/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go index 4ccae2a85..ca85659ba 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go +++ b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go @@ -62,7 +62,7 @@ func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interf case *ecdsa.PublicKey: ecdsaKey = k default: - return ErrInvalidKeyType + return newError("ECDSA verify expects *ecsda.PublicKey", ErrInvalidKeyType) } if len(sig) != 2*m.KeySize { @@ -96,7 +96,7 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte case *ecdsa.PrivateKey: ecdsaKey = k default: - return nil, ErrInvalidKeyType + return nil, newError("ECDSA sign expects *ecsda.PrivateKey", ErrInvalidKeyType) } // Create the hasher diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go index 3db00e4a2..c2138119e 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go +++ b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go @@ -1,11 +1,10 @@ package jwt import ( - "errors" - "crypto" "crypto/ed25519" "crypto/rand" + "errors" ) var ( @@ -39,7 +38,7 @@ func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key inte var ok bool if ed25519Key, ok = key.(ed25519.PublicKey); !ok { - return ErrInvalidKeyType + return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType) } if len(ed25519Key) != ed25519.PublicKeySize { @@ -61,7 +60,7 @@ func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]by var ok bool if ed25519Key, ok = key.(crypto.Signer); !ok { - return nil, ErrInvalidKeyType + return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType) } if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go index 3afb04e64..2ad542f00 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go +++ b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go @@ -22,7 +22,7 @@ func (je joinedError) Is(err error) bool { // wrappedErrors is a workaround for wrapping multiple errors in environments // where Go 1.20 is not available. It basically uses the already implemented -// functionatlity of joinedError to handle multiple errors with supplies a +// functionality of joinedError to handle multiple errors with supplies a // custom error message that is identical to the one we produce in Go 1.20 using // multiple %w directives. type wrappedErrors struct { diff --git a/vendor/github.com/golang-jwt/jwt/v5/hmac.go b/vendor/github.com/golang-jwt/jwt/v5/hmac.go index 91b688ba9..96c62722d 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/hmac.go +++ b/vendor/github.com/golang-jwt/jwt/v5/hmac.go @@ -59,7 +59,7 @@ func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interfa // Verify the key is the right type keyBytes, ok := key.([]byte) if !ok { - return ErrInvalidKeyType + return newError("HMAC verify expects []byte", ErrInvalidKeyType) } // Can we use the specified hashing method? @@ -91,7 +91,7 @@ func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interfa func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { if keyBytes, ok := key.([]byte); ok { if !m.Hash.Available() { - return nil, ErrHashUnavailable + return nil, newError("HMAC sign expects []byte", ErrInvalidKeyType) } hasher := hmac.New(m.Hash.New, keyBytes) diff --git a/vendor/github.com/golang-jwt/jwt/v5/none.go b/vendor/github.com/golang-jwt/jwt/v5/none.go index c93daa584..685c2ea30 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/none.go +++ b/vendor/github.com/golang-jwt/jwt/v5/none.go @@ -32,7 +32,7 @@ func (m *signingMethodNone) Verify(signingString string, sig []byte, key interfa return NoneSignatureTypeDisallowedError } // If signing method is none, signature must be an empty string - if string(sig) != "" { + if len(sig) != 0 { return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) } diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser.go b/vendor/github.com/golang-jwt/jwt/v5/parser.go index f4386fbaa..ecf99af78 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/parser.go +++ b/vendor/github.com/golang-jwt/jwt/v5/parser.go @@ -18,7 +18,7 @@ type Parser struct { // Skip claims validation during token parsing. skipClaimsValidation bool - validator *validator + validator *Validator decodeStrict bool @@ -28,7 +28,7 @@ type Parser struct { // NewParser creates a new Parser with the specified options func NewParser(options ...ParserOption) *Parser { p := &Parser{ - validator: &validator{}, + validator: &Validator{}, } // Loop through our parsing options and apply them @@ -74,24 +74,40 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } } - // Lookup key - var key interface{} + // Decode signature + token.Signature, err = p.DecodeSegment(parts[2]) + if err != nil { + return token, newError("could not base64 decode signature", ErrTokenMalformed, err) + } + text := strings.Join(parts[0:2], ".") + + // Lookup key(s) if keyFunc == nil { // keyFunc was not provided. short circuiting validation return token, newError("no keyfunc was provided", ErrTokenUnverifiable) } - if key, err = keyFunc(token); err != nil { - return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) - } - // Decode signature - token.Signature, err = p.DecodeSegment(parts[2]) + got, err := keyFunc(token) if err != nil { - return token, newError("could not base64 decode signature", ErrTokenMalformed, err) + return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) } - // Perform signature validation - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + switch have := got.(type) { + case VerificationKeySet: + if len(have.Keys) == 0 { + return token, newError("keyfunc returned empty verification key set", ErrTokenUnverifiable) + } + // Iterate through keys and verify signature, skipping the rest when a match is found. + // Return the last error if no match is found. + for _, key := range have.Keys { + if err = token.Method.Verify(text, token.Signature, key); err == nil { + break + } + } + default: + err = token.Method.Verify(text, token.Signature, have) + } + if err != nil { return token, newError("", ErrTokenSignatureInvalid, err) } @@ -99,7 +115,7 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf if !p.skipClaimsValidation { // Make sure we have at least a default validator if p.validator == nil { - p.validator = newValidator() + p.validator = NewValidator() } if err := p.validator.Validate(claims); err != nil { @@ -117,8 +133,8 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf // // WARNING: Don't use this method unless you know what you're doing. // -// It's only ever useful in cases where you know the signature is valid (because it has -// been checked previously in the stack) and you want to extract values from it. +// It's only ever useful in cases where you know the signature is valid (since it has already +// been or will be checked elsewhere in the stack) and you want to extract values from it. func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { parts = strings.Split(tokenString, ".") if len(parts) != 3 { @@ -130,9 +146,6 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke // parse Header var headerBytes []byte if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed) - } return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { @@ -140,23 +153,33 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke } // parse Claims - var claimBytes []byte token.Claims = claims - if claimBytes, err = p.DecodeSegment(parts[1]); err != nil { + claimBytes, err := p.DecodeSegment(parts[1]) + if err != nil { return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.useJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) + + // If `useJSONNumber` is enabled then we must use *json.Decoder to decode + // the claims. However, this comes with a performance penalty so only use + // it if we must and, otherwise, simple use json.Unmarshal. + if !p.useJSONNumber { + // JSON Unmarshal. Special case for map type to avoid weird pointer behavior. + if c, ok := token.Claims.(MapClaims); ok { + err = json.Unmarshal(claimBytes, &c) + } else { + err = json.Unmarshal(claimBytes, &claims) + } } else { - err = dec.Decode(&claims) + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + dec.UseNumber() + // JSON Decode. Special case for map type to avoid weird pointer behavior. + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } } - // Handle decode error if err != nil { return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) } diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go index 1b5af970f..88a780fbd 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go +++ b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go @@ -58,6 +58,14 @@ func WithIssuedAt() ParserOption { } } +// WithExpirationRequired returns the ParserOption to make exp claim required. +// By default exp claim is optional. +func WithExpirationRequired() ParserOption { + return func(p *Parser) { + p.validator.requireExp = true + } +} + // WithAudience configures the validator to require the specified audience in // the `aud` claim. Validation will fail if the audience is not listed in the // token or the `aud` claim is missing. diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa.go b/vendor/github.com/golang-jwt/jwt/v5/rsa.go index daff09431..83cbee6ae 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa.go @@ -51,7 +51,7 @@ func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interfac var ok bool if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return ErrInvalidKeyType + return newError("RSA verify expects *rsa.PublicKey", ErrInvalidKeyType) } // Create hasher @@ -73,7 +73,7 @@ func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, // Validate type of key if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return nil, ErrInvalidKey + return nil, newError("RSA sign expects *rsa.PrivateKey", ErrInvalidKeyType) } // Create the hasher diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go index 9599f0a46..28c386ec4 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go @@ -88,7 +88,7 @@ func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key inter case *rsa.PublicKey: rsaKey = k default: - return ErrInvalidKey + return newError("RSA-PSS verify expects *rsa.PublicKey", ErrInvalidKeyType) } // Create hasher @@ -115,7 +115,7 @@ func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byt case *rsa.PrivateKey: rsaKey = k default: - return nil, ErrInvalidKeyType + return nil, newError("RSA-PSS sign expects *rsa.PrivateKey", ErrInvalidKeyType) } // Create the hasher diff --git a/vendor/github.com/golang-jwt/jwt/v5/token.go b/vendor/github.com/golang-jwt/jwt/v5/token.go index c8ad7c783..352873a2d 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/token.go +++ b/vendor/github.com/golang-jwt/jwt/v5/token.go @@ -1,6 +1,7 @@ package jwt import ( + "crypto" "encoding/base64" "encoding/json" ) @@ -9,8 +10,21 @@ import ( // the key for verification. The function receives the parsed, but unverified // Token. This allows you to use properties in the Header of the token (such as // `kid`) to identify which key to use. +// +// The returned interface{} may be a single key or a VerificationKeySet containing +// multiple keys. type Keyfunc func(*Token) (interface{}, error) +// VerificationKey represents a public or secret key for verifying a token's signature. +type VerificationKey interface { + crypto.PublicKey | []uint8 +} + +// VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token. +type VerificationKeySet struct { + Keys []VerificationKey +} + // Token represents a JWT Token. Different fields will be used depending on // whether you're creating or parsing/verifying a token. type Token struct { diff --git a/vendor/github.com/golang-jwt/jwt/v5/types.go b/vendor/github.com/golang-jwt/jwt/v5/types.go index b82b38867..b2655a9e6 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/types.go +++ b/vendor/github.com/golang-jwt/jwt/v5/types.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "math" - "reflect" "strconv" "time" ) @@ -121,14 +120,14 @@ func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { for _, vv := range v { vs, ok := vv.(string) if !ok { - return &json.UnsupportedTypeError{Type: reflect.TypeOf(vv)} + return ErrInvalidType } aud = append(aud, vs) } case nil: return nil default: - return &json.UnsupportedTypeError{Type: reflect.TypeOf(v)} + return ErrInvalidType } *s = aud diff --git a/vendor/github.com/golang-jwt/jwt/v5/validator.go b/vendor/github.com/golang-jwt/jwt/v5/validator.go index 385043893..008ecd871 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/validator.go +++ b/vendor/github.com/golang-jwt/jwt/v5/validator.go @@ -28,13 +28,12 @@ type ClaimsValidator interface { Validate() error } -// validator is the core of the new Validation API. It is automatically used by +// Validator is the core of the new Validation API. It is automatically used by // a [Parser] during parsing and can be modified with various parser options. // -// Note: This struct is intentionally not exported (yet) as we want to -// internally finalize its API. In the future, we might make it publicly -// available. -type validator struct { +// The [NewValidator] function should be used to create an instance of this +// struct. +type Validator struct { // leeway is an optional leeway that can be provided to account for clock skew. leeway time.Duration @@ -42,6 +41,9 @@ type validator struct { // validation. If unspecified, this defaults to time.Now. timeFunc func() time.Time + // requireExp specifies whether the exp claim is required + requireExp bool + // verifyIat specifies whether the iat (Issued At) claim will be verified. // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this // only specifies the age of the token, but no validation check is @@ -62,16 +64,28 @@ type validator struct { expectedSub string } -// newValidator can be used to create a stand-alone validator with the supplied +// NewValidator can be used to create a stand-alone validator with the supplied // options. This validator can then be used to validate already parsed claims. -func newValidator(opts ...ParserOption) *validator { +// +// Note: Under normal circumstances, explicitly creating a validator is not +// needed and can potentially be dangerous; instead functions of the [Parser] +// class should be used. +// +// The [Validator] is only checking the *validity* of the claims, such as its +// expiration time, but it does NOT perform *signature verification* of the +// token. +func NewValidator(opts ...ParserOption) *Validator { p := NewParser(opts...) return p.validator } // Validate validates the given claims. It will also perform any custom // validation if claims implements the [ClaimsValidator] interface. -func (v *validator) Validate(claims Claims) error { +// +// Note: It will NOT perform any *signature verification* on the token that +// contains the claims and expects that the [Claim] was already successfully +// verified. +func (v *Validator) Validate(claims Claims) error { var ( now time.Time errs []error = make([]error, 0, 6) @@ -86,8 +100,9 @@ func (v *validator) Validate(claims Claims) error { } // We always need to check the expiration time, but usage of the claim - // itself is OPTIONAL. - if err = v.verifyExpiresAt(claims, now, false); err != nil { + // itself is OPTIONAL by default. requireExp overrides this behavior + // and makes the exp claim mandatory. + if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil { errs = append(errs, err) } @@ -149,7 +164,7 @@ func (v *validator) Validate(claims Claims) error { // // Additionally, if any error occurs while retrieving the claim, e.g., when its // the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { +func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { exp, err := claims.GetExpirationTime() if err != nil { return err @@ -170,7 +185,7 @@ func (v *validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) // // Additionally, if any error occurs while retrieving the claim, e.g., when its // the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { +func (v *Validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { iat, err := claims.GetIssuedAt() if err != nil { return err @@ -191,7 +206,7 @@ func (v *validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) // // Additionally, if any error occurs while retrieving the claim, e.g., when its // the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { +func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { nbf, err := claims.GetNotBefore() if err != nil { return err @@ -211,7 +226,7 @@ func (v *validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) // // Additionally, if any error occurs while retrieving the claim, e.g., when its // the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyAudience(claims Claims, cmp string, required bool) error { +func (v *Validator) verifyAudience(claims Claims, cmp string, required bool) error { aud, err := claims.GetAudience() if err != nil { return err @@ -247,7 +262,7 @@ func (v *validator) verifyAudience(claims Claims, cmp string, required bool) err // // Additionally, if any error occurs while retrieving the claim, e.g., when its // the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyIssuer(claims Claims, cmp string, required bool) error { +func (v *Validator) verifyIssuer(claims Claims, cmp string, required bool) error { iss, err := claims.GetIssuer() if err != nil { return err @@ -267,7 +282,7 @@ func (v *validator) verifyIssuer(claims Claims, cmp string, required bool) error // // Additionally, if any error occurs while retrieving the claim, e.g., when its // the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifySubject(claims Claims, cmp string, required bool) error { +func (v *Validator) verifySubject(claims Claims, cmp string, required bool) error { sub, err := claims.GetSubject() if err != nil { return err diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md index c9fb829dc..7ec5ac7ea 100644 --- a/vendor/github.com/google/uuid/CHANGELOG.md +++ b/vendor/github.com/google/uuid/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [1.6.0](https://github.com/google/uuid/compare/v1.5.0...v1.6.0) (2024-01-16) + + +### Features + +* add Max UUID constant ([#149](https://github.com/google/uuid/issues/149)) ([c58770e](https://github.com/google/uuid/commit/c58770eb495f55fe2ced6284f93c5158a62e53e3)) + + +### Bug Fixes + +* fix typo in version 7 uuid documentation ([#153](https://github.com/google/uuid/issues/153)) ([016b199](https://github.com/google/uuid/commit/016b199544692f745ffc8867b914129ecb47ef06)) +* Monotonicity in UUIDv7 ([#150](https://github.com/google/uuid/issues/150)) ([a2b2b32](https://github.com/google/uuid/commit/a2b2b32373ff0b1a312b7fdf6d38a977099698a6)) + ## [1.5.0](https://github.com/google/uuid/compare/v1.4.0...v1.5.0) (2023-12-12) diff --git a/vendor/github.com/google/uuid/hash.go b/vendor/github.com/google/uuid/hash.go index b404f4bec..dc60082d3 100644 --- a/vendor/github.com/google/uuid/hash.go +++ b/vendor/github.com/google/uuid/hash.go @@ -17,6 +17,12 @@ var ( NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) Nil UUID // empty UUID, all zeros + + // The Max UUID is special form of UUID that is specified to have all 128 bits set to 1. + Max = UUID{ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + } ) // NewHash returns a new UUID derived from the hash of space concatenated with diff --git a/vendor/github.com/google/uuid/version7.go b/vendor/github.com/google/uuid/version7.go index ba9dd5eb6..3167b643d 100644 --- a/vendor/github.com/google/uuid/version7.go +++ b/vendor/github.com/google/uuid/version7.go @@ -44,7 +44,7 @@ func NewV7FromReader(r io.Reader) (UUID, error) { // makeV7 fill 48 bits time (uuid[0] - uuid[5]), set version b0111 (uuid[6]) // uuid[8] already has the right version number (Variant is 10) -// see function NewV7 and NewV7FromReader +// see function NewV7 and NewV7FromReader func makeV7(uuid []byte) { /* 0 1 2 3 @@ -52,7 +52,7 @@ func makeV7(uuid []byte) { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | unix_ts_ms | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | unix_ts_ms | ver | rand_a | + | unix_ts_ms | ver | rand_a (12 bit seq) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |var| rand_b | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -61,7 +61,7 @@ func makeV7(uuid []byte) { */ _ = uuid[15] // bounds check - t := timeNow().UnixMilli() + t, s := getV7Time() uuid[0] = byte(t >> 40) uuid[1] = byte(t >> 32) @@ -70,6 +70,35 @@ func makeV7(uuid []byte) { uuid[4] = byte(t >> 8) uuid[5] = byte(t) - uuid[6] = 0x70 | (uuid[6] & 0x0F) - // uuid[8] has already has right version + uuid[6] = 0x70 | (0x0F & byte(s>>8)) + uuid[7] = byte(s) +} + +// lastV7time is the last time we returned stored as: +// +// 52 bits of time in milliseconds since epoch +// 12 bits of (fractional nanoseconds) >> 8 +var lastV7time int64 + +const nanoPerMilli = 1000000 + +// getV7Time returns the time in milliseconds and nanoseconds / 256. +// The returned (milli << 12 + seq) is guarenteed to be greater than +// (milli << 12 + seq) returned by any previous call to getV7Time. +func getV7Time() (milli, seq int64) { + timeMu.Lock() + defer timeMu.Unlock() + + nano := timeNow().UnixNano() + milli = nano / nanoPerMilli + // Sequence number is between 0 and 3906 (nanoPerMilli>>8) + seq = (nano - milli*nanoPerMilli) >> 8 + now := milli<<12 + seq + if now <= lastV7time { + now = lastV7time + 1 + milli = now >> 12 + seq = now & 0xfff + } + lastV7time = now + return milli, seq } diff --git a/vendor/k8s.io/cloud-provider/volume/errors/errors.go b/vendor/k8s.io/cloud-provider/volume/errors/errors.go deleted file mode 100644 index 2e5adb176..000000000 --- a/vendor/k8s.io/cloud-provider/volume/errors/errors.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package errors - -import ( - k8stypes "k8s.io/apimachinery/pkg/types" -) - -// NewDeletedVolumeInUseError returns a new instance of DeletedVolumeInUseError -// error. -func NewDeletedVolumeInUseError(message string) error { - return deletedVolumeInUseError(message) -} - -type deletedVolumeInUseError string - -var _ error = deletedVolumeInUseError("") - -// IsDeletedVolumeInUse returns true if an error returned from Delete() is -// deletedVolumeInUseError -func IsDeletedVolumeInUse(err error) bool { - switch err.(type) { - case deletedVolumeInUseError: - return true - default: - return false - } -} - -func (err deletedVolumeInUseError) Error() string { - return string(err) -} - -// DanglingAttachError indicates volume is attached to a different node -// than we expected. -type DanglingAttachError struct { - msg string - CurrentNode k8stypes.NodeName - DevicePath string -} - -func (err *DanglingAttachError) Error() string { - return err.msg -} - -// NewDanglingError create a new dangling error -func NewDanglingError(msg string, node k8stypes.NodeName, devicePath string) error { - return &DanglingAttachError{ - msg: msg, - CurrentNode: node, - DevicePath: devicePath, - } -} - -// IsDanglingError returns true if an error is DanglingAttachError -func IsDanglingError(err error) bool { - switch err.(type) { - case *DanglingAttachError: - return true - default: - return false - } -} diff --git a/vendor/k8s.io/cloud-provider/volume/helpers/rounding.go b/vendor/k8s.io/cloud-provider/volume/helpers/rounding.go deleted file mode 100644 index 101815738..000000000 --- a/vendor/k8s.io/cloud-provider/volume/helpers/rounding.go +++ /dev/null @@ -1,165 +0,0 @@ -/* -Copyright 2019 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package helpers - -import ( - "fmt" - "math" - "math/bits" - - "k8s.io/apimachinery/pkg/api/resource" -) - -/* -The Cloud Provider's volume plugins provision disks for corresponding -PersistentVolumeClaims. Cloud Providers use different allocation unit for their -disk sizes. AWS allows you to specify the size as an integer amount of GiB, -while Portworx expects bytes for example. On AWS, if you want a volume of -1500MiB, the actual call to the AWS API should therefore be for a 2GiB disk. -This file contains functions that help rounding a storage request based on a -Cloud Provider's allocation unit. -*/ - -const ( - // GB - GigaByte size - GB = 1000 * 1000 * 1000 - // GiB - GibiByte size - GiB = 1024 * 1024 * 1024 - - // MB - MegaByte size - MB = 1000 * 1000 - // MiB - MebiByte size - MiB = 1024 * 1024 - - // KB - KiloByte size - KB = 1000 - // KiB - KibiByte size - KiB = 1024 -) - -// RoundUpToGiB rounds up given quantity upto chunks of GiB -func RoundUpToGiB(size resource.Quantity) (int64, error) { - return roundUpSizeInt64(size, GiB) -} - -// RoundUpToMB rounds up given quantity to chunks of MB -func RoundUpToMB(size resource.Quantity) (int64, error) { - return roundUpSizeInt64(size, MB) -} - -// RoundUpToMiB rounds up given quantity upto chunks of MiB -func RoundUpToMiB(size resource.Quantity) (int64, error) { - return roundUpSizeInt64(size, MiB) -} - -// RoundUpToKB rounds up given quantity to chunks of KB -func RoundUpToKB(size resource.Quantity) (int64, error) { - return roundUpSizeInt64(size, KB) -} - -// RoundUpToKiB rounds up given quantity to chunks of KiB -func RoundUpToKiB(size resource.Quantity) (int64, error) { - return roundUpSizeInt64(size, KiB) -} - -// RoundUpToB rounds up given quantity to chunks of bytes -func RoundUpToB(size resource.Quantity) (int64, error) { - return roundUpSizeInt64(size, 1) -} - -// RoundUpToGiBInt rounds up given quantity upto chunks of GiB. It returns an -// int instead of an int64 and an error if there's overflow -func RoundUpToGiBInt(size resource.Quantity) (int, error) { - return roundUpSizeInt(size, GiB) -} - -// RoundUpToMBInt rounds up given quantity to chunks of MB. It returns an -// int instead of an int64 and an error if there's overflow -func RoundUpToMBInt(size resource.Quantity) (int, error) { - return roundUpSizeInt(size, MB) -} - -// RoundUpToMiBInt rounds up given quantity upto chunks of MiB. It returns an -// int instead of an int64 and an error if there's overflow -func RoundUpToMiBInt(size resource.Quantity) (int, error) { - return roundUpSizeInt(size, MiB) -} - -// RoundUpToKBInt rounds up given quantity to chunks of KB. It returns an -// int instead of an int64 and an error if there's overflow -func RoundUpToKBInt(size resource.Quantity) (int, error) { - return roundUpSizeInt(size, KB) -} - -// RoundUpToKiBInt rounds up given quantity upto chunks of KiB. It returns an -// int instead of an int64 and an error if there's overflow -func RoundUpToKiBInt(size resource.Quantity) (int, error) { - return roundUpSizeInt(size, KiB) -} - -// RoundUpToGiBInt32 rounds up given quantity up to chunks of GiB. It returns an -// int32 instead of an int64 and an error if there's overflow -func RoundUpToGiBInt32(size resource.Quantity) (int32, error) { - return roundUpSizeInt32(size, GiB) -} - -// roundUpSizeInt calculates how many allocation units are needed to accommodate -// a volume of a given size. It returns an int and an error if there's overflow -func roundUpSizeInt(size resource.Quantity, allocationUnitBytes int64) (int, error) { - if bits.UintSize == 32 { - res, err := roundUpSizeInt32(size, allocationUnitBytes) - return int(res), err - } - res, err := roundUpSizeInt64(size, allocationUnitBytes) - return int(res), err -} - -// roundUpSizeInt32 calculates how many allocation units are needed to accommodate -// a volume of a given size. It returns an int32 and an error if there's overflow -func roundUpSizeInt32(size resource.Quantity, allocationUnitBytes int64) (int32, error) { - roundedUpInt32, err := roundUpSizeInt64(size, allocationUnitBytes) - if err != nil { - return 0, err - } - if roundedUpInt32 > math.MaxInt32 { - return 0, fmt.Errorf("quantity %s is too great, overflows int32", size.String()) - } - return int32(roundedUpInt32), nil -} - -// roundUpSizeInt64 calculates how many allocation units are needed to accommodate -// a volume of a given size. It returns an int64 and an error if there's overflow -func roundUpSizeInt64(size resource.Quantity, allocationUnitBytes int64) (int64, error) { - // Use CmpInt64() to find out if the value of "size" would overflow an - // int64 and therefore have Value() return a wrong result. Then, retrieve - // the value as int64 and perform the rounding. - // It's not convenient to use AsScale() and related functions as they don't - // support BinarySI format, nor can we use AsInt64() directly since it's - // only implemented for int64 scaled numbers (int64Amount). - - // CmpInt64() actually returns 0 when comparing an amount bigger than MaxInt64. - if size.CmpInt64(math.MaxInt64) >= 0 { - return 0, fmt.Errorf("quantity %s is too great, overflows int64", size.String()) - } - volumeSizeBytes := size.Value() - - roundedUp := volumeSizeBytes / allocationUnitBytes - if volumeSizeBytes%allocationUnitBytes > 0 { - roundedUp++ - } - return roundedUp, nil -} diff --git a/vendor/k8s.io/cloud-provider/volume/helpers/zones.go b/vendor/k8s.io/cloud-provider/volume/helpers/zones.go deleted file mode 100644 index ff3a39284..000000000 --- a/vendor/k8s.io/cloud-provider/volume/helpers/zones.go +++ /dev/null @@ -1,313 +0,0 @@ -/* -Copyright 2019 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package helpers - -import ( - "fmt" - "hash/fnv" - "math/rand" - "strconv" - "strings" - - v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/sets" - cloudvolume "k8s.io/cloud-provider/volume" - "k8s.io/klog/v2" -) - -// LabelZonesToSet converts a PV label value from string containing a delimited list of zones to set -func LabelZonesToSet(labelZonesValue string) (sets.String, error) { - return stringToSet(labelZonesValue, cloudvolume.LabelMultiZoneDelimiter) -} - -// ZonesSetToLabelValue converts zones set to label value -func ZonesSetToLabelValue(strSet sets.String) string { - return strings.Join(strSet.UnsortedList(), cloudvolume.LabelMultiZoneDelimiter) -} - -// ZonesToSet converts a string containing a comma separated list of zones to set -func ZonesToSet(zonesString string) (sets.String, error) { - zones, err := stringToSet(zonesString, ",") - if err != nil { - return nil, fmt.Errorf("error parsing zones %s, must be strings separated by commas: %v", zonesString, err) - } - return zones, nil -} - -// StringToSet converts a string containing list separated by specified delimiter to a set -func stringToSet(str, delimiter string) (sets.String, error) { - zonesSlice := strings.Split(str, delimiter) - zonesSet := make(sets.String) - for _, zone := range zonesSlice { - trimmedZone := strings.TrimSpace(zone) - if trimmedZone == "" { - return make(sets.String), fmt.Errorf( - "%q separated list (%q) must not contain an empty string", - delimiter, - str) - } - zonesSet.Insert(trimmedZone) - } - return zonesSet, nil -} - -// LabelZonesToList converts a PV label value from string containing a delimited list of zones to list -func LabelZonesToList(labelZonesValue string) ([]string, error) { - return stringToList(labelZonesValue, cloudvolume.LabelMultiZoneDelimiter) -} - -// StringToList converts a string containing list separated by specified delimiter to a list -func stringToList(str, delimiter string) ([]string, error) { - zonesSlice := make([]string, 0) - for _, zone := range strings.Split(str, delimiter) { - trimmedZone := strings.TrimSpace(zone) - if trimmedZone == "" { - return nil, fmt.Errorf( - "%q separated list (%q) must not contain an empty string", - delimiter, - str) - } - zonesSlice = append(zonesSlice, trimmedZone) - } - return zonesSlice, nil -} - -// SelectZoneForVolume is a wrapper around SelectZonesForVolume -// to select a single zone for a volume based on parameters -func SelectZoneForVolume(zoneParameterPresent, zonesParameterPresent bool, zoneParameter string, zonesParameter, zonesWithNodes sets.String, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm, pvcName string) (string, error) { - zones, err := SelectZonesForVolume(zoneParameterPresent, zonesParameterPresent, zoneParameter, zonesParameter, zonesWithNodes, node, allowedTopologies, pvcName, 1) - if err != nil { - return "", err - } - zone, ok := zones.PopAny() - if !ok { - return "", fmt.Errorf("could not determine a zone to provision volume in") - } - return zone, nil -} - -// SelectZonesForVolume selects zones for a volume based on several factors: -// node.zone, allowedTopologies, zone/zones parameters from storageclass, -// zones with active nodes from the cluster. The number of zones = replicas. -func SelectZonesForVolume(zoneParameterPresent, zonesParameterPresent bool, zoneParameter string, zonesParameter, zonesWithNodes sets.String, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm, pvcName string, numReplicas uint32) (sets.String, error) { - if zoneParameterPresent && zonesParameterPresent { - return nil, fmt.Errorf("both zone and zones StorageClass parameters must not be used at the same time") - } - - var zoneFromNode string - // pick one zone from node if present - if node != nil { - // VolumeScheduling implicit since node is not nil - if zoneParameterPresent || zonesParameterPresent { - return nil, fmt.Errorf("zone[s] cannot be specified in StorageClass if VolumeBindingMode is set to WaitForFirstConsumer. Please specify allowedTopologies in StorageClass for constraining zones") - } - - // pick node's zone for one of the replicas - var ok bool - zoneFromNode, ok = node.ObjectMeta.Labels[v1.LabelTopologyZone] - if !ok { - zoneFromNode, ok = node.ObjectMeta.Labels[v1.LabelFailureDomainBetaZone] - if !ok { - return nil, fmt.Errorf("Either %s or %s Label for node missing", v1.LabelTopologyZone, v1.LabelFailureDomainBetaZone) - } - } - // if single replica volume and node with zone found, return immediately - if numReplicas == 1 { - return sets.NewString(zoneFromNode), nil - } - } - - // pick zone from allowedZones if specified - allowedZones, err := ZonesFromAllowedTopologies(allowedTopologies) - if err != nil { - return nil, err - } - - if (len(allowedTopologies) > 0) && (allowedZones.Len() == 0) { - return nil, fmt.Errorf("no matchLabelExpressions with %s key found in allowedTopologies. Please specify matchLabelExpressions with %s key", v1.LabelTopologyZone, v1.LabelTopologyZone) - } - - if allowedZones.Len() > 0 { - // VolumeScheduling implicit since allowedZones present - if zoneParameterPresent || zonesParameterPresent { - return nil, fmt.Errorf("zone[s] cannot be specified in StorageClass if allowedTopologies specified") - } - // scheduler will guarantee if node != null above, zoneFromNode is member of allowedZones. - // so if zoneFromNode != "", we can safely assume it is part of allowedZones. - zones, err := chooseZonesForVolumeIncludingZone(allowedZones, pvcName, zoneFromNode, numReplicas) - if err != nil { - return nil, fmt.Errorf("cannot process zones in allowedTopologies: %v", err) - } - return zones, nil - } - - // pick zone from parameters if present - if zoneParameterPresent { - if numReplicas > 1 { - return nil, fmt.Errorf("zone cannot be specified if desired number of replicas for pv is greather than 1. Please specify zones or allowedTopologies to specify desired zones") - } - return sets.NewString(zoneParameter), nil - } - - if zonesParameterPresent { - if uint32(zonesParameter.Len()) < numReplicas { - return nil, fmt.Errorf("not enough zones found in zones parameter to provision a volume with %d replicas. Found %d zones, need %d zones", numReplicas, zonesParameter.Len(), numReplicas) - } - // directly choose from zones parameter; no zone from node need to be considered - return ChooseZonesForVolume(zonesParameter, pvcName, numReplicas), nil - } - - // pick zone from zones with nodes - if zonesWithNodes.Len() > 0 { - // If node != null (and thus zoneFromNode != ""), zoneFromNode will be member of zonesWithNodes - zones, err := chooseZonesForVolumeIncludingZone(zonesWithNodes, pvcName, zoneFromNode, numReplicas) - if err != nil { - return nil, fmt.Errorf("cannot process zones where nodes exist in the cluster: %v", err) - } - return zones, nil - } - return nil, fmt.Errorf("cannot determine zones to provision volume in") -} - -// ZonesFromAllowedTopologies returns a list of zones specified in allowedTopologies -func ZonesFromAllowedTopologies(allowedTopologies []v1.TopologySelectorTerm) (sets.String, error) { - zones := make(sets.String) - for _, term := range allowedTopologies { - for _, exp := range term.MatchLabelExpressions { - if exp.Key == v1.LabelTopologyZone || exp.Key == v1.LabelFailureDomainBetaZone { - for _, value := range exp.Values { - zones.Insert(value) - } - } else { - return nil, fmt.Errorf("unsupported key found in matchLabelExpressions: %s", exp.Key) - } - } - } - return zones, nil -} - -// chooseZonesForVolumeIncludingZone is a wrapper around ChooseZonesForVolume that ensures zoneToInclude is chosen -// zoneToInclude can either be empty in which case it is ignored. If non-empty, zoneToInclude is expected to be member of zones. -// numReplicas is expected to be > 0 and <= zones.Len() -func chooseZonesForVolumeIncludingZone(zones sets.String, pvcName, zoneToInclude string, numReplicas uint32) (sets.String, error) { - if numReplicas == 0 { - return nil, fmt.Errorf("invalid number of replicas passed") - } - if uint32(zones.Len()) < numReplicas { - return nil, fmt.Errorf("not enough zones found to provision a volume with %d replicas. Need at least %d distinct zones for a volume with %d replicas", numReplicas, numReplicas, numReplicas) - } - if zoneToInclude != "" && !zones.Has(zoneToInclude) { - return nil, fmt.Errorf("zone to be included: %s needs to be member of set: %v", zoneToInclude, zones) - } - if uint32(zones.Len()) == numReplicas { - return zones, nil - } - if zoneToInclude != "" { - zones.Delete(zoneToInclude) - numReplicas = numReplicas - 1 - } - zonesChosen := ChooseZonesForVolume(zones, pvcName, numReplicas) - if zoneToInclude != "" { - zonesChosen.Insert(zoneToInclude) - } - return zonesChosen, nil -} - -// ChooseZonesForVolume is identical to ChooseZoneForVolume, but selects a multiple zones, for multi-zone disks. -func ChooseZonesForVolume(zones sets.String, pvcName string, numZones uint32) sets.String { - // No zones available, return empty set. - replicaZones := sets.NewString() - if zones.Len() == 0 { - return replicaZones - } - - // We create the volume in a zone determined by the name - // Eventually the scheduler will coordinate placement into an available zone - hash, index := getPVCNameHashAndIndexOffset(pvcName) - - // Zones.List returns zones in a consistent order (sorted) - // We do have a potential failure case where volumes will not be properly spread, - // if the set of zones changes during StatefulSet volume creation. However, this is - // probably relatively unlikely because we expect the set of zones to be essentially - // static for clusters. - // Hopefully we can address this problem if/when we do full scheduler integration of - // PVC placement (which could also e.g. avoid putting volumes in overloaded or - // unhealthy zones) - zoneSlice := zones.List() - - startingIndex := index * numZones - for index = startingIndex; index < startingIndex+numZones; index++ { - zone := zoneSlice[(hash+index)%uint32(len(zoneSlice))] - replicaZones.Insert(zone) - } - - klog.V(2).Infof("Creating volume for replicated PVC %q; chosen zones=%q from zones=%q", - pvcName, replicaZones.UnsortedList(), zoneSlice) - return replicaZones -} - -func getPVCNameHashAndIndexOffset(pvcName string) (hash uint32, index uint32) { - if pvcName == "" { - // We should always be called with a name; this shouldn't happen - klog.Warningf("No name defined during volume create; choosing random zone") - - hash = rand.Uint32() - } else { - hashString := pvcName - - // Heuristic to make sure that volumes in a StatefulSet are spread across zones - // StatefulSet PVCs are (currently) named ClaimName-StatefulSetName-Id, - // where Id is an integer index. - // Note though that if a StatefulSet pod has multiple claims, we need them to be - // in the same zone, because otherwise the pod will be unable to mount both volumes, - // and will be unschedulable. So we hash _only_ the "StatefulSetName" portion when - // it looks like `ClaimName-StatefulSetName-Id`. - // We continue to round-robin volume names that look like `Name-Id` also; this is a useful - // feature for users that are creating statefulset-like functionality without using statefulsets. - lastDash := strings.LastIndexByte(pvcName, '-') - if lastDash != -1 { - statefulsetIDString := pvcName[lastDash+1:] - statefulsetID, err := strconv.ParseUint(statefulsetIDString, 10, 32) - if err == nil { - // Offset by the statefulsetID, so we round-robin across zones - index = uint32(statefulsetID) - // We still hash the volume name, but only the prefix - hashString = pvcName[:lastDash] - - // In the special case where it looks like `ClaimName-StatefulSetName-Id`, - // hash only the StatefulSetName, so that different claims on the same StatefulSet - // member end up in the same zone. - // Note that StatefulSetName (and ClaimName) might themselves both have dashes. - // We actually just take the portion after the final - of ClaimName-StatefulSetName. - // For our purposes it doesn't much matter (just suboptimal spreading). - lastDash := strings.LastIndexByte(hashString, '-') - if lastDash != -1 { - hashString = hashString[lastDash+1:] - } - - klog.V(2).Infof("Detected StatefulSet-style volume name %q; index=%d", pvcName, index) - } - } - - // We hash the (base) volume name, so we don't bias towards the first N zones - h := fnv.New32() - h.Write([]byte(hashString)) - hash = h.Sum32() - } - - return hash, index -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 98fe6087a..73d4e5a92 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -11,7 +11,7 @@ github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage github.com/Azure/azure-sdk-for-go/storage github.com/Azure/azure-sdk-for-go/version -# github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 +# github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/azcore github.com/Azure/azure-sdk-for-go/sdk/azcore/arm @@ -34,10 +34,11 @@ github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming github.com/Azure/azure-sdk-for-go/sdk/azcore/to github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing -# github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0 +# github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/azidentity -# github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 +github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal +# github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/internal/diag github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo @@ -46,13 +47,13 @@ github.com/Azure/azure-sdk-for-go/sdk/internal/log github.com/Azure/azure-sdk-for-go/sdk/internal/poller github.com/Azure/azure-sdk-for-go/sdk/internal/temporal github.com/Azure/azure-sdk-for-go/sdk/internal/uuid -# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.4.0 +# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.5.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 # github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry -# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.6.0 +# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.7.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 # github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault v1.4.0 @@ -113,7 +114,7 @@ github.com/Azure/go-autorest/logger # github.com/Azure/go-autorest/tracing v0.6.0 ## explicit; go 1.12 github.com/Azure/go-autorest/tracing -# github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0 +# github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 ## explicit; go 1.18 github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential @@ -177,7 +178,7 @@ github.com/distribution/reference ## explicit; go 1.13 github.com/emicklei/go-restful/v3 github.com/emicklei/go-restful/v3/log -# github.com/evanphx/json-patch v5.7.0+incompatible +# github.com/evanphx/json-patch v5.9.0+incompatible ## explicit github.com/evanphx/json-patch # github.com/felixge/httpsnoop v1.0.4 @@ -221,7 +222,7 @@ github.com/gogo/protobuf/sortkeys # github.com/golang-jwt/jwt/v4 v4.5.0 ## explicit; go 1.16 github.com/golang-jwt/jwt/v4 -# github.com/golang-jwt/jwt/v5 v5.0.0 +# github.com/golang-jwt/jwt/v5 v5.2.0 ## explicit; go 1.18 github.com/golang-jwt/jwt/v5 # github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da @@ -283,7 +284,7 @@ github.com/google/gofuzz/bytesource # github.com/google/pprof v0.0.0-20230602010524-ada837c32108 ## explicit; go 1.19 github.com/google/pprof/profile -# github.com/google/uuid v1.5.0 +# github.com/google/uuid v1.6.0 ## explicit github.com/google/uuid # github.com/gorilla/websocket v1.5.0 @@ -392,7 +393,7 @@ github.com/pborman/uuid # github.com/pelletier/go-toml v1.9.5 ## explicit; go 1.12 github.com/pelletier/go-toml -# github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 +# github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c ## explicit; go 1.14 github.com/pkg/browser # github.com/pkg/errors v0.9.1 @@ -753,7 +754,7 @@ gopkg.in/yaml.v2 # gopkg.in/yaml.v3 v3.0.1 ## explicit gopkg.in/yaml.v3 -# k8s.io/api v0.29.0 => k8s.io/api v0.29.0 +# k8s.io/api v0.29.2 => k8s.io/api v0.29.0 ## explicit; go 1.21 k8s.io/api/admission/v1 k8s.io/api/admission/v1beta1 @@ -814,7 +815,7 @@ k8s.io/api/storage/v1beta1 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/features -# k8s.io/apimachinery v0.29.0 => k8s.io/apimachinery v0.29.0 +# k8s.io/apimachinery v0.29.2 => k8s.io/apimachinery v0.29.0 ## explicit; go 1.21 k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors @@ -1025,7 +1026,7 @@ k8s.io/apiserver/plugin/pkg/audit/truncate k8s.io/apiserver/plugin/pkg/audit/webhook k8s.io/apiserver/plugin/pkg/authenticator/token/webhook k8s.io/apiserver/plugin/pkg/authorizer/webhook -# k8s.io/client-go v0.29.0 => k8s.io/client-go v0.29.0 +# k8s.io/client-go v0.29.2 => k8s.io/client-go v0.29.0 ## explicit; go 1.21 k8s.io/client-go/applyconfigurations/admissionregistration/v1 k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1 @@ -1364,9 +1365,6 @@ k8s.io/cloud-provider/names k8s.io/cloud-provider/node/helpers k8s.io/cloud-provider/options k8s.io/cloud-provider/service/helpers -k8s.io/cloud-provider/volume -k8s.io/cloud-provider/volume/errors -k8s.io/cloud-provider/volume/helpers # k8s.io/component-base v0.29.0 => k8s.io/component-base v0.29.0 ## explicit; go 1.21 k8s.io/component-base/cli/flag @@ -1554,7 +1552,7 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client -# sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240108181414-3a9c6084f8a5 +# sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240220055818-b76605c9c708 ## explicit; go 1.21 sigs.k8s.io/cloud-provider-azure/pkg/azureclients sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient @@ -1607,9 +1605,12 @@ sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/securitygroup sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine sigs.k8s.io/cloud-provider-azure/pkg/retry sigs.k8s.io/cloud-provider-azure/pkg/util/deepcopy +sigs.k8s.io/cloud-provider-azure/pkg/util/sets +sigs.k8s.io/cloud-provider-azure/pkg/util/string sigs.k8s.io/cloud-provider-azure/pkg/util/taints +sigs.k8s.io/cloud-provider-azure/pkg/util/vm sigs.k8s.io/cloud-provider-azure/pkg/version -# sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240105075710-c4d4895a970b +# sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20240218020800-ba9f211f36bf ## explicit; go 1.20 sigs.k8s.io/cloud-provider-azure/pkg/azclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient @@ -1651,8 +1652,8 @@ sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworklinkclient -# sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231208022044-b9ede3fc98e9 -## explicit; go 1.20 +# sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20240220055818-b76605c9c708 +## explicit; go 1.21 sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader # sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd ## explicit; go 1.18 diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go index 4deeb1bb2..46a66e94f 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go @@ -65,5 +65,5 @@ func (config *AzureAuthConfig) GetAzureFederatedTokenFile() (string, bool) { if clientCertPath := os.Getenv(utils.AzureFederatedTokenFile); clientCertPath != "" { return clientCertPath, true } - return config.AADClientCertPath, config.UseFederatedWorkloadIdentityExtension + return config.AADFederatedTokenFile, config.UseFederatedWorkloadIdentityExtension } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/custom.go new file mode 100644 index 000000000..e8d8af834 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/custom.go @@ -0,0 +1,45 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package diskclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + armcompute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +const PatchOperationName = "DisksClient.Patch" + +func (client *Client) Patch(ctx context.Context, resourceGroupName string, resourceName string, parameters armcompute.DiskUpdate) (result *armcompute.Disk, err error) { + ctx = utils.ContextWithClientName(ctx, "DisksClient") + ctx = utils.ContextWithRequestMethod(ctx, "Patch") + ctx = utils.ContextWithResourceGroupName(ctx, resourceGroupName) + ctx = utils.ContextWithSubscriptionID(ctx, client.subscriptionID) + ctx, endSpan := runtime.StartSpan(ctx, CreateOrUpdateOperationName, client.tracer, nil) + defer endSpan(err) + resp, err := utils.NewPollerWrapper(client.DisksClient.BeginUpdate(ctx, resourceGroupName, resourceName, parameters, nil)).WaitforPollerResp(ctx) + if err != nil { + return nil, err + } + if resp != nil { + return &resp.Disk, nil + } + return nil, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/interface.go index af3d0a903..9b9f85e10 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/interface.go @@ -18,6 +18,8 @@ limitations under the License. package diskclient import ( + "context" + armcompute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" @@ -29,4 +31,5 @@ type Interface interface { utils.CreateOrUpdateFunc[armcompute.Disk] utils.DeleteFunc[armcompute.Disk] utils.ListFunc[armcompute.Disk] + Patch(ctx context.Context, resourceGroupName string, resourceName string, parameters armcompute.DiskUpdate) (result *armcompute.Disk, err error) } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go index d2b159e57..f51b85dc8 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go @@ -79,6 +79,7 @@ type ClientFactory interface { GetSecretClient() secretclient.Interface GetSecurityGroupClient() securitygroupclient.Interface GetSnapshotClient() snapshotclient.Interface + GetSnapshotClientForSub(subscriptionID string) (snapshotclient.Interface, error) GetSSHPublicKeyResourceClient() sshpublickeyresourceclient.Interface GetSubnetClient() subnetclient.Interface GetVaultClient() vaultclient.Interface diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go index c1aed81d6..1c2f36ee1 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go @@ -86,7 +86,7 @@ type ClientFactoryImpl struct { routetableclientInterface routetableclient.Interface secretclientInterface secretclient.Interface securitygroupclientInterface securitygroupclient.Interface - snapshotclientInterface snapshotclient.Interface + snapshotclientInterface sync.Map sshpublickeyresourceclientInterface sshpublickeyresourceclient.Interface subnetclientInterface subnetclient.Interface vaultclientInterface vaultclient.Interface @@ -247,7 +247,7 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c } //initialize snapshotclient - factory.snapshotclientInterface, err = factory.createSnapshotClient(config.SubscriptionID) + _, err = factory.GetSnapshotClientForSub(config.SubscriptionID) if err != nil { return nil, err } @@ -888,7 +888,24 @@ func (factory *ClientFactoryImpl) createSnapshotClient(subscription string) (sna } func (factory *ClientFactoryImpl) GetSnapshotClient() snapshotclient.Interface { - return factory.snapshotclientInterface + clientImp, _ := factory.snapshotclientInterface.Load(strings.ToLower(factory.facotryConfig.SubscriptionID)) + return clientImp.(snapshotclient.Interface) +} +func (factory *ClientFactoryImpl) GetSnapshotClientForSub(subscriptionID string) (snapshotclient.Interface, error) { + if subscriptionID == "" { + subscriptionID = factory.facotryConfig.SubscriptionID + } + clientImp, loaded := factory.snapshotclientInterface.Load(strings.ToLower(subscriptionID)) + if loaded { + return clientImp.(snapshotclient.Interface), nil + } + //It's not thread safe, but it's ok for now. because it will be called once. + clientImp, err := factory.createSnapshotClient(subscriptionID) + if err != nil { + return nil, err + } + factory.snapshotclientInterface.Store(strings.ToLower(subscriptionID), clientImp) + return clientImp.(snapshotclient.Interface), nil } func (factory *ClientFactoryImpl) createSSHPublicKeyResourceClient(subscription string) (sshpublickeyresourceclient.Interface, error) { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/mock_azclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/mock_azclient/interface.go index 763b5b338..8e0445440 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/mock_azclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/mock_azclient/interface.go @@ -482,6 +482,21 @@ func (mr *MockClientFactoryMockRecorder) GetSnapshotClient() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSnapshotClient", reflect.TypeOf((*MockClientFactory)(nil).GetSnapshotClient)) } +// GetSnapshotClientForSub mocks base method. +func (m *MockClientFactory) GetSnapshotClientForSub(arg0 string) (snapshotclient.Interface, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSnapshotClientForSub", arg0) + ret0, _ := ret[0].(snapshotclient.Interface) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSnapshotClientForSub indicates an expected call of GetSnapshotClientForSub. +func (mr *MockClientFactoryMockRecorder) GetSnapshotClientForSub(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSnapshotClientForSub", reflect.TypeOf((*MockClientFactory)(nil).GetSnapshotClientForSub), arg0) +} + // GetSubnetClient mocks base method. func (m *MockClientFactory) GetSubnetClient() subnetclient.Interface { m.ctrl.T.Helper() diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/snapshotclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/snapshotclient/interface.go index 1cae1fb80..b6452e6c3 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/snapshotclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/snapshotclient/interface.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" ) -// +azure:client:verbs=get;createorupdate;delete,resource=Snapshot,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5,packageAlias=armcompute,clientName=SnapshotsClient,expand=false,rateLimitKey=snapshotRateLimit +// +azure:client:verbs=get;createorupdate;delete,resource=Snapshot,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5,packageAlias=armcompute,clientName=SnapshotsClient,expand=false,rateLimitKey=snapshotRateLimit,crossSubFactory=true type Interface interface { utils.GetFunc[armcompute.Snapshot] utils.CreateOrUpdateFunc[armcompute.Snapshot] diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/interface.go index 611a5ef5b..ade11e4e3 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/interface.go @@ -35,4 +35,5 @@ type Interface interface { InstanceView(ctx context.Context, resourceGroupName string, vmName string) (*armcompute.VirtualMachineInstanceView, error) ListVMInstanceView(ctx context.Context, resourceGroupName string) (result []*armcompute.VirtualMachine, rerr error) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmName string, parameters armcompute.VirtualMachine, options *armcompute.VirtualMachinesClientBeginCreateOrUpdateOptions) (*runtime.Poller[armcompute.VirtualMachinesClientCreateOrUpdateResponse], error) + BeginAttachDetachDataDisks(ctx context.Context, resourceGroupName string, vmName string, parameters armcompute.AttachDetachDataDisksRequest, options *armcompute.VirtualMachinesClientBeginAttachDetachDataDisksOptions) (*runtime.Poller[armcompute.VirtualMachinesClientAttachDetachDataDisksResponse], error) } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/fileclient/azure_fileclient.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/fileclient/azure_fileclient.go index f66f1a40a..fc79f66c3 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/fileclient/azure_fileclient.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/fileclient/azure_fileclient.go @@ -93,9 +93,10 @@ func (c *Client) CreateFileShare(ctx context.Context, resourceGroupName, account if shareOptions == nil { return storage.FileShare{}, fmt.Errorf("share options is nil") } - quota := int32(shareOptions.RequestGiB) - fileShareProperties := &storage.FileShareProperties{ - ShareQuota: "a, + fileShareProperties := &storage.FileShareProperties{} + if shareOptions.RequestGiB > 0 { + quota := int32(shareOptions.RequestGiB) + fileShareProperties.ShareQuota = "a } if shareOptions.Protocol == storage.EnabledProtocolsNFS { fileShareProperties.EnabledProtocols = shareOptions.Protocol diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go index 3b2448658..75bd1708b 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go @@ -113,8 +113,8 @@ const ( // StrRawVersion is the raw version string StrRawVersion string = "raw" - // VirtualMachineScaleSetsDeallocating indicates VMSS instances are in Deallocating state. - VirtualMachineScaleSetsDeallocating = "Deallocating" + // ProvisionStateDeleting indicates VMSS instances are in Deleting state. + ProvisionStateDeleting = "Deleting" // VmssMachineIDTemplate is the vmss manchine ID template VmssMachineIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s" // VMSetCIDRIPV4TagKey specifies the node ipv4 CIDR mask of the instances on the VMSS or VMAS @@ -132,6 +132,8 @@ const ( ProvisioningStateDeleting = "Deleting" // ProvisioningStateSucceeded ... ProvisioningStateSucceeded = "Succeeded" + // ProvisioningStateUnknown is the unknown provisioning state + ProvisioningStateUnknown = "Unknown" ) // cache @@ -572,3 +574,13 @@ const ( ClusterServiceLoadBalancerHealthProbeDefaultPath = "/healthz" SharedProbeName = "cluster-service-shared-health-probe" ) + +// VM power state +const ( + VMPowerStatePrefix = "PowerState/" + VMPowerStateStopped = "stopped" + VMPowerStateStopping = "stopping" + VMPowerStateDeallocated = "deallocated" + VMPowerStateDeallocating = "deallocating" + VMPowerStateUnknown = "unknown" +) diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go index 83e1b73fc..a44fccfbe 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go @@ -31,10 +31,10 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/informers" clientset "k8s.io/client-go/kubernetes" @@ -48,7 +48,6 @@ import ( cloudnodeutil "k8s.io/cloud-provider/node/helpers" nodeutil "k8s.io/component-helpers/node/util" "k8s.io/klog/v2" - "sigs.k8s.io/yaml" "sigs.k8s.io/cloud-provider-azure/pkg/azclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader" @@ -76,10 +75,14 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/zoneclient" + + "sigs.k8s.io/yaml" + azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" ratelimitconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/retry" + utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" "sigs.k8s.io/cloud-provider-azure/pkg/util/taints" ) @@ -331,11 +334,11 @@ type MultipleStandardLoadBalancerConfigurationSpec struct { // MultipleStandardLoadBalancerConfigurationStatus stores the properties regarding multiple standard load balancers. type MultipleStandardLoadBalancerConfigurationStatus struct { // ActiveServices stores the services that are supposed to use the load balancer. - ActiveServices sets.Set[string] `json:"activeServices" yaml:"activeServices"` + ActiveServices *utilsets.IgnoreCaseSet `json:"activeServices" yaml:"activeServices"` // ActiveNodes stores the nodes that are supposed to be in the load balancer. // It will be used in EnsureHostsInPool to make sure the given ones are in the backend pool. - ActiveNodes sets.Set[string] `json:"activeNodes" yaml:"activeNodes"` + ActiveNodes *utilsets.IgnoreCaseSet `json:"activeNodes" yaml:"activeNodes"` } // HasExtendedLocation returns true if extendedlocation prop are specified. @@ -349,7 +352,6 @@ var ( _ cloudprovider.LoadBalancer = (*Cloud)(nil) _ cloudprovider.Routes = (*Cloud)(nil) _ cloudprovider.Zones = (*Cloud)(nil) - _ cloudprovider.PVLabeler = (*Cloud)(nil) ) // Cloud holds the config and clients @@ -393,17 +395,17 @@ type Cloud struct { // Lock for access to node caches, includes nodeZones, nodeResourceGroups, and unmanagedNodes. nodeCachesLock sync.RWMutex // nodeNames holds current nodes for tracking added nodes in VM caches. - nodeNames sets.Set[string] + nodeNames *utilsets.IgnoreCaseSet // nodeZones is a mapping from Zone to a sets.Set[string] of Node's names in the Zone // it is updated by the nodeInformer - nodeZones map[string]sets.Set[string] + nodeZones map[string]*utilsets.IgnoreCaseSet // nodeResourceGroups holds nodes external resource groups nodeResourceGroups map[string]string // unmanagedNodes holds a list of nodes not managed by Azure cloud provider. - unmanagedNodes sets.Set[string] + unmanagedNodes *utilsets.IgnoreCaseSet // excludeLoadBalancerNodes holds a list of nodes that should be excluded from LoadBalancer. - excludeLoadBalancerNodes sets.Set[string] - nodePrivateIPs map[string]sets.Set[string] + excludeLoadBalancerNodes *utilsets.IgnoreCaseSet + nodePrivateIPs map[string]*utilsets.IgnoreCaseSet nodePrivateIPToNodeNameMap map[string]string // nodeInformerSynced is for determining if the informer has synced. nodeInformerSynced cache.InformerSynced @@ -441,8 +443,7 @@ type Cloud struct { // node-sync-loop routine and service-reconcile routine should not update LoadBalancer at the same time serviceReconcileLock sync.Mutex - *ManagedDiskController - + lockMap *LockMap // multipleStandardLoadBalancerConfigurationsSynced make sure the `reconcileMultipleStandardLoadBalancerConfigurations` // runs only once every time the cloud provide restarts. multipleStandardLoadBalancerConfigurationsSynced bool @@ -457,13 +458,13 @@ type Cloud struct { // NewCloud returns a Cloud with initialized clients func NewCloud(ctx context.Context, config *Config, callFromCCM bool) (cloudprovider.Interface, error) { az := &Cloud{ - nodeNames: sets.New[string](), - nodeZones: map[string]sets.Set[string]{}, + nodeNames: utilsets.NewString(), + nodeZones: map[string]*utilsets.IgnoreCaseSet{}, nodeResourceGroups: map[string]string{}, - unmanagedNodes: sets.New[string](), + unmanagedNodes: utilsets.NewString(), routeCIDRs: map[string]string{}, - excludeLoadBalancerNodes: sets.New[string](), - nodePrivateIPs: map[string]sets.Set[string]{}, + excludeLoadBalancerNodes: utilsets.NewString(), + nodePrivateIPs: map[string]*utilsets.IgnoreCaseSet{}, nodePrivateIPToNodeNameMap: map[string]string{}, } @@ -473,7 +474,9 @@ func NewCloud(ctx context.Context, config *Config, callFromCCM bool) (cloudprovi } az.ipv6DualStackEnabled = true - + if az.lockMap == nil { + az.lockMap = newLockMap() + } return az, nil } @@ -567,7 +570,7 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, // The default cloud config type is cloudConfigTypeMerge. config.CloudConfigType = configloader.CloudConfigTypeMerge } else { - supportedCloudConfigTypes := sets.New( + supportedCloudConfigTypes := utilsets.NewString( string(configloader.CloudConfigTypeMerge), string(configloader.CloudConfigTypeFile), string(configloader.CloudConfigTypeSecret)) @@ -581,7 +584,7 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, strings.EqualFold(config.LoadBalancerBackendPoolConfigurationType, consts.LoadBalancerBackendPoolConfigurationTypePODIP) { config.LoadBalancerBackendPoolConfigurationType = consts.LoadBalancerBackendPoolConfigurationTypeNodeIPConfiguration } else { - supportedLoadBalancerBackendPoolConfigurationTypes := sets.New( + supportedLoadBalancerBackendPoolConfigurationTypes := utilsets.NewString( strings.ToLower(consts.LoadBalancerBackendPoolConfigurationTypeNodeIPConfiguration), strings.ToLower(consts.LoadBalancerBackendPoolConfigurationTypeNodeIP), strings.ToLower(consts.LoadBalancerBackendPoolConfigurationTypePODIP)) @@ -593,7 +596,7 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, if config.ClusterServiceLoadBalancerHealthProbeMode == "" { config.ClusterServiceLoadBalancerHealthProbeMode = consts.ClusterServiceLoadBalancerHealthProbeModeServiceNodePort } else { - supportedClusterServiceLoadBalancerHealthProbeModes := sets.New( + supportedClusterServiceLoadBalancerHealthProbeModes := utilsets.NewString( strings.ToLower(consts.ClusterServiceLoadBalancerHealthProbeModeServiceNodePort), strings.ToLower(consts.ClusterServiceLoadBalancerHealthProbeModeShared), ) @@ -623,6 +626,7 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, return err } + az.lockMap = newLockMap() az.Config = *config az.Environment = *env az.ResourceRequestBackoff = resourceRequestBackoff @@ -728,9 +732,6 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, return err } - if err := InitDiskControllers(az); err != nil { - return err - } // Common controller contains the function // needed by both blob disk and managed disk controllers qps := float32(ratelimitconfig.DefaultAtachDetachDiskQPS) @@ -741,14 +742,6 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, } klog.V(2).Infof("attach/detach disk operation rate limit QPS: %f, Bucket: %d", qps, bucket) - common := &controllerCommon{ - cloud: az, - lockMap: newLockMap(), - AttachDetachInitialDelayInMs: defaultAttachDetachInitialDelayInMs, - } - - az.ManagedDiskController = &ManagedDiskController{common} - // updating routes and syncing zones only in CCM if callFromCCM { // start delayed route updater. @@ -795,8 +788,8 @@ func (az *Cloud) checkEnableMultipleStandardLoadBalancers() error { return fmt.Errorf("multiple standard load balancers cannot be used with backend pool type %s", consts.LoadBalancerBackendPoolConfigurationTypeNodeIPConfiguration) } - names := sets.New[string]() - primaryVMSets := sets.New[string]() + names := utilsets.NewString() + primaryVMSets := utilsets.NewString() for _, multiSLBConfig := range az.MultipleStandardLoadBalancerConfigurations { if names.Has(multiSLBConfig.Name) { return fmt.Errorf("duplicated multiple standard load balancer configuration name %s", multiSLBConfig.Name) @@ -1173,29 +1166,6 @@ func (az *Cloud) ProviderName() string { return consts.CloudProviderName } -func InitDiskControllers(az *Cloud) error { - // Common controller contains the function - // needed by both blob disk and managed disk controllers - - qps := float32(ratelimitconfig.DefaultAtachDetachDiskQPS) - bucket := ratelimitconfig.DefaultAtachDetachDiskBucket - if az.Config.AttachDetachDiskRateLimit != nil { - qps = az.Config.AttachDetachDiskRateLimit.CloudProviderRateLimitQPSWrite - bucket = az.Config.AttachDetachDiskRateLimit.CloudProviderRateLimitBucketWrite - } - klog.V(2).Infof("attach/detach disk operation rate limit QPS: %f, Bucket: %d", qps, bucket) - - common := &controllerCommon{ - cloud: az, - lockMap: newLockMap(), - AttachDetachInitialDelayInMs: defaultAttachDetachInitialDelayInMs, - } - - az.ManagedDiskController = &ManagedDiskController{common} - - return nil -} - // SetInformers sets informers for Azure cloud provider. func (az *Cloud) SetInformers(informerFactory informers.SharedInformerFactory) { klog.Infof("Setting up informers for Azure cloud provider") @@ -1293,15 +1263,12 @@ func (az *Cloud) updateNodeCaches(prevNode, newNode *v1.Node) { if newNode != nil { // Add to nodeNames cache. - az.nodeNames.Insert(newNode.ObjectMeta.Name) + az.nodeNames = utilsets.SafeInsert(az.nodeNames, newNode.ObjectMeta.Name) // Add to nodeZones cache. newZone, ok := newNode.ObjectMeta.Labels[v1.LabelTopologyZone] if ok && az.isAvailabilityZone(newZone) { - if az.nodeZones[newZone] == nil { - az.nodeZones[newZone] = sets.New[string]() - } - az.nodeZones[newZone].Insert(newNode.ObjectMeta.Name) + az.nodeZones[newZone] = utilsets.SafeInsert(az.nodeZones[newZone], newNode.ObjectMeta.Name) } // Add to nodeResourceGroups cache. @@ -1337,15 +1304,12 @@ func (az *Cloud) updateNodeCaches(prevNode, newNode *v1.Node) { // Add to nodePrivateIPs cache for _, address := range getNodePrivateIPAddresses(newNode) { - if az.nodePrivateIPs[strings.ToLower(newNode.Name)] == nil { - az.nodePrivateIPs[strings.ToLower(newNode.Name)] = sets.New[string]() - } if az.nodePrivateIPToNodeNameMap == nil { az.nodePrivateIPToNodeNameMap = make(map[string]string) } klog.V(6).Infof("adding IP address %s of the node %s", address, newNode.Name) - az.nodePrivateIPs[strings.ToLower(newNode.Name)].Insert(address) + az.nodePrivateIPs[strings.ToLower(newNode.Name)] = utilsets.SafeInsert(az.nodePrivateIPs[strings.ToLower(newNode.Name)], address) az.nodePrivateIPToNodeNameMap[address] = newNode.Name } } @@ -1381,7 +1345,7 @@ func (az *Cloud) updateNodeTaint(node *v1.Node) { } // GetActiveZones returns all the zones in which k8s nodes are currently running. -func (az *Cloud) GetActiveZones() (sets.Set[string], error) { +func (az *Cloud) GetActiveZones() (*utilsets.IgnoreCaseSet, error) { if az.nodeInformerSynced == nil { return nil, fmt.Errorf("azure cloud provider doesn't have informers set") } @@ -1392,9 +1356,9 @@ func (az *Cloud) GetActiveZones() (sets.Set[string], error) { return nil, fmt.Errorf("node informer is not synced when trying to GetActiveZones") } - zones := sets.New[string]() + zones := utilsets.NewString() for zone, nodes := range az.nodeZones { - if len(nodes) > 0 { + if nodes.Len() > 0 { zones.Insert(zone) } } @@ -1429,7 +1393,7 @@ func (az *Cloud) GetNodeResourceGroup(nodeName string) (string, error) { } // GetNodeNames returns a set of all node names in the k8s cluster. -func (az *Cloud) GetNodeNames() (sets.Set[string], error) { +func (az *Cloud) GetNodeNames() (*utilsets.IgnoreCaseSet, error) { // Kubelet won't set az.nodeInformerSynced, return nil. if az.nodeInformerSynced == nil { return nil, nil @@ -1441,14 +1405,14 @@ func (az *Cloud) GetNodeNames() (sets.Set[string], error) { return nil, fmt.Errorf("node informer is not synced when trying to GetNodeNames") } - return sets.New(az.nodeNames.UnsortedList()...), nil + return utilsets.NewString(az.nodeNames.UnsortedList()...), nil } // GetResourceGroups returns a set of resource groups that all nodes are running on. -func (az *Cloud) GetResourceGroups() (sets.Set[string], error) { +func (az *Cloud) GetResourceGroups() (*utilsets.IgnoreCaseSet, error) { // Kubelet won't set az.nodeInformerSynced, always return configured resourceGroup. if az.nodeInformerSynced == nil { - return sets.New(az.ResourceGroup), nil + return utilsets.NewString(az.ResourceGroup), nil } az.nodeCachesLock.RLock() @@ -1457,7 +1421,7 @@ func (az *Cloud) GetResourceGroups() (sets.Set[string], error) { return nil, fmt.Errorf("node informer is not synced when trying to GetResourceGroups") } - resourceGroups := sets.New(az.ResourceGroup) + resourceGroups := utilsets.NewString(az.ResourceGroup) for _, rg := range az.nodeResourceGroups { resourceGroups.Insert(rg) } @@ -1466,7 +1430,7 @@ func (az *Cloud) GetResourceGroups() (sets.Set[string], error) { } // GetUnmanagedNodes returns a list of nodes not managed by Azure cloud provider (e.g. on-prem nodes). -func (az *Cloud) GetUnmanagedNodes() (sets.Set[string], error) { +func (az *Cloud) GetUnmanagedNodes() (*utilsets.IgnoreCaseSet, error) { // Kubelet won't set az.nodeInformerSynced, always return nil. if az.nodeInformerSynced == nil { return nil, nil @@ -1478,7 +1442,7 @@ func (az *Cloud) GetUnmanagedNodes() (sets.Set[string], error) { return nil, fmt.Errorf("node informer is not synced when trying to GetUnmanagedNodes") } - return sets.New(az.unmanagedNodes.UnsortedList()...), nil + return utilsets.NewString(az.unmanagedNodes.UnsortedList()...), nil } // ShouldNodeExcludedFromLoadBalancer returns true if node is unmanaged, in external resource group or labeled with "node.kubernetes.io/exclude-from-external-load-balancers". @@ -1502,17 +1466,17 @@ func (az *Cloud) ShouldNodeExcludedFromLoadBalancer(nodeName string) (bool, erro return az.excludeLoadBalancerNodes.Has(nodeName), nil } -func (az *Cloud) getActiveNodesByLoadBalancerName(lbName string) sets.Set[string] { +func (az *Cloud) getActiveNodesByLoadBalancerName(lbName string) *utilsets.IgnoreCaseSet { az.multipleStandardLoadBalancersActiveNodesLock.Lock() defer az.multipleStandardLoadBalancersActiveNodesLock.Unlock() for _, multiSLBConfig := range az.MultipleStandardLoadBalancerConfigurations { - if strings.EqualFold(strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { + if strings.EqualFold(trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { return multiSLBConfig.ActiveNodes } } - return sets.New[string]() + return utilsets.NewString() } func isNodeReady(node *v1.Node) bool { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_common.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_common.go index e1ba039a8..d4c966e85 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_common.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_common.go @@ -18,35 +18,18 @@ package provider import ( "context" - "errors" "fmt" "net/http" "path" - "regexp" "strings" - "sync" - "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/apimachinery/pkg/types" - kwait "k8s.io/apimachinery/pkg/util/wait" - cloudprovider "k8s.io/cloud-provider" - volerr "k8s.io/cloud-provider/volume/errors" "k8s.io/klog/v2" - "k8s.io/utils/pointer" - azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" - "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" + "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient" ) const ( - // Disk Caching is not supported for disks 4 TiB and larger - // https://docs.microsoft.com/en-us/azure/virtual-machines/premium-storage-performance#disk-caching - diskCachingLimit = 4096 // GiB - maxLUN = 64 // max number of LUNs per VM errStatusCode400 = "statuscode=400" errInvalidParameter = `code="invalidparameter"` @@ -56,68 +39,11 @@ const ( attachDiskMapKeySuffix = "attachdiskmap" detachDiskMapKeySuffix = "detachdiskmap" - updateVMRetryDuration = time.Duration(1) * time.Second - updateVMRetryFactor = 3.0 - updateVMRetrySteps = 5 - - // default initial delay in milliseconds for batch disk attach/detach - defaultAttachDetachInitialDelayInMs = 1000 - // WriteAcceleratorEnabled support for Azure Write Accelerator on Azure Disks // https://docs.microsoft.com/azure/virtual-machines/windows/how-to-enable-write-accelerator WriteAcceleratorEnabled = "writeacceleratorenabled" - - // see https://docs.microsoft.com/en-us/rest/api/compute/disks/createorupdate#create-a-managed-disk-by-copying-a-snapshot. - diskSnapshotPath = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/snapshots/%s" - - // see https://docs.microsoft.com/en-us/rest/api/compute/disks/createorupdate#create-a-managed-disk-from-an-existing-managed-disk-in-the-same-or-different-subscription. - managedDiskPath = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s" ) -var defaultBackOff = kwait.Backoff{ - Steps: 20, - Duration: 2 * time.Second, - Factor: 1.5, - Jitter: 0.0, -} - -var updateVMBackoff = kwait.Backoff{ - Duration: updateVMRetryDuration, - Factor: updateVMRetryFactor, - Steps: updateVMRetrySteps, -} - -var ( - managedDiskPathRE = regexp.MustCompile(`.*/subscriptions/(?:.*)/resourceGroups/(?:.*)/providers/Microsoft.Compute/disks/(.+)`) - diskSnapshotPathRE = regexp.MustCompile(`.*/subscriptions/(?:.*)/resourceGroups/(?:.*)/providers/Microsoft.Compute/snapshots/(.+)`) - errorCodeRE = regexp.MustCompile(`Code="(.*?)".*`) -) - -type controllerCommon struct { - diskStateMap sync.Map // - lockMap *lockMap - cloud *Cloud - // disk queue that is waiting for attach or detach on specific node - // > - attachDiskMap sync.Map - detachDiskMap sync.Map - // DisableUpdateCache whether disable update cache in disk attach/detach - DisableUpdateCache bool - // DisableDiskLunCheck whether disable disk lun check after disk attach/detach - DisableDiskLunCheck bool - // AttachDetachInitialDelayInMs determines initial delay in milliseconds for batch disk attach/detach - AttachDetachInitialDelayInMs int -} - -// AttachDiskOptions attach disk options -type AttachDiskOptions struct { - CachingMode compute.CachingTypes - DiskName string - DiskEncryptionSetID string - WriteAcceleratorEnabled bool - Lun int32 -} - // ExtendedLocation contains additional info about the location of resources. type ExtendedLocation struct { // Name - The name of the extended location. @@ -126,504 +52,13 @@ type ExtendedLocation struct { Type string `json:"type,omitempty"` } -// AttachDisk attaches a disk to vm -// occupiedLuns is used to avoid conflict with other disk attach in k8s VolumeAttachments -// return (lun, error) -func (c *controllerCommon) AttachDisk(ctx context.Context, diskName, diskURI string, nodeName types.NodeName, - cachingMode compute.CachingTypes, disk *compute.Disk, occupiedLuns []int) (int32, error) { - diskEncryptionSetID := "" - writeAcceleratorEnabled := false - - // there is possibility that disk is nil when GetDisk is throttled - // don't check disk state when GetDisk is throttled - if disk != nil { - if disk.ManagedBy != nil && (disk.MaxShares == nil || *disk.MaxShares <= 1) { - vmset, err := c.cloud.GetNodeVMSet(nodeName, azcache.CacheReadTypeUnsafe) - if err != nil { - return -1, err - } - attachedNode, err := vmset.GetNodeNameByProviderID(*disk.ManagedBy) - if err != nil { - return -1, err - } - if strings.EqualFold(string(nodeName), string(attachedNode)) { - klog.Warningf("volume %s is actually attached to current node %s, invalidate vm cache and return error", diskURI, nodeName) - // update VM(invalidate vm cache) - if errUpdate := c.UpdateVM(ctx, nodeName); errUpdate != nil { - return -1, errUpdate - } - lun, _, err := c.GetDiskLun(diskName, diskURI, nodeName) - return lun, err - } - - attachErr := fmt.Sprintf( - "disk(%s) already attached to node(%s), could not be attached to node(%s)", - diskURI, *disk.ManagedBy, nodeName) - klog.V(2).Infof("found dangling volume %s attached to node %s, could not be attached to node(%s)", diskURI, attachedNode, nodeName) - return -1, volerr.NewDanglingError(attachErr, attachedNode, "") - } - - if disk.DiskProperties != nil { - if disk.DiskProperties.DiskSizeGB != nil && *disk.DiskProperties.DiskSizeGB >= diskCachingLimit && cachingMode != compute.CachingTypesNone { - // Disk Caching is not supported for disks 4 TiB and larger - // https://docs.microsoft.com/en-us/azure/virtual-machines/premium-storage-performance#disk-caching - cachingMode = compute.CachingTypesNone - klog.Warningf("size of disk(%s) is %dGB which is bigger than limit(%dGB), set cacheMode as None", - diskURI, *disk.DiskProperties.DiskSizeGB, diskCachingLimit) - } - - if disk.DiskProperties.Encryption != nil && - disk.DiskProperties.Encryption.DiskEncryptionSetID != nil { - diskEncryptionSetID = *disk.DiskProperties.Encryption.DiskEncryptionSetID - } - - if disk.DiskProperties.DiskState != compute.Unattached && (disk.MaxShares == nil || *disk.MaxShares <= 1) { - return -1, fmt.Errorf("state of disk(%s) is %s, not in expected %s state", diskURI, disk.DiskProperties.DiskState, compute.Unattached) - } - } - - if v, ok := disk.Tags[WriteAcceleratorEnabled]; ok { - if v != nil && strings.EqualFold(*v, "true") { - writeAcceleratorEnabled = true - } - } - } - - options := AttachDiskOptions{ - Lun: -1, - DiskName: diskName, - CachingMode: cachingMode, - DiskEncryptionSetID: diskEncryptionSetID, - WriteAcceleratorEnabled: writeAcceleratorEnabled, - } - node := strings.ToLower(string(nodeName)) - diskuri := strings.ToLower(diskURI) - requestNum, err := c.insertAttachDiskRequest(diskuri, node, &options) - if err != nil { - return -1, err - } - - c.lockMap.LockEntry(node) - unlock := false - defer func() { - if !unlock { - c.lockMap.UnlockEntry(node) - } - }() - - if c.AttachDetachInitialDelayInMs > 0 && requestNum == 1 { - klog.V(2).Infof("wait %dms for more requests on node %s, current disk attach: %s", c.AttachDetachInitialDelayInMs, node, diskURI) - time.Sleep(time.Duration(c.AttachDetachInitialDelayInMs) * time.Millisecond) - } - - diskMap, err := c.cleanAttachDiskRequests(node) - if err != nil { - return -1, err - } - - lun, err := c.SetDiskLun(nodeName, diskuri, diskMap, occupiedLuns) - if err != nil { - return -1, err - } - - klog.V(2).Infof("Trying to attach volume %s lun %d to node %s, diskMap len:%d, %+v", diskURI, lun, nodeName, len(diskMap), diskMap) - if len(diskMap) == 0 { - if !c.DisableDiskLunCheck { - // always check disk lun after disk attach complete - diskLun, vmState, errGetLun := c.GetDiskLun(diskName, diskURI, nodeName) - if errGetLun != nil { - return -1, fmt.Errorf("disk(%s) could not be found on node(%s), vmState: %s, error: %w", diskURI, nodeName, pointer.StringDeref(vmState, ""), errGetLun) - } - lun = diskLun - } - return lun, nil - } - - vmset, err := c.cloud.GetNodeVMSet(nodeName, azcache.CacheReadTypeUnsafe) - if err != nil { - return -1, err - } - c.diskStateMap.Store(disk, "attaching") - defer c.diskStateMap.Delete(disk) - - defer func() { - // invalidate the cache if there is error in disk attach - if err != nil { - _ = vmset.DeleteCacheForNode(string(nodeName)) - } - }() - - var future *azure.Future - future, err = vmset.AttachDisk(ctx, nodeName, diskMap) - if err != nil { - return -1, err - } - // err will be handled by waitForUpdateResult below - if err = c.waitForUpdateResult(ctx, vmset, nodeName, future, err); err != nil { - return -1, err - } - - if !c.DisableDiskLunCheck { - // always check disk lun after disk attach complete - diskLun, vmState, errGetLun := c.GetDiskLun(diskName, diskURI, nodeName) - if errGetLun != nil { - return -1, fmt.Errorf("disk(%s) could not be found on node(%s), vmState: %s, error: %w", diskURI, nodeName, pointer.StringDeref(vmState, ""), errGetLun) - } - lun = diskLun - } - return lun, nil -} - -// waitForUpdateResult handles asynchronous VM update operations and retries with backoff if OperationPreempted error is observed -func (c *controllerCommon) waitForUpdateResult(ctx context.Context, vmset VMSet, nodeName types.NodeName, future *azure.Future, updateErr error) (err error) { - err = updateErr - if err == nil { - err = vmset.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") - } - - if vmUpdateRequired(future, err) { - if derr := kwait.ExponentialBackoffWithContext(ctx, updateVMBackoff, func(ctx context.Context) (bool, error) { - klog.Errorf("Retry VM Update on node (%s) due to error (%v)", nodeName, err) - future, err = vmset.UpdateVMAsync(ctx, nodeName) - if err == nil { - err = vmset.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") - } - return !vmUpdateRequired(future, err), nil - }); derr != nil { - err = derr - return - } - } - - if err != nil && configAccepted(future) { - err = retry.NewPartialUpdateError(err.Error()) - } - return -} - -// insertAttachDiskRequest return (attachDiskRequestQueueLength, error) -func (c *controllerCommon) insertAttachDiskRequest(diskURI, nodeName string, options *AttachDiskOptions) (int, error) { - var diskMap map[string]*AttachDiskOptions - attachDiskMapKey := nodeName + attachDiskMapKeySuffix - c.lockMap.LockEntry(attachDiskMapKey) - defer c.lockMap.UnlockEntry(attachDiskMapKey) - v, ok := c.attachDiskMap.Load(nodeName) - if ok { - if diskMap, ok = v.(map[string]*AttachDiskOptions); !ok { - return -1, fmt.Errorf("convert attachDiskMap failure on node(%s)", nodeName) - } - } else { - diskMap = make(map[string]*AttachDiskOptions) - c.attachDiskMap.Store(nodeName, diskMap) - } - // insert attach disk request to queue - _, ok = diskMap[diskURI] - if ok { - klog.V(2).Infof("azureDisk - duplicated attach disk(%s) request on node(%s)", diskURI, nodeName) - } else { - diskMap[diskURI] = options - } - return len(diskMap), nil -} - -// clean up attach disk requests -// return original attach disk requests -func (c *controllerCommon) cleanAttachDiskRequests(nodeName string) (map[string]*AttachDiskOptions, error) { - var diskMap map[string]*AttachDiskOptions - - attachDiskMapKey := nodeName + attachDiskMapKeySuffix - c.lockMap.LockEntry(attachDiskMapKey) - defer c.lockMap.UnlockEntry(attachDiskMapKey) - v, ok := c.attachDiskMap.Load(nodeName) - if !ok { - return diskMap, nil - } - if diskMap, ok = v.(map[string]*AttachDiskOptions); !ok { - return diskMap, fmt.Errorf("convert attachDiskMap failure on node(%s)", nodeName) - } - c.attachDiskMap.Store(nodeName, make(map[string]*AttachDiskOptions)) - return diskMap, nil -} - -// DetachDisk detaches a disk from VM -func (c *controllerCommon) DetachDisk(ctx context.Context, diskName, diskURI string, nodeName types.NodeName) error { - if _, err := c.cloud.InstanceID(ctx, nodeName); err != nil { - if errors.Is(err, cloudprovider.InstanceNotFound) { - // if host doesn't exist, no need to detach - klog.Warningf("azureDisk - failed to get azure instance id(%s), DetachDisk(%s) will assume disk is already detached", - nodeName, diskURI) - return nil - } - klog.Warningf("failed to get azure instance id (%v)", err) - return fmt.Errorf("failed to get azure instance id for node %q: %w", nodeName, err) - } - - vmset, err := c.cloud.GetNodeVMSet(nodeName, azcache.CacheReadTypeUnsafe) - if err != nil { - return err - } - - node := strings.ToLower(string(nodeName)) - disk := strings.ToLower(diskURI) - requestNum, err := c.insertDetachDiskRequest(diskName, disk, node) - if err != nil { - return err - } - - c.lockMap.LockEntry(node) - defer c.lockMap.UnlockEntry(node) - - if c.AttachDetachInitialDelayInMs > 0 && requestNum == 1 { - klog.V(2).Infof("wait %dms for more requests on node %s, current disk detach: %s", c.AttachDetachInitialDelayInMs, node, diskURI) - time.Sleep(time.Duration(c.AttachDetachInitialDelayInMs) * time.Millisecond) - } - diskMap, err := c.cleanDetachDiskRequests(node) - if err != nil { - return err - } - - klog.V(2).Infof("Trying to detach volume %s from node %s, diskMap len:%d, %s", diskURI, nodeName, len(diskMap), diskMap) - if len(diskMap) > 0 { - c.diskStateMap.Store(disk, "detaching") - defer c.diskStateMap.Delete(disk) - if err = vmset.DetachDisk(ctx, nodeName, diskMap); err != nil { - if isInstanceNotFoundError(err) { - // if host doesn't exist, no need to detach - klog.Warningf("azureDisk - got InstanceNotFoundError(%v), DetachDisk(%s) will assume disk is already detached", - err, diskURI) - return nil - } - } - } - - if err != nil { - klog.Errorf("azureDisk - detach disk(%s, %s) failed, err: %v", diskName, diskURI, err) - return err - } - - if !c.DisableDiskLunCheck { - // always check disk lun after disk detach complete - lun, vmState, errGetLun := c.GetDiskLun(diskName, diskURI, nodeName) - if errGetLun == nil || !strings.Contains(errGetLun.Error(), consts.CannotFindDiskLUN) { - return fmt.Errorf("disk(%s) is still attached to node(%s) on lun(%d), vmState: %s, error: %w", diskURI, nodeName, lun, pointer.StringDeref(vmState, ""), errGetLun) - } - } - - klog.V(2).Infof("azureDisk - detach disk(%s, %s) succeeded", diskName, diskURI) - return nil -} - -// UpdateVM updates a vm -func (c *controllerCommon) UpdateVM(ctx context.Context, nodeName types.NodeName) error { - vmset, err := c.cloud.GetNodeVMSet(nodeName, azcache.CacheReadTypeUnsafe) - if err != nil { - return err - } - node := strings.ToLower(string(nodeName)) - c.lockMap.LockEntry(node) - defer c.lockMap.UnlockEntry(node) - - defer func() { - _ = vmset.DeleteCacheForNode(string(nodeName)) - }() - - klog.V(2).Infof("azureDisk - update: vm(%s)", nodeName) - return vmset.UpdateVM(ctx, nodeName) -} - -// insertDetachDiskRequest return (detachDiskRequestQueueLength, error) -func (c *controllerCommon) insertDetachDiskRequest(diskName, diskURI, nodeName string) (int, error) { - var diskMap map[string]string - detachDiskMapKey := nodeName + detachDiskMapKeySuffix - c.lockMap.LockEntry(detachDiskMapKey) - defer c.lockMap.UnlockEntry(detachDiskMapKey) - v, ok := c.detachDiskMap.Load(nodeName) - if ok { - if diskMap, ok = v.(map[string]string); !ok { - return -1, fmt.Errorf("convert detachDiskMap failure on node(%s)", nodeName) - } - } else { - diskMap = make(map[string]string) - c.detachDiskMap.Store(nodeName, diskMap) - } - // insert detach disk request to queue - _, ok = diskMap[diskURI] - if ok { - klog.V(2).Infof("azureDisk - duplicated detach disk(%s) request on node(%s)", diskURI, nodeName) - } else { - diskMap[diskURI] = diskName - } - return len(diskMap), nil -} - -// clean up detach disk requests -// return original detach disk requests -func (c *controllerCommon) cleanDetachDiskRequests(nodeName string) (map[string]string, error) { - var diskMap map[string]string - - detachDiskMapKey := nodeName + detachDiskMapKeySuffix - c.lockMap.LockEntry(detachDiskMapKey) - defer c.lockMap.UnlockEntry(detachDiskMapKey) - v, ok := c.detachDiskMap.Load(nodeName) - if !ok { - return diskMap, nil - } - if diskMap, ok = v.(map[string]string); !ok { - return diskMap, fmt.Errorf("convert detachDiskMap failure on node(%s)", nodeName) - } - // clean up original requests in disk map - c.detachDiskMap.Store(nodeName, make(map[string]string)) - return diskMap, nil -} - -// GetNodeDataDisks invokes vmSet interfaces to get data disks for the node. -func (c *controllerCommon) GetNodeDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, *string, error) { - vmset, err := c.cloud.GetNodeVMSet(nodeName, crt) - if err != nil { - return nil, nil, err - } - - return vmset.GetDataDisks(nodeName, crt) -} - -// GetDiskLun finds the lun on the host that the vhd is attached to, given a vhd's diskName and diskURI. -func (c *controllerCommon) GetDiskLun(diskName, diskURI string, nodeName types.NodeName) (int32, *string, error) { - // GetNodeDataDisks need to fetch the cached data/fresh data if cache expired here - // to ensure we get LUN based on latest entry. - disks, provisioningState, err := c.GetNodeDataDisks(nodeName, azcache.CacheReadTypeDefault) - if err != nil { - klog.Errorf("error of getting data disks for node %s: %v", nodeName, err) - return -1, provisioningState, err - } - - for _, disk := range disks { - if disk.Lun != nil && (disk.Name != nil && diskName != "" && strings.EqualFold(*disk.Name, diskName)) || - (disk.Vhd != nil && disk.Vhd.URI != nil && diskURI != "" && strings.EqualFold(*disk.Vhd.URI, diskURI)) || - (disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) { - if disk.ToBeDetached != nil && *disk.ToBeDetached { - klog.Warningf("azureDisk - find disk(ToBeDetached): lun %d name %s uri %s", *disk.Lun, diskName, diskURI) - } else { - // found the disk - klog.V(2).Infof("azureDisk - find disk: lun %d name %s uri %s", *disk.Lun, diskName, diskURI) - return *disk.Lun, provisioningState, nil - } - } - } - return -1, provisioningState, fmt.Errorf("%s for disk %s", consts.CannotFindDiskLUN, diskName) -} - -// SetDiskLun find unused luns and allocate lun for every disk in diskMap. -// occupiedLuns is used to avoid conflict with other disk attach in k8s VolumeAttachments -// Return lun of diskURI, -1 if all luns are used. -func (c *controllerCommon) SetDiskLun(nodeName types.NodeName, diskURI string, diskMap map[string]*AttachDiskOptions, occupiedLuns []int) (int32, error) { - disks, _, err := c.GetNodeDataDisks(nodeName, azcache.CacheReadTypeDefault) - if err != nil { - klog.Errorf("error of getting data disks for node %s: %v", nodeName, err) - return -1, err - } - - lun := int32(-1) - _, isDiskInMap := diskMap[diskURI] - used := make([]bool, maxLUN) - for _, disk := range disks { - if disk.Lun != nil { - used[*disk.Lun] = true - if !isDiskInMap { - // find lun of diskURI since diskURI is not in diskMap - if disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diskURI) { - lun = *disk.Lun - } - } - } - } - if !isDiskInMap && lun < 0 { - return -1, fmt.Errorf("could not find disk(%s) in current disk list(len: %d) nor in diskMap(%v)", diskURI, len(disks), diskMap) - } - if len(diskMap) == 0 { - // attach disk request is empty, return directly - return lun, nil - } - - for _, lun := range occupiedLuns { - used[int32(lun)] = true - } - - // allocate lun for every disk in diskMap - var diskLuns []int32 - count := 0 - for k, v := range used { - if !v { - diskLuns = append(diskLuns, int32(k)) - count++ - if count >= len(diskMap) { - break - } - } - } - - if len(diskLuns) != len(diskMap) { - return -1, fmt.Errorf("could not find enough disk luns(current: %d) for diskMap(%v, len=%d), diskURI(%s)", - len(diskLuns), diskMap, len(diskMap), diskURI) - } - - count = 0 - for uri, opt := range diskMap { - if opt == nil { - return -1, fmt.Errorf("unexpected nil pointer in diskMap(%v), diskURI(%s)", diskMap, diskURI) - } - if strings.EqualFold(uri, diskURI) { - lun = diskLuns[count] - } - opt.Lun = diskLuns[count] - count++ - } - if lun < 0 { - return lun, fmt.Errorf("could not find lun of diskURI(%s), diskMap(%v)", diskURI, diskMap) - } - return lun, nil -} - -// DisksAreAttached checks if a list of volumes are attached to the node with the specified NodeName. -func (c *controllerCommon) DisksAreAttached(diskNames []string, nodeName types.NodeName) (map[string]bool, error) { - attached := make(map[string]bool) - for _, diskName := range diskNames { - attached[diskName] = false - } - - // doing stalled read for GetNodeDataDisks to ensure we don't call ARM - // for every reconcile call. The cache is invalidated after Attach/Detach - // disk. So the new entry will be fetched and cached the first time reconcile - // loop runs after the Attach/Disk OP which will reflect the latest model. - disks, _, err := c.GetNodeDataDisks(nodeName, azcache.CacheReadTypeUnsafe) - if err != nil { - if errors.Is(err, cloudprovider.InstanceNotFound) { - // if host doesn't exist, no need to detach - klog.Warningf("azureDisk - Cannot find node %s, DisksAreAttached will assume disks %v are not attached to it.", - nodeName, diskNames) - return attached, nil - } - - return attached, err - } - - for _, disk := range disks { - for _, diskName := range diskNames { - if disk.Name != nil && diskName != "" && strings.EqualFold(*disk.Name, diskName) { - attached[diskName] = true - } - } - } - - return attached, nil -} - -func (c *controllerCommon) filterNonExistingDisks(ctx context.Context, unfilteredDisks []compute.DataDisk) []compute.DataDisk { +func FilterNonExistingDisks(ctx context.Context, diskClient diskclient.Interface, unfilteredDisks []compute.DataDisk) []compute.DataDisk { filteredDisks := []compute.DataDisk{} for _, disk := range unfilteredDisks { filter := false if disk.ManagedDisk != nil && disk.ManagedDisk.ID != nil { diskURI := *disk.ManagedDisk.ID - exist, err := c.cloud.checkDiskExists(ctx, diskURI) + exist, err := checkDiskExists(ctx, diskClient, diskURI) if err != nil { klog.Errorf("checkDiskExists(%s) failed with error: %v", diskURI, err) } else { @@ -642,14 +77,14 @@ func (c *controllerCommon) filterNonExistingDisks(ctx context.Context, unfiltere return filteredDisks } -func (c *controllerCommon) checkDiskExists(ctx context.Context, diskURI string) (bool, error) { +func checkDiskExists(ctx context.Context, diskClient diskclient.Interface, diskURI string) (bool, error) { diskName := path.Base(diskURI) resourceGroup, subsID, err := getInfoFromDiskURI(diskURI) if err != nil { return false, err } - if _, rerr := c.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName); rerr != nil { + if _, rerr := diskClient.Get(ctx, subsID, resourceGroup, diskName); rerr != nil { if rerr.HTTPStatusCode == http.StatusNotFound { return false, nil } @@ -659,73 +94,13 @@ func (c *controllerCommon) checkDiskExists(ctx context.Context, diskURI string) return true, nil } -func vmUpdateRequired(future *azure.Future, err error) bool { - errCode := getAzureErrorCode(err) - return configAccepted(future) && errCode == consts.OperationPreemptedErrorCode -} - -func getValidCreationData(subscriptionID, resourceGroup string, options *ManagedDiskOptions) (compute.CreationData, error) { - if options.SourceResourceID == "" { - return compute.CreationData{ - CreateOption: compute.Empty, - PerformancePlus: options.PerformancePlus, - }, nil - } - - sourceResourceID := options.SourceResourceID - switch options.SourceType { - case sourceSnapshot: - if match := diskSnapshotPathRE.FindString(sourceResourceID); match == "" { - sourceResourceID = fmt.Sprintf(diskSnapshotPath, subscriptionID, resourceGroup, sourceResourceID) - } - - case sourceVolume: - if match := managedDiskPathRE.FindString(sourceResourceID); match == "" { - sourceResourceID = fmt.Sprintf(managedDiskPath, subscriptionID, resourceGroup, sourceResourceID) - } - default: - return compute.CreationData{ - CreateOption: compute.Empty, - PerformancePlus: options.PerformancePlus, - }, nil - } - - splits := strings.Split(sourceResourceID, "/") - if len(splits) > 9 { - if options.SourceType == sourceSnapshot { - return compute.CreationData{}, fmt.Errorf("sourceResourceID(%s) is invalid, correct format: %s", sourceResourceID, diskSnapshotPathRE) - } - return compute.CreationData{}, fmt.Errorf("sourceResourceID(%s) is invalid, correct format: %s", sourceResourceID, managedDiskPathRE) - } - return compute.CreationData{ - CreateOption: compute.Copy, - SourceResourceID: &sourceResourceID, - PerformancePlus: options.PerformancePlus, - }, nil -} - -func isInstanceNotFoundError(err error) bool { - errMsg := strings.ToLower(err.Error()) - if strings.Contains(errMsg, strings.ToLower(consts.VmssVMNotActiveErrorMessage)) { - return true +// get resource group name, subs id from a managed disk URI, e.g. return {group-name}, {sub-id} according to +// /subscriptions/{sub-id}/resourcegroups/{group-name}/providers/microsoft.compute/disks/{disk-id} +// according to https://docs.microsoft.com/en-us/rest/api/compute/disks/get +func getInfoFromDiskURI(diskURI string) (string, string, error) { + fields := strings.Split(diskURI, "/") + if len(fields) != 9 || strings.ToLower(fields[3]) != "resourcegroups" { + return "", "", fmt.Errorf("invalid disk URI: %s", diskURI) } - return strings.Contains(errMsg, errStatusCode400) && strings.Contains(errMsg, errInvalidParameter) && strings.Contains(errMsg, errTargetInstanceIds) -} - -// getAzureErrorCode uses regex to parse out the error code encapsulated in the error string. -func getAzureErrorCode(err error) string { - if err == nil { - return "" - } - matches := errorCodeRE.FindStringSubmatch(err.Error()) - if matches == nil { - return "" - } - return matches[1] -} - -// configAccepted returns true if storage profile change had been committed (i.e. HTTP status code == 2xx) and returns false otherwise. -func configAccepted(future *azure.Future) bool { - // if status code indicates success, the storage profile change was committed - return future != nil && future.Response() != nil && future.Response().StatusCode/100 == 2 + return fields[4], fields[2], nil } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go index 229e061b5..e47b8296d 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go @@ -22,6 +22,7 @@ import ( "net/http" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" @@ -35,16 +36,16 @@ import ( ) // AttachDisk attaches a disk to vm -func (as *availabilitySet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) (*azure.Future, error) { +func (as *availabilitySet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) error { vm, err := as.getVirtualMachine(nodeName, azcache.CacheReadTypeDefault) if err != nil { - return nil, err + return err } vmName := mapNodeNameToVMName(nodeName) nodeResourceGroup, err := as.GetNodeResourceGroup(vmName) if err != nil { - return nil, err + return err } disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) @@ -60,7 +61,7 @@ func (as *availabilitySet) AttachDisk(ctx context.Context, nodeName types.NodeNa attached = true break } - return nil, fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) + return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) } } if attached { @@ -106,7 +107,7 @@ func (as *availabilitySet) AttachDisk(ctx context.Context, nodeName types.NodeNa klog.Errorf("azureDisk - attach disk list(%v) on rg(%s) vm(%s) failed, err: %+v", diskMap, nodeResourceGroup, vmName, rerr) if rerr.HTTPStatusCode == http.StatusNotFound { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := as.filterNonExistingDisks(ctx, *newVM.VirtualMachineProperties.StorageProfile.DataDisks) + disks := FilterNonExistingDisks(ctx, as.DisksClient, *newVM.VirtualMachineProperties.StorageProfile.DataDisks) newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks future, rerr = as.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, vmName, newVM, "attach_disk") } @@ -114,13 +115,13 @@ func (as *availabilitySet) AttachDisk(ctx context.Context, nodeName types.NodeNa klog.V(2).Infof("azureDisk - update(%s): vm(%s) - attach disk list(%v) returned with %v", nodeResourceGroup, vmName, diskMap, rerr) if rerr != nil { - return future, rerr.Error() + return rerr.Error() } - return future, nil + return as.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") } func (as *availabilitySet) DeleteCacheForNode(nodeName string) error { - err := as.cloud.vmCache.Delete(nodeName) + err := as.vmCache.Delete(nodeName) if err == nil { klog.V(2).Infof("DeleteCacheForNode(%s) successfully", nodeName) } else { @@ -187,7 +188,7 @@ func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeNa // only log here, next action is to update VM status with original meta data klog.Warningf("detach azure disk on node(%s): disk list(%s) not found", nodeName, diskMap) } else { - if strings.EqualFold(as.cloud.Environment.Name, consts.AzureStackCloudName) && !as.Config.DisableAzureStackCloud { + if strings.EqualFold(as.Environment.Name, consts.AzureStackCloudName) && !as.Config.DisableAzureStackCloud { // Azure stack does not support ToBeDetached flag, use original way to detach disk newDisks := []compute.DataDisk{} for _, disk := range disks { @@ -226,7 +227,7 @@ func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeNa klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, rerr) if rerr.HTTPStatusCode == http.StatusNotFound { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := as.filterNonExistingDisks(ctx, *vm.StorageProfile.DataDisks) + disks := FilterNonExistingDisks(ctx, as.DisksClient, *vm.StorageProfile.DataDisks) newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks result, rerr = as.VirtualMachinesClient.Update(ctx, nodeResourceGroup, vmName, newVM, "detach_disk") } @@ -264,15 +265,12 @@ func (as *availabilitySet) UpdateVMAsync(ctx context.Context, nodeName types.Nod } func (as *availabilitySet) updateCache(nodeName string, vm *compute.VirtualMachine) { - if as.ManagedDiskController.DisableUpdateCache { - return - } - as.cloud.vmCache.Update(nodeName, vm) + as.vmCache.Update(nodeName, vm) klog.V(2).Infof("updateCache(%s) successfully", nodeName) } // GetDataDisks gets a list of data disks attached to the node. -func (as *availabilitySet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, *string, error) { +func (as *availabilitySet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]*armcompute.DataDisk, *string, error) { vm, err := as.getVirtualMachine(nodeName, crt) if err != nil { return nil, nil, err @@ -282,5 +280,9 @@ func (as *availabilitySet) GetDataDisks(nodeName types.NodeName, crt azcache.Azu return nil, nil, nil } - return *vm.StorageProfile.DataDisks, vm.ProvisioningState, nil + result, err := ToArmcomputeDisk(*vm.StorageProfile.DataDisks) + if err != nil { + return nil, nil, err + } + return result, vm.ProvisioningState, nil } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmss.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmss.go index 650c13f62..fada0393f 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmss.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmss.go @@ -22,6 +22,7 @@ import ( "net/http" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" @@ -35,16 +36,16 @@ import ( ) // AttachDisk attaches a disk to vm -func (ss *ScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) (*azure.Future, error) { +func (ss *ScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) error { vmName := mapNodeNameToVMName(nodeName) vm, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault) if err != nil { - return nil, err + return err } nodeResourceGroup, err := ss.GetNodeResourceGroup(vmName) if err != nil { - return nil, err + return err } var disks []compute.DataDisk @@ -66,7 +67,7 @@ func (ss *ScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, dis attached = true break } - return nil, fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) + return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) } } @@ -113,7 +114,7 @@ func (ss *ScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, dis klog.Errorf("azureDisk - attach disk list(%+v) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, nodeName, rerr) if rerr.HTTPStatusCode == http.StatusNotFound { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, nodeName) - disks := ss.filterNonExistingDisks(ctx, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks) + disks := FilterNonExistingDisks(ctx, ss.DisksClient, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks) newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks = &disks future, rerr = ss.VirtualMachineScaleSetVMsClient.UpdateAsync(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, newVM, "attach_disk") } @@ -121,9 +122,9 @@ func (ss *ScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, dis klog.V(2).Infof("azureDisk - update: rg(%s) vm(%s) - attach disk list(%+v) returned with %v", nodeResourceGroup, nodeName, diskMap, rerr) if rerr != nil { - return future, rerr.Error() + return rerr.Error() } - return future, nil + return ss.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") } // WaitForUpdateResult waits for the response of the update request @@ -201,7 +202,7 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis // only log here, next action is to update VM status with original meta data klog.Warningf("detach azure disk on node(%s): disk list(%s) not found", nodeName, diskMap) } else { - if strings.EqualFold(ss.cloud.Environment.Name, consts.AzureStackCloudName) && !ss.Config.DisableAzureStackCloud { + if strings.EqualFold(ss.Environment.Name, consts.AzureStackCloudName) && !ss.Config.DisableAzureStackCloud { // Azure stack does not support ToBeDetached flag, use original way to detach disk var newDisks []compute.DataDisk for _, disk := range disks { @@ -243,7 +244,7 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, nodeName, rerr) if rerr.HTTPStatusCode == http.StatusNotFound { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, nodeName) - disks := ss.filterNonExistingDisks(ctx, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks) + disks := FilterNonExistingDisks(ctx, ss.DisksClient, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks) newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks = &disks result, rerr = ss.VirtualMachineScaleSetVMsClient.Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, newVM, "detach_disk") } @@ -286,7 +287,7 @@ func (ss *ScaleSet) UpdateVMAsync(ctx context.Context, nodeName types.NodeName) } // GetDataDisks gets a list of data disks attached to the node. -func (ss *ScaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, *string, error) { +func (ss *ScaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]*armcompute.DataDisk, *string, error) { vm, err := ss.getVmssVM(string(nodeName), crt) if err != nil { return nil, nil, err @@ -298,8 +299,11 @@ func (ss *ScaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCache if storageProfile == nil || storageProfile.DataDisks == nil { return nil, nil, nil } - - return *storageProfile.DataDisks, vm.AsVirtualMachineScaleSetVM().ProvisioningState, nil + result, err := ToArmcomputeDisk(*storageProfile.DataDisks) + if err != nil { + return nil, nil, err + } + return result, vm.AsVirtualMachineScaleSetVM().ProvisioningState, nil } return nil, nil, nil diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go index 9fa834934..d34ea871e 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go @@ -23,6 +23,7 @@ import ( "strings" "sync" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" "k8s.io/apimachinery/pkg/types" @@ -35,16 +36,16 @@ import ( ) // AttachDisk attaches a disk to vm -func (fs *FlexScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) (*azure.Future, error) { +func (fs *FlexScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) error { vmName := mapNodeNameToVMName(nodeName) vm, err := fs.getVmssFlexVM(vmName, azcache.CacheReadTypeDefault) if err != nil { - return nil, err + return err } nodeResourceGroup, err := fs.GetNodeResourceGroup(vmName) if err != nil { - return nil, err + return err } disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) @@ -60,7 +61,7 @@ func (fs *FlexScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, attached = true break } - return nil, fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) + return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) } } if attached { @@ -107,7 +108,7 @@ func (fs *FlexScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, klog.Errorf("azureDisk - attach disk list(%+v) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, rerr) if rerr.HTTPStatusCode == http.StatusNotFound { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := fs.filterNonExistingDisks(ctx, *newVM.VirtualMachineProperties.StorageProfile.DataDisks) + disks := FilterNonExistingDisks(ctx, fs.DisksClient, *newVM.VirtualMachineProperties.StorageProfile.DataDisks) newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks future, rerr = fs.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, *vm.Name, newVM, "attach_disk") } @@ -115,9 +116,9 @@ func (fs *FlexScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, klog.V(2).Infof("azureDisk - update(%s): vm(%s) - attach disk list(%+v) returned with %v", nodeResourceGroup, vmName, diskMap, rerr) if rerr != nil { - return future, rerr.Error() + return rerr.Error() } - return future, nil + return fs.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") } // DetachDisk detaches a disk from VM @@ -156,7 +157,7 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, // only log here, next action is to update VM status with original meta data klog.Warningf("detach azure disk on node(%s): disk list(%s) not found", nodeName, diskMap) } else { - if strings.EqualFold(fs.cloud.Environment.Name, consts.AzureStackCloudName) && !fs.Config.DisableAzureStackCloud { + if strings.EqualFold(fs.Environment.Name, consts.AzureStackCloudName) && !fs.Config.DisableAzureStackCloud { // Azure stack does not support ToBeDetached flag, use original way to detach disk newDisks := []compute.DataDisk{} for _, disk := range disks { @@ -197,7 +198,7 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, rerr) if rerr.HTTPStatusCode == http.StatusNotFound { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := fs.filterNonExistingDisks(ctx, *vm.StorageProfile.DataDisks) + disks := FilterNonExistingDisks(ctx, fs.DisksClient, *vm.StorageProfile.DataDisks) newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks result, rerr = fs.VirtualMachinesClient.Update(ctx, nodeResourceGroup, *vm.Name, newVM, "detach_disk") } @@ -263,9 +264,6 @@ func (fs *FlexScaleSet) UpdateVMAsync(ctx context.Context, nodeName types.NodeNa } func (fs *FlexScaleSet) updateCache(nodeName string, vm *compute.VirtualMachine) error { - if fs.ManagedDiskController.DisableUpdateCache { - return nil - } if vm == nil { return fmt.Errorf("vm is nil") } @@ -300,7 +298,7 @@ func (fs *FlexScaleSet) updateCache(nodeName string, vm *compute.VirtualMachine) } // GetDataDisks gets a list of data disks attached to the node. -func (fs *FlexScaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, *string, error) { +func (fs *FlexScaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]*armcompute.DataDisk, *string, error) { vm, err := fs.getVmssFlexVM(string(nodeName), crt) if err != nil { return nil, nil, err @@ -309,6 +307,9 @@ func (fs *FlexScaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureC if vm.StorageProfile.DataDisks == nil { return nil, nil, nil } - - return *vm.StorageProfile.DataDisks, vm.ProvisioningState, nil + result, err := ToArmcomputeDisk(*vm.StorageProfile.DataDisks) + if err != nil { + return nil, nil, err + } + return result, vm.ProvisioningState, nil } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go index 8ba4ac31a..60d6ab70f 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go @@ -25,7 +25,6 @@ import ( "go.uber.org/mock/gomock" - "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/tools/record" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient/mockdiskclient" @@ -42,6 +41,7 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" + utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) // NewTestScaleSet creates a fake ScaleSet for unit test @@ -96,14 +96,15 @@ func GetTestCloud(ctrl *gomock.Controller) (az *Cloud) { VMType: consts.VMTypeStandard, LoadBalancerBackendPoolConfigurationType: consts.LoadBalancerBackendPoolConfigurationTypeNodeIPConfiguration, }, - nodeZones: map[string]sets.Set[string]{}, + nodeZones: map[string]*utilsets.IgnoreCaseSet{}, nodeInformerSynced: func() bool { return true }, nodeResourceGroups: map[string]string{}, - unmanagedNodes: sets.New[string](), - excludeLoadBalancerNodes: sets.New[string](), - nodePrivateIPs: map[string]sets.Set[string]{}, + unmanagedNodes: utilsets.NewString(), + excludeLoadBalancerNodes: utilsets.NewString(), + nodePrivateIPs: map[string]*utilsets.IgnoreCaseSet{}, routeCIDRs: map[string]string{}, eventRecorder: &record.FakeRecorder{}, + lockMap: newLockMap(), } az.DisksClient = mockdiskclient.NewMockInterface(ctrl) az.SnapshotsClient = mocksnapshotclient.NewMockInterface(ctrl) @@ -129,8 +130,6 @@ func GetTestCloud(ctrl *gomock.Controller) (az *Cloud) { az.LoadBalancerBackendPool = NewMockBackendPool(ctrl) az.storageAccountCache, _ = az.newStorageAccountCache() - _ = InitDiskControllers(az) - az.regionZonesMap = map[string][]string{az.Location: {"1", "2", "3"}} return az diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances_v1.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances_v1.go index e8a4a76f4..2e5c9ebbf 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances_v1.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances_v1.go @@ -35,12 +35,6 @@ import ( var _ cloudprovider.Instances = (*Cloud)(nil) const ( - vmPowerStatePrefix = "PowerState/" - vmPowerStateStopped = "stopped" - vmPowerStateDeallocated = "deallocated" - vmPowerStateDeallocating = "deallocating" - vmPowerStateUnknown = "unknown" - // nodeNameEnvironmentName is the environment variable name for getting node name. // It is only used for out-of-tree cloud provider. nodeNameEnvironmentName = "NODE_NAME" @@ -266,7 +260,7 @@ func (az *Cloud) InstanceShutdownByProviderID(_ context.Context, providerID stri status := strings.ToLower(powerStatus) provisioningSucceeded := strings.EqualFold(strings.ToLower(provisioningState), strings.ToLower(string(consts.ProvisioningStateSucceeded))) - return provisioningSucceeded && (status == vmPowerStateStopped || status == vmPowerStateDeallocated || status == vmPowerStateDeallocating), nil + return provisioningSucceeded && (status == consts.VMPowerStateStopped || status == consts.VMPowerStateDeallocated || status == consts.VMPowerStateDeallocating), nil } func (az *Cloud) isCurrentInstance(name types.NodeName, metadataVMName string) (bool, error) { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go index 168efc90c..c4a4d2c50 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go @@ -36,7 +36,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/sets" cloudprovider "k8s.io/cloud-provider" servicehelpers "k8s.io/cloud-provider/service/helpers" "k8s.io/klog/v2" @@ -50,6 +49,7 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer" "sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/iputil" "sigs.k8s.io/cloud-provider-azure/pkg/retry" + utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) var _ cloudprovider.LoadBalancer = (*Cloud)(nil) @@ -269,7 +269,7 @@ func (az *Cloud) UpdateLoadBalancer(ctx context.Context, clusterName string, ser } if !serviceExists { isOperationSucceeded = true - klog.V(2).Infof("UpdateLoadBalancer: skipping service %s because service is going to be deleted", service.Name) + klog.V(2).Infof("UpdateLoadBalancer: skipping service %s because service is going to be deleted", serviceName) return nil } @@ -394,10 +394,10 @@ func (az *Cloud) shouldChangeLoadBalancer(service *v1.Service, currLBName, clust return false } - lbName := strings.TrimSuffix(currLBName, consts.InternalLoadBalancerNameSuffix) + lbName := trimSuffixIgnoreCase(currLBName, consts.InternalLoadBalancerNameSuffix) // change the LB from vmSet dedicated to primary if the vmSet becomes the primary one if strings.EqualFold(lbName, vmSetName) { - if lbName != clusterName && + if !strings.EqualFold(lbName, clusterName) && strings.EqualFold(az.VMSet.GetPrimaryVMSetName(), vmSetName) { klog.V(2).Infof("shouldChangeLoadBalancer(%s, %s, %s): change the LB to another one", service.Name, currLBName, clusterName) return true @@ -593,15 +593,13 @@ func (az *Cloud) safeDeleteLoadBalancer(lb network.LoadBalancer, clusterName, vm // Remove corresponding nodes in ActiveNodes and nodesWithCorrectLoadBalancerByPrimaryVMSet. for i := range az.MultipleStandardLoadBalancerConfigurations { if strings.EqualFold( - strings.TrimSuffix(pointer.StringDeref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), + trimSuffixIgnoreCase(pointer.StringDeref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), az.MultipleStandardLoadBalancerConfigurations[i].Name, ) { - if az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes != nil { - for nodeName := range az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes { - az.nodesWithCorrectLoadBalancerByPrimaryVMSet.Delete(strings.ToLower(nodeName)) - } + for _, nodeName := range az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes.UnsortedList() { + az.nodesWithCorrectLoadBalancerByPrimaryVMSet.Delete(nodeName) } - az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes = sets.New[string]() + az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes = utilsets.NewString() break } } @@ -1597,12 +1595,9 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerConfigurations( lbName, ruleName, svcName, ) for i := range az.MultipleStandardLoadBalancerConfigurations { - if strings.EqualFold(strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix), az.MultipleStandardLoadBalancerConfigurations[i].Name) { + if strings.EqualFold(trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix), az.MultipleStandardLoadBalancerConfigurations[i].Name) { az.multipleStandardLoadBalancersActiveServicesLock.Lock() - if az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices == nil { - az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices = sets.New[string]() - } - az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices.Insert(strings.ToLower(svcName)) + az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices = utilsets.SafeInsert(az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices, svcName) az.multipleStandardLoadBalancersActiveServicesLock.Unlock() klog.V(2).Infof("reconcileMultipleStandardLoadBalancerConfigurations: service(%s) is active on lb(%s)", svcName, lbName) } @@ -1918,9 +1913,9 @@ func (az *Cloud) removeNodeFromLBConfig(nodeNameToLBConfigIDXMap map[string]int, // removeDeletedNodesFromLoadBalancerConfigurations removes the deleted nodes // that do not exist in nodes list from the load balancer configurations func (az *Cloud) removeDeletedNodesFromLoadBalancerConfigurations(nodes []*v1.Node) map[string]int { - nodeNamesSet := sets.New[string]() + nodeNamesSet := utilsets.NewString() for _, node := range nodes { - nodeNamesSet.Insert(strings.ToLower(node.Name)) + nodeNamesSet.Insert(node.Name) } az.multipleStandardLoadBalancersActiveNodesLock.Lock() @@ -1930,12 +1925,12 @@ func (az *Cloud) removeDeletedNodesFromLoadBalancerConfigurations(nodes []*v1.No nodeNameToLBConfigIDXMap := make(map[string]int) for i, multiSLBConfig := range az.MultipleStandardLoadBalancerConfigurations { if multiSLBConfig.ActiveNodes != nil { - for nodeName := range multiSLBConfig.ActiveNodes { + for _, nodeName := range multiSLBConfig.ActiveNodes.UnsortedList() { if nodeNamesSet.Has(nodeName) { nodeNameToLBConfigIDXMap[nodeName] = i } else { klog.V(4).Infof("reconcileMultipleStandardLoadBalancerBackendNodes: node(%s) is gone, remove it from lb(%s)", nodeName, multiSLBConfig.Name) - az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes, _ = safeRemoveKeyFromStringsSet(az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes, strings.ToLower(nodeName)) + az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes.Delete(nodeName) } } } @@ -1966,19 +1961,19 @@ func (az *Cloud) accommodateNodesByPrimaryVMSet( multiSLBConfig := az.MultipleStandardLoadBalancerConfigurations[i] if strings.EqualFold(multiSLBConfig.PrimaryVMSet, vmSetName) { foundPrimaryLB := isLBInList(lbs, multiSLBConfig.Name) - if !foundPrimaryLB && !strings.EqualFold(strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { + if !foundPrimaryLB && !strings.EqualFold(trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { klog.V(4).Infof("accommodateNodesByPrimaryVMSet: node(%s) should be on lb(%s) because of primary vmSet (%s), but the lb is not found and will not be created this time, will ignore the primaryVMSet", node.Name, multiSLBConfig.Name, vmSetName) continue } - az.nodesWithCorrectLoadBalancerByPrimaryVMSet.Store(strings.ToLower(node.Name), sets.Empty{}) + az.nodesWithCorrectLoadBalancerByPrimaryVMSet.Store(strings.ToLower(node.Name), struct{}{}) if !multiSLBConfig.ActiveNodes.Has(node.Name) { klog.V(4).Infof("accommodateNodesByPrimaryVMSet: node(%s) should be on lb(%s) because of primary vmSet (%s)", node.Name, multiSLBConfig.Name, vmSetName) az.removeNodeFromLBConfig(nodeNameToLBConfigIDXMap, node.Name) az.multipleStandardLoadBalancersActiveNodesLock.Lock() - az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes = safeAddKeyToStringsSet(az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes, strings.ToLower(node.Name)) + az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes = utilsets.SafeInsert(az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes, node.Name) az.multipleStandardLoadBalancersActiveNodesLock.Unlock() } break @@ -2018,7 +2013,7 @@ func (az *Cloud) accommodateNodesByNodeSelector( if nodeSelector.Matches(labels.Set(node.Labels)) { klog.V(4).Infof("accommodateNodesByNodeSelector: lb(%s) matches node(%s) labels", multiSLBConfig.Name, node.Name) found := isLBInList(lbs, multiSLBConfig.Name) - if !found && !strings.EqualFold(strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { + if !found && !strings.EqualFold(trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { klog.V(4).Infof("accommodateNodesByNodeSelector: but the lb is not found and will not be created this time, will ignore this load balancer") continue } @@ -2039,7 +2034,7 @@ func (az *Cloud) accommodateNodesByNodeSelector( for i := len(eligibleLBsIDX) - 1; i >= 0; i-- { multiSLBConfig := az.MultipleStandardLoadBalancerConfigurations[eligibleLBsIDX[i]] found := isLBInList(lbs, multiSLBConfig.Name) - if !found && !strings.EqualFold(strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { + if !found && !strings.EqualFold(trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix), multiSLBConfig.Name) { klog.V(4).Infof("accommodateNodesByNodeSelector: the load balancer %s is a valid placement target for node %s, but the lb is not found and will not be created this time, ignore this load balancer", multiSLBConfig.Name, node.Name) eligibleLBsIDX = append(eligibleLBsIDX[:i], eligibleLBsIDX[i+1:]...) } @@ -2077,7 +2072,7 @@ func (az *Cloud) accommodateNodesByNodeSelector( klog.V(4).Infof("accommodateNodesByNodeSelector: node(%s) should be on lb(%s) it is the eligible LB with fewest number of nodes", node.Name, az.MultipleStandardLoadBalancerConfigurations[minNodesIDX].Name) az.multipleStandardLoadBalancersActiveNodesLock.Lock() - az.MultipleStandardLoadBalancerConfigurations[minNodesIDX].ActiveNodes = safeAddKeyToStringsSet(az.MultipleStandardLoadBalancerConfigurations[minNodesIDX].ActiveNodes, strings.ToLower(node.Name)) + az.MultipleStandardLoadBalancerConfigurations[minNodesIDX].ActiveNodes = utilsets.SafeInsert(az.MultipleStandardLoadBalancerConfigurations[minNodesIDX].ActiveNodes, node.Name) az.multipleStandardLoadBalancersActiveNodesLock.Unlock() } @@ -2088,7 +2083,7 @@ func (az *Cloud) accommodateNodesByNodeSelector( func isLBInList(lbs *[]network.LoadBalancer, lbConfigName string) bool { if lbs != nil { for _, lb := range *lbs { - if strings.EqualFold(strings.TrimSuffix(pointer.StringDeref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), lbConfigName) { + if strings.EqualFold(trimSuffixIgnoreCase(pointer.StringDeref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), lbConfigName) { return true } } @@ -2135,20 +2130,17 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerBackendNodes( } func (az *Cloud) reconcileMultipleStandardLoadBalancerConfigurationStatus(wantLb bool, svcName, lbName string) { - lbName = strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix) + lbName = trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix) for i := range az.MultipleStandardLoadBalancerConfigurations { if strings.EqualFold(lbName, az.MultipleStandardLoadBalancerConfigurations[i].Name) { az.multipleStandardLoadBalancersActiveServicesLock.Lock() - if az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices == nil { - az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices = sets.New[string]() - } if wantLb { klog.V(4).Infof("reconcileMultipleStandardLoadBalancerConfigurationStatus: service(%s) is active on lb(%s)", svcName, lbName) - az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices.Insert(strings.ToLower(svcName)) + az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices = utilsets.SafeInsert(az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices, svcName) } else { klog.V(4).Infof("reconcileMultipleStandardLoadBalancerConfigurationStatus: service(%s) is not active on lb(%s) any more", svcName, lbName) - az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices, _ = safeRemoveKeyFromStringsSet(az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices, strings.ToLower(svcName)) + az.MultipleStandardLoadBalancerConfigurations[i].ActiveServices.Delete(svcName) } az.multipleStandardLoadBalancersActiveServicesLock.Unlock() break @@ -3298,7 +3290,7 @@ func (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string // Check whether there are still load balancer rules referring to it. if len(referencedLBRules) > 0 { - referencedLBRuleIDs := sets.New[string]() + referencedLBRuleIDs := utilsets.NewString() for _, refer := range referencedLBRules { referencedLBRuleIDs.Insert(pointer.StringDeref(refer.ID, "")) } @@ -3793,7 +3785,7 @@ func getMostEligibleLBForService( var found bool if existingLBs != nil { for _, existingLB := range *existingLBs { - if strings.EqualFold(pointer.StringDeref(existingLB.Name, ""), eligibleLB) { + if strings.EqualFold(trimSuffixIgnoreCase(pointer.StringDeref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLB) { found = true break } @@ -3810,7 +3802,7 @@ func getMostEligibleLBForService( ruleCount := 301 if existingLBs != nil { for _, existingLB := range *existingLBs { - if StringInSlice(pointer.StringDeref(existingLB.Name, ""), eligibleLBs) { + if StringInSlice(trimSuffixIgnoreCase(pointer.StringDeref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLBs) { if existingLB.LoadBalancerPropertiesFormat != nil && existingLB.LoadBalancingRules != nil { if len(*existingLB.LoadBalancingRules) < ruleCount { @@ -3826,7 +3818,7 @@ func getMostEligibleLBForService( klog.V(4).Infof("getMostEligibleLBForService: choose %s with fewest %d rules", expectedLBName, ruleCount) } - return expectedLBName + return trimSuffixIgnoreCase(expectedLBName, consts.InternalLoadBalancerNameSuffix) } func (az *Cloud) getServiceCurrentLoadBalancerName(service *v1.Service) string { @@ -3844,9 +3836,8 @@ func (az *Cloud) getServiceCurrentLoadBalancerName(service *v1.Service) string { // 2. AllowServicePlacement flag. Default to true, if set to false, the new services will not be put onto the LB. // But the existing services that is using the LB will not be affected. // 3. ServiceLabelSelector. The service will be put onto the LB only if the service has the labels specified in the selector. -// If there is no ServiceLabel selector on the LB, all services can be valid. // 4. ServiceNamespaceSelector. The service will be put onto the LB only if the service is in the namespaces specified in the selector. -// If there is no ServiceNamespace selector on the LB, all services can be valid. +// 5. If there is no label/namespace selector on the LB, it can be a valid placement target if and only if the service has no other choice. func (az *Cloud) getEligibleLoadBalancersForService(service *v1.Service) ([]string, error) { var ( eligibleLBs []MultipleStandardLoadBalancerConfiguration @@ -3857,14 +3848,19 @@ func (az *Cloud) getEligibleLoadBalancersForService(service *v1.Service) ([]stri lbFailedPlacementFlag []string ) + logger := klog.Background(). + WithName("getEligibleLoadBalancersForService"). + WithValues("service", service.Name) + // 1. Service selects LBs defined in the annotation. // If there is no annotation given, it selects all LBs. lbsFromAnnotation := consts.GetLoadBalancerConfigurationsNames(service) if len(lbsFromAnnotation) > 0 { - lbNamesSet := sets.New[string](lbsFromAnnotation...) + lbNamesSet := utilsets.NewString(lbsFromAnnotation...) for _, multiSLBConfig := range az.MultipleStandardLoadBalancerConfigurations { - if lbNamesSet.Has(strings.ToLower(multiSLBConfig.Name)) { - klog.V(4).Infof("getEligibleLoadBalancersForService: service %q selects load balancer %q by annotation", service.Name, multiSLBConfig.Name) + if lbNamesSet.Has(multiSLBConfig.Name) { + logger.V(4).Info("selects the load balancer by annotation", + "load balancer configuration name", multiSLBConfig.Name) eligibleLBs = append(eligibleLBs, multiSLBConfig) lbSelectedByAnnotation = append(lbSelectedByAnnotation, multiSLBConfig.Name) } @@ -3873,13 +3869,14 @@ func (az *Cloud) getEligibleLoadBalancersForService(service *v1.Service) ([]stri return nil, fmt.Errorf("service %q selects %d load balancers by annotation, but none of them is defined in cloud provider configuration", service.Name, len(lbsFromAnnotation)) } } else { - klog.V(4).Infof("getEligibleLoadBalancersForService: service %q does not select any load balancer by annotation, all load balancers are eligible", service.Name) + logger.V(4).Info("the service does not select any load balancer by annotation, all load balancers are eligible") eligibleLBs = append(eligibleLBs, az.MultipleStandardLoadBalancerConfigurations...) for _, eligibleLB := range eligibleLBs { lbSelectedByAnnotation = append(lbSelectedByAnnotation, eligibleLB.Name) } } + var selectorMatched bool for i := len(eligibleLBs) - 1; i >= 0; i-- { eligibleLB := eligibleLBs[i] @@ -3887,9 +3884,11 @@ func (az *Cloud) getEligibleLoadBalancersForService(service *v1.Service) ([]stri // unless the service is already using the LB. if !pointer.BoolDeref(eligibleLB.AllowServicePlacement, true) { if az.isLoadBalancerInUseByService(service, eligibleLB) { - klog.V(4).Infof("getEligibleLoadBalancersForService: although load balancer %q has AllowServicePlacement=false, service %q is allowed to be placed on load balancer %q because it is using the load balancer", eligibleLB.Name, service.Name, eligibleLB.Name) + logger.V(4).Info("although the load balancer has AllowServicePlacement=false, service is allowed to be placed on load balancer because it is using the load balancer", + "load balancer configuration name", eligibleLB.Name) } else { - klog.V(4).Infof("getEligibleLoadBalancersForService: service %q is not allowed to be placed on load balancer %q", service.Name, eligibleLB.Name) + logger.V(4).Info("the load balancer has AllowServicePlacement=false, service is not allowed to be placed on load balancer", + "load balancer configuration name", eligibleLB.Name) eligibleLBs = append(eligibleLBs[:i], eligibleLBs[i+1:]...) lbFailedPlacementFlag = append(lbFailedPlacementFlag, eligibleLB.Name) continue @@ -3901,15 +3900,23 @@ func (az *Cloud) getEligibleLoadBalancersForService(service *v1.Service) ([]stri if eligibleLB.ServiceLabelSelector != nil { serviceLabelSelector, err := metav1.LabelSelectorAsSelector(eligibleLB.ServiceLabelSelector) if err != nil { - klog.Errorf("Failed to parse label selector %q for load balancer %q: %s", eligibleLB.ServiceLabelSelector.String(), eligibleLB.Name, err.Error()) + logger.Error(err, "failed to parse label selector", + "label selector", eligibleLB.ServiceLabelSelector.String(), + "load balancer configuration name", eligibleLB.Name) return []string{}, err } if !serviceLabelSelector.Matches(labels.Set(service.Labels)) { - klog.V(2).Infof("getEligibleLoadBalancersForService: service %q does not match label selector %q for load balancer %q", service.Name, eligibleLB.ServiceLabelSelector.String(), eligibleLB.Name) + logger.V(2).Info("service does not match the label selector", + "label selector", eligibleLB.ServiceLabelSelector.String(), + "load balancer configuration name", eligibleLB.Name) eligibleLBs = append(eligibleLBs[:i], eligibleLBs[i+1:]...) lbFailedLabelSelector = append(lbFailedLabelSelector, eligibleLB.Name) continue } + logger.V(4).Info("service matches the label selector", + "label selector", eligibleLB.ServiceLabelSelector.String(), + "load balancer configuration name", eligibleLB.Name) + selectorMatched = true } // 4. Check the service namespace selector. The service can be migrated from one LB to another LB @@ -3917,20 +3924,32 @@ func (az *Cloud) getEligibleLoadBalancersForService(service *v1.Service) ([]stri if eligibleLB.ServiceNamespaceSelector != nil { serviceNamespaceSelector, err := metav1.LabelSelectorAsSelector(eligibleLB.ServiceNamespaceSelector) if err != nil { - klog.Errorf("Failed to parse namespace selector %q for load balancer %q: %s", eligibleLB.ServiceNamespaceSelector.String(), eligibleLB.Name, err.Error()) + logger.Error(err, "failed to parse namespace selector", + "namespace selector", eligibleLB.ServiceNamespaceSelector.String(), + "load balancer configuration name", eligibleLB.Name) return []string{}, err } ns, err := az.KubeClient.CoreV1().Namespaces().Get(context.Background(), service.Namespace, metav1.GetOptions{}) if err != nil { - klog.Errorf("Failed to get namespace %q for load balancer %q: %s", service.Namespace, eligibleLB.Name, err.Error()) + logger.Error(err, "failed to get namespace", + "namespace", service.Namespace, + "load balancer configuration name", eligibleLB.Name) return []string{}, err } if !serviceNamespaceSelector.Matches(labels.Set(ns.Labels)) { - klog.V(2).Infof("getEligibleLoadBalancersForService: namespace %q does not match namespace selector %q for load balancer %q", service.Namespace, eligibleLB.ServiceNamespaceSelector.String(), eligibleLB.Name) + logger.V(2).Info("namespace does not match the namespace selector", + "namespace", service.Namespace, + "namespace selector", eligibleLB.ServiceNamespaceSelector.String(), + "load balancer configuration name", eligibleLB.Name) eligibleLBs = append(eligibleLBs[:i], eligibleLBs[i+1:]...) lbFailedNamespaceSelector = append(lbFailedNamespaceSelector, eligibleLB.Name) continue } + logger.V(4).Info("namespace matches the namespace selector", + "namespace", service.Namespace, + "namespace selector", eligibleLB.ServiceNamespaceSelector.String(), + "load balancer configuration name", eligibleLB.Name) + selectorMatched = true } } @@ -3950,6 +3969,19 @@ func (az *Cloud) getEligibleLoadBalancersForService(service *v1.Service) ([]stri ) } + if selectorMatched { + for i := len(eligibleLBs) - 1; i >= 0; i-- { + eligibleLB := eligibleLBs[i] + if eligibleLB.ServiceLabelSelector == nil && eligibleLB.ServiceNamespaceSelector == nil { + logger.V(6).Info("service matches at least one label/namespace selector of the load balancer, so it should not be placed on the load balancer that does not have any label/namespace selector", + "load balancer configuration name", eligibleLB.Name) + eligibleLBs = append(eligibleLBs[:i], eligibleLBs[i+1:]...) + } + } + } else { + logger.V(4).Info("no load balancer that has label/namespace selector matches the service, so the service can be placed on the load balancers that do not have label/namespace selector") + } + for _, eligibleLB := range eligibleLBs { eligibleLBNames = append(eligibleLBNames, eligibleLB.Name) } @@ -3962,10 +3994,7 @@ func (az *Cloud) isLoadBalancerInUseByService(service *v1.Service, lbConfig Mult defer az.multipleStandardLoadBalancersActiveServicesLock.Unlock() serviceName := getServiceName(service) - if lbConfig.ActiveServices != nil { - return lbConfig.ActiveServices.Has(serviceName) - } - return false + return lbConfig.ActiveServices.Has(serviceName) } // There are two cases when a service owns the frontend IP config: diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go index 67f213c32..b33ee2e71 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go @@ -26,7 +26,6 @@ import ( "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/sets" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" utilnet "k8s.io/utils/net" @@ -35,6 +34,7 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/metrics" + utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) type BackendPool interface { @@ -304,8 +304,8 @@ func getBackendIPConfigurationsToBeDeleted( return []network.InterfaceIPConfiguration{} } - bipConfigNotFoundIDSet := sets.New[string]() - bipConfigExcludeIDSet := sets.New[string]() + bipConfigNotFoundIDSet := utilsets.NewString() + bipConfigExcludeIDSet := utilsets.NewString() for _, ipConfig := range bipConfigNotFound { bipConfigNotFoundIDSet.Insert(pointer.StringDeref(ipConfig.ID, "")) } @@ -344,7 +344,7 @@ func (bc *backendPoolTypeNodeIPConfig) GetBackendPrivateIPs(clusterName string, return nil, nil } - backendPrivateIPv4s, backendPrivateIPv6s := sets.New[string](), sets.New[string]() + backendPrivateIPv4s, backendPrivateIPv6s := utilsets.NewString(), utilsets.NewString() for _, bp := range *lb.BackendAddressPools { found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { @@ -399,7 +399,7 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(service *v1.Service, nodes [] var ( changed bool numOfAdd, numOfDelete int - activeNodes sets.Set[string] + activeNodes *utilsets.IgnoreCaseSet err error ) if bi.useMultipleStandardLoadBalancers() { @@ -420,9 +420,6 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(service *v1.Service, nodes [] return err } } - if activeNodes == nil { - activeNodes = sets.New[string]() - } } lbBackendPoolName := bi.getBackendPoolNameForService(service, clusterName, isIPv6) @@ -437,7 +434,7 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(service *v1.Service, nodes [] backendPool.LoadBalancerBackendAddresses = &lbBackendPoolAddresses } - existingIPs := sets.New[string]() + existingIPs := utilsets.NewString() for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses { if loadBalancerBackendAddress.LoadBalancerBackendAddressPropertiesFormat != nil && loadBalancerBackendAddress.IPAddress != nil { @@ -447,7 +444,7 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(service *v1.Service, nodes [] } var nodeIPsToBeAdded []string - nodePrivateIPsSet := sets.New[string]() + nodePrivateIPsSet := utilsets.NewString() for _, node := range nodes { if isControlPlaneNode(node) { klog.V(4).Infof("bi.EnsureHostsInPool: skipping control plane node %s", node.Name) @@ -458,7 +455,7 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(service *v1.Service, nodes [] nodePrivateIPsSet.Insert(privateIP) if bi.useMultipleStandardLoadBalancers() { - if activeNodes == nil || !activeNodes.Has(node.Name) { + if !activeNodes.Has(node.Name) { klog.V(4).Infof("bi.EnsureHostsInPool: node %s should not be in load balancer %q", node.Name, lbName) continue } @@ -519,7 +516,7 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(slb *net found, isIPv6 := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { klog.V(2).Infof("bi.CleanupVMSetFromBackendPoolByCondition: checking the backend pool %s from standard load balancer %s", pointer.StringDeref(bp.Name, ""), pointer.StringDeref(slb.Name, "")) - vmIPsToBeDeleted := sets.New[string]() + vmIPsToBeDeleted := utilsets.NewString() for _, node := range nodes { vmSetName, err := bi.VMSet.GetNodeVMSetName(node) if err != nil { @@ -662,8 +659,8 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi for _, i := range bpIdxes { bp := newBackendPools[i] var nodeIPAddressesToBeDeleted []string - for nodeName := range bi.excludeLoadBalancerNodes { - for ip := range bi.nodePrivateIPs[strings.ToLower(nodeName)] { + for _, nodeName := range bi.excludeLoadBalancerNodes.UnsortedList() { + for _, ip := range bi.nodePrivateIPs[strings.ToLower(nodeName)].UnsortedList() { klog.V(2).Infof("bi.ReconcileBackendPools for service (%s): found unwanted node private IP %s, decouple it from the LB %s", serviceName, ip, lbName) nodeIPAddressesToBeDeleted = append(nodeIPAddressesToBeDeleted, ip) } @@ -744,7 +741,7 @@ func (bi *backendPoolTypeNodeIP) GetBackendPrivateIPs(clusterName string, servic return nil, nil } - backendPrivateIPv4s, backendPrivateIPv6s := sets.New[string](), sets.New[string]() + backendPrivateIPv4s, backendPrivateIPv6s := utilsets.NewString(), utilsets.NewString() for _, bp := range *lb.BackendAddressPools { found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { @@ -839,7 +836,7 @@ func removeNodeIPAddressesFromBackendPool( removeAll, useMultipleStandardLoadBalancers bool, ) bool { changed := false - nodeIPsSet := sets.New(nodeIPAddresses...) + nodeIPsSet := utilsets.NewString(nodeIPAddresses...) if backendPool.BackendAddressPoolPropertiesFormat == nil || backendPool.LoadBalancerBackendAddresses == nil { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go index 83ac58487..cfee45118 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go @@ -26,8 +26,8 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/klog/v2" "k8s.io/utils/pointer" @@ -35,6 +35,7 @@ import ( azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/retry" + utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) // DeleteLB invokes az.LoadBalancerClient.Delete with exponential backoff retry @@ -87,7 +88,7 @@ func (az *Cloud) ListManagedLBs(service *v1.Service, nodes []*v1.Node, clusterNa return nil, nil } - managedLBNames := sets.New[string](strings.ToLower(clusterName)) + managedLBNames := utilsets.NewString(clusterName) managedLBs := make([]network.LoadBalancer, 0) if strings.EqualFold(az.LoadBalancerSku, consts.LoadBalancerSkuBasic) { // return early if wantLb=false @@ -121,7 +122,7 @@ func (az *Cloud) ListManagedLBs(service *v1.Service, nodes []*v1.Node, clusterNa } for _, lb := range allLBs { - if managedLBNames.Has(strings.ToLower(strings.TrimSuffix(pointer.StringDeref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix))) { + if managedLBNames.Has(trimSuffixIgnoreCase(pointer.StringDeref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix)) { managedLBs = append(managedLBs, lb) klog.V(4).Infof("ListManagedLBs: found managed LB %s", pointer.StringDeref(lb.Name, "")) } @@ -372,7 +373,7 @@ func isBackendPoolOnSameLB(newBackendPoolID string, existingBackendPools []strin } newLBName := matches[1] - newLBNameTrimmed := strings.TrimSuffix(newLBName, consts.InternalLoadBalancerNameSuffix) + newLBNameTrimmed := trimSuffixIgnoreCase(newLBName, consts.InternalLoadBalancerNameSuffix) for _, backendPool := range existingBackendPools { matches := backendPoolIDRE.FindStringSubmatch(backendPool) if len(matches) != 2 { @@ -380,7 +381,7 @@ func isBackendPoolOnSameLB(newBackendPoolID string, existingBackendPools []strin } lbName := matches[1] - if !strings.EqualFold(strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix), newLBNameTrimmed) { + if !strings.EqualFold(trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix), newLBNameTrimmed) { return false, lbName, nil } } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go index 25ff0e816..63640d7b4 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go @@ -38,6 +38,7 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/retry" + utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) // batchProcessor collects operations in a certain interval and then processes them in batches. @@ -329,11 +330,11 @@ func (az *Cloud) setUpEndpointSlicesInformer(informerFactory informers.SharedInf } for _, previousNodeName := range previousNodeNames { nodeIPsSet := az.nodePrivateIPs[strings.ToLower(previousNodeName)] - previousIPs = append(previousIPs, setToStrings(nodeIPsSet)...) + previousIPs = append(previousIPs, nodeIPsSet.UnsortedList()...) } for _, currentNodeName := range currentNodeNames { nodeIPsSet := az.nodePrivateIPs[strings.ToLower(currentNodeName)] - currentIPs = append(currentIPs, setToStrings(nodeIPsSet)...) + currentIPs = append(currentIPs, nodeIPsSet.UnsortedList()...) } if az.backendPoolUpdater != nil { @@ -462,7 +463,7 @@ func newServiceInfo(ipFamily, lbName string) *serviceInfo { } // getLocalServiceEndpointsNodeNames gets the node names that host all endpoints of the local service. -func (az *Cloud) getLocalServiceEndpointsNodeNames(service *v1.Service) (sets.Set[string], error) { +func (az *Cloud) getLocalServiceEndpointsNodeNames(service *v1.Service) (*utilsets.IgnoreCaseSet, error) { var ( ep *discovery_v1.EndpointSlice foundInCache bool @@ -505,7 +506,7 @@ func (az *Cloud) getLocalServiceEndpointsNodeNames(service *v1.Service) (sets.Se nodeNames = append(nodeNames, pointer.StringDeref(endpoint.NodeName, "")) } - return sets.New[string](nodeNames...), nil + return utilsets.NewString(nodeNames...), nil } // cleanupLocalServiceBackendPool cleans up the backend pool of @@ -553,11 +554,9 @@ func (az *Cloud) checkAndApplyLocalServiceBackendPoolUpdates(lb network.LoadBala return err } var expectedIPs []string - for nodeName := range endpointsNodeNames { + for _, nodeName := range endpointsNodeNames.UnsortedList() { ips := az.nodePrivateIPs[strings.ToLower(nodeName)] - for ip := range ips { - expectedIPs = append(expectedIPs, ip) - } + expectedIPs = append(expectedIPs, ips.UnsortedList()...) } currentIPsInBackendPools := make(map[string][]string) for _, bp := range *lb.BackendAddressPools { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_managedDiskController.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_managedDiskController.go deleted file mode 100644 index 206be6034..000000000 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_managedDiskController.go +++ /dev/null @@ -1,461 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package provider - -import ( - "context" - "fmt" - "net/http" - "path" - "strconv" - "strings" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - - v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - kwait "k8s.io/apimachinery/pkg/util/wait" - cloudprovider "k8s.io/cloud-provider" - cloudvolume "k8s.io/cloud-provider/volume" - volumehelpers "k8s.io/cloud-provider/volume/helpers" - "k8s.io/klog/v2" - "k8s.io/utils/pointer" - - "sigs.k8s.io/cloud-provider-azure/pkg/consts" -) - -var _ cloudprovider.PVLabeler = (*Cloud)(nil) - -// ManagedDiskController : managed disk controller struct -type ManagedDiskController struct { - *controllerCommon -} - -// ManagedDiskOptions specifies the options of managed disks. -type ManagedDiskOptions struct { - // The SKU of storage account. - StorageAccountType compute.DiskStorageAccountTypes - // The name of the disk. - DiskName string - // The name of PVC. - PVCName string - // The name of resource group. - ResourceGroup string - // The AvailabilityZone to create the disk. - AvailabilityZone string - // The tags of the disk. - Tags map[string]string - // IOPS Caps for UltraSSD disk - DiskIOPSReadWrite string - // Throughput Cap (MBps) for UltraSSD disk - DiskMBpsReadWrite string - // if SourceResourceID is not empty, then it's a disk copy operation(for snapshot) - SourceResourceID string - // The type of source - SourceType string - // ResourceId of the disk encryption set to use for enabling encryption at rest. - DiskEncryptionSetID string - // DiskEncryption type, available values: EncryptionAtRestWithCustomerKey, EncryptionAtRestWithPlatformAndCustomerKeys - DiskEncryptionType string - // The size in GB. - SizeGB int - // The maximum number of VMs that can attach to the disk at the same time. Value greater than one indicates a disk that can be mounted on multiple VMs at the same time. - MaxShares int32 - // Logical sector size in bytes for Ultra disks - LogicalSectorSize int32 - // SkipGetDiskOperation indicates whether skip GetDisk operation(mainly due to throttling) - SkipGetDiskOperation bool - // PublicNetworkAccess - Possible values include: 'Enabled', 'Disabled' - PublicNetworkAccess compute.PublicNetworkAccess - // NetworkAccessPolicy - Possible values include: 'AllowAll', 'AllowPrivate', 'DenyAll' - NetworkAccessPolicy compute.NetworkAccessPolicy - // DiskAccessID - ARM id of the DiskAccess resource for using private endpoints on disks. - DiskAccessID *string - // BurstingEnabled - Set to true to enable bursting beyond the provisioned performance target of the disk. - BurstingEnabled *bool - // SubscriptionID - specify a different SubscriptionID - SubscriptionID string - // Location - specify a different location - Location string - // PerformancePlus - Set this flag to true to get a boost on the performance target of the disk deployed - PerformancePlus *bool -} - -// CreateManagedDisk: create managed disk -func (c *ManagedDiskController) CreateManagedDisk(ctx context.Context, options *ManagedDiskOptions) (string, error) { - var err error - klog.V(4).Infof("azureDisk - creating new managed Name:%s StorageAccountType:%s Size:%v", options.DiskName, options.StorageAccountType, options.SizeGB) - - var createZones []string - if len(options.AvailabilityZone) > 0 { - requestedZone := c.cloud.GetZoneID(options.AvailabilityZone) - if requestedZone != "" { - createZones = append(createZones, requestedZone) - } - } - - // insert original tags to newTags - newTags := make(map[string]*string) - azureDDTag := "kubernetes-azure-dd" - newTags[consts.CreatedByTag] = &azureDDTag - if options.Tags != nil { - for k, v := range options.Tags { - // Azure won't allow / (forward slash) in tags - newKey := strings.Replace(k, "/", "-", -1) - newValue := strings.Replace(v, "/", "-", -1) - newTags[newKey] = &newValue - } - } - - diskSizeGB := int32(options.SizeGB) - diskSku := options.StorageAccountType - - rg := c.cloud.ResourceGroup - if options.ResourceGroup != "" { - rg = options.ResourceGroup - } - if options.SubscriptionID != "" && !strings.EqualFold(options.SubscriptionID, c.cloud.SubscriptionID) && options.ResourceGroup == "" { - return "", fmt.Errorf("resourceGroup must be specified when subscriptionID(%s) is not empty", options.SubscriptionID) - } - subsID := c.cloud.SubscriptionID - if options.SubscriptionID != "" { - subsID = options.SubscriptionID - } - - creationData, err := getValidCreationData(subsID, rg, options) - if err != nil { - return "", err - } - diskProperties := compute.DiskProperties{ - DiskSizeGB: &diskSizeGB, - CreationData: &creationData, - BurstingEnabled: options.BurstingEnabled, - } - - if options.PublicNetworkAccess != "" { - diskProperties.PublicNetworkAccess = options.PublicNetworkAccess - } - - if options.NetworkAccessPolicy != "" { - diskProperties.NetworkAccessPolicy = options.NetworkAccessPolicy - if options.NetworkAccessPolicy == compute.AllowPrivate { - if options.DiskAccessID == nil { - return "", fmt.Errorf("DiskAccessID should not be empty when NetworkAccessPolicy is AllowPrivate") - } - diskProperties.DiskAccessID = options.DiskAccessID - } else { - if options.DiskAccessID != nil { - return "", fmt.Errorf("DiskAccessID(%s) must be empty when NetworkAccessPolicy(%s) is not AllowPrivate", *options.DiskAccessID, options.NetworkAccessPolicy) - } - } - } - - if diskSku == compute.UltraSSDLRS || diskSku == compute.PremiumV2LRS { - if options.DiskIOPSReadWrite == "" { - if diskSku == compute.UltraSSDLRS { - diskIOPSReadWrite := int64(consts.DefaultDiskIOPSReadWrite) - diskProperties.DiskIOPSReadWrite = pointer.Int64(diskIOPSReadWrite) - } - } else { - v, err := strconv.Atoi(options.DiskIOPSReadWrite) - if err != nil { - return "", fmt.Errorf("AzureDisk - failed to parse DiskIOPSReadWrite: %w", err) - } - diskIOPSReadWrite := int64(v) - diskProperties.DiskIOPSReadWrite = pointer.Int64(diskIOPSReadWrite) - } - - if options.DiskMBpsReadWrite == "" { - if diskSku == compute.UltraSSDLRS { - diskMBpsReadWrite := int64(consts.DefaultDiskMBpsReadWrite) - diskProperties.DiskMBpsReadWrite = pointer.Int64(diskMBpsReadWrite) - } - } else { - v, err := strconv.Atoi(options.DiskMBpsReadWrite) - if err != nil { - return "", fmt.Errorf("AzureDisk - failed to parse DiskMBpsReadWrite: %w", err) - } - diskMBpsReadWrite := int64(v) - diskProperties.DiskMBpsReadWrite = pointer.Int64(diskMBpsReadWrite) - } - - if options.LogicalSectorSize != 0 { - klog.V(2).Infof("AzureDisk - requested LogicalSectorSize: %v", options.LogicalSectorSize) - diskProperties.CreationData.LogicalSectorSize = pointer.Int32(options.LogicalSectorSize) - } - } else { - if options.DiskIOPSReadWrite != "" { - return "", fmt.Errorf("AzureDisk - DiskIOPSReadWrite parameter is only applicable in UltraSSD_LRS disk type") - } - if options.DiskMBpsReadWrite != "" { - return "", fmt.Errorf("AzureDisk - DiskMBpsReadWrite parameter is only applicable in UltraSSD_LRS disk type") - } - if options.LogicalSectorSize != 0 { - return "", fmt.Errorf("AzureDisk - LogicalSectorSize parameter is only applicable in UltraSSD_LRS disk type") - } - } - - if options.DiskEncryptionSetID != "" { - if strings.Index(strings.ToLower(options.DiskEncryptionSetID), "/subscriptions/") != 0 { - return "", fmt.Errorf("AzureDisk - format of DiskEncryptionSetID(%s) is incorrect, correct format: %s", options.DiskEncryptionSetID, consts.DiskEncryptionSetIDFormat) - } - encryptionType := compute.EncryptionTypeEncryptionAtRestWithCustomerKey - if options.DiskEncryptionType != "" { - encryptionType = compute.EncryptionType(options.DiskEncryptionType) - klog.V(4).Infof("azureDisk - DiskEncryptionType: %s, DiskEncryptionSetID: %s", options.DiskEncryptionType, options.DiskEncryptionSetID) - } - diskProperties.Encryption = &compute.Encryption{ - DiskEncryptionSetID: &options.DiskEncryptionSetID, - Type: encryptionType, - } - } else { - if options.DiskEncryptionType != "" { - return "", fmt.Errorf("AzureDisk - DiskEncryptionType(%s) should be empty when DiskEncryptionSetID is not set", options.DiskEncryptionType) - } - } - - if options.MaxShares > 1 { - diskProperties.MaxShares = &options.MaxShares - } - - location := c.cloud.Location - if options.Location != "" { - location = options.Location - } - model := compute.Disk{ - Location: &location, - Tags: newTags, - Sku: &compute.DiskSku{ - Name: diskSku, - }, - DiskProperties: &diskProperties, - } - - if c.cloud.HasExtendedLocation() { - model.ExtendedLocation = &compute.ExtendedLocation{ - Name: pointer.String(c.cloud.ExtendedLocationName), - Type: compute.ExtendedLocationTypes(c.cloud.ExtendedLocationType), - } - } - - if len(createZones) > 0 { - model.Zones = &createZones - } - - if rerr := c.cloud.DisksClient.CreateOrUpdate(ctx, subsID, rg, options.DiskName, model); rerr != nil { - return "", rerr.Error() - } - - diskID := fmt.Sprintf(managedDiskPath, subsID, rg, options.DiskName) - - if options.SkipGetDiskOperation { - klog.Warningf("azureDisk - GetDisk(%s, StorageAccountType:%s) is throttled, unable to confirm provisioningState in poll process", options.DiskName, options.StorageAccountType) - } else { - err = kwait.ExponentialBackoffWithContext(ctx, defaultBackOff, func(ctx context.Context) (bool, error) { - provisionState, id, err := c.GetDisk(ctx, subsID, rg, options.DiskName) - if err == nil { - if id != "" { - diskID = id - } - } else { - // We are waiting for provisioningState==Succeeded - // We don't want to hand-off managed disks to k8s while they are - //still being provisioned, this is to avoid some race conditions - return false, err - } - if strings.ToLower(provisionState) == "succeeded" { - return true, nil - } - return false, nil - }) - - if err != nil { - klog.Warningf("azureDisk - created new MD Name:%s StorageAccountType:%s Size:%v but was unable to confirm provisioningState in poll process", options.DiskName, options.StorageAccountType, options.SizeGB) - } - } - - klog.V(2).Infof("azureDisk - created new MD Name:%s StorageAccountType:%s Size:%v", options.DiskName, options.StorageAccountType, options.SizeGB) - return diskID, nil -} - -// DeleteManagedDisk : delete managed disk -func (c *ManagedDiskController) DeleteManagedDisk(ctx context.Context, diskURI string) error { - resourceGroup, subsID, err := getInfoFromDiskURI(diskURI) - if err != nil { - return err - } - - if state, ok := c.diskStateMap.Load(strings.ToLower(diskURI)); ok { - return fmt.Errorf("failed to delete disk(%s) since it's in %s state", diskURI, state.(string)) - } - - diskName := path.Base(diskURI) - disk, rerr := c.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) - if rerr != nil { - if rerr.HTTPStatusCode == http.StatusNotFound { - klog.V(2).Infof("azureDisk - disk(%s) is already deleted", diskURI) - return nil - } - // ignore GetDisk throttling - if !rerr.IsThrottled() && !strings.Contains(rerr.RawError.Error(), consts.RateLimited) { - return rerr.Error() - } - } - if disk.ManagedBy != nil { - return fmt.Errorf("disk(%s) already attached to node(%s), could not be deleted", diskURI, *disk.ManagedBy) - } - - if rerr := c.cloud.DisksClient.Delete(ctx, subsID, resourceGroup, diskName); rerr != nil { - return rerr.Error() - } - // We don't need poll here, k8s will immediately stop referencing the disk - // the disk will be eventually deleted - cleanly - by ARM - - klog.V(2).Infof("azureDisk - deleted a managed disk: %s", diskURI) - - return nil -} - -// GetDisk return: disk provisionState, diskID, error -func (c *ManagedDiskController) GetDisk(ctx context.Context, subsID, resourceGroup, diskName string) (string, string, error) { - result, rerr := c.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) - if rerr != nil { - return "", "", rerr.Error() - } - - if result.DiskProperties != nil && (*result.DiskProperties).ProvisioningState != nil { - return *(*result.DiskProperties).ProvisioningState, *result.ID, nil - } - return "", "", nil -} - -// ResizeDisk Expand the disk to new size -func (c *ManagedDiskController) ResizeDisk(ctx context.Context, diskURI string, oldSize resource.Quantity, newSize resource.Quantity, supportOnlineResize bool) (resource.Quantity, error) { - diskName := path.Base(diskURI) - resourceGroup, subsID, err := getInfoFromDiskURI(diskURI) - if err != nil { - return oldSize, err - } - - result, rerr := c.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) - if rerr != nil { - return oldSize, rerr.Error() - } - - if result.DiskProperties == nil || result.DiskProperties.DiskSizeGB == nil { - return oldSize, fmt.Errorf("DiskProperties of disk(%s) is nil", diskName) - } - - // Azure resizes in chunks of GiB (not GB) - requestGiB, err := volumehelpers.RoundUpToGiBInt32(newSize) - if err != nil { - return oldSize, err - } - - newSizeQuant := resource.MustParse(fmt.Sprintf("%dGi", requestGiB)) - - klog.V(2).Infof("azureDisk - begin to resize disk(%s) with new size(%d), old size(%v)", diskName, requestGiB, oldSize) - // If disk already of greater or equal size than requested we return - if *result.DiskProperties.DiskSizeGB >= requestGiB { - return newSizeQuant, nil - } - - if !supportOnlineResize && result.DiskProperties.DiskState != compute.Unattached { - return oldSize, fmt.Errorf("azureDisk - disk resize is only supported on Unattached disk, current disk state: %s, already attached to %s", result.DiskProperties.DiskState, pointer.StringDeref(result.ManagedBy, "")) - } - - diskParameter := compute.DiskUpdate{ - DiskUpdateProperties: &compute.DiskUpdateProperties{ - DiskSizeGB: &requestGiB, - }, - } - - if rerr := c.cloud.DisksClient.Update(ctx, subsID, resourceGroup, diskName, diskParameter); rerr != nil { - return oldSize, rerr.Error() - } - - klog.V(2).Infof("azureDisk - resize disk(%s) with new size(%d) completed", diskName, requestGiB) - return newSizeQuant, nil -} - -// get resource group name, subs id from a managed disk URI, e.g. return {group-name}, {sub-id} according to -// /subscriptions/{sub-id}/resourcegroups/{group-name}/providers/microsoft.compute/disks/{disk-id} -// according to https://docs.microsoft.com/en-us/rest/api/compute/disks/get -func getInfoFromDiskURI(diskURI string) (string, string, error) { - fields := strings.Split(diskURI, "/") - if len(fields) != 9 || strings.ToLower(fields[3]) != "resourcegroups" { - return "", "", fmt.Errorf("invalid disk URI: %s", diskURI) - } - return fields[4], fields[2], nil -} - -// PVLabeler is an abstract, pluggable interface for fetching labels for volumes -// GetLabelsForVolume implements PVLabeler.GetLabelsForVolume -func (c *Cloud) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error) { - // Ignore if not AzureDisk. - if pv.Spec.AzureDisk == nil { - return nil, nil - } - - // Ignore any volumes that are being provisioned - if pv.Spec.AzureDisk.DiskName == cloudvolume.ProvisionedVolumeName { - return nil, nil - } - - return c.GetAzureDiskLabels(ctx, pv.Spec.AzureDisk.DataDiskURI) -} - -// GetAzureDiskLabels gets availability zone labels for Azuredisk. -func (c *Cloud) GetAzureDiskLabels(ctx context.Context, diskURI string) (map[string]string, error) { - // Get disk's resource group. - diskName := path.Base(diskURI) - resourceGroup, subsID, err := getInfoFromDiskURI(diskURI) - if err != nil { - klog.Errorf("Failed to get resource group for AzureDisk %s: %v", diskName, err) - return nil, err - } - - labels := map[string]string{ - consts.LabelFailureDomainBetaRegion: c.Location, - } - // no azure credential is set, return nil - if c.DisksClient == nil { - return labels, nil - } - disk, rerr := c.DisksClient.Get(ctx, subsID, resourceGroup, diskName) - if rerr != nil { - klog.Errorf("Failed to get information for AzureDisk %s: %v", diskName, rerr) - return nil, rerr.Error() - } - - // Check whether availability zone is specified. - if disk.Zones == nil || len(*disk.Zones) == 0 { - klog.V(4).Infof("Azure disk %s is not zoned", diskName) - return labels, nil - } - - zones := *disk.Zones - zoneID, err := strconv.Atoi(zones[0]) - if err != nil { - return nil, fmt.Errorf("failed to parse zone %v for AzureDisk %v: %w", zones, diskName, err) - } - - zone := c.makeZone(c.Location, zoneID) - klog.V(4).Infof("Got zone %s for Azure disk %s", zone, diskName) - labels[consts.LabelFailureDomainBetaZone] = zone - return labels, nil -} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_vmsets.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_vmsets.go index 833fb38bc..78de8bf84 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_vmsets.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_vmsets.go @@ -1,34 +1,42 @@ -/* -Copyright 2020 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - +// /* +// Copyright The Kubernetes Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// */ +// + +// Code generated by MockGen. DO NOT EDIT. +// Source: azure_vmsets.go +// +// Generated by this command: +// +// mockgen -package provider -source azure_vmsets.go -self_package sigs.k8s.io/cloud-provider-azure/pkg/provider -copyright_file ../../hack/boilerplate/boilerplate.generatego.txt +// + +// Package provider is a generated GoMock package. package provider import ( context "context" reflect "reflect" + v5 "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - azure "github.com/Azure/go-autorest/autorest/azure" gomock "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" types "k8s.io/apimachinery/pkg/types" cloud_provider "k8s.io/cloud-provider" - cache "sigs.k8s.io/cloud-provider-azure/pkg/cache" ) @@ -56,16 +64,15 @@ func (m *MockVMSet) EXPECT() *MockVMSetMockRecorder { } // AttachDisk mocks base method. -func (m *MockVMSet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) (*azure.Future, error) { +func (m *MockVMSet) AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AttachDisk", ctx, nodeName, diskMap) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret0, _ := ret[0].(error) + return ret0 } // AttachDisk indicates an expected call of AttachDisk. -func (mr *MockVMSetMockRecorder) AttachDisk(ctx, nodeName, diskMap interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) AttachDisk(ctx, nodeName, diskMap any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AttachDisk", reflect.TypeOf((*MockVMSet)(nil).AttachDisk), ctx, nodeName, diskMap) } @@ -79,7 +86,7 @@ func (m *MockVMSet) DeleteCacheForNode(nodeName string) error { } // DeleteCacheForNode indicates an expected call of DeleteCacheForNode. -func (mr *MockVMSetMockRecorder) DeleteCacheForNode(nodeName interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) DeleteCacheForNode(nodeName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCacheForNode", reflect.TypeOf((*MockVMSet)(nil).DeleteCacheForNode), nodeName) } @@ -93,7 +100,7 @@ func (m *MockVMSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis } // DetachDisk indicates an expected call of DetachDisk. -func (mr *MockVMSetMockRecorder) DetachDisk(ctx, nodeName, diskMap interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) DetachDisk(ctx, nodeName, diskMap any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DetachDisk", reflect.TypeOf((*MockVMSet)(nil).DetachDisk), ctx, nodeName, diskMap) } @@ -108,7 +115,7 @@ func (m *MockVMSet) EnsureBackendPoolDeleted(service *v1.Service, backendPoolIDs } // EnsureBackendPoolDeleted indicates an expected call of EnsureBackendPoolDeleted. -func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeleted(service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeleted(service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureBackendPoolDeleted", reflect.TypeOf((*MockVMSet)(nil).EnsureBackendPoolDeleted), service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet) } @@ -122,7 +129,7 @@ func (m *MockVMSet) EnsureBackendPoolDeletedFromVMSets(vmSetNamesMap map[string] } // EnsureBackendPoolDeletedFromVMSets indicates an expected call of EnsureBackendPoolDeletedFromVMSets. -func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeletedFromVMSets(vmSetNamesMap, backendPoolIDs interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeletedFromVMSets(vmSetNamesMap, backendPoolIDs any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureBackendPoolDeletedFromVMSets", reflect.TypeOf((*MockVMSet)(nil).EnsureBackendPoolDeletedFromVMSets), vmSetNamesMap, backendPoolIDs) } @@ -140,7 +147,7 @@ func (m *MockVMSet) EnsureHostInPool(service *v1.Service, nodeName types.NodeNam } // EnsureHostInPool indicates an expected call of EnsureHostInPool. -func (mr *MockVMSetMockRecorder) EnsureHostInPool(service, nodeName, backendPoolID, vmSetName interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureHostInPool(service, nodeName, backendPoolID, vmSetName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostInPool", reflect.TypeOf((*MockVMSet)(nil).EnsureHostInPool), service, nodeName, backendPoolID, vmSetName) } @@ -154,7 +161,7 @@ func (m *MockVMSet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, bac } // EnsureHostsInPool indicates an expected call of EnsureHostsInPool. -func (mr *MockVMSetMockRecorder) EnsureHostsInPool(service, nodes, backendPoolID, vmSetName interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureHostsInPool(service, nodes, backendPoolID, vmSetName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostsInPool", reflect.TypeOf((*MockVMSet)(nil).EnsureHostsInPool), service, nodes, backendPoolID, vmSetName) } @@ -169,23 +176,23 @@ func (m *MockVMSet) GetAgentPoolVMSetNames(nodes []*v1.Node) (*[]string, error) } // GetAgentPoolVMSetNames indicates an expected call of GetAgentPoolVMSetNames. -func (mr *MockVMSetMockRecorder) GetAgentPoolVMSetNames(nodes interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetAgentPoolVMSetNames(nodes any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAgentPoolVMSetNames", reflect.TypeOf((*MockVMSet)(nil).GetAgentPoolVMSetNames), nodes) } // GetDataDisks mocks base method. -func (m *MockVMSet) GetDataDisks(nodeName types.NodeName, crt cache.AzureCacheReadType) ([]compute.DataDisk, *string, error) { +func (m *MockVMSet) GetDataDisks(nodeName types.NodeName, crt cache.AzureCacheReadType) ([]*v5.DataDisk, *string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetDataDisks", nodeName, crt) - ret0, _ := ret[0].([]compute.DataDisk) + ret0, _ := ret[0].([]*v5.DataDisk) ret1, _ := ret[1].(*string) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // GetDataDisks indicates an expected call of GetDataDisks. -func (mr *MockVMSetMockRecorder) GetDataDisks(nodeName, crt interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetDataDisks(nodeName, crt any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDataDisks", reflect.TypeOf((*MockVMSet)(nil).GetDataDisks), nodeName, crt) } @@ -201,7 +208,7 @@ func (m *MockVMSet) GetIPByNodeName(name string) (string, string, error) { } // GetIPByNodeName indicates an expected call of GetIPByNodeName. -func (mr *MockVMSetMockRecorder) GetIPByNodeName(name interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetIPByNodeName(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetIPByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetIPByNodeName), name) } @@ -216,7 +223,7 @@ func (m *MockVMSet) GetInstanceIDByNodeName(name string) (string, error) { } // GetInstanceIDByNodeName indicates an expected call of GetInstanceIDByNodeName. -func (mr *MockVMSetMockRecorder) GetInstanceIDByNodeName(name interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetInstanceIDByNodeName(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstanceIDByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetInstanceIDByNodeName), name) } @@ -231,7 +238,7 @@ func (m *MockVMSet) GetInstanceTypeByNodeName(name string) (string, error) { } // GetInstanceTypeByNodeName indicates an expected call of GetInstanceTypeByNodeName. -func (mr *MockVMSetMockRecorder) GetInstanceTypeByNodeName(name interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetInstanceTypeByNodeName(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstanceTypeByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetInstanceTypeByNodeName), name) } @@ -247,7 +254,7 @@ func (m *MockVMSet) GetNodeCIDRMasksByProviderID(providerID string) (int, int, e } // GetNodeCIDRMasksByProviderID indicates an expected call of GetNodeCIDRMasksByProviderID. -func (mr *MockVMSetMockRecorder) GetNodeCIDRMasksByProviderID(providerID interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeCIDRMasksByProviderID(providerID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeCIDRMasksByProviderID", reflect.TypeOf((*MockVMSet)(nil).GetNodeCIDRMasksByProviderID), providerID) } @@ -263,7 +270,7 @@ func (m *MockVMSet) GetNodeNameByIPConfigurationID(ipConfigurationID string) (st } // GetNodeNameByIPConfigurationID indicates an expected call of GetNodeNameByIPConfigurationID. -func (mr *MockVMSetMockRecorder) GetNodeNameByIPConfigurationID(ipConfigurationID interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeNameByIPConfigurationID(ipConfigurationID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeNameByIPConfigurationID", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByIPConfigurationID), ipConfigurationID) } @@ -278,7 +285,7 @@ func (m *MockVMSet) GetNodeNameByProviderID(providerID string) (types.NodeName, } // GetNodeNameByProviderID indicates an expected call of GetNodeNameByProviderID. -func (mr *MockVMSetMockRecorder) GetNodeNameByProviderID(providerID interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeNameByProviderID(providerID any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeNameByProviderID", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByProviderID), providerID) } @@ -293,7 +300,7 @@ func (m *MockVMSet) GetNodeVMSetName(node *v1.Node) (string, error) { } // GetNodeVMSetName indicates an expected call of GetNodeVMSetName. -func (mr *MockVMSetMockRecorder) GetNodeVMSetName(node interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeVMSetName(node any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeVMSetName", reflect.TypeOf((*MockVMSet)(nil).GetNodeVMSetName), node) } @@ -308,7 +315,7 @@ func (m *MockVMSet) GetPowerStatusByNodeName(name string) (string, error) { } // GetPowerStatusByNodeName indicates an expected call of GetPowerStatusByNodeName. -func (mr *MockVMSetMockRecorder) GetPowerStatusByNodeName(name interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetPowerStatusByNodeName(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPowerStatusByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetPowerStatusByNodeName), name) } @@ -323,7 +330,7 @@ func (m *MockVMSet) GetPrimaryInterface(nodeName string) (network.Interface, err } // GetPrimaryInterface indicates an expected call of GetPrimaryInterface. -func (mr *MockVMSetMockRecorder) GetPrimaryInterface(nodeName interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetPrimaryInterface(nodeName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrimaryInterface", reflect.TypeOf((*MockVMSet)(nil).GetPrimaryInterface), nodeName) } @@ -352,7 +359,7 @@ func (m *MockVMSet) GetPrivateIPsByNodeName(name string) ([]string, error) { } // GetPrivateIPsByNodeName indicates an expected call of GetPrivateIPsByNodeName. -func (mr *MockVMSetMockRecorder) GetPrivateIPsByNodeName(name interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetPrivateIPsByNodeName(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrivateIPsByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetPrivateIPsByNodeName), name) } @@ -367,7 +374,7 @@ func (m *MockVMSet) GetProvisioningStateByNodeName(name string) (string, error) } // GetProvisioningStateByNodeName indicates an expected call of GetProvisioningStateByNodeName. -func (mr *MockVMSetMockRecorder) GetProvisioningStateByNodeName(name interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetProvisioningStateByNodeName(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProvisioningStateByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetProvisioningStateByNodeName), name) } @@ -382,7 +389,7 @@ func (m *MockVMSet) GetVMSetNames(service *v1.Service, nodes []*v1.Node) (*[]str } // GetVMSetNames indicates an expected call of GetVMSetNames. -func (mr *MockVMSetMockRecorder) GetVMSetNames(service, nodes interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetVMSetNames(service, nodes any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVMSetNames", reflect.TypeOf((*MockVMSet)(nil).GetVMSetNames), service, nodes) } @@ -397,7 +404,7 @@ func (m *MockVMSet) GetZoneByNodeName(name string) (cloud_provider.Zone, error) } // GetZoneByNodeName indicates an expected call of GetZoneByNodeName. -func (mr *MockVMSetMockRecorder) GetZoneByNodeName(name interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetZoneByNodeName(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetZoneByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetZoneByNodeName), name) } @@ -411,36 +418,7 @@ func (m *MockVMSet) UpdateVM(ctx context.Context, nodeName types.NodeName) error } // UpdateVM indicates an expected call of UpdateVM. -func (mr *MockVMSetMockRecorder) UpdateVM(ctx, nodeName interface{}) *gomock.Call { +func (mr *MockVMSetMockRecorder) UpdateVM(ctx, nodeName any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVM", reflect.TypeOf((*MockVMSet)(nil).UpdateVM), ctx, nodeName) } - -// UpdateVMAsync mocks base method. -func (m *MockVMSet) UpdateVMAsync(ctx context.Context, nodeName types.NodeName) (*azure.Future, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateVMAsync", ctx, nodeName) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateVMAsync indicates an expected call of UpdateVMAsync. -func (mr *MockVMSetMockRecorder) UpdateVMAsync(ctx, nodeName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVMAsync", reflect.TypeOf((*MockVMSet)(nil).UpdateVMAsync), ctx, nodeName) -} - -// WaitForUpdateResult mocks base method. -func (m *MockVMSet) WaitForUpdateResult(ctx context.Context, future *azure.Future, nodeName types.NodeName, source string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForUpdateResult", ctx, future, nodeName, source) - ret0, _ := ret[0].(error) - return ret0 -} - -// WaitForUpdateResult indicates an expected call of WaitForUpdateResult. -func (mr *MockVMSetMockRecorder) WaitForUpdateResult(ctx, future, nodeName, source interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForUpdateResult", reflect.TypeOf((*MockVMSet)(nil).WaitForUpdateResult), ctx, future, nodeName, source) -} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go index ca2a1bdae..1d1863b2c 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go @@ -38,10 +38,12 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" "k8s.io/utils/pointer" + "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/metrics" + vmutil "sigs.k8s.io/cloud-provider-azure/pkg/util/vm" ) var ( @@ -121,7 +123,7 @@ func (az *Cloud) getNetworkResourceSubscriptionID() string { } func (az *Cloud) mapLoadBalancerNameToVMSet(lbName string, clusterName string) (vmSetName string) { - vmSetName = strings.TrimSuffix(lbName, consts.InternalLoadBalancerNameSuffix) + vmSetName = trimSuffixIgnoreCase(lbName, consts.InternalLoadBalancerNameSuffix) if strings.EqualFold(clusterName, vmSetName) { vmSetName = az.VMSet.GetPrimaryVMSetName() } @@ -501,19 +503,13 @@ func (as *availabilitySet) GetPowerStatusByNodeName(name string) (powerState str return powerState, err } - if vm.InstanceView != nil && vm.InstanceView.Statuses != nil { - statuses := *vm.InstanceView.Statuses - for _, status := range statuses { - state := pointer.StringDeref(status.Code, "") - if strings.HasPrefix(state, vmPowerStatePrefix) { - return strings.TrimPrefix(state, vmPowerStatePrefix), nil - } - } + if vm.InstanceView != nil { + return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.InstanceView.Statuses), nil } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) - return vmPowerStateUnknown, nil + return consts.VMPowerStateUnknown, nil } // GetProvisioningStateByNodeName returns the provisioningState for the specified node. diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go index a8d683efc..a26719f80 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go @@ -285,7 +285,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } if len(accountOptions.StorageEndpointSuffix) == 0 { - accountOptions.StorageEndpointSuffix = az.cloud.Environment.StorageEndpointSuffix + accountOptions.StorageEndpointSuffix = az.Environment.StorageEndpointSuffix } privateDNSZoneName = fmt.Sprintf(privateDNSZoneNameFmt, accountOptions.StorageType, accountOptions.StorageEndpointSuffix) } @@ -635,10 +635,10 @@ func (az *Cloud) createPrivateDNSZone(ctx context.Context, vnetResourceGroup, pr func (az *Cloud) createVNetLink(ctx context.Context, vNetLinkName, vnetResourceGroup, vnetName, privateDNSZoneName string) error { klog.V(2).Infof("Creating virtual link for vnet(%s) and DNS Zone(%s) in resourceGroup(%s)", vNetLinkName, privateDNSZoneName, vnetResourceGroup) var clientFactory azclient.ClientFactory - if az.cloud.NetworkClientFactory != nil { - clientFactory = az.cloud.NetworkClientFactory + if az.NetworkClientFactory != nil { + clientFactory = az.NetworkClientFactory } else { - clientFactory = az.cloud.ComputeClientFactory + clientFactory = az.ComputeClientFactory } vnetLinkClient := clientFactory.GetVirtualNetworkLinkClient() @@ -840,17 +840,16 @@ func isTagsEqual(account storage.Account, accountOptions *AccountOptions) bool { return true } - for k, v := range account.Tags { - var value string - // nil and empty value should be regarded as equal - if v != nil { - value = *v - } - if accountOptions.Tags[k] != value { + if len(account.Tags) < len(accountOptions.Tags) { + return false + } + + // ensure all tags in accountOptions are in account + for k, v := range accountOptions.Tags { + if pointer.StringDeref(account.Tags[k], "") != v { return false } } - return true } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go index 70ae36338..541c74b18 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go @@ -18,15 +18,17 @@ package provider import ( "context" + "encoding/json" "fmt" "net" "strings" "sync" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/sets" "k8s.io/klog/v2" utilnet "k8s.io/utils/net" "k8s.io/utils/pointer" @@ -44,21 +46,21 @@ var strToExtendedLocationType = map[string]network.ExtendedLocationTypes{ "edgezone": network.EdgeZone, } -// lockMap used to lock on entries -type lockMap struct { +// LockMap used to lock on entries +type LockMap struct { sync.Mutex mutexMap map[string]*sync.Mutex } // NewLockMap returns a new lock map -func newLockMap() *lockMap { - return &lockMap{ +func newLockMap() *LockMap { + return &LockMap{ mutexMap: make(map[string]*sync.Mutex), } } // LockEntry acquires a lock associated with the specific entry -func (lm *lockMap) LockEntry(entry string) { +func (lm *LockMap) LockEntry(entry string) { lm.Lock() // check if entry does not exists, then add entry mutex, exists := lm.mutexMap[entry] @@ -71,7 +73,7 @@ func (lm *lockMap) LockEntry(entry string) { } // UnlockEntry release the lock associated with the specific entry -func (lm *lockMap) UnlockEntry(entry string) { +func (lm *LockMap) UnlockEntry(entry string) { lm.Lock() defer lm.Unlock() @@ -502,36 +504,6 @@ func IntInSlice(i int, list []int) bool { return false } -func safeAddKeyToStringsSet(set sets.Set[string], key string) sets.Set[string] { - if set != nil { - set.Insert(key) - } else { - set = sets.New[string](key) - } - - return set -} - -func safeRemoveKeyFromStringsSet(set sets.Set[string], key string) (sets.Set[string], bool) { - var has bool - if set != nil { - if set.Has(key) { - has = true - } - set.Delete(key) - } - - return set, has -} - -func setToStrings(set sets.Set[string]) []string { - var res []string - for key := range set { - res = append(res, key) - } - return res -} - func isLocalService(service *v1.Service) bool { return service.Spec.ExternalTrafficPolicy == v1.ServiceExternalTrafficPolicyLocal } @@ -566,3 +538,36 @@ func getResourceGroupAndNameFromNICID(ipConfigurationID string) (string, string, func isInternalLoadBalancer(lb *network.LoadBalancer) bool { return strings.HasSuffix(strings.ToLower(*lb.Name), consts.InternalLoadBalancerNameSuffix) } + +// trimSuffixIgnoreCase trims the suffix from the string, case-insensitive. +// It returns the original string if the suffix is not found. +// The returning string is in lower case. +func trimSuffixIgnoreCase(str, suf string) string { + str = strings.ToLower(str) + suf = strings.ToLower(suf) + if strings.HasSuffix(str, suf) { + return strings.TrimSuffix(str, suf) + } + return str +} + +// ToArmcomputeDisk converts compute.DataDisk to armcompute.DataDisk +// This is a workaround during track2 migration. +// TODO: remove this function after compute api is migrated to track2 +func ToArmcomputeDisk(disks []compute.DataDisk) ([]*armcompute.DataDisk, error) { + var result []*armcompute.DataDisk + for _, disk := range disks { + content, err := json.Marshal(disk) + if err != nil { + return nil, err + } + var dataDisk armcompute.DataDisk + err = json.Unmarshal(content, &dataDisk) + if err != nil { + return nil, err + } + result = append(result, &dataDisk) + } + + return result, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmsets.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmsets.go index e405ef3a7..d680f5ced 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmsets.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmsets.go @@ -19,9 +19,9 @@ package provider import ( "context" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest/azure" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -76,21 +76,17 @@ type VMSet interface { EnsureBackendPoolDeletedFromVMSets(vmSetNamesMap map[string]bool, backendPoolIDs []string) error // AttachDisk attaches a disk to vm - AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) (*azure.Future, error) + AttachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]*AttachDiskOptions) error // DetachDisk detaches a disk from vm DetachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]string) error // WaitForUpdateResult waits for the response of the update request - WaitForUpdateResult(ctx context.Context, future *azure.Future, nodeName types.NodeName, source string) error // GetDataDisks gets a list of data disks attached to the node. - GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, *string, error) + GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]*armcompute.DataDisk, *string, error) // UpdateVM updates a vm UpdateVM(ctx context.Context, nodeName types.NodeName) error - // UpdateVMAsync updates a vm asynchronously - UpdateVMAsync(ctx context.Context, nodeName types.NodeName) (*azure.Future, error) - // GetPowerStatusByNodeName returns the powerState for the specified node. GetPowerStatusByNodeName(name string) (string, error) @@ -112,3 +108,12 @@ type VMSet interface { // DeleteCacheForNode removes the node entry from cache. DeleteCacheForNode(nodeName string) error } + +// AttachDiskOptions attach disk options +type AttachDiskOptions struct { + CachingMode compute.CachingTypes + DiskName string + DiskEncryptionSetID string + WriteAcceleratorEnabled bool + Lun int32 +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go index d423a2dfd..3c84f767b 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go @@ -35,11 +35,13 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" "k8s.io/utils/pointer" + "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/metrics" "sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine" + vmutil "sigs.k8s.io/cloud-provider-azure/pkg/util/vm" ) var ( @@ -101,7 +103,7 @@ type ScaleSet struct { nonVmssUniformNodesCache azcache.Resource // lockMap in cache refresh - lockMap *lockMap + lockMap *LockMap } // newScaleSet creates a new ScaleSet. @@ -144,6 +146,7 @@ func newScaleSet(ctx context.Context, az *Cloud) (VMSet, error) { return nil, err } + ss.lockMap = newLockMap() return ss, nil } @@ -281,20 +284,14 @@ func (ss *ScaleSet) GetPowerStatusByNodeName(name string) (powerState string, er if vm.IsVirtualMachineScaleSetVM() { v := vm.AsVirtualMachineScaleSetVM() - if v.InstanceView != nil && v.InstanceView.Statuses != nil { - statuses := *v.InstanceView.Statuses - for _, status := range statuses { - state := pointer.StringDeref(status.Code, "") - if strings.HasPrefix(state, vmPowerStatePrefix) { - return strings.TrimPrefix(state, vmPowerStatePrefix), nil - } - } + if v.InstanceView != nil { + return vmutil.GetVMPowerState(ptr.Deref(v.Name, ""), v.InstanceView.Statuses), nil } } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) - return vmPowerStateUnknown, nil + return consts.VMPowerStateUnknown, nil } // GetProvisioningStateByNodeName returns the provisioningState for the specified node. @@ -1028,6 +1025,8 @@ func getPrimaryIPConfigFromVMSSNetworkConfig(config *compute.VirtualMachineScale // EnsureHostInPool ensures the given VM's Primary NIC's Primary IP Configuration is // participating in the specified LoadBalancer Backend Pool, which returns (resourceGroup, vmasName, instanceID, vmssVM, error). func (ss *ScaleSet) EnsureHostInPool(_ *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetNameOfLB string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) { + logger := klog.Background().WithName("EnsureHostInPool"). + WithValues("nodeName", nodeName, "backendPoolID", backendPoolID, "vmSetNameOfLB", vmSetNameOfLB) vmName := mapNodeNameToVMName(nodeName) vm, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault) if err != nil { @@ -1036,13 +1035,20 @@ func (ss *ScaleSet) EnsureHostInPool(_ *v1.Service, nodeName types.NodeName, bac return "", "", "", nil, nil } - klog.Errorf("EnsureHostInPool: failed to get VMSS VM %s: %v", vmName, err) + logger.Error(err, "failed to get vmss vm", "vmName", vmName) if !errors.Is(err, ErrorNotVmssInstance) { return "", "", "", nil, err } } + statuses := vm.GetInstanceViewStatus() + vmPowerState := vmutil.GetVMPowerState(vm.Name, statuses) + provisioningState := vm.GetProvisioningState() + if vmutil.IsNotActiveVMState(provisioningState, vmPowerState) { + logger.V(2).Info("skip updating the node because it is not in an active state", "vmName", vmName, "provisioningState", provisioningState, "vmPowerState", vmPowerState) + return "", "", "", nil, nil + } - klog.V(2).Infof("ensuring node %q of scaleset %q in LB backendpool %q", nodeName, vm.VMSSName, backendPoolID) + logger.V(2).Info("ensuring the vmss node in LB backendpool", "vmss name", vm.VMSSName) // Check scale set name: // - For basic SKU load balancer, return nil if the node's scale set is mismatched with vmSetNameOfLB. @@ -1056,14 +1062,13 @@ func (ss *ScaleSet) EnsureHostInPool(_ *v1.Service, nodeName types.NodeName, bac } if vmSetNameOfLB != "" && needCheck && !strings.EqualFold(vmSetNameOfLB, vm.VMSSName) { - klog.V(3).Infof("EnsureHostInPool skips node %s because it is not in the ScaleSet %s", vmName, vmSetNameOfLB) + logger.V(3).Info("skips the node %s because it is not in the ScaleSet %s", vmName, vmSetNameOfLB) return "", "", "", nil, nil } // Find primary network interface configuration. if vm.VirtualMachineScaleSetVMProperties.NetworkProfileConfiguration.NetworkInterfaceConfigurations == nil { - klog.V(4).Infof("EnsureHostInPool: cannot obtain the primary network interface configuration, of vm %s, "+ - "probably because the vm's being deleted", vmName) + logger.V(4).Info("cannot obtain the primary network interface configuration, of the vm, probably because the vm's being deleted", "vmName", vmName) return "", "", "", nil, nil } @@ -1113,7 +1118,7 @@ func (ss *ScaleSet) EnsureHostInPool(_ *v1.Service, nodeName types.NodeName, bac return "", "", "", nil, err } if !isSameLB { - klog.V(4).Infof("Node %q has already been added to LB %q, omit adding it to a new one", nodeName, oldLBName) + logger.V(4).Info("The node has already been added to an LB, omit adding it to a new one", "lbName", oldLBName) return "", "", "", nil, nil } } @@ -1220,7 +1225,7 @@ func (ss *ScaleSet) ensureVMSSInPool(_ *v1.Service, nodes []*v1.Node, backendPoo // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.VirtualMachineScaleSetsDeallocating) { + if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("ensureVMSSInPool: found vmss %s being deleted, skipping", vmssName) continue } @@ -1492,6 +1497,7 @@ func (ss *ScaleSet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, bac // ensureBackendPoolDeletedFromNode ensures the loadBalancer backendAddressPools deleted // from the specified node, which returns (resourceGroup, vmasName, instanceID, vmssVM, error). func (ss *ScaleSet) ensureBackendPoolDeletedFromNode(nodeName string, backendPoolIDs []string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) { + logger := klog.Background().WithName("ensureBackendPoolDeletedFromNode").WithValues("nodeName", nodeName, "backendPoolIDs", backendPoolIDs) vm, err := ss.getVmssVM(nodeName, azcache.CacheReadTypeDefault) if err != nil { if errors.Is(err, cloudprovider.InstanceNotFound) { @@ -1502,6 +1508,14 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromNode(nodeName string, backendPoo return "", "", "", nil, err } + statuses := vm.GetInstanceViewStatus() + vmPowerState := vmutil.GetVMPowerState(vm.Name, statuses) + provisioningState := vm.GetProvisioningState() + if vmutil.IsNotActiveVMState(provisioningState, vmPowerState) { + logger.V(2).Info("skip updating the node because it is not in an active state", "provisioningState", provisioningState, "vmPowerState", vmPowerState) + return "", "", "", nil, nil + } + // Find primary network interface configuration. if vm.VirtualMachineScaleSetVMProperties.NetworkProfileConfiguration.NetworkInterfaceConfigurations == nil { klog.V(4).Infof("ensureBackendPoolDeletedFromNode: cannot obtain the primary network interface configuration, of vm %s, "+ @@ -1678,7 +1692,7 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVmssUniform(backendPoolIDs []str // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.VirtualMachineScaleSetsDeallocating) { + if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("ensureBackendPoolDeletedFromVMSS: found vmss %s being deleted, skipping", pointer.StringDeref(vmss.Name, "")) return true } @@ -2085,7 +2099,7 @@ func (ss *ScaleSet) EnsureBackendPoolDeletedFromVMSets(vmssNamesMap map[string]b // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.VirtualMachineScaleSetsDeallocating) { + if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("EnsureBackendPoolDeletedFromVMSets: found vmss %s being deleted, skipping", vmssName) continue } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go index 592e05d16..11949faf9 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go @@ -25,12 +25,12 @@ import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "k8s.io/apimachinery/pkg/util/sets" "k8s.io/klog/v2" "k8s.io/utils/pointer" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" + utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) type VMSSVirtualMachineEntry struct { @@ -48,11 +48,11 @@ type VMSSEntry struct { } type NonVmssUniformNodesEntry struct { - VMSSFlexVMNodeNames sets.Set[string] - VMSSFlexVMProviderIDs sets.Set[string] - AvSetVMNodeNames sets.Set[string] - AvSetVMProviderIDs sets.Set[string] - ClusterNodeNames sets.Set[string] + VMSSFlexVMNodeNames *utilsets.IgnoreCaseSet + VMSSFlexVMProviderIDs *utilsets.IgnoreCaseSet + AvSetVMNodeNames *utilsets.IgnoreCaseSet + AvSetVMProviderIDs *utilsets.IgnoreCaseSet + ClusterNodeNames *utilsets.IgnoreCaseSet } type VMManagementType string @@ -288,9 +288,6 @@ func (ss *ScaleSet) DeleteCacheForNode(nodeName string) error { } func (ss *ScaleSet) updateCache(nodeName, resourceGroupName, vmssName, instanceID string, updatedVM *compute.VirtualMachineScaleSetVM) error { - if ss.ManagedDiskController.DisableUpdateCache { - return nil - } // lock the VMSS entry to ensure a consistent view of the VM map when there are concurrent updates. cacheKey := getVMSSVMCacheKey(resourceGroupName, vmssName) ss.lockMap.LockEntry(cacheKey) @@ -327,10 +324,10 @@ func (ss *ScaleSet) updateCache(nodeName, resourceGroupName, vmssName, instanceI func (ss *ScaleSet) newNonVmssUniformNodesCache() (azcache.Resource, error) { getter := func(key string) (interface{}, error) { - vmssFlexVMNodeNames := sets.New[string]() - vmssFlexVMProviderIDs := sets.New[string]() - avSetVMNodeNames := sets.New[string]() - avSetVMProviderIDs := sets.New[string]() + vmssFlexVMNodeNames := utilsets.NewString() + vmssFlexVMProviderIDs := utilsets.NewString() + avSetVMNodeNames := utilsets.NewString() + avSetVMProviderIDs := utilsets.NewString() resourceGroups, err := ss.GetResourceGroups() if err != nil { return nil, err diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_repo.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_repo.go index 6721dceab..89b5a900f 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_repo.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_repo.go @@ -39,7 +39,7 @@ func (az *Cloud) CreateOrUpdateVMSS(resourceGroupName string, VMScaleSetName str klog.Errorf("CreateOrUpdateVMSS: error getting vmss(%s): %v", VMScaleSetName, rerr) return rerr } - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.VirtualMachineScaleSetsDeallocating) { + if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("CreateOrUpdateVMSS: found vmss %s being deleted, skipping", VMScaleSetName) return nil } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go index c1a4f8893..646785c75 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go @@ -27,16 +27,19 @@ import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" utilerrors "k8s.io/apimachinery/pkg/util/errors" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" "k8s.io/utils/pointer" + "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/metrics" + vmutil "sigs.k8s.io/cloud-provider-azure/pkg/util/vm" ) var ( @@ -48,14 +51,13 @@ var ( type FlexScaleSet struct { *Cloud - vmssFlexCache azcache.Resource - + vmssFlexCache azcache.Resource vmssFlexVMNameToVmssID *sync.Map vmssFlexVMNameToNodeName *sync.Map vmssFlexVMCache azcache.Resource // lockMap in cache refresh - lockMap *lockMap + lockMap *LockMap } func newFlexScaleSet(ctx context.Context, az *Cloud) (VMSet, error) { @@ -268,19 +270,13 @@ func (fs *FlexScaleSet) GetPowerStatusByNodeName(name string) (powerState string return powerState, err } - if vm.InstanceView != nil && vm.InstanceView.Statuses != nil { - statuses := *vm.InstanceView.Statuses - for _, status := range statuses { - state := pointer.StringDeref(status.Code, "") - if strings.HasPrefix(state, vmPowerStatePrefix) { - return strings.TrimPrefix(state, vmPowerStatePrefix), nil - } - } + if vm.InstanceView != nil { + return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.InstanceView.Statuses), nil } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) - return vmPowerStateUnknown, nil + return consts.VMPowerStateUnknown, nil } // GetPrimaryInterface gets machine primary network interface by node name. @@ -617,7 +613,7 @@ func (fs *FlexScaleSet) ensureVMSSFlexInPool(_ *v1.Service, nodes []*v1.Node, ba // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmssFlex.ProvisioningState != nil && strings.EqualFold(*vmssFlex.ProvisioningState, consts.VirtualMachineScaleSetsDeallocating) { + if vmssFlex.ProvisioningState != nil && strings.EqualFold(*vmssFlex.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("ensureVMSSFlexInPool: found vmss %s being deleted, skipping", vmssFlexID) continue } @@ -791,7 +787,7 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeletedFromVMSets(vmssNamesMap map[stri // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.VirtualMachineScaleSetsDeallocating) { + if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("fs.EnsureBackendPoolDeletedFromVMSets: found vmss %s being deleted, skipping", vmssName) continue } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine/virtualmachine.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine/virtualmachine.go index bd6b77535..924f08c8e 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine/virtualmachine.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine/virtualmachine.go @@ -18,7 +18,10 @@ package virtualmachine import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "k8s.io/utils/pointer" + + "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) type Variant string @@ -145,6 +148,36 @@ func (vm *VirtualMachine) AsVirtualMachineScaleSetVM() *compute.VirtualMachineSc return vm.vmssVM } +func (vm *VirtualMachine) GetInstanceViewStatus() *[]compute.InstanceViewStatus { + if vm.IsVirtualMachine() && vm.vm != nil && + vm.vm.VirtualMachineProperties != nil && + vm.vm.VirtualMachineProperties.InstanceView != nil { + return vm.vm.VirtualMachineProperties.InstanceView.Statuses + } + if vm.IsVirtualMachineScaleSetVM() && + vm.vmssVM != nil && + vm.vmssVM.VirtualMachineScaleSetVMProperties != nil && + vm.vmssVM.VirtualMachineScaleSetVMProperties.InstanceView != nil { + return vm.vmssVM.VirtualMachineScaleSetVMProperties.InstanceView.Statuses + } + return nil +} + +func (vm *VirtualMachine) GetProvisioningState() string { + if vm.IsVirtualMachine() && vm.vm != nil && + vm.vm.VirtualMachineProperties != nil && + vm.vm.VirtualMachineProperties.ProvisioningState != nil { + return *vm.vm.VirtualMachineProperties.ProvisioningState + } + if vm.IsVirtualMachineScaleSetVM() && + vm.vmssVM != nil && + vm.vmssVM.VirtualMachineScaleSetVMProperties != nil && + vm.vmssVM.VirtualMachineScaleSetVMProperties.ProvisioningState != nil { + return *vm.vmssVM.VirtualMachineScaleSetVMProperties.ProvisioningState + } + return consts.ProvisioningStateUnknown +} + // StringMap returns a map of strings built from the map of string pointers. The empty string is // used for nil pointers. func stringMap(msp map[string]*string) map[string]string { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/sets/string.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/sets/string.go new file mode 100644 index 000000000..2562fcf6e --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/sets/string.go @@ -0,0 +1,100 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package sets + +import ( + "strings" + + "k8s.io/apimachinery/pkg/util/sets" +) + +// IgnoreCaseSet is a set of strings that is case-insensitive. +type IgnoreCaseSet struct { + set sets.Set[string] +} + +// NewString creates a new IgnoreCaseSet with the given items. +func NewString(items ...string) *IgnoreCaseSet { + var lowerItems []string + for _, item := range items { + lowerItems = append(lowerItems, strings.ToLower(item)) + } + set := sets.New[string](lowerItems...) + return &IgnoreCaseSet{set: set} +} + +// Insert adds the given items to the set. It only works if the set is initialized. +func (s *IgnoreCaseSet) Insert(items ...string) { + var lowerItems []string + for _, item := range items { + lowerItems = append(lowerItems, strings.ToLower(item)) + } + for _, item := range lowerItems { + s.set.Insert(item) + } +} + +// SafeInsert creates a new IgnoreCaseSet with the given items if the set is not initialized. +// This is the recommended way to insert elements into the set. +func SafeInsert(s *IgnoreCaseSet, items ...string) *IgnoreCaseSet { + if s.Initialized() { + s.Insert(items...) + return s + } + return NewString(items...) +} + +// Delete removes the given item from the set. +// It will be a no-op if the set is not initialized or the item is not in the set. +func (s *IgnoreCaseSet) Delete(item string) bool { + var has bool + item = strings.ToLower(item) + if s.Initialized() && s.Has(item) { + s.set.Delete(item) + has = true + } + return has +} + +// Has returns true if the given item is in the set, and the set is initialized. +func (s *IgnoreCaseSet) Has(item string) bool { + if !s.Initialized() { + return false + } + return s.set.Has(strings.ToLower(item)) +} + +// Initialized returns true if the set is initialized. +func (s *IgnoreCaseSet) Initialized() bool { + return s != nil && s.set != nil +} + +// UnsortedList returns the items in the set in an arbitrary order. +func (s *IgnoreCaseSet) UnsortedList() []string { + if !s.Initialized() { + return []string{} + } + return s.set.UnsortedList() +} + +// Len returns the number of items in the set. +func (s *IgnoreCaseSet) Len() int { + if !s.Initialized() { + return 0 + } + return s.set.Len() +} diff --git a/vendor/k8s.io/cloud-provider/volume/constants.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/string/string.go similarity index 59% rename from vendor/k8s.io/cloud-provider/volume/constants.go rename to vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/string/string.go index d05f64ae2..10510ecc7 100644 --- a/vendor/k8s.io/cloud-provider/volume/constants.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/string/string.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Kubernetes Authors. +Copyright 2024 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,13 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ -package volume +package stringutils -const ( - // ProvisionedVolumeName is the name of a volume in an external cloud - // that is being provisioned and thus should be ignored by rest of Kubernetes. - ProvisionedVolumeName = "placeholder-for-provisioning" +import "strings" - // LabelMultiZoneDelimiter separates zones for volumes - LabelMultiZoneDelimiter = "__" -) +// HasPrefixCaseInsensitive returns true if the string has the prefix, case-insensitive. +func HasPrefixCaseInsensitive(s string, prefix string) bool { + return strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix)) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/vm/vm.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/vm/vm.go new file mode 100644 index 000000000..a5084f30b --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/vm/vm.go @@ -0,0 +1,55 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package vm + +import ( + "strings" + + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + + "k8s.io/klog/v2" + "k8s.io/utils/ptr" + + "sigs.k8s.io/cloud-provider-azure/pkg/consts" + stringutils "sigs.k8s.io/cloud-provider-azure/pkg/util/string" +) + +// GetVMPowerState returns the power state of the VM +func GetVMPowerState(vmName string, vmStatuses *[]compute.InstanceViewStatus) string { + logger := klog.Background().WithName("getVMSSVMPowerState").WithValues("vmName", vmName) + if vmStatuses != nil { + for _, status := range *vmStatuses { + state := ptr.Deref(status.Code, "") + if stringutils.HasPrefixCaseInsensitive(state, consts.VMPowerStatePrefix) { + return strings.TrimPrefix(state, consts.VMPowerStatePrefix) + } + } + } + logger.V(3).Info("vm status is nil in the instance view or there is no power state in the status") + return consts.VMPowerStateUnknown +} + +// IsNotActiveVMState checks if the VM is in the active states +func IsNotActiveVMState(provisioningState, powerState string) bool { + return strings.EqualFold(provisioningState, consts.ProvisioningStateDeleting) || + strings.EqualFold(provisioningState, consts.ProvisioningStateUnknown) || + strings.EqualFold(powerState, consts.VMPowerStateUnknown) || + strings.EqualFold(powerState, consts.VMPowerStateStopped) || + strings.EqualFold(powerState, consts.VMPowerStateStopping) || + strings.EqualFold(powerState, consts.VMPowerStateDeallocated) || + strings.EqualFold(powerState, consts.VMPowerStateDeallocating) +}