[Acloud] Check if user has access to the project on start
Cherry-pick cl/148795271
TEST: Manually test the google3 version. can't test the android tree
version untill b/35918788 is fixed
BUG:32411892
Change-Id: I8920db33f82d035218ef608962849628bbc8d9eb
diff --git a/internal/lib/gcompute_client.py b/internal/lib/gcompute_client.py
index 8cd32b3..05710c4 100755
--- a/internal/lib/gcompute_client.py
+++ b/internal/lib/gcompute_client.py
@@ -26,6 +26,7 @@
and it only keeps states about authentication. ComputeClient should be very
generic, and only knows how to talk to Compute Engine APIs.
"""
+import copy
import functools
import logging
import os
@@ -60,6 +61,7 @@
OPERATION_TIMEOUT_SECS = 15 * 60 # 15 mins
OPERATION_POLL_INTERVAL_SECS = 5
MACHINE_SIZE_METRICS = ["guestCpus", "memoryMb"]
+ ACCESS_DENIED_CODE = 403
def __init__(self, acloud_config, oauth2_credentials):
"""Initialize.
@@ -1015,3 +1017,25 @@
sshkey_item["value"] = "\n".join([sshkey_item["value"].strip(), entry
]).strip()
self.SetCommonInstanceMetadata(metadata)
+
+ def CheckAccess(self):
+ """Check if the user has read access to the cloud project.
+
+ Returns:
+ True if the user has at least read access to the project.
+ False otherwise.
+
+ Raises:
+ errors.HttpError if other unexpected error happens when
+ accessing the project.
+ """
+ api = self.service.zones().list(project=self._project)
+ retry_http_codes = copy.copy(self.RETRY_HTTP_CODES)
+ retry_http_codes.remove(self.ACCESS_DENIED_CODE)
+ try:
+ self.Execute(api, retry_http_codes=retry_http_codes)
+ except errors.HttpError as e:
+ if e.code == self.ACCESS_DENIED_CODE:
+ return False
+ raise
+ return True