from googleapiclient import discovery from oauth2client.client import GoogleCredentials import requests import json import time credentials = GoogleCredentials.get_application_default() project = 'pingcap-gardener' computeClient = discovery.build('compute', 'v1', credentials=credentials) disks = [] BOT_SECRET = "Rk7vQ3pmlG1uIrfQmWWvab" BOT_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/0b83323d-f406-4ecd-9771-389cea6e7253" def post_to_feishu(ebs): headers = { 'Content-Type': 'application/json' } payload_message = { "timestamp": str(int(time.time())), "msg_type": "interactive", "card": { "i18n_elements": { "en_us": [ { "tag": "div", "text": { "tag": "lark_md", "content": "**GCP Disk Robot**" }, "fields": [ { "is_short": False, "text": { "tag": "lark_md", "content": "" } }, { "is_short": True, "text": { "tag": "lark_md", "content": "自动清理: {} 块盘".format(len(ebs)) } } ] }, ] } } } response = requests.request( "POST", BOT_WEBHOOK, headers=headers, data=json.dumps(payload_message)) print(response.text) def clean_disks(): zones = [ "us-west2-a", "us-west2-b", "us-west2-c", ] ebs = [] for zone in zones: request = computeClient.disks().list(project=project, zone=zone) while request is not None: response = request.execute() time.sleep(10) if 'items' not in response: continue for disk in response['items']: # TODO: Change code below to process each `disk` resource: name = disk['name'] if 'shoot--' not in name: continue if 'description' not in disk: continue description = json.loads(disk['description']) if 'kubernetes.io/created-for/pvc/name' not in description: continue pvcName = description['kubernetes.io/created-for/pvc/name'] if 'users' not in disk and \ ('pd' in pvcName or 'tikv' in pvcName): print("delete disk ", name) deleteRequest = computeClient.disks().delete(project=project, zone=zone, disk= name) deleteRequest.execute() ebs.append(name) request = computeClient.disks().list_next(previous_request=request, previous_response=response) if len(ebs) > 0: post_to_feishu(ebs) def hello_pubsub(event, context): clean_disks()