/
resource.go
309 lines (273 loc) · 7.04 KB
/
resource.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package service
import (
"bytes"
"encoding/json"
"fmt"
"github.com/emreodabas/kubectl-bulk/pkg/interaction"
"github.com/emreodabas/kubectl-bulk/pkg/model"
"github.com/emreodabas/kubectl-bulk/pkg/utils"
"io/ioutil"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"os"
"regexp"
"strings"
)
var resourceList []model.Resource
// need to dynamic be for kubectl context and fixed in a path
const path = ".api-resource-cache.json"
func ResourceSelection(command *model.Command) error {
list, err := GetResourceList()
if err != nil {
return err
}
command.Resource = interaction.ShowResourceList(list)
return nil
}
func GetResourceList() ([]model.Resource, error) {
if cacheFileExist() {
resourceList, err := readResourcelist()
if err != nil {
return nil, err
}
return resourceList, nil
}
result := make(map[string]model.Resource) // resource could have multi group
_, clientset, err := getClientSet()
if err != nil {
return nil, err
}
resources, _ := clientset.ServerPreferredResources()
for _, res := range resources {
if res.APIResources != nil && len(res.APIResources) > 0 {
groupVersion, _ := schema.ParseGroupVersion(res.GroupVersion)
for i := 0; i < len(res.APIResources); i++ {
groupV := result[res.APIResources[i].Kind].GroupVersion
if groupV != nil {
groupV = append(groupV, groupVersion)
result[res.APIResources[i].Kind] =
model.Resource{res.APIResources[i].Name,
res.APIResources[i].Namespaced,
res.APIResources[i].Kind,
res.APIResources[i].ShortNames,
res.APIResources[i].Verbs,
res.GroupVersionKind(),
groupV,
}
} else {
var groupV = []schema.GroupVersion{groupVersion}
result[res.APIResources[i].Kind] =
model.Resource{res.APIResources[i].Name,
res.APIResources[i].Namespaced,
res.APIResources[i].Kind,
res.APIResources[i].ShortNames,
res.APIResources[i].Verbs,
res.GroupVersionKind(),
groupV,
}
}
}
}
}
for i := range result {
resourceList = append(resourceList, result[i])
}
saveResourcelist(resourceList)
return resourceList, nil
}
func saveResourcelist(resourceList []model.Resource) {
//resources := model.Resources{Resources: resourceList}
_, err := WriteDataToFileAsJSON(resourceList, path)
if err != nil {
fmt.Println(err)
}
}
func WriteDataToFileAsJSON(data interface{}, filedir string) (int, error) {
//write data as buffer to json encoder
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent("", "\t")
err := encoder.Encode(data)
if err != nil {
return 0, err
}
file, err := os.OpenFile(filedir, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return 0, err
}
n, err := file.Write(buffer.Bytes())
if err != nil {
return 0, err
}
return n, nil
}
func cacheFileExist() bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func readResourcelist() ([]model.Resource, error) {
// Open our jsonFile
jsonFile, err := os.Open(path)
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println("ERROR!!")
fmt.Println(err)
return []model.Resource{}, err
}
defer jsonFile.Close()
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// we initialize our Users array
var resources []model.Resource
// we unmarshal our byteArray which contains our
// jsonFile's content into 'users' which we defined above
err = json.Unmarshal(byteValue, &resources)
if err != nil {
fmt.Errorf("Marshall problem")
}
return resources, nil
}
func GetResource(resourceName string) (model.Resource, error) {
//TODO could be cached
resourceList, _ := GetResourceList()
resourceName = strings.ToLower(resourceName)
for i := 0; i < len(resourceList); i++ {
if strings.ToLower(resourceList[i].Kind) == resourceName || utils.Contains(resourceList[i].ShortName, resourceName) {
return resourceList[i], nil
}
}
return model.Resource{}, fmt.Errorf(resourceName + " is not a valid resource.")
}
func GetNamespaces() ([]string, error) {
var res []string
res = append(res, "all-namespaces[-A]")
_, clientset, err := getClientSet()
if err != nil {
return nil, fmt.Errorf("K8s client could not created")
}
var next string
for {
list, _ := clientset.CoreV1().Namespaces().List(v1.ListOptions{
Limit: 250,
Continue: next,
})
for i := 0; i < len(list.Items); i++ {
res = append(res, list.Items[i].Name)
}
next = list.GetContinue()
if next == "" {
break
}
}
return res, nil
}
func SourceSelection(command *model.Command) error {
// filter or multi selection could be ask to user
var err error
if command.Resource.Namespaced {
namespaces, err := GetNamespaces()
command.Namespace = interaction.ShowList(namespaces)
if err != nil {
return fmt.Errorf("Namespace list could not fetch")
}
err = FetchInstances(command)
} else {
err = FetchInstances(command)
}
if err != nil {
return err
}
return err
}
func FetchInstances(command *model.Command) error {
var res []unstructured.Unstructured
var list *unstructured.UnstructuredList
resource := command.Resource
namespace := command.Namespace
clientset, _, err := getClientSet()
if err != nil {
return fmt.Errorf("K8s client could not created ")
}
var next string
listOptions := v1.ListOptions{
Limit: 250,
Continue: next,
}
if command.LabelFilter != "" {
listOptions.LabelSelector = command.LabelFilter
}
if command.FieldSelector != "" {
listOptions.FieldSelector = command.FieldSelector
}
for i := 0; i < len(resource.GroupVersion); i++ {
gv := resource.GroupVersion[i]
resourceInterface := clientset.Resource(schema.GroupVersionResource{
Group: gv.Group,
Version: gv.Version,
Resource: resource.Name,
})
if namespace != "all-namespaces[-A]" {
for {
list, err = resourceInterface.Namespace(namespace).List(listOptions)
if err != nil {
return err
}
res = append(res, list.Items...)
next = list.GetContinue()
if next == "" {
break
}
}
} else {
for {
list, err = resourceInterface.List(listOptions)
if err != nil {
return err
}
if list != nil {
res = append(res, list.Items...)
next = list.GetContinue()
if next == "" {
break
}
} else {
break
}
}
}
}
if res != nil {
var temp []unstructured.Unstructured
if len(command.GrepFilter) > 0 {
var grepFilter = command.GrepFilter
for i, item := range grepFilter {
if strings.Contains(item, "-i") {
item = strings.Trim(item, "-i")
item = strings.Trim(item, " ")
item = "(?i)" + item
grepFilter[i] = item
}
}
for _, item := range res {
marshalJSON, _ := item.MarshalJSON()
var allContains = true
for _, grep := range grepFilter {
match, _ := regexp.Match(grep, marshalJSON)
if !match {
allContains = false
}
}
if allContains {
temp = append(temp, item)
}
}
res = temp
}
command.List = utils.Unique(res)
}
return nil
}