Last active
April 8, 2019 01:24
-
-
Save Bak-Jin-Hyeong/e7a0248fb0642202011d34c4f0c4ff20 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import itertools | |
import json | |
import boto3 | |
REGION = 'us-east-1' | |
CLUSTER = 'what-the-fuck' | |
ECS_CLIENT = boto3.client('ecs', REGION) | |
REQUIRED_CPU_PER_TASK = 1024 | |
REQUIRED_MEMORY_PER_TASK = 3500 | |
def log(x): | |
class Encoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, datetime.datetime): | |
return o.isoformat() | |
return json.JSONEncoder.default(self, o) | |
print(json.dumps(x, cls=Encoder)) | |
def container_instance_arns(page_list): | |
return [page['containerInstanceArns'] for page in page_list] | |
def get_active_instances(ecs, cluster): | |
return ecs.get_paginator('list_container_instances').paginate( | |
cluster=cluster, status='ACTIVE' | |
) | |
def describe_container_instances(ecs, cluster, instance_arns): | |
response = ecs.describe_container_instances( | |
cluster=cluster, | |
containerInstances=instance_arns) | |
for i in response['containerInstances']: | |
yield i | |
def describe_active_instances(ecs, cluster): | |
page_list = get_active_instances(ecs, cluster) | |
arns = [x for x in container_instance_arns(page_list) if x] | |
desc = [describe_container_instances(ecs, cluster, x) for x in arns] | |
return itertools.chain.from_iterable(desc) | |
def get_registered_cpu_and_memory(instance_description): | |
cpu, memory = 0, 0 | |
for x in instance_description['registeredResources']: | |
if x['name'] == 'CPU': | |
cpu += x['integerValue'] | |
elif x['name'] == 'MEMORY': | |
memory += x['integerValue'] | |
return cpu, memory | |
def calc_possible_tasks(cpu, memory, required_cpu, required_memory): | |
by_cpu = cpu // required_cpu | |
by_memory = memory // required_memory | |
return by_cpu if by_cpu < by_memory else by_memory | |
def sum_possible_tasks(ecs, cluster, required_cpu, required_memory): | |
possible_tasks = 0 | |
for i in describe_active_instances(ecs, cluster): | |
cpu, memory = get_registered_cpu_and_memory(i) | |
log({'cpu': cpu, 'memory': memory}) | |
possible_tasks += calc_possible_tasks( | |
cpu, memory, required_cpu, required_memory | |
) | |
return possible_tasks | |
def foo(ecs, cluster, required_cpu, required_memory): | |
tasks = sum_possible_tasks(ecs, cluster, required_cpu, required_memory) | |
log(tasks) | |
foo(ECS_CLIENT, CLUSTER, REQUIRED_CPU_PER_TASK, REQUIRED_MEMORY_PER_TASK) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment