awsvpc.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. "net"
  19. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  20. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/mitchellh/goamz/aws"
  21. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/mitchellh/goamz/ec2"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/flannel/backend"
  24. "github.com/coreos/flannel/pkg/ip"
  25. "github.com/coreos/flannel/subnet"
  26. )
  27. type AwsVpcBackend struct {
  28. sm subnet.Manager
  29. publicIP ip.IP4
  30. mtu int
  31. cfg struct {
  32. RouteTableID string
  33. }
  34. lease *subnet.Lease
  35. }
  36. func New(sm subnet.Manager, extIface *net.Interface, extIaddr net.IP, extEaddr net.IP) (backend.Backend, error) {
  37. be := AwsVpcBackend{
  38. sm: sm,
  39. publicIP: ip.FromIP(extEaddr),
  40. mtu: extIface.MTU,
  41. }
  42. return &be, nil
  43. }
  44. func (m *AwsVpcBackend) RegisterNetwork(ctx context.Context, network string, config *subnet.Config) (*backend.SubnetDef, error) {
  45. // Parse our configuration
  46. if len(config.Backend) > 0 {
  47. if err := json.Unmarshal(config.Backend, &m.cfg); err != nil {
  48. return nil, fmt.Errorf("error decoding VPC backend config: %v", err)
  49. }
  50. }
  51. // Acquire the lease form subnet manager
  52. attrs := subnet.LeaseAttrs{
  53. PublicIP: m.publicIP,
  54. }
  55. l, err := m.sm.AcquireLease(ctx, network, &attrs)
  56. switch err {
  57. case nil:
  58. m.lease = l
  59. case context.Canceled, context.DeadlineExceeded:
  60. return nil, err
  61. default:
  62. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  63. }
  64. // Figure out this machine's EC2 instance ID and region
  65. identity, err := getInstanceIdentity()
  66. if err != nil {
  67. return nil, fmt.Errorf("error getting EC2 instance identity: %v", err)
  68. }
  69. instanceID, ok := identity["instanceId"].(string)
  70. if !ok {
  71. return nil, fmt.Errorf("invalid EC2 instance ID: %v", identity["instanceId"])
  72. }
  73. regionVal, _ := identity["region"].(string)
  74. region, ok := aws.Regions[regionVal]
  75. if !ok {
  76. return nil, fmt.Errorf("invalid AWS region: %v", identity["region"])
  77. }
  78. // Setup the EC2 client
  79. auth, err := aws.GetAuth("", "")
  80. if err != nil {
  81. return nil, fmt.Errorf("error getting AWS credentials from environment: %v", err)
  82. }
  83. ec2c := ec2.New(auth, region)
  84. if _, err = m.disableSrcDestCheck(instanceID, ec2c); err != nil {
  85. log.Infof("Warning- disabling source destination check failed: %v", err)
  86. }
  87. if m.cfg.RouteTableID == "" {
  88. log.Infof("RouteTableID not passed as config parameter, detecting ...")
  89. if err := m.detectRouteTableID(instanceID, ec2c); err != nil {
  90. return nil, err
  91. }
  92. }
  93. log.Info("RouteRouteTableID: ", m.cfg.RouteTableID)
  94. matchingRouteFound, err := m.checkMatchingRoutes(instanceID, l.Subnet.String(), ec2c)
  95. if err != nil {
  96. log.Errorf("Error describing route tables: %v", err)
  97. if ec2Err, ok := err.(*ec2.Error); ok {
  98. if ec2Err.Code == "UnauthorizedOperation" {
  99. log.Errorf("Note: DescribeRouteTables permission cannot be bound to any resource")
  100. }
  101. }
  102. }
  103. if !matchingRouteFound {
  104. if _, err := ec2c.DeleteRoute(m.cfg.RouteTableID, l.Subnet.String()); err != nil {
  105. if ec2err, ok := err.(*ec2.Error); !ok || ec2err.Code != "InvalidRoute.NotFound" {
  106. // an error other than the route not already existing occurred
  107. return nil, fmt.Errorf("error deleting existing route for %s: %v", l.Subnet.String(), err)
  108. }
  109. }
  110. // Add the route for this machine's subnet
  111. if _, err := m.createRoute(instanceID, l.Subnet.String(), ec2c); err != nil {
  112. return nil, fmt.Errorf("unable to add route %s: %v", l.Subnet.String(), err)
  113. }
  114. }
  115. return &backend.SubnetDef{
  116. Lease: l,
  117. MTU: m.mtu,
  118. }, nil
  119. }
  120. func (m *AwsVpcBackend) checkMatchingRoutes(instanceID, subnet string, ec2c *ec2.EC2) (bool, error) {
  121. filter := ec2.NewFilter()
  122. filter.Add("route.destination-cidr-block", subnet)
  123. filter.Add("route.state", "active")
  124. matchingRouteFound := false
  125. resp, err := ec2c.DescribeRouteTables([]string{m.cfg.RouteTableID}, filter)
  126. if err != nil {
  127. return matchingRouteFound, err
  128. }
  129. for _, routeTable := range resp.RouteTables {
  130. for _, route := range routeTable.Routes {
  131. if subnet == route.DestinationCidrBlock && route.State == "active" {
  132. if route.InstanceId == instanceID {
  133. matchingRouteFound = true
  134. break
  135. }
  136. log.Errorf("Deleting invalid *active* matching route: %s, %s \n", route.DestinationCidrBlock, route.InstanceId)
  137. }
  138. }
  139. }
  140. return matchingRouteFound, nil
  141. }
  142. func (m *AwsVpcBackend) createRoute(instanceID, subnet string, ec2c *ec2.EC2) (*ec2.SimpleResp, error) {
  143. route := &ec2.CreateRoute{
  144. RouteTableId: m.cfg.RouteTableID,
  145. InstanceId: instanceID,
  146. DestinationCidrBlock: subnet,
  147. }
  148. return ec2c.CreateRoute(route)
  149. }
  150. func (m *AwsVpcBackend) disableSrcDestCheck(instanceID string, ec2c *ec2.EC2) (*ec2.ModifyInstanceResp, error) {
  151. modifyAttributes := &ec2.ModifyInstance{
  152. SourceDestCheck: false,
  153. SetSourceDestCheck: true,
  154. }
  155. return ec2c.ModifyInstance(instanceID, modifyAttributes)
  156. }
  157. func (m *AwsVpcBackend) detectRouteTableID(instanceID string, ec2c *ec2.EC2) error {
  158. resp, err := ec2c.Instances([]string{instanceID}, nil)
  159. if err != nil {
  160. return fmt.Errorf("error getting instance info: %v", err)
  161. }
  162. if len(resp.Reservations) == 0 {
  163. return fmt.Errorf("no reservations found")
  164. }
  165. if len(resp.Reservations[0].Instances) == 0 {
  166. return fmt.Errorf("no matching instance found with id: %v", instanceID)
  167. }
  168. subnetID := resp.Reservations[0].Instances[0].SubnetId
  169. vpcID := resp.Reservations[0].Instances[0].VpcId
  170. log.Info("Subnet-ID: ", subnetID)
  171. log.Info("VPC-ID: ", vpcID)
  172. filter := ec2.NewFilter()
  173. filter.Add("association.subnet-id", subnetID)
  174. res, err := ec2c.DescribeRouteTables(nil, filter)
  175. if err != nil {
  176. return fmt.Errorf("error describing routeTables for subnetID %s: %v", subnetID, err)
  177. }
  178. if len(res.RouteTables) != 0 {
  179. m.cfg.RouteTableID = res.RouteTables[0].RouteTableId
  180. return nil
  181. }
  182. filter = ec2.NewFilter()
  183. filter.Add("association.main", "true")
  184. filter.Add("vpc-id", vpcID)
  185. res, err = ec2c.DescribeRouteTables(nil, filter)
  186. if err != nil {
  187. log.Info("error describing route tables: ", err)
  188. }
  189. if len(res.RouteTables) == 0 {
  190. return fmt.Errorf("main route table not found")
  191. }
  192. m.cfg.RouteTableID = res.RouteTables[0].RouteTableId
  193. return nil
  194. }
  195. func (m *AwsVpcBackend) Run(ctx context.Context) {
  196. }