blob: cd0ff657ab725f6006b8b91c2d00beb5946ff428 [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
39from acloud.public import avd
40from acloud.public import errors
41from 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
52ALL_SCOPES = " ".join([android_build_client.AndroidBuildClient.SCOPE,
53 gstorage_client.StorageClient.SCOPE,
54 android_compute_client.AndroidComputeClient.SCOPE])
55
56MAX_BATCH_CLEANUP_COUNT = 100
57
cylan66713722018-10-06 01:38:26 +080058#For gce_x86_phones remote instances: adb port is 5555 and vnc is 6444.
59_TARGET_VNC_PORT = 6444
60_TARGET_ADB_PORT = 5555
61_SSH_USER = "root"
Kevin Chengb5963882018-05-09 00:06:27 -070062
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070063
Kevin Cheng5c124ec2018-05-16 13:28:51 -070064# pylint: disable=invalid-name
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070065class AndroidVirtualDevicePool(object):
66 """A class that manages a pool of devices."""
67
68 def __init__(self, cfg, devices=None):
69 self._devices = devices or []
70 self._cfg = cfg
71 credentials = auth.CreateCredentials(cfg, ALL_SCOPES)
72 self._build_client = android_build_client.AndroidBuildClient(
73 credentials)
74 self._storage_client = gstorage_client.StorageClient(credentials)
75 self._compute_client = android_compute_client.AndroidComputeClient(
76 cfg, credentials)
77
78 def _CreateGceImageWithBuildInfo(self, build_target, build_id):
79 """Creates a Gce image using build from Launch Control.
80
81 Clone avd-system.tar.gz of a build to a cache storage bucket
82 using launch control api. And then create a Gce image.
83
84 Args:
Kevin Chengb5963882018-05-09 00:06:27 -070085 build_target: Target name, e.g. "aosp_cf_x86_phone-userdebug"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070086 build_id: Build id, a string, e.g. "2263051", "P2804227"
87
88 Returns:
89 String, name of the Gce image that has been created.
90 """
91 logger.info("Creating a new gce image using build: build_id %s, "
92 "build_target %s", build_id, build_target)
93 disk_image_id = utils.GenerateUniqueName(
94 suffix=self._cfg.disk_image_name)
95 self._build_client.CopyTo(
96 build_target,
97 build_id,
98 artifact_name=self._cfg.disk_image_name,
99 destination_bucket=self._cfg.storage_bucket_name,
100 destination_path=disk_image_id)
101 disk_image_url = self._storage_client.GetUrl(
102 self._cfg.storage_bucket_name, disk_image_id)
103 try:
104 image_name = self._compute_client.GenerateImageName(build_target,
105 build_id)
106 self._compute_client.CreateImage(image_name=image_name,
107 source_uri=disk_image_url)
108 finally:
109 self._storage_client.Delete(self._cfg.storage_bucket_name,
110 disk_image_id)
111 return image_name
112
113 def _CreateGceImageWithLocalFile(self, local_disk_image):
114 """Create a Gce image with a local image file.
115
116 The local disk image can be either a tar.gz file or a
117 raw vmlinux image.
118 e.g. /tmp/avd-system.tar.gz or /tmp/android_system_disk_syslinux.img
119 If a raw vmlinux image is provided, it will be archived into a tar.gz file.
120
121 The final tar.gz file will be uploaded to a cache bucket in storage.
122
123 Args:
124 local_disk_image: string, path to a local disk image,
125
126 Returns:
127 String, name of the Gce image that has been created.
128
129 Raises:
130 DriverError: if a file with an unexpected extension is given.
131 """
132 logger.info("Creating a new gce image from a local file %s",
133 local_disk_image)
134 with utils.TempDir() as tempdir:
135 if local_disk_image.endswith(self._cfg.disk_raw_image_extension):
136 dest_tar_file = os.path.join(tempdir,
137 self._cfg.disk_image_name)
138 utils.MakeTarFile(
139 src_dict={local_disk_image: self._cfg.disk_raw_image_name},
140 dest=dest_tar_file)
141 local_disk_image = dest_tar_file
142 elif not local_disk_image.endswith(self._cfg.disk_image_extension):
143 raise errors.DriverError(
144 "Wrong local_disk_image type, must be a *%s file or *%s file"
145 % (self._cfg.disk_raw_image_extension,
146 self._cfg.disk_image_extension))
147
148 disk_image_id = utils.GenerateUniqueName(
149 suffix=self._cfg.disk_image_name)
150 self._storage_client.Upload(
151 local_src=local_disk_image,
152 bucket_name=self._cfg.storage_bucket_name,
153 object_name=disk_image_id,
154 mime_type=self._cfg.disk_image_mime_type)
155 disk_image_url = self._storage_client.GetUrl(
156 self._cfg.storage_bucket_name, disk_image_id)
157 try:
158 image_name = self._compute_client.GenerateImageName()
159 self._compute_client.CreateImage(image_name=image_name,
160 source_uri=disk_image_url)
161 finally:
162 self._storage_client.Delete(self._cfg.storage_bucket_name,
163 disk_image_id)
164 return image_name
165
166 def CreateDevices(self,
167 num,
168 build_target=None,
169 build_id=None,
170 gce_image=None,
171 local_disk_image=None,
172 cleanup=True,
173 extra_data_disk_size_gb=None,
174 precreated_data_image=None):
175 """Creates |num| devices for given build_target and build_id.
176
177 - If gce_image is provided, will use it to create an instance.
178 - If local_disk_image is provided, will upload it to a temporary
179 caching storage bucket which is defined by user as |storage_bucket_name|
180 And then create an gce image with it; and then create an instance.
181 - If build_target and build_id are provided, will clone the disk image
182 via launch control to the temporary caching storage bucket.
183 And then create an gce image with it; and then create an instance.
184
185 Args:
186 num: Number of devices to create.
Kevin Chengb5963882018-05-09 00:06:27 -0700187 build_target: Target name, e.g. "aosp_cf_x86_phone-userdebug"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700188 build_id: Build id, a string, e.g. "2263051", "P2804227"
189 gce_image: string, if given, will use this image
190 instead of creating a new one.
191 implies cleanup=False.
192 local_disk_image: string, path to a local disk image, e.g.
193 /tmp/avd-system.tar.gz
194 cleanup: boolean, if True clean up compute engine image after creating
195 the instance.
196 extra_data_disk_size_gb: Integer, size of extra disk, or None.
197 precreated_data_image: A string, the image to use for the extra disk.
198
199 Raises:
200 errors.DriverError: If no source is specified for image creation.
201 """
202 if gce_image:
203 # GCE image is provided, we can directly move to instance creation.
204 logger.info("Using existing gce image %s", gce_image)
205 image_name = gce_image
206 cleanup = False
207 elif local_disk_image:
208 image_name = self._CreateGceImageWithLocalFile(local_disk_image)
209 elif build_target and build_id:
210 image_name = self._CreateGceImageWithBuildInfo(build_target,
211 build_id)
212 else:
213 raise errors.DriverError(
214 "Invalid image source, must specify one of the following: gce_image, "
215 "local_disk_image, or build_target and build id.")
216
217 # Create GCE instances.
218 try:
219 for _ in range(num):
220 instance = self._compute_client.GenerateInstanceName(
221 build_target, build_id)
222 extra_disk_name = None
223 if extra_data_disk_size_gb > 0:
224 extra_disk_name = self._compute_client.GetDataDiskName(
225 instance)
226 self._compute_client.CreateDisk(extra_disk_name,
227 precreated_data_image,
228 extra_data_disk_size_gb)
Kevin Chengb5963882018-05-09 00:06:27 -0700229 self._compute_client.CreateInstance(
230 instance=instance,
231 image_name=image_name,
232 extra_disk_name=extra_disk_name)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700233 ip = self._compute_client.GetInstanceIP(instance)
234 self.devices.append(avd.AndroidVirtualDevice(
235 ip=ip, instance_name=instance))
236 finally:
237 if cleanup:
238 self._compute_client.DeleteImage(image_name)
239
240 def DeleteDevices(self):
241 """Deletes devices.
242
243 Returns:
244 A tuple, (deleted, failed, error_msgs)
245 deleted: A list of names of instances that have been deleted.
246 faild: A list of names of instances that we fail to delete.
247 error_msgs: A list of failure messages.
248 """
249 instance_names = [device.instance_name for device in self._devices]
250 return self._compute_client.DeleteInstances(instance_names,
251 self._cfg.zone)
252
253 def WaitForBoot(self):
254 """Waits for all devices to boot up.
255
256 Returns:
257 A dictionary that contains all the failures.
258 The key is the name of the instance that fails to boot,
Kevin Chengb5963882018-05-09 00:06:27 -0700259 the value is an errors.DeviceBoottError object.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700260 """
261 failures = {}
262 for device in self._devices:
263 try:
264 self._compute_client.WaitForBoot(device.instance_name)
Kevin Chengb5963882018-05-09 00:06:27 -0700265 except errors.DeviceBootError as e:
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700266 failures[device.instance_name] = e
267 return failures
268
269 @property
270 def devices(self):
271 """Returns a list of devices in the pool.
272
273 Returns:
274 A list of devices in the pool.
275 """
276 return self._devices
277
278
279def _AddDeletionResultToReport(report_obj, deleted, failed, error_msgs,
280 resource_name):
281 """Adds deletion result to a Report object.
282
283 This function will add the following to report.data.
284 "deleted": [
285 {"name": "resource_name", "type": "resource_name"},
286 ],
287 "failed": [
288 {"name": "resource_name", "type": "resource_name"},
289 ],
290 This function will append error_msgs to report.errors.
291
292 Args:
293 report_obj: A Report object.
294 deleted: A list of names of the resources that have been deleted.
295 failed: A list of names of the resources that we fail to delete.
296 error_msgs: A list of error message strings to be added to the report.
297 resource_name: A string, representing the name of the resource.
298 """
299 for name in deleted:
300 report_obj.AddData(key="deleted",
301 value={"name": name,
302 "type": resource_name})
303 for name in failed:
304 report_obj.AddData(key="failed",
305 value={"name": name,
306 "type": resource_name})
307 report_obj.AddErrors(error_msgs)
308 if failed or error_msgs:
309 report_obj.SetStatus(report.Status.FAIL)
310
311
312def _FetchSerialLogsFromDevices(compute_client, instance_names, output_file,
313 port):
314 """Fetch serial logs from a port for a list of devices to a local file.
315
316 Args:
317 compute_client: An object of android_compute_client.AndroidComputeClient
318 instance_names: A list of instance names.
319 output_file: A path to a file ending with "tar.gz"
320 port: The number of serial port to read from, 0 for serial output, 1 for
321 logcat.
322 """
323 with utils.TempDir() as tempdir:
324 src_dict = {}
325 for instance_name in instance_names:
326 serial_log = compute_client.GetSerialPortOutput(
327 instance=instance_name, port=port)
328 file_name = "%s.log" % instance_name
329 file_path = os.path.join(tempdir, file_name)
330 src_dict[file_path] = file_name
331 with open(file_path, "w") as f:
332 f.write(serial_log.encode("utf-8"))
333 utils.MakeTarFile(src_dict, output_file)
334
335
Kevin Cheng5c124ec2018-05-16 13:28:51 -0700336# pylint: disable=too-many-locals
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700337def CreateAndroidVirtualDevices(cfg,
338 build_target=None,
339 build_id=None,
340 num=1,
341 gce_image=None,
342 local_disk_image=None,
343 cleanup=True,
344 serial_log_file=None,
Kevin Chengb5963882018-05-09 00:06:27 -0700345 logcat_file=None,
Kevin Cheng86d43c72018-08-30 10:59:14 -0700346 autoconnect=False,
347 report_internal_ip=False):
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.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700368
369 Returns:
370 A Report instance.
371 """
372 r = report.Report(command="create")
373 credentials = auth.CreateCredentials(cfg, ALL_SCOPES)
374 compute_client = android_compute_client.AndroidComputeClient(cfg,
375 credentials)
376 try:
Kevin Chengb5963882018-05-09 00:06:27 -0700377 common_operations.CreateSshKeyPairIfNecessary(cfg)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700378 device_pool = AndroidVirtualDevicePool(cfg)
379 device_pool.CreateDevices(
380 num,
381 build_target,
382 build_id,
383 gce_image,
384 local_disk_image,
385 cleanup,
386 extra_data_disk_size_gb=cfg.extra_data_disk_size_gb,
387 precreated_data_image=cfg.precreated_data_image_map.get(
388 cfg.extra_data_disk_size_gb))
389 failures = device_pool.WaitForBoot()
390 # Write result to report.
391 for device in device_pool.devices:
cylan66713722018-10-06 01:38:26 +0800392 ip = (device.ip.internal if report_internal_ip
393 else device.ip.external)
394 device_dict = {
395 "ip": ip,
396 "instance_name": device.instance_name
397 }
Kevin Chengb5963882018-05-09 00:06:27 -0700398 if autoconnect:
cylan66713722018-10-06 01:38:26 +0800399 forwarded_ports = utils.AutoConnect(ip,
400 cfg.ssh_private_key_path,
401 _TARGET_VNC_PORT,
402 _TARGET_ADB_PORT,
403 _SSH_USER)
404 device_dict[constants.VNC_PORT] = forwarded_ports.vnc_port
405 device_dict[constants.ADB_PORT] = forwarded_ports.adb_port
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700406 if device.instance_name in failures:
407 r.AddData(key="devices_failing_boot", value=device_dict)
408 r.AddError(str(failures[device.instance_name]))
409 else:
410 r.AddData(key="devices", value=device_dict)
411 if failures:
412 r.SetStatus(report.Status.BOOT_FAIL)
413 else:
414 r.SetStatus(report.Status.SUCCESS)
415
416 # Dump serial and logcat logs.
417 if serial_log_file:
Fang Dengfbef7c92017-02-08 14:09:34 -0800418 _FetchSerialLogsFromDevices(
419 compute_client,
420 instance_names=[d.instance_name for d in device_pool.devices],
421 port=constants.DEFAULT_SERIAL_PORT,
422 output_file=serial_log_file)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700423 if logcat_file:
Fang Dengfbef7c92017-02-08 14:09:34 -0800424 _FetchSerialLogsFromDevices(
425 compute_client,
426 instance_names=[d.instance_name for d in device_pool.devices],
427 port=constants.LOGCAT_SERIAL_PORT,
428 output_file=logcat_file)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700429 except errors.DriverError as e:
430 r.AddError(str(e))
431 r.SetStatus(report.Status.FAIL)
432 return r
433
434
435def DeleteAndroidVirtualDevices(cfg, instance_names):
436 """Deletes android devices.
437
438 Args:
439 cfg: An AcloudConfig instance.
440 instance_names: A list of names of the instances to delete.
441
442 Returns:
443 A Report instance.
444 """
445 r = report.Report(command="delete")
446 credentials = auth.CreateCredentials(cfg, ALL_SCOPES)
447 compute_client = android_compute_client.AndroidComputeClient(cfg,
448 credentials)
449 try:
450 deleted, failed, error_msgs = compute_client.DeleteInstances(
451 instance_names, cfg.zone)
452 _AddDeletionResultToReport(
453 r, deleted,
454 failed, error_msgs,
455 resource_name="instance")
456 if r.status == report.Status.UNKNOWN:
457 r.SetStatus(report.Status.SUCCESS)
458 except errors.DriverError as e:
459 r.AddError(str(e))
460 r.SetStatus(report.Status.FAIL)
461 return r
462
463
464def _FindOldItems(items, cut_time, time_key):
465 """Finds items from |items| whose timestamp is earlier than |cut_time|.
466
467 Args:
468 items: A list of items. Each item is a dictionary represent
469 the properties of the item. It should has a key as noted
470 by time_key.
471 cut_time: A datetime.datatime object.
472 time_key: String, key for the timestamp.
473
474 Returns:
475 A list of those from |items| whose timestamp is earlier than cut_time.
476 """
477 cleanup_list = []
478 for item in items:
479 t = dateutil.parser.parse(item[time_key])
480 if t < cut_time:
481 cleanup_list.append(item)
482 return cleanup_list
483
484
485def Cleanup(cfg, expiration_mins):
486 """Cleans up stale gce images, gce instances, and disk images in storage.
487
488 Args:
489 cfg: An AcloudConfig instance.
490 expiration_mins: Integer, resources older than |expiration_mins| will
491 be cleaned up.
492
493 Returns:
494 A Report instance.
495 """
496 r = report.Report(command="cleanup")
497 try:
498 cut_time = (datetime.datetime.now(dateutil.tz.tzlocal()) -
499 datetime.timedelta(minutes=expiration_mins))
500 logger.info(
501 "Cleaning up any gce images/instances and cached build artifacts."
502 "in google storage that are older than %s", cut_time)
503 credentials = auth.CreateCredentials(cfg, ALL_SCOPES)
504 compute_client = android_compute_client.AndroidComputeClient(
505 cfg, credentials)
506 storage_client = gstorage_client.StorageClient(credentials)
507
508 # Cleanup expired instances
509 items = compute_client.ListInstances(zone=cfg.zone)
510 cleanup_list = [
511 item["name"]
512 for item in _FindOldItems(items, cut_time, "creationTimestamp")
513 ]
514 logger.info("Found expired instances: %s", cleanup_list)
515 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
516 result = compute_client.DeleteInstances(
517 instances=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT],
518 zone=cfg.zone)
519 _AddDeletionResultToReport(r, *result, resource_name="instance")
520
521 # Cleanup expired images
522 items = compute_client.ListImages()
523 skip_list = cfg.precreated_data_image_map.viewvalues()
524 cleanup_list = [
525 item["name"]
526 for item in _FindOldItems(items, cut_time, "creationTimestamp")
527 if item["name"] not in skip_list
528 ]
529 logger.info("Found expired images: %s", cleanup_list)
530 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
531 result = compute_client.DeleteImages(
532 image_names=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT])
533 _AddDeletionResultToReport(r, *result, resource_name="image")
534
535 # Cleanup expired disks
536 # Disks should have been attached to instances with autoDelete=True.
537 # However, sometimes disks may not be auto deleted successfully.
538 items = compute_client.ListDisks(zone=cfg.zone)
539 cleanup_list = [
540 item["name"]
541 for item in _FindOldItems(items, cut_time, "creationTimestamp")
542 if not item.get("users")
543 ]
544 logger.info("Found expired disks: %s", cleanup_list)
545 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
546 result = compute_client.DeleteDisks(
547 disk_names=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT],
548 zone=cfg.zone)
549 _AddDeletionResultToReport(r, *result, resource_name="disk")
550
551 # Cleanup expired google storage
552 items = storage_client.List(bucket_name=cfg.storage_bucket_name)
553 cleanup_list = [
554 item["name"]
555 for item in _FindOldItems(items, cut_time, "timeCreated")
556 ]
557 logger.info("Found expired cached artifacts: %s", cleanup_list)
558 for i in range(0, len(cleanup_list), MAX_BATCH_CLEANUP_COUNT):
559 result = storage_client.DeleteFiles(
560 bucket_name=cfg.storage_bucket_name,
561 object_names=cleanup_list[i:i + MAX_BATCH_CLEANUP_COUNT])
562 _AddDeletionResultToReport(
563 r, *result, resource_name="cached_build_artifact")
564
565 # Everything succeeded, write status to report.
566 if r.status == report.Status.UNKNOWN:
567 r.SetStatus(report.Status.SUCCESS)
568 except errors.DriverError as e:
569 r.AddError(str(e))
570 r.SetStatus(report.Status.FAIL)
571 return r
572
573
574def AddSshRsa(cfg, user, ssh_rsa_path):
575 """Add public ssh rsa key to the project.
576
577 Args:
578 cfg: An AcloudConfig instance.
579 user: the name of the user which the key belongs to.
580 ssh_rsa_path: The absolute path to public rsa key.
581
582 Returns:
583 A Report instance.
584 """
585 r = report.Report(command="sshkey")
586 try:
587 credentials = auth.CreateCredentials(cfg, ALL_SCOPES)
588 compute_client = android_compute_client.AndroidComputeClient(
589 cfg, credentials)
590 compute_client.AddSshRsa(user, ssh_rsa_path)
591 r.SetStatus(report.Status.SUCCESS)
592 except errors.DriverError as e:
593 r.AddError(str(e))
594 r.SetStatus(report.Status.FAIL)
595 return r
Fang Dengcef4b112017-03-02 11:20:17 -0800596
597
598def CheckAccess(cfg):
599 """Check if user has access.
600
601 Args:
602 cfg: An AcloudConfig instance.
603 """
604 credentials = auth.CreateCredentials(cfg, ALL_SCOPES)
605 compute_client = android_compute_client.AndroidComputeClient(
Kevin Cheng5c124ec2018-05-16 13:28:51 -0700606 cfg, credentials)
Fang Dengcef4b112017-03-02 11:20:17 -0800607 logger.info("Checking if user has access to project %s", cfg.project)
608 if not compute_client.CheckAccess():
609 logger.error("User does not have access to project %s", cfg.project)
610 # Print here so that command line user can see it.
Kevin Chengd9d5f0f2018-06-19 14:54:17 -0700611 print("Looks like you do not have access to %s. " % cfg.project)
Fang Dengcef4b112017-03-02 11:20:17 -0800612 if cfg.project in cfg.no_project_access_msg_map:
Kevin Chengd9d5f0f2018-06-19 14:54:17 -0700613 print(cfg.no_project_access_msg_map[cfg.project])