tencentvpc.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 tencentvpc
  16. import (
  17. "encoding/json"
  18. "fmt"
  19. "github.com/flannel-io/flannel/backend"
  20. "github.com/flannel-io/flannel/pkg/ip"
  21. "github.com/flannel-io/flannel/subnet"
  22. "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
  23. "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
  24. vpc "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vpc/v20170312"
  25. "golang.org/x/net/context"
  26. "io/ioutil"
  27. log "k8s.io/klog"
  28. "net/http"
  29. "os"
  30. "sync"
  31. )
  32. func init() {
  33. backend.Register("tencent-vpc", New)
  34. }
  35. type TencentVpcBackend struct {
  36. sm subnet.Manager
  37. extIface *backend.ExternalInterface
  38. }
  39. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  40. be := TencentVpcBackend{
  41. sm: sm,
  42. extIface: extIface,
  43. }
  44. return &be, nil
  45. }
  46. func get_vm_metadata(url string) (string, error) {
  47. resp, err := http.Get(url)
  48. if err != nil || resp.StatusCode != http.StatusOK {
  49. return "", fmt.Errorf("get vm region error: %v", err)
  50. }
  51. defer resp.Body.Close()
  52. metadata, _ := ioutil.ReadAll(resp.Body)
  53. return string(metadata), nil
  54. }
  55. func get_vm_region() (string, error) {
  56. url := "http://metadata.tencentyun.com/latest/meta-data/placement/region"
  57. return get_vm_metadata(url)
  58. }
  59. func get_vm_vpcid() (string, error) {
  60. macUrl := "http://metadata.tencentyun.com/latest/meta-data/mac"
  61. mac, err := get_vm_metadata(macUrl)
  62. if err != nil {
  63. return "", fmt.Errorf("get vm mac error: %v", err)
  64. }
  65. vpcUrl := fmt.Sprintf("http://metadata.tencentyun.com/latest/meta-data/network/interfaces/macs/%s/vpc-id", mac)
  66. vpcid, err := get_vm_metadata(vpcUrl)
  67. if err != nil {
  68. return "", fmt.Errorf("get vm vpcid error: %v", err)
  69. }
  70. return vpcid, nil
  71. }
  72. func (be *TencentVpcBackend) RegisterNetwork(ctx context.Context, wg *sync.WaitGroup, config *subnet.Config) (backend.Network, error) {
  73. // 1. Parse our configuration
  74. cfg := struct {
  75. AccessKeyID string
  76. AccessKeySecret string
  77. }{}
  78. if len(config.Backend) > 0 {
  79. if err := json.Unmarshal(config.Backend, &cfg); err != nil {
  80. return nil, fmt.Errorf("error decoding VPC backend config: %v", err)
  81. }
  82. }
  83. log.Infof("Unmarshal Configure : %v\n", cfg)
  84. // 2. Acquire the lease form subnet manager
  85. attrs := subnet.LeaseAttrs{
  86. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  87. }
  88. l, err := be.sm.AcquireLease(ctx, &attrs)
  89. switch err {
  90. case nil:
  91. case context.Canceled, context.DeadlineExceeded:
  92. return nil, err
  93. default:
  94. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  95. }
  96. if cfg.AccessKeyID == "" || cfg.AccessKeySecret == "" {
  97. cfg.AccessKeyID = os.Getenv("ACCESS_KEY_ID")
  98. cfg.AccessKeySecret = os.Getenv("ACCESS_KEY_SECRET")
  99. if cfg.AccessKeyID == "" || cfg.AccessKeySecret == "" {
  100. return nil, fmt.Errorf("ACCESS_KEY_ID and ACCESS_KEY_SECRET must be provided! ")
  101. }
  102. }
  103. region, err := get_vm_region()
  104. if err != nil {
  105. return nil, err
  106. }
  107. vpcid, err := get_vm_vpcid()
  108. if err != nil {
  109. return nil, err
  110. }
  111. c, _ := vpc.NewClientWithSecretId(cfg.AccessKeyID, cfg.AccessKeySecret, region)
  112. request := vpc.NewDescribeRouteTablesRequest()
  113. request.Filters = []*vpc.Filter{
  114. &vpc.Filter{
  115. Name: common.StringPtr("vpc-id"),
  116. Values: common.StringPtrs([]string{vpcid}),
  117. },
  118. }
  119. res, err := c.DescribeRouteTables(request)
  120. if _, ok := err.(*errors.TencentCloudSDKError); ok {
  121. return nil, fmt.Errorf("describe route table error: %v", ok)
  122. }
  123. if err != nil {
  124. return nil, err
  125. }
  126. response := res.Response
  127. if len(response.RouteTableSet) <= 0 {
  128. return nil, fmt.Errorf("No suitable routing table found")
  129. }
  130. routeTable := response.RouteTableSet[0]
  131. exists := false
  132. gatewayType := "NORMAL_CVM"
  133. routeType := "USER"
  134. for _, route := range routeTable.RouteSet {
  135. if *route.DestinationCidrBlock == l.Subnet.String() &&
  136. *route.GatewayId == be.extIface.ExtAddr.String() &&
  137. *route.GatewayType == gatewayType &&
  138. *route.RouteType == routeType {
  139. if *route.Enabled {
  140. exists = true
  141. } else {
  142. delRouteRequest := vpc.NewDeleteRoutesRequest()
  143. delRouteRequest.RouteTableId = routeTable.RouteTableId
  144. delRouteRequest.Routes = []*vpc.Route{
  145. &vpc.Route{
  146. RouteId: route.RouteId,
  147. },
  148. }
  149. _, err := c.DeleteRoutes(delRouteRequest)
  150. if err != nil {
  151. return nil, err
  152. }
  153. }
  154. }
  155. }
  156. if !exists {
  157. createRouteRequest := vpc.NewCreateRoutesRequest()
  158. createRouteRequest.RouteTableId = routeTable.RouteTableId
  159. createRouteRequest.Routes = []*vpc.Route{
  160. &vpc.Route{
  161. DestinationCidrBlock: common.StringPtr(l.Subnet.String()),
  162. GatewayType: &gatewayType,
  163. GatewayId: common.StringPtr(be.extIface.ExtAddr.String()),
  164. Enabled: common.BoolPtr(true),
  165. },
  166. }
  167. _, err := c.CreateRoutes(createRouteRequest)
  168. if err != nil {
  169. return nil, err
  170. }
  171. }
  172. return &backend.SimpleNetwork{
  173. SubnetLease: l,
  174. ExtIface: be.extIface,
  175. }, nil
  176. }