getter.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2019 Yunion
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package k8s
  15. import (
  16. "fmt"
  17. "strings"
  18. "time"
  19. "github.com/hako/durafmt"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. )
  23. var (
  24. getName nameGetter
  25. getStatus statusGetter
  26. getAge ageGetter
  27. getNamespace namespaceGetter
  28. getLabel labelGetter
  29. )
  30. type nameGetter struct{}
  31. func (g nameGetter) Get_Id(obj jsonutils.JSONObject) interface{} {
  32. id, _ := obj.GetString("id")
  33. return id
  34. }
  35. func (g nameGetter) Get_Name(obj jsonutils.JSONObject) interface{} {
  36. name, _ := obj.GetString("name")
  37. return name
  38. }
  39. type statusGetter struct{}
  40. func (g statusGetter) Get_Status(obj jsonutils.JSONObject) interface{} {
  41. status, _ := obj.GetString("status")
  42. return status
  43. }
  44. type ageGetter struct{}
  45. func (g ageGetter) Get_Age(obj jsonutils.JSONObject) interface{} {
  46. creationTimestamp, err := obj.GetString("creationTimestamp")
  47. if err != nil {
  48. creationTimestamp, err = obj.GetString("created_at")
  49. if err != nil {
  50. log.Errorf("Get creationTimestamp and created_at error: %v", err)
  51. return nil
  52. }
  53. }
  54. t, err := time.Parse(time.RFC3339, creationTimestamp)
  55. if err != nil {
  56. log.Errorf("parse creationTimestamp %v: %v", creationTimestamp, err)
  57. return nil
  58. }
  59. dur := time.Since(t)
  60. return durafmt.ParseShort(dur).String()
  61. }
  62. type namespaceGetter struct{}
  63. func (g namespaceGetter) Get_Namespace(obj jsonutils.JSONObject) interface{} {
  64. ns, _ := obj.GetString("namespace")
  65. return ns
  66. }
  67. type labelGetter struct{}
  68. func (g labelGetter) Get_Labels(obj jsonutils.JSONObject) interface{} {
  69. labels, _ := obj.GetMap("labels")
  70. str := ""
  71. ls := []string{}
  72. for k, v := range labels {
  73. vs, _ := v.GetString()
  74. ls = append(ls, fmt.Sprintf("%s=%s", k, vs))
  75. }
  76. if len(ls) != 0 {
  77. str = strings.Join(ls, ",")
  78. }
  79. return str
  80. }