Search code examples
kuberneteskubectl

how to get top N latest created pods inside kubernetes based on filter


In Kubernetes (using a filter) we can limit the output from k8s on interesting resource and I wonder whether it is possible to list top 5 latest created pods using only filter.

The current example mostly list all pods and pipe to another unix (head command)

kubectl get pods --sort-by=.metadata.creationTimestamp | head -n 5

But I guess it takes quite long time to get all first from server side, then lists first 5.

Can I use special filter will make it more efficiency?


Solution

  • There are several aspects which prevent you to solve this question using only filter:

    1. Filter itself:

      Field selectors are essentially resource filters. By default, no selectors/filters are applied, meaning that all resources of the specified type are selected. This makes the kubectl queries kubectl get pods and kubectl get pods --field-selector "" equivalent.

      Reference - Field selectors.

      And its limitations on supported operations:

      You can use the =, ==, and != operators with field selectors (= and == mean the same thing). This kubectl command, for example, selects all Kubernetes Services that aren't in the default namespace:

      kubectl get services --all-namespaces --field-selector metadata.namespace!=default

      It can't compare value like > or < even if a number of total pods would have been available.

    2. I compared requests with --v=8 to see which exact response is performed when kubectl get pods is executed with different options:

      $ kubectl get pods -A --sort-by=.metadata.creationTimestamp --v=8
      I1007 12:40:45.296727     562 round_trippers.go:432] GET https://10.186.0.2:6443/api/v1/pods?includeObject=Object
      

      and

      $ kubectl get pods -A --field-selector=metadata.namespace=kube-system --v=8
      I1007 12:41:42.873609    1067 round_trippers.go:432] GET https://10.186.0.2:6443/api/v1/pods?fieldSelector=metadata.namespace%3Dkube-system&limit=500
      

      The difference when --field-selector kubectl used is it adds &limit=500 to the request, so it's a point where some data inconsistency can appear if using kubectl from terminal. While --sort-by get all data from api server to the client.

    3. Using -o jsonpath works the same way as regular kubectl get pods request and has again the limit of 500 results which may lead to data inconsistency:

      $ kubectl get pods -A --v=7 -o jsonpath='{range.items[*]}{.metadata.creationTimestamp}{"\t"}{.metadata.name}{"\n"}{end}'
      I1007 12:52:25.505109    6943 round_trippers.go:432] GET https://10.186.0.2:6443/api/v1/pods?limit=500
      

      Also even developers using another linux commands (jq, grep, sort, |) to work with initial results which are got from kubernetes api. See examples of Viewing, finding resources.

    So to confirm @P...'s comment, you will need to get data first to the client and only then work on it.