loadbalancerbackendgroup.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // Copyright 2019 Yunion
  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 aws
  15. import (
  16. "context"
  17. "fmt"
  18. "strconv"
  19. "strings"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/pkg/errors"
  22. api "yunion.io/x/cloudmux/pkg/apis/compute"
  23. "yunion.io/x/cloudmux/pkg/cloudprovider"
  24. "yunion.io/x/cloudmux/pkg/multicloud"
  25. )
  26. type SElbBackendGroup struct {
  27. multicloud.SLoadbalancerBackendGroupBase
  28. AwsTags
  29. lb *SElb
  30. TargetGroupName string `xml:"TargetGroupName"`
  31. Protocol string `xml:"Protocol"`
  32. Port int64 `xml:"Port"`
  33. VpcID string `xml:"VpcId"`
  34. TargetType string `xml:"TargetType"`
  35. HealthyThresholdCount int `xml:"HealthyThresholdCount"`
  36. Matcher Matcher `xml:"Matcher"`
  37. UnhealthyThresholdCount int `xml:"UnhealthyThresholdCount"`
  38. HealthCheckPath string `xml:"HealthCheckPath"`
  39. HealthCheckProtocol string `xml:"HealthCheckProtocol"`
  40. HealthCheckPort string `xml:"HealthCheckPort"`
  41. HealthCheckIntervalSeconds int `xml:"HealthCheckIntervalSeconds"`
  42. HealthCheckTimeoutSeconds int `xml:"HealthCheckTimeoutSeconds"`
  43. TargetGroupArn string `xml:"TargetGroupArn"`
  44. LoadBalancerArns []string `xml:"LoadBalancerArns>member"`
  45. }
  46. func (self *SElbBackendGroup) GetILoadbalancer() cloudprovider.ICloudLoadbalancer {
  47. return self.lb
  48. }
  49. type Matcher struct {
  50. HTTPCode string `json:"HttpCode"`
  51. }
  52. func (self *SElbBackendGroup) GetId() string {
  53. return self.TargetGroupArn
  54. }
  55. func (self *SElbBackendGroup) GetName() string {
  56. return self.TargetGroupName
  57. }
  58. func (self *SElbBackendGroup) GetGlobalId() string {
  59. return self.GetId()
  60. }
  61. func (self *SElbBackendGroup) GetStatus() string {
  62. return api.LB_STATUS_ENABLED
  63. }
  64. func (self *SElbBackendGroup) Refresh() error {
  65. lbbg, err := self.lb.region.GetElbBackendgroup(self.GetId())
  66. if err != nil {
  67. return err
  68. }
  69. return jsonutils.Update(self, lbbg)
  70. }
  71. func (self *SElbBackendGroup) GetSysTags() map[string]string {
  72. data := map[string]string{}
  73. data["port"] = strconv.FormatInt(self.Port, 10)
  74. data["target_type"] = self.TargetType
  75. data["health_check_protocol"] = strings.ToLower(self.HealthCheckProtocol)
  76. data["health_check_interval"] = strconv.Itoa(self.HealthCheckIntervalSeconds)
  77. return data
  78. }
  79. func (self *SElbBackendGroup) GetProjectId() string {
  80. return ""
  81. }
  82. func (self *SElbBackendGroup) IsDefault() bool {
  83. return false
  84. }
  85. func (self *SElbBackendGroup) GetType() string {
  86. return api.LB_BACKENDGROUP_TYPE_NORMAL
  87. }
  88. func (self *SElbBackendGroup) GetILoadbalancerBackends() ([]cloudprovider.ICloudLoadbalancerBackend, error) {
  89. backends, err := self.lb.region.GetELbBackends(self.GetId())
  90. if err != nil {
  91. return nil, errors.Wrap(err, "GetELbBackends")
  92. }
  93. ibackends := make([]cloudprovider.ICloudLoadbalancerBackend, len(backends))
  94. for i := range backends {
  95. backends[i].group = self
  96. ibackends[i] = &backends[i]
  97. }
  98. return ibackends, nil
  99. }
  100. func (self *SElbBackendGroup) GetILoadbalancerBackendById(backendId string) (cloudprovider.ICloudLoadbalancerBackend, error) {
  101. backend, err := self.lb.region.GetELbBackend(backendId)
  102. if err != nil {
  103. return nil, errors.Wrap(err, "GetELbBackend")
  104. }
  105. backend.group = self
  106. return backend, nil
  107. }
  108. func (self *SElbBackendGroup) GetProtocolType() string {
  109. switch self.Protocol {
  110. case "TCP":
  111. return api.LB_LISTENER_TYPE_TCP
  112. case "UDP":
  113. return api.LB_LISTENER_TYPE_UDP
  114. case "HTTP":
  115. return api.LB_LISTENER_TYPE_HTTP
  116. case "HTTPS":
  117. return api.LB_LISTENER_TYPE_HTTPS
  118. case "TCP_UDP":
  119. return api.LB_LISTENER_TYPE_TCP_UDP
  120. default:
  121. return ""
  122. }
  123. }
  124. func (self *SElbBackendGroup) GetScheduler() string {
  125. return ""
  126. }
  127. func (self *SElbBackendGroup) GetHealthCheck() (*cloudprovider.SLoadbalancerHealthCheck, error) {
  128. health := &cloudprovider.SLoadbalancerHealthCheck{}
  129. health.HealthCheck = api.LB_BOOL_ON
  130. health.HealthCheckRise = self.HealthyThresholdCount
  131. health.HealthCheckFail = self.UnhealthyThresholdCount
  132. health.HealthCheckInterval = self.HealthCheckIntervalSeconds
  133. health.HealthCheckURI = self.HealthCheckPath
  134. health.HealthCheckType = strings.ToLower(self.HealthCheckProtocol)
  135. health.HealthCheckTimeout = self.HealthCheckTimeoutSeconds
  136. health.HealthCheckHttpCode = ToOnecloudHealthCode(self.Matcher.HTTPCode)
  137. return health, nil
  138. }
  139. func (self *SElbBackendGroup) GetStickySession() (*cloudprovider.SLoadbalancerStickySession, error) {
  140. attrs, err := self.lb.region.GetElbBackendgroupAttributes(self.GetId())
  141. if err != nil {
  142. return nil, errors.Wrap(err, "GetElbBackendgroupAttributes")
  143. }
  144. cookieTime := 0
  145. if t, ok := attrs["stickiness.lb_cookie.duration_seconds"]; !ok {
  146. cookieTime, err = strconv.Atoi(t)
  147. }
  148. ret := &cloudprovider.SLoadbalancerStickySession{
  149. StickySession: attrs["stickiness.enabled"],
  150. StickySessionCookie: "",
  151. StickySessionType: api.LB_STICKY_SESSION_TYPE_INSERT,
  152. StickySessionCookieTimeout: cookieTime,
  153. }
  154. return ret, nil
  155. }
  156. func (self *SElbBackendGroup) AddBackendServer(opts *cloudprovider.SLoadbalancerBackend) (cloudprovider.ICloudLoadbalancerBackend, error) {
  157. backend, err := self.lb.region.AddElbBackend(self.GetId(), opts.ExternalId, opts.Weight, opts.Port)
  158. if err != nil {
  159. return nil, errors.Wrap(err, "AddElbBackend")
  160. }
  161. backend.group = self
  162. return backend, nil
  163. }
  164. func (self *SElbBackendGroup) RemoveBackendServer(opts *cloudprovider.SLoadbalancerBackend) error {
  165. return self.lb.region.RemoveElbBackend(self.GetId(), opts.ExternalId, opts.Weight, opts.Port)
  166. }
  167. func (self *SElbBackendGroup) Delete(ctx context.Context) error {
  168. return self.lb.region.DeleteElbBackendGroup(self.GetId())
  169. }
  170. func (self *SRegion) GetELbBackends(backendgroupId string) ([]SElbBackend, error) {
  171. params := map[string]string{
  172. "TargetGroupArn": backendgroupId,
  173. }
  174. ret := &SElbBackends{}
  175. err := self.elbRequest("DescribeTargetHealth", params, ret)
  176. if err != nil {
  177. return nil, err
  178. }
  179. return ret.TargetHealthDescriptions, nil
  180. }
  181. func (self *SRegion) GetELbBackend(backendId string) (*SElbBackend, error) {
  182. groupId, instanceId, port, err := parseElbBackendId(backendId)
  183. if err != nil {
  184. return nil, errors.Wrap(err, "parseElbBackendId")
  185. }
  186. params := map[string]string{
  187. "TargetGroupArn": groupId,
  188. "Targets.member.1.Id": instanceId,
  189. "Targets.member.1.Port": fmt.Sprintf("%d", port),
  190. }
  191. ret := &SElbBackends{}
  192. err = self.elbRequest("DescribeTargetHealth", params, ret)
  193. if err != nil {
  194. return nil, errors.Wrapf(err, "DescribeTargetHealth")
  195. }
  196. for i := range ret.TargetHealthDescriptions {
  197. if ret.TargetHealthDescriptions[i].GetGlobalId() == backendId {
  198. return &ret.TargetHealthDescriptions[i], nil
  199. }
  200. }
  201. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "%s", backendId)
  202. }
  203. func parseElbBackendId(id string) (string, string, int, error) {
  204. segs := strings.Split(id, "::")
  205. if len(segs) != 3 {
  206. return "", "", 0, fmt.Errorf("%s is not a valid backend id", id)
  207. }
  208. port, err := strconv.Atoi(segs[2])
  209. if err != nil {
  210. return "", "", 0, fmt.Errorf("%s is not a valid backend id, %s", id, err)
  211. }
  212. return segs[0], segs[1], port, nil
  213. }
  214. func genElbBackendId(backendgroupId string, serverId string, port int) string {
  215. return strings.Join([]string{backendgroupId, serverId, strconv.Itoa(port)}, "::")
  216. }
  217. func (self *SRegion) AddElbBackend(backendgroupId, serverId string, weight int, port int) (*SElbBackend, error) {
  218. params := map[string]string{
  219. "TargetGroupArn": backendgroupId,
  220. "Targets.member.1.Id": serverId,
  221. "Targets.member.1.Port": fmt.Sprintf("%d", port),
  222. }
  223. err := self.elbRequest("RegisterTargets", params, nil)
  224. if err != nil {
  225. return nil, errors.Wrapf(err, "RegisterTargets")
  226. }
  227. return self.GetELbBackend(genElbBackendId(backendgroupId, serverId, port))
  228. }
  229. func (self *SRegion) RemoveElbBackend(backendgroupId, serverId string, weight int, port int) error {
  230. params := map[string]string{
  231. "TargetGroupArn": backendgroupId,
  232. "Targets.member.1.Id": serverId,
  233. "Targets.member.1.Port": fmt.Sprintf("%d", port),
  234. }
  235. return self.elbRequest("DeregisterTargets", params, nil)
  236. }
  237. func (self *SRegion) DeleteElbBackendGroup(id string) error {
  238. return self.elbRequest("DeleteTargetGroup", map[string]string{"TargetGroupArn": id}, nil)
  239. }
  240. func (self *SRegion) RemoveElbBackends(backendgroupId string) error {
  241. backends, err := self.GetELbBackends(backendgroupId)
  242. if err != nil {
  243. return errors.Wrap(err, "GetELbBackends")
  244. }
  245. if len(backends) == 0 {
  246. return nil
  247. }
  248. for i := range backends {
  249. err := self.RemoveElbBackend(backendgroupId, backends[i].GetBackendId(), 0, backends[i].GetPort())
  250. if err != nil {
  251. return err
  252. }
  253. }
  254. return nil
  255. }
  256. func (self *SRegion) GetElbBackendgroupAttributes(id string) (map[string]string, error) {
  257. ret := struct {
  258. Attributes []struct {
  259. Key string
  260. Value string
  261. } `xml:"Attributes>member"`
  262. }{}
  263. err := self.elbRequest("DescribeTargetGroupAttributes", map[string]string{"TargetGroupArn": id}, &ret)
  264. if err != nil {
  265. return nil, err
  266. }
  267. result := map[string]string{}
  268. for _, attr := range ret.Attributes {
  269. result[attr.Key] = attr.Value
  270. }
  271. return result, nil
  272. }
  273. func (self *SElbBackendGroup) GetDescription() string {
  274. return self.AwsTags.GetDescription()
  275. }