gateway_update.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. # weight_list = [(10, 10), (20, 10), (40, 10), (60, 10), (80, 10), (100, 10)]
  58. 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)
  59. success_count += 1
  60. print("更新进度" + "%s/%s" % (success_count, total))
  61. except Exception as e:
  62. print(e)
  63. sys.exit()
  64. def pull_image():
  65. """从镜像仓库中拉取指定版本的镜像"""
  66. instanceId = q1.get()
  67. ipaddr = utils.get_ip_address(ecs_client, instanceId)
  68. cd_url = "tcp://{}:2375".format(ipaddr)
  69. client = docker.DockerClient(base_url=cd_url, timeout=30)
  70. try:
  71. client.images.pull(repository.format(apps), tag=version) #
  72. print(ipaddr, "pull images success ")
  73. return True
  74. except Exception as e:
  75. print(e, "images pull fail")
  76. return False
  77. if __name__ == '__main__':
  78. # 初始化 ECS 客户端
  79. ecs_client = utils.connect_client(access_key_id=gateway_config.ecs_client_params['access_key_id'],
  80. access_key_secret=gateway_config.ecs_client_params['access_key_secret'],
  81. region_id=gateway_config.ecs_client_params['region_id'])
  82. # 初始化 ALB 客户端
  83. alb_client = utils.connect_alb_client(gateway_config.alb_client_params['access_key_id'],
  84. gateway_config.alb_client_params['access_key_secret'],
  85. endpoint=gateway_config.alb_client_params['endpoint']
  86. )
  87. success_count = 0
  88. threads = []
  89. total = 0
  90. InstanceIDs = []
  91. q1 = queue.Queue()
  92. # 获取 ALB 下服务器组的实例 ID
  93. res = utils.list_server_group_servers(alb_client=alb_client, server_group_id=gateway_config.server_group_id_list[0])
  94. total += len(res)
  95. print(f"获取 ALB 下服务器组的实例 ID = {res} total = {total}")
  96. InstanceIDs.extend(res)
  97. print(InstanceIDs)
  98. # 将实例 ID 放入队列中
  99. for instance_id in InstanceIDs:
  100. q1.put(instance_id)
  101. # 多线程预先拉取镜像
  102. for i in range(len(InstanceIDs)):
  103. thread = MyThread(pull_image)
  104. thread.start()
  105. threads.append(thread)
  106. for thread in threads:
  107. thread.join()
  108. # 更新每个实例
  109. for instanceID in InstanceIDs:
  110. for server_group_id in gateway_config.server_group_id_list:
  111. utils.update_server_group_server_weight(alb_client, server_group_id, instanceID,
  112. weight=0, port=gateway_config.port) # 设置初始权重为0
  113. update(instanceID, port=gateway_config.port)