#!/usr/bin/python
# coding: utf-8
import sys
from aliyunsdkcore import client
from aliyunsdkcore.request import CommonRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkslb.request.v20140515.DescribeLoadBalancerAttributeRequest import DescribeLoadBalancerAttributeRequest
import json
import socket

AccessKey = 'LTAIuPbTPL3LDDKN'
AccessSecret = 'ORcNedKwWuwVtcq4IRFtUDZgS0b1le'
RegionId = 'cn-hangzhou'
slb_id= 'lb-bp1d6hp2ctotgt870miav'
weight_instance = 0
# slb_id= 'lb-bp12usgpoh04qsa6pw42r'

clt = client.AcsClient (AccessKey, AccessSecret, RegionId)
Host = socket.gethostname ()

def setServerWeight(BackendServers):
    request = CommonRequest ()
    request.set_accept_format ('json')
    request.set_domain ('slb.aliyuncs.com')
    request.set_version ('2014-05-15')
    request.set_method ('POST')
    request.set_action_name ('SetBackendServers')
    request.add_query_param ('BackendServers', BackendServers)
    request.add_query_param ('LoadBalancerId', slb_id)
    response = clt.do_action (request)
    return json.loads (response)

def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
        # ip = '192.168.204.111'
    finally:
        s.close()
        return ip


def  check_slb_weight(instance_id):
    global   weight_instance
    request = DescribeLoadBalancerAttributeRequest ()
    request.set_accept_format ('json')
    request.set_LoadBalancerId (slb_id)
    response = clt.do_action_with_exception (request)
    result= json.loads (response)
    if  result["BackendServers"]["BackendServer"]:
        for i  in  range(len( result["BackendServers"]["BackendServer"])):
            if   instance_id == result["BackendServers"]["BackendServer"][i]["ServerId"]:
                weight_instance =  result["BackendServers"]["BackendServer"][i]["Weight"]
    return weight_instance
if __name__ == "__main__":

    ip_add = []
    ip_add.append(get_host_ip())
    request = DescribeInstancesRequest ()
    #request.set_PublicIpAddresses (ip_add)
    request.set_PrivateIpAddresses (ip_add)


    response = clt.do_action_with_exception (request)
    result = json.loads(response)
    
    instance_id = result["Instances"]["Instance"][0]["InstanceId"]
    print(instance_id)
    back_servers = [{"ServerId": '', "Weight": ''}]
    back_servers[0]["ServerId"] = instance_id
    back_servers[0]["Weight"] = sys.argv[1]
    print(back_servers)

    setServerWeight ( back_servers)
    weight_instance = check_slb_weight(instance_id)
    if weight_instance != back_servers[0]["Weight"]:
        setServerWeight ( back_servers)




