alivpc.go 5.7 KB

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