pod.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package format
  14. import (
  15. "fmt"
  16. "strings"
  17. "time"
  18. "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/types"
  20. )
  21. type podHandler func(*v1.Pod) string
  22. // Pod returns a string representing a pod in a consistent human readable format,
  23. // with pod UID as part of the string.
  24. func Pod(pod *v1.Pod) string {
  25. return PodDesc(pod.Name, pod.Namespace, pod.UID)
  26. }
  27. // PodDesc returns a string representing a pod in a consistent human readable format,
  28. // with pod UID as part of the string.
  29. func PodDesc(podName, podNamespace string, podUID types.UID) string {
  30. // Use underscore as the delimiter because it is not allowed in pod name
  31. // (DNS subdomain format), while allowed in the container name format.
  32. return fmt.Sprintf("%s_%s(%s)", podName, podNamespace, podUID)
  33. }
  34. // PodWithDeletionTimestamp is the same as Pod. In addition, it prints the
  35. // deletion timestamp of the pod if it's not nil.
  36. func PodWithDeletionTimestamp(pod *v1.Pod) string {
  37. var deletionTimestamp string
  38. if pod.DeletionTimestamp != nil {
  39. deletionTimestamp = ":DeletionTimestamp=" + pod.DeletionTimestamp.UTC().Format(time.RFC3339)
  40. }
  41. return Pod(pod) + deletionTimestamp
  42. }
  43. // Pods returns a string representation a list of pods in a human
  44. // readable format.
  45. func Pods(pods []*v1.Pod) string {
  46. return aggregatePods(pods, Pod)
  47. }
  48. // PodsWithDeletionTimestamps is the same as Pods. In addition, it prints the
  49. // deletion timestamps of the pods if they are not nil.
  50. func PodsWithDeletionTimestamps(pods []*v1.Pod) string {
  51. return aggregatePods(pods, PodWithDeletionTimestamp)
  52. }
  53. func aggregatePods(pods []*v1.Pod, handler podHandler) string {
  54. podStrings := make([]string, 0, len(pods))
  55. for _, pod := range pods {
  56. podStrings = append(podStrings, handler(pod))
  57. }
  58. return fmt.Sprintf(strings.Join(podStrings, ", "))
  59. }