alivpc.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. // +build !windows
  15. package alivpc
  16. import (
  17. "encoding/json"
  18. "fmt"
  19. log "github.com/golang/glog"
  20. "golang.org/x/net/context"
  21. "os"
  22. "sync"
  23. "github.com/coreos/flannel/backend"
  24. "github.com/coreos/flannel/pkg/ip"
  25. "github.com/coreos/flannel/subnet"
  26. "github.com/denverdino/aliyungo/common"
  27. "github.com/denverdino/aliyungo/ecs"
  28. "github.com/denverdino/aliyungo/metadata"
  29. )
  30. func init() {
  31. backend.Register("ali-vpc", New)
  32. }
  33. type AliVpcBackend struct {
  34. sm subnet.Manager
  35. extIface *backend.ExternalInterface
  36. }
  37. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  38. be := AliVpcBackend{
  39. sm: sm,
  40. extIface: extIface,
  41. }
  42. return &be, nil
  43. }
  44. func (be *AliVpcBackend) RegisterNetwork(ctx context.Context, wg sync.WaitGroup, config *subnet.Config) (backend.Network, error) {
  45. // 1. Parse our configuration
  46. cfg := struct {
  47. AccessKeyID string
  48. AccessKeySecret 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. log.Infof("Unmarshal Configure : %v\n", cfg)
  56. // 2. Acquire the lease form subnet manager
  57. attrs := subnet.LeaseAttrs{
  58. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  59. }
  60. l, err := be.sm.AcquireLease(ctx, &attrs)
  61. switch err {
  62. case nil:
  63. case context.Canceled, context.DeadlineExceeded:
  64. return nil, err
  65. default:
  66. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  67. }
  68. if cfg.AccessKeyID == "" || cfg.AccessKeySecret == "" {
  69. cfg.AccessKeyID = os.Getenv("ACCESS_KEY_ID")
  70. cfg.AccessKeySecret = os.Getenv("ACCESS_KEY_SECRET")
  71. if cfg.AccessKeyID == "" || cfg.AccessKeySecret == "" {
  72. return nil, fmt.Errorf("ACCESS_KEY_ID and ACCESS_KEY_SECRET must be provided! ")
  73. }
  74. }
  75. meta := metadata.NewMetaData(nil)
  76. REGION, err := meta.Region()
  77. if err != nil {
  78. return nil, err
  79. }
  80. instanceid, err := meta.InstanceID()
  81. if err != nil {
  82. return nil, err
  83. }
  84. VpcID, err := meta.VpcID()
  85. if err != nil {
  86. return nil, err
  87. }
  88. c := ecs.NewClient(cfg.AccessKeyID, cfg.AccessKeySecret)
  89. vpc, _, err := c.DescribeVpcs(&ecs.DescribeVpcsArgs{
  90. RegionId: common.Region(REGION),
  91. VpcId: VpcID,
  92. })
  93. if err != nil || len(vpc) <= 0 {
  94. log.Errorf("Error DescribeVpcs: %s . \n", getErrorString(err))
  95. return nil, err
  96. }
  97. vroute, _, err := c.DescribeVRouters(&ecs.DescribeVRoutersArgs{
  98. VRouterId: vpc[0].VRouterId,
  99. RegionId: common.Region(REGION),
  100. })
  101. if err != nil || len(vroute) <= 0 {
  102. log.Errorf("Error DescribeVRouters: %s .\n", getErrorString(err))
  103. return nil, err
  104. }
  105. vRouterId := vroute[0].VRouterId
  106. rTableId := vroute[0].RouteTableIds.RouteTableId[0]
  107. rtables, _, err := c.DescribeRouteTables(&ecs.DescribeRouteTablesArgs{
  108. VRouterId: vRouterId,
  109. RouteTableId: rTableId,
  110. })
  111. if err != nil || len(rtables) <= 0 {
  112. log.Errorf("Error DescribeRouteTables: %s.\n", err.Error())
  113. return nil, err
  114. }
  115. route := &ecs.CreateRouteEntryArgs{
  116. DestinationCidrBlock: l.Subnet.String(),
  117. NextHopType: ecs.NextHopIntance,
  118. NextHopId: instanceid,
  119. ClientToken: "",
  120. RouteTableId: rTableId,
  121. }
  122. if err := be.recreateRoute(c, rtables[0], route); err != nil {
  123. return nil, err
  124. }
  125. if err := c.WaitForAllRouteEntriesAvailable(vRouterId, rTableId, 60); err != nil {
  126. return nil, err
  127. }
  128. return &backend.SimpleNetwork{
  129. SubnetLease: l,
  130. ExtIface: be.extIface,
  131. }, nil
  132. }
  133. func (be *AliVpcBackend) recreateRoute(c *ecs.Client, table ecs.RouteTableSetType, route *ecs.CreateRouteEntryArgs) error {
  134. exist := false
  135. for _, e := range table.RouteEntrys.RouteEntry {
  136. if e.RouteTableId == route.RouteTableId &&
  137. e.Type == ecs.RouteTableCustom &&
  138. e.InstanceId == route.NextHopId {
  139. if e.DestinationCidrBlock == route.DestinationCidrBlock &&
  140. e.Status == ecs.RouteEntryStatusAvailable {
  141. exist = true
  142. log.Infof("Keep target entry: rtableid=%s, CIDR=%s, NextHop=%s \n", e.RouteTableId, e.DestinationCidrBlock, e.InstanceId)
  143. continue
  144. }
  145. // 0.0.0.0/0 => ECS1 this kind of route is used for DNAT. so we keep it
  146. if e.DestinationCidrBlock == "0.0.0.0/0" {
  147. log.Infof("Keep route entry: rtableid=%s, CIDR=%s, NextHop=%s For DNAT\n", e.RouteTableId, e.DestinationCidrBlock, e.InstanceId)
  148. continue
  149. }
  150. // Fix: here we delete all the route which targeted to us(instance) except the specified route.
  151. // That means only one CIDR was allowed to target to the instance. Think if We need to change this
  152. // to adapt to multi CIDR and deal with unavailable route entry.
  153. if err := c.DeleteRouteEntry(&ecs.DeleteRouteEntryArgs{
  154. RouteTableId: route.RouteTableId,
  155. DestinationCidrBlock: e.DestinationCidrBlock,
  156. NextHopId: route.NextHopId,
  157. }); err != nil {
  158. return err
  159. }
  160. log.Infof("Remove old route entry: rtableid=%s, CIDR=%s, NextHop=%s \n", e.RouteTableId, e.DestinationCidrBlock, e.InstanceId)
  161. continue
  162. }
  163. log.Infof("Keep route entry: rtableid=%s, CIDR=%s, NextHop=%s \n", e.RouteTableId, e.DestinationCidrBlock, e.InstanceId)
  164. }
  165. if !exist {
  166. return c.CreateRouteEntry(route)
  167. }
  168. return nil
  169. }
  170. func getErrorString(e error) string {
  171. if e == nil {
  172. return ""
  173. }
  174. return e.Error()
  175. }