awsvpc.go 7.3 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. package awsvpc
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws"
  19. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr"
  20. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata"
  21. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2"
  22. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  23. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  24. "github.com/coreos/flannel/backend"
  25. "github.com/coreos/flannel/pkg/ip"
  26. "github.com/coreos/flannel/subnet"
  27. )
  28. func init() {
  29. backend.Register("aws-vpc", New)
  30. }
  31. type AwsVpcBackend struct {
  32. sm subnet.Manager
  33. extIface *backend.ExternalInterface
  34. }
  35. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  36. be := AwsVpcBackend{
  37. sm: sm,
  38. extIface: extIface,
  39. }
  40. return &be, nil
  41. }
  42. func (be *AwsVpcBackend) Run(ctx context.Context) {
  43. <-ctx.Done()
  44. }
  45. func (be *AwsVpcBackend) RegisterNetwork(ctx context.Context, network string, config *subnet.Config) (backend.Network, error) {
  46. // Parse our configuration
  47. cfg := struct {
  48. RouteTableID string
  49. }{}
  50. if len(config.Backend) > 0 {
  51. if err := json.Unmarshal(config.Backend, &cfg); err != nil {
  52. return nil, fmt.Errorf("error decoding VPC backend config: %v", err)
  53. }
  54. }
  55. // Acquire the lease form subnet manager
  56. attrs := subnet.LeaseAttrs{
  57. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  58. }
  59. l, err := be.sm.AcquireLease(ctx, network, &attrs)
  60. switch err {
  61. case nil:
  62. case context.Canceled, context.DeadlineExceeded:
  63. return nil, err
  64. default:
  65. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  66. }
  67. // Figure out this machine's EC2 instance ID and region
  68. metadataClient := ec2metadata.New(nil)
  69. region, err := metadataClient.Region()
  70. if err != nil {
  71. return nil, fmt.Errorf("error getting EC2 region name: %v", err)
  72. }
  73. instanceID, err := metadataClient.GetMetadata("instance-id")
  74. if err != nil {
  75. return nil, fmt.Errorf("error getting EC2 instance ID: %v", err)
  76. }
  77. ec2c := ec2.New(&aws.Config{Region: aws.String(region)})
  78. if _, err = be.disableSrcDestCheck(instanceID, ec2c); err != nil {
  79. log.Infof("Warning- disabling source destination check failed: %v", err)
  80. }
  81. if cfg.RouteTableID == "" {
  82. log.Infof("RouteTableID not passed as config parameter, detecting ...")
  83. if cfg.RouteTableID, err = be.detectRouteTableID(instanceID, ec2c); err != nil {
  84. return nil, err
  85. }
  86. }
  87. log.Info("RouteRouteTableID: ", cfg.RouteTableID)
  88. matchingRouteFound, err := be.checkMatchingRoutes(cfg.RouteTableID, instanceID, l.Subnet.String(), ec2c)
  89. if err != nil {
  90. log.Errorf("Error describing route tables: %v", err)
  91. if ec2Err, ok := err.(awserr.Error); ok {
  92. if ec2Err.Code() == "UnauthorizedOperation" {
  93. log.Errorf("Note: DescribeRouteTables permission cannot be bound to any resource")
  94. }
  95. }
  96. }
  97. if !matchingRouteFound {
  98. cidrBlock := l.Subnet.String()
  99. deleteRouteInput := &ec2.DeleteRouteInput{RouteTableId: &cfg.RouteTableID, DestinationCidrBlock: &cidrBlock}
  100. if _, err := ec2c.DeleteRoute(deleteRouteInput); err != nil {
  101. if ec2err, ok := err.(awserr.Error); !ok || ec2err.Code() != "InvalidRoute.NotFound" {
  102. // an error other than the route not already existing occurred
  103. return nil, fmt.Errorf("error deleting existing route for %s: %v", l.Subnet.String(), err)
  104. }
  105. }
  106. // Add the route for this machine's subnet
  107. if _, err := be.createRoute(cfg.RouteTableID, instanceID, l.Subnet.String(), ec2c); err != nil {
  108. return nil, fmt.Errorf("unable to add route %s: %v", l.Subnet.String(), err)
  109. }
  110. }
  111. return &backend.SimpleNetwork{
  112. SubnetLease: l,
  113. ExtIface: be.extIface,
  114. }, nil
  115. }
  116. func (be *AwsVpcBackend) checkMatchingRoutes(routeTableID, instanceID, subnet string, ec2c *ec2.EC2) (bool, error) {
  117. matchingRouteFound := false
  118. filter := newFilter()
  119. filter.Add("route.destination-cidr-block", subnet)
  120. filter.Add("route.state", "active")
  121. input := ec2.DescribeRouteTablesInput{Filters: filter, RouteTableIds: []*string{&routeTableID}}
  122. resp, err := ec2c.DescribeRouteTables(&input)
  123. if err != nil {
  124. return matchingRouteFound, err
  125. }
  126. for _, routeTable := range resp.RouteTables {
  127. for _, route := range routeTable.Routes {
  128. if subnet == *route.DestinationCidrBlock && *route.State == "active" {
  129. if *route.InstanceId == instanceID {
  130. matchingRouteFound = true
  131. break
  132. }
  133. log.Errorf("Deleting invalid *active* matching route: %s, %s \n", *route.DestinationCidrBlock, *route.InstanceId)
  134. }
  135. }
  136. }
  137. return matchingRouteFound, nil
  138. }
  139. func (be *AwsVpcBackend) createRoute(routeTableID, instanceID, subnet string, ec2c *ec2.EC2) (*ec2.CreateRouteOutput, error) {
  140. route := &ec2.CreateRouteInput{
  141. RouteTableId: &routeTableID,
  142. InstanceId: &instanceID,
  143. DestinationCidrBlock: &subnet,
  144. }
  145. return ec2c.CreateRoute(route)
  146. }
  147. func (be *AwsVpcBackend) disableSrcDestCheck(instanceID string, ec2c *ec2.EC2) (*ec2.ModifyInstanceAttributeOutput, error) {
  148. modifyAttributes := &ec2.ModifyInstanceAttributeInput{
  149. InstanceId: aws.String(instanceID),
  150. SourceDestCheck: &ec2.AttributeBooleanValue{Value: aws.Bool(false)},
  151. }
  152. return ec2c.ModifyInstanceAttribute(modifyAttributes)
  153. }
  154. func (be *AwsVpcBackend) detectRouteTableID(instanceID string, ec2c *ec2.EC2) (string, error) {
  155. instancesInput := &ec2.DescribeInstancesInput{
  156. InstanceIds: []*string{&instanceID},
  157. }
  158. resp, err := ec2c.DescribeInstances(instancesInput)
  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 := newFilter()
  173. filter.Add("association.subnet-id", *subnetID)
  174. routeTablesInput := &ec2.DescribeRouteTablesInput{
  175. Filters: filter,
  176. }
  177. res, err := ec2c.DescribeRouteTables(routeTablesInput)
  178. if err != nil {
  179. return "", fmt.Errorf("error describing routeTables for subnetID %s: %v", *subnetID, err)
  180. }
  181. if len(res.RouteTables) != 0 {
  182. return *res.RouteTables[0].RouteTableId, nil
  183. }
  184. filter = newFilter()
  185. filter.Add("association.main", "true")
  186. filter.Add("vpc-id", *vpcID)
  187. routeTablesInput = &ec2.DescribeRouteTablesInput{
  188. Filters: filter,
  189. }
  190. res, err = ec2c.DescribeRouteTables(routeTablesInput)
  191. if err != nil {
  192. log.Info("error describing route tables: ", err)
  193. }
  194. if len(res.RouteTables) == 0 {
  195. return "", fmt.Errorf("main route table not found")
  196. }
  197. return *res.RouteTables[0].RouteTableId, nil
  198. }