blob: 46339be504a44599dfea3c8230ec97ba347bbb8f [file] [log] [blame]
Keun Soo Yimb293fdb2016-09-21 16:03:44 -07001#!/usr/bin/env python
2#
3# Copyright 2016 - The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Public Device Driver APIs.
18
19This module provides public device driver APIs that can be called
20as a Python library.
21
Kevin Chengb5963882018-05-09 00:06:27 -070022TODO: The following APIs have not been implemented
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070023 - RebootAVD(ip):
24 - RegisterSshPubKey(username, key):
25 - UnregisterSshPubKey(username, key):
26 - CleanupStaleImages():
27 - CleanupStaleDevices():
28"""
29
Kevin Chengd9d5f0f2018-06-19 14:54:17 -070030from __future__ import print_function
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070031import datetime
32import logging
33import os
34
Kevin Chengd9d5f0f2018-06-19 14:54:17 -070035# pylint: disable=import-error
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070036import dateutil.parser
37import dateutil.tz
38
Sam Chiu7de3b232018-12-06 19:45:52 +080039from acloud import errors
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070040from acloud.public import avd
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070041from acloud.public import report
Kevin Chengb5963882018-05-09 00:06:27 -070042from acloud.public.actions import common_operations
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070043from acloud.internal import constants
44from acloud.internal.lib import auth
45from acloud.internal.lib import android_build_client
46from acloud.internal.lib import android_compute_client
47from acloud.internal.lib import gstorage_client
48from acloud.internal.lib import utils
49
50logger = logging.getLogger(__name__)
51
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070052MAX_BATCH_CLEANUP_COUNT = 100
53
cylan66713722018-10-06 01:38:26 +080054_SSH_USER = "root"
Kevin Chengb5963882018-05-09 00:06:27 -070055
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070056
Kevin Cheng5c124ec2018-05-16 13:28:51 -070057# pylint: disable=invalid-name
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070058class AndroidVirtualDevicePool(object):
59 """A class that manages a pool of devices."""
60
61 def __init__(self, cfg, devices=None):
62 self._devices = devices or []
63 self._cfg = cfg
Sam Chiu4d9bb4b2018-10-26 11:38:23 +080064 credentials = auth.CreateCredentials(cfg)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070065 self._build_client = android_build_client.AndroidBuildClient(
66 credentials)
67 self._storage_client = gstorage_client.StorageClient(credentials)
68 self._compute_client = android_compute_client.AndroidComputeClient(
69 cfg, credentials)
70
chojoyce7a361732018-11-26 16:26:13 +080071 @utils.TimeExecute("Creating GCE image")
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070072 def _CreateGceImageWithBuildInfo(self, build_target, build_id):
73 """Creates a Gce image using build from Launch Control.
74
75 Clone avd-system.tar.gz of a build to a cache storage bucket
76 using launch control api. And then create a Gce image.
77
78 Args:
Kevin Chengb5963882018-05-09 00:06:27 -070079 build_target: Target name, e.g. "aosp_cf_x86_phone-userdebug"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070080 build_id: Build id, a string, e.g. "2263051", "P2804227"
81
82 Returns:
83 String, name of the Gce image that has been created.
84 """
85 logger.info("Creating a new gce image using build: build_id %s, "
86 "build_target %s", build_id, build_target)
87 disk_image_id = utils.GenerateUniqueName(
88 suffix=self._cfg.disk_image_name)
89 self._build_client.CopyTo(
90 build_target,
91 build_id,
92 artifact_name=self._cfg.disk_image_name,
93 destination_bucket=self._cfg.storage_bucket_name,
94 destination_path=disk_image_id)
95 disk_image_url = self._storage_client.GetUrl(
96 self._cfg.storage_bucket_name, disk_image_id)
97 try:
98 image_name = self._compute_client.GenerateImageName(build_target,
99 build_id)
100 self._compute_client.CreateImage(image_name=image_name,
101 source_uri=disk_image_url)
102 finally:
103 self._storage_client.Delete(self._cfg.storage_bucket_name,
104 disk_image_id)
105 return image_name
106
chojoyce7a361732018-11-26 16:26:13 +0800107 @utils.TimeExecute("Creating GCE image")
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700108 def _CreateGceImageWithLocalFile(self, local_disk_image):
109 """Create a Gce image with a local image file.
110
111 The local disk image can be either a tar.gz file or a
112 raw vmlinux image.
113 e.g. /tmp/avd-system.tar.gz or /tmp/android_system_disk_syslinux.img
114 If a raw vmlinux image is provided, it will be archived into a tar.gz file.
115
116 The final tar.gz file will be uploaded to a cache bucket in storage.
117
118 Args:
119 local_disk_image: string, path to a local disk image,
120
121 Returns:
122 String, name of the Gce image that has been created.
123
124 Raises:
125 DriverError: if a file with an unexpected extension is given.
126 """
127 logger.info("Creating a new gce image from a local file %s",
128 local_disk_image)
129 with utils.TempDir() as tempdir:
130 if local_disk_image.endswith(self._cfg.disk_raw_image_extension):
131 dest_tar_file = os.path.join(tempdir,
132 self._cfg.disk_image_name)
133 utils.MakeTarFile(
134 src_dict={local_disk_image: self._cfg.disk_raw_image_name},
135 dest=dest_tar_file)
136 local_disk_image = dest_tar_file
137 elif not local_disk_image.endswith(self._cfg.disk_image_extension):
138 raise errors.DriverError(
139 "Wrong local_disk_image type, must be a *%s file or *%s file"
140 % (self._cfg.disk_raw_image_extension,
141 self._cfg.disk_image_extension))
142
143 disk_image_id = utils.GenerateUniqueName(
144 suffix=self._cfg.disk_image_name)
145 self._storage_client.Upload(
146 local_src=local_disk_image,
147 bucket_name=self._cfg.storage_bucket_name,
148 object_name=disk_image_id,
149 mime_type=self._cfg.disk_image_mime_type)
150 disk_image_url = self._storage_client.GetUrl(
151 self._cfg.storage_bucket_name, disk_image_id)
152 try:
153 image_name = self._compute_client.GenerateImageName()
154 self._compute_client.CreateImage(image_name=image_name,
155 source_uri=disk_image_url)
156 finally:
157 self._storage_client.Delete(self._cfg.storage_bucket_name,
158 disk_image_id)
159 return image_name
160
161 def CreateDevices(self,
162 num,
163 build_target=None,
164 build_id=None,
165 gce_image=None,
166 local_disk_image=None,
167 cleanup=True,
168 extra_data_disk_size_gb=None,
chojoyce7a361732018-11-26 16:26:13 +0800169 precreated_data_image=None,
170 avd_spec=None):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700171 """Creates |num| devices for given build_target and build_id.
172
173 - If gce_image is provided, will use it to create an instance.
174 - If local_disk_image is provided, will upload it to a temporary
175 caching storage bucket which is defined by user as |storage_bucket_name|
176 And then create an gce image with it; and then create an instance.
177 - If build_target and build_id are provided, will clone the disk image
178 via launch control to the temporary caching storage bucket.
179 And then create an gce image with it; and then create an instance.
180
181 Args:
182 num: Number of devices to create.
Kevin Chengb5963882018-05-09 00:06:27 -0700183 build_target: Target name, e.g. "aosp_cf_x86_phone-userdebug"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700184 build_id: Build id, a string, e.g. "2263051", "P2804227"
185 gce_image: string, if given, will use this image
186 instead of creating a new one.
187 implies cleanup=False.
188 local_disk_image: string, path to a local disk image, e.g.
189 /tmp/avd-system.tar.gz
190 cleanup: boolean, if True clean up compute engine image after creating
191 the instance.
192 extra_data_disk_size_gb: Integer, size of extra disk, or None.
193 precreated_data_image: A string, the image to use for the extra disk.
chojoyce7a361732018-11-26 16:26:13 +0800194 avd_spec: AVDSpec object for pass hw_property.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700195
196 Raises:
197 errors.DriverError: If no source is specified for image creation.
198 """
199 if gce_image:
200 # GCE image is provided, we can directly move to instance creation.
201 logger.info("Using existing gce image %s", gce_image)
202 image_name = gce_image
203 cleanup = False
204 elif local_disk_image:
205 image_name = self._CreateGceImageWithLocalFile(local_disk_image)
206 elif build_target and build_id:
207 image_name = self._CreateGceImageWithBuildInfo(build_target,
208 build_id)
209 else:
210 raise errors.DriverError(
211 "Invalid image source, must specify one of the following: gce_image, "
212 "local_disk_image, or build_target and build id.")
213
214 # Create GCE instances.
215 try:
216 for _ in range(num):
217 instance = self._compute_client.GenerateInstanceName(
218 build_target, build_id)
219 extra_disk_name = None
220 if extra_data_disk_size_gb > 0:
221 extra_disk_name = self._compute_client.GetDataDiskName(
222 instance)
223 self._compute_client.CreateDisk(extra_disk_name,
224 precreated_data_image,
225 extra_data_disk_size_gb)
Kevin Chengb5963882018-05-09 00:06:27 -0700226 self._compute_client.CreateInstance(
227 instance=instance,
228 image_name=image_name,
chojoyce7a361732018-11-26 16:26:13 +0800229 extra_disk_name=extra_disk_name,
230 avd_spec=avd_spec)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700231 ip = self._compute_client.GetInstanceIP(instance)
232 self.devices.append(avd.AndroidVirtualDevice(
233 ip=ip, instance_name=instance))
234 finally:
235 if cleanup:
236 self._compute_client.DeleteImage(image_name)
237
238 def DeleteDevices(self):
239 """Deletes devices.
240
241 Returns:
242 A tuple, (deleted, failed, error_msgs)
243 deleted: A list of names of instances that have been deleted.
244 faild: A list of names of instances that we fail to delete.
245 error_msgs: A list of failure messages.
246 """
247 instance_names = [device.instance_name for device in self._devices]
248 return self._compute_client.DeleteInstances(instance_names,
249 self._cfg.zone)
250
chojoyce7a361732018-11-26 16:26:13 +0800251 @utils.TimeExecute("Waiting for AVD to boot")
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700252 def WaitForBoot(self):
253 """Waits for all devices to boot up.
254
255 Returns:
256 A dictionary that contains all the failures.
257 The key is the name of the instance that fails to boot,
Kevin Chengb5963882018-05-09 00:06:27 -0700258 the value is an errors.DeviceBoottError object.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700259 """
260 failures = {}
261 for device in self._devices:
262 try:
263 self._compute_client.WaitForBoot(device.instance_name)
Kevin Chengb5963882018-05-09 00:06:27 -0700264 except errors.DeviceBootError as e:
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700265 failures[device.instance_name] = e
266 return failures
267
268 @property
269 def devices(self):
270 """Returns a list of devices in the pool.
271
272 Returns:
273 A list of devices in the pool.
274 """
275 return self._devices
276
277
herbertxue07293a32018-11-05 20:40:11 +0800278def AddDeletionResultToReport(report_obj, deleted, failed, error_msgs,
279 resource_name):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700280 """Adds deletion result to a Report object.
281
282 This function will add the following to report.data.
283 "deleted": [
284 {"name": "resource_name", "type": "resource_name"},
285 ],
286 "failed": [
287 {"name": "resource_name", "type": "resource_name"},
288 ],
289 This function will append error_msgs to report.errors.
290
291 Args:
292 report_obj: A Report object.
293 deleted: A list of names of the resources that have been deleted.
294 failed: A list of names of the resources that we fail to delete.
295 error_msgs: A list of error message strings to be added to the report.
296 resource_name: A string, representing the name of the resource.
297 """
298 for name in deleted:
299 report_obj.AddData(key="deleted",
300 value={"name": name,
301 "type": resource_name})
302 for name in failed:
303 report_obj.AddData(key="failed",
304 value={"name": name,
305 "type": resource_name})
306 report_obj.AddErrors(error_msgs)
307 if failed or error_msgs:
308 report_obj.SetStatus(report.Status.FAIL)
309
310
311def _FetchSerialLogsFromDevices(compute_client, instance_names, output_file,
312 port):
313 """Fetch serial logs from a port for a list of devices to a local file.
314
315 Args:
316 compute_client: An object of android_compute_client.AndroidComputeClient
317 instance_names: A list of instance names.
318 output_file: A path to a file ending with "tar.gz"
319 port: The number of serial port to read from, 0 for serial output, 1 for
320 logcat.
321 """
322 with utils.TempDir() as tempdir:
323 src_dict = {}
324 for instance_name in instance_names:
325 serial_log = compute_client.GetSerialPortOutput(
326 instance=instance_name, port=port)
327 file_name = "%s.log" % instance_name
328 file_path = os.path.join(tempdir, file_name)
329 src_dict[file_path] = file_name
330 with open(file_path, "w") as f:
331 f.write(serial_log.encode("utf-8"))
332 utils.MakeTarFile(src_dict, output_file)
333
334
Kevin Cheng5c124ec2018-05-16 13:28:51 -0700335# pylint: disable=too-many-locals
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700336def CreateAndroidVirtualDevices(cfg,
337 build_target=None,
338 build_id=None,
339 num=1,
340 gce_image=None,
341 local_disk_image=None,
342 cleanup=True,
343 serial_log_file=None,
Kevin Chengb5963882018-05-09 00:06:27 -0700344 logcat_file=None,
Kevin Cheng86d43c72018-08-30 10:59:14 -0700345 autoconnect=False,
chojoyce7a361732018-11-26 16:26:13 +0800346 report_internal_ip=False,
347 avd_spec=None):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700348 """Creates one or multiple android devices.
349
350 Args:
351 cfg: An AcloudConfig instance.
Kevin Chengb5963882018-05-09 00:06:27 -0700352 build_target: Target name, e.g. "aosp_cf_x86_phone-userdebug"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700353 build_id: Build id, a string, e.g. "2263051", "P2804227"
354 num: Number of devices to create.
355 gce_image: string, if given, will use this gce image
356 instead of creating a new one.
357 implies cleanup=False.
358 local_disk_image: string, path to a local disk image, e.g.
359 /tmp/avd-system.tar.gz
360 cleanup: boolean, if True clean up compute engine image and
361 disk image in storage after creating the instance.
362 serial_log_file: A path to a file where serial output should
Fang Dengfbef7c92017-02-08 14:09:34 -0800363 be saved to.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700364 logcat_file: A path to a file where logcat logs should be saved.
Kevin Chengb5963882018-05-09 00:06:27 -0700365 autoconnect: Create ssh tunnel(s) and adb connect after device creation.
Kevin Cheng86d43c72018-08-30 10:59:14 -0700366 report_internal_ip: Boolean to report the internal ip instead of
367 external ip.
chojoyce7a361732018-11-26 16:26:13 +0800368 avd_spec: AVDSpec object for pass hw_property.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700369
370 Returns:
371 A Report instance.
372 """
373 r = report.Report(command="create")
Sam Chiu4d9bb4b2018-10-26 11:38:23 +0800374 credentials = auth.CreateCredentials(cfg)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700375 compute_client = android_compute_client.AndroidComputeClient(cfg,
376 credentials)
377 try:
Kevin Chengb5963882018-05-09 00:06:27 -0700378 common_operations.CreateSshKeyPairIfNecessary(cfg)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700379 device_pool = AndroidVirtualDevicePool(cfg)
380 device_pool.CreateDevices(
381 num,
382 build_target,
383 build_id,
384 gce_image,
385 local_disk_image,
386 cleanup,
387 extra_data_disk_size_gb=cfg.extra_data_disk_size_gb,
388 precreated_data_image=cfg.precreated_data_image_map.get(
chojoyce7a361732018-11-26 16:26:13 +0800389 cfg.extra_data_disk_size_gb),
390 avd_spec=avd_spec)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700391 failures = device_pool.WaitForBoot()
392 # Write result to report.
393 for device in device_pool.devices:
cylan66713722018-10-06 01:38:26 +0800394 ip = (device.ip.internal if report_internal_ip
395 else device.ip.external)
396 device_dict = {
397 "ip": ip,
398 "instance_name": device.instance_name
399 }
Kevin Chengb5963882018-05-09 00:06:27 -0700400 if autoconnect:
chojoyce7a361732018-11-26 16:26:13 +0800401 forwarded_ports = utils.AutoConnect(
402 ip,
403 cfg.ssh_private_key_path,
herbertxue543457e2019-03-18 18:13:34 +0800404 constants.GCE_VNC_PORT,
405 constants.GCE_ADB_PORT,
chojoyce7a361732018-11-26 16:26:13 +0800406 _SSH_USER)
cylan66713722018-10-06 01:38:26 +0800407 device_dict[constants.VNC_PORT] = forwarded_ports.vnc_port
408 device_dict[constants.ADB_PORT] = forwarded_ports.adb_port
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700409 if device.instance_name in failures:
410 r.AddData(key="devices_failing_boot", value=device_dict)
411 r.AddError(str(failures[device.instance_name]))
412 else:
413 r.AddData(key="devices", value=device_dict)
414 if failures:
415 r.SetStatus(report.Status.BOOT_FAIL)
416 else:
417 r.SetStatus(report.Status.SUCCESS)
418
419 # Dump serial and logcat logs.
420 if serial_log_file:
Fang Dengfbef7c92017-02-08 14:09:34 -0800421 _FetchSerialLogsFromDevices(
422 compute_client,
423 instance_names=[d.instance_name for d in device_pool.devices],
424 port=constants.DEFAULT_SERIAL_PORT,
425 output_file=serial_log_file)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700426 if logcat_file:
Fang Dengfbef7c92017-02-08 14:09:34 -0800427 _FetchSerialLogsFromDevices(
428 compute_client,
429 instance_names=[d.instance_name for d in device_pool.devices],
430 port=constants.LOGCAT_SERIAL_PORT,
431 output_file=logcat_file)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700432 except errors.DriverError as e:
433 r.AddError(str(e))
434 r.SetStatus(report.Status.FAIL)
435 return r
436
437
herbertxue07293a32018-11-05 20:40:11 +0800438def DeleteAndroidVirtualDevices(cfg, instance_names, default_report=None):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700439 """Deletes android devices.
440
441 Args:
442 cfg: An AcloudConfig instance.
443 instance_names: A list of names of the instances to delete.
herbertxue07293a32018-11-05 20:40:11 +0800444 default_report: A initialized Report instance.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700445
446 Returns:
447 A Report instance.
448 """
herbertxue07293a32018-11-05 20:40:11 +0800449 r = default_report if default_report else report.Report(command="delete")
Sam Chiu4d9bb4b2018-10-26 11:38:23 +0800450 credentials = auth.CreateCredentials(cfg)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700451 compute_client = android_compute_client.AndroidComputeClient(cfg,
452 credentials)
453 try:
454 deleted, failed, error_msgs = compute_client.DeleteInstances(
455 instance_names, cfg.zone)
herbertxue07293a32018-11-05 20:40:11 +0800456 AddDeletionResultToReport(
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700457 r, deleted,
458 failed, error_msgs,
459 resource_name="instance")
460 if r.status == report.Status.UNKNOWN:
461 r.SetStatus(report.Status.SUCCESS)
462 except errors.DriverError as e:
463 r.AddError(str(e))
464 r.SetStatus(report.Status.FAIL)
465 return r
466
467
468def _FindOldItems(items, cut_time, time_key):
469 """Finds items from |items| whose timestamp is earlier than |cut_time|.
470
471 Args:
472 items: A list of items. Each item is a dictionary represent
473 the properties of the item. It should has a key as noted
474 by time_key.
475 cut_time: A datetime.datatime object.
476 time_key: String, key for the timestamp.
477
478 Returns:
479 A list of those from |items| whose timestamp is earlier than cut_time.
480 """
481 cleanup_list = []
482 for item in items:
483 t = dateutil.parser.parse(item[time_key])
484 if t < cut_time:
485 cleanup_list.append(item)
486 return cleanup_list
487
488
489def Cleanup(cfg, expiration_mins):
490 """Cleans up stale gce images, gce instances, and disk images in storage.
491
492 Args:
493 cfg: An AcloudConfig instance.
494 expiration_mins: Integer, resources older than |expiration_mins| will
495 be cleaned up.
496
497 Returns:
498 A Report instance.
499 """
500 r = report.Report(command="cleanup")
501 try:
502 cut_time = (datetime.datetime.now(dateutil.tz.tzlocal()) -
503 datetime.timedelta(minutes=expiration_mins))
504 logger.info(
505 "Cleaning up any gce images/instances and cached build artifacts."
506 "in google storage that are older than %s", cut_time)
Sam Chiu4d9bb4b2018-10-26 11:38:23 +0800507 credentials = auth.CreateCredentials(cfg)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700508 compute_client = android_compute_client.AndroidComputeClient(
509 cfg, credentials)
510 storage_client = gstorage_client.StorageClient(credentials)
511
512 # Cleanup expired instances
513 items = compute_client.ListInstances(zone=cfg.zone)
514 cleanup_list = [
515 item["name"]
516 for item in _FindOldItems(items, cut_time, "creationTimestamp")
517 ]
518 logger.info("Found expired instances: %s", cleanup_list)
519 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
520 result = compute_client.DeleteInstances(
521 instances=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT],
522 zone=cfg.zone)
herbertxue07293a32018-11-05 20:40:11 +0800523 AddDeletionResultToReport(r, *result, resource_name="instance")
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700524
525 # Cleanup expired images
526 items = compute_client.ListImages()
527 skip_list = cfg.precreated_data_image_map.viewvalues()
528 cleanup_list = [
529 item["name"]
530 for item in _FindOldItems(items, cut_time, "creationTimestamp")
531 if item["name"] not in skip_list
532 ]
533 logger.info("Found expired images: %s", cleanup_list)
534 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
535 result = compute_client.DeleteImages(
536 image_names=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT])
herbertxue07293a32018-11-05 20:40:11 +0800537 AddDeletionResultToReport(r, *result, resource_name="image")
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700538
539 # Cleanup expired disks
540 # Disks should have been attached to instances with autoDelete=True.
541 # However, sometimes disks may not be auto deleted successfully.
542 items = compute_client.ListDisks(zone=cfg.zone)
543 cleanup_list = [
544 item["name"]
545 for item in _FindOldItems(items, cut_time, "creationTimestamp")
546 if not item.get("users")
547 ]
548 logger.info("Found expired disks: %s", cleanup_list)
549 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
550 result = compute_client.DeleteDisks(
551 disk_names=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT],
552 zone=cfg.zone)
herbertxue07293a32018-11-05 20:40:11 +0800553 AddDeletionResultToReport(r, *result, resource_name="disk")
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700554
555 # Cleanup expired google storage
556 items = storage_client.List(bucket_name=cfg.storage_bucket_name)
557 cleanup_list = [
558 item["name"]
559 for item in _FindOldItems(items, cut_time, "timeCreated")
560 ]
561 logger.info("Found expired cached artifacts: %s", cleanup_list)
562 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
563 result = storage_client.DeleteFiles(
564 bucket_name=cfg.storage_bucket_name,
565 object_names=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT])
herbertxue07293a32018-11-05 20:40:11 +0800566 AddDeletionResultToReport(
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700567 r, *result, resource_name="cached_build_artifact")
568
569 # Everything succeeded, write status to report.
570 if r.status == report.Status.UNKNOWN:
571 r.SetStatus(report.Status.SUCCESS)
572 except errors.DriverError as e:
573 r.AddError(str(e))
574 r.SetStatus(report.Status.FAIL)
575 return r
576
577
Fang Dengcef4b112017-03-02 11:20:17 -0800578def CheckAccess(cfg):
579 """Check if user has access.
580
581 Args:
582 cfg: An AcloudConfig instance.
583 """
Sam Chiu4d9bb4b2018-10-26 11:38:23 +0800584 credentials = auth.CreateCredentials(cfg)
Fang Dengcef4b112017-03-02 11:20:17 -0800585 compute_client = android_compute_client.AndroidComputeClient(
Kevin Cheng5c124ec2018-05-16 13:28:51 -0700586 cfg, credentials)
Fang Dengcef4b112017-03-02 11:20:17 -0800587 logger.info("Checking if user has access to project %s", cfg.project)
588 if not compute_client.CheckAccess():
589 logger.error("User does not have access to project %s", cfg.project)
590 # Print here so that command line user can see it.
Kevin Chengd9d5f0f2018-06-19 14:54:17 -0700591 print("Looks like you do not have access to %s. " % cfg.project)
Fang Dengcef4b112017-03-02 11:20:17 -0800592 if cfg.project in cfg.no_project_access_msg_map:
Kevin Chengd9d5f0f2018-06-19 14:54:17 -0700593 print(cfg.no_project_access_msg_map[cfg.project])