-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
191 lines (159 loc) · 4.75 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"bytes"
"context"
"flag"
"fmt"
"log"
"strings"
"github.com/goccy/go-graphviz"
"github.com/goccy/go-graphviz/cgraph"
"k8s.io/client-go/discovery"
"k8s.io/client-go/restmapper"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/tools/clientcmd"
)
var (
kubeconfig *string
group *string
version *string
resource *string
name *string
namespace *string
)
type Graphz struct {
client dynamic.Interface
mapper meta.RESTMapper
graph *cgraph.Graph
}
func init() {
kubeconfig = flag.String("kubeconfig", "kubeconfig", "(optional) absolute path to the kubeconfig file")
// object GVR flags
group = flag.String("group", "", "Group of the object")
version = flag.String("version", "v1", "Version of the object")
resource = flag.String("resource", "pods", "Resource of the object")
// object details flags
name = flag.String("name", "coredns", "Name of the object")
namespace = flag.String("namespace", "default", "Namespace of the object")
}
// fetchOnwerReferences return the references to the owners of a particular object
func (g *Graphz) fetchOnwerReferences(group, version, resource, namespace, name string) ([]interface{}, error) {
scheme := schema.GroupVersionResource{Group: group, Version: version, Resource: resource}
res, err := g.client.Resource(scheme).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return nil, err
}
metadata, exists, err := unstructured.NestedMap(res.Object, "metadata")
if err != nil && !exists {
panic(err)
}
owners := metadata["ownerReferences"]
if owners != nil { // typecase on owners existence
return owners.([]interface{}), nil
}
return nil, nil
}
// fetchRecursiveOwners traverse with bfs and create edges between nodes
func (g *Graphz) fetchRecursiveOwners(owners []interface{}, node *cgraph.Node) {
for _, n := range owners {
owner := n.(map[string]interface{})
apiVersion := owner["apiVersion"].(string)
avSplit := strings.Split(apiVersion, "/")
ownerKind := owner["kind"].(string)
ownerName := owner["name"].(string)
// create owner node
gnode, err := g.graph.CreateNode(generateNodeName(ownerName, apiVersion, ownerKind))
if err != nil {
panic(err.Error())
}
// create owner node and node edge
_, err = g.graph.CreateEdge("", node, gnode)
if err != nil {
panic(err.Error())
}
// convert GVK to GVR, so it's possible to fetch object owners
gk := schema.ParseGroupKind(fmt.Sprintf("%s.%s", ownerKind, avSplit[0]))
mapping, err := g.mapper.RESTMapping(gk)
if err != nil {
panic(err)
}
owners, err := g.fetchOnwerReferences(mapping.Resource.Group, mapping.Resource.Version, mapping.Resource.Resource, *namespace, ownerName)
if err != nil {
panic(err.Error())
}
if owners != nil {
g.fetchRecursiveOwners(owners, gnode)
}
}
}
// NewClients return dynamic and discovery clients
func NewClients(kubeconfig *string) (*discovery.DiscoveryClient, dynamic.Interface, error) {
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
return nil, nil, err
}
client, err := dynamic.NewForConfig(config)
if err != nil {
return nil, nil, err
}
return discovery.NewDiscoveryClientForConfigOrDie(config), client, nil
}
// generateNodeName return GRV/GRK formatted name
func generateNodeName(name, group, resource string) string {
return fmt.Sprintf("%s\n%s\n%s", resource, group, name)
}
func main() {
var (
owners []interface{}
buf bytes.Buffer
)
flag.Parse()
// create graphviz setup
g := graphviz.New()
graph, err := g.Graph()
if err != nil {
log.Fatal(err)
}
defer func() {
if err := graph.Close(); err != nil {
log.Fatal(err)
}
g.Close()
}()
// return discovery and dynamic clients
discovery, client, err := NewClients(kubeconfig)
if err != nil {
panic(err.Error())
}
// setup initial mapper from gvr -> gvk
groupResources, err := restmapper.GetAPIGroupResources(discovery)
if err != nil {
panic(err.Error())
}
mapper := restmapper.NewDiscoveryRESTMapper(groupResources)
// add initial node from passed parameter
gz := &Graphz{
client: client,
mapper: mapper,
graph: graph,
}
node, err := graph.CreateNode(generateNodeName(*name, *group, *resource))
if err != nil {
log.Fatal(err)
}
// fetch initial parent owners of the object
if owners, err = gz.fetchOnwerReferences(*group, *version, *resource, *namespace, *name); err != nil {
panic(err.Error())
}
gz.fetchRecursiveOwners(owners, node)
// print out diagram
if err := g.Render(graph, "dot", &buf); err != nil {
log.Fatalf("%+v", err)
}
fmt.Println(buf.String())
}