def getProjectID(): logging.info('Requesting project_id') try: p = cache['project-id'] return str(p) except KeyError as e: logging.info('project-id not found, refreshing..') result = GCloud([ '--configuration', gcloud_configuraiton, 'config', 'list', '--format', 'json()' ]) p = json.loads(result) try: logging.info('Returning project-id: ' + p['core']['project']) cache['project-id'] = p['core']['project'] return p['core']['project'] except KeyError as e: logging.info('project-id not found or not set in gcloud') return __getStaticMetadataValue(GOOGLE_PROJECT_ID)
def getDefaultServiceAccount(acct, k): logging.info('Requesting ServiceAccount : ' + acct + '/' + k) # check if the access_token is still valid. If it is, return from cache but first decrement # the expires_in field for the remaining time. For all other attributes, return as-is try: p = cache[k] if (k == 'token'): key_expire_at = cache['token_valid_until'] if (int(calendar.timegm(time.gmtime()) >= key_expire_at)): logging.info('access_token expired') else: token_val = cache[k] seconds_still_valid = key_expire_at - int( calendar.timegm(time.gmtime())) logging.info('token still valid for ' + str(seconds_still_valid)) token_val['expires_in'] = seconds_still_valid return jsonify(**token_val) else: return str(p) except KeyError as e: logging.info(k + ' not found in cache, refreshing..') # First acquire gcloud's access_token try: token = GCloud([ '--configuration', gcloud_configuraiton, 'auth', 'print-access-token' ]) except: logging.error( "gcloud not initialized, attempting to return static access_token from environment" ) token = __getStaticMetadataValue(GOOGLE_ACCESS_TOKEN) logging.info('access_token: ' + token) try: # and then ask the token_info endpoint for details about it. r = urllib.request.urlopen( "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=" + token).read() r = json.loads(r) cache['aliases'] = acct cache['email'] = r['email'] cache['scopes'] = ("\n".join(r['scope'].split(' '))) valid_for = r['expires_in'] key_expire_at = int(calendar.timegm(time.gmtime()) + int(valid_for)) cache['token_valid_until'] = key_expire_at f = { "access_token": token, "expires_in": int(valid_for), "token_type": "Bearer" } cache['token'] = f if (k == 'token'): return jsonify(**f) else: return cache[k] except: logging.error( "Unable to interrogate tokeninfo endpoint for token details; bailing.." ) # TODO: we could try to fake a response (eg, while running this in disconnected mode...but lets just bail for now return "Unable to acquire access_token", 500