Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade Azure Storage SDK, allow use of default credential #577

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
219 changes: 125 additions & 94 deletions abs/replica_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,20 @@ import (
"context"
"fmt"
"io"
"net/url"
"os"
"path"
"strings"
"sync"
"time"

"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/benbjohnson/litestream"
"github.com/benbjohnson/litestream/internal"
"golang.org/x/sync/errgroup"
Expand All @@ -24,8 +30,8 @@ var _ litestream.ReplicaClient = (*ReplicaClient)(nil)

// ReplicaClient is a client for writing snapshots & WAL segments to disk.
type ReplicaClient struct {
mu sync.Mutex
containerURL *azblob.ContainerURL
mu sync.Mutex
client *container.Client

// Azure credentials
AccountName string
Expand All @@ -52,41 +58,57 @@ func (c *ReplicaClient) Init(ctx context.Context) (err error) {
c.mu.Lock()
defer c.mu.Unlock()

if c.containerURL != nil {
return nil
// Construct & parse endpoint unless already set.
endpoint := c.Endpoint
if endpoint == "" {
if c.AccountName == "" {
return fmt.Errorf("account name is required")
}
endpoint = fmt.Sprintf("https://%s.blob.core.windows.net", c.AccountName)
}
if !strings.HasSuffix(endpoint, "/") {
endpoint += "/"
}
endpoint += c.Bucket

// Read account key from environment, if available.
accountKey := c.AccountKey
if accountKey == "" {
accountKey = os.Getenv("LITESTREAM_AZURE_ACCOUNT_KEY")
}

// Authenticate to ACS.
credential, err := azblob.NewSharedKeyCredential(c.AccountName, accountKey)
if err != nil {
return err
// Authenticate to ACS and build client
options := container.ClientOptions{
ClientOptions: policy.ClientOptions{
Retry: policy.RetryOptions{
TryTimeout: 24 * time.Hour,
},
Telemetry: policy.TelemetryOptions{
ApplicationID: "litestream",
},
},
}

// Construct & parse endpoint unless already set.
endpoint := c.Endpoint
if endpoint == "" {
endpoint = fmt.Sprintf("https://%s.blob.core.windows.net", c.AccountName)
}
endpointURL, err := url.Parse(endpoint)
if err != nil {
return fmt.Errorf("cannot parse azure endpoint: %w", err)
if accountKey == "" {
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
return err
}
c.client, err = container.NewClient(endpoint, credential, &options)
if err != nil {
return fmt.Errorf("cannot create Azure Blob Storage client: %w", err)
}
} else {
credential, err := azblob.NewSharedKeyCredential(c.AccountName, accountKey)
if err != nil {
return err
}
c.client, err = container.NewClientWithSharedKeyCredential(endpoint, credential, &options)
if err != nil {
return fmt.Errorf("cannot create Azure Blob Storage client: %w", err)
}
}

// Build pipeline and reference to container.
pipeline := azblob.NewPipeline(credential, azblob.PipelineOptions{
Retry: azblob.RetryOptions{
TryTimeout: 24 * time.Hour,
},
})
containerURL := azblob.NewServiceURL(*endpointURL, pipeline).NewContainerURL(c.Bucket)
c.containerURL = &containerURL

return nil
}

Expand All @@ -97,20 +119,21 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
}

var generations []string
var marker azblob.Marker
for marker.NotDone() {
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()

resp, err := c.containerURL.ListBlobsHierarchySegment(ctx, marker, "/", azblob.ListBlobsSegmentOptions{
Prefix: litestream.GenerationsPath(c.Path) + "/",
})
pager := c.client.NewListBlobsHierarchyPager("/", &container.ListBlobsHierarchyOptions{
Prefix: to.Ptr(litestream.GenerationsPath(c.Path) + "/"),
})
for pager.More() {
resp, err := pager.NextPage(ctx)
if err != nil {
return nil, err
}
marker = resp.NextMarker

for _, prefix := range resp.Segment.BlobPrefixes {
name := path.Base(strings.TrimSuffix(prefix.Name, "/"))
if prefix == nil || prefix.Name == nil {
continue
}
name := path.Base(strings.TrimSuffix(*prefix.Name, "/"))
if !litestream.IsGenerationName(name) {
continue
}
Expand All @@ -132,23 +155,28 @@ func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string)
return fmt.Errorf("cannot determine generation path: %w", err)
}

var marker azblob.Marker
for marker.NotDone() {
pager := c.client.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
Prefix: to.Ptr(dir + "/"),
})
for pager.More() {
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()

resp, err := c.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
resp, err := pager.NextPage(ctx)
if err != nil {
return err
}
marker = resp.NextMarker

for _, item := range resp.Segment.BlobItems {
if item == nil || item.Name == nil {
continue
}
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()

blobURL := c.containerURL.NewBlobURL(item.Name)
if _, err := blobURL.Delete(ctx, azblob.DeleteSnapshotsOptionNone, azblob.BlobAccessConditions{}); isNotExists(err) {
continue
} else if err != nil {
_, err = c.client.NewBlobClient(*item.Name).Delete(ctx, nil)
if err != nil {
if bloberror.HasCode(err, bloberror.BlobNotFound) {
continue
}
return err
}
}
Expand Down Expand Up @@ -181,11 +209,12 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in

rc := internal.NewReadCounter(rd)

blobURL := c.containerURL.NewBlockBlobURL(key)
if _, err := azblob.UploadStreamToBlockBlob(ctx, rc, blobURL, azblob.UploadStreamToBlockBlobOptions{
BlobHTTPHeaders: azblob.BlobHTTPHeaders{ContentType: "application/octet-stream"},
BlobAccessTier: azblob.DefaultAccessTier,
}); err != nil {
_, err = c.client.NewBlockBlobClient(key).UploadStream(ctx, rc, &blockblob.UploadStreamOptions{
HTTPHeaders: &blob.HTTPHeaders{
BlobContentType: to.Ptr("application/octet-stream"),
},
})
if err != nil {
return info, err
}

Expand Down Expand Up @@ -213,18 +242,18 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
}

blobURL := c.containerURL.NewBlobURL(key)
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
if isNotExists(err) {
return nil, os.ErrNotExist
} else if err != nil {
resp, err := c.client.NewBlobClient(key).DownloadStream(ctx, nil)
if err != nil {
if bloberror.HasCode(err, bloberror.BlobNotFound) {
return nil, os.ErrNotExist
}
return nil, fmt.Errorf("cannot start new reader for %q: %w", key, err)
}

internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "GET").Inc()
internal.OperationBytesCounterVec.WithLabelValues(ReplicaClientType, "GET").Add(float64(resp.ContentLength()))
internal.OperationBytesCounterVec.WithLabelValues(ReplicaClientType, "GET").Add(float64(*resp.ContentLength))

return resp.Body(azblob.RetryReaderOptions{}), nil
return resp.NewRetryReader(ctx, nil), nil
}

// DeleteSnapshot deletes a snapshot with the given generation & index.
Expand All @@ -240,10 +269,11 @@ func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, i

internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()

blobURL := c.containerURL.NewBlobURL(key)
if _, err := blobURL.Delete(ctx, azblob.DeleteSnapshotsOptionNone, azblob.BlobAccessConditions{}); isNotExists(err) {
return nil
} else if err != nil {
_, err = c.client.NewBlobClient(key).Delete(ctx, nil)
if err != nil {
if bloberror.HasCode(err, bloberror.BlobNotFound) {
return nil
}
return fmt.Errorf("cannot delete snapshot %q: %w", key, err)
}
return nil
Expand Down Expand Up @@ -271,11 +301,12 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,

rc := internal.NewReadCounter(rd)

blobURL := c.containerURL.NewBlockBlobURL(key)
if _, err := azblob.UploadStreamToBlockBlob(ctx, rc, blobURL, azblob.UploadStreamToBlockBlobOptions{
BlobHTTPHeaders: azblob.BlobHTTPHeaders{ContentType: "application/octet-stream"},
BlobAccessTier: azblob.DefaultAccessTier,
}); err != nil {
_, err = c.client.NewBlockBlobClient(key).UploadStream(ctx, rc, &blockblob.UploadStreamOptions{
HTTPHeaders: &blob.HTTPHeaders{
BlobContentType: to.Ptr("application/octet-stream"),
},
})
if err != nil {
return info, err
}

Expand Down Expand Up @@ -303,18 +334,18 @@ func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
}

blobURL := c.containerURL.NewBlobURL(key)
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
if isNotExists(err) {
return nil, os.ErrNotExist
} else if err != nil {
resp, err := c.client.NewBlobClient(key).DownloadStream(ctx, nil)
if err != nil {
if bloberror.HasCode(err, bloberror.BlobNotFound) {
return nil, os.ErrNotExist
}
return nil, fmt.Errorf("cannot start new reader for %q: %w", key, err)
}

internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "GET").Inc()
internal.OperationBytesCounterVec.WithLabelValues(ReplicaClientType, "GET").Add(float64(resp.ContentLength()))
internal.OperationBytesCounterVec.WithLabelValues(ReplicaClientType, "GET").Add(float64(*resp.ContentLength))

return resp.Body(azblob.RetryReaderOptions{}), nil
return resp.NewRetryReader(ctx, nil), nil
}

// DeleteWALSegments deletes WAL segments with at the given positions.
Expand All @@ -331,10 +362,11 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po

internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()

blobURL := c.containerURL.NewBlobURL(key)
if _, err := blobURL.Delete(ctx, azblob.DeleteSnapshotsOptionNone, azblob.BlobAccessConditions{}); isNotExists(err) {
continue
} else if err != nil {
_, err = c.client.NewBlobClient(key).Delete(ctx, nil)
if err != nil {
if bloberror.HasCode(err, bloberror.BlobNotFound) {
continue
}
return fmt.Errorf("cannot delete wal segment %q: %w", key, err)
}
}
Expand Down Expand Up @@ -377,18 +409,22 @@ func (itr *snapshotIterator) fetch() error {
return fmt.Errorf("cannot determine snapshots path: %w", err)
}

var marker azblob.Marker
for marker.NotDone() {
pager := itr.client.client.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
Prefix: to.Ptr(dir + "/"),
})
for pager.More() {
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()

resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
resp, err := pager.NextPage(itr.ctx)
if err != nil {
return err
}
marker = resp.NextMarker

for _, item := range resp.Segment.BlobItems {
key := path.Base(item.Name)
if item == nil || item.Name == nil {
continue
}
key := path.Base(*item.Name)
index, err := litestream.ParseSnapshotPath(key)
if err != nil {
continue
Expand Down Expand Up @@ -483,18 +519,22 @@ func (itr *walSegmentIterator) fetch() error {
return fmt.Errorf("cannot determine wal path: %w", err)
}

var marker azblob.Marker
for marker.NotDone() {
pager := itr.client.client.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
Prefix: to.Ptr(dir + "/"),
})
for pager.More() {
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()

resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
resp, err := pager.NextPage(itr.ctx)
if err != nil {
return err
}
marker = resp.NextMarker

for _, item := range resp.Segment.BlobItems {
key := path.Base(item.Name)
if item == nil || item.Name == nil {
continue
}
key := path.Base(*item.Name)
index, offset, err := litestream.ParseWALSegmentPath(key)
if err != nil {
continue
Expand Down Expand Up @@ -554,12 +594,3 @@ func (itr *walSegmentIterator) Err() error { return itr.err }
func (itr *walSegmentIterator) WALSegment() litestream.WALSegmentInfo {
return itr.info
}

func isNotExists(err error) bool {
switch err := err.(type) {
case azblob.StorageError:
return err.ServiceCode() == azblob.ServiceCodeBlobNotFound
default:
return false
}
}
Loading