gateway_update.py 4.8 KB

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