switch_lb.py 2.71 KB
#!/usr/bin/python
# -*- coding: UTF-8 -*-

""" 
修改腾讯云七层负载均衡器的权重

@see doc:  https://cloud.tencent.com/document/product/214/8978
  
"""

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)








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})