gce.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. // This work borrows from the https://github.com/kelseyhightower/flannel-route-manager
  15. // project which has the following license agreement.
  16. // Copyright (c) 2014 Kelsey Hightower
  17. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  18. // this software and associated documentation files (the "Software"), to deal in
  19. // the Software without restriction, including without limitation the rights to
  20. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  21. // of the Software, and to permit persons to whom the Software is furnished to do
  22. // so, subject to the following conditions:
  23. // The above copyright notice and this permission notice shall be included in all
  24. // copies or substantial portions of the Software.
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  31. // SOFTWARE.
  32. package gce
  33. import (
  34. "fmt"
  35. "net"
  36. "strings"
  37. "time"
  38. "github.com/coreos/flannel/Godeps/_workspace/src/code.google.com/p/goauth2/compute/serviceaccount"
  39. "github.com/coreos/flannel/Godeps/_workspace/src/code.google.com/p/google-api-go-client/compute/v1"
  40. "github.com/coreos/flannel/Godeps/_workspace/src/code.google.com/p/google-api-go-client/googleapi"
  41. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  42. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  43. "github.com/coreos/flannel/backend"
  44. "github.com/coreos/flannel/pkg/ip"
  45. "github.com/coreos/flannel/subnet"
  46. )
  47. var metadataEndpoint = "http://169.254.169.254/computeMetadata/v1"
  48. var replacer = strings.NewReplacer(".", "-", "/", "-")
  49. type GCEBackend struct {
  50. sm subnet.Manager
  51. publicIP ip.IP4
  52. mtu int
  53. project string
  54. lease *subnet.Lease
  55. computeService *compute.Service
  56. gceNetwork *compute.Network
  57. gceInstance *compute.Instance
  58. }
  59. func New(sm subnet.Manager, extIface *net.Interface, extIaddr net.IP, extEaddr net.IP) (backend.Backend, error) {
  60. gb := GCEBackend{
  61. sm: sm,
  62. publicIP: ip.FromIP(extEaddr),
  63. mtu: extIface.MTU,
  64. }
  65. return &gb, nil
  66. }
  67. func (g *GCEBackend) RegisterNetwork(ctx context.Context, network string, config *subnet.Config) (*backend.SubnetDef, error) {
  68. attrs := subnet.LeaseAttrs{
  69. PublicIP: g.publicIP,
  70. }
  71. l, err := g.sm.AcquireLease(ctx, network, &attrs)
  72. switch err {
  73. case nil:
  74. g.lease = l
  75. case context.Canceled, context.DeadlineExceeded:
  76. return nil, err
  77. default:
  78. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  79. }
  80. client, err := serviceaccount.NewClient(&serviceaccount.Options{})
  81. if err != nil {
  82. return nil, fmt.Errorf("error creating client: %v", err)
  83. }
  84. g.computeService, err = compute.New(client)
  85. if err != nil {
  86. return nil, fmt.Errorf("error creating compute service: %v", err)
  87. }
  88. networkName, err := networkFromMetadata()
  89. if err != nil {
  90. return nil, fmt.Errorf("error getting network metadata: %v", err)
  91. }
  92. g.project, err = projectFromMetadata()
  93. if err != nil {
  94. return nil, fmt.Errorf("error getting project: %v", err)
  95. }
  96. instanceName, err := instanceNameFromMetadata()
  97. if err != nil {
  98. return nil, fmt.Errorf("error getting instance name: %v", err)
  99. }
  100. instanceZone, err := instanceZoneFromMetadata()
  101. if err != nil {
  102. return nil, fmt.Errorf("error getting instance zone: %v", err)
  103. }
  104. g.gceNetwork, err = g.computeService.Networks.Get(g.project, networkName).Do()
  105. if err != nil {
  106. return nil, fmt.Errorf("error getting network from compute service: %v", err)
  107. }
  108. g.gceInstance, err = g.computeService.Instances.Get(g.project, instanceZone, instanceName).Do()
  109. if err != nil {
  110. return nil, fmt.Errorf("error getting instance from compute service: %v", err)
  111. }
  112. found, err := g.handleMatchingRoute(l.Subnet.String())
  113. if err != nil {
  114. return nil, fmt.Errorf("error handling matching route: %v", err)
  115. }
  116. if !found {
  117. operation, err := g.insertRoute(l.Subnet.String())
  118. if err != nil {
  119. return nil, fmt.Errorf("error inserting route: %v", err)
  120. }
  121. err = g.pollOperationStatus(operation.Name)
  122. if err != nil {
  123. return nil, fmt.Errorf("insert operaiton failed: ", err)
  124. }
  125. }
  126. return &backend.SubnetDef{
  127. Lease: l,
  128. MTU: g.mtu,
  129. }, nil
  130. }
  131. func (g *GCEBackend) Run(ctx context.Context) {
  132. }
  133. func (g *GCEBackend) UnregisterNetwork(ctx context.Context, name string) {
  134. }
  135. func (g *GCEBackend) pollOperationStatus(operationName string) error {
  136. for i := 0; i < 100; i++ {
  137. operation, err := g.computeService.GlobalOperations.Get(g.project, operationName).Do()
  138. if err != nil {
  139. return fmt.Errorf("error fetching operation status: %v", err)
  140. }
  141. if operation.Error != nil {
  142. return fmt.Errorf("error running operation: %v", operation.Error)
  143. }
  144. if i%5 == 0 {
  145. log.Infof("%v operation status: %v waiting for completion...", operation.OperationType, operation.Status)
  146. }
  147. if operation.Status == "DONE" {
  148. return nil
  149. }
  150. time.Sleep(time.Second)
  151. }
  152. return fmt.Errorf("timeout waiting for operation to finish")
  153. }
  154. //returns true if an exact matching rule is found
  155. func (g *GCEBackend) handleMatchingRoute(subnet string) (bool, error) {
  156. matchingRoute, err := g.getRoute(subnet)
  157. if err != nil {
  158. if apiError, ok := err.(*googleapi.Error); ok {
  159. if apiError.Code != 404 {
  160. return false, fmt.Errorf("error getting the route err: %v", err)
  161. }
  162. return false, nil
  163. }
  164. return false, fmt.Errorf("error getting googleapi: %v", err)
  165. }
  166. if matchingRoute.NextHopInstance == g.gceInstance.SelfLink {
  167. log.Info("Exact pre-existing route found")
  168. return true, nil
  169. }
  170. log.Info("Deleting conflicting route")
  171. operation, err := g.deleteRoute(subnet)
  172. if err != nil {
  173. return false, fmt.Errorf("error deleting conflicting route : %v", err)
  174. }
  175. err = g.pollOperationStatus(operation.Name)
  176. if err != nil {
  177. return false, fmt.Errorf("delete operation failed: %v", err)
  178. }
  179. return false, nil
  180. }
  181. func (g *GCEBackend) getRoute(subnet string) (*compute.Route, error) {
  182. routeName := formatRouteName(subnet)
  183. return g.computeService.Routes.Get(g.project, routeName).Do()
  184. }
  185. func (g *GCEBackend) deleteRoute(subnet string) (*compute.Operation, error) {
  186. routeName := formatRouteName(subnet)
  187. return g.computeService.Routes.Delete(g.project, routeName).Do()
  188. }
  189. func (g *GCEBackend) insertRoute(subnet string) (*compute.Operation, error) {
  190. log.Infof("Inserting route for subnet: %v", subnet)
  191. route := &compute.Route{
  192. Name: formatRouteName(subnet),
  193. DestRange: subnet,
  194. Network: g.gceNetwork.SelfLink,
  195. NextHopInstance: g.gceInstance.SelfLink,
  196. Priority: 1000,
  197. Tags: []string{},
  198. }
  199. return g.computeService.Routes.Insert(g.project, route).Do()
  200. }
  201. func formatRouteName(subnet string) string {
  202. return fmt.Sprintf("flannel-%s", replacer.Replace(subnet))
  203. }