-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompute.go
298 lines (264 loc) · 11.3 KB
/
compute.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package gcp
import (
"context"
"fmt"
"strings"
compute "cloud.google.com/go/compute/apiv1"
"cloud.google.com/go/compute/apiv1/computepb"
"google.golang.org/api/option"
"github.com/ondrejbudai/osbuild-composer-public/public/common"
)
// Guest OS Features for RHEL8 images
var GuestOsFeaturesRHEL8 []*computepb.GuestOsFeature = []*computepb.GuestOsFeature{
{Type: common.ToPtr(computepb.GuestOsFeature_UEFI_COMPATIBLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_VIRTIO_SCSI_MULTIQUEUE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_SEV_CAPABLE.String())},
}
// Guest OS Features for RHEL9 images. Note that if you update this, also
// consider changing the code in https://github.com/coreos/coreos-assembler/blob/0083086c4720b602b8243effb85c0a1f73f013dd/mantle/platform/api/gcloud/image.go#L105
// for RHEL CoreOS which uses coreos-assembler today.
var GuestOsFeaturesRHEL9 []*computepb.GuestOsFeature = []*computepb.GuestOsFeature{
{Type: common.ToPtr(computepb.GuestOsFeature_UEFI_COMPATIBLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_VIRTIO_SCSI_MULTIQUEUE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_SEV_CAPABLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_GVNIC.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_SEV_SNP_CAPABLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_SEV_LIVE_MIGRATABLE_V2.String())},
}
// Guest OS Features for RHEL9.1 images.
// The SEV_LIVE_MIGRATABLE_V2 support was added since RHEL-9.2
var GuestOsFeaturesRHEL91 []*computepb.GuestOsFeature = []*computepb.GuestOsFeature{
{Type: common.ToPtr(computepb.GuestOsFeature_UEFI_COMPATIBLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_VIRTIO_SCSI_MULTIQUEUE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_SEV_CAPABLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_GVNIC.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_SEV_SNP_CAPABLE.String())},
}
// Guest OS Features for RHEL9.0 images.
// The SEV-SNP support was added since RHEL-9.1, so keeping this for RHEL-9.0 only.
var GuestOsFeaturesRHEL90 []*computepb.GuestOsFeature = []*computepb.GuestOsFeature{
{Type: common.ToPtr(computepb.GuestOsFeature_UEFI_COMPATIBLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_VIRTIO_SCSI_MULTIQUEUE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_SEV_CAPABLE.String())},
{Type: common.ToPtr(computepb.GuestOsFeature_GVNIC.String())},
}
// GuestOsFeaturesByDistro returns the the list of Guest OS Features, which
// should be used when importing an image of the specified distribution.
//
// In case the provided distribution does not have any specific Guest OS
// Features list defined, nil is returned.
func GuestOsFeaturesByDistro(distroName string) []*computepb.GuestOsFeature {
switch {
case strings.HasPrefix(distroName, "centos-8"):
fallthrough
case strings.HasPrefix(distroName, "rhel-8"):
return GuestOsFeaturesRHEL8
case distroName == "rhel-90":
return GuestOsFeaturesRHEL90
case distroName == "rhel-91":
return GuestOsFeaturesRHEL91
case strings.HasPrefix(distroName, "centos-9"):
fallthrough
case strings.HasPrefix(distroName, "rhel-9"):
return GuestOsFeaturesRHEL9
default:
return nil
}
}
// ComputeImageInsert imports a previously uploaded archive with raw image into Compute Engine.
//
// The image must be RAW image named 'disk.raw' inside a gzip-ed tarball.
//
// To delete the Storage object (image) used for the image import, use StorageObjectDelete().
//
// bucket - Google storage bucket name with the uploaded image archive
// object - Google storage object name of the uploaded image
// imageName - Desired image name after the import. This must be unique within the whole project.
// regions - A list of valid Google Storage regions where the resulting image should be located.
//
// It is possible to specify multiple regions. Also multi and dual regions are allowed.
// If not provided, the region of the used Storage object is used.
// See: https://cloud.google.com/storage/docs/locations
//
// guestOsFeatures - A list of features supported by the Guest OS on the imported image.
//
// Uses:
// - Compute Engine API
func (g *GCP) ComputeImageInsert(
ctx context.Context,
bucket, object, imageName string,
regions []string,
guestOsFeatures []*computepb.GuestOsFeature) (*computepb.Image, error) {
imagesClient, err := compute.NewImagesRESTClient(ctx, option.WithCredentials(g.creds))
if err != nil {
return nil, fmt.Errorf("failed to get Compute Engine Images client: %v", err)
}
defer imagesClient.Close()
operationsClient, err := compute.NewGlobalOperationsRESTClient(ctx, option.WithCredentials(g.creds))
if err != nil {
return nil, fmt.Errorf("failed to get Compute Engine Operations client: %v", err)
}
defer operationsClient.Close()
imgInsertReq := &computepb.InsertImageRequest{
Project: g.GetProjectID(),
ImageResource: &computepb.Image{
Name: &imageName,
StorageLocations: regions,
GuestOsFeatures: guestOsFeatures,
RawDisk: &computepb.RawDisk{
ContainerType: common.ToPtr(computepb.RawDisk_TAR.String()),
Source: common.ToPtr(fmt.Sprintf("https://storage.googleapis.com/%s/%s", bucket, object)),
},
},
}
operation, err := imagesClient.Insert(ctx, imgInsertReq)
if err != nil {
return nil, fmt.Errorf("failed to insert provided image into GCE: %v", err)
}
// wait for the operation to finish
var operationResource *computepb.Operation
for {
waitOperationReq := &computepb.WaitGlobalOperationRequest{
Operation: operation.Proto().GetName(),
Project: g.GetProjectID(),
}
operationResource, err = operationsClient.Wait(ctx, waitOperationReq)
if err != nil {
return nil, fmt.Errorf("failed to wait for an Image Import operation: %v", err)
}
// The operation finished
if operationResource.GetStatus() != computepb.Operation_RUNNING && operationResource.GetStatus() != computepb.Operation_PENDING {
break
}
}
// If the operation failed, the HttpErrorStatusCode is set to a non-zero value
if operationStatusCode := operationResource.GetHttpErrorStatusCode(); operationStatusCode != 0 {
operationErrorMsg := operationResource.GetHttpErrorMessage()
operationErrors := operationResource.GetError().GetErrors()
return nil, fmt.Errorf("failed to insert image into GCE. HTTPErrorCode:%d HTTPErrorMsg:%v Errors:%v", operationStatusCode, operationErrorMsg, operationErrors)
}
getImageReq := &computepb.GetImageRequest{
Image: imageName,
Project: g.GetProjectID(),
}
image, err := imagesClient.Get(ctx, getImageReq)
if err != nil {
return nil, fmt.Errorf("failed to get information about the imported Image: %v", err)
}
return image, nil
}
// ComputeImageURL returns an image's URL to Google Cloud Console. The method does
// not check at all, if the image actually exists or not.
func (g *GCP) ComputeImageURL(imageName string) string {
return fmt.Sprintf("https://console.cloud.google.com/compute/imagesDetail/projects/%s/global/images/%s", g.GetProjectID(), imageName)
}
// ComputeImageShare shares the specified Compute Engine image with list of accounts.
//
// "shareWith" is a list of accounts to share the image with. Items can be one
// of the following options:
//
// - `user:{emailid}`: An email address that represents a specific
// Google account. For example, `alice@example.com`.
//
// - `serviceAccount:{emailid}`: An email address that represents a
// service account. For example, `my-other-app@appspot.gserviceaccount.com`.
//
// - `group:{emailid}`: An email address that represents a Google group.
// For example, `admins@example.com`.
//
// - `domain:{domain}`: The G Suite domain (primary) that represents all
// the users of that domain. For example, `google.com` or `example.com`.
//
// Uses:
// - Compute Engine API
func (g *GCP) ComputeImageShare(ctx context.Context, imageName string, shareWith []string) error {
imagesClient, err := compute.NewImagesRESTClient(ctx, option.WithCredentials(g.creds))
if err != nil {
return fmt.Errorf("failed to get Compute Engine Images client: %v", err)
}
defer imagesClient.Close()
// Standard role to enable account to view and use a specific Image
imageDesiredRole := "roles/compute.imageUser"
// Get the current Policy set on the Image
getIamPolicyReq := &computepb.GetIamPolicyImageRequest{
Project: g.GetProjectID(),
Resource: imageName,
}
policy, err := imagesClient.GetIamPolicy(ctx, getIamPolicyReq)
if err != nil {
return fmt.Errorf("failed to get image's policy: %v", err)
}
// Add new members, who can use the image
// Completely override the old policy
userBinding := &computepb.Binding{
Members: shareWith,
Role: common.ToPtr(imageDesiredRole),
}
newPolicy := &computepb.Policy{
Bindings: []*computepb.Binding{userBinding},
Etag: policy.Etag,
}
setIamPolicyReq := &computepb.SetIamPolicyImageRequest{
Project: g.GetProjectID(),
Resource: imageName,
GlobalSetPolicyRequestResource: &computepb.GlobalSetPolicyRequest{
Policy: newPolicy,
},
}
_, err = imagesClient.SetIamPolicy(ctx, setIamPolicyReq)
if err != nil {
return fmt.Errorf("failed to set new image policy: %v", err)
}
// Users won't see the shared image in their images.list requests, unless
// they are also granted a specific "imagesList" role on the project. If you
// don't need users to be able to view the list of shared images, this
// step can be skipped.
//
// Downside of granting the "imagesList" role to a project is that the user
// will be able to list all available images in the project, even those that
// they can't use because of insufficient permissions.
//
// Even without the ability to view / list shared images, the user can still
// create a Compute Engine instance using the image via API or 'gcloud' tool.
//
// Custom role to enable account to only list images in the project.
// Without this role, the account won't be able to list and see the image
// in the GCP Web UI.
// For now, the decision is that the account should not get any role to the
// project, where the image has been imported.
return nil
}
// ComputeImageDelete deletes a Compute Engine image with the given name. If the
// image existed and was successfully deleted, no error is returned.
//
// Uses:
// - Compute Engine API
func (g *GCP) ComputeImageDelete(ctx context.Context, name string) error {
imagesClient, err := compute.NewImagesRESTClient(ctx, option.WithCredentials(g.creds))
if err != nil {
return fmt.Errorf("failed to get Compute Engine Images client: %v", err)
}
defer imagesClient.Close()
req := &computepb.DeleteImageRequest{
Project: g.GetProjectID(),
Image: name,
}
_, err = imagesClient.Delete(ctx, req)
return err
}
// ComputeExecuteFunctionForImages will pass all the compute images in the account to a function,
// which is able to iterate over the images. Useful if something needs to be execute for each image.
// Uses:
// - Compute Engine API
func (g *GCP) ComputeExecuteFunctionForImages(ctx context.Context, f func(*compute.ImageIterator) error) error {
imagesClient, err := compute.NewImagesRESTClient(ctx, option.WithCredentials(g.creds))
if err != nil {
return fmt.Errorf("failed to get Compute Engine Images client: %v", err)
}
defer imagesClient.Close()
req := &computepb.ListImagesRequest{
Project: g.GetProjectID(),
}
imagesIterator := imagesClient.List(ctx, req)
return f(imagesIterator)
}