This topic describes how to view the monitoring metrics of a Server Load Balancer (SLB) instance and set alarms by using the Alibaba Cloud SDK for Python.

Prerequisites

Two ECS instances are created in the China (Zhangjiakou) region and the two instances are in the Running state.

Background information

In this topic, the process for viewing the monitoring metrics of an SLB instance and setting alarms is as follows:
  1. Create an SLB instance in China (Zhangjiakou), set its name to SLB1, set the primary zone to cn-zhangjiakou-a, set the secondary zone to cn-zhangjiakou-b, and set the billing method to Pay-As-You-Go.
  2. Create a TCP listener. Set the frontend port to 80, set the backend port for receiving requests to 80, and set the health check protocol to TCP. Add the created two ECS instances to the default server group and set the weight of both to 100.
  3. Query the QPS usage of the created SLB instance.
  4. Set an alarm rule that an alarm is triggered when the average QPS usage of the SLB instance reaches or exceeds 35.
  5. Delete the SLB instance.

Procedure

  1. From the downloaded SDK package, open the folder $aliyun-openapi-python-sdk-examples\sdk_examples\examples\slb.
  2. Open slb_monitor.py by using an editor. Set the user authentication parameter ACS_CLIENT and other parameters as needed, save the file, and exit.
    Note Because the identity of a user must be authenticated by the SDK, you can also set the AcsClient parameter in the constants file and call the constants file when needed.
    #encoding=utf-8
    """
    Create an SLB instance->Create a TCP listener->Add backend servers->
    Query current connections at the port of the SLB instance->Create an alarm rule
    """
    import sys
    import json
    import uuid
    
    #Call the AcsClient parameter for authentication.
    from aliyunsdkcore.client import AcsClient
    # Exception handling module using Alibaba Cloud official sdk
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    #Handle exceptions.
    from sdk_lib.exception import ExceptionHandler
    #Call the API used to create an SLB instance.   
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerRequest
    #Call the API used to add backend servers to the default server group.
    from aliyunsdkslb.request.v20140515 import AddBackendServersRequest
    #Call the API used to create a TCP listener.
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerTCPListenerRequest
    #Call the CloudMonitor API to view the latest monitoring data.
    from aliyunsdkcms.request.v20180308 import QueryMetricLastRequest
    #Call the CloudMonitor API to create an alarm rule for the SLB instance.
    from aliyunsdkcms.request.v20180308 import CreateAlarmRequest
    #Call the API used to delete an SLB instance.  
    from aliyunsdkslb.request.v20140515 import DeleteLoadBalancerRequest
    #Redirect command line output.
    from sdk_lib.common_util import CommonUtil
    
    #Set the user authentication parameter.
    ACS_CLIENT = AcsClient(
        'your-access-key-id',     #your-access-key-id
        'your-access-key-secret',   #your-access-key-secret
        'cn-zhangjiakou',     #your-region-id
    )
    #The maximum number of retry times after a failture
    TRY_TIME = 3
    
    def create_load_balancer(params):
        '''
        create_load_balancer: Create an SLB instance.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27577.htm?spm=a2c63.p38356.b99.137.1aad1093fJoHIT.
        '''
        try:
            #Set the API parameters for creating an SLB instance.
        request = CreateLoadBalancerRequest.CreateLoadBalancerRequest() 
        request.set_MasterZoneId(params["master_zone_id"]) 
        request.set_SlaveZoneId(params["slave_zone_id"]) 
        request.set_LoadBalancerName(params["load_balancer_name"]) 
        request.set_PayType(params["pay_balancer_type"])
            request.set_ClientToken(str(uuid.uuid1()))
        #Send the API request and receive the response.
        response = ACS_CLIENT.do_action_with_exception(request)
        response_json = json.loads(response)
        #Return results.    
        return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
    
    def add_backend_servers(params):
        '''
        add_backend_servers: Add backend servers.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                #Set the API parameters for adding backend servers to the default sever group.
                request = AddBackendServersRequest.AddBackendServersRequest()
                #The ID of the SLB instance
                request.set_LoadBalancerId(params["load_balancer_id"])
                #A list of the backend servers to be added
                request.set_BackendServers(params["backend_servers"])
                request.set_ClientToken(str(uuid.uuid1()))
            #Send the request and receive the response.
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
            #Return results.
                return response_json
            except ServerException as e:
                if ExceptionHandler.server_exception(e):
                    return e
            except ClientException as e:
                if ExceptionHandler.client_exception(e):
                    return e
            finally:
                counter += 1
    
    def create_tcp_listener(params):
        '''
        create_tcp_listener: Create a TCP listener.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
            #Set the API parameters for creating a TCP listener.
                request = CreateLoadBalancerTCPListenerRequest.CreateLoadBalancerTCPListenerRequest()
                #The ID of the SLB instance
                request.set_LoadBalancerId(params["load_balancer_id"])
            #The frontend port of the SLB instance 
                request.set_ListenerPort(params["listener_port"])
                #The backend port of the SLB instance 
                request.set_BackendServerPort(params["backend_server_port"])
            #The health check protocol of the listener
                request.set_HealthCheckType(params["listener_health_check"])
            #The peak bandwidth of the listener
                request.set_Bandwidth(params["listener_bandwidth"])
                request.set_ClientToken(str(uuid.uuid1()))
            #Send the request and receive the response.
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
            #Return results.
                return response_json
            except ServerException as e:
                if ExceptionHandler.server_exception(e):
                    return e
            except ClientException as e:
                if ExceptionHandler.client_exception(e):
                    return e
            finally:
                counter += 1
    
    def query_metric_last(params):
        '''
        Query_metric_last: Query the latest monitoring data of a specified metric.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = QueryMetricLastRequest.QueryMetricLastRequest()
                #The name space which indicates to which product the queried monitoring data belongs.
                request.set_Project(params["project"])
                #The name of the metric
                request.set_Metric(params["metric_name"])
                #Filtor conditions
                request.set_Dimensions(params['dimensions'])
                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
    
    def create_alarm(params):
        '''
        create_alarm: Create an alarm rule for one instance or multiple instances at a time.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = CreateAlarmRequest.CreateAlarmRequest()
    
                #The name of the product. You can refer to corresponding projects.
                request.set_Namespace(params["name_space"])
                #The name of the alarm rule
                request.set_Name(params["name"])
                #The name of the metric. You can refer to the descriptions of metrics for the corresponding product.
                request.set_MetricName(params["metric_name"])
                #A list of the instances for which the alarm rule is created
                request.set_Dimensions(params["dimensions"])
                #The statistical method. It must be consistent with the metric.
                request.set_Statistics(params["statistics"])
                #The alarm comparison operator
                request.set_ComparisonOperator(params["comparison_operator"])
                #The threshold of the alarm. Only numbers are supported.
                request.set_Threshold(params["threshold"])
                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
    
    def delete_load_balancer(load_balancer_id):
        '''
        delete_load_balancer:Delete an SLB instance.
        '''
        try:
        #Set the API parameters for deleting an SLB instance.
            request = DeleteLoadBalancerRequest.DeleteLoadBalancerRequest()
            #The ID of the SLB instance
            request.set_LoadBalancerId(load_balancer_id)
            #Send the request and receive the response.
            response = ACS_CLIENT.do_action_with_exception(request)
            response_json = json.loads(response)
        #Return results.
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
    
    def main():
        params = {}
        #Set parameters for the SLB instance.
        #Set the primary zone of the SLB instance to cn-zhangjiakou-a. 
        params["master_zone_id"] = "cn-zhangjiakou-a" 
        #Set the secondary zone of the SLB instance to cn-zhangjiakou-b. 
        params["slave_zone_id"] = "cn-zhangjiakou-b" 
        #Set the name of the SLB instance to SLB1. 
        params["load_balancer_name"] = "SLB1"
        #Set the billing method of the SLB instance to Pay-As-You-Go.
        params["pay_balancer_type"] = "PayOnDemand"
    
        #Set IDs and weights of the ECS instances added to the default server group.
        params["backend_servers"] = [{"ServerId":"i-8vbe8xxxxxxxxxxxw","Weight":"100"},{"ServerId":"i-8vbe8yixxxxxxxxxxxxv","Weight":"100"}]
    
        #Set parameters for the TCP listener.
        #Set the frontend port to 80.
        params["listener_port"] = 80
        #Set the backend port for receiving requests to 80.
        params["backend_server_port"] = 80
        #Set the health check protocol to TCP.
        params["listener_health_check"] = "tcp"
        #Set the peak bandwidth of the TCP listener to -1, which means the peak bandwidth is not limited.
        params["listener_bandwidth"] = -1
    
        #Set parameters for the queried metric.
        #Set the product to which the monitoring data belongs.
        params["project"] = "acs_slb_dashboard"
        #Set the name of the metric.
        params["traffic_tx_new"] = "InstanceQpsUtilization"
    
        #Set parameters for the alarm rule.
        #Set the product to which the alarm rule belongs.
        params["name_space"] = "acs_slb_dashboard"
        #Set the name of the alarm rule.
        params["name"] = "slb_alarm"
        #Set the name of the metric for which the alarm rule is created.
        params["metric_name"] = "InstanceQpsUtilization"
        #Set the statistical method of the monitoring data.
        params["statistics"] = "Average"
        #Set the alarm comparison operator.
        params["comparison_operator"] = ">="
        #Set the threshold of the alarm.
        params["threshold"] = 35
    
    
        #Create an SLB instance.
        #Obtain the returned value of create_load_balancer. "load_balancer_json" is the returned value in json format.
        load_balancer_json = create_load_balancer(params)
        #Print the returned value of load_balancer_json, where "create_load_balancer" is the name of the json string.
        CommonUtil.log("create_load_balancer", load_balancer_json)
    
        #The ID of the SLB instance
        params["load_balancer_id"] = load_balancer_json["LoadBalancerId"]
    
        #Create a TCP listener.
        result_json = create_tcp_listener(params)
        CommonUtil.log("create_tcp_listener", result_json)
    
        #Add backend servers.
        result_json = add_backend_servers(params)
        CommonUtil.log("add_backend_servers", result_json)
    
        #Query the QPS usage of the SLB instance.
        params["dimensions"] = '[{"instanceId":"' + load_balancer_json["LoadBalancerId"] + '"}]'
        result_json = query_metric_last(params)
        CommonUtil.log("query_metric_last", result_json)
    
        #Create an alarm rule.
        params["metric_name"] = "InstanceQpsUtilization"
        result_json = create_alarm(params)
        CommonUtil.log("create_alarm", result_json)
    
        #Delete an SLB instance.
        #Delete the SLB instance that the returned LoadBalancerId indicates.
        load_balancer_json = delete_load_balancer(load_balancer_json["LoadBalancerId"])
        #Print the returned value of load_balancer_json.
        CommonUtil.log("delete_load_balancer", load_balancer_json)
    
    if __name__ == "__main__":
        sys.exit(main())
  3. Go to the slb_monitor.py directory and run the following command to view monitoring data.
    python slb_monitor.py
    A similar output is displayed:
    ---------------------------create_load_balancer---------------------------
    {
      "VpcId": "",
      "AddressIPVersion": "ipv4",
      "LoadBalancerName": "SLB1",
      "ResourceGroupId": "rg-axxxxxxxxxx",
      "VSwitchId": "",
      "RequestId": "661DDF49-FD2B-46C1-8E38-FDE5E62C8448",
      "Address": "39.xx.xx.xx4",
      "NetworkType": "classic",
      "LoadBalancerId": "lb-8vbtxxxxxxxxxxx1hn"
    }
    
    ---------------------------create_tcp_listener---------------------------
    {
      "RequestId": "7ED453FF-7DF6-4F4F-81A0-670EED9EB997"
    }
    
    ---------------------------add_backend_servers---------------------------
    {
      "RequestId": "4B730606-BD44-4A6B-BE9E-118E9606B064",
      "BackendServers": {
        "BackendServer": [
          {
            "ServerId": "i-8xxxxxxxxxxf4z",
            "Type": "ecs",
            "Weight": 100
          },
          {
            "ServerId": "i-8xxxxxxxxxxxxx",
            "Type": "ecs",
            "Weight": 100
          }
        ]
      },
      "LoadBalancerId": "lb-8xxxxxxxxxxxxxx"
    }
    
    ---------------------------query_metric_last---------------------------
    {
      "Code": "200",
      "Period": "60",
      "RequestId": "15FD2461-FD94-451F-ABE3-D281DB453161",
      "Datapoints": "[]"
    }
    
    ---------------------------create_alarm---------------------------
    {
      "Code": "200",
      "Data": "53547DF14168E368073BE8E34E1522DE25854224",
      "RequestId": "8652E53F-74AD-413B-B2D9-103BFE557FAC",
      "Success": true
    }
    
    ---------------------------delete_load_balancer---------------------------
    {
      "RequestId": "D6CCD259-41C2-4D5C-A644-19A0E96F1D4C"
    }