gateway_update.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #!/bin/env python
  2. # coding=utf-8
  3. import docker
  4. import sys
  5. import requests
  6. import json
  7. import queue
  8. import threading
  9. import time
  10. from aliyunsdkcore import client
  11. from aliyunsdkecs.request.v20140526.DescribeNetworkInterfacesRequest import DescribeNetworkInterfacesRequest
  12. import gateway_config
  13. import alb_utils
  14. # 从配置文件中获取应用程序名称和容器仓库地址
  15. apps = gateway_config.apps
  16. repository = gateway_config.repository
  17. registry = gateway_config.registry
  18. version = sys.argv[1] # 从命令行参数获取版本号
  19. class MyThread(threading.Thread):
  20. def __init__(self, func):
  21. threading.Thread.__init__(self)
  22. self.func = func
  23. def run(self):
  24. self.func()
  25. def checkHealth(ipadd):
  26. while True:
  27. health_url = 'http://%s:9000/healthcheck' % (ipadd)
  28. header = {"Content-Type": "application/json"}
  29. try:
  30. health_code = requests.get(health_url).status_code
  31. except Exception as e:
  32. continue # 如果请求失败,继续重试
  33. if health_code == 200:
  34. print("httpcode 200,开始挂载流量")
  35. return False # 健康检查通过,返回
  36. def update(instance_id):
  37. time.sleep(10) # 等待10秒钟
  38. global success_count
  39. ipadd = alb_utils.get_ip_address(ecs_client, instance_id) # 使用 utils 获取实例的 IP 地址
  40. print("服务器信息:" + "%s/%s" % (instance_id, ipadd))
  41. client = docker.DockerClient(base_url='tcp://%s:2375' % (ipadd), timeout=60)
  42. # 尝试删除旧的容器
  43. try:
  44. id = client.containers.get(apps)
  45. id.remove(force=True)
  46. except Exception as e:
  47. print("容器不存在或者无法删除当前容器")
  48. # 尝试登录并启动新的容器
  49. try:
  50. # 使用 gateway_config 中的 Docker 登录配置
  51. docker_config = gateway_config.docker_config
  52. client.login(username=docker_config['username'], password=docker_config['password'],
  53. registry=docker_config['registry'])
  54. client.containers.run(registry.format(apps, version), detach=True, cap_add='SYS_PTRACE', network_mode='host', name=apps,
  55. volumes={'/datalog/': {'bind': '/datalog/', 'mode': 'rw'}})
  56. print("开始健康检查")
  57. checkHealth(ipadd)
  58. print("%s :权重修改中......" % (ipadd))
  59. weight_list = [(10, 5), (20, 5), (40, 5), (60, 5), (80, 5), (100, 5)]
  60. for server_group_id in gateway_config.server_group_id_list:
  61. alb_utils.update_server_group_servers_attribute(alb_client, [server_group_id], [instance_id], weight_list)
  62. success_count += 1
  63. print("更新进度" + "%s/%s" % (success_count, total))
  64. except Exception as e:
  65. print(e)
  66. sys.exit()
  67. def pull_image():
  68. """从镜像仓库中拉取指定版本的镜像"""
  69. instanceId = q1.get()
  70. ipaddr = alb_utils.get_ip_address(ecs_client, instanceId)
  71. cd_url = "tcp://{}:2375".format(ipaddr)
  72. client = docker.DockerClient(base_url=cd_url, timeout=30)
  73. try:
  74. client.images.pull(repository.format(apps), tag=version) #
  75. print(ipaddr, "pull images success ")
  76. return True
  77. except Exception as e:
  78. print(e, "images pull fail")
  79. return False
  80. if __name__ == '__main__':
  81. # 初始化 ECS 客户端
  82. ecs_client = alb_utils.connect_client(access_key_id=gateway_config.ecs_client_params['access_key_id'],
  83. access_key_secret=gateway_config.ecs_client_params['access_key_secret'],
  84. region_id=gateway_config.ecs_client_params['region_id'])
  85. # 初始化 ALB 客户端
  86. alb_client = alb_utils.connect_alb_client(gateway_config.alb_client_params['access_key_id'],
  87. gateway_config.alb_client_params['access_key_secret'],
  88. endpoint=gateway_config.alb_client_params['endpoint']
  89. )
  90. success_count = 0
  91. threads = []
  92. total = 0
  93. InstanceIDs = []
  94. q1 = queue.Queue()
  95. # 获取 ALB 下服务器组的实例 ID
  96. res = alb_utils.list_server_group_servers(alb_client=alb_client, server_group_id=gateway_config.server_group_id_list[0])
  97. total += len(res)
  98. InstanceIDs.extend(res)
  99. print(InstanceIDs)
  100. # 将实例 ID 放入队列中
  101. for instance_id in InstanceIDs:
  102. q1.put(instance_id)
  103. # 多线程预先拉取镜像
  104. for i in range(len(InstanceIDs)):
  105. thread = MyThread(pull_image)
  106. thread.start()
  107. threads.append(thread)
  108. for thread in threads:
  109. thread.join()
  110. # 更新每个实例
  111. for instanceID in InstanceIDs:
  112. for server_group_id in gateway_config.server_group_id_list:
  113. alb_utils.update_server_group_servers_attribute(alb_client, [server_group_id], [instanceID],
  114. [(0, 20)]) # 设置初始权重为0
  115. update(instanceID)