#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import  socket
import  json
import   docker
import time

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkslb.request.v20140515.AddBackendServersRequest import AddBackendServersRequest


AccessKey = 'LTAIuPbTPL3LDDKN'
AccessSecret = 'ORcNedKwWuwVtcq4IRFtUDZgS0b1le'
RegionId = 'cn-hangzhou'

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

slb_id = {
          'test':'lb-bp1r9duz4k7z0riz9zs3n'
         }

docker_name = {'test':'vlogapi',
               'vlogapi':'vlogapi',
               'longvideoapi':'vlogapi',
               'commonapi':'commonapi'
              }

health_check_name = {'test':'longvideoapi',
               'vlogapi':'longvideoapi',
               'longvideoapi':'longvideoapi',
               'commonapi':'commonapi'
              }

def getIpaddr():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ipaddr = s.getsockname()[0]
    finally:
        s.close()
        return ipaddr


def  getTag():
     ipadd = []
     ipadd.append(getIpaddr())
     request = DescribeInstancesRequest()
     request.set_accept_format('json')
     request.set_PrivateIpAddresses(ipadd)

     response = client.do_action_with_exception(request)
     print(str(response, encoding='utf-8'))
     res = json.loads(response)
     tag = res["Instances"]["Instance"][0]["Tags"]["Tag"][0]["TagValue"]

     return  tag

def  run(apps):
    i_name = docker_name.get(apps)
    images = "registry-vpc.cn-hangzhou.aliyuncs.com/stuuudy/" + i_name + ":latest"
    client = docker.DockerClient(base_url='tcp://localhost:2375' ,timeout=60 )
    c_name = docker_name.get(apps)
    try:
        client.containers.run(images,restart_policy={"Name": "always", "MaximumRetryCount": 5},name=c_name,cap_add="SYS_PTRACE",network_mode="host")

    except Exception as e:
        print(e)


def  healthCheck(apps):


    healcheck_apps = health_check_name.get(apps)
    health_url = 'http://localhost:8182/%s/test' %(healcheck_apps)
    print(health_url)
    try:
        http_code = requests.get(health_url).status_code
        return http_code
    except  Exception  as e:
        print(e)

def getInstanceId():
    request = DescribeInstancesRequest()
    request.set_accept_format('json')
    ipaddr = []
    request.set_PrivateIpAddresses(ipaddr.append(getIpaddr()))

    response = client.do_action_with_exception(request)
    result = json.loads(response)
    instanceId = result["Instances"]["Instance"][0]["InstanceId"]
    return instanceId

def  addBackendServers(apps):
    request = AddBackendServersRequest()
    request.set_accept_format('json')
    ipaddr = getIpaddr()
    instanceId = getInstanceId()
    slb = slb_id.get(apps)
    request.set_LoadBalancerId(slb)
    request.set_BackendServers([{ "ServerId": instanceId, "Weight": "100", "Type": "ecs", "ServerIp": ipaddr}])

    response = client.do_action_with_exception(request)
    print(str(response, encoding='utf-8'))
if __name__ == "__main__":

    apps = getTag()
    run(apps)
    time.sleep(60)

    while  times < 30:
        try:
            http_code = healthCheck(apps)
            if  http_code == 200:
                break
            else:
                time.sleep(2)
                times += 1
        except Exception as e:
            print(e)

    
