OLD | NEW |
(Empty) | |
| 1 # Copyright 2015 The Chromium OS Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 """ |
| 6 Utilities for interfacing with Google Compute Engine. |
| 7 """ |
| 8 |
| 9 import httplib |
| 10 import json |
| 11 import logging |
| 12 import socket |
| 13 import time |
| 14 import urlparse |
| 15 |
| 16 |
| 17 LOGGER = logging.getLogger('gce') |
| 18 TRY_LIMIT = 5 |
| 19 |
| 20 |
| 21 class Authenticator(object): |
| 22 """Authenticator implementation that uses GCE metadata service for token. |
| 23 """ |
| 24 |
| 25 _INFO_URL = 'http://metadata.google.internal' |
| 26 _ACQUIRE_URL = ('http://metadata/computeMetadata/v1/instance/' |
| 27 'service-accounts/default/token') |
| 28 _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"} |
| 29 |
| 30 _cache_is_gce = None |
| 31 _token_cache = None |
| 32 _token_expiration = None |
| 33 |
| 34 @classmethod |
| 35 def is_gce(cls): |
| 36 if cls._cache_is_gce is None: |
| 37 cls._cache_is_gce = cls._test_is_gce() |
| 38 return cls._cache_is_gce |
| 39 |
| 40 @classmethod |
| 41 def _test_is_gce(cls): |
| 42 # Based on https://cloud.google.com/compute/docs/metadata#runninggce |
| 43 try: |
| 44 resp = cls._get(cls._INFO_URL) |
| 45 except socket.error: |
| 46 # Could not resolve URL. |
| 47 return False |
| 48 return resp.getheader('Metadata-Flavor', None) == 'Google' |
| 49 |
| 50 @staticmethod |
| 51 def _get(url, **kwargs): |
| 52 next_delay_sec = 1 |
| 53 for i in xrange(TRY_LIMIT): |
| 54 if i > 0: |
| 55 # Retry server error status codes. |
| 56 LOGGER.info('Encountered server error; retrying after %d second(s).', |
| 57 next_delay_sec) |
| 58 time.sleep(next_delay_sec) |
| 59 next_delay_sec *= 2 |
| 60 |
| 61 p = urlparse.urlparse(url) |
| 62 c = GetConnectionClass(protocol=p.scheme)(p.netloc) |
| 63 c.request('GET', url, **kwargs) |
| 64 resp = c.getresponse() |
| 65 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status) |
| 66 if resp.status < httplib.INTERNAL_SERVER_ERROR: |
| 67 return resp |
| 68 |
| 69 |
| 70 @classmethod |
| 71 def _get_token_dict(cls): |
| 72 if cls._token_cache: |
| 73 # If it expires within 25 seconds, refresh. |
| 74 if cls._token_expiration < time.time() - 25: |
| 75 return cls._token_cache |
| 76 |
| 77 resp = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS) |
| 78 if resp.status != httplib.OK: |
| 79 return None |
| 80 cls._token_cache = json.load(resp) |
| 81 cls._token_expiration = cls._token_cache['expires_in'] + time.time() |
| 82 return cls._token_cache |
| 83 |
| 84 def get_auth_header(self, _host): |
| 85 token_dict = self._get_token_dict() |
| 86 if not token_dict: |
| 87 return None |
| 88 return '%(token_type)s %(access_token)s' % token_dict |
OLD | NEW |