| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package azureblob provides a blob implementation that uses Azure Storage’s |
| 16 |
// BlockBlob. Use OpenBucket to construct a *blob.Bucket. |
| 17 |
// |
| 18 |
// NOTE: SignedURLs for PUT created with this package are not fully portable; |
| 19 |
// they will not work unless the PUT request includes a "x-ms-blob-type" header |
| 20 |
// set to "BlockBlob". |
| 21 |
// See https://stackoverflow.com/questions/37824136/put-on-sas-blob-url-without-specifying-x-ms-blob-type-header. |
| 22 |
// |
| 23 |
// # URLs |
| 24 |
// |
| 25 |
// For blob.OpenBucket, azureblob registers for the scheme "azblob". |
| 26 |
// |
| 27 |
// The default URL opener will use environment variables to generate |
| 28 |
// credentials and a service URL; see |
| 29 |
// https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/storage/azblob |
| 30 |
// for a more complete descriptions of each approach. |
| 31 |
// - AZURE_STORAGE_ACCOUNT: The service account name. Required if used along with AZURE_STORAGE KEY, because it defines |
| 32 |
// authentication mechanism to be azblob.NewSharedKeyCredential, which creates immutable shared key credentials. |
| 33 |
// Otherwise, "storage_account" in the URL query string parameter can be used. |
| 34 |
// - AZURE_STORAGE_KEY: To use a shared key credential. The service account |
| 35 |
// name and key are passed to NewSharedKeyCredential and then the |
| 36 |
// resulting credential is passed to NewClientWithSharedKeyCredential. |
| 37 |
// - AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGEBLOB_CONNECTIONSTRING: To use a connection string, passed to |
| 38 |
// NewClientFromConnectionString. |
| 39 |
// - AZURE_STORAGE_SAS_TOKEN: To use a SAS token. The SAS token is added |
| 40 |
// as a URL parameter to the service URL, and passed to |
| 41 |
// NewClientWithNoCredential. |
| 42 |
// - If none of the above are provided, azureblob defaults to |
| 43 |
// azidentity.NewDefaultAzureCredential: |
| 44 |
// https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#NewDefaultAzureCredential. |
| 45 |
// See the documentation there for the credential types it supports, including |
| 46 |
// CLI creds, environment variables like AZURE_CLIENT_ID, AZURE_TENANT_ID, etc. |
| 47 |
// |
| 48 |
// In addition, the environment variables AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_DOMAIN, |
| 49 |
// AZURE_STORAGE_PROTOCOL, AZURE_STORAGE_IS_CDN, and AZURE_STORAGE_IS_LOCAL_EMULATOR |
| 50 |
// can be used to configure how the default URLOpener generates the Azure |
| 51 |
// Service URL via ServiceURLOptions. These can all be configured via URL |
| 52 |
// parameters as well. See ServiceURLOptions and NewDefaultServiceURL |
| 53 |
// for more details. |
| 54 |
// |
| 55 |
// To customize the URL opener, or for more details on the URL format, |
| 56 |
// see URLOpener. |
| 57 |
// |
| 58 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 59 |
// |
| 60 |
// # Escaping |
| 61 |
// |
| 62 |
// Go CDK supports all UTF-8 strings; to make this work with services lacking |
| 63 |
// full UTF-8 support, strings must be escaped (during writes) and unescaped |
| 64 |
// (during reads). The following escapes are performed for azureblob: |
| 65 |
// - Blob keys: ASCII characters 0-31, 34 ("\""), 35 ("#"), 37 ("%"), 63 ("?"), |
| 66 |
// 92 ("\"), and 127 are escaped to "__0x<hex>__". |
| 67 |
// Additionally, the "/" in "../" and a trailing "/" in a key (e.g., "foo/") are escaped in the same way. |
| 68 |
// - Metadata keys: Per https://docs.microsoft.com/en-us/azure/storage/blobs/storage-properties-metadata, |
| 69 |
// Azure only allows C# identifiers as metadata keys. Therefore, characters |
| 70 |
// other than "[a-z][A-z][0-9]_" are escaped using "__0x<hex>__". In addition, |
| 71 |
// characters "[0-9]" are escaped when they start the string. |
| 72 |
// URL encoding would not work since "%" is not valid. |
| 73 |
// - Metadata values: Escaped using URL encoding. |
| 74 |
// |
| 75 |
// # As |
| 76 |
// |
| 77 |
// azureblob exposes the following types for As: |
| 78 |
// - Bucket: *container.Client |
| 79 |
// - Error: *azcore.ResponseError. You can use bloberror.HasCode directly though. |
| 80 |
// - ListObject: container.BlobItem for objects, container.BlobPrefix for "directories" |
| 81 |
// - ListOptions.BeforeList: *container.ListBlobsHierarchyOptions |
| 82 |
// - Reader: azblobblob.DownloadStreamResponse |
| 83 |
// - Reader.BeforeRead: *azblob.DownloadStreamOptions |
| 84 |
// - Attributes: azblobblob.GetPropertiesResponse |
| 85 |
// - CopyOptions.BeforeCopy: *azblobblob.StartCopyFromURLOptions |
| 86 |
// - WriterOptions.BeforeWrite: *azblob.UploadStreamOptions |
| 87 |
// - SignedURLOptions.BeforeSign: *sas.BlobPermissions |
| 88 |
package azureblob |
| 89 |
|
| 90 |
import ( |
| 91 |
"context" |
| 92 |
"errors" |
| 93 |
"fmt" |
| 94 |
"io" |
| 95 |
"net/http" |
| 96 |
"net/url" |
| 97 |
"os" |
| 98 |
"sort" |
| 99 |
"strconv" |
| 100 |
"strings" |
| 101 |
"sync" |
| 102 |
"time" |
| 103 |
|
| 104 |
"github.com/Azure/azure-sdk-for-go/sdk/azcore" |
| 105 |
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" |
| 106 |
"github.com/Azure/azure-sdk-for-go/sdk/azidentity" |
| 107 |
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" |
| 108 |
azblobblob "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob" |
| 109 |
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror" |
| 110 |
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob" |
| 111 |
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container" |
| 112 |
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas" |
| 113 |
"github.com/Azure/go-autorest/autorest/to" |
| 114 |
"github.com/google/wire" |
| 115 |
"gocloud.dev/blob" |
| 116 |
"gocloud.dev/blob/driver" |
| 117 |
"gocloud.dev/gcerrors" |
| 118 |
|
| 119 |
"gocloud.dev/internal/escape" |
| 120 |
"gocloud.dev/internal/gcerr" |
| 121 |
"gocloud.dev/internal/useragent" |
| 122 |
) |
| 123 |
|
| 124 |
const ( |
| 125 |
defaultPageSize = 1000 // default page size for ListPaged (Azure default is 5000) |
| 126 |
defaultUploadBuffers = 5 // configure the number of rotating buffers that are used when uploading (for degree of parallelism) |
| 127 |
defaultUploadBlockSize = 8 * 1024 * 1024 // configure the upload buffer size |
| 128 |
) |
| 129 |
|
| 130 |
func init() { |
| 131 |
blob.DefaultURLMux().RegisterBucket(Scheme, new(lazyOpener)) |
| 132 |
} |
| 133 |
|
| 134 |
// Set holds Wire providers for this package. |
| 135 |
var Set = wire.NewSet( |
| 136 |
NewDefaultServiceURLOptions, |
| 137 |
NewServiceURL, |
| 138 |
NewDefaultClient, |
| 139 |
) |
| 140 |
|
| 141 |
// Options sets options for constructing a *blob.Bucket backed by Azure Blob. |
| 142 |
type Options struct{} |
| 143 |
|
| 144 |
// ServiceURL represents an Azure service URL. |
| 145 |
type ServiceURL string |
| 146 |
|
| 147 |
// ContainerName represents an Azure blob container name. |
| 148 |
type ContainerName string |
| 149 |
|
| 150 |
// ServiceURLOptions sets options for constructing a service URL for Azure Blob. |
| 151 |
type ServiceURLOptions struct { |
| 152 |
// AccountName is the account name the credentials are for. |
| 153 |
AccountName string |
| 154 |
|
| 155 |
// SASToken will be appended to the service URL. |
| 156 |
// See https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1#shared-access-signature-parameters. |
| 157 |
SASToken string |
| 158 |
|
| 159 |
// StorageDomain can be provided to specify an Azure Cloud Environment |
| 160 |
// domain to target for the blob storage account (i.e. public, government, china). |
| 161 |
// Defaults to "blob.core.windows.net". Possible values will look similar |
| 162 |
// to this but are different for each cloud (i.e. "blob.core.govcloudapi.net" for USGovernment). |
| 163 |
// Check the Azure developer guide for the cloud environment where your bucket resides. |
| 164 |
// See the docstring for NewServiceURL to see examples of how this is used |
| 165 |
// along with the other Options fields. |
| 166 |
StorageDomain string |
| 167 |
|
| 168 |
// Protocol can be provided to specify protocol to access Azure Blob Storage. |
| 169 |
// Protocols that can be specified are "http" for local emulator and "https" for general. |
| 170 |
// Defaults to "https". |
| 171 |
// See the docstring for NewServiceURL to see examples of how this is used |
| 172 |
// along with the other Options fields. |
| 173 |
Protocol string |
| 174 |
|
| 175 |
// IsCDN can be set to true when using a CDN URL pointing to a blob storage account: |
| 176 |
// https://docs.microsoft.com/en-us/azure/cdn/cdn-create-a-storage-account-with-cdn |
| 177 |
// See the docstring for NewServiceURL to see examples of how this is used |
| 178 |
// along with the other Options fields. |
| 179 |
IsCDN bool |
| 180 |
|
| 181 |
// IsLocalEmulator should be set to true when targeting Local Storage Emulator (Azurite). |
| 182 |
// See the docstring for NewServiceURL to see examples of how this is used |
| 183 |
// along with the other Options fields. |
| 184 |
IsLocalEmulator bool |
| 185 |
} |
| 186 |
|
| 187 |
// NewDefaultServiceURLOptions generates a ServiceURLOptions based on environment variables. |
| 188 |
func NewDefaultServiceURLOptions() *ServiceURLOptions { |
| 189 |
isCDN, _ := strconv.ParseBool(os.Getenv("AZURE_STORAGE_IS_CDN")) |
| 190 |
isLocalEmulator, _ := strconv.ParseBool(os.Getenv("AZURE_STORAGE_IS_LOCAL_EMULATOR")) |
| 191 |
accountName := os.Getenv("AZURE_STORAGE_ACCOUNT") |
| 192 |
protocol := os.Getenv("AZURE_STORAGE_PROTOCOL") |
| 193 |
connectionString := os.Getenv("AZURE_STORAGE_CONNECTION_STRING") |
| 194 |
if connectionString == "" { |
| 195 |
connectionString = os.Getenv("AZURE_STORAGEBLOB_CONNECTIONSTRING") |
| 196 |
} |
| 197 |
if connectionString != "" { |
| 198 |
// Parse the connection string to get a default account name and protocol. |
| 199 |
// Format: DefaultEndpointsProtocol=https;AccountName=some-account;AccountKey=very-secure;EndpointSuffix=core.windows.net |
| 200 |
for part := range strings.SplitSeq(connectionString, ";") { |
| 201 |
keyval := strings.Split(part, "=") |
| 202 |
if len(keyval) == 2 { |
| 203 |
if accountName == "" && keyval[0] == "AccountName" { |
| 204 |
accountName = keyval[1] |
| 205 |
} else if protocol == "" && keyval[0] == "DefaultEndpointsProtocol" { |
| 206 |
protocol = keyval[1] |
| 207 |
} |
| 208 |
} |
| 209 |
} |
| 210 |
} |
| 211 |
return &ServiceURLOptions{ |
| 212 |
AccountName: accountName, |
| 213 |
SASToken: os.Getenv("AZURE_STORAGE_SAS_TOKEN"), |
| 214 |
StorageDomain: os.Getenv("AZURE_STORAGE_DOMAIN"), |
| 215 |
Protocol: protocol, |
| 216 |
IsCDN: isCDN, |
| 217 |
IsLocalEmulator: isLocalEmulator, |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
// withOverrides returns o with overrides from urlValues. |
| 222 |
// See URLOpener for supported overrides. |
| 223 |
func (o *ServiceURLOptions) withOverrides(urlValues url.Values) (*ServiceURLOptions, error) { |
| 224 |
retval := *o |
| 225 |
for param, values := range urlValues { |
| 226 |
if len(values) > 1 { |
| 227 |
return nil, fmt.Errorf("multiple values of %v not allowed", param) |
| 228 |
} |
| 229 |
value := values[0] |
| 230 |
switch param { |
| 231 |
case "domain": |
| 232 |
retval.StorageDomain = value |
| 233 |
case "protocol": |
| 234 |
retval.Protocol = value |
| 235 |
case "cdn": |
| 236 |
isCDN, err := strconv.ParseBool(value) |
| 237 |
if err != nil { |
| 238 |
return nil, err |
| 239 |
} |
| 240 |
retval.IsCDN = isCDN |
| 241 |
case "localemu": |
| 242 |
isLocalEmulator, err := strconv.ParseBool(value) |
| 243 |
if err != nil { |
| 244 |
return nil, err |
| 245 |
} |
| 246 |
retval.IsLocalEmulator = isLocalEmulator |
| 247 |
case "storage_account": |
| 248 |
retval.AccountName = value |
| 249 |
default: |
| 250 |
return nil, fmt.Errorf("unknown query parameter %q", param) |
| 251 |
} |
| 252 |
} |
| 253 |
return &retval, nil |
| 254 |
} |
| 255 |
|
| 256 |
// NewServiceURL generates a URL for addressing an Azure Blob service |
| 257 |
// account. It uses several parameters, each of which can be specified |
| 258 |
// via ServiceURLOptions. |
| 259 |
// |
| 260 |
// The generated URL is "<protocol>://<account name>.<domain>" |
| 261 |
// with the following caveats: |
| 262 |
// - If opts.SASToken is provided, it is appended to the URL as a query |
| 263 |
// parameter. |
| 264 |
// - If opts.IsCDN is true, the <account name> part is dropped. |
| 265 |
// - If opts.IsLocalEmulator is true, or the domain starts with "localhost" |
| 266 |
// or "127.0.0.1", the account name and domain are flipped, e.g.: |
| 267 |
// http://127.0.0.1:10000/myaccount |
| 268 |
func NewServiceURL(opts *ServiceURLOptions) (ServiceURL, error) { |
| 269 |
if opts == nil { |
| 270 |
opts = &ServiceURLOptions{} |
| 271 |
} |
| 272 |
accountName := opts.AccountName |
| 273 |
if accountName == "" { |
| 274 |
return "", errors.New("azureblob: Options.AccountName is required") |
| 275 |
} |
| 276 |
domain := opts.StorageDomain |
| 277 |
if domain == "" { |
| 278 |
domain = "blob.core.windows.net" |
| 279 |
} |
| 280 |
protocol := opts.Protocol |
| 281 |
if protocol == "" { |
| 282 |
protocol = "https" |
| 283 |
} else if protocol != "http" && protocol != "https" { |
| 284 |
return "", fmt.Errorf("invalid protocol %q", protocol) |
| 285 |
} |
| 286 |
var svcURL string |
| 287 |
if strings.HasPrefix(domain, "127.0.0.1") || strings.HasPrefix(domain, "localhost") || opts.IsLocalEmulator { |
| 288 |
svcURL = fmt.Sprintf("%s://%s/%s", protocol, domain, accountName) |
| 289 |
} else if opts.IsCDN { |
| 290 |
svcURL = fmt.Sprintf("%s://%s", protocol, domain) |
| 291 |
} else { |
| 292 |
svcURL = fmt.Sprintf("%s://%s.%s", protocol, accountName, domain) |
| 293 |
} |
| 294 |
if opts.SASToken != "" { |
| 295 |
svcURL += "?" + opts.SASToken |
| 296 |
} |
| 297 |
return ServiceURL(svcURL), nil |
| 298 |
} |
| 299 |
|
| 300 |
// lazyOpener obtains credentials and creates a client on the first call to OpenBucketURL. |
| 301 |
type lazyOpener struct { |
| 302 |
init sync.Once |
| 303 |
opener *URLOpener |
| 304 |
} |
| 305 |
|
| 306 |
func (o *lazyOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { |
| 307 |
o.init.Do(func() { |
| 308 |
credInfo := newCredInfoFromEnv() |
| 309 |
opts := NewDefaultServiceURLOptions() |
| 310 |
o.opener = &URLOpener{ |
| 311 |
MakeClient: credInfo.NewClient, |
| 312 |
ServiceURLOptions: *opts, |
| 313 |
} |
| 314 |
}) |
| 315 |
return o.opener.OpenBucketURL(ctx, u) |
| 316 |
} |
| 317 |
|
| 318 |
type credTypeEnumT int |
| 319 |
|
| 320 |
const ( |
| 321 |
credTypeDefault credTypeEnumT = iota |
| 322 |
credTypeSharedKey |
| 323 |
credTypeSASViaNone |
| 324 |
credTypeConnectionString |
| 325 |
) |
| 326 |
|
| 327 |
type credInfoT struct { |
| 328 |
CredType credTypeEnumT |
| 329 |
|
| 330 |
// For credTypeSharedKey. |
| 331 |
AccountName string |
| 332 |
AccountKey string |
| 333 |
|
| 334 |
// For credTypeConnectionString |
| 335 |
ConnectionString string |
| 336 |
} |
| 337 |
|
| 338 |
func newCredInfoFromEnv() *credInfoT { |
| 339 |
accountName := os.Getenv("AZURE_STORAGE_ACCOUNT") |
| 340 |
accountKey := os.Getenv("AZURE_STORAGE_KEY") |
| 341 |
sasToken := os.Getenv("AZURE_STORAGE_SAS_TOKEN") |
| 342 |
connectionString := os.Getenv("AZURE_STORAGE_CONNECTION_STRING") |
| 343 |
if connectionString == "" { |
| 344 |
connectionString = os.Getenv("AZURE_STORAGEBLOB_CONNECTIONSTRING") |
| 345 |
} |
| 346 |
credInfo := &credInfoT{ |
| 347 |
AccountName: accountName, |
| 348 |
} |
| 349 |
if accountName != "" && accountKey != "" { |
| 350 |
credInfo.CredType = credTypeSharedKey |
| 351 |
credInfo.AccountKey = accountKey |
| 352 |
} else if sasToken != "" { |
| 353 |
credInfo.CredType = credTypeSASViaNone |
| 354 |
} else if connectionString != "" { |
| 355 |
credInfo.CredType = credTypeConnectionString |
| 356 |
credInfo.ConnectionString = connectionString |
| 357 |
} else { |
| 358 |
credInfo.CredType = credTypeDefault |
| 359 |
} |
| 360 |
return credInfo |
| 361 |
} |
| 362 |
|
| 363 |
func (i *credInfoT) NewClient(svcURL ServiceURL, containerName ContainerName) (*container.Client, error) { |
| 364 |
// Set the ApplicationID. |
| 365 |
azClientOpts := &container.ClientOptions{} |
| 366 |
azClientOpts.Telemetry = policy.TelemetryOptions{ |
| 367 |
ApplicationID: useragent.AzureUserAgentPrefix("blob"), |
| 368 |
} |
| 369 |
|
| 370 |
containerURL, err := url.JoinPath(string(svcURL), string(containerName)) |
| 371 |
if err != nil { |
| 372 |
return nil, err |
| 373 |
} |
| 374 |
switch i.CredType { |
| 375 |
case credTypeDefault: |
| 376 |
cred, err := azidentity.NewDefaultAzureCredential(nil) |
| 377 |
if err != nil { |
| 378 |
return nil, fmt.Errorf("failed azidentity.NewDefaultAzureCredential: %v", err) |
| 379 |
} |
| 380 |
return container.NewClient(containerURL, cred, azClientOpts) |
| 381 |
case credTypeSharedKey: |
| 382 |
sharedKeyCred, err := azblob.NewSharedKeyCredential(i.AccountName, i.AccountKey) |
| 383 |
if err != nil { |
| 384 |
return nil, fmt.Errorf("failed azblob.NewSharedKeyCredential: %v", err) |
| 385 |
} |
| 386 |
return container.NewClientWithSharedKeyCredential(containerURL, sharedKeyCred, azClientOpts) |
| 387 |
case credTypeSASViaNone: |
| 388 |
return container.NewClientWithNoCredential(containerURL, azClientOpts) |
| 389 |
case credTypeConnectionString: |
| 390 |
return container.NewClientFromConnectionString(i.ConnectionString, string(containerName), azClientOpts) |
| 391 |
default: |
| 392 |
return nil, errors.New("internal error, unknown cred type") |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
// Scheme is the URL scheme gcsblob registers its URLOpener under on |
| 397 |
// blob.DefaultMux. |
| 398 |
const Scheme = "azblob" |
| 399 |
|
| 400 |
// URLOpener opens Azure URLs like "azblob://mybucket". |
| 401 |
// |
| 402 |
// The URL host is used as the bucket name. |
| 403 |
// |
| 404 |
// The following query options are supported: |
| 405 |
// - domain: Overrides Options.StorageDomain. |
| 406 |
// - protocol: Overrides Options.Protocol. |
| 407 |
// - cdn: Overrides Options.IsCDN. |
| 408 |
// - localemu: Overrides Options.IsLocalEmulator. |
| 409 |
type URLOpener struct { |
| 410 |
// MakeClient must be set to a non-nil value. |
| 411 |
MakeClient func(svcURL ServiceURL, containerName ContainerName) (*container.Client, error) |
| 412 |
|
| 413 |
// ServiceURLOptions specifies default options for generating the service URL. |
| 414 |
// Some options can be overridden in the URL as described above. |
| 415 |
ServiceURLOptions ServiceURLOptions |
| 416 |
|
| 417 |
// Options specifies the options to pass to OpenBucket. |
| 418 |
Options Options |
| 419 |
} |
| 420 |
|
| 421 |
// OpenBucketURL opens a blob.Bucket based on u. |
| 422 |
func (o *URLOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { |
| 423 |
opts, err := o.ServiceURLOptions.withOverrides(u.Query()) |
| 424 |
if err != nil { |
| 425 |
return nil, err |
| 426 |
} |
| 427 |
svcURL, err := NewServiceURL(opts) |
| 428 |
if err != nil { |
| 429 |
return nil, err |
| 430 |
} |
| 431 |
client, err := o.MakeClient(svcURL, ContainerName(u.Host)) |
| 432 |
if err != nil { |
| 433 |
return nil, err |
| 434 |
} |
| 435 |
return OpenBucket(ctx, client, &o.Options) |
| 436 |
} |
| 437 |
|
| 438 |
// bucket represents a Azure Storage Account Container, which handles read, |
| 439 |
// write and delete operations on objects within it. |
| 440 |
// See https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction. |
| 441 |
type bucket struct { |
| 442 |
client *container.Client |
| 443 |
opts *Options |
| 444 |
} |
| 445 |
|
| 446 |
// NewDefaultClient returns an Azure Blob container client |
| 447 |
// with credentials from the environment as described in the package |
| 448 |
// docstring. |
| 449 |
func NewDefaultClient(svcURL ServiceURL, containerName ContainerName) (*container.Client, error) { |
| 450 |
return newCredInfoFromEnv().NewClient(svcURL, containerName) |
| 451 |
} |
| 452 |
|
| 453 |
// OpenBucket returns a *blob.Bucket backed by Azure Storage Account. See the package |
| 454 |
// documentation for an example and |
| 455 |
// https://godoc.org/github.com/Azure/azure-storage-blob-go/azblob |
| 456 |
// for more details. |
| 457 |
func OpenBucket(ctx context.Context, client *container.Client, opts *Options) (*blob.Bucket, error) { |
| 458 |
b, err := openBucket(ctx, client, opts) |
| 459 |
if err != nil { |
| 460 |
return nil, err |
| 461 |
} |
| 462 |
return blob.NewBucket(b), nil |
| 463 |
} |
| 464 |
|
| 465 |
func openBucket(ctx context.Context, client *container.Client, opts *Options) (*bucket, error) { |
| 466 |
if client == nil { |
| 467 |
return nil, errors.New("azureblob.OpenBucket: client is required") |
| 468 |
} |
| 469 |
if opts == nil { |
| 470 |
opts = &Options{} |
| 471 |
} |
| 472 |
return &bucket{ |
| 473 |
client: client, |
| 474 |
opts: opts, |
| 475 |
}, nil |
| 476 |
} |
| 477 |
|
| 478 |
// Close implements driver.Close. |
| 479 |
func (b *bucket) Close() error { |
| 480 |
return nil |
| 481 |
} |
| 482 |
|
| 483 |
// Copy implements driver.Copy. |
| 484 |
func (b *bucket) Copy(ctx context.Context, dstKey, srcKey string, opts *driver.CopyOptions) error { |
| 485 |
dstKey = escapeKey(dstKey, false) |
| 486 |
dstBlobClient := b.client.NewBlobClient(dstKey) |
| 487 |
srcKey = escapeKey(srcKey, false) |
| 488 |
srcBlobClient := b.client.NewBlobClient(srcKey) |
| 489 |
copyOptions := &azblobblob.StartCopyFromURLOptions{} |
| 490 |
if opts.BeforeCopy != nil { |
| 491 |
asFunc := func(i any) bool { |
| 492 |
switch v := i.(type) { |
| 493 |
case **azblobblob.StartCopyFromURLOptions: |
| 494 |
*v = copyOptions |
| 495 |
return true |
| 496 |
} |
| 497 |
return false |
| 498 |
} |
| 499 |
if err := opts.BeforeCopy(asFunc); err != nil { |
| 500 |
return err |
| 501 |
} |
| 502 |
} |
| 503 |
resp, err := dstBlobClient.StartCopyFromURL(ctx, srcBlobClient.URL(), copyOptions) |
| 504 |
if err != nil { |
| 505 |
return err |
| 506 |
} |
| 507 |
nErrors := 0 |
| 508 |
copyStatus := *resp.CopyStatus |
| 509 |
for copyStatus == azblobblob.CopyStatusTypePending { |
| 510 |
// Poll until the copy is complete. |
| 511 |
time.Sleep(500 * time.Millisecond) |
| 512 |
propertiesResp, err := dstBlobClient.GetProperties(ctx, nil) |
| 513 |
if err != nil { |
| 514 |
// A GetProperties failure may be transient, so allow a couple |
| 515 |
// of them before giving up. |
| 516 |
nErrors++ |
| 517 |
if ctx.Err() != nil || nErrors == 3 { |
| 518 |
return err |
| 519 |
} |
| 520 |
} |
| 521 |
copyStatus = *propertiesResp.CopyStatus |
| 522 |
} |
| 523 |
if copyStatus != azblobblob.CopyStatusTypeSuccess { |
| 524 |
return fmt.Errorf("Copy failed with status: %s", copyStatus) |
| 525 |
} |
| 526 |
return nil |
| 527 |
} |
| 528 |
|
| 529 |
// Delete implements driver.Delete. |
| 530 |
func (b *bucket) Delete(ctx context.Context, key string) error { |
| 531 |
key = escapeKey(key, false) |
| 532 |
blobClient := b.client.NewBlobClient(key) |
| 533 |
_, err := blobClient.Delete(ctx, nil) |
| 534 |
return err |
| 535 |
} |
| 536 |
|
| 537 |
// reader reads an azblob. It implements io.ReadCloser. |
| 538 |
type reader struct { |
| 539 |
body io.ReadCloser |
| 540 |
attrs driver.ReaderAttributes |
| 541 |
raw *azblobblob.DownloadStreamResponse |
| 542 |
} |
| 543 |
|
| 544 |
func (r *reader) Read(p []byte) (int, error) { |
| 545 |
return r.body.Read(p) |
| 546 |
} |
| 547 |
|
| 548 |
func (r *reader) Close() error { |
| 549 |
return r.body.Close() |
| 550 |
} |
| 551 |
|
| 552 |
func (r *reader) Attributes() *driver.ReaderAttributes { |
| 553 |
return &r.attrs |
| 554 |
} |
| 555 |
|
| 556 |
func (r *reader) As(i any) bool { |
| 557 |
p, ok := i.(*azblobblob.DownloadStreamResponse) |
| 558 |
if !ok { |
| 559 |
return false |
| 560 |
} |
| 561 |
*p = *r.raw |
| 562 |
return true |
| 563 |
} |
| 564 |
|
| 565 |
// NewRangeReader implements driver.NewRangeReader. |
| 566 |
func (b *bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *driver.ReaderOptions) (driver.Reader, error) { |
| 567 |
key = escapeKey(key, false) |
| 568 |
blobClient := b.client.NewBlobClient(key) |
| 569 |
downloadOpts := azblob.DownloadStreamOptions{} |
| 570 |
if offset != 0 { |
| 571 |
downloadOpts.Range.Offset = offset |
| 572 |
} |
| 573 |
if length >= 0 { |
| 574 |
downloadOpts.Range.Count = length |
| 575 |
} |
| 576 |
if opts.BeforeRead != nil { |
| 577 |
asFunc := func(i any) bool { |
| 578 |
if p, ok := i.(**azblobblob.DownloadStreamOptions); ok { |
| 579 |
*p = &downloadOpts |
| 580 |
return true |
| 581 |
} |
| 582 |
return false |
| 583 |
} |
| 584 |
if err := opts.BeforeRead(asFunc); err != nil { |
| 585 |
return nil, err |
| 586 |
} |
| 587 |
} |
| 588 |
blobDownloadResponse, err := blobClient.DownloadStream(ctx, &downloadOpts) |
| 589 |
if err != nil { |
| 590 |
return nil, err |
| 591 |
} |
| 592 |
attrs := driver.ReaderAttributes{ |
| 593 |
ContentType: to.String(blobDownloadResponse.ContentType), |
| 594 |
Size: getSize(blobDownloadResponse.ContentLength, to.String(blobDownloadResponse.ContentRange)), |
| 595 |
ModTime: *blobDownloadResponse.LastModified, |
| 596 |
} |
| 597 |
var body io.ReadCloser |
| 598 |
if length == 0 { |
| 599 |
body = http.NoBody |
| 600 |
} else { |
| 601 |
body = blobDownloadResponse.Body |
| 602 |
} |
| 603 |
return &reader{ |
| 604 |
body: body, |
| 605 |
attrs: attrs, |
| 606 |
raw: &blobDownloadResponse, |
| 607 |
}, nil |
| 608 |
} |
| 609 |
|
| 610 |
func getSize(contentLength *int64, contentRange string) int64 { |
| 611 |
var size int64 |
| 612 |
// Default size to ContentLength, but that's incorrect for partial-length reads, |
| 613 |
// where ContentLength refers to the size of the returned Body, not the entire |
| 614 |
// size of the blob. ContentRange has the full size. |
| 615 |
if contentLength != nil { |
| 616 |
size = *contentLength |
| 617 |
} |
| 618 |
if contentRange != "" { |
| 619 |
// Sample: bytes 10-14/27 (where 27 is the full size). |
| 620 |
parts := strings.Split(contentRange, "/") |
| 621 |
if len(parts) == 2 { |
| 622 |
if i, err := strconv.ParseInt(parts[1], 10, 64); err == nil { |
| 623 |
size = i |
| 624 |
} |
| 625 |
} |
| 626 |
} |
| 627 |
return size |
| 628 |
} |
| 629 |
|
| 630 |
// As implements driver.As. |
| 631 |
func (b *bucket) As(i any) bool { |
| 632 |
p, ok := i.(**container.Client) |
| 633 |
if !ok { |
| 634 |
return false |
| 635 |
} |
| 636 |
*p = b.client |
| 637 |
return true |
| 638 |
} |
| 639 |
|
| 640 |
// As implements driver.ErrorAs. |
| 641 |
func (b *bucket) ErrorAs(err error, i any) bool { |
| 642 |
switch v := err.(type) { |
| 643 |
case *azcore.ResponseError: |
| 644 |
if p, ok := i.(**azcore.ResponseError); ok { |
| 645 |
*p = v |
| 646 |
return true |
| 647 |
} |
| 648 |
} |
| 649 |
return false |
| 650 |
} |
| 651 |
|
| 652 |
func (b *bucket) ErrorCode(err error) gcerrors.ErrorCode { |
| 653 |
var rErr *azcore.ResponseError |
| 654 |
if errors.As(err, &rErr) { |
| 655 |
switch bloberror.Code(rErr.ErrorCode) { |
| 656 |
case bloberror.AuthenticationFailed: |
| 657 |
return gcerrors.PermissionDenied |
| 658 |
case bloberror.BlobAlreadyExists, |
| 659 |
bloberror.ConditionNotMet, |
| 660 |
bloberror.TargetConditionNotMet, |
| 661 |
bloberror.SourceConditionNotMet: |
| 662 |
// the documented error code is a variation of "ConditionNotMet", but "BlobAlreadyExists" has also been observed |
| 663 |
return gcerrors.FailedPrecondition |
| 664 |
case bloberror.BlobNotFound: |
| 665 |
return gcerrors.NotFound |
| 666 |
} |
| 667 |
|
| 668 |
if rErr.StatusCode == http.StatusNotFound { |
| 669 |
return gcerrors.NotFound |
| 670 |
} |
| 671 |
} |
| 672 |
|
| 673 |
if strings.Contains(err.Error(), "no such host") { |
| 674 |
// This happens with an invalid storage account name; the host |
| 675 |
// is something like invalidstorageaccount.blob.core.windows.net. |
| 676 |
return gcerrors.NotFound |
| 677 |
} |
| 678 |
return gcerrors.Unknown |
| 679 |
} |
| 680 |
|
| 681 |
// Attributes implements driver.Attributes. |
| 682 |
func (b *bucket) Attributes(ctx context.Context, key string) (*driver.Attributes, error) { |
| 683 |
key = escapeKey(key, false) |
| 684 |
blobClient := b.client.NewBlobClient(key) |
| 685 |
blobPropertiesResponse, err := blobClient.GetProperties(ctx, nil) |
| 686 |
if err != nil { |
| 687 |
return nil, err |
| 688 |
} |
| 689 |
|
| 690 |
md := make(map[string]string, len(blobPropertiesResponse.Metadata)) |
| 691 |
for k, v := range blobPropertiesResponse.Metadata { |
| 692 |
// See the package comments for more details on escaping of metadata |
| 693 |
// keys & values. |
| 694 |
if v != nil { |
| 695 |
md[escape.HexUnescape(k)] = escape.URLUnescape(*v) |
| 696 |
} |
| 697 |
} |
| 698 |
var eTag string |
| 699 |
if blobPropertiesResponse.ETag != nil { |
| 700 |
eTag = string(*blobPropertiesResponse.ETag) |
| 701 |
} |
| 702 |
return &driver.Attributes{ |
| 703 |
CacheControl: to.String(blobPropertiesResponse.CacheControl), |
| 704 |
ContentDisposition: to.String(blobPropertiesResponse.ContentDisposition), |
| 705 |
ContentEncoding: to.String(blobPropertiesResponse.ContentEncoding), |
| 706 |
ContentLanguage: to.String(blobPropertiesResponse.ContentLanguage), |
| 707 |
ContentType: to.String(blobPropertiesResponse.ContentType), |
| 708 |
Size: to.Int64(blobPropertiesResponse.ContentLength), |
| 709 |
CreateTime: *blobPropertiesResponse.CreationTime, |
| 710 |
ModTime: *blobPropertiesResponse.LastModified, |
| 711 |
MD5: blobPropertiesResponse.ContentMD5, |
| 712 |
ETag: eTag, |
| 713 |
Metadata: md, |
| 714 |
AsFunc: func(i any) bool { |
| 715 |
p, ok := i.(*azblobblob.GetPropertiesResponse) |
| 716 |
if !ok { |
| 717 |
return false |
| 718 |
} |
| 719 |
*p = blobPropertiesResponse |
| 720 |
return true |
| 721 |
}, |
| 722 |
}, nil |
| 723 |
} |
| 724 |
|
| 725 |
// ListPaged implements driver.ListPaged. |
| 726 |
func (b *bucket) ListPaged(ctx context.Context, opts *driver.ListOptions) (*driver.ListPage, error) { |
| 727 |
pageSize := opts.PageSize |
| 728 |
if pageSize == 0 { |
| 729 |
pageSize = defaultPageSize |
| 730 |
} |
| 731 |
|
| 732 |
var marker *string |
| 733 |
if len(opts.PageToken) > 0 { |
| 734 |
pt := string(opts.PageToken) |
| 735 |
marker = &pt |
| 736 |
} |
| 737 |
|
| 738 |
pageSize32 := int32(pageSize) |
| 739 |
prefix := escapeKey(opts.Prefix, true) |
| 740 |
azOpts := container.ListBlobsHierarchyOptions{ |
| 741 |
MaxResults: &pageSize32, |
| 742 |
Prefix: &prefix, |
| 743 |
Marker: marker, |
| 744 |
} |
| 745 |
if opts.BeforeList != nil { |
| 746 |
asFunc := func(i any) bool { |
| 747 |
p, ok := i.(**container.ListBlobsHierarchyOptions) |
| 748 |
if !ok { |
| 749 |
return false |
| 750 |
} |
| 751 |
*p = &azOpts |
| 752 |
return true |
| 753 |
} |
| 754 |
if err := opts.BeforeList(asFunc); err != nil { |
| 755 |
return nil, err |
| 756 |
} |
| 757 |
} |
| 758 |
azPager := b.client.NewListBlobsHierarchyPager(escapeKey(opts.Delimiter, true), &azOpts) |
| 759 |
resp, err := azPager.NextPage(ctx) |
| 760 |
if err != nil { |
| 761 |
return nil, err |
| 762 |
} |
| 763 |
page := &driver.ListPage{} |
| 764 |
page.Objects = []*driver.ListObject{} |
| 765 |
segment := resp.ListBlobsHierarchySegmentResponse.Segment |
| 766 |
for _, blobPrefix := range segment.BlobPrefixes { |
| 767 |
page.Objects = append(page.Objects, &driver.ListObject{ |
| 768 |
Key: unescapeKey(to.String(blobPrefix.Name)), |
| 769 |
Size: 0, |
| 770 |
IsDir: true, |
| 771 |
AsFunc: func(i any) bool { |
| 772 |
v, ok := i.(*container.BlobPrefix) |
| 773 |
if ok { |
| 774 |
*v = *blobPrefix |
| 775 |
} |
| 776 |
return ok |
| 777 |
}, |
| 778 |
}) |
| 779 |
} |
| 780 |
for _, blobInfo := range segment.BlobItems { |
| 781 |
page.Objects = append(page.Objects, &driver.ListObject{ |
| 782 |
Key: unescapeKey(to.String(blobInfo.Name)), |
| 783 |
ModTime: *blobInfo.Properties.LastModified, |
| 784 |
Size: *blobInfo.Properties.ContentLength, |
| 785 |
MD5: blobInfo.Properties.ContentMD5, |
| 786 |
IsDir: false, |
| 787 |
AsFunc: func(i any) bool { |
| 788 |
v, ok := i.(*container.BlobItem) |
| 789 |
if ok { |
| 790 |
*v = *blobInfo |
| 791 |
} |
| 792 |
return ok |
| 793 |
}, |
| 794 |
}) |
| 795 |
} |
| 796 |
if resp.NextMarker != nil { |
| 797 |
page.NextPageToken = []byte(*resp.NextMarker) |
| 798 |
} |
| 799 |
if len(segment.BlobPrefixes) > 0 && len(segment.BlobItems) > 0 { |
| 800 |
sort.Slice(page.Objects, func(i, j int) bool { |
| 801 |
return page.Objects[i].Key < page.Objects[j].Key |
| 802 |
}) |
| 803 |
} |
| 804 |
return page, nil |
| 805 |
} |
| 806 |
|
| 807 |
// SignedURL implements driver.SignedURL. |
| 808 |
func (b *bucket) SignedURL(ctx context.Context, key string, opts *driver.SignedURLOptions) (string, error) { |
| 809 |
if opts.ContentType != "" || opts.EnforceAbsentContentType { |
| 810 |
return "", gcerr.New(gcerr.Unimplemented, nil, 1, "azureblob: does not enforce Content-Type on PUT") |
| 811 |
} |
| 812 |
|
| 813 |
key = escapeKey(key, false) |
| 814 |
blobClient := b.client.NewBlobClient(key) |
| 815 |
perms := sas.BlobPermissions{} |
| 816 |
switch opts.Method { |
| 817 |
case http.MethodGet: |
| 818 |
perms.Read = true |
| 819 |
case http.MethodPut: |
| 820 |
perms.Create = true |
| 821 |
perms.Write = true |
| 822 |
case http.MethodDelete: |
| 823 |
perms.Delete = true |
| 824 |
default: |
| 825 |
return "", fmt.Errorf("unsupported Method %s", opts.Method) |
| 826 |
} |
| 827 |
|
| 828 |
if opts.BeforeSign != nil { |
| 829 |
asFunc := func(i any) bool { |
| 830 |
v, ok := i.(**sas.BlobPermissions) |
| 831 |
if ok { |
| 832 |
*v = &perms |
| 833 |
} |
| 834 |
return ok |
| 835 |
} |
| 836 |
if err := opts.BeforeSign(asFunc); err != nil { |
| 837 |
return "", err |
| 838 |
} |
| 839 |
} |
| 840 |
start := time.Now().UTC() |
| 841 |
expiry := start.Add(opts.Expiry) |
| 842 |
return blobClient.GetSASURL(perms, expiry, &azblobblob.GetSASURLOptions{StartTime: &start}) |
| 843 |
} |
| 844 |
|
| 845 |
type writer struct { |
| 846 |
ctx context.Context |
| 847 |
client *blockblob.Client |
| 848 |
uploadOpts *azblob.UploadStreamOptions |
| 849 |
|
| 850 |
// Ends of an io.Pipe, created when the first byte is written. |
| 851 |
pw *io.PipeWriter |
| 852 |
pr *io.PipeReader |
| 853 |
|
| 854 |
// Alternatively, upload is set to true when Upload was |
| 855 |
// used to upload data. |
| 856 |
upload bool |
| 857 |
|
| 858 |
donec chan struct{} // closed when done writing |
| 859 |
// The following fields will be written before donec closes: |
| 860 |
err error |
| 861 |
} |
| 862 |
|
| 863 |
// escapeKey does all required escaping for UTF-8 strings to work with Azure. |
| 864 |
// isPrefix indicates whether the key is a full key, or a prefix/delimiter. |
| 865 |
func escapeKey(key string, isPrefix bool) string { |
| 866 |
return escape.HexEscape(key, func(r []rune, i int) bool { |
| 867 |
c := r[i] |
| 868 |
switch { |
| 869 |
// Azure does not work well with backslashes in blob names. |
| 870 |
case c == '\\': |
| 871 |
return true |
| 872 |
// Azure doesn't handle these characters (determined via experimentation). |
| 873 |
case c < 32 || c == 34 || c == 35 || c == 37 || c == 63 || c == 127: |
| 874 |
return true |
| 875 |
// Escape trailing "/" for full keys, otherwise Azure can't address them |
| 876 |
// consistently. |
| 877 |
case !isPrefix && i == len(key)-1 && c == '/': |
| 878 |
return true |
| 879 |
// For "../", escape the trailing slash. |
| 880 |
case i > 1 && r[i] == '/' && r[i-1] == '.' && r[i-2] == '.': |
| 881 |
return true |
| 882 |
} |
| 883 |
return false |
| 884 |
}) |
| 885 |
} |
| 886 |
|
| 887 |
// unescapeKey reverses escapeKey. |
| 888 |
func unescapeKey(key string) string { |
| 889 |
return escape.HexUnescape(key) |
| 890 |
} |
| 891 |
|
| 892 |
// NewTypedWriter implements driver.NewTypedWriter. |
| 893 |
func (b *bucket) NewTypedWriter(ctx context.Context, key, contentType string, opts *driver.WriterOptions) (driver.Writer, error) { |
| 894 |
key = escapeKey(key, false) |
| 895 |
blobClient := b.client.NewBlockBlobClient(key) |
| 896 |
if opts.BufferSize == 0 { |
| 897 |
opts.BufferSize = defaultUploadBlockSize |
| 898 |
} |
| 899 |
if opts.MaxConcurrency == 0 { |
| 900 |
opts.MaxConcurrency = defaultUploadBuffers |
| 901 |
} |
| 902 |
|
| 903 |
md := make(map[string]*string, len(opts.Metadata)) |
| 904 |
for k, v := range opts.Metadata { |
| 905 |
// See the package comments for more details on escaping of metadata |
| 906 |
// keys & values. |
| 907 |
e := escape.HexEscape(k, func(runes []rune, i int) bool { |
| 908 |
c := runes[i] |
| 909 |
switch { |
| 910 |
case i == 0 && c >= '0' && c <= '9': |
| 911 |
return true |
| 912 |
case escape.IsASCIIAlphanumeric(c): |
| 913 |
return false |
| 914 |
case c == '_': |
| 915 |
return false |
| 916 |
} |
| 917 |
return true |
| 918 |
}) |
| 919 |
if _, ok := md[e]; ok { |
| 920 |
return nil, fmt.Errorf("duplicate keys after escaping: %q => %q", k, e) |
| 921 |
} |
| 922 |
escaped := escape.URLEscape(v) |
| 923 |
md[e] = &escaped |
| 924 |
} |
| 925 |
uploadOpts := &azblob.UploadStreamOptions{ |
| 926 |
BlockSize: int64(opts.BufferSize), |
| 927 |
Concurrency: opts.MaxConcurrency, |
| 928 |
Metadata: md, |
| 929 |
HTTPHeaders: &azblobblob.HTTPHeaders{ |
| 930 |
BlobCacheControl: &opts.CacheControl, |
| 931 |
BlobContentDisposition: &opts.ContentDisposition, |
| 932 |
BlobContentEncoding: &opts.ContentEncoding, |
| 933 |
BlobContentLanguage: &opts.ContentLanguage, |
| 934 |
BlobContentMD5: opts.ContentMD5, |
| 935 |
BlobContentType: &contentType, |
| 936 |
}, |
| 937 |
} |
| 938 |
if opts.IfNotExist { |
| 939 |
etagAny := azcore.ETagAny |
| 940 |
uploadOpts.AccessConditions = &azblob.AccessConditions{ |
| 941 |
ModifiedAccessConditions: &azblobblob.ModifiedAccessConditions{ |
| 942 |
IfNoneMatch: &etagAny, |
| 943 |
}, |
| 944 |
} |
| 945 |
} |
| 946 |
if opts.BeforeWrite != nil { |
| 947 |
asFunc := func(i any) bool { |
| 948 |
p, ok := i.(**azblob.UploadStreamOptions) |
| 949 |
if !ok { |
| 950 |
return false |
| 951 |
} |
| 952 |
*p = uploadOpts |
| 953 |
return true |
| 954 |
} |
| 955 |
if err := opts.BeforeWrite(asFunc); err != nil { |
| 956 |
return nil, err |
| 957 |
} |
| 958 |
} |
| 959 |
return &writer{ |
| 960 |
ctx: ctx, |
| 961 |
client: blobClient, |
| 962 |
uploadOpts: uploadOpts, |
| 963 |
donec: make(chan struct{}), |
| 964 |
}, nil |
| 965 |
} |
| 966 |
|
| 967 |
// Write appends p to w.pw. User must call Close to close the w after done writing. |
| 968 |
func (w *writer) Write(p []byte) (int, error) { |
| 969 |
// Avoid opening the pipe for a zero-length write; |
| 970 |
// the concrete can do these for empty blobs. |
| 971 |
if len(p) == 0 { |
| 972 |
return 0, nil |
| 973 |
} |
| 974 |
if w.pw == nil { |
| 975 |
// We'll write into pw and use pr as an io.Reader for the |
| 976 |
// Upload call to Azure. |
| 977 |
w.pr, w.pw = io.Pipe() |
| 978 |
w.open(w.pr, true) |
| 979 |
} |
| 980 |
return w.pw.Write(p) |
| 981 |
} |
| 982 |
|
| 983 |
// Upload reads from r. Per the driver, it is guaranteed to be the only |
| 984 |
// write call for this writer. |
| 985 |
func (w *writer) Upload(r io.Reader) error { |
| 986 |
w.upload = true |
| 987 |
w.open(r, false) |
| 988 |
return nil |
| 989 |
} |
| 990 |
|
| 991 |
// r may be nil if we're Closing and no data was written. |
| 992 |
// If closePipeOnError is true, w.pr will be closed if there's an |
| 993 |
// error uploading to Azure. |
| 994 |
func (w *writer) open(r io.Reader, closePipeOnError bool) { |
| 995 |
go func() { |
| 996 |
defer close(w.donec) |
| 997 |
|
| 998 |
if r == nil { |
| 999 |
r = http.NoBody |
| 1000 |
} |
| 1001 |
_, w.err = w.client.UploadStream(w.ctx, r, w.uploadOpts) |
| 1002 |
if w.err != nil { |
| 1003 |
if closePipeOnError { |
| 1004 |
w.pr.CloseWithError(w.err) |
| 1005 |
w.pr = nil |
| 1006 |
} |
| 1007 |
} |
| 1008 |
}() |
| 1009 |
} |
| 1010 |
|
| 1011 |
// Close completes the writer and closes it. Any error occurring during write will |
| 1012 |
// be returned. If a writer is closed before any Write is called, Close will |
| 1013 |
// create an empty file at the given key. |
| 1014 |
func (w *writer) Close() error { |
| 1015 |
if !w.upload { |
| 1016 |
if w.pr != nil { |
| 1017 |
defer w.pr.Close() |
| 1018 |
} |
| 1019 |
if w.pw == nil { |
| 1020 |
// We never got any bytes written. We'll write an http.NoBody. |
| 1021 |
w.open(nil, false) |
| 1022 |
} else if err := w.pw.Close(); err != nil { |
| 1023 |
return err |
| 1024 |
} |
| 1025 |
} |
| 1026 |
<-w.donec |
| 1027 |
return w.err |
| 1028 |
} |