import os import requests import pymysql import time, datetime import json from kubernetes import client, config host = "tidb.e23bdccc.cb17aaf2.us-west-2.prod.aws.tidbcloud.com" passwd = os.getenv('passwd') stagingUrl = "https://us-west-2.staging.shared.aws.tidbcloud.com" nightlyUrl = "https://us-west-2.nightly.shared.aws.tidbcloud.com" feishu_webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/09cc9db1-5f47-493d-a242-d87b27c1569d" instanceIDs = {} sleepingShoots = [] def post_bot_webhook(): post_infos = [] post_infos.append( { "is_short": False, "text": { "tag": "lark_md", "content": "" } }, ) post_infos.append( { "is_short": True, "text": { "tag": "lark_md", "content": "Sleeping Shoots:\n {}".format(",\n".join( sleepingShoots )) } }, ) url = feishu_webhook payload_message = { "timestamp": str(int(time.time())), "msg_type": "interactive", "card": { "i18n_elements": { "en_us": [ { "tag": "div", "text": { "tag": "lark_md", "content": "** Shoot Sleeping ** {}\n".format( datetime.datetime.today().strftime("%Y-%m-%d")), }, "fields": post_infos, }, ] } } } headers = { 'Content-Type': 'application/json' } response = requests.request( "POST", url, headers=headers, data=json.dumps(payload_message)) print(response.text) def fetch_useless_projects( env ): projects = {} tenant_projects = {} if env == 'nightly': env = 'dev' dbName = env + '_central' db = pymysql.connect(host=host, port=4000, user='root', password=passwd, db=dbName, charset='utf8' ) cursor = db.cursor() cursor.execute("select id,name,tenant_id from projects where status = 'active' and id != 1") results = cursor.fetchall() for row in results: id = row[0] name = row[1] tenantId = row[2] # 千万不能删除任何QA的project if 'QA' in name \ or 'ApiAuto' in name \ or 'AutoTest' in name: continue cursor.execute("select id,deleted_time,status from clusters where project_id={} " " and status in ('created','initializing','preparing','launching','normal','scaling','upgrading')" .format(id) ) results = cursor.fetchall() if len( results ) > 0: continue projects[ str(id) ] = name tenant_projects[ str(id) ] = tenantId return projects, tenant_projects def process_shoot(env, projects): if env != 'staging': env = 'nightly' config.kube_config.load_kube_config(config_file="gardener-{}".format(env) ) shootClient = client.CustomObjectsApi() shoots = shootClient.list_namespaced_custom_object( group="core.gardener.cloud", version="v1beta1", namespace="garden-{}".format( env ), plural="shoots", ) for shoot in shoots['items']: if 'project' not in shoot['metadata']['labels']: continue theProjectId = shoot['metadata']['labels']['project'] if theProjectId in projects.keys(): patch_body = { "spec": {"hibernation": { "enable": 'true'} } } shootClient.patch_namespaced_custom_object( group="core.gardener.cloud", version="v1beta1", name= shoot['metadata']['name'], namespace= "garden-{}".format( env ) , plural= "shoots", body=patch_body, ) print(" hibernate shoot {}/{} of projectId {} named {}".format( env, shoot['metadata']['name'], theProjectId, projects[theProjectId] )) sleepingShoots.append( env + "/" + shoot['metadata']['name']) envs = [ "nightly", "staging", "yinliang3", "ouyan", 'yunqing', 'nizheming', 'jyzdev10', 'hanlins', 'gweber', 'baoling2' ] def lambda_handler(event, context): for env in envs: print(" process env {}".format( env ) ) try: projects, _ = fetch_useless_projects( env ) process_shoot( env , projects) except: print("bypass env {}".format( env )) post_bot_webhook() return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') }