awsvpc.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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, extIaddr net.IP, extEaddr 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(extEaddr),
  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 _, err = m.disableSrcDestCheck(instanceID, ec2c); err != nil {
  92. log.Info("Warning- disabling source destination check falied!: %v", err)
  93. }
  94. if m.cfg.RouteTableID == "" {
  95. log.Infof("RouteTableID not passed as config parameter, detecting ...")
  96. if err := m.detectRouteTableID(instanceID, ec2c); err != nil {
  97. return nil, err
  98. }
  99. }
  100. log.Info("RouteRouteTableID: ", m.cfg.RouteTableID)
  101. matchingRouteFound, err := m.checkMatchingRoutes(instanceID, l.Subnet.String(), ec2c)
  102. if err != nil {
  103. log.Errorf("Error describing route tables: %v", err)
  104. if ec2Err, ok := err.(*ec2.Error); ok {
  105. if ec2Err.Code == "UnauthorizedOperation" {
  106. log.Errorf("Note: DescribeRouteTables permission cannot be bound to any resource")
  107. }
  108. }
  109. }
  110. if !matchingRouteFound {
  111. if _, err := ec2c.DeleteRoute(m.cfg.RouteTableID, l.Subnet.String()); err != nil {
  112. if ec2err, ok := err.(*ec2.Error); !ok || ec2err.Code != "InvalidRoute.NotFound" {
  113. // an error other than the route not already existing occurred
  114. return nil, fmt.Errorf("error deleting existing route for %s: %v", l.Subnet.String(), err)
  115. }
  116. }
  117. // Add the route for this machine's subnet
  118. if _, err := m.createRoute(instanceID, l.Subnet.String(), ec2c); err != nil {
  119. return nil, fmt.Errorf("unable to add route %s: %v", l.Subnet.String(), err)
  120. }
  121. }
  122. return &backend.SubnetDef{
  123. Net: l.Subnet,
  124. MTU: extIface.MTU,
  125. }, nil
  126. }
  127. func (m *AwsVpcBackend) checkMatchingRoutes(instanceID, subnet string, ec2c *ec2.EC2) (bool, error) {
  128. filter := ec2.NewFilter()
  129. filter.Add("route.destination-cidr-block", subnet)
  130. filter.Add("route.state", "active")
  131. matchingRouteFound := false
  132. resp, err := ec2c.DescribeRouteTables([]string{m.cfg.RouteTableID}, filter)
  133. if err != nil {
  134. return matchingRouteFound, err
  135. }
  136. for _, routeTable := range resp.RouteTables {
  137. for _, route := range routeTable.Routes {
  138. if subnet == route.DestinationCidrBlock && route.State == "active" {
  139. if route.InstanceId == instanceID {
  140. matchingRouteFound = true
  141. break
  142. }
  143. log.Errorf("Deleting invalid *active* matching route: %s, %s \n", route.DestinationCidrBlock, route.InstanceId)
  144. }
  145. }
  146. }
  147. return matchingRouteFound, nil
  148. }
  149. func (m *AwsVpcBackend) createRoute(instanceID, subnet string, ec2c *ec2.EC2) (*ec2.SimpleResp, error) {
  150. route := &ec2.CreateRoute{
  151. RouteTableId: m.cfg.RouteTableID,
  152. InstanceId: instanceID,
  153. DestinationCidrBlock: subnet,
  154. }
  155. return ec2c.CreateRoute(route)
  156. }
  157. func (m *AwsVpcBackend) disableSrcDestCheck(instanceID string, ec2c *ec2.EC2) (*ec2.ModifyInstanceResp, error) {
  158. modifyAttributes := &ec2.ModifyInstance{
  159. SourceDestCheck: false,
  160. SetSourceDestCheck: true,
  161. }
  162. return ec2c.ModifyInstance(instanceID, modifyAttributes)
  163. }
  164. func (m *AwsVpcBackend) detectRouteTableID(instanceID string, ec2c *ec2.EC2) error {
  165. resp, err := ec2c.Instances([]string{instanceID}, nil)
  166. if err != nil {
  167. return fmt.Errorf("error getting instance info: %v", err)
  168. }
  169. if len(resp.Reservations) == 0 {
  170. return fmt.Errorf("no reservations found")
  171. }
  172. if len(resp.Reservations[0].Instances) == 0 {
  173. return fmt.Errorf("no matching instance found with id: %v", instanceID)
  174. }
  175. subnetID := resp.Reservations[0].Instances[0].SubnetId
  176. vpcID := resp.Reservations[0].Instances[0].VpcId
  177. log.Info("Subnet-ID: ", subnetID)
  178. log.Info("VPC-ID: ", vpcID)
  179. filter := ec2.NewFilter()
  180. filter.Add("association.subnet-id", subnetID)
  181. res, err := ec2c.DescribeRouteTables(nil, filter)
  182. if err != nil {
  183. return fmt.Errorf("error describing routeTables for subnetID %s: %v", subnetID, err)
  184. }
  185. if len(res.RouteTables) != 0 {
  186. m.cfg.RouteTableID = res.RouteTables[0].RouteTableId
  187. return nil
  188. }
  189. filter = ec2.NewFilter()
  190. filter.Add("association.main", "true")
  191. filter.Add("vpc-id", vpcID)
  192. res, err = ec2c.DescribeRouteTables(nil, filter)
  193. if err != nil {
  194. log.Info("error describing route tables: ", err)
  195. }
  196. if len(res.RouteTables) == 0 {
  197. return fmt.Errorf("main route table not found")
  198. }
  199. m.cfg.RouteTableID = res.RouteTables[0].RouteTableId
  200. return nil
  201. }
  202. func (m *AwsVpcBackend) Run() {
  203. subnet.LeaseRenewer(m.ctx, m.sm, m.network, m.lease)
  204. }
  205. func (m *AwsVpcBackend) Stop() {
  206. m.cancel()
  207. }
  208. func (m *AwsVpcBackend) Name() string {
  209. return "aws-vpc"
  210. }