2021-09-30 10:12:58 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
import json
|
2023-03-02 00:29:40 +00:00
|
|
|
import sys
|
2021-09-30 10:12:58 +00:00
|
|
|
import time
|
2023-03-02 00:29:40 +00:00
|
|
|
from dataclasses import dataclass
|
2023-05-23 16:47:19 +00:00
|
|
|
from typing import Any, Dict, List
|
2021-09-30 10:12:58 +00:00
|
|
|
|
2022-11-29 12:24:45 +00:00
|
|
|
import boto3 # type: ignore
|
2022-03-22 16:39:58 +00:00
|
|
|
|
2023-05-23 10:55:23 +00:00
|
|
|
from lambda_shared import RunnerDescriptions, list_runners
|
2023-05-23 16:47:19 +00:00
|
|
|
from lambda_shared.token import get_access_token_by_key_app, get_cached_access_token
|
2023-03-02 00:29:40 +00:00
|
|
|
|
|
|
|
|
2023-04-27 14:54:37 +00:00
|
|
|
@dataclass
|
|
|
|
class CachedInstances:
|
|
|
|
time: int
|
|
|
|
value: dict
|
|
|
|
updating: bool = False
|
|
|
|
|
|
|
|
|
|
|
|
cached_instances = CachedInstances(0, {})
|
|
|
|
|
|
|
|
|
|
|
|
def get_cached_instances() -> dict:
|
|
|
|
"""return cached instances description with updating it once per five minutes"""
|
|
|
|
if time.time() - 250 < cached_instances.time or cached_instances.updating:
|
|
|
|
return cached_instances.value
|
|
|
|
# Indicate that the value is updating now, so the cached value can be
|
|
|
|
# used. The first setting and close-to-ttl are not counted as update
|
|
|
|
if cached_instances.time != 0 or time.time() - 300 < cached_instances.time:
|
|
|
|
cached_instances.updating = True
|
2023-06-06 16:32:17 +00:00
|
|
|
else:
|
|
|
|
cached_instances.updating = False
|
2023-04-27 14:54:37 +00:00
|
|
|
ec2_client = boto3.client("ec2")
|
|
|
|
instances_response = ec2_client.describe_instances(
|
|
|
|
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]
|
|
|
|
)
|
|
|
|
cached_instances.time = int(time.time())
|
|
|
|
cached_instances.value = {
|
|
|
|
instance["InstanceId"]: instance
|
|
|
|
for reservation in instances_response["Reservations"]
|
|
|
|
for instance in reservation["Instances"]
|
|
|
|
}
|
|
|
|
cached_instances.updating = False
|
|
|
|
return cached_instances.value
|
|
|
|
|
|
|
|
|
2022-11-29 12:24:45 +00:00
|
|
|
def how_many_instances_to_kill(event_data: dict) -> Dict[str, int]:
|
2022-03-22 16:39:58 +00:00
|
|
|
data_array = event_data["CapacityToTerminate"]
|
2022-11-29 12:24:45 +00:00
|
|
|
to_kill_by_zone = {} # type: Dict[str, int]
|
2021-09-30 10:12:58 +00:00
|
|
|
for av_zone in data_array:
|
2022-03-22 16:39:58 +00:00
|
|
|
zone_name = av_zone["AvailabilityZone"]
|
|
|
|
to_kill = av_zone["Capacity"]
|
2021-09-30 10:12:58 +00:00
|
|
|
if zone_name not in to_kill_by_zone:
|
|
|
|
to_kill_by_zone[zone_name] = 0
|
|
|
|
|
|
|
|
to_kill_by_zone[zone_name] += to_kill
|
2022-11-29 12:24:45 +00:00
|
|
|
|
2021-09-30 10:12:58 +00:00
|
|
|
return to_kill_by_zone
|
|
|
|
|
2022-03-22 16:39:58 +00:00
|
|
|
|
2022-11-29 12:24:45 +00:00
|
|
|
def get_candidates_to_be_killed(event_data: dict) -> Dict[str, List[str]]:
|
2022-03-22 16:39:58 +00:00
|
|
|
data_array = event_data["Instances"]
|
2022-11-29 12:24:45 +00:00
|
|
|
instances_by_zone = {} # type: Dict[str, List[str]]
|
2021-09-30 10:12:58 +00:00
|
|
|
for instance in data_array:
|
2022-03-22 16:39:58 +00:00
|
|
|
zone_name = instance["AvailabilityZone"]
|
2022-11-29 12:24:45 +00:00
|
|
|
instance_id = instance["InstanceId"] # type: str
|
2021-09-30 10:12:58 +00:00
|
|
|
if zone_name not in instances_by_zone:
|
|
|
|
instances_by_zone[zone_name] = []
|
|
|
|
instances_by_zone[zone_name].append(instance_id)
|
|
|
|
|
|
|
|
return instances_by_zone
|
|
|
|
|
2022-03-22 16:39:58 +00:00
|
|
|
|
2023-03-02 00:29:40 +00:00
|
|
|
def main(access_token: str, event: dict) -> Dict[str, List[str]]:
|
2023-04-27 14:56:17 +00:00
|
|
|
start = time.time()
|
2023-04-26 19:20:19 +00:00
|
|
|
print("Got event", json.dumps(event, sort_keys=True).replace("\n", ""))
|
2021-09-30 10:12:58 +00:00
|
|
|
to_kill_by_zone = how_many_instances_to_kill(event)
|
|
|
|
instances_by_zone = get_candidates_to_be_killed(event)
|
2023-04-27 14:56:17 +00:00
|
|
|
# Getting ASG and instances' descriptions from the API
|
|
|
|
# We don't kill instances that alive for less than 10 minutes, since they
|
|
|
|
# could be not in the GH active runners yet
|
|
|
|
print(f"Check other hosts from the same ASG {event['AutoScalingGroupName']}")
|
|
|
|
asg_client = boto3.client("autoscaling")
|
|
|
|
as_groups_response = asg_client.describe_auto_scaling_groups(
|
|
|
|
AutoScalingGroupNames=[event["AutoScalingGroupName"]]
|
|
|
|
)
|
|
|
|
assert len(as_groups_response["AutoScalingGroups"]) == 1
|
|
|
|
asg = as_groups_response["AutoScalingGroups"][0]
|
|
|
|
asg_instance_ids = [instance["InstanceId"] for instance in asg["Instances"]]
|
|
|
|
instance_descriptions = get_cached_instances()
|
|
|
|
# The instances launched less than 10 minutes ago
|
|
|
|
immune_ids = [
|
|
|
|
instance["InstanceId"]
|
|
|
|
for instance in instance_descriptions.values()
|
|
|
|
if start - instance["LaunchTime"].timestamp() < 600
|
|
|
|
]
|
|
|
|
# if the ASG's instance ID not in instance_descriptions, it's most probably
|
|
|
|
# is not cached yet, so we must mark it as immuned
|
|
|
|
immune_ids.extend(
|
|
|
|
iid for iid in asg_instance_ids if iid not in instance_descriptions
|
|
|
|
)
|
|
|
|
print("Time spent on the requests to AWS: ", time.time() - start)
|
2021-09-30 10:12:58 +00:00
|
|
|
|
|
|
|
runners = list_runners(access_token)
|
2023-04-27 14:56:17 +00:00
|
|
|
runner_ids = set(runner.name for runner in runners)
|
2022-12-07 15:28:00 +00:00
|
|
|
# We used to delete potential hosts to terminate from GitHub runners pool,
|
|
|
|
# but the documentation states:
|
|
|
|
# --- Returning an instance first in the response data does not guarantee its termination
|
|
|
|
# so they will be cleaned out by ci_runners_metrics_lambda eventually
|
2021-09-30 10:12:58 +00:00
|
|
|
|
|
|
|
instances_to_kill = []
|
2023-03-01 23:56:11 +00:00
|
|
|
total_to_kill = 0
|
2022-11-29 12:24:45 +00:00
|
|
|
for zone, num_to_kill in to_kill_by_zone.items():
|
2021-09-30 10:12:58 +00:00
|
|
|
candidates = instances_by_zone[zone]
|
2023-03-01 23:56:11 +00:00
|
|
|
total_to_kill += num_to_kill
|
2021-09-30 10:12:58 +00:00
|
|
|
if num_to_kill > len(candidates):
|
2022-03-22 16:39:58 +00:00
|
|
|
raise Exception(
|
2023-04-26 19:20:19 +00:00
|
|
|
f"Required to kill {num_to_kill}, but have only {len(candidates)}"
|
|
|
|
f" candidates in AV {zone}"
|
2022-03-22 16:39:58 +00:00
|
|
|
)
|
2021-09-30 10:12:58 +00:00
|
|
|
|
2022-11-29 12:24:45 +00:00
|
|
|
delete_for_av = [] # type: RunnerDescriptions
|
2021-09-30 10:12:58 +00:00
|
|
|
for candidate in candidates:
|
2023-04-27 14:56:17 +00:00
|
|
|
if candidate in immune_ids:
|
|
|
|
print(
|
|
|
|
f"Candidate {candidate} started less than 10 minutes ago, won't touch a child"
|
|
|
|
)
|
|
|
|
break
|
|
|
|
if candidate not in runner_ids:
|
2022-03-22 16:39:58 +00:00
|
|
|
print(
|
|
|
|
f"Candidate {candidate} was not in runners list, simply delete it"
|
|
|
|
)
|
2021-09-30 11:26:46 +00:00
|
|
|
instances_to_kill.append(candidate)
|
2023-04-27 14:56:17 +00:00
|
|
|
break
|
2021-09-30 11:26:46 +00:00
|
|
|
if len(delete_for_av) + len(instances_to_kill) == num_to_kill:
|
2021-09-30 10:12:58 +00:00
|
|
|
break
|
2021-09-30 11:26:46 +00:00
|
|
|
if candidate in instances_to_kill:
|
|
|
|
continue
|
|
|
|
|
2021-09-30 10:12:58 +00:00
|
|
|
for runner in runners:
|
|
|
|
if runner.name == candidate:
|
|
|
|
if not runner.busy:
|
2022-03-22 16:39:58 +00:00
|
|
|
print(
|
|
|
|
f"Runner {runner.name} is not busy and can be deleted from AV {zone}"
|
|
|
|
)
|
2021-09-30 10:12:58 +00:00
|
|
|
delete_for_av.append(runner)
|
|
|
|
else:
|
|
|
|
print(f"Runner {runner.name} is busy, not going to delete it")
|
|
|
|
break
|
|
|
|
|
|
|
|
if len(delete_for_av) < num_to_kill:
|
2022-03-22 16:39:58 +00:00
|
|
|
print(
|
2023-04-26 19:20:19 +00:00
|
|
|
f"Checked all candidates for av {zone}, get to delete "
|
|
|
|
f"{len(delete_for_av)}, but still cannot get required {num_to_kill}"
|
2022-03-22 16:39:58 +00:00
|
|
|
)
|
2022-12-07 15:28:00 +00:00
|
|
|
|
|
|
|
instances_to_kill += [runner.name for runner in delete_for_av]
|
2021-09-30 10:12:58 +00:00
|
|
|
|
2023-03-01 23:56:11 +00:00
|
|
|
if len(instances_to_kill) < total_to_kill:
|
2023-04-27 14:56:17 +00:00
|
|
|
for instance in asg_instance_ids:
|
|
|
|
if instance in immune_ids:
|
|
|
|
continue
|
2023-03-01 23:56:11 +00:00
|
|
|
for runner in runners:
|
2023-04-27 14:56:17 +00:00
|
|
|
if runner.name == instance and not runner.busy:
|
2023-03-01 23:56:11 +00:00
|
|
|
print(f"Runner {runner.name} is not busy and can be deleted")
|
|
|
|
instances_to_kill.append(runner.name)
|
2021-09-30 10:12:58 +00:00
|
|
|
|
2023-03-01 23:56:11 +00:00
|
|
|
if total_to_kill <= len(instances_to_kill):
|
|
|
|
print("Got enough instances to kill")
|
|
|
|
break
|
|
|
|
|
2022-03-22 16:39:58 +00:00
|
|
|
response = {"InstanceIDs": instances_to_kill}
|
2023-04-27 14:56:17 +00:00
|
|
|
print("Got instances to kill: ", response)
|
|
|
|
print("Time spent on the request: ", time.time() - start)
|
2021-09-30 10:12:58 +00:00
|
|
|
return response
|
|
|
|
|
2022-03-22 16:39:58 +00:00
|
|
|
|
2022-11-29 12:24:45 +00:00
|
|
|
def handler(event: dict, context: Any) -> Dict[str, List[str]]:
|
2023-03-02 00:29:40 +00:00
|
|
|
return main(get_cached_access_token(), event)
|
2021-09-30 10:12:58 +00:00
|
|
|
|
2022-03-22 16:39:58 +00:00
|
|
|
|
2021-09-30 10:12:58 +00:00
|
|
|
if __name__ == "__main__":
|
2022-03-22 16:39:58 +00:00
|
|
|
parser = argparse.ArgumentParser(description="Get list of runners and their states")
|
|
|
|
parser.add_argument(
|
|
|
|
"-p", "--private-key-path", help="Path to file with private key"
|
|
|
|
)
|
|
|
|
parser.add_argument("-k", "--private-key", help="Private key")
|
|
|
|
parser.add_argument(
|
|
|
|
"-a", "--app-id", type=int, help="GitHub application ID", required=True
|
|
|
|
)
|
2021-09-30 10:12:58 +00:00
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
if not args.private_key_path and not args.private_key:
|
2022-03-22 16:39:58 +00:00
|
|
|
print(
|
|
|
|
"Either --private-key-path or --private-key must be specified",
|
|
|
|
file=sys.stderr,
|
|
|
|
)
|
2021-09-30 10:12:58 +00:00
|
|
|
|
|
|
|
if args.private_key_path and args.private_key:
|
2022-03-22 16:39:58 +00:00
|
|
|
print(
|
|
|
|
"Either --private-key-path or --private-key must be specified",
|
|
|
|
file=sys.stderr,
|
|
|
|
)
|
2021-09-30 10:12:58 +00:00
|
|
|
|
|
|
|
if args.private_key:
|
|
|
|
private_key = args.private_key
|
|
|
|
else:
|
2022-03-22 16:39:58 +00:00
|
|
|
with open(args.private_key_path, "r") as key_file:
|
2021-09-30 10:12:58 +00:00
|
|
|
private_key = key_file.read()
|
|
|
|
|
2023-05-23 16:47:19 +00:00
|
|
|
token = get_access_token_by_key_app(private_key, args.app_id)
|
|
|
|
|
2021-09-30 10:12:58 +00:00
|
|
|
sample_event = {
|
|
|
|
"AutoScalingGroupARN": "arn:aws:autoscaling:us-east-1:<account-id>:autoScalingGroup:d4738357-2d40-4038-ae7e-b00ae0227003:autoScalingGroupName/my-asg",
|
|
|
|
"AutoScalingGroupName": "my-asg",
|
|
|
|
"CapacityToTerminate": [
|
|
|
|
{
|
|
|
|
"AvailabilityZone": "us-east-1b",
|
|
|
|
"Capacity": 1,
|
2022-03-22 16:39:58 +00:00
|
|
|
"InstanceMarketOption": "OnDemand",
|
2021-09-30 10:12:58 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
"AvailabilityZone": "us-east-1c",
|
|
|
|
"Capacity": 2,
|
2022-03-22 16:39:58 +00:00
|
|
|
"InstanceMarketOption": "OnDemand",
|
|
|
|
},
|
2021-09-30 10:12:58 +00:00
|
|
|
],
|
|
|
|
"Instances": [
|
|
|
|
{
|
|
|
|
"AvailabilityZone": "us-east-1b",
|
|
|
|
"InstanceId": "i-08d0b3c1a137e02a5",
|
|
|
|
"InstanceType": "t2.nano",
|
2022-03-22 16:39:58 +00:00
|
|
|
"InstanceMarketOption": "OnDemand",
|
2021-09-30 10:12:58 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
"AvailabilityZone": "us-east-1c",
|
|
|
|
"InstanceId": "ip-172-31-45-253.eu-west-1.compute.internal",
|
|
|
|
"InstanceType": "t2.nano",
|
2022-03-22 16:39:58 +00:00
|
|
|
"InstanceMarketOption": "OnDemand",
|
2021-09-30 10:12:58 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
"AvailabilityZone": "us-east-1c",
|
|
|
|
"InstanceId": "ip-172-31-27-227.eu-west-1.compute.internal",
|
|
|
|
"InstanceType": "t2.nano",
|
2022-03-22 16:39:58 +00:00
|
|
|
"InstanceMarketOption": "OnDemand",
|
2021-09-30 10:12:58 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
"AvailabilityZone": "us-east-1c",
|
|
|
|
"InstanceId": "ip-172-31-45-253.eu-west-1.compute.internal",
|
|
|
|
"InstanceType": "t2.nano",
|
2022-03-22 16:39:58 +00:00
|
|
|
"InstanceMarketOption": "OnDemand",
|
|
|
|
},
|
2021-09-30 10:12:58 +00:00
|
|
|
],
|
2022-03-22 16:39:58 +00:00
|
|
|
"Cause": "SCALE_IN",
|
2021-09-30 10:12:58 +00:00
|
|
|
}
|
|
|
|
|
2023-05-23 16:47:19 +00:00
|
|
|
main(token, sample_event)
|