|
| 1 | +package leeway |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "os/exec" |
| 9 | + |
| 10 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 11 | + "github.com/aws/aws-sdk-go-v2/config" |
| 12 | + "github.com/aws/aws-sdk-go-v2/service/ecr" |
| 13 | + "github.com/aws/aws-sdk-go-v2/service/ecr/types" |
| 14 | +) |
| 15 | + |
| 16 | +type ImageAdapter interface { |
| 17 | + Create(imageName string) error |
| 18 | + Sign(imageName, profileARN string) error |
| 19 | +} |
| 20 | + |
| 21 | +// ECRAdapter implements the ImageAdapter interface for AWS ECR |
| 22 | +type ECRAdapter struct { |
| 23 | + ecrClient *ecr.Client |
| 24 | +} |
| 25 | + |
| 26 | +// NewECRAdapter initializes an ECRAdapter with an AWS ECR client |
| 27 | +func NewECRAdapter() (*ECRAdapter, error) { |
| 28 | + cfg, err := config.LoadDefaultConfig(context.TODO()) |
| 29 | + if err != nil { |
| 30 | + return nil, fmt.Errorf("unable to load SDK config, %v", err) |
| 31 | + } |
| 32 | + |
| 33 | + client := ecr.NewFromConfig(cfg) |
| 34 | + return &ECRAdapter{ |
| 35 | + ecrClient: client, |
| 36 | + }, nil |
| 37 | +} |
| 38 | + |
| 39 | +// Create checks if the ECR image exists and creates it if it doesn't |
| 40 | +func (e *ECRAdapter) Create(imageName string) error { |
| 41 | + _, err := e.ecrClient.DescribeImages(context.TODO(), &ecr.DescribeImagesInput{ |
| 42 | + RepositoryName: aws.String(imageName), |
| 43 | + }) |
| 44 | + if err == nil { |
| 45 | + fmt.Printf("Image %s already exists\n", imageName) |
| 46 | + return nil |
| 47 | + } |
| 48 | + |
| 49 | + if !isRepositoryNotFoundErr(err) { |
| 50 | + return fmt.Errorf("failed to check if ECR image %s exists: %w", imageName, err) |
| 51 | + } |
| 52 | + |
| 53 | + _, err = e.ecrClient.CreateRepository(context.TODO(), &ecr.CreateRepositoryInput{ |
| 54 | + RepositoryName: aws.String(imageName), |
| 55 | + }) |
| 56 | + if err != nil { |
| 57 | + return fmt.Errorf("failed to create ECR image: %w", err) |
| 58 | + } |
| 59 | + |
| 60 | + fmt.Printf("Image %s created successfully\n", imageName) |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +// Sign uses the notation tool to sign the ECR image |
| 65 | +func (e *ECRAdapter) Sign(imageName, profileARN string) error { |
| 66 | + cmd := exec.Command("notation", "sign", "--profile", profileARN, imageName) |
| 67 | + output, err := cmd.CombinedOutput() |
| 68 | + if err != nil { |
| 69 | + return fmt.Errorf("failed to sign the image: %v, output: %s", err, string(output)) |
| 70 | + } |
| 71 | + |
| 72 | + fmt.Printf("Image %s signed successfully\n", imageName) |
| 73 | + return nil |
| 74 | +} |
| 75 | + |
| 76 | +// isImageNotFoundErr checks if the error is an ImageNotFoundException |
| 77 | +func isRepositoryNotFoundErr(err error) bool { |
| 78 | + var notFoundErr *types.RepositoryNotFoundException |
| 79 | + return errors.As(err, ¬FoundErr) |
| 80 | +} |
0 commit comments