| 
 | 1 | +import { CoreV1Api, V1Node, V1Pod } from './gen/api';  | 
 | 2 | +import { podsForNode, quantityToScalar, totalCPU, totalMemory } from './util';  | 
 | 3 | + | 
 | 4 | +export class ResourceUsage {  | 
 | 5 | +    constructor(  | 
 | 6 | +        public readonly Capacity: number,  | 
 | 7 | +        public readonly RequestTotal: number,  | 
 | 8 | +        public readonly LimitTotal: number,  | 
 | 9 | +    ) {}  | 
 | 10 | +}  | 
 | 11 | + | 
 | 12 | +export class NodeStatus {  | 
 | 13 | +    constructor(  | 
 | 14 | +        public readonly Node: V1Node,  | 
 | 15 | +        public readonly CPU: ResourceUsage,  | 
 | 16 | +        public readonly Memory: ResourceUsage,  | 
 | 17 | +    ) {}  | 
 | 18 | +}  | 
 | 19 | + | 
 | 20 | +export async function topNodes(api: CoreV1Api): Promise<NodeStatus[]> {  | 
 | 21 | +    // TODO: Support metrics APIs in the client and this library  | 
 | 22 | +    const nodes = await api.listNode();  | 
 | 23 | +    const result: NodeStatus[] = [];  | 
 | 24 | +    for (const node of nodes.body!.items) {  | 
 | 25 | +        const availableCPU = quantityToScalar(node.status!.allocatable!.cpu);  | 
 | 26 | +        const availableMem = quantityToScalar(node.status!.allocatable!.memory);  | 
 | 27 | +        let totalPodCPU = 0;  | 
 | 28 | +        let totalPodCPULimit = 0;  | 
 | 29 | +        let totalPodMem = 0;  | 
 | 30 | +        let totalPodMemLimit = 0;  | 
 | 31 | +        let pods = await podsForNode(api, node.metadata!.name!);  | 
 | 32 | +        pods = pods.filter((pod: V1Pod) => pod.status!.phase === 'Running');  | 
 | 33 | +        pods.forEach((pod: V1Pod) => {  | 
 | 34 | +            const cpuTotal = totalCPU(pod);  | 
 | 35 | +            totalPodCPU += cpuTotal.request;  | 
 | 36 | +            totalPodCPULimit += cpuTotal.limit;  | 
 | 37 | + | 
 | 38 | +            const memTotal = totalMemory(pod);  | 
 | 39 | +            totalPodMem += memTotal.request;  | 
 | 40 | +            totalPodMemLimit += memTotal.limit;  | 
 | 41 | +        });  | 
 | 42 | + | 
 | 43 | +        const cpuUsage = new ResourceUsage(availableCPU, totalPodCPU, totalPodCPULimit);  | 
 | 44 | +        const memUsage = new ResourceUsage(availableMem, totalPodMem, totalPodMemLimit);  | 
 | 45 | +        result.push(new NodeStatus(node, cpuUsage, memUsage));  | 
 | 46 | +    }  | 
 | 47 | +    return result;  | 
 | 48 | +}  | 
0 commit comments