Jelajahi Sumber

add gateway

xuekailun 5 bulan lalu
induk
melakukan
7cb562c257
2 mengubah file dengan 317 tambahan dan 0 penghapusan
  1. 177 0
      gateway/gateway_config.py
  2. 140 0
      gateway/gateway_update.py

+ 177 - 0
gateway/gateway_config.py

@@ -0,0 +1,177 @@
+import os
+import logging
+
+logging.basicConfig(level=logging.INFO,
+                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
+                    datefmt='%a, %d %b %Y %H:%M:%S')
+
+server_group_id_list = ["sgp-l2k0p33e470vfmj538"]
+apps = 'piaoquan-gateway'
+repository = 'registry-vpc.cn-hangzhou.aliyuncs.com/stuuudy/{}'.format(apps)
+registry = 'registry-vpc.cn-hangzhou.aliyuncs.com/stuuudy/{}:{}'.format(apps, version)
+
+# 修改负载均衡权限
+alb_client_params = {
+    'access_key_id': 'LTAI5tASD5yEZLeC8ffmNebY',
+    'access_key_secret': '1PtsFRdp8viJmI78lEhNZR8MezWZBq',
+    'region_id': 'cn-hangzhou'
+}
+# 购买机器权限
+ecs_client_params = {
+    'access_key_id': 'LTAI4GBWbFvvXoXsSVBe1o9f',
+    'access_key_secret': 'kRAikWitb4kDxaAyBqNrmLmllMEDO3',
+    'region_id': 'cn-hangzhou'
+}
+
+docker_config = {
+    'username': 'stuuudys',
+    'password': 'Qingqu@2019',
+    'registry': 'registry-vpc.cn-hangzhou.aliyuncs.com'
+}
+# 机器配置
+instance_config = {
+    # 使用的镜像信息
+    'image_id': 'm-bp12bkuvg20k6ueqmb4v',
+    # 设置实例规格
+    'instance_type': 'ecs.c6.2xlarge',
+    # 选择的交换机
+    'vswitch_id': 'vsw-bp19lpjwtc6j0p0m9mdc2',
+    # 当前VPC类型的安全组
+    'security_group_id': 'sg-bp1irhrkr4vfj272hk4y',
+    # 硬盘的大小,单位:G
+    'disk_size': '200',
+    # 服务器命名
+    'instance_name': 'ESS-vlogapi-[1,2]',
+    # 服务器所在区域
+    'zone_id': 'cn-hangzhou-h',
+    # 磁盘类型:云盘
+    'disk_category': 'cloud_efficiency',
+    # 密钥
+    'key_pair_name': 'stuuudy',
+    # tag
+    'tags': [{"Key": "ecs", "Value": "longvideoapi.prod"}]
+}
+
+# 机器配置_hangzhou_i
+instance_config_i = {
+    # 使用的镜像信息
+    'image_id': 'm-bp12bkuvg20k6ueqmb4v',
+    # 设置实例规格
+    'instance_type': 'ecs.c6.2xlarge',
+    # 选择的交换机
+    'vswitch_id': 'vsw-bp17c002ovyomzwnhhdhj',
+    # 当前VPC类型的安全组
+    'security_group_id': 'sg-bp1irhrkr4vfj272hk4y',
+    # 硬盘的大小,单位:G
+    'disk_size': '200',
+    # 服务器命名
+    'instance_name': 'ESS-vlogapi-[1,2]',
+    # 服务器所在区域
+    'zone_id': 'cn-hangzhou-i',
+    # 磁盘类型:云盘
+    'disk_category': 'cloud_efficiency',
+    # 密钥
+    'key_pair_name': 'stuuudy',
+    # tag
+    'tags': [{"Key": "ecs", "Value": "longvideoapi.prod"}]
+}
+
+# 机器配置_hangzhou_g
+instance_config_g = {
+    # 使用的镜像信息
+    'image_id': 'm-bp12bkuvg20k6ueqmb4v',
+    # 设置实例规格
+    'instance_type': 'ecs.c6.2xlarge',
+    # 选择的交换机
+    'vswitch_id': 'vsw-bp10m69sb9ydfa64jdrn3',
+    # 当前VPC类型的安全组
+    'security_group_id': 'sg-bp1irhrkr4vfj272hk4y',
+    # 硬盘的大小,单位:G
+    'disk_size': '200',
+    # 服务器命名
+    'instance_name': 'ESS-vlogapi-[1,2]',
+    # 服务器所在区域
+    'zone_id': 'cn-hangzhou-g',
+    # 磁盘类型:云盘
+    'disk_category': 'cloud_efficiency',
+    # 密钥
+    'key_pair_name': 'stuuudy',
+    # tag
+    'tags': [{"Key": "ecs", "Value": "longvideoapi.prod"}]
+}
+
+# 机器配置_hangzhou_j
+instance_config_j = {
+    # 使用的镜像信息
+    'image_id': 'm-bp12bkuvg20k6ueqmb4v',
+    # 设置实例规格
+    'instance_type': 'ecs.c6.2xlarge',
+    # 选择的交换机
+    'vswitch_id': 'vsw-bp1ssuwxyrt0p17ceeir0',
+    # 当前VPC类型的安全组
+    'security_group_id': 'sg-bp1irhrkr4vfj272hk4y',
+    # 硬盘的大小,单位:G
+    'disk_size': '200',
+    # 服务器命名
+    'instance_name': 'ESS-vlogapi-[1,2]',
+    # 服务器所在区域
+    'zone_id': 'cn-hangzhou-j',
+    # 磁盘类型:云盘
+    'disk_category': 'cloud_efficiency',
+    # 密钥
+    'key_pair_name': 'stuuudy',
+    # tag
+    'tags': [{"Key": "ecs", "Value": "longvideoapi.prod"}]
+}
+
+# 机器配置_hangzhou_k
+instance_config_k = {
+    # 使用的镜像信息
+    'image_id': 'm-bp12bkuvg20k6ueqmb4v',
+    # 设置实例规格
+    'instance_type': 'ecs.c6.2xlarge',
+    # 选择的交换机
+    'vswitch_id': 'vsw-bp14e4xu6uzte9nyn6nvr',
+    # 当前VPC类型的安全组
+    'security_group_id': 'sg-bp1irhrkr4vfj272hk4y',
+    # 硬盘的大小,单位:G
+    'disk_size': '200',
+    # 服务器命名
+    'instance_name': 'ESS-longvideoapi-alb-[1,2]',
+    # 服务器所在区域
+    'zone_id': 'cn-hangzhou-k',
+    # 磁盘类型:云盘
+    'disk_category': 'cloud_efficiency',
+    # 密钥
+    'key_pair_name': 'stuuudy',
+    # tag
+    'tags': [{"Key": "ecs", "Value": "longvideoapi.prod"}]
+}
+
+# 机器配置_hangzhou_k alb
+instance_config_k_alb = {
+    # 使用的镜像信息
+    'image_id': 'm-bp12bkuvg20k6ueqmb4v',
+    # 设置实例规格
+    'instance_type': 'ecs.c6.2xlarge',
+    # 选择的交换机
+    'vswitch_id': 'vsw-bp14e4xu6uzte9nyn6nvr',
+    # 当前VPC类型的安全组
+    'security_group_id': 'sg-bp1irhrkr4vfj272hk4y',
+    # 硬盘的大小,单位:G
+    'disk_size': '200',
+    # 服务器命名
+    'instance_name': 'ESS-vlogapi-alb-[1,2]',
+    # 服务器所在区域
+    'zone_id': 'cn-hangzhou-k',
+    # 磁盘类型:云盘
+    'disk_category': 'cloud_efficiency',
+    # 密钥
+    'key_pair_name': 'stuuudy',
+    # tag
+    'tags': [{"Key": "ecs", "Value": "longvideoapi.prod"}]
+}
+
+
+
+

+ 140 - 0
gateway/gateway_update.py

@@ -0,0 +1,140 @@
+#!/bin/env python
+# coding=utf-8
+# edite  panwang
+import docker
+import sys
+import requests
+import json
+import queue
+import threading
+import time
+from aliyunsdkcore import client
+from aliyunsdkecs.request.v20140526.DescribeNetworkInterfacesRequest import DescribeNetworkInterfacesRequest
+import gateway_config
+import utils
+
+# 从配置文件中获取应用程序名称和容器仓库地址
+apps = gateway_config.apps
+repository = gateway_config.repository
+version = sys.argv[1]  # 从命令行参数获取版本号
+
+
+class MyThread(threading.Thread):
+    def __init__(self, func):
+        threading.Thread.__init__(self)
+        self.func = func
+
+    def run(self):
+        self.func()
+
+
+def checkHealth(ipadd):
+
+    while True:
+        health_url = 'http://%s:9000/healthcheck' % (ipadd)
+        header = {"Content-Type": "application/json"}
+        try:
+            health_code = requests.get(health_url).status_code
+        except Exception as e:
+            continue  # 如果请求失败,继续重试
+        if health_code == 200:
+            print("httpcode 200,开始挂载流量")
+            return False  # 健康检查通过,返回
+
+
+def update(instance_id):
+
+    time.sleep(10)  # 等待10秒钟
+    global success_count
+
+    ipadd = utils.get_ip_address(ecs_client, instance_id)  # 使用 utils 获取实例的 IP 地址
+    print("服务器信息:" + "%s/%s" % (instance_id, ipadd))
+    client = docker.DockerClient(base_url='tcp://%s:2375' % (ipadd), timeout=60)
+
+    # 尝试删除旧的容器
+    try:
+        id = client.containers.get(apps)
+        id.remove(force=True)
+    except Exception as e:
+        print("容器不存在或者无法删除当前容器")
+
+    # 尝试登录并启动新的容器
+    try:
+        # 使用 gateway_config 中的 Docker 登录配置
+        docker_config = gateway_config.docker_config
+        client.login(username=docker_config['username'], password=docker_config['password'],
+                     registry=docker_config['registry'])
+        client.containers.run(repository, detach=True, cap_add='SYS_PTRACE', network_mode='host', name=apps,
+                              volumes={'/datalog/': {'bind': '/datalog/', 'mode': 'rw'}})
+        print("开始健康检查")
+        checkHealth(ipadd)
+        print("%s :权重修改中......" % (ipadd))
+
+        weight_list = [(10, 5), (20, 5), (40, 5), (60, 5), (80, 5), (100, 5)]
+        for server_group_id in gateway_config.server_group_id_list:
+            utils.set_instance_weight_process_with_alb(alb_client, [server_group_id],   [instance_id], weight_list)
+
+        success_count += 1
+        print("更新进度" + "%s/%s" % (success_count, total))
+    except Exception as e:
+        print(e)
+        sys.exit()
+
+
+def pull_image():
+    """从镜像仓库中拉取指定版本的镜像"""
+    instanceId = q1.get()
+    ipaddr = utils.get_ip_address(ecs_client, instanceId)
+    cd_url = "tcp://{}:2375".format(ipaddr)
+    client = docker.DockerClient(base_url=cd_url, timeout=30)
+
+    try:
+        client.images.pull(repository, tag=version)
+        print(ipaddr, "pull images success ")
+        return True
+    except Exception as e:
+        print(e, "images pull fail")
+        return False
+
+
+if __name__ == '__main__':
+    # 初始化 ECS 客户端
+    ecs_client = utils.connect_client(access_key_id=gateway_config.ecs_client_params['access_key_id'],
+                                      access_key_secret=gateway_config.ecs_client_params['access_key_secret'],
+                                      region_id=gateway_config.ecs_client_params['region_id'])
+
+    # 初始化 ALB 客户端
+    alb_client = utils.connect_alb_client(gateway_config.alb_client_params['access_key_id'],
+                                          gateway_config.alb_client_params['access_key_secret'])
+
+    success_count = 0
+    threads = []
+    total = 0
+    InstanceIDs = []
+    q1 = queue.Queue()
+
+    # 获取 ALB 下服务器组的实例 ID
+    res = utils.get_instance_ids(alb_client=alb_client, server_group_id=gateway_config.server_group_id_list[0])
+    total += len(res)
+    InstanceIDs.extend(res)
+    print(InstanceIDs)
+
+    # 将实例 ID 放入队列中
+    for instance_id in InstanceIDs:
+        q1.put(instance_id)
+
+    # 多线程预先拉取镜像
+    for i in range(len(InstanceIDs)):
+        thread = MyThread(pull_image)
+        thread.start()
+        threads.append(thread)
+
+    for thread in threads:
+        thread.join()
+
+    # 更新每个实例
+    for instanceID in InstanceIDs:
+        for server_group_id in gateway_config.server_group_id_list:
+            utils.set_instance_weight_process_with_alb(alb_client, [server_group_id], [instanceID],
+                                                       [(0, 5)])  # 设置初始权重为0
+        update(instanceID)