longvideoapi_update.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #!/u:sr/bin/env python
  2. #coding=utf-8
  3. #edite panwang
  4. import docker
  5. import sys
  6. import requests
  7. import json
  8. import queue
  9. import threading
  10. from aliyunsdkcore import client
  11. from aliyunsdkess.request.v20140828.DescribeScalingInstancesRequest import DescribeScalingInstancesRequest
  12. from aliyunsdkecs.request.v20140526.DescribeNetworkInterfacesRequest import DescribeNetworkInterfacesRequest
  13. from aliyunsdkcore.request import CommonRequest
  14. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  15. from aliyunsdkslb.request.v20140515.DescribeLoadBalancerAttributeRequest import DescribeLoadBalancerAttributeRequest
  16. import time
  17. AccessKey = 'LTAIuPbTPL3LDDKN'
  18. AccessSecret = 'ORcNedKwWuwVtcq4IRFtUDZgS0b1le'
  19. RegionId = 'cn-hangzhou'
  20. clt = client.AcsClient (AccessKey, AccessSecret, RegionId)
  21. #stress
  22. #slb_id = 'lb-bp12usgpoh04qsa6pw42r'
  23. #longvidleoapi
  24. #id_2 = 'lb-bp1lktzqe3mksoj8whjdf'
  25. id_2 = 'lb-bp1qk9mkvjtundlzz7owm'
  26. # id_3 = 'lb-bp1by407qxe4y7bkvye27'
  27. # id_4 = 'lb-bp1akia6vlguiwg4znaq8'
  28. id_4 = 'lb-bp1y63rnrb2e64whryghz'
  29. id_5 = 'lb-bp1pj2v06ladvgftgxcp0'
  30. class MyThread (threading.Thread):
  31. def __init__(self, func):
  32. threading.Thread.__init__ (self)
  33. self.func = func
  34. def run(self):
  35. self.func ()
  36. #健康检查
  37. def checkHealth(ipadd):
  38. while True:
  39. health_url = 'http://%s:8080/longvideoapi/test' %(ipadd)
  40. header = {"Content-Type":"application/json"}
  41. try:
  42. health_code = requests.get(health_url).status_code
  43. except Exception as e:
  44. continue
  45. if health_code == 200:
  46. return False
  47. #服务更新完之后逐步修改服务器的权重值,直接加载100会出现502。权重值每次增加10,每2s修改一次
  48. def setInstanceWeightProcess(instance_id):
  49. for i in range(1,6):
  50. weight = i*20
  51. setWeight(id_2,instance_id,weight)
  52. # setWeight(id_3,instance_id,weight)
  53. setWeight(id_4,instance_id,weight)
  54. setWeight(id_5,instance_id,weight)
  55. time.sleep(5)
  56. #设置权重 instance_id :服务器id,weight:权重值
  57. def setWeight(slb_id,instance_id ,weight):
  58. BackendServers = [{"ServerId": instance_id, "Weight": weight}]
  59. request = CommonRequest ()
  60. request.set_accept_format ('json')
  61. request.set_domain ('slb.aliyuncs.com')
  62. request.set_version ('2014-05-15')
  63. request.set_method ('POST')
  64. request.set_action_name ('SetBackendServers')
  65. request.add_query_param ('BackendServers', BackendServers)
  66. request.add_query_param ('LoadBalancerId', slb_id)
  67. try:
  68. response = clt.do_action (request)
  69. except Exception as e:
  70. print (e)
  71. #获取slb下所有服务器信息
  72. def getInstanceId(slb_id):
  73. request = DescribeLoadBalancerAttributeRequest()
  74. request.set_accept_format('json')
  75. request.set_LoadBalancerId(slb_id)
  76. response = clt.do_action_with_exception(request)
  77. return json.loads (response)
  78. #获取实例IP地址
  79. def getIpadd(instance_id):
  80. request = DescribeNetworkInterfacesRequest()
  81. request.set_accept_format('json')
  82. request.set_InstanceId(instance_id)
  83. response = clt.do_action_with_exception(request)
  84. request_content = json.loads(response)
  85. IpAddr = request_content['NetworkInterfaceSets']['NetworkInterfaceSet'][0]['PrivateIpAddress']
  86. return IpAddr
  87. #更新服务
  88. def update():
  89. time.sleep(10)
  90. global success_count
  91. apps = 'vlogapi'
  92. version = sys.argv[1]
  93. registry = 'registry-vpc.cn-hangzhou.aliyuncs.com/stuuudy/vlogapi:{}'.format(version)
  94. while not q2.empty():
  95. instance_id = q2.get()
  96. ipadd = getIpadd(instance_id)
  97. print("服务器信息:" + "%s/%s" %(instance_id, ipadd))
  98. client = docker.DockerClient(base_url='tcp://%s:2375' %(ipadd),timeout=60 )
  99. try:
  100. #更新前移除旧的容器
  101. id = client.containers.get(apps)
  102. id.remove(force = True)
  103. except Exception as e:
  104. print("容器不存在或者无法删除当前容器")
  105. try:
  106. #更新前删除旧的镜像
  107. images = client.images.list(all)
  108. for i in range(len(images)):
  109. if images[i]:
  110. client.images.remove(force=True, image=images[i].tags[0])
  111. time.sleep(2)
  112. #images = client.images.get(registry)
  113. #client.images.remove(force=True, image=registry)
  114. except Exception as e:
  115. print(e)
  116. print("镜像不存在,无法获取到镜像ID")
  117. sys.exit(0)
  118. try:
  119. #登录镜像仓库
  120. client.login(username='stuuudys' ,password='Qingqu@2019', registry='registry-vpc.cn-hangzhou.aliyuncs.com')
  121. #启动一个容器
  122. client.containers.run(registry, detach = True, cap_add = 'SYS_PTRACE', network_mode = 'host', name = apps,volumes={'/datalog/': {'bind': '/datalog/', 'mode': 'rw'}})
  123. checkHealth(ipadd)
  124. print("%s :权重修改中......" %(ipadd))
  125. setInstanceWeightProcess(instance_id)
  126. success_count = success_count + 1
  127. print("更新进度" + "%s/%s" %(success_count, total))
  128. except Exception as e:
  129. raise e
  130. sys.exit()#容器启动失败立即退出更新
  131. if __name__ == '__main__':
  132. #更新完成计数
  133. success_count = 0
  134. threads = []
  135. thread_num = 1
  136. res = getInstanceId (id_2)
  137. #slb下服务器总数
  138. total = len(res["BackendServers"]["BackendServer"])
  139. q1 = queue.Queue()
  140. q2 = queue.Queue()
  141. if res["BackendServers"]["BackendServer"]:
  142. for i in range ((len (res["BackendServers"]["BackendServer"]))):
  143. instance_id = res["BackendServers"]["BackendServer"][i]["ServerId"]
  144. q1.put(instance_id)
  145. while not q1.empty():
  146. for i in range (thread_num ):
  147. if q1.empty():
  148. break
  149. instance_id = q1.get ()
  150. setWeight (id_2,instance_id, 0)
  151. # setWeight (id_3,instance_id, 0)
  152. setWeight (id_4,instance_id, 0)
  153. setWeight (id_5,instance_id, 0)
  154. q2.put(instance_id)
  155. for i in range (thread_num ):
  156. # 开启线程
  157. thread = MyThread (update)
  158. thread.start ()
  159. threads.append(thread)
  160. for thread in threads:
  161. thread.join ()