Authored by chunhua.zhang

支持修改clb的权重

... ... @@ -7,7 +7,7 @@ import base64
import hashlib
import time
import requests
import json
import json
class QcloudApi:
... ... @@ -70,11 +70,6 @@ class QcloudApi:
hmac_sign = hmac.new(bytes(self.secretKey), bytes(str_full), hashlib.sha1).digest()
return base64.b64encode(hmac_sign).decode()
# for test
if __name__ == "__main__":
api = QcloudApi(secretId='AK**K', secretKey='AC**QaW')
api.do_query(params={'Action': 'DescribeLoadBalancers'}, req_url=QcloudApi.URLS_lb)
... ...
... ... @@ -9,65 +9,151 @@
"""
from qcloud.qcloud_api import QcloudApi
import time, sys
def modify_alb_weight(SecretId, SecretKey, lb_id, domain, ip_weight_dict):
"""
修改应用型负载均衡器上服务器的权重
@:param lb_id: 应用型负载均衡器ID
@:param domain: 应用型负载均衡器的domain
@:param ip_weight_dict: 需要设置权重的dict, 格式为 {'ip': weight }
@return list
"""
instance_weight = {} # instance_id --> weight
instance_port = {} # instance_id --> port
listener_ids = [] # all linsters
api = QcloudApi(secretId=SecretId, secretKey=SecretKey)
lb_info = api.do_query(params={'Action': 'DescribeForwardLBBackends', 'loadBalancerId': lb_id}, req_url=QcloudApi.URLS_lb)
# listener : [http , https]
for listener in lb_info['data']:
for rule in listener['rules']:
if rule['domain'] == domain: # domain match
listener_ids.append(listener['listenerId'])
for backend in rule['backends']:
instance_port[backend['unInstanceId']] = backend['port']
if backend['lanIp'] in ip_weight_dict.keys():
# setup the instance_id --> weight
instance_weight[backend['unInstanceId']] = ip_weight_dict[backend['lanIp']]
else:
instance_weight[backend['unInstanceId']] = 0
# 检查至少有一个weight
normal = False
for v in instance_weight.values():
if v != 0:
normal = True
if not normal:
sys.exit(" instance weight: %s is all zero. please check again!" % instance_weight)
# 修改七层负载均衡器的权重: https://cloud.tencent.com/document/product/214/8978
for lis_id in listener_ids:
params = {'Action': 'ModifyForwardSeventhBackends', 'loadBalancerId': lb_id, 'listenerId': lis_id, 'domain': domain}
i = 1
for ins_id, ins_weight in instance_weight.iteritems():
params['backends.%i.instanceId' % i] = ins_id
params['backends.%i.weight' % i] = ins_weight
params['backends.%i.port' % i] = instance_port[ins_id]
i = i + 1
rsp = api.do_query(params, req_url=QcloudApi.URLS_lb)
print(u"response code: %s . success change domain: %s for lis_id : %s. wait for 10s" % (rsp['code'], domain, lis_id))
time.sleep(10)
import time, sys, os
from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
"""
切换负载均衡器的流量
依赖: inventory 文件
"""
class LBSwitch:
def __init__(self, secretId, secretKey, az1_lb_id, az2_lb_id, az3_lb_id):
self.SecretId = secretId
self.SecretKey = secretKey
self.az1_lb_id = az1_lb_id
self.az2_lb_id = az2_lb_id
self.az3_lb_id = az3_lb_id
def all_to_az1(self):
"""
所有流量切换到az1
:return:
"""
az1_nginxs = self.get_inventory_ifo("az1", 'java-nginx')
print "get all java nginx: %s for az: %s" % (az1_nginxs, "az1")
ip_weight_dict = {}
for az1_nginx in az1_nginxs:
ip_weight_dict[az1_nginx] = 10
self.modify_alb_weight(lb_id=self.az2_lb_id, domain="*.yoho.cn", ip_weight_dict=ip_weight_dict)
def all_to_az2(self):
"""
所有流量切换到AZ2
:return:
"""
az2_nginx = self.get_inventory_ifo("az2", 'java-nginx')
ip_weight_dict = {}
for nginx in az2_nginx:
ip_weight_dict[nginx] = 10
self.modify_alb_weight(lb_id=self.az3_lb_id, domain="*.yoho.cn", ip_weight_dict=ip_weight_dict)
@staticmethod
def get_inventory_ifo(az, group):
"""
get hosts info from ansible inventory file
"""
data_loader = DataLoader()
inventory = InventoryManager(loader=data_loader,
sources=[os.path.join("./inventories", az, 'hosts')])
return inventory.get_groups_dict()[group]
def modify_clb_weight(self, lb_id, ip_weight_dict):
"""
修改传统负载均衡器的权重
@:param lb_id 负载均衡器的ID
@:param ip_weight_dict 需要设置权重的后端IP-权重字典, 格式为 {'ip': weight }
:return: True: 修改成功
"""
# 1.获取传统型负载均衡器的后端列表:https://cloud.tencent.com/document/api/214/1259
instance_weight = {} # instance_id --> weight
api = QcloudApi(secretId=self.SecretId, secretKey=self.SecretKey)
lb_info = api.do_query(params={'Action': 'DescribeLoadBalancerBackends', 'loadBalancerId': lb_id}, req_url=QcloudApi.URLS_lb)
for backend in lb_info['backendSet']:
if backend['lanIp'] in ip_weight_dict.keys():
# setup the instance_id --> weight
instance_weight[backend['unInstanceId']] = ip_weight_dict[backend['lanIp']]
else:
instance_weight[backend['unInstanceId']] = 0
# 2.检查至少有一个weight
if len(filter(lambda w: w != 0, instance_weight.values())) == 0:
sys.exit(" instance weight: %s is all zero. please check again!" % instance_weight)
# 3.修改权重: https://cloud.tencent.com/document/api/214/1264
modify_params = {'Action': 'ModifyLoadBalancerBackends', 'loadBalancerId': lb_id}
i = 1
for ins_id, ins_weight in instance_weight.iteritems():
modify_params['backends.%i.instanceId' % i] = ins_id
modify_params['backends.%i.weight' % i] = ins_weight
i = i + 1
api = QcloudApi(secretId=self.SecretId, secretKey=self.SecretKey)
lb_info = api.do_query(params=modify_params, req_url=QcloudApi.URLS_lb)
return lb_info['code'] == 0
def modify_alb_weight(self, lb_id, domain, ip_weight_dict):
"""
修改应用型负载均衡器上服务器的权重
@:param lb_id: 应用型负载均衡器ID
@:param domain: 应用型负载均衡器的domain
@:param ip_weight_dict: 需要设置权重的dict, 格式为 {'ip': weight }
@return list
"""
instance_weight = {} # instance_id --> weight
instance_port = {} # instance_id --> port
listener_ids = [] # all linsters
api = QcloudApi(secretId=self.SecretId, secretKey=self.SecretKey)
lb_info = api.do_query(params={'Action': 'DescribeForwardLBBackends', 'loadBalancerId': lb_id}, req_url=QcloudApi.URLS_lb)
# listener : [http , https]
for listener in lb_info['data']:
for rule in listener['rules']:
if rule['domain'] == domain: # domain match
listener_ids.append(listener['listenerId'])
for backend in rule['backends']:
instance_port[backend['unInstanceId']] = backend['port']
if backend['lanIp'] in ip_weight_dict.keys():
# setup the instance_id --> weight
instance_weight[backend['unInstanceId']] = ip_weight_dict[backend['lanIp']]
else:
instance_weight[backend['unInstanceId']] = 0
# 检查至少有一个weight
if len(filter(lambda w: w != 0, instance_weight.values())) == 0:
sys.exit(" instance weight: %s is all zero. please check again!" % instance_weight)
# 修改七层负载均衡器的权重: https://cloud.tencent.com/document/product/214/8978
return_code = []
for lis_id in listener_ids:
params = {'Action': 'ModifyForwardSeventhBackends', 'loadBalancerId': lb_id, 'listenerId': lis_id, 'domain': domain}
i = 1
for ins_id, ins_weight in instance_weight.iteritems():
params['backends.%i.instanceId' % i] = ins_id
params['backends.%i.weight' % i] = ins_weight
params['backends.%i.port' % i] = instance_port[ins_id]
i = i + 1
rsp = api.do_query(params, req_url=QcloudApi.URLS_lb)
print(u"response code: %s . success change domain: %s for lis_id : %s. wait for 10s" % (rsp['code'], domain, lis_id))
return_code.append(rsp['code'])
time.sleep(10)
lbswitch = LBSwitch(secretId="AKID6dwpKadiQgbDpXDtyNhppIHPO5qPv5GK", secretKey="ACJkH9mg0DBA1PYpf0E7f3g534wBsQaW",
az1_lb_id="lb-e14oxiq3", az2_lb_id="lb-e14oxiq3", az3_lb_id="lb-e14oxiq3")
ret = lbswitch.modify_clb_weight(lb_id="lb-e14oxiq3", ip_weight_dict={"10.66.104.15": 10, "10.66.104.13":20})
print ret
modify_alb_weight('AKID6dwpKadiQgbDpXDtyNhppIHPO5qPv5GK', 'ACJkH9mg0DBA1PYpf0E7f3g534wBsQaW', lb_id='lb-990aeqw1', domain='*.yoho.cn', ip_weight_dict={'10.66.202.5': 10, '10.66.202.12':10})
... ...