Example #1
0
def get_slb_info(instance):
    request = DescribeLoadBalancersRequest.DescribeLoadBalancersRequest()
    response = client.do_action_with_exception(request)
    SLBInfo = json.loads(response)
    LoadBalancerIdList = []
    for SLBInstance in SLBInfo['LoadBalancers']['LoadBalancer']:
        LoadBalancerIdList.append(SLBInstance['LoadBalancerId'])

    if instance == 'all':
        Ali_Slb_Info = {}
        for SLBInstance in SLBInfo['LoadBalancers']['LoadBalancer']:
            request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
            request.set_LoadBalancerId(SLBInstance['LoadBalancerId'])
            response = client.do_action_with_exception(request)
            Ali_Slb_Info[SLBInstance['LoadBalancerId']] = json.loads(response.decode('utf-8'))
        print(LoadBalancerIdList)
    elif instance in LoadBalancerIdList:
        request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
        request.set_LoadBalancerId(instance)
        response = client.do_action_with_exception(request)
        response = json.loads(response.decode('utf-8'))
        print(response['BackendServers'])
        return response['BackendServers']['BackendServer']

    else:
        print("输入错误,请输入 all 或 SLB实例ID !")
Example #2
0
def get_backserver(id):
    request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
    )
    request.set_LoadBalancerId(id)
    response = client.do_action_with_exception(request)
    serverid = json.loads(response)['BackendServers']['BackendServer']
    print serverid
Example #3
0
def get_slb_item(keys):
    '''
    获取单个slb信息
    :param keys:
    :return:
    '''
    key_id = keys['key_id']
    key_secret = keys['key_secret']
    region_id = keys['region_id']
    instanceId = keys['instanceId']
    result = {}

    try:
        client = AcsClient(key_id, key_secret, region_id)
        request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
        request.set_LoadBalancerId(instanceId)
        response = client.do_action_with_exception(request)
        response_json = json.loads(response)
        BackendServers = [i.get('ServerId') for i in response_json.get('BackendServers').get('BackendServer')]
        ListenPorts = [i.get('ListenerProtocal') + ':' + str(i.get('ListenerPort')) for i in
                       response_json.get('ListenerPortsAndProtocal').get('ListenerPortAndProtocal')]
        expiredTime = response_json.get('EndTime')
        result['BackendServers'] = BackendServers
        result['ListenPorts'] = ListenPorts
        result['expiredTime'] = expiredTime

    except Exception as e:
        print (e)

    return  result
 def get_slb_attr(self, slb_id):
     request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
     )
     request.set_accept_format('json')
     request.set_LoadBalancerId(slb_id)
     response = self.client.do_action_with_exception(request)
     response_dict = json.loads(response)
     return response_dict
Example #5
0
 def get_slb(self, LoadBalancerId):
     request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
     )
     request.set_LoadBalancerId(LoadBalancerId)
     request.set_accept_format("json")
     result = json.loads(self.clt.do_action(request))
     print(result)
     return result
Example #6
0
 def getBackServer(self, id):
     #获取slb后端ECS实例状态
     request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
     )
     request.set_LoadBalancerId(id)
     response = client.do_action_with_exception(request)
     serverid = json.loads(response)['BackendServers']['BackendServer']
     return serverid
Example #7
0
 def describelbackenserverid(self,loadbalancername):
     """通过slb 查询后端ecs id"""
     loadbalancerid = self.describeloadbalancer(loadbalancername)[0]
     masterzoneid = self.selcetmasterzoneid(loadbalancername)[0]
     request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
     values = {"RegionId":"cn-hangzhou","MasterZoneId":str(masterzoneid),"LoadBalancerId":str(loadbalancerid)}
     info = self.request_aliyun_api(request,values)['BackendServers']['BackendServer']      
     ecsidlist = [ecsid['ServerId'] for ecsid in info]
     return ecsidlist
Example #8
0
File: api.py Project: zeus911/POW
 def get_slb_attrs(self, slb_id):
     slb = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
     )
     slb.set_LoadBalancerId(slb_id)
     slb.set_accept_format('json')
     slb_r = self.clt.do_action(slb)
     slb_json = json.loads(slb_r)
     return [
         obj for obj in slb_json.get('BackendServers').get('BackendServer')
     ]
Example #9
0
    def get_lb_attr(self, lbids):

        instanceIds = defaultdict(set)
        for lbid in lbids:
            request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
            )
            request.set_LoadBalancerId(lbid)
            result = self._request(request)
            #print json.dumps(result,sort_keys=True,indent=4, separators=(',', ': '))
            for server in result['BackendServers']['BackendServer']:
                instanceIds[lbid].add(server['ServerId'])

        return instanceIds
Example #10
0
 def get_slb_config(self, slb_id):
     """
     :params:
         SLB实例ID
     :return:
         SLB ID对应实例配置字典
     """
     request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
     )
     request.set_accept_format('json')
     request.set_LoadBalancerId(slb_id)
     result = self.client.do_action(request)
     return result
Example #11
0
def get_aliyun_slb_by_loadbalancer_id(loadbalancer_id):
    """
    获取slb的实例属性
    :param loadbalancer_id:
    :return:
    """
    aliyun_client = get_aliyun_client()
    # 获取实例属性.
    aliyun_request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
    )
    aliyun_request.set_accept_format('json')
    aliyun_request.set_LoadBalancerId(loadbalancer_id)

    aliyun_response = aliyun_client.do_action_with_exception(aliyun_request)
    return json.loads(aliyun_response)
Example #12
0
def update_Slb():
    Slb_Info = {}
    client = AcsClient(Config.configs['AliAK']['AccessKey'],
                       Config.configs['AliAK']['AccessKeySecret'], RegionId)
    request = DescribeLoadBalancersRequest.DescribeLoadBalancersRequest()
    response = client.do_action_with_exception(request)
    SLBInfo = json.loads(response)

    for SLBInstance in SLBInfo['LoadBalancers']['LoadBalancer']:
        request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
        )
        request.set_LoadBalancerId(SLBInstance['LoadBalancerId'])
        response = client.do_action_with_exception(request)
        Slb_Info[SLBInstance['LoadBalancerId']] = json.loads(
            response.decode('utf-8'))

    conn.set('Slb_Info', json.dumps(Slb_Info))
Example #13
0
    def describeloadbalancerattribute(self, loadbalanceid):
        """
        查询负载均衡实例的详细信息 - 来获取端口 --没有分页
        :param loadbalanceid:
        :return:
        """
        try:
            request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
            request.set_accept_format('json')
            request.add_query_param('RegionId', self.instance_regionid)
            request.add_query_param('LoadBalancerId', loadbalanceid)

            # 发起请求
            response = self.cli.do_action_with_exception(request)
            return response.decode('utf8')
        except Exception as ee:
            log.error('查询负载均衡接偶错误: {}'.format(ee))
Example #14
0
 def slb_info(self) -> GaugeMetricFamily:
     req = DescribeSLB.DescribeLoadBalancersRequest()
     gauge = self.info_template(
         req,
         'aliyun_meta_slb_info',
         to_list=lambda data: data['LoadBalancers']['LoadBalancer'])
     gauge_slb_info = None
     for s in gauge.samples:
         slb_id = s.labels['LoadBalancerId']
         req_slb_attr = DescribeSLBAttr.DescribeLoadBalancerAttributeRequest(
         )
         req_slb_attr.set_LoadBalancerId(slb_id)
         slb_attrs_resp = self.client.do_action_with_exception(req_slb_attr)
         slb_attrs_info = json.loads(slb_attrs_resp)
         for protocol_info in slb_attrs_info['ListenerPortsAndProtocol'][
                 'ListenerPortAndProtocol']:
             protocol = protocol_info['ListenerProtocol']
             port = protocol_info['ListenerPort']
             req_slb_proto = None
             if protocol == 'tcp':
                 req_slb_proto = DescribeSLBTcpAttr.DescribeLoadBalancerTCPListenerAttributeRequest(
                 )
             elif protocol == 'http':
                 req_slb_proto = DescribeSLBHttpAttr.DescribeLoadBalancerHTTPListenerAttributeRequest(
                 )
             elif protocol == 'https':
                 req_slb_proto = DescribeSLBHttpsAttr.DescribeLoadBalancerHTTPSListenerAttributeRequest(
                 )
             req_slb_proto.set_LoadBalancerId(slb_id)
             req_slb_proto.set_ListenerPort(int(port))
             slb_protocol_resp = self.client.do_action_with_exception(
                 req_slb_proto)
             slb_protocol_info: dict = json.loads(slb_protocol_resp)
             if 'ForwardCode' in slb_protocol_info.keys():
                 continue
             Bandwidth = slb_protocol_info['Bandwidth']
             if gauge_slb_info is None:
                 gauge_slb_info = GaugeMetricFamily(
                     'aliyun_meta_slb_proto_bandwidth',
                     'protocolBandwidth',
                     labels=[
                         'instanceId', 'ListenerProtocol', 'ListenerPort'
                     ])
             gauge_slb_info.add_metric(
                 [slb_id, protocol, str(port)], value=float(Bandwidth))
     return gauge_slb_info
def describe_load_balancer_attribute(params):
    '''
    describe_load_balancer_attribute:查询指定负载均衡实例的详细信息
    官网API参考链接: https://help.aliyun.com/document_detail/27583.html
    '''
    counter = 0
    while counter < TRY_TIME:
        try:
            request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest()
            # 负载均衡实例的id
            request.set_LoadBalancerId(params["load_balancer_id"])
            response = ACS_CLIENT.do_action_with_exception(request)
            response_json = json.loads(response)
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
        finally:
            counter += 1
Example #16
0
    def get_slb_backends(self, slb_id):
        """
        :param slb_id: str
        return: ecs instance-id list, ecs is slb instance's backend
        """
        slb_req = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
        )
        slb_req.add_query_param('LoadBalancerId', slb_id)

        # Print response, show remix slb related ecs:
        slb_res = self.client.do_action_with_exception(slb_req)
        slb = json.loads(slb_res.decode('utf-8'))
        # print(json.dumps(slb, indent=2))

        # list all ecs-id which is elb backend:
        slb_backends = slb['BackendServers']['BackendServer']
        slb_backend_ids = []
        for backend in slb_backends:
            slb_backend_ids.append(backend['ServerId'])
        return slb_backend_ids
Example #17
0
import json
from aliyunsdkcore.client import AcsClient
import sys

from aliyunsdkslb.request.v20140515 import SetBackendServersRequest

from aliyunsdkcore import client
from aliyunsdkslb.request.v20140515 import DescribeLoadBalancerAttributeRequest
from aliyunsdkcore.profile import region_provider

clt = client.AcsClient("LTAIqM1yei0xXdQ7", "0T01csJF2SvRsFybw9X1g8s6dGxDO9",
                       "cn-shenzhen")

request = DescribeLoadBalancerAttributeRequest.DescribeLoadBalancerAttributeRequest(
)
request.set_accept_format('json')

request.add_query_param('RegionId', 'cn-shenzhen')
request.add_query_param('LoadBalancerId', 'lb-wz9bic77x0m0xfdtnjy0t')

response = clt.do_action_with_exception(request)
weight = json.loads(response)["BackendServers"]["BackendServer"]
weight[0]["Weight"] = 100
weight[1]["Weight"] = 100
# for i in range(len(weight)):
#     weight[i]["Weight"] = sys.argv[i+1]
#     print(weight[i]["Weight"])

weight = json.dumps(weight)

request = SetBackendServersRequest.SetBackendServersRequest()
Example #18
0
File: slb.py Project: zeus911/POW
 def do_thread_request(cls, instance_id, clt, access_key, ret):
     request = SLBAttrRequest.DescribeLoadBalancerAttributeRequest()
     request.set_LoadBalancerId(instance_id)
     instance = cls.do_single_request(clt, request)
     instance['Access_key'] = access_key
     ret.append(instance)