python python3 腾讯云微服务脚本操控TSF

代码语言:javascript
复制
#!/usr/bin/env python3
# coding=utf-8
# author: wangzi
# mail: 277215243@qq.com
# datetime:2020/4/13 10:36 PM
# web: https://www.bthlt.com


from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tsf.v20180326 import tsf_client, models
import json
import requests

online = 'namespace-******'
qa = 'namespace-******'
dev = 'namespace-******'
tsf_info = dict()
tsf_info['SecretId'] = '**************************'
tsf_info['SecretKey'] = '**************************'
tsf_info['namespace_id'] = online
tsf_info['area'] = 'ap-guangzhou'


class TSF:

    def __init__(self):

        self.cred = credential.Credential(tsf_info['SecretId'], tsf_info['SecretKey'])
        self.httpProfile = HttpProfile()
        self.httpProfile.endpoint = "tsf.tencentcloudapi.com"
        self.clientProfile = ClientProfile()
        self.clientProfile.httpProfile = self.httpProfile
        self.namespace_id = tsf_info['namespace_id']
        self.client = tsf_client.TsfClient(self.cred, tsf_info['area'], self.clientProfile)

    def get_applications(self):
        ret_results = []
        try:
            req = models.DescribeSimpleApplicationsRequest()
            params = '{"Limit":100}'
            req.from_json_string(params)

            resp = self.client.DescribeSimpleApplications(req)
            for group in json.loads(resp.to_json_string())['Result']['Content']:
                ret_results.append({'id': group['ApplicationId'], 'name': group['ApplicationName']})
            return ret_results
        except TencentCloudSDKException as err:
            print(err)
            return ret_results

    def get_container_groups(self):
        ret_results = []
        try:
            req = models.DescribeSimpleGroupsRequest()
            params = '{{"NamespaceId":"{0}","Limit":100}}'.format(self.namespace_id)
            req.from_json_string(params)

            resp = self.client.DescribeSimpleGroups(req)
            # print(resp.to_json_string())
            for group in json.loads(resp.to_json_string())['Result']['Content']:
                ret_results.append({'id': group['GroupId'], 'name': group['GroupName']})
            return ret_results
        except TencentCloudSDKException as err:
            print(err)
            return ret_results

    def get_container_group_detail(self, group_id):

        try:
            req = models.DescribeContainerGroupDetailRequest()

            params = '{{"GroupId":"{0}"}}'.format(group_id)
            req.from_json_string(params)

            resp = self.client.DescribeContainerGroupDetail(req)
            # print(resp.to_json_string())
            return json.loads(resp.to_json_string())['Result']

        except TencentCloudSDKException as err:
            print(err)

    def get_group_id(self, group_name):
        for group in self.get_container_groups():
            if group['name'] == group_name:
                return group['id']
        return ''

    def get_app_id(self, name):
        for app in self.get_applications():
            if app['name'] == name:
                return app['id']
        return ''

    def get_repo_tags(self, app_name):
        ret_results = []

        try:
            req = models.DescribeImageTagsRequest()
            params = '{{"ApplicationId":"{0}","Limit":100}}'.format(self.get_app_id(app_name))
            req.from_json_string(params)

            resp = self.client.DescribeImageTags(req)
            print(resp.to_json_string())
            for repo in json.loads(resp.to_json_string())['Result']['Content']:
                ret_results.append(
                    {'name': repo['RepoName'], 'id': repo['TagId'], 'tag': repo['TagName'],
                     'ctime': repo['CreationTime']})

            ret_results.sort(key=lambda k: (k.get('ctime', 0)))

            return ret_results
        except TencentCloudSDKException as err:
            print(err)

    def stop_container_group(self, group_name):
        try:
            print('停止{0}'.format(group_name))

            group_id = self.get_group_id(group_name)
            req = models.StopContainerGroupRequest()
            params = '{{"GroupId":"{0}"}}'.format(group_id)

            req.from_json_string(params)

            resp = self.client.StopContainerGroup(req)
            print(resp.to_json_string())

        except TencentCloudSDKException as err:
            print(err)

    def start_container_group(self, group_name):
        try:
            print('启动{0}'.format(group_name))
            group_id = self.get_group_id(group_name)

            req = models.StartContainerGroupRequest()
            params = '{{"GroupId":"{0}"}}'.format(group_id)
            req.from_json_string(params)
            resp = self.client.StartContainerGroup(req)
            print(resp.to_json_string())

        except TencentCloudSDKException as err:
            print(err)

    def restart_container_group(self, group_name):
        self.stop_container_group(group_name)
        self.start_container_group(group_name)

    def restart_container_all_group(self):
        groups = self.get_container_groups()
        for group in groups:
            try:
                self.stop_container_group(group['name'])
                self.start_container_group(group['name'])
            except TencentCloudSDKException as err:
                print(err)

    def delete_repo_image(self, name, tag):
        try:
            req = models.DeleteImageTagsRequest()
            params = '{{"ImageTags":[{{"RepoName":"{0}","TagName":"{1}"}}]}}'.format(name, tag)
            req.from_json_string(params)

            resp = self.client.DeleteImageTags(req)
            print(resp.to_json_string())

        except TencentCloudSDKException as err:
            print(err)

    def delete_n_repo_image(self, app_name, delete_num):
        count = 0
        repos = self.get_repo_tags(app_name)
        if len(repos) < 80:
            return

        for repo in repos:
            if count >= delete_num or delete_num <= 0:
                break
            print("{0}删除{1}:{2}".format(app_name, repo['name'], repo['tag']))
            self.delete_repo_image(repo['name'], repo['tag'])
            count += 1

    def delete_all_repo_image(self, delete_num):
        apps = self.get_applications()
        count = 0
        for app in apps:
            if count == 3:
                break
            self.delete_n_repo_image(app['name'], delete_num)
            count += 1

    def deploy_group_repo(self, group_name, tagname=''):
        group_id = self.get_group_id(group_name)
        group = self.get_container_group_detail(group_id)
        app_name = group['ApplicationName']
        namespace_name = group['NamespaceName']
        instance_num = group['InstanceNum']
        envs = group['Envs']
        tag_name = tagname
        java_opts = '-Xms2048m -Xmx3840m -XX:MetaspaceSize=2048m -XX:MaxMetaspaceSize=3840m'
        for env in envs:
            if env['Name'] == 'JAVA_OPTS':
                java_opts = env['Value']
        cpu_request = group['CpuRequest']
        mem_reuqest = group['MemRequest']
        repo = self.get_repo_tags(app_name)[-1]
        repo_name = repo['name']
        if tag_name == '':
            tag_name = repo['tag']

        print('环境:{0}\n部署服务:{1}\n版本: {2}\n发布完成'.format(namespace_name, app_name, tag_name))

        try:
            req = models.DeployContainerGroupRequest()
            params = '{{"GroupId":"{0}","Server":"ccr.ccs.tencentyun.com","Reponame":"{1}","TagName":"{2}",' \
                     '"InstanceNum":{3},"JvmOpts":"{4}","CpuRequest":"{5}","MemRequest":"{6}","UpdateType":1,' \
                     '"UpdateIvl":90}}'.format(group_id, repo_name, tag_name, instance_num, java_opts, cpu_request,
                                               mem_reuqest)
            print(params)
            req.from_json_string(params)

            resp = self.client.DeployContainerGroup(req)
            print(resp.to_json_string())
            if json.loads(resp.to_json_string())['Result']:
                robot_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/' \
                            'send?key=**********************'
                robot_data = {
                    "msgtype": "text",
                    "text": {
                        "content": '环境:{0}\n部署服务:{1}\n版本: {2}\n发布完成'.format(namespace_name, app_name, tag_name)
                    }
                }
                robot_json = json.dumps(robot_data)

                r = requests.post(robot_url, data=robot_json)
                print(r.text)
        except TencentCloudSDKException as err:
            print(err)

    def deploy_all_groups_repo(self):
        groups = self.get_container_groups()
        for group in groups:
            self.deploy_group_repo(self.namespace_id, group['name'])


if __name__ == "__main__":
    tsf_info['namespace_id'] = online
    tsf = TSF()
    pass