dump.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. Copyright 2018 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 garbagecollector
  14. import (
  15. "fmt"
  16. "net/http"
  17. "strings"
  18. "gonum.org/v1/gonum/graph"
  19. "gonum.org/v1/gonum/graph/encoding"
  20. "gonum.org/v1/gonum/graph/encoding/dot"
  21. "gonum.org/v1/gonum/graph/simple"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/runtime/schema"
  24. "k8s.io/apimachinery/pkg/types"
  25. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  26. )
  27. type gonumVertex struct {
  28. uid types.UID
  29. gvk schema.GroupVersionKind
  30. namespace string
  31. name string
  32. missingFromGraph bool
  33. beingDeleted bool
  34. deletingDependents bool
  35. virtual bool
  36. vertexID int64
  37. }
  38. func (v *gonumVertex) ID() int64 {
  39. return v.vertexID
  40. }
  41. func (v *gonumVertex) String() string {
  42. kind := v.gvk.Kind + "." + v.gvk.Version
  43. if len(v.gvk.Group) > 0 {
  44. kind = kind + "." + v.gvk.Group
  45. }
  46. missing := ""
  47. if v.missingFromGraph {
  48. missing = "(missing)"
  49. }
  50. deleting := ""
  51. if v.beingDeleted {
  52. deleting = "(deleting)"
  53. }
  54. deletingDependents := ""
  55. if v.deletingDependents {
  56. deleting = "(deletingDependents)"
  57. }
  58. virtual := ""
  59. if v.virtual {
  60. virtual = "(virtual)"
  61. }
  62. return fmt.Sprintf(`%s/%s[%s]-%v%s%s%s%s`, kind, v.name, v.namespace, v.uid, missing, deleting, deletingDependents, virtual)
  63. }
  64. func (v *gonumVertex) Attributes() []encoding.Attribute {
  65. kubectlString := v.gvk.Kind + "." + v.gvk.Version
  66. if len(v.gvk.Group) > 0 {
  67. kubectlString = kubectlString + "." + v.gvk.Group
  68. }
  69. kubectlString = kubectlString + "/" + v.name
  70. label := fmt.Sprintf(`uid=%v
  71. namespace=%v
  72. %v
  73. `,
  74. v.uid,
  75. v.namespace,
  76. kubectlString,
  77. )
  78. conditionStrings := []string{}
  79. if v.beingDeleted {
  80. conditionStrings = append(conditionStrings, "beingDeleted")
  81. }
  82. if v.deletingDependents {
  83. conditionStrings = append(conditionStrings, "deletingDependents")
  84. }
  85. if v.virtual {
  86. conditionStrings = append(conditionStrings, "virtual")
  87. }
  88. if v.missingFromGraph {
  89. conditionStrings = append(conditionStrings, "missingFromGraph")
  90. }
  91. conditionString := strings.Join(conditionStrings, ",")
  92. if len(conditionString) > 0 {
  93. label = label + conditionString + "\n"
  94. }
  95. return []encoding.Attribute{
  96. {Key: "label", Value: fmt.Sprintf(`"%v"`, label)},
  97. // these place metadata in the correct location, but don't conform to any normal attribute for rendering
  98. {Key: "group", Value: fmt.Sprintf(`"%v"`, v.gvk.Group)},
  99. {Key: "version", Value: fmt.Sprintf(`"%v"`, v.gvk.Version)},
  100. {Key: "kind", Value: fmt.Sprintf(`"%v"`, v.gvk.Kind)},
  101. {Key: "namespace", Value: fmt.Sprintf(`"%v"`, v.namespace)},
  102. {Key: "name", Value: fmt.Sprintf(`"%v"`, v.name)},
  103. {Key: "uid", Value: fmt.Sprintf(`"%v"`, v.uid)},
  104. {Key: "missing", Value: fmt.Sprintf(`"%v"`, v.missingFromGraph)},
  105. {Key: "beingDeleted", Value: fmt.Sprintf(`"%v"`, v.beingDeleted)},
  106. {Key: "deletingDependents", Value: fmt.Sprintf(`"%v"`, v.deletingDependents)},
  107. {Key: "virtual", Value: fmt.Sprintf(`"%v"`, v.virtual)},
  108. }
  109. }
  110. func NewGonumVertex(node *node, nodeID int64) *gonumVertex {
  111. gv, err := schema.ParseGroupVersion(node.identity.APIVersion)
  112. if err != nil {
  113. // this indicates a bad data serialization that should be prevented during storage of the API
  114. utilruntime.HandleError(err)
  115. }
  116. return &gonumVertex{
  117. uid: node.identity.UID,
  118. gvk: gv.WithKind(node.identity.Kind),
  119. namespace: node.identity.Namespace,
  120. name: node.identity.Name,
  121. beingDeleted: node.beingDeleted,
  122. deletingDependents: node.deletingDependents,
  123. virtual: node.virtual,
  124. vertexID: nodeID,
  125. }
  126. }
  127. func NewMissingGonumVertex(ownerRef metav1.OwnerReference, nodeID int64) *gonumVertex {
  128. gv, err := schema.ParseGroupVersion(ownerRef.APIVersion)
  129. if err != nil {
  130. // this indicates a bad data serialization that should be prevented during storage of the API
  131. utilruntime.HandleError(err)
  132. }
  133. return &gonumVertex{
  134. uid: ownerRef.UID,
  135. gvk: gv.WithKind(ownerRef.Kind),
  136. name: ownerRef.Name,
  137. missingFromGraph: true,
  138. vertexID: nodeID,
  139. }
  140. }
  141. func (m *concurrentUIDToNode) ToGonumGraph() graph.Directed {
  142. m.uidToNodeLock.Lock()
  143. defer m.uidToNodeLock.Unlock()
  144. return toGonumGraph(m.uidToNode)
  145. }
  146. func toGonumGraph(uidToNode map[types.UID]*node) graph.Directed {
  147. uidToVertex := map[types.UID]*gonumVertex{}
  148. graphBuilder := simple.NewDirectedGraph()
  149. // add the vertices first, then edges. That avoids having to deal with missing refs.
  150. for _, node := range uidToNode {
  151. // skip adding objects that don't have owner references and aren't referred to.
  152. if len(node.dependents) == 0 && len(node.owners) == 0 {
  153. continue
  154. }
  155. vertex := NewGonumVertex(node, graphBuilder.NewNode().ID())
  156. uidToVertex[node.identity.UID] = vertex
  157. graphBuilder.AddNode(vertex)
  158. }
  159. for _, node := range uidToNode {
  160. currVertex := uidToVertex[node.identity.UID]
  161. for _, ownerRef := range node.owners {
  162. currOwnerVertex, ok := uidToVertex[ownerRef.UID]
  163. if !ok {
  164. currOwnerVertex = NewMissingGonumVertex(ownerRef, graphBuilder.NewNode().ID())
  165. uidToVertex[node.identity.UID] = currOwnerVertex
  166. graphBuilder.AddNode(currOwnerVertex)
  167. }
  168. graphBuilder.SetEdge(simple.Edge{
  169. F: currVertex,
  170. T: currOwnerVertex,
  171. })
  172. }
  173. }
  174. return graphBuilder
  175. }
  176. func (m *concurrentUIDToNode) ToGonumGraphForObj(uids ...types.UID) graph.Directed {
  177. m.uidToNodeLock.Lock()
  178. defer m.uidToNodeLock.Unlock()
  179. return toGonumGraphForObj(m.uidToNode, uids...)
  180. }
  181. func toGonumGraphForObj(uidToNode map[types.UID]*node, uids ...types.UID) graph.Directed {
  182. uidsToCheck := append([]types.UID{}, uids...)
  183. interestingNodes := map[types.UID]*node{}
  184. // build the set of nodes to inspect first, then use the normal construction on the subset
  185. for i := 0; i < len(uidsToCheck); i++ {
  186. uid := uidsToCheck[i]
  187. // if we've already been observed, there was a bug, but skip it so we don't loop forever
  188. if _, ok := interestingNodes[uid]; ok {
  189. continue
  190. }
  191. node, ok := uidToNode[uid]
  192. // if there is no node for the UID, skip over it. We may add it to the list multiple times
  193. // but we won't loop forever and hopefully the condition doesn't happen very often
  194. if !ok {
  195. continue
  196. }
  197. interestingNodes[node.identity.UID] = node
  198. for _, ownerRef := range node.owners {
  199. // if we've already inspected this UID, don't add it to be inspected again
  200. if _, ok := interestingNodes[ownerRef.UID]; ok {
  201. continue
  202. }
  203. uidsToCheck = append(uidsToCheck, ownerRef.UID)
  204. }
  205. for dependent := range node.dependents {
  206. // if we've already inspected this UID, don't add it to be inspected again
  207. if _, ok := interestingNodes[dependent.identity.UID]; ok {
  208. continue
  209. }
  210. uidsToCheck = append(uidsToCheck, dependent.identity.UID)
  211. }
  212. }
  213. return toGonumGraph(interestingNodes)
  214. }
  215. func NewDebugHandler(controller *GarbageCollector) http.Handler {
  216. return &debugHTTPHandler{controller: controller}
  217. }
  218. type debugHTTPHandler struct {
  219. controller *GarbageCollector
  220. }
  221. func (h *debugHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  222. if req.URL.Path != "/graph" {
  223. http.Error(w, "", http.StatusNotFound)
  224. return
  225. }
  226. var graph graph.Directed
  227. if uidStrings := req.URL.Query()["uid"]; len(uidStrings) > 0 {
  228. uids := []types.UID{}
  229. for _, uidString := range uidStrings {
  230. uids = append(uids, types.UID(uidString))
  231. }
  232. graph = h.controller.dependencyGraphBuilder.uidToNode.ToGonumGraphForObj(uids...)
  233. } else {
  234. graph = h.controller.dependencyGraphBuilder.uidToNode.ToGonumGraph()
  235. }
  236. data, err := dot.Marshal(graph, "full", "", " ")
  237. if err != nil {
  238. http.Error(w, err.Error(), http.StatusInternalServerError)
  239. return
  240. }
  241. w.Write(data)
  242. w.WriteHeader(http.StatusOK)
  243. }