|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright 2024 The Kubernetes Authors. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +""" |
| 17 | +Example demonstrating how to fetch and display metrics from the Kubernetes |
| 18 | +metrics-server using the Python client. |
| 19 | +
|
| 20 | +This example shows: |
| 21 | +1. Fetching node metrics |
| 22 | +2. Fetching pod metrics in a namespace |
| 23 | +3. Fetching pod metrics across multiple namespaces |
| 24 | +4. Filtering pod metrics by labels |
| 25 | +
|
| 26 | +Prerequisites: |
| 27 | +- A running Kubernetes cluster with metrics-server installed |
| 28 | +- kubectl configured to access the cluster |
| 29 | +- The kubernetes Python client library installed |
| 30 | +""" |
| 31 | + |
| 32 | +from kubernetes import client, config, utils |
| 33 | + |
| 34 | + |
| 35 | +def print_node_metrics(api_client): |
| 36 | + """Fetch and display node metrics.""" |
| 37 | + print("\n" + "="*60) |
| 38 | + print("NODE METRICS") |
| 39 | + print("="*60) |
| 40 | + |
| 41 | + try: |
| 42 | + metrics = utils.get_nodes_metrics(api_client) |
| 43 | + |
| 44 | + print(f"Found {len(metrics.get('items', []))} nodes\n") |
| 45 | + |
| 46 | + for node in metrics.get('items', []): |
| 47 | + node_name = node['metadata']['name'] |
| 48 | + timestamp = node.get('timestamp', 'N/A') |
| 49 | + window = node.get('window', 'N/A') |
| 50 | + usage = node.get('usage', {}) |
| 51 | + |
| 52 | + print(f"Node: {node_name}") |
| 53 | + print(f" Timestamp: {timestamp}") |
| 54 | + print(f" Window: {window}") |
| 55 | + print(f" CPU Usage: {usage.get('cpu', 'N/A')}") |
| 56 | + print(f" Memory Usage: {usage.get('memory', 'N/A')}") |
| 57 | + print() |
| 58 | + |
| 59 | + except Exception as e: |
| 60 | + print(f"Error fetching node metrics: {e}") |
| 61 | + |
| 62 | + |
| 63 | +def print_pod_metrics(api_client, namespace): |
| 64 | + """Fetch and display pod metrics for a namespace.""" |
| 65 | + print("\n" + "="*60) |
| 66 | + print(f"POD METRICS IN NAMESPACE: {namespace}") |
| 67 | + print("="*60) |
| 68 | + |
| 69 | + try: |
| 70 | + metrics = utils.get_pods_metrics(api_client, namespace) |
| 71 | + |
| 72 | + print(f"Found {len(metrics.get('items', []))} pods\n") |
| 73 | + |
| 74 | + for pod in metrics.get('items', []): |
| 75 | + pod_name = pod['metadata']['name'] |
| 76 | + timestamp = pod.get('timestamp', 'N/A') |
| 77 | + window = pod.get('window', 'N/A') |
| 78 | + |
| 79 | + print(f"Pod: {pod_name}") |
| 80 | + print(f" Timestamp: {timestamp}") |
| 81 | + print(f" Window: {window}") |
| 82 | + print(f" Containers:") |
| 83 | + |
| 84 | + for container in pod.get('containers', []): |
| 85 | + container_name = container['name'] |
| 86 | + usage = container.get('usage', {}) |
| 87 | + print(f" - {container_name}:") |
| 88 | + print(f" CPU: {usage.get('cpu', 'N/A')}") |
| 89 | + print(f" Memory: {usage.get('memory', 'N/A')}") |
| 90 | + print() |
| 91 | + |
| 92 | + except Exception as e: |
| 93 | + print(f"Error fetching pod metrics: {e}") |
| 94 | + |
| 95 | + |
| 96 | +def print_filtered_pod_metrics(api_client, namespace, labels): |
| 97 | + """Fetch and display pod metrics filtered by labels.""" |
| 98 | + print("\n" + "="*60) |
| 99 | + print(f"POD METRICS IN NAMESPACE: {namespace}") |
| 100 | + print(f"FILTERED BY LABELS: {labels}") |
| 101 | + print("="*60) |
| 102 | + |
| 103 | + try: |
| 104 | + metrics = utils.get_pods_metrics(api_client, namespace, labels) |
| 105 | + |
| 106 | + pods = metrics.get('items', []) |
| 107 | + print(f"Found {len(pods)} pods matching labels\n") |
| 108 | + |
| 109 | + for pod in pods: |
| 110 | + pod_name = pod['metadata']['name'] |
| 111 | + print(f"Pod: {pod_name}") |
| 112 | + |
| 113 | + for container in pod.get('containers', []): |
| 114 | + container_name = container['name'] |
| 115 | + usage = container.get('usage', {}) |
| 116 | + print(f" {container_name}: CPU={usage.get('cpu')}, Memory={usage.get('memory')}") |
| 117 | + print() |
| 118 | + |
| 119 | + except Exception as e: |
| 120 | + print(f"Error fetching filtered pod metrics: {e}") |
| 121 | + |
| 122 | + |
| 123 | +def print_multi_namespace_metrics(api_client, namespaces): |
| 124 | + """Fetch and display pod metrics across multiple namespaces.""" |
| 125 | + print("\n" + "="*60) |
| 126 | + print(f"POD METRICS ACROSS MULTIPLE NAMESPACES") |
| 127 | + print("="*60) |
| 128 | + |
| 129 | + try: |
| 130 | + all_metrics = utils.get_pods_metrics_in_all_namespaces(api_client, namespaces) |
| 131 | + |
| 132 | + for ns, result in all_metrics.items(): |
| 133 | + print(f"\nNamespace: {ns}") |
| 134 | + |
| 135 | + if 'error' in result: |
| 136 | + print(f" Error: {result['error']}") |
| 137 | + else: |
| 138 | + pod_count = len(result.get('items', [])) |
| 139 | + print(f" Pods: {pod_count}") |
| 140 | + |
| 141 | + # Calculate total resource usage for namespace |
| 142 | + total_containers = 0 |
| 143 | + for pod in result.get('items', []): |
| 144 | + total_containers += len(pod.get('containers', [])) |
| 145 | + |
| 146 | + print(f" Total containers: {total_containers}") |
| 147 | + |
| 148 | + except Exception as e: |
| 149 | + print(f"Error fetching multi-namespace metrics: {e}") |
| 150 | + |
| 151 | + |
| 152 | +def main(): |
| 153 | + """Main function to demonstrate metrics API usage.""" |
| 154 | + # Load kubernetes configuration |
| 155 | + # This will use your current kubectl context |
| 156 | + config.load_kube_config() |
| 157 | + |
| 158 | + # Create API client |
| 159 | + api_client = client.ApiClient() |
| 160 | + |
| 161 | + print("\nKubernetes Metrics API Example") |
| 162 | + print("================================") |
| 163 | + print("\nThis example demonstrates fetching resource usage metrics") |
| 164 | + print("from the Kubernetes metrics-server.") |
| 165 | + print("\nNote: metrics-server must be installed in your cluster for this to work.") |
| 166 | + |
| 167 | + # Example 1: Fetch node metrics |
| 168 | + print_node_metrics(api_client) |
| 169 | + |
| 170 | + # Example 2: Fetch pod metrics in default namespace |
| 171 | + print_pod_metrics(api_client, 'default') |
| 172 | + |
| 173 | + # Example 3: Fetch pod metrics in kube-system namespace |
| 174 | + print_pod_metrics(api_client, 'kube-system') |
| 175 | + |
| 176 | + # Example 4: Fetch pod metrics with label filter |
| 177 | + # Uncomment and modify the label selector to match your pods |
| 178 | + # print_filtered_pod_metrics(api_client, 'default', 'app=nginx') |
| 179 | + |
| 180 | + # Example 5: Fetch metrics across multiple namespaces |
| 181 | + namespaces_to_query = ['default', 'kube-system'] |
| 182 | + print_multi_namespace_metrics(api_client, namespaces_to_query) |
| 183 | + |
| 184 | + print("\n" + "="*60) |
| 185 | + print("Example completed successfully!") |
| 186 | + print("="*60 + "\n") |
| 187 | + |
| 188 | + |
| 189 | +if __name__ == '__main__': |
| 190 | + main() |
0 commit comments