2022-09-05 03:06:08 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-08-23 07:19:37 -04:00
|
|
|
package gcp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
compute "cloud.google.com/go/compute/apiv1"
|
2022-12-08 05:26:51 -05:00
|
|
|
"cloud.google.com/go/compute/apiv1/computepb"
|
2022-09-21 07:47:57 -04:00
|
|
|
"github.com/edgelesssys/constellation/v2/internal/logger"
|
2022-08-23 07:19:37 -04:00
|
|
|
"google.golang.org/api/iterator"
|
|
|
|
)
|
|
|
|
|
2022-11-09 09:57:54 -05:00
|
|
|
// Client for GCP Image API.
|
2022-08-23 07:19:37 -04:00
|
|
|
type Client struct {
|
|
|
|
client *compute.ImagesClient
|
|
|
|
log *logger.Logger
|
|
|
|
opts Options
|
|
|
|
}
|
|
|
|
|
2022-11-09 09:57:54 -05:00
|
|
|
// NewClient creates a new Client.
|
2022-08-23 07:19:37 -04:00
|
|
|
func NewClient(ctx context.Context, log *logger.Logger, opts Options) *Client {
|
|
|
|
client, err := compute.NewImagesRESTClient(ctx)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Unable to create GCP client: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Client{
|
|
|
|
client: client,
|
|
|
|
log: log,
|
|
|
|
opts: opts,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-09 09:57:54 -05:00
|
|
|
// Close the GCP client.
|
2022-08-23 07:19:37 -04:00
|
|
|
func (c *Client) Close() error {
|
|
|
|
return c.client.Close()
|
|
|
|
}
|
|
|
|
|
2022-11-09 09:57:54 -05:00
|
|
|
// FetchImages for the given client options.
|
2022-08-23 07:19:37 -04:00
|
|
|
func (c *Client) FetchImages(ctx context.Context) (map[string]string, error) {
|
|
|
|
imgIterator := c.client.List(ctx, &computepb.ListImagesRequest{
|
|
|
|
Project: c.opts.ProjectID,
|
|
|
|
})
|
|
|
|
|
|
|
|
images := map[string]string{}
|
|
|
|
|
|
|
|
for {
|
|
|
|
img, err := imgIterator.Next()
|
|
|
|
if err == iterator.Done {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
c.log.Fatalf("unable to request image: %v", err)
|
|
|
|
}
|
|
|
|
if img == nil || *img.Family != c.opts.ImageFamily {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
imgReference := strings.TrimPrefix(*img.SelfLink, "https://www.googleapis.com/compute/v1/")
|
|
|
|
imgVersion, err := c.opts.Filter(imgReference)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
images[imgVersion] = imgReference
|
|
|
|
}
|
|
|
|
|
|
|
|
return images, nil
|
|
|
|
}
|