|
| 1 | +// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 | + |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "errors" |
| 10 | + "fmt" |
| 11 | + "io" |
| 12 | + "log" |
| 13 | + "net/http" |
| 14 | + "os" |
| 15 | + "path/filepath" |
| 16 | + "strings" |
| 17 | + "time" |
| 18 | + |
| 19 | + "cloud.google.com/go/storage" |
| 20 | + "github.com/google/uuid" |
| 21 | + "github.com/siderolabs/go-retry/retry" |
| 22 | + "golang.org/x/sync/errgroup" |
| 23 | + "google.golang.org/api/compute/v1" |
| 24 | + "google.golang.org/api/googleapi" |
| 25 | + "google.golang.org/api/iterator" |
| 26 | + "google.golang.org/api/option" |
| 27 | +) |
| 28 | + |
| 29 | +// GCPUploder registers the image in GCP. |
| 30 | +type GCPUploder struct { |
| 31 | + Options Options |
| 32 | + |
| 33 | + storageClient *storage.Client |
| 34 | + computeService *compute.Service |
| 35 | + projectID string |
| 36 | + |
| 37 | + imagePath string |
| 38 | +} |
| 39 | + |
| 40 | +// NewGCPUploder creates a new GCPUploder. |
| 41 | +func NewGCPUploder(options Options) (*GCPUploder, error) { |
| 42 | + projectID := os.Getenv("GOOGLE_PROJECT_ID") |
| 43 | + credentials := os.Getenv("GOOGLE_CREDENTIALS_JSON") |
| 44 | + |
| 45 | + if projectID == "" { |
| 46 | + return nil, fmt.Errorf("gcp: GOOGLE_PROJECT_ID is not set") |
| 47 | + } |
| 48 | + |
| 49 | + if credentials == "" { |
| 50 | + return nil, fmt.Errorf("gcp: GOOGLE_CREDENTIALS_JSON is not set") |
| 51 | + } |
| 52 | + |
| 53 | + gcpUploader := &GCPUploder{ |
| 54 | + Options: options, |
| 55 | + } |
| 56 | + |
| 57 | + gcpUploader.projectID = projectID |
| 58 | + |
| 59 | + var err error |
| 60 | + |
| 61 | + gcpUploader.storageClient, err = storage.NewClient(context.Background(), option.WithCredentialsJSON([]byte(credentials))) |
| 62 | + if err != nil { |
| 63 | + return nil, fmt.Errorf("gcp: failed to create google storage client: %w", err) |
| 64 | + } |
| 65 | + |
| 66 | + gcpUploader.computeService, err = compute.NewService(context.Background(), option.WithCredentialsJSON([]byte(credentials))) |
| 67 | + if err != nil { |
| 68 | + return nil, fmt.Errorf("gcp: failed to create google compute service: %w", err) |
| 69 | + } |
| 70 | + |
| 71 | + return gcpUploader, nil |
| 72 | +} |
| 73 | + |
| 74 | +// Upload uploads the image to GCP. |
| 75 | +func (u *GCPUploder) Upload(ctx context.Context) error { |
| 76 | + bucketName := fmt.Sprintf("talos-image-upload-%s", uuid.New()) |
| 77 | + |
| 78 | + bucketHandle := u.storageClient.Bucket(bucketName) |
| 79 | + |
| 80 | + if err := bucketHandle.Create(ctx, u.projectID, &storage.BucketAttrs{ |
| 81 | + PublicAccessPrevention: storage.PublicAccessPreventionEnforced, |
| 82 | + }); err != nil { |
| 83 | + return fmt.Errorf("gcp: failed to create bucket %s: %w", bucketName, err) |
| 84 | + } |
| 85 | + |
| 86 | + log.Println("gcp: created bucket", bucketName) |
| 87 | + |
| 88 | + defer func() { |
| 89 | + objects := bucketHandle.Objects(ctx, nil) |
| 90 | + |
| 91 | + for { |
| 92 | + objAttr, err := objects.Next() |
| 93 | + if errors.Is(err, iterator.Done) { |
| 94 | + break |
| 95 | + } |
| 96 | + |
| 97 | + if err != nil { |
| 98 | + log.Printf("gcp: failed to list objects: %v", err) |
| 99 | + } |
| 100 | + |
| 101 | + if err := bucketHandle.Object(objAttr.Name).Delete(ctx); err != nil { |
| 102 | + log.Printf("gcp: failed to delete object %s: %v", objAttr.Name, err) |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + if err := bucketHandle.Delete(ctx); err != nil { |
| 107 | + log.Printf("gcp: failed to delete bucket %s: %v", bucketName, err) |
| 108 | + } |
| 109 | + }() |
| 110 | + |
| 111 | + var g errgroup.Group |
| 112 | + |
| 113 | + for _, arch := range u.Options.Architectures { |
| 114 | + g.Go(func() error { |
| 115 | + return u.uploadImage(ctx, arch, bucketName) |
| 116 | + }) |
| 117 | + } |
| 118 | + |
| 119 | + if err := g.Wait(); err != nil { |
| 120 | + return fmt.Errorf("gcp: failed to upload images: %w", err) |
| 121 | + } |
| 122 | + |
| 123 | + return nil |
| 124 | +} |
| 125 | + |
| 126 | +func (u *GCPUploder) uploadImage(ctx context.Context, arch, bucketName string) error { |
| 127 | + objectPath := u.Options.GCPImage(arch) |
| 128 | + |
| 129 | + objectName := filepath.Base(objectPath) |
| 130 | + |
| 131 | + objectReader, err := os.Open(objectPath) |
| 132 | + if err != nil { |
| 133 | + return fmt.Errorf("gcp: failed to open object data file %s: %w", objectPath, err) |
| 134 | + } |
| 135 | + |
| 136 | + objectHandle := u.storageClient.Bucket(bucketName).Object(objectName) |
| 137 | + |
| 138 | + objectWriter := objectHandle.NewWriter(ctx) |
| 139 | + |
| 140 | + defer objectWriter.Close() //nolint:errcheck |
| 141 | + |
| 142 | + if _, err := io.Copy(objectWriter, objectReader); err != nil { |
| 143 | + return fmt.Errorf("gcp: failed to write object data: %w", err) |
| 144 | + } |
| 145 | + |
| 146 | + if err := objectWriter.Close(); err != nil { |
| 147 | + return fmt.Errorf("gcp: failed to close object writer: %w", err) |
| 148 | + } |
| 149 | + |
| 150 | + u.imagePath = fmt.Sprintf("https://storage.googleapis.com/%s/%s", bucketName, objectName) |
| 151 | + |
| 152 | + log.Println("gcp: uploaded image", u.imagePath) |
| 153 | + |
| 154 | + return u.registerImage(arch) |
| 155 | +} |
| 156 | + |
| 157 | +//nolint:gocyclo |
| 158 | +func (u *GCPUploder) registerImage(arch string) error { |
| 159 | + imageName := fmt.Sprintf("talos-%s-%s", strings.ReplaceAll(u.Options.Tag, ".", "-"), arch) |
| 160 | + |
| 161 | + if u.Options.NamePrefix != "" { |
| 162 | + imageName = fmt.Sprintf("%s-talos-%s-%s", u.Options.NamePrefix, strings.ReplaceAll(u.Options.Tag, ".", "-"), arch) |
| 163 | + } |
| 164 | + |
| 165 | + exists, err := u.checkImageExists(imageName) |
| 166 | + if err != nil { |
| 167 | + return err |
| 168 | + } |
| 169 | + |
| 170 | + if exists { |
| 171 | + log.Printf("gcp: image %s already exists, deleting", imageName) |
| 172 | + |
| 173 | + if deleteErr := u.deleteImage(imageName); deleteErr != nil { |
| 174 | + return deleteErr |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + operationID, link, err := u.insertImage(imageName, arch) |
| 179 | + if err != nil { |
| 180 | + return err |
| 181 | + } |
| 182 | + |
| 183 | + if err := retry.Constant(15*time.Minute, retry.WithUnits(30*time.Second)).Retry(func() error { |
| 184 | + op, err := u.computeService.GlobalOperations.Get(u.projectID, operationID).Do() |
| 185 | + if err != nil { |
| 186 | + return fmt.Errorf("gcp: failed to get operation: %w", err) |
| 187 | + } |
| 188 | + |
| 189 | + if op.HTTPStatusCode != http.StatusOK { |
| 190 | + return fmt.Errorf("gcp: operation failed with http error message: %s", op.HttpErrorMessage) |
| 191 | + } |
| 192 | + |
| 193 | + if op.Error != nil { |
| 194 | + return fmt.Errorf("gcp: operation faild with error message: %s", op.Error.Errors[0].Message) |
| 195 | + } |
| 196 | + |
| 197 | + if op.Status == "DONE" { |
| 198 | + return nil |
| 199 | + } |
| 200 | + |
| 201 | + log.Printf("gcp: image creation progress: %d", op.Progress) |
| 202 | + |
| 203 | + return retry.ExpectedError(fmt.Errorf("gcp: image status is %s", op.Status)) |
| 204 | + }); err != nil { |
| 205 | + return fmt.Errorf("gcp: image creation is taking longer than expected: %w", err) |
| 206 | + } |
| 207 | + |
| 208 | + pushResult(CloudImage{ |
| 209 | + Cloud: "gcp", |
| 210 | + Tag: u.Options.Tag, |
| 211 | + Region: "us", |
| 212 | + Arch: arch, |
| 213 | + Type: "compute#image", |
| 214 | + ID: link, |
| 215 | + }) |
| 216 | + |
| 217 | + return nil |
| 218 | +} |
| 219 | + |
| 220 | +func (u *GCPUploder) checkImageExists(imageName string) (bool, error) { |
| 221 | + _, err := u.computeService.Images.Get(u.projectID, imageName).Do() |
| 222 | + if err != nil { |
| 223 | + var googleErr *googleapi.Error |
| 224 | + |
| 225 | + if errors.As(err, &googleErr) { |
| 226 | + if googleErr.Code == http.StatusNotFound { |
| 227 | + return false, nil |
| 228 | + } |
| 229 | + } |
| 230 | + |
| 231 | + return false, fmt.Errorf("gcp: failed to get image %s: %w", imageName, err) |
| 232 | + } |
| 233 | + |
| 234 | + return true, nil |
| 235 | +} |
| 236 | + |
| 237 | +func (u *GCPUploder) insertImage(imageName, arch string) (operationID, imageLink string, err error) { |
| 238 | + var archImage string |
| 239 | + |
| 240 | + switch arch { |
| 241 | + case "amd64": |
| 242 | + archImage = "x86_64" |
| 243 | + case "arm64": |
| 244 | + archImage = "ARM64" |
| 245 | + default: |
| 246 | + return "", "", fmt.Errorf("gcp: unknown architecture %s", arch) |
| 247 | + } |
| 248 | + |
| 249 | + op, err := u.computeService.Images.Insert(u.projectID, &compute.Image{ |
| 250 | + Architecture: archImage, |
| 251 | + Description: fmt.Sprintf("Talos %s %s", u.Options.Tag, arch), |
| 252 | + GuestOsFeatures: []*compute.GuestOsFeature{ |
| 253 | + { |
| 254 | + Type: "VIRTIO_SCSI_MULTIQUEUE", |
| 255 | + }, |
| 256 | + }, |
| 257 | + Name: imageName, |
| 258 | + RawDisk: &compute.ImageRawDisk{ |
| 259 | + Source: u.imagePath, |
| 260 | + }, |
| 261 | + }).Do() |
| 262 | + if err != nil { |
| 263 | + return "", "", fmt.Errorf("gcp: failed to insert image: %w", err) |
| 264 | + } |
| 265 | + |
| 266 | + if op.HTTPStatusCode != http.StatusOK { |
| 267 | + return "", "", fmt.Errorf("gcp: insert image failed with http error message: %s", op.HttpErrorMessage) |
| 268 | + } |
| 269 | + |
| 270 | + if op.Error != nil { |
| 271 | + return "", "", fmt.Errorf("gcp: insert image failed with error message: %s", op.Error.Errors[0].Message) |
| 272 | + } |
| 273 | + |
| 274 | + log.Printf("gcp: image %s is being created with operation %s", imageName, op.Name) |
| 275 | + |
| 276 | + return op.Name, op.TargetLink, nil |
| 277 | +} |
| 278 | + |
| 279 | +func (u *GCPUploder) deleteImage(imageName string) error { |
| 280 | + if _, err := u.computeService.Images.Delete(u.projectID, imageName).Do(); err != nil { |
| 281 | + return fmt.Errorf("gcp: failed to delete image %s: %w", imageName, err) |
| 282 | + } |
| 283 | + |
| 284 | + if err := retry.Constant(5*time.Minute, retry.WithUnits(30*time.Second)).Retry(func() error { |
| 285 | + _, err := u.computeService.Images.Get(u.projectID, imageName).Do() |
| 286 | + if err != nil { |
| 287 | + var googleErr *googleapi.Error |
| 288 | + |
| 289 | + if errors.As(err, &googleErr) { |
| 290 | + if googleErr.Code == http.StatusNotFound { |
| 291 | + return nil |
| 292 | + } |
| 293 | + } |
| 294 | + |
| 295 | + return err |
| 296 | + } |
| 297 | + |
| 298 | + return retry.ExpectedError(fmt.Errorf("gcp: image %s still exists", imageName)) |
| 299 | + }); err != nil { |
| 300 | + return fmt.Errorf("gcp: failed to delete image %s: %w", imageName, err) |
| 301 | + } |
| 302 | + |
| 303 | + return nil |
| 304 | +} |
0 commit comments