relation.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package grapher
  2. import (
  3. "strconv"
  4. )
  5. // Relation describes the relationship between k8s components. Type is one of CostrolRel, LabelRel, AnnotationsRel, SpecRel.
  6. // Source and Target contains the ID of the k8s component that is either the giver or recipient of a relationship.
  7. // All relations are bi-directional in that each object contains both the incoming and outbound relationships.
  8. type Relation struct {
  9. Source int
  10. Target int
  11. }
  12. // ControlRel describes the relationship between a controller and its children pod.
  13. type ControlRel struct {
  14. Relation
  15. Replicas int
  16. Template map[string]interface{}
  17. }
  18. // LabelRel connects objects with spec.selector with pods that have corresponding metadata.labels.
  19. type LabelRel struct {
  20. Relation
  21. }
  22. // SpecRel connects objects via various spec properties.
  23. type SpecRel struct {
  24. Relation
  25. }
  26. // ParsedObjs has methods GetControlRel and GetLabelRel that updates its objects array.
  27. type ParsedObjs struct {
  28. Objects []Object
  29. }
  30. // Relations is embedded into the Object struct and contains arrays of the three types of relationships.
  31. type Relations struct {
  32. ControlRels []ControlRel
  33. LabelRels []LabelRel
  34. SpecRels []SpecRel
  35. }
  36. // MatchLabel is used to match Equality label selector.
  37. type MatchLabel struct {
  38. key string
  39. value string
  40. }
  41. // MatchExpression is used to match Set-based label selectors.
  42. type MatchExpression struct {
  43. key string
  44. operator string // In, NotIn, Exists, DoesNotExist are valid
  45. values []string
  46. }
  47. // =============== helpers for parsing relationships from YAML ===============
  48. // GetControlRel generates relationships and children objects for common k8s controller types.
  49. // Note that this only includes controllers whose children are 1) pods and 2) do not have its own YAML.
  50. // i.e. Children relies entirely on the parent's template. Controllers like CronJob are excluded because its children are not pods.
  51. func (parsed *ParsedObjs) GetControlRel() {
  52. // First collect all children (Pods) that are not included in the yaml as top-level object.
  53. children := []Object{}
  54. for i, obj := range parsed.Objects {
  55. yaml := obj.RawYAML
  56. switch kind := getField(yaml, "kind").(string); kind {
  57. // Parse for all possible controller types
  58. case "Deployment", "StatefulSet", "ReplicaSet", "DaemonSet", "Job":
  59. rs := getField(yaml, "spec", "replicas")
  60. if rs != nil && rs.(int) > 0 {
  61. // Add Pods for controller objects
  62. template := getField(yaml, "spec", "template").(map[string]interface{})
  63. for j := 0; j < rs.(int); j++ {
  64. cid := len(parsed.Objects) + len(children)
  65. crel := ControlRel{
  66. Relation: Relation{
  67. Source: obj.ID,
  68. Target: cid,
  69. },
  70. Replicas: rs.(int),
  71. }
  72. pod := Object{
  73. ID: cid,
  74. Kind: "Pod",
  75. Name: obj.Name + "-" + strconv.Itoa(j), // tentative name pre-deploy
  76. Namespace: obj.Namespace,
  77. RawYAML: template,
  78. Relations: Relations{
  79. ControlRels: []ControlRel{
  80. crel,
  81. },
  82. },
  83. }
  84. children = append(children, pod)
  85. obj.Relations.ControlRels = append(obj.Relations.ControlRels, crel)
  86. parsed.Objects[i] = obj
  87. }
  88. }
  89. }
  90. }
  91. // add children to the objects array at the end.
  92. parsed.Objects = append(parsed.Objects, children...)
  93. }
  94. // GetLabelRel is generates relationships between objects connected by selector-label.
  95. // It supports both Equality-based and Set-based operators with MatchLabels and MatchExpressions, respectively.
  96. func (parsed *ParsedObjs) GetLabelRel() {
  97. for i, o := range parsed.Objects {
  98. // Skip Pods
  99. yaml := o.RawYAML
  100. matchLabels := []MatchLabel{}
  101. matchExpressions := []MatchExpression{}
  102. // First check for the outdated syntax (matchLabels were added in recent k8s version)
  103. if l := getField(yaml, "spec", "selector"); l != nil {
  104. simple := true
  105. if ml := getField(yaml, "spec", "selector", "matchLabels"); ml != nil {
  106. matchLabels = addMatchLabels(matchLabels, ml.(map[string]interface{}))
  107. simple = false
  108. }
  109. if me := getField(yaml, "spec", "selector", "matchExpressions"); me != nil {
  110. for _, o := range me.([]interface{}) {
  111. ot := o.(map[string]interface{})
  112. values := []string{}
  113. for _, arg := range ot["values"].([]interface{}) {
  114. values = append(values, arg.(string))
  115. }
  116. matchExpressions = append(matchExpressions, MatchExpression{
  117. key: ot["key"].(string),
  118. operator: ot["operator"].(string),
  119. values: values,
  120. })
  121. }
  122. simple = false
  123. }
  124. if simple {
  125. matchLabels = addMatchLabels(matchLabels, l.(map[string]interface{}))
  126. }
  127. }
  128. // Find ID's of targets that match the label selector
  129. targetID := parsed.findLabelsBySelector(o.ID, matchLabels, matchExpressions)
  130. lrels := o.Relations.LabelRels
  131. for _, tid := range targetID {
  132. newrel := LabelRel{
  133. Relation{
  134. Source: o.ID,
  135. Target: tid,
  136. },
  137. }
  138. lrels = append(lrels, newrel)
  139. }
  140. parsed.Objects[i].Relations.LabelRels = lrels
  141. }
  142. }
  143. // GetSpecRel draws relationships between two objects that are tied via various fields in their spec.
  144. func (parsed *ParsedObjs) GetSpecRel() {
  145. for i, o := range parsed.Objects {
  146. tid := []int{}
  147. switch o.Kind {
  148. case "ClusterRoleBinding", "RoleBinding":
  149. tid = parsed.findRBACTargets(o.ID, o.RawYAML)
  150. case "Ingress":
  151. rules := getField(o.RawYAML, "spec", "rules")
  152. if rules == nil {
  153. rules = []interface{}{}
  154. }
  155. for _, r := range rules.([]interface{}) {
  156. paths := getField(r.(map[string]interface{}), "http", "paths")
  157. if paths == nil {
  158. paths = []interface{}{}
  159. }
  160. for _, p := range paths.([]interface{}) {
  161. // service and resource are mutually exclusive backend types.
  162. name := getField(p.(map[string]interface{}), "backend", "serviceName")
  163. kind := "Service"
  164. if name == nil {
  165. name = getField(p.(map[string]interface{}), "backend", "service", "name")
  166. }
  167. if name == nil {
  168. name = getField(p.(map[string]interface{}), "backend", "resource", "name")
  169. kind = getField(p.(map[string]interface{}), "backend", "resource", "kind").(string)
  170. }
  171. tid = parsed.findObjectByNameAndKind(o.ID, name, kind)
  172. }
  173. }
  174. case "StatefulSet":
  175. serviceName := getField(o.RawYAML, "spec", "serviceName")
  176. tid = append(tid, parsed.findObjectByNameAndKind(o.ID, serviceName, "Service")...)
  177. case "Pod":
  178. volume := getField(o.RawYAML, "spec", "volumes")
  179. imageSecrets := getField(o.RawYAML, "spec", "ImagePullSecrets")
  180. serviceAccount := getField(o.RawYAML, "spec", "serviceAccountName")
  181. if imageSecrets == nil {
  182. imageSecrets = []interface{}{}
  183. }
  184. if volume == nil {
  185. volume = []interface{}{}
  186. }
  187. for _, sec := range imageSecrets.([]interface{}) {
  188. tid = append(tid, parsed.findObjectByNameAndKind(o.ID, sec, "Secret")...)
  189. }
  190. tid = append(tid, parsed.findObjectByNameAndKind(o.ID, serviceAccount, "ServiceAccount")...)
  191. for _, v := range volume.([]interface{}) {
  192. vt := v.(map[string]interface{})
  193. configMap := getField(vt, "configMap", "name")
  194. pvc := getField(vt, "persistentVolumeClaim", "claimName")
  195. secret := getField(vt, "secret", "secretName")
  196. tid = append(tid, parsed.findObjectByNameAndKind(o.ID, configMap, "ConfigMap")...)
  197. tid = append(tid, parsed.findObjectByNameAndKind(o.ID, pvc, "PersistentVolumeClaim")...)
  198. tid = append(tid, parsed.findObjectByNameAndKind(o.ID, secret, "Secret")...)
  199. }
  200. }
  201. // Add edges to parent
  202. rels := o.Relations.SpecRels
  203. for _, id := range tid {
  204. newrel := SpecRel{
  205. Relation{
  206. Source: o.ID,
  207. Target: id,
  208. },
  209. }
  210. rels = append(rels, newrel)
  211. }
  212. parsed.Objects[i].Relations.SpecRels = rels
  213. }
  214. }
  215. // SpecRel helpers
  216. func (parsed *ParsedObjs) findObjectByNameAndKind(parentID int, name interface{}, kind string) []int {
  217. targets := []int{}
  218. if name == nil {
  219. return targets
  220. }
  221. name = name.(string)
  222. for i, o := range parsed.Objects {
  223. newrel := SpecRel{
  224. Relation{
  225. Source: parentID,
  226. Target: o.ID,
  227. },
  228. }
  229. if o.Name == name && o.Kind == kind {
  230. // Add bidirectional link from children as well.
  231. parsed.Objects[i].Relations.SpecRels = append(parsed.Objects[i].Relations.SpecRels, newrel)
  232. targets = append(targets, o.ID)
  233. return targets
  234. }
  235. }
  236. return targets
  237. }
  238. func (parsed *ParsedObjs) findRBACTargets(parentID int, yaml map[string]interface{}) []int {
  239. roleRef := getField(yaml, "roleRef")
  240. subjects := getField(yaml, "subjects")
  241. rules := append(subjects.([]interface{}), roleRef)
  242. targets := []int{}
  243. for i, o := range parsed.Objects {
  244. for _, r := range rules {
  245. tr := r.(map[string]interface{})
  246. newrel := SpecRel{
  247. Relation{
  248. Source: parentID,
  249. Target: o.ID,
  250. },
  251. }
  252. // first consider case of targets added via subjects, which are namespace scoped.
  253. if tr["namespace"] != nil && o.Kind == tr["kind"] &&
  254. o.Name == tr["name"] && o.Namespace == tr["namespace"] {
  255. // Add bidirectional link from children as well.
  256. parsed.Objects[i].Relations.SpecRels = append(parsed.Objects[i].Relations.SpecRels, newrel)
  257. targets = append(targets, o.ID)
  258. } else if tr["namespace"] == nil && o.Kind == tr["kind"] && o.Name == tr["name"] {
  259. parsed.Objects[i].Relations.SpecRels = append(parsed.Objects[i].Relations.SpecRels, newrel)
  260. targets = append(targets, o.ID)
  261. }
  262. }
  263. }
  264. return targets
  265. }
  266. func addMatchLabels(matchLabels []MatchLabel, ml map[string]interface{}) []MatchLabel {
  267. for k, v := range ml {
  268. matchLabels = append(matchLabels, MatchLabel{
  269. key: k,
  270. value: v.(string),
  271. })
  272. }
  273. return matchLabels
  274. }
  275. // TODO: Implement MatchExpression for set based operations.
  276. func (parsed *ParsedObjs) findLabelsBySelector(parentID int, ml []MatchLabel, me []MatchExpression) []int {
  277. matchedObjs := []int{}
  278. for i, o := range parsed.Objects {
  279. // Only Pods can be selected by spec.selector
  280. if o.Kind != "Pod" {
  281. continue
  282. }
  283. // find Pods that match labels
  284. labels := getField(o.RawYAML, "metadata", "labels")
  285. match := 0
  286. for _, l := range ml {
  287. if labels.(map[string]interface{})[l.key] == l.value {
  288. match++
  289. }
  290. }
  291. // Returns only if labels meet all conditions of the selector.
  292. if match == len(ml) && match > 0 {
  293. newrel := LabelRel{
  294. Relation{
  295. Source: parentID,
  296. Target: o.ID,
  297. },
  298. }
  299. // Add bidirectional link from children as well.
  300. parsed.Objects[i].Relations.LabelRels = append(parsed.Objects[i].Relations.LabelRels, newrel)
  301. matchedObjs = append(matchedObjs, o.ID)
  302. }
  303. }
  304. return matchedObjs
  305. }