美文网首页Aliyun
Aliyun - Swarm Cluster Client

Aliyun - Swarm Cluster Client

作者: 红薯爱帅 | 来源:发表于2019-12-11 19:52 被阅读0次

1. 概述

Aliyun将于20191231停止SwarmPortal的技术支持,如何完成日后aliyun swarm cluster的维护,准备了一个脚本,可以完成template的更新。如果需要登录到docker container,可以登录到node完成;如果需要查看日志,可以通过logstore完成。

2. 参考文档

3. 使用说明

安装依赖

$ python3 aliyun_cs.py
Welcome to the aliyun cluster service shell. Type help or ? to list commands.
[malong clusters]# ?

Documented commands (type help <topic>):
========================================
bye  clusters  help  projects  select

[malong clusters]# ? clusters

        Get clusters list: clusters
        or get a cluster details: clusters <cluster_id>

[malong clusters]# ? select

        Select a cluster: select <cluster_id>

[malong clusters]# ? projects

        Get projects list: projects
        or get a project details: projects <project_name>
        or update a project template: projects <project_name> update <new_project_version> <new_project_template_filepath>

4. 代码奉上

import cmd, shlex, subprocess, json, requests
from functools import partial
from subprocess import check_call as _call


call = partial(_call, shell=True)


def exec_cmd(command_line):
    try:
        args = shlex.split(command_line)
        # res = subprocess.run(args, stdout=subprocess.PIPE)
        res = subprocess.check_output(args, encoding='utf8')
        data = json.loads(res)
    except Exception as e:
        print(e)
        return None  # todo should abort
    return data


class AliyunClusterInfo(object):
    name = None
    cluster_id = None
    region_id = None
    state = None
    master_url = None
    cluster_type = None
    created = None
    updated = None
    ca_pem_file = None
    cert_pem_file = None
    key_pem_file = None

    def __repr__(self):
        return f'{self.name:30} {self.cluster_id:33} {self.cluster_type:10} {self.state:10} {self.region_id:11} {self.updated:25}'

    @classmethod
    def from_dict(cls, data):
        info = cls()
        info.__dict__ = data
        return info


def get_clusters():
    data = exec_cmd('aliyun cs GET /clusters')
    clusters = [AliyunClusterInfo.from_dict(item) for item in data]
    clusters = sorted(clusters, key=lambda x: x.name)
    clusters = filter(lambda x: x.cluster_type == 'aliyun', clusters)  # ignore ManagedKubernetes
    return clusters


def get_a_cluster(cluster_id):
    return exec_cmd(f'aliyun cs GET /clusters/{cluster_id}')


def select_a_cluster(cluster_id):
    ca_pem_file = f'.certs/{cluster_id}.ca.pem'
    cert_pem_file = f'.certs/{cluster_id}.cert.pem'
    key_pem_file = f'.certs/{cluster_id}.key.pem'

    call(f'[ -d .certs ] || mkdir .certs')
    call(f'''[ -f {ca_pem_file} ] || aliyun cs GET /clusters/{cluster_id}/certs | jq '.ca' | sed 's/"//g' | sed 's/\\\\n/\\n/g' > {ca_pem_file}''')
    call(f'''[ -f {cert_pem_file} ] || aliyun cs GET /clusters/{cluster_id}/certs | jq '.cert' | sed 's/"//g' | sed 's/\\\\n/\\n/g' > {cert_pem_file}''')
    call(f'''[ -f {key_pem_file} ] || aliyun cs GET /clusters/{cluster_id}/certs | jq '.key' | sed 's/"//g' | sed 's/\\\\n/\\n/g' > {key_pem_file}''')

    data = get_a_cluster(cluster_id)
    cluster_info = AliyunClusterInfo.from_dict(data)
    cluster_info.ca_pem_file = ca_pem_file
    cluster_info.cert_pem_file = cert_pem_file
    cluster_info.key_pem_file = key_pem_file
    return cluster_info


def get_projects(cluster_info: AliyunClusterInfo, project_name=None):
    request_url = f'{cluster_info.master_url}/projects/?services=true&containers=true&q={project_name}' \
        if project_name else f'{cluster_info.master_url}/projects/?services=true&containers=true'
    res = requests.get(request_url,
                       verify=cluster_info.ca_pem_file,
                       cert=(cluster_info.cert_pem_file, cluster_info.key_pem_file))
    my_projects = list(filter(lambda x: not x['name'].startswith('acs'), res.json()))
    return my_projects


def update_a_project_template(cluster_info: AliyunClusterInfo, project_name, new_version, new_template):
    body = {'template': new_template, 'version': new_version}
    request_url = f'{cluster_info.master_url}/projects/{project_name}/update'
    resp = requests.post(
        request_url, json=body, verify=cluster_info.ca_pem_file,
        cert=(cluster_info.cert_pem_file, cluster_info.key_pem_file))

    if resp.status_code == 202:
        print(f'Project {project_name} in {cluster_info.name}({cluster_info.cluster_id}) updated to version {new_version} success.')
    else:
        print(f'ERROR: Fail to update project {project_name} in {cluster_info.name}({cluster_info.cluster_id}) due to:')
        print(resp.status_code)
        print(resp.text)


class AliyunCsShell(cmd.Cmd):
    intro = 'Welcome to the aliyun cluster service shell. Type help or ? to list commands.'
    prompt = '[malong clusters]# '

    def __init__(self):
        super().__init__()
        self.cluster_info: AliyunClusterInfo = None

    def do_select(self, arg):
        """
        Select a cluster: select <cluster_id>
        """
        if len(arg) != 33:
            print(f'{arg} error, should be a valid cluster_id')
            return

        self.cluster_info = select_a_cluster(arg)
        print('select cluster_id success')

    def do_clusters(self, arg):
        """
        Get clusters list: clusters
        or get a cluster details: clusters <cluster_id>
        """
        if not arg:
            print(f"{'='*40}Clusters Table{'='*40}")
            clusters = get_clusters()
            for item in clusters:
                print(item)
        else:
            if len(arg) != 33:  # the length of cluster_id should be 33
                print(f'cluster_id {arg} error')
                return
            print(f"{'='*40}Cluster {arg} Details{'='*40}")
            data = get_a_cluster(arg)
            print(json.dumps(data, indent=4))

    def do_projects(self, arg):
        """
        Get projects list: projects
        or get a project details: projects <project_name>
        or update a project template: projects <project_name> update <new_project_version> <new_project_template_filepath>
        """
        if not self.cluster_info:
            print(f'Please select cluster_id first')
            return

        args = arg.split() if arg else []
        if not args:
            my_projects = get_projects(self.cluster_info)

            print(f"{'='*40}Projects Details{'='*40}")
            print(json.dumps(my_projects, indent=4))

            print(f"{'='*40}Projects Summary{'='*40}")
            print(f'my projects num: {len(my_projects)}')
            print(f'my projects:')
            for proj in my_projects:
                print(f"{proj['name']:40} {proj['version']:10} {proj['current_state']:10} {proj['updated']}")
        elif len(args) == 1:
            project_name = args[0]
            print(f"{'='*40}Project {project_name} Template{'='*40}")
            projects = get_projects(self.cluster_info, project_name=project_name)
            if not projects:
                print(f'not exists project: {project_name}')
                return
            for proj in projects:
                print(f"{'=' * 20}cluster_id: {self.cluster_info.cluster_id}, cluster_name: {self.cluster_info.name}")
                print(f"{'=' * 20}project_name: {proj['name']}, project_version: {proj['version']}, project_template: \n{proj['template']}")
        elif len(args) == 4:
            if args[1] != 'update':
                print('only support update operation')
                return
            project_name = args[0]
            new_proj_version = args[2]
            new_proj_template = args[3]
            with open(new_proj_template, 'r') as f:
                new_proj_template = f.read()
            update_a_project_template(self.cluster_info, project_name, new_proj_version, new_proj_template)
        else:
            print('not support command, please type "help projects" for help')

    def do_bye(self, arg):
        """
        Bye bye
        """
        exit()


if __name__ == '__main__':
    AliyunCsShell().cmdloop()

相关文章

网友评论

    本文标题:Aliyun - Swarm Cluster Client

    本文链接:https://www.haomeiwen.com/subject/kaeagctx.html