metadata.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. package gce
  15. import (
  16. "io/ioutil"
  17. "net/http"
  18. "path"
  19. "strings"
  20. )
  21. func networkFromMetadata() (string, error) {
  22. network, err := metadataGet("/instance/network-interfaces/0/network")
  23. if err != nil {
  24. return "", err
  25. }
  26. return path.Base(network), nil
  27. }
  28. func projectFromMetadata() (string, error) {
  29. projectName, err := metadataGet("/project/project-id")
  30. if err != nil {
  31. return "", err
  32. }
  33. return path.Base(projectName), nil
  34. }
  35. func instanceZoneFromMetadata() (string, error) {
  36. zone, err := metadataGet("/instance/zone")
  37. if err != nil {
  38. return "", err
  39. }
  40. return path.Base(zone), nil
  41. }
  42. func instanceNameFromMetadata() (string, error) {
  43. hostname, err := metadataGet("/instance/hostname")
  44. if err != nil {
  45. return "", err
  46. }
  47. //works because we can't have . in the instance name
  48. return strings.SplitN(hostname, ".", 2)[0], nil
  49. }
  50. func metadataGet(path string) (string, error) {
  51. req, err := http.NewRequest("GET", metadataEndpoint+path, nil)
  52. if err != nil {
  53. return "", err
  54. }
  55. req.Header.Add("Metadata-Flavor", "Google")
  56. client := &http.Client{}
  57. resp, err := client.Do(req)
  58. if err != nil {
  59. return "", err
  60. }
  61. defer resp.Body.Close()
  62. data, err := ioutil.ReadAll(resp.Body)
  63. if err != nil {
  64. return "", err
  65. }
  66. return string(data), nil
  67. }