from ecs.cluster import Cluster from lambda_function.function import Function import boto3 from abc import ABC, abstractmethod def list_clusters(client) -> list: paginator = client.get_paginator('list_clusters') page_iterator = paginator.paginate() return [Cluster(client, item) for sublist in page_iterator for item in sublist.get('clusterArns', [])] def list_functions(client) -> list: paginator = client.get_paginator('list_functions') page_iterator = paginator.paginate() return [Function(client, item) for sublist in page_iterator for item in sublist.get('Functions', [])] class Report(ABC): def __init__(self, profile: str): self.__profile = profile self.__session = boto3.session.Session(profile_name=self.__profile) def get_profile(self): return self.__profile def get_session(self): return self.__session @abstractmethod def make_report(self): pass class EcsReport(Report): def __init__(self, profile: str): super().__init__(profile) self.__ecs_client = self.get_session().client('ecs') self.__as_client = self.get_session().client('application-autoscaling') def make_report(self): rows = [] for cluster in list_clusters(self.__ecs_client): for service in cluster.get_services(): min_num_of_tasks = service.get_min_count( self.__as_client) max_num_of_tasks = service.get_max_count( self.__as_client) tasks = service.get_tasks() num_of_containers = 0 num_of_tasks = len(tasks) if num_of_tasks != 0: num_of_containers = len(tasks[0].list_containers()) service_type = 'WEB' if service.get_load_balancers() != [] else 'JOB' rows.append( [ self.get_profile(), cluster.get_cluster_name(), service.get_service_name(), num_of_tasks, num_of_containers, num_of_tasks * num_of_containers, min_num_of_tasks, max_num_of_tasks, max_num_of_tasks * num_of_containers, service_type, ] ) return rows class LambdaReport(Report): def __init__(self, profile: str): super().__init__(profile) self.__lambda_client = self.get_session().client('lambda') self.__cw_client = self.get_session().client('cloudwatch') def make_report(self): rows = [] for function in list_functions(self.__lambda_client): rows.append( [ self.get_profile(), function.name, function.runtime, function.get_number_of_invocations(self.__cw_client) ] ) return rows