awsvpc.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2015 CoreOS, Inc.
  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 awsvpc
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  19. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/mitchellh/goamz/aws"
  20. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/mitchellh/goamz/ec2"
  21. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  22. "github.com/coreos/flannel/backend"
  23. "github.com/coreos/flannel/pkg/ip"
  24. "github.com/coreos/flannel/subnet"
  25. "net"
  26. "sync"
  27. )
  28. type AwsVpcBackend struct {
  29. sm subnet.Manager
  30. network string
  31. config *subnet.Config
  32. cfg struct {
  33. RouteTableID string
  34. }
  35. lease *subnet.Lease
  36. ctx context.Context
  37. cancel context.CancelFunc
  38. wg sync.WaitGroup
  39. }
  40. func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
  41. ctx, cancel := context.WithCancel(context.Background())
  42. be := AwsVpcBackend{
  43. sm: sm,
  44. network: network,
  45. config: config,
  46. ctx: ctx,
  47. cancel: cancel,
  48. }
  49. return &be
  50. }
  51. func (m *AwsVpcBackend) Init(extIface *net.Interface, extIP net.IP) (*backend.SubnetDef, error) {
  52. // Parse our configuration
  53. if len(m.config.Backend) > 0 {
  54. if err := json.Unmarshal(m.config.Backend, &m.cfg); err != nil {
  55. return nil, fmt.Errorf("error decoding VPC backend config: %v", err)
  56. }
  57. }
  58. // Acquire the lease form subnet manager
  59. attrs := subnet.LeaseAttrs{
  60. PublicIP: ip.FromIP(extIP),
  61. }
  62. l, err := m.sm.AcquireLease(m.ctx, m.network, &attrs)
  63. switch err {
  64. case nil:
  65. m.lease = l
  66. case context.Canceled, context.DeadlineExceeded:
  67. return nil, err
  68. default:
  69. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  70. }
  71. // Figure out this machine's EC2 instance ID and region
  72. identity, err := getInstanceIdentity()
  73. if err != nil {
  74. return nil, fmt.Errorf("error getting EC2 instance identity: %v", err)
  75. }
  76. instanceID, ok := identity["instanceId"].(string)
  77. if !ok {
  78. return nil, fmt.Errorf("invalid EC2 instance ID: %v", identity["instanceId"])
  79. }
  80. regionVal, _ := identity["region"].(string)
  81. region, ok := aws.Regions[regionVal]
  82. if !ok {
  83. return nil, fmt.Errorf("invalid AWS region: %v", identity["region"])
  84. }
  85. // Setup the EC2 client
  86. auth, err := aws.GetAuth("", "")
  87. if err != nil {
  88. return nil, fmt.Errorf("error getting AWS credentials from environment: %v", err)
  89. }
  90. ec2c := ec2.New(auth, region)
  91. if m.cfg.RouteTableID == "" {
  92. log.Infof("RouteTableID not passed as config parameter, attempting to detect")
  93. routeTableID, err := m.DetectRouteTableID(instanceID, ec2c)
  94. if err != nil {
  95. return nil, err
  96. }
  97. log.Info("Detected routeRouteTableID: ", routeTableID)
  98. m.cfg.RouteTableID = routeTableID
  99. }
  100. filter := ec2.NewFilter()
  101. filter.Add("route.destination-cidr-block", l.Subnet.String())
  102. filter.Add("route.state", "active")
  103. resp, err := ec2c.DescribeRouteTables([]string{m.cfg.RouteTableID}, filter)
  104. if err != nil {
  105. log.Errorf("Error describing route tables: %v", err)
  106. if ec2Err, ok := err.(*ec2.Error); ok {
  107. if ec2Err.Code == "UnauthorizedOperation" {
  108. log.Errorf("Note: describeRouteTables permission cannot be bound to any resource")
  109. }
  110. }
  111. } else {
  112. for _, routeTable := range resp.RouteTables {
  113. for _, route := range routeTable.Routes {
  114. if l.Subnet.String() == route.DestinationCidrBlock && route.State == "active" {
  115. log.Errorf("Matching *active* entry to: %s that will be deleted: %s, %s \n", l.Subnet.String(), route.DestinationCidrBlock, route.GatewayId)
  116. }
  117. }
  118. }
  119. }
  120. // Delete route for this machine's subnet if it already exists
  121. if _, err := ec2c.DeleteRoute(m.cfg.RouteTableID, l.Subnet.String()); err != nil {
  122. if ec2err, ok := err.(*ec2.Error); !ok || ec2err.Code != "InvalidRoute.NotFound" {
  123. // an error other than the route not already existing occurred
  124. return nil, fmt.Errorf("error deleting existing route for %s: %v", l.Subnet.String(), err)
  125. }
  126. }
  127. // Add the route for this machine's subnet
  128. route := &ec2.CreateRoute{
  129. RouteTableId: m.cfg.RouteTableID,
  130. InstanceId: instanceID,
  131. DestinationCidrBlock: l.Subnet.String(),
  132. }
  133. if _, err := ec2c.CreateRoute(route); err != nil {
  134. return nil, fmt.Errorf("unable to add route %+v: %v", route, err)
  135. }
  136. return &backend.SubnetDef{
  137. Net: l.Subnet,
  138. MTU: extIface.MTU,
  139. }, nil
  140. }
  141. func (m *AwsVpcBackend) DetectRouteTableID(instanceID string, ec2c *ec2.EC2) (string, error) {
  142. resp, err := ec2c.Instances([]string{instanceID}, nil)
  143. if err != nil {
  144. return "", fmt.Errorf("error getting instance info: %v", err)
  145. }
  146. subnetID := resp.Reservations[0].Instances[0].SubnetId
  147. log.Info("SubnetId: ", subnetID)
  148. filter := ec2.NewFilter()
  149. filter.Add("association.subnet-id", subnetID)
  150. res, err := ec2c.DescribeRouteTables(nil, filter)
  151. if err != nil {
  152. return "", fmt.Errorf("error describing routeTables for subnetID %s: %v", subnetID, err)
  153. }
  154. return res.RouteTables[0].RouteTableId, nil
  155. }
  156. func (m *AwsVpcBackend) Run() {
  157. subnet.LeaseRenewer(m.ctx, m.sm, m.network, m.lease)
  158. }
  159. func (m *AwsVpcBackend) Stop() {
  160. m.cancel()
  161. }
  162. func (m *AwsVpcBackend) Name() string {
  163. return "aws-vpc"
  164. }