-
Notifications
You must be signed in to change notification settings - Fork 247
Support prom discovery #93
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
lujiajing1126
wants to merge
15
commits into
robusta-dev:main
from
lujiajing1126:support-prom-discovery
Closed
Changes from 8 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
d756d49
first commit
lujiajing1126 67f264c
fix all bugs
lujiajing1126 180b19a
support labels in the table
lujiajing1126 9279ce8
fix None cluster issue
lujiajing1126 28bf5a9
fix name
lujiajing1126 8bb2857
abstract workload discovery
lujiajing1126 88b98f8
revert BaseFilteredMetricLoader
lujiajing1126 85c62d5
revert table format
lujiajing1126 325274b
fix Literal
lujiajing1126 308edf6
Merge branch 'main' into support-prom-discovery
lujiajing1126 c301571
Merge branch 'main' into support-prom-discovery
LeaveMyYard dc97454
Merge branch 'main' into support-prom-discovery
lujiajing1126 e4b443b
remove coroutine limit
lujiajing1126 f4267f5
remove labels
lujiajing1126 f6268c5
Merge branch 'main' into support-prom-discovery
lujiajing1126 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import abc | ||
| from typing import Optional | ||
|
|
||
| from robusta_krr.core.models.objects import K8sObjectData | ||
| from robusta_krr.utils.configurable import Configurable | ||
|
|
||
| class WorkloadLoader(Configurable, abc.ABC): | ||
|
|
||
| @abc.abstractmethod | ||
| async def list_scannable_objects(self, clusters: Optional[list[str]]) -> list[K8sObjectData]: | ||
| ... | ||
|
|
||
| @abc.abstractmethod | ||
| async def list_clusters(self) -> Optional[list[str]]: | ||
| ... |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| import asyncio | ||
| import itertools | ||
| from typing import Optional, List, Dict | ||
| from collections import defaultdict | ||
|
|
||
| from robusta_krr.core.models.config import Config | ||
| from robusta_krr.core.models.objects import K8sObjectData, PodData | ||
| from robusta_krr.core.models.result import ResourceAllocations, ResourceType, RecommendationValue | ||
| from .prometheus.loader import MetricsLoader | ||
| from .base_workload_loader import WorkloadLoader | ||
|
|
||
| class PrometheusLoader(WorkloadLoader): | ||
| def __init__(self, config: Config): | ||
| super().__init__(config) | ||
| self.metrics_loader = MetricsLoader(config) | ||
|
|
||
| async def list_clusters(self) -> Optional[list[str]]: | ||
| self.debug("Working in Prometheus-based workload discovery mode. Only support a single cluster") | ||
| return None | ||
|
|
||
| async def list_scannable_objects(self, clusters: Optional[list[str]]) -> list[K8sObjectData]: | ||
| """List all scannable objects from Prometheus | ||
| In this workload discovery mode, clusters are not supported. | ||
|
|
||
| Returns: | ||
| A list of scannable objects. | ||
| """ | ||
| self.info(f"Listing scannable objects from Prometheus") | ||
| self.debug(f"Namespaces: {self.config.namespaces}") | ||
| try: | ||
| objects_tuple = await asyncio.gather( | ||
| self._list_deployments(), | ||
| ) | ||
| except Exception as e: | ||
| self.error(f"Error trying to list pods from Prometheus: {e}") | ||
| self.debug_exception() | ||
| return [] | ||
|
|
||
| objects = itertools.chain(*objects_tuple) | ||
| if self.config.namespaces == "*": | ||
| # NOTE: We are not scanning kube-system namespace by default | ||
| result = [obj for obj in objects if obj.namespace != "kube-system"] | ||
| else: | ||
| result = [obj for obj in objects if obj.namespace in self.config.namespaces] | ||
|
|
||
| namespaces = {obj.namespace for obj in result} | ||
| self.info(f"Found {len(result)} objects across {len(namespaces)} namespaces from Prometheus({self.config.prometheus_url})") | ||
|
|
||
| return result | ||
|
|
||
| async def __parse_allocation(self, namespace: str, pod_selector: str, container_name: str) -> ResourceAllocations: | ||
| limits = await self.metrics_loader.loader.query("avg by(resource) (kube_pod_container_resource_limits{" | ||
| f'namespace="{namespace}", ' | ||
| f'pod=~"{pod_selector}", ' | ||
| f'container="{container_name}"' | ||
| "})") | ||
| requests = await self.metrics_loader.loader.query("avg by(resource) (kube_pod_container_resource_requests{" | ||
| f'namespace="{namespace}", ' | ||
| f'pod=~"{pod_selector}", ' | ||
| f'container="{container_name}"' | ||
| "})") | ||
| requests_values: Dict[ResourceType, RecommendationValue] = {ResourceType.CPU: None, ResourceType.Memory: None} | ||
| limits_values: Dict[ResourceType, RecommendationValue] = {ResourceType.CPU: None, ResourceType.Memory: None} | ||
| for limit in limits: | ||
| if limit['metric']['resource'] == ResourceType.CPU: | ||
| limits_values[ResourceType.CPU] = float(limit['value'][1]) | ||
| elif limit['metric']['resource'] == ResourceType.Memory: | ||
| limits_values[ResourceType.Memory] = float(limit['value'][1]) | ||
|
|
||
| for request in requests: | ||
| if request['metric']['resource'] == ResourceType.CPU: | ||
| requests_values[ResourceType.CPU] = float(request['value'][1]) | ||
| elif request['metric']['resource'] == ResourceType.Memory: | ||
| requests_values[ResourceType.Memory] = float(request['value'][1]) | ||
| return ResourceAllocations(requests=requests_values, limits=limits_values) | ||
|
|
||
|
|
||
| async def __build_from_owner(self, namespace: str, app_name: str, containers: List[str], pod_names: List[str], labels: Dict[str, str]) -> List[K8sObjectData]: | ||
| return [ | ||
| K8sObjectData( | ||
| cluster=None, | ||
| namespace=namespace, | ||
| labels=labels, | ||
| name=app_name, | ||
| kind="Deployment", | ||
| container=container_name, | ||
| allocations=await self.__parse_allocation(namespace, "|".join(pod_names), container_name), # find | ||
| pods=[PodData(name=pod_name, deleted=False) for pod_name in pod_names], # list pods | ||
| ) | ||
| for container_name in containers | ||
| ] | ||
|
|
||
| async def _list_containers(self, namespace: str, pod_selector: str) -> List[str]: | ||
| containers = await self.metrics_loader.loader.query("count by (container) (kube_pod_container_info{" | ||
| f'namespace="{namespace}", ' | ||
| f'pod=~"{pod_selector}"' | ||
| "})") | ||
| return [container['metric']['container'] for container in containers] | ||
|
|
||
| async def _list_containers_in_pods(self, app_name: str, pod_owner_kind: str, namespace: str, owner_name: str, labels: Dict[str, str]) -> list[K8sObjectData]: | ||
| if pod_owner_kind == "ReplicaSet": | ||
| # owner_name is ReplicaSet names | ||
| pods = await self.metrics_loader.loader.query("count by (owner_name, replicaset, pod) (kube_pod_owner{" | ||
| f'namespace="{namespace}", ' | ||
| f'owner_name=~"{owner_name}", ' | ||
| 'owner_kind="ReplicaSet"})') | ||
| if pods is None or len(pods) == 0: | ||
| return [] # no container | ||
| # [{'metric': {'owner_name': 'wbjs-algorithm-base-565b645489', 'pod': 'wbjs-algorithm-base-565b645489-jqt4x'}, 'value': [1685529217, '1']}, | ||
| # {'metric': {'owner_name': 'wbjs-algorithm-base-565b645489', 'pod': 'wbjs-algorithm-base-565b645489-lj9qg'}, 'value': [1685529217, '1']}] | ||
| pod_names = [pod['metric']['pod'] for pod in pods] | ||
| container_names = await self._list_containers(namespace, "|".join(pod_names)) | ||
| return await self.__build_from_owner(namespace, app_name, container_names, pod_names, labels) | ||
| return [] | ||
|
|
||
| async def _list_labels(self, owner_kind: str, namespace: str, owner_name: str) -> Dict[str, str]: | ||
| if owner_kind == "Deployment": | ||
| self.debug(f"{owner_kind} in {namespace}: {owner_name}") | ||
| labels_metric = await self.metrics_loader.loader.query("kube_deployment_labels{" | ||
| f'namespace="{namespace}", ' | ||
| f'deployment="{owner_name}"' | ||
| "}") | ||
| if len(labels_metric) == 0: | ||
| return {} | ||
| labels = {} | ||
| for key in labels_metric[0]['metric'].keys(): | ||
| if key.startswith('label_'): | ||
| labels[key[6:]] = labels_metric[0]['metric'][key] | ||
| return labels | ||
|
|
||
| async def _list_deployments(self) -> list[K8sObjectData]: | ||
| self.debug(f"Listing deployments in namespace({self.config.namespaces}) from Prometheus({self.config.prometheus_url})") | ||
| ns = "|".join(self.config.namespaces) | ||
| replicasets = await self.metrics_loader.loader.query("count by (namespace, owner_name, replicaset) (kube_replicaset_owner{" | ||
| f'namespace=~"{ns}", ' | ||
| 'owner_kind="Deployment"})') | ||
| # groupBy: 'ns/owner_name' => [{metadata}...] | ||
| pod_owner_kind = "ReplicaSet" | ||
| replicaset_dict = defaultdict(list) | ||
| for replicaset in replicasets: | ||
| replicaset_dict[replicaset['metric']['namespace'] + "/" + replicaset['metric']['owner_name']].append(replicaset['metric']) | ||
| objects = await asyncio.gather( | ||
| *[ | ||
| self._list_containers_in_pods(replicas[0]['owner_name'], pod_owner_kind, replicas[0]['namespace'], | ||
| "|".join(list(map(lambda metric: metric['replicaset'], replicas))), | ||
| await self._list_labels("Deployment", replicas[0]['namespace'], replicas[0]['owner_name']) | ||
| ) | ||
| for replicas in replicaset_dict.values() | ||
| ] | ||
| ) | ||
| return list(itertools.chain(*objects)) |
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
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
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
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
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
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
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.