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

AccessKey = 'LTAIuPbTPL3LDDKN'
AccessSecret = 'ORcNedKwWuwVtcq4IRFtUDZgS0b1le'
RegionId = 'cn-hangzhou'
SlbId = 'lb-bp1xmaogphakz0l1o13mu'

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', SlbId)
    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]
    finally:
        s.close()
        return ip

if __name__ == "__main__":

    ip_add = []
    ip_add.append(get_host_ip())
    request = DescribeInstancesRequest ()
    request.set_PublicIpAddresses (ip_add)
    response = clt.do_action_with_exception (request)
    result = json.loads(response)
    instance_id = result["Instances"]["Instance"][0]["InstanceId"]
    back_servers = [{"ServerId": '', "Weight": ''}]
    back_servers[0]["ServerId"] = instance_id.encode('utf-8')
    back_servers[0]["Weight"] = sys.argv[1]
    print(back_servers)
    setServerWeight ( back_servers)


