Guest User

Untitled

a guest
Jan 28th, 2014
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.51 KB | None | 0 0
  1. # Copyright 2013 Google Inc. All Rights Reserved.
  2. #
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License version 3, as
  5. # published by the Free Software Foundation.
  6. #
  7. # This program is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. """An implementation of the DataSource API for cloud-init that knows
  15. how to talk to Google Compute Engine virtual machines.
  16. """
  17. import urllib2
  18.  
  19. from cloudinit import log as logging
  20. from cloudinit import sources
  21.  
  22. MD_URL = 'http://metadata/computeMetadata/v1beta1'
  23.  
  24. LOG = logging.getLogger(__name__)
  25.  
  26. class MetaDataResponse(object):
  27. """ An object that represents a response from the metadata server."""
  28. def __init__(self, code, contents):
  29. self._code = code
  30. self._contents = contents
  31.  
  32. @property
  33. def code(self):
  34. return self._code
  35.  
  36. @property
  37. def contents(self):
  38. return self._contents
  39.  
  40.  
  41. class DataSourceGCE(sources.DataSource):
  42. """Implements the cloud-init DataSource API for GCE."""
  43.  
  44. def __str__(self):
  45. clazz = self.__class__
  46. return str(clazz.__name__)
  47.  
  48. def _ReadUrl(self, url):
  49. headers = {}
  50. try:
  51. req = urllib2.Request(url, data=None, headers=headers)
  52. resp = urllib2.urlopen(req, timeout=50)
  53. return MetaDataResponse(200, resp.read())
  54. except urllib2.HTTPError as e:
  55. return MetaDataResponse(e.code, '')
  56.  
  57. def _GetMetadata(self, server_name, local_name):
  58. result = self._ReadUrl(MD_URL + '/' + server_name)
  59. if result.code != 200:
  60. LOG.error('Failed to fetch %s from server (%d)',
  61. server_name, result.code)
  62. return False
  63. self.metadata[local_name] = result.contents
  64. return True
  65.  
  66. def get_data(self):
  67. """Overrides the implementation in the parent class."""
  68. self.metadata = {}
  69. try:
  70. if not self._GetMetadata('instance/id', 'instance-id'):
  71. return False
  72. if not self._GetMetadata('instance/zone', 'availability-zone'):
  73. return False
  74. if not self._GetMetadata('project/attributes/sshKeys', 'public-keys'):
  75. return False
  76. if not self._GetMetadata('instance/hostname', 'local-hostname'):
  77. return False
  78. except:
  79. LOG.error('GCE Metadata lookup failed.', exc_info=True)
  80. return False
  81.  
  82. clipped_keys = self._TrimKeys(self.metadata['public-keys'])
  83. self.metadata['public-keys'] = clipped_keys
  84.  
  85. try:
  86. userdata_result = self._ReadUrl(MD_URL + 'instance/attributes/user-data')
  87. if userdata_result != 200:
  88. LOG.error('Got %d from metadata server',
  89. userdata_result.code)
  90. self.userdata_raw = userdata_result.contents
  91. except:
  92. LOG.error('Failed to load userdata', exc_info=True)
  93. if not self.userdata_raw:
  94. self.userdata_raw = ''
  95. return True
  96.  
  97. def _TrimKeys(self, key_string):
  98. index = key_string.index(':')
  99. if index > 0:
  100. return key_string[(index + 1):]
  101. else:
  102. return key_string
  103.  
  104.  
  105. DATASOURCES = [
  106. (DataSourceGCE, (sources.DEP_FILESYSTEM, sources.DEP_NETWORK)),
  107. ]
  108.  
  109.  
  110. # DataSource instantiation hook.
  111. def get_datasource_list(depends):
  112. return sources.list_from_depends(depends, DATASOURCES)
Advertisement
Add Comment
Please, Sign In to add comment