k8s_references.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /*
  2. Copyright 2021 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 klog
  14. import (
  15. "bytes"
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. "github.com/go-logr/logr"
  20. )
  21. // ObjectRef references a kubernetes object
  22. type ObjectRef struct {
  23. Name string `json:"name"`
  24. Namespace string `json:"namespace,omitempty"`
  25. }
  26. func (ref ObjectRef) String() string {
  27. if ref.Namespace != "" {
  28. var builder strings.Builder
  29. builder.Grow(len(ref.Namespace) + len(ref.Name) + 1)
  30. builder.WriteString(ref.Namespace)
  31. builder.WriteRune('/')
  32. builder.WriteString(ref.Name)
  33. return builder.String()
  34. }
  35. return ref.Name
  36. }
  37. func (ref ObjectRef) WriteText(out *bytes.Buffer) {
  38. out.WriteRune('"')
  39. ref.writeUnquoted(out)
  40. out.WriteRune('"')
  41. }
  42. func (ref ObjectRef) writeUnquoted(out *bytes.Buffer) {
  43. if ref.Namespace != "" {
  44. out.WriteString(ref.Namespace)
  45. out.WriteRune('/')
  46. }
  47. out.WriteString(ref.Name)
  48. }
  49. // MarshalLog ensures that loggers with support for structured output will log
  50. // as a struct by removing the String method via a custom type.
  51. func (ref ObjectRef) MarshalLog() interface{} {
  52. type or ObjectRef
  53. return or(ref)
  54. }
  55. var _ logr.Marshaler = ObjectRef{}
  56. // KMetadata is a subset of the kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface
  57. // this interface may expand in the future, but will always be a subset of the
  58. // kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface
  59. type KMetadata interface {
  60. GetName() string
  61. GetNamespace() string
  62. }
  63. // KObj returns ObjectRef from ObjectMeta
  64. func KObj(obj KMetadata) ObjectRef {
  65. if obj == nil {
  66. return ObjectRef{}
  67. }
  68. if val := reflect.ValueOf(obj); val.Kind() == reflect.Ptr && val.IsNil() {
  69. return ObjectRef{}
  70. }
  71. return ObjectRef{
  72. Name: obj.GetName(),
  73. Namespace: obj.GetNamespace(),
  74. }
  75. }
  76. // KRef returns ObjectRef from name and namespace
  77. func KRef(namespace, name string) ObjectRef {
  78. return ObjectRef{
  79. Name: name,
  80. Namespace: namespace,
  81. }
  82. }
  83. // KObjs returns slice of ObjectRef from an slice of ObjectMeta
  84. //
  85. // DEPRECATED: Use KObjSlice instead, it has better performance.
  86. func KObjs(arg interface{}) []ObjectRef {
  87. s := reflect.ValueOf(arg)
  88. if s.Kind() != reflect.Slice {
  89. return nil
  90. }
  91. objectRefs := make([]ObjectRef, 0, s.Len())
  92. for i := 0; i < s.Len(); i++ {
  93. if v, ok := s.Index(i).Interface().(KMetadata); ok {
  94. objectRefs = append(objectRefs, KObj(v))
  95. } else {
  96. return nil
  97. }
  98. }
  99. return objectRefs
  100. }
  101. // KObjSlice takes a slice of objects that implement the KMetadata interface
  102. // and returns an object that gets logged as a slice of ObjectRef values or a
  103. // string containing those values, depending on whether the logger prefers text
  104. // output or structured output.
  105. //
  106. // An error string is logged when KObjSlice is not passed a suitable slice.
  107. //
  108. // Processing of the argument is delayed until the value actually gets logged,
  109. // in contrast to KObjs where that overhead is incurred regardless of whether
  110. // the result is needed.
  111. func KObjSlice(arg interface{}) interface{} {
  112. return kobjSlice{arg: arg}
  113. }
  114. type kobjSlice struct {
  115. arg interface{}
  116. }
  117. var _ fmt.Stringer = kobjSlice{}
  118. var _ logr.Marshaler = kobjSlice{}
  119. func (ks kobjSlice) String() string {
  120. objectRefs, errStr := ks.process()
  121. if errStr != "" {
  122. return errStr
  123. }
  124. return fmt.Sprintf("%v", objectRefs)
  125. }
  126. func (ks kobjSlice) MarshalLog() interface{} {
  127. objectRefs, errStr := ks.process()
  128. if errStr != "" {
  129. return errStr
  130. }
  131. return objectRefs
  132. }
  133. func (ks kobjSlice) process() (objs []interface{}, err string) {
  134. s := reflect.ValueOf(ks.arg)
  135. switch s.Kind() {
  136. case reflect.Invalid:
  137. // nil parameter, print as nil.
  138. return nil, ""
  139. case reflect.Slice:
  140. // Okay, handle below.
  141. default:
  142. return nil, fmt.Sprintf("<KObjSlice needs a slice, got type %T>", ks.arg)
  143. }
  144. objectRefs := make([]interface{}, 0, s.Len())
  145. for i := 0; i < s.Len(); i++ {
  146. item := s.Index(i).Interface()
  147. if item == nil {
  148. objectRefs = append(objectRefs, nil)
  149. } else if v, ok := item.(KMetadata); ok {
  150. objectRefs = append(objectRefs, KObj(v))
  151. } else {
  152. return nil, fmt.Sprintf("<KObjSlice needs a slice of values implementing KMetadata, got type %T>", item)
  153. }
  154. }
  155. return objectRefs, ""
  156. }
  157. var nilToken = []byte("null")
  158. func (ks kobjSlice) WriteText(out *bytes.Buffer) {
  159. s := reflect.ValueOf(ks.arg)
  160. switch s.Kind() {
  161. case reflect.Invalid:
  162. // nil parameter, print as null.
  163. out.Write(nilToken)
  164. return
  165. case reflect.Slice:
  166. // Okay, handle below.
  167. default:
  168. fmt.Fprintf(out, `"<KObjSlice needs a slice, got type %T>"`, ks.arg)
  169. return
  170. }
  171. out.Write([]byte{'['})
  172. defer out.Write([]byte{']'})
  173. for i := 0; i < s.Len(); i++ {
  174. if i > 0 {
  175. out.Write([]byte{','})
  176. }
  177. item := s.Index(i).Interface()
  178. if item == nil {
  179. out.Write(nilToken)
  180. } else if v, ok := item.(KMetadata); ok {
  181. KObj(v).WriteText(out)
  182. } else {
  183. fmt.Fprintf(out, `"<KObjSlice needs a slice of values implementing KMetadata, got type %T>"`, item)
  184. return
  185. }
  186. }
  187. }