Skip to content

Commit

Permalink
ACR data plane module (#19554)
Browse files Browse the repository at this point in the history
* very early version of azacr

* update ci

* init blob client

* do not export jwtOnlyWithExp

* fix lint

* change to use CGC as much as possible

* move operation

* rename module path

* change back to public autorest/go version

* finalize auth policy

* add and refine example

* add test

* finish test, example and docs

* loose test coverage criteria temporarily

* update recording

* make authenticationPolicy private

* remove readAll from example and change digest calculation to buffered method

* add blob related examples

* remove endpoint schema check logic

* remove unreferenced types

* fix pageable could not get next page problem and add related tests

* rollback some directives

* refine with review

* change coverage config

* refine some naming

* refine some naming

* refine some naming

* refine with latest review

* add BlobDigestCalculator and refine samples and examples

* update Audience value to consolidate with azcore

* refine test and doc

* add test of upload chunk by chunk

* add test recording file

* update autorest/go version and add some error path test case

* refine readme.md

* update uploadChunk API

* update uploadChunk API

* change options of chunk upload

* upgrade core lib version

* move recording file to remote

* refine model name

* fix lint and doc problem

* remove package link for ci check

* update changelog after running pre-release script

* remove pkg link from url validation
  • Loading branch information
tadelesh committed Feb 1, 2023
1 parent dd2af33 commit 3a39031
Show file tree
Hide file tree
Showing 42 changed files with 5,944 additions and 0 deletions.
4 changes: 4 additions & 0 deletions eng/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
"Name": "azblob",
"CoverageGoal": 0.30
},
{
"Name": "azcontainerregistry",
"CoverageGoal": 0.60
},
{
"Name": "azcore",
"CoverageGoal": 0.92
Expand Down
5 changes: 5 additions & 0 deletions sdk/containers/azcontainerregistry/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Release History

## 0.1.0 (2023-02-07)

* This is the initial release of the `azcontainerregistry` library
21 changes: 21 additions & 0 deletions sdk/containers/azcontainerregistry/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Microsoft Corporation. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
147 changes: 147 additions & 0 deletions sdk/containers/azcontainerregistry/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# Azure Container Registry client module for Go

Azure Container Registry allows you to store and manage container images and artifacts in a private registry for all types of container deployments.

Use the client library for Azure Container Registry to:

- List images or artifacts in a registry
- Obtain metadata for images and artifacts, repositories and tags
- Set read/write/delete properties on registry items
- Delete images and artifacts, repositories and tags
- Upload and download images

[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/containers/azcontainerregistry) | [REST API documentation](https://docs.microsoft.com/rest/api/containerregistry/) | [Product documentation](https://docs.microsoft.com/azure/container-registry/)

## Getting started

### Install packages

Install `azcontainerregistry` and `azidentity` with `go get`:
```Bash
go get github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
```
[azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) is used for Azure Active Directory authentication as demonstrated below.

### Prerequisites

- An [Azure subscription](https://azure.microsoft.com/free/)
- A supported Go version (the Azure SDK supports the two most recent Go releases)
- A [Container Registry service instance](https://docs.microsoft.com/azure/container-registry/container-registry-intro)

To create a new Container Registry, you can use the [Azure Portal](https://docs.microsoft.com/azure/container-registry/container-registry-get-started-portal),
[Azure PowerShell](https://docs.microsoft.com/azure/container-registry/container-registry-get-started-powershell), or the [Azure CLI](https://docs.microsoft.com/azure/container-registry/container-registry-get-started-azure-cli).
Here's an example using the Azure CLI:

```Powershell
az acr create --name MyContainerRegistry --resource-group MyResourceGroup --location westus --sku Basic
```
### Authentication

This document demonstrates using [azidentity.NewDefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#NewDefaultAzureCredential) to authenticate.
This credential type works in both local development and production environments.
We recommend using a [managed identity](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview) in production.

Client and BlobClient accepts any [azidentity][https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity] credential.
See the [azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) documentation for more information about other credential types.

#### Create a client

Constructing the client requires your Container Registry's endpoint URL, which you can get from the Azure CLI or the Azure Portal.

```go
import (
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)

func main() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}

client, err := azcontainerregistry.NewClient("<your Container Registry's endpoint URL>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
}
```

## Key concepts

A **registry** stores Docker images and [OCI Artifacts](https://opencontainers.org/).
An image or artifact consists of a **manifest** and **layers**.
An image's manifest describes the layers that make up the image, and is uniquely identified by its **digest**.
An image can also be "tagged" to give it a human-readable alias.
An image or artifact can have zero or more **tags** associated with it, and each tag uniquely identifies the image.
A collection of images that share the same name but have different tags, is referred to as a **repository**.

For more information please see [Container Registry Concepts](https://docs.microsoft.com/azure/container-registry/container-registry-concepts).

## Examples

Get started with our examples in pkg.go.dev.

## Troubleshooting

### Error Handling

All methods which send HTTP requests return `*azcore.ResponseError` when these requests fail. `ResponseError` has error details and the raw response from Container Registry.

```go
import "github.com/Azure/azure-sdk-for-go/sdk/azcore"

resp, err := client.GetRepositoryProperties(ctx, "library/hello-world", nil)
if err != nil {
var httpErr *azcore.ResponseError
if errors.As(err, &httpErr) {
// TODO: investigate httpErr
} else {
// TODO: not an HTTP error
}
}
```

### Logging

This module uses the logging implementation in `azcore`. To turn on logging for all Azure SDK modules, set `AZURE_SDK_GO_LOGGING` to `all`. By default the logger writes to stderr. Use the `azcore/log` package to control log output. For example, logging only HTTP request and response events, and printing them to stdout:

```go
import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"

// Print log events to stdout
azlog.SetListener(func(cls azlog.Event, msg string) {
fmt.Println(msg)
})

// Includes only requests and responses in credential logs
azlog.SetEvents(azlog.EventRequest, azlog.EventResponse)
```

### Accessing `http.Response`

You can access the raw `*http.Response` returned by Container Registry using the `runtime.WithCaptureResponse` method and a context passed to any client method.

```go
import "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"

var response *http.Response
ctx := runtime.WithCaptureResponse(context.TODO(), &response)
_, err = client.GetRepositoryProperties(ctx, "library/hello-world", nil)
if err != nil {
// TODO: handle error
}
// TODO: do something with response
```

## Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct][https://opensource.microsoft.com/codeofconduct/]. For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact opencode@microsoft.com with any additional questions or comments.


6 changes: 6 additions & 0 deletions sdk/containers/azcontainerregistry/assets.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "go",
"TagPrefix": "go/containers/azcontainerregistry",
"Tag": "go/containers/azcontainerregistry_c8ca813cd9"
}
142 changes: 142 additions & 0 deletions sdk/containers/azcontainerregistry/authentication_client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions sdk/containers/azcontainerregistry/authentication_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//go:build go1.18
// +build go1.18

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

package azcontainerregistry

import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/stretchr/testify/require"
"testing"
)

func Test_authenticationClient_ExchangeAADAccessTokenForACRRefreshToken(t *testing.T) {
startRecording(t)
cred, options := getCredAndClientOptions(t)
client := newAuthenticationClient("https://azacrlivetest.azurecr.io", &authenticationClientOptions{ClientOptions: options})
ctx := context.Background()
accessToken, err := cred.GetToken(
ctx,
policy.TokenRequestOptions{
Scopes: []string{"https://management.core.windows.net/.default"},
})
require.NoError(t, err)
resp, err := client.ExchangeAADAccessTokenForACRRefreshToken(ctx, postContentSchemaGrantTypeAccessToken, "azacrlivetest.azurecr.io", &authenticationClientExchangeAADAccessTokenForACRRefreshTokenOptions{
AccessToken: &accessToken.Token,
})
require.NoError(t, err)
require.NotEmpty(t, *resp.acrRefreshToken.RefreshToken)
}

func Test_authenticationClient_ExchangeACRRefreshTokenForACRAccessToken(t *testing.T) {
startRecording(t)
cred, options := getCredAndClientOptions(t)
client := newAuthenticationClient("https://azacrlivetest.azurecr.io", &authenticationClientOptions{ClientOptions: options})
ctx := context.Background()
accessToken, err := cred.GetToken(
ctx,
policy.TokenRequestOptions{
Scopes: []string{"https://management.core.windows.net/.default"},
})
require.NoError(t, err)
refreshResp, err := client.ExchangeAADAccessTokenForACRRefreshToken(ctx, postContentSchemaGrantTypeAccessToken, "azacrlivetest.azurecr.io", &authenticationClientExchangeAADAccessTokenForACRRefreshTokenOptions{
AccessToken: &accessToken.Token,
})
require.NoError(t, err)
require.NotEmpty(t, *refreshResp.acrRefreshToken.RefreshToken)
accessResp, err := client.ExchangeACRRefreshTokenForACRAccessToken(ctx, "azacrlivetest.azurecr.io", "registry:catalog:*", *refreshResp.acrRefreshToken.RefreshToken, &authenticationClientExchangeACRRefreshTokenForACRAccessTokenOptions{GrantType: to.Ptr(tokenGrantTypeRefreshToken)})
require.NoError(t, err)
require.NotEmpty(t, *accessResp.acrAccessToken.AccessToken)
}
Loading

0 comments on commit 3a39031

Please sign in to comment.