(address=None, url_params=None, platform_check=True)
| 248 | |
| 249 | |
| 250 | def read_md(address=None, url_params=None, platform_check=True): |
| 251 | |
| 252 | if address is None: |
| 253 | address = MD_V1_URL |
| 254 | |
| 255 | ret = { |
| 256 | "meta-data": None, |
| 257 | "user-data": None, |
| 258 | "success": False, |
| 259 | "reason": None, |
| 260 | } |
| 261 | ret["platform_reports_gce"] = platform_reports_gce() |
| 262 | |
| 263 | if platform_check and not ret["platform_reports_gce"]: |
| 264 | ret["reason"] = "Not running on GCE." |
| 265 | return ret |
| 266 | |
| 267 | # If we cannot resolve the metadata server, then no point in trying. |
| 268 | if not util.is_resolvable_url(address): |
| 269 | LOG.debug("%s is not resolvable", address) |
| 270 | ret["reason"] = 'address "%s" is not resolvable' % address |
| 271 | return ret |
| 272 | |
| 273 | # url_map: (our-key, path, required, is_text, is_recursive) |
| 274 | url_map = [ |
| 275 | ("instance-id", ("instance/id",), True, True, False), |
| 276 | ("availability-zone", ("instance/zone",), True, True, False), |
| 277 | ("local-hostname", ("instance/hostname",), True, True, False), |
| 278 | ("instance-data", ("instance/attributes",), False, False, True), |
| 279 | ("project-data", ("project/attributes",), False, False, True), |
| 280 | ] |
| 281 | metadata_fetcher = GoogleMetadataFetcher( |
| 282 | address, url_params.num_retries, url_params.sec_between_retries |
| 283 | ) |
| 284 | md = {} |
| 285 | # Iterate over url_map keys to get metadata items. |
| 286 | for mkey, paths, required, is_text, is_recursive in url_map: |
| 287 | value = None |
| 288 | for path in paths: |
| 289 | new_value = metadata_fetcher.get_value(path, is_text, is_recursive) |
| 290 | if new_value is not None: |
| 291 | value = new_value |
| 292 | if required and value is None: |
| 293 | msg = "required key %s returned nothing. not GCE" |
| 294 | ret["reason"] = msg % mkey |
| 295 | return ret |
| 296 | md[mkey] = value |
| 297 | |
| 298 | instance_data = json.loads(md["instance-data"] or "{}") |
| 299 | project_data = json.loads(md["project-data"] or "{}") |
| 300 | valid_keys = [instance_data.get("sshKeys"), instance_data.get("ssh-keys")] |
| 301 | block_project = instance_data.get("block-project-ssh-keys", "").lower() |
| 302 | if block_project != "true" and not instance_data.get("sshKeys"): |
| 303 | valid_keys.append(project_data.get("ssh-keys")) |
| 304 | valid_keys.append(project_data.get("sshKeys")) |
| 305 | public_keys_data = "\n".join([key for key in valid_keys if key]) |
| 306 | md["public-keys-data"] = public_keys_data.splitlines() |
| 307 |
no test coverage detected