背景说明

通过kubectl进行获取资源对象例如pod、pv时经常需要按照一定的条件排序,此时需要用到排序参数—sort-by

解决方案

排序字段

针对排序字段这里需要查看资源对象的spec[规格]描述,这里拿pv举例

  1. student@master01:~$ kubectl explain pv
  2. KIND: PersistentVolume
  3. VERSION: v1
  4. DESCRIPTION:
  5. PersistentVolume (PV) is a storage resource provisioned by an
  6. administrator. It is analogous to a node. More info:
  7. https://kubernetes.io/docs/concepts/storage/persistent-volumes
  8. FIELDS:
  9. apiVersion <string>
  10. APIVersion defines the versioned schema of this representation of an
  11. object. Servers should convert recognized schemas to the latest internal
  12. value, and may reject unrecognized values. More info:
  13. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
  14. kind <string>
  15. Kind is a string value representing the REST resource this object
  16. represents. Servers may infer this from the endpoint the client submits
  17. requests to. Cannot be updated. In CamelCase. More info:
  18. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
  19. metadata <Object>
  20. Standard object's metadata. More info:
  21. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  22. spec <Object>
  23. Spec defines a specification of a persistent volume owned by the cluster.
  24. Provisioned by an administrator. More info:
  25. https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumes
  26. status <Object>
  27. Status represents the current information/status for the persistent volume.
  28. Populated by the system. Read-only. More info:
  29. https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumes
  30. student@master01:~$
  31. student@master01:~$ kubectl explain pv.metadata
  32. KIND: PersistentVolume
  33. VERSION: v1
  34. RESOURCE: metadata <Object>
  35. DESCRIPTION:
  36. Standard object's metadata. More info:
  37. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  38. ObjectMeta is metadata that all persisted resources must have, which
  39. includes all objects users must create.
  40. FIELDS:
  41. annotations <map[string]string>
  42. Annotations is an unstructured key value map stored with a resource that
  43. may be set by external tools to store and retrieve arbitrary metadata. They
  44. are not queryable and should be preserved when modifying objects. More
  45. info: http://kubernetes.io/docs/user-guide/annotations
  46. clusterName <string>
  47. The name of the cluster which the object belongs to. This is used to
  48. distinguish resources with same name and namespace in different clusters.
  49. This field is not set anywhere right now and apiserver is going to ignore
  50. it if set in create or update request.
  51. creationTimestamp <string>
  52. CreationTimestamp is a timestamp representing the server time when this
  53. object was created. It is not guaranteed to be set in happens-before order
  54. across separate operations. Clients may not set this value. It is
  55. represented in RFC3339 form and is in UTC.
  56. Populated by the system. Read-only. Null for lists. More info:
  57. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  58. deletionGracePeriodSeconds <integer>
  59. Number of seconds allowed for this object to gracefully terminate before it
  60. will be removed from the system. Only set when deletionTimestamp is also
  61. set. May only be shortened. Read-only.
  62. deletionTimestamp <string>
  63. DeletionTimestamp is RFC 3339 date and time at which this resource will be
  64. deleted. This field is set by the server when a graceful deletion is
  65. requested by the user, and is not directly settable by a client. The
  66. resource is expected to be deleted (no longer visible from resource lists,
  67. and not reachable by name) after the time in this field, once the
  68. finalizers list is empty. As long as the finalizers list contains items,
  69. deletion is blocked. Once the deletionTimestamp is set, this value may not
  70. be unset or be set further into the future, although it may be shortened or
  71. the resource may be deleted prior to this time. For example, a user may
  72. request that a pod is deleted in 30 seconds. The Kubelet will react by
  73. sending a graceful termination signal to the containers in the pod. After
  74. that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL)
  75. to the container and after cleanup, remove the pod from the API. In the
  76. presence of network partitions, this object may still exist after this
  77. timestamp, until an administrator or automated process can determine the
  78. resource is fully terminated. If not set, graceful deletion of the object
  79. has not been requested.
  80. Populated by the system when a graceful deletion is requested. Read-only.
  81. More info:
  82. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  83. finalizers <[]string>
  84. Must be empty before the object is deleted from the registry. Each entry is
  85. an identifier for the responsible component that will remove the entry from
  86. the list. If the deletionTimestamp of the object is non-nil, entries in
  87. this list can only be removed. Finalizers may be processed and removed in
  88. any order. Order is NOT enforced because it introduces significant risk of
  89. stuck finalizers. finalizers is a shared field, any actor with permission
  90. can reorder it. If the finalizer list is processed in order, then this can
  91. lead to a situation in which the component responsible for the first
  92. finalizer in the list is waiting for a signal (field value, external
  93. system, or other) produced by a component responsible for a finalizer later
  94. in the list, resulting in a deadlock. Without enforced ordering finalizers
  95. are free to order amongst themselves and are not vulnerable to ordering
  96. changes in the list.
  97. generateName <string>
  98. GenerateName is an optional prefix, used by the server, to generate a
  99. unique name ONLY IF the Name field has not been provided. If this field is
  100. used, the name returned to the client will be different than the name
  101. passed. This value will also be combined with a unique suffix. The provided
  102. value has the same validation rules as the Name field, and may be truncated
  103. by the length of the suffix required to make the value unique on the
  104. server.
  105. If this field is specified and the generated name exists, the server will
  106. NOT return a 409 - instead, it will either return 201 Created or 500 with
  107. Reason ServerTimeout indicating a unique name could not be found in the
  108. time allotted, and the client should retry (optionally after the time
  109. indicated in the Retry-After header).
  110. Applied only if Name is not specified. More info:
  111. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency
  112. generation <integer>
  113. A sequence number representing a specific generation of the desired state.
  114. Populated by the system. Read-only.
  115. labels <map[string]string>
  116. Map of string keys and values that can be used to organize and categorize
  117. (scope and select) objects. May match selectors of replication controllers
  118. and services. More info: http://kubernetes.io/docs/user-guide/labels
  119. managedFields <[]Object>
  120. ManagedFields maps workflow-id and version to the set of fields that are
  121. managed by that workflow. This is mostly for internal housekeeping, and
  122. users typically shouldn't need to set or understand this field. A workflow
  123. can be the user's name, a controller's name, or the name of a specific
  124. apply path like "ci-cd". The set of fields is always in the version that
  125. the workflow used when modifying the object.
  126. name <string>
  127. Name must be unique within a namespace. Is required when creating
  128. resources, although some resources may allow a client to request the
  129. generation of an appropriate name automatically. Name is primarily intended
  130. for creation idempotence and configuration definition. Cannot be updated.
  131. More info: http://kubernetes.io/docs/user-guide/identifiers#names
  132. namespace <string>
  133. Namespace defines the space within which each name must be unique. An empty
  134. namespace is equivalent to the "default" namespace, but "default" is the
  135. canonical representation. Not all objects are required to be scoped to a
  136. namespace - the value of this field for those objects will be empty.
  137. Must be a DNS_LABEL. Cannot be updated. More info:
  138. http://kubernetes.io/docs/user-guide/namespaces
  139. ownerReferences <[]Object>
  140. List of objects depended by this object. If ALL objects in the list have
  141. been deleted, this object will be garbage collected. If this object is
  142. managed by a controller, then an entry in this list will point to this
  143. controller, with the controller field set to true. There cannot be more
  144. than one managing controller.
  145. resourceVersion <string>
  146. An opaque value that represents the internal version of this object that
  147. can be used by clients to determine when objects have changed. May be used
  148. for optimistic concurrency, change detection, and the watch operation on a
  149. resource or set of resources. Clients must treat these values as opaque and
  150. passed unmodified back to the server. They may only be valid for a
  151. particular resource or set of resources.
  152. Populated by the system. Read-only. Value must be treated as opaque by
  153. clients and . More info:
  154. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
  155. selfLink <string>
  156. SelfLink is a URL representing this object. Populated by the system.
  157. Read-only.
  158. DEPRECATED Kubernetes will stop propagating this field in 1.20 release and
  159. the field is planned to be removed in 1.21 release.
  160. uid <string>
  161. UID is the unique in time and space value for this object. It is typically
  162. generated by the server on successful creation of a resource and is not
  163. allowed to change on PUT operations.
  164. Populated by the system. Read-only. More info:
  165. http://kubernetes.io/docs/user-guide/identifiers#uids
  166. student@master01:~$

这里支持两种语法{{xxxx}}和直接xxx
按照名称进行排序则为{{.metadata.name}}或者.metadata.name
按照创建时间排序{{.metadata.creationTimestamp}}或者.metadata.creationTimestamp
按照存储排序则为{{.spec.capacity.storage}}或者.spec.capacity.storage

排序样例

  1. student@master01:~$ kubectl get pv --sort-by={{.metadata.name}}
  2. NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
  3. pv01 10Mi RWO Retain Available csi-hostpath-sc 72d
  4. student@master01:~$ kubectl get pv --sort-by=.metadata.name
  5. NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
  6. pv01 10Mi RWO Retain Available csi-hostpath-sc 72d
  7. student@master01:~$

特殊说明

针对—sort-by参数在top指令时只有两个可用即cpu和memory

  1. student@master01:~$ kubectl top node -h
  2. Display resource (CPU/memory) usage of nodes.
  3. The top-node command allows you to see the resource consumption of nodes.
  4. Aliases:
  5. node, nodes, no
  6. Examples:
  7. # Show metrics for all nodes
  8. kubectl top node
  9. # Show metrics for a given node
  10. kubectl top node NODE_NAME
  11. Options:
  12. --no-headers=false: If present, print output without headers
  13. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
  14. --show-capacity=false: Print node resources based on Capacity instead of Allocatable(default) of the nodes.
  15. --sort-by='': If non-empty, sort nodes list using specified field. The field can be either 'cpu' or 'memory'.
  16. --use-protocol-buffers=true: Enables using protocol-buffers to access Metrics API.
  17. Usage:
  18. kubectl top node [NAME | -l label] [options]
  19. Use "kubectl options" for a list of global command-line options (applies to all commands).
  20. student@master01:~$
  21. student@master01:~$ kubectl top pod -h
  22. Display resource (CPU/memory) usage of pods.
  23. The 'top pod' command allows you to see the resource consumption of pods.
  24. Due to the metrics pipeline delay, they may be unavailable for a few minutes since pod creation.
  25. Aliases:
  26. pod, pods, po
  27. Examples:
  28. # Show metrics for all pods in the default namespace
  29. kubectl top pod
  30. # Show metrics for all pods in the given namespace
  31. kubectl top pod --namespace=NAMESPACE
  32. # Show metrics for a given pod and its containers
  33. kubectl top pod POD_NAME --containers
  34. # Show metrics for the pods defined by label name=myLabel
  35. kubectl top pod -l name=myLabel
  36. Options:
  37. -A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
  38. context is ignored even if specified with --namespace.
  39. --containers=false: If present, print usage of containers within a pod.
  40. --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
  41. key1=value1,key2=value2). The server only supports a limited number of field queries per type.
  42. --no-headers=false: If present, print output without headers.
  43. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
  44. --sort-by='': If non-empty, sort pods list using specified field. The field can be either 'cpu' or 'memory'.
  45. --use-protocol-buffers=true: Enables using protocol-buffers to access Metrics API.
  46. Usage:
  47. kubectl top pod [NAME | -l label] [options]
  48. Use "kubectl options" for a list of global command-line options (applies to all commands).
  49. student@master01:~$

例如示例例如下



student@master01:~$ kubectl top pod --sort-by=cpu
NAME                            CPU(cores)   MEMORY(bytes)   
11-factor-app                   2m           1Mi             
foo                             0m           10Mi            
front-end-94f5bf8fb-hxg4p       0m           4Mi             
podname1                        0m           3Mi             
podname2                        0m           1Mi             
presentation-5649f596b9-jxfnn   0m           2Mi             
student@master01:~$ kubectl top pod --sort-by=memory
NAME                            CPU(cores)   MEMORY(bytes)   
foo                             0m           10Mi            
front-end-94f5bf8fb-hxg4p       0m           4Mi             
podname1                        0m           3Mi             
presentation-5649f596b9-jxfnn   0m           2Mi             
11-factor-app                   2m           1Mi             
podname2                        0m           1Mi             
student@master01:~$