metadata.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2015 flannel authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build !windows
  15. package gce
  16. import (
  17. "io/ioutil"
  18. "net/http"
  19. "path"
  20. "strings"
  21. )
  22. func networkFromMetadata() (string, error) {
  23. network, err := metadataGet("/instance/network-interfaces/0/network")
  24. if err != nil {
  25. return "", err
  26. }
  27. return path.Base(network), nil
  28. }
  29. func projectFromMetadata() (string, error) {
  30. projectName, err := metadataGet("/project/project-id")
  31. if err != nil {
  32. return "", err
  33. }
  34. return path.Base(projectName), nil
  35. }
  36. func instanceZoneFromMetadata() (string, error) {
  37. zone, err := metadataGet("/instance/zone")
  38. if err != nil {
  39. return "", err
  40. }
  41. return path.Base(zone), nil
  42. }
  43. func instanceNameFromMetadata() (string, error) {
  44. hostname, err := metadataGet("/instance/hostname")
  45. if err != nil {
  46. return "", err
  47. }
  48. //works because we can't have . in the instance name
  49. return strings.SplitN(hostname, ".", 2)[0], nil
  50. }
  51. func metadataGet(path string) (string, error) {
  52. req, err := http.NewRequest("GET", metadataEndpoint+path, nil)
  53. if err != nil {
  54. return "", err
  55. }
  56. req.Header.Add("Metadata-Flavor", "Google")
  57. client := &http.Client{}
  58. resp, err := client.Do(req)
  59. if err != nil {
  60. return "", err
  61. }
  62. defer resp.Body.Close()
  63. data, err := ioutil.ReadAll(resp.Body)
  64. if err != nil {
  65. return "", err
  66. }
  67. return string(data), nil
  68. }