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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
|
// Copyright 2016 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// Package gce provides wrappers around Google Compute Engine (GCE) APIs.
// It is assumed that the program itself also runs on GCE as APIs operate on the current project/zone.
//
// See https://cloud.google.com/compute/docs for details.
// In particular, API reference:
// https://cloud.google.com/compute/docs/reference/latest
// and Go API wrappers:
// https://godoc.org/google.golang.org/api/compute/v1
package gce
import (
"context"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"regexp"
"strings"
"time"
"github.com/google/syzkaller/sys/targets"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)
type Context struct {
ProjectID string
ZoneID string
RegionID string
Instance string
InternalIP string
ExternalIP string
Network string
Subnetwork string
computeService *compute.Service
// apiCallTicker ticks regularly, preventing us from accidentally making
// GCE API calls too quickly. Our quota is 20 QPS, but we limit ourselves
// to less than that because several independent programs can do API calls.
apiRateGate <-chan time.Time
}
type CreateArgs struct {
Preemptible bool
DisplayDevice bool
}
func NewContext(customZoneID string) (*Context, error) {
ctx := &Context{
apiRateGate: time.NewTicker(time.Second).C,
}
background := context.Background()
tokenSource, err := google.DefaultTokenSource(background, compute.CloudPlatformScope)
if err != nil {
return nil, fmt.Errorf("failed to get a token source: %w", err)
}
httpClient := oauth2.NewClient(background, tokenSource)
ctx.computeService, err = compute.NewService(background, option.WithHTTPClient(httpClient))
if err != nil {
return nil, fmt.Errorf("failed to create compute service: %w", err)
}
// Obtain project name, zone and current instance IP address.
ctx.ProjectID, err = ctx.getMeta("project/project-id")
if err != nil {
return nil, fmt.Errorf("failed to query gce project-id: %w", err)
}
myZoneID, err := ctx.getMeta("instance/zone")
if err != nil {
return nil, fmt.Errorf("failed to query gce zone: %w", err)
}
if i := strings.LastIndexByte(myZoneID, '/'); i != -1 {
myZoneID = myZoneID[i+1:] // the query returns some nonsense prefix
}
if customZoneID != "" {
ctx.ZoneID = customZoneID
} else {
ctx.ZoneID = myZoneID
}
if !validateZone(ctx.ZoneID) {
return nil, fmt.Errorf("%q is not a valid zone name", ctx.ZoneID)
}
ctx.RegionID = zoneToRegion(ctx.ZoneID)
if ctx.RegionID == "" {
return nil, fmt.Errorf("failed to extract region id from %s", ctx.ZoneID)
}
ctx.Instance, err = ctx.getMeta("instance/name")
if err != nil {
return nil, fmt.Errorf("failed to query gce instance name: %w", err)
}
inst, err := ctx.computeService.Instances.Get(ctx.ProjectID, myZoneID, ctx.Instance).Do()
if err != nil {
return nil, fmt.Errorf("error getting instance info: %w", err)
}
for _, iface := range inst.NetworkInterfaces {
if strings.HasPrefix(iface.NetworkIP, "10.") {
ctx.InternalIP = iface.NetworkIP
}
for _, ac := range iface.AccessConfigs {
if ac.NatIP != "" {
ctx.ExternalIP = ac.NatIP
}
}
ctx.Network = iface.Network
ctx.Subnetwork = iface.Subnetwork
}
if ctx.InternalIP == "" {
return nil, fmt.Errorf("failed to get current instance internal IP")
}
return ctx, nil
}
func (ctx *Context) CreateInstance(name, machineType, image, sshkey string,
preemptible, displayDevice bool) (string, error) {
prefix := "https://www.googleapis.com/compute/v1/projects/" + ctx.ProjectID
sshkeyAttr := "syzkaller:" + sshkey
oneAttr := "1"
falseAttr := false
instance := &compute.Instance{
Name: name,
Description: "syzkaller worker",
MachineType: prefix + "/zones/" + ctx.ZoneID + "/machineTypes/" + machineType,
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
DiskSizeGb: int64(diskSizeGB(machineType)),
InitializeParams: &compute.AttachedDiskInitializeParams{
DiskName: name,
SourceImage: prefix + "/global/images/" + image,
},
},
},
Metadata: &compute.Metadata{
Items: []*compute.MetadataItems{
{
Key: "ssh-keys",
Value: &sshkeyAttr,
},
{
Key: "serial-port-enable",
Value: &oneAttr,
},
},
},
NetworkInterfaces: []*compute.NetworkInterface{
{
Network: ctx.Network,
Subnetwork: ctx.Subnetwork,
},
},
Scheduling: &compute.Scheduling{
AutomaticRestart: &falseAttr,
Preemptible: preemptible,
OnHostMaintenance: "TERMINATE",
},
DisplayDevice: &compute.DisplayDevice{
EnableDisplay: displayDevice,
},
}
retry:
if !instance.Scheduling.Preemptible && strings.HasPrefix(machineType, "e2-") {
// Otherwise we get "Error 400: Efficient instances do not support
// onHostMaintenance=TERMINATE unless they are preemptible".
instance.Scheduling.OnHostMaintenance = "MIGRATE"
}
var op *compute.Operation
err := ctx.apiCall(func() (err error) {
op, err = ctx.computeService.Instances.Insert(ctx.ProjectID, ctx.ZoneID, instance).Do()
return
})
if err != nil {
return "", fmt.Errorf("failed to create instance: %w", err)
}
if err := ctx.waitForCompletion("zone", "create instance", op.Name, false); err != nil {
var resourcePoolExhaustedError resourcePoolExhaustedError
if errors.As(err, &resourcePoolExhaustedError) && instance.Scheduling.Preemptible {
instance.Scheduling.Preemptible = false
goto retry
}
return "", err
}
var inst *compute.Instance
err = ctx.apiCall(func() (err error) {
inst, err = ctx.computeService.Instances.Get(ctx.ProjectID, ctx.ZoneID, name).Do()
return
})
if err != nil {
return "", fmt.Errorf("error getting instance %s details after creation: %w", name, err)
}
// Finds its internal IP.
ip := ""
for _, iface := range inst.NetworkInterfaces {
if strings.HasPrefix(iface.NetworkIP, "10.") {
ip = iface.NetworkIP
break
}
}
if ip == "" {
return "", fmt.Errorf("didn't find instance internal IP address")
}
return ip, nil
}
func diskSizeGB(machineType string) int {
if strings.HasPrefix(machineType, "c4a-") {
// For C4A machines, the only available disk type is "Hyperdisk Balanced",
// which must be >= 10GB.
return 10
}
// Use the default value.
return 0
}
func (ctx *Context) DeleteInstance(name string, wait bool) error {
var op *compute.Operation
err := ctx.apiCall(func() (err error) {
op, err = ctx.computeService.Instances.Delete(ctx.ProjectID, ctx.ZoneID, name).Do()
return
})
var apiErr *googleapi.Error
if errors.As(err, &apiErr) && apiErr.Code == 404 {
return nil
}
if err != nil {
return fmt.Errorf("failed to delete instance: %w", err)
}
if wait {
if err := ctx.waitForCompletion("zone", "delete image", op.Name, true); err != nil {
return err
}
}
return nil
}
func (ctx *Context) IsInstanceRunning(name string) bool {
var inst *compute.Instance
err := ctx.apiCall(func() (err error) {
inst, err = ctx.computeService.Instances.Get(ctx.ProjectID, ctx.ZoneID, name).Do()
return
})
if err != nil {
return false
}
return inst.Status == "RUNNING"
}
func (ctx *Context) CreateImage(imageName, gcsFile, OS string) error {
var features []*compute.GuestOsFeature
if OS == targets.Linux {
features = []*compute.GuestOsFeature{
{
Type: "GVNIC",
},
}
}
image := &compute.Image{
Name: imageName,
RawDisk: &compute.ImageRawDisk{
Source: "https://storage.googleapis.com/" + gcsFile,
},
Licenses: []string{
"https://www.googleapis.com/compute/v1/projects/vm-options/global/licenses/enable-vmx",
},
GuestOsFeatures: features,
}
var op *compute.Operation
err := ctx.apiCall(func() (err error) {
op, err = ctx.computeService.Images.Insert(ctx.ProjectID, image).Do()
return
})
if err != nil {
// Try again without the vmx license in case it is not supported.
image.Licenses = nil
err := ctx.apiCall(func() (err error) {
op, err = ctx.computeService.Images.Insert(ctx.ProjectID, image).Do()
return
})
if err != nil {
return fmt.Errorf("failed to create image: %w", err)
}
}
if err := ctx.waitForCompletion("global", "create image", op.Name, false); err != nil {
return err
}
return nil
}
func (ctx *Context) DeleteImage(imageName string) error {
var op *compute.Operation
err := ctx.apiCall(func() (err error) {
op, err = ctx.computeService.Images.Delete(ctx.ProjectID, imageName).Do()
return
})
var apiErr *googleapi.Error
if errors.As(err, &apiErr) && apiErr.Code == 404 {
return nil
}
if err != nil {
return fmt.Errorf("failed to delete image: %w", err)
}
if err := ctx.waitForCompletion("global", "delete image", op.Name, true); err != nil {
return err
}
return nil
}
type resourcePoolExhaustedError string
func (err resourcePoolExhaustedError) Error() string {
return string(err)
}
func (ctx *Context) waitForCompletion(typ, desc, opName string, ignoreNotFound bool) error {
time.Sleep(3 * time.Second)
for {
time.Sleep(3 * time.Second)
var op *compute.Operation
err := ctx.apiCall(func() (err error) {
switch typ {
case "global":
op, err = ctx.computeService.GlobalOperations.Get(ctx.ProjectID, opName).Do()
case "zone":
op, err = ctx.computeService.ZoneOperations.Get(ctx.ProjectID, ctx.ZoneID, opName).Do()
default:
panic("unknown operation type: " + typ)
}
return
})
if err != nil {
return fmt.Errorf("failed to get %v operation %v: %w", desc, opName, err)
}
switch op.Status {
case "PENDING", "RUNNING":
continue
case "DONE":
if op.Error != nil {
reason := ""
for _, operr := range op.Error.Errors {
if operr.Code == "ZONE_RESOURCE_POOL_EXHAUSTED" ||
operr.Code == "ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS" {
return resourcePoolExhaustedError(fmt.Sprintf("%+v", operr))
}
if ignoreNotFound && operr.Code == "RESOURCE_NOT_FOUND" {
return nil
}
reason += fmt.Sprintf("%+v.", operr)
}
return fmt.Errorf("%v operation failed: %v", desc, reason)
}
return nil
default:
return fmt.Errorf("unknown %v operation status %q: %+v", desc, op.Status, op)
}
}
}
func (ctx *Context) getMeta(path string) (string, error) {
req, err := http.NewRequest("GET", "http://metadata.google.internal/computeMetadata/v1/"+path, nil)
if err != nil {
return "", err
}
req.Header.Add("Metadata-Flavor", "Google")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func (ctx *Context) apiCall(fn func() error) error {
rateLimited := 0
for {
<-ctx.apiRateGate
err := fn()
if err != nil {
if strings.Contains(err.Error(), "Rate Limit Exceeded") ||
strings.Contains(err.Error(), "rateLimitExceeded") {
rateLimited++
backoff := time.Duration(float64(rateLimited) * 1e9 * (rand.Float64() + 1))
time.Sleep(backoff)
if rateLimited < 20 {
continue
}
}
}
return err
}
}
var zoneNameRe = regexp.MustCompile("^[a-zA-Z0-9]*-[a-zA-Z0-9]*[-][a-zA-Z0-9]*$")
func validateZone(zone string) bool {
return zoneNameRe.MatchString(zone)
}
var regionNameRe = regexp.MustCompile("^[a-zA-Z0-9]*-[a-zA-Z0-9]*")
func zoneToRegion(zone string) string {
return regionNameRe.FindString(zone)
}
|