OLD | NEW |
(Empty) | |
| 1 # Copyright 2015 The Chromium 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 |
| 27 _cache_is_gce = None |
| 28 |
| 29 @classmethod |
| 30 def is_gce(cls): |
| 31 if cls._cache_is_gce is None: |
| 32 cls._cache_is_gce = cls._test_is_gce() |
| 33 return cls._cache_is_gce |
| 34 |
| 35 @classmethod |
| 36 def _test_is_gce(cls): |
| 37 # Based on https://cloud.google.com/compute/docs/metadata#runninggce |
| 38 try: |
| 39 resp = cls._get(cls._INFO_URL) |
| 40 except socket.error: |
| 41 # Could not resolve URL. |
| 42 return False |
| 43 return resp.getheader('Metadata-Flavor', None) == 'Google' |
| 44 |
| 45 @staticmethod |
| 46 def _get(url, **kwargs): |
| 47 next_delay_sec = 1 |
| 48 for i in xrange(TRY_LIMIT): |
| 49 if i > 0: |
| 50 # Retry server error status codes. |
| 51 LOGGER.info('Encountered server error; retrying after %d second(s).', |
| 52 next_delay_sec) |
| 53 time.sleep(next_delay_sec) |
| 54 next_delay_sec *= 2 |
| 55 |
| 56 p = urlparse.urlparse(url) |
| 57 c = GetConnectionClass(protocol=p.scheme)(p.netloc) |
| 58 c.request('GET', url, **kwargs) |
| 59 resp = c.getresponse() |
| 60 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status) |
| 61 if resp.status < httplib.INTERNAL_SERVER_ERROR: |
| 62 return resp |
| 63 |
| 64 |
| 65 def GetConnectionClass(protocol=None): |
| 66 if protocol is None: |
| 67 protocol = 'https' |
| 68 if protocol == 'https': |
| 69 return httplib.HTTPSConnection |
| 70 elif protocol == 'http': |
| 71 return httplib.HTTPConnection |
| 72 else: |
| 73 raise RuntimeError( |
| 74 "Don't know how to work with protocol '%s'" % protocol) |
OLD | NEW |