relation.go 10 KB

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