forked from jumpserver/koko
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect_handler.go
More file actions
445 lines (398 loc) · 11.2 KB
/
select_handler.go
File metadata and controls
445 lines (398 loc) · 11.2 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package handler
import (
"fmt"
"sort"
"strconv"
"strings"
"github.com/jumpserver/koko/pkg/i18n"
"github.com/jumpserver/koko/pkg/jms-sdk-go/model"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/utils"
)
type dataSource string
const (
loadingFromLocal dataSource = "local"
loadingFromRemote dataSource = "remote"
)
type selectType int
const (
TypeAsset selectType = iota + 1
TypeNodeAsset
TypeK8s
TypeDatabase
)
type UserSelectHandler struct {
user *model.User
h *InteractiveHandler
loadingPolicy dataSource
currentType selectType
searchKeys []string
hasPre bool
hasNext bool
allLocalData []map[string]interface{}
selectedNode model.Node
currentResult []map[string]interface{}
*pageInfo
}
func (u *UserSelectHandler) SetSelectType(s selectType) {
u.SetLoadPolicy(loadingFromRemote) // default remote
switch s {
case TypeAsset:
switch u.h.assetLoadPolicy {
case "all":
u.SetLoadPolicy(loadingFromLocal)
u.AutoCompletion()
}
u.h.term.SetPrompt("[Host]> ")
case TypeNodeAsset:
u.h.term.SetPrompt("[Host]> ")
case TypeK8s:
u.h.term.SetPrompt("[K8S]> ")
case TypeDatabase:
u.h.term.SetPrompt("[DB]> ")
}
u.currentType = s
}
func (u *UserSelectHandler) AutoCompletion() {
assets := u.Retrieve(0, 0, "")
suggests := make([]string, 0, len(assets))
for _, v := range assets {
switch u.currentType {
case TypeAsset, TypeNodeAsset:
suggests = append(suggests, v["hostname"].(string))
default:
suggests = append(suggests, v["name"].(string))
}
}
sort.Strings(suggests)
u.h.term.AutoCompleteCallback = func(line string, pos int, key rune) (newLine string, newPos int, ok bool) {
if key == 9 {
termWidth, _ := u.h.term.GetSize()
if len(line) >= 1 {
sugs := utils.FilterPrefix(suggests, line)
if len(sugs) >= 1 {
commonPrefix := utils.LongestCommonPrefix(sugs)
switch u.currentType {
case TypeAsset, TypeNodeAsset:
fmt.Fprintf(u.h.term, "%s%s\n%s\n", "[Host]> ", line, utils.Pretty(sugs, termWidth))
case TypeK8s:
fmt.Fprintf(u.h.term, "%s%s\n%s\n", "[K8S]> ", line, utils.Pretty(sugs, termWidth))
case TypeDatabase:
fmt.Fprintf(u.h.term, "%s%s\n%s\n", "[DB]> ", line, utils.Pretty(sugs, termWidth))
}
return commonPrefix, len(commonPrefix), true
}
}
}
return newLine, newPos, false
}
}
func (u *UserSelectHandler) SetNode(node model.Node) {
u.SetSelectType(TypeNodeAsset)
u.selectedNode = node
}
func (u *UserSelectHandler) SetAllLocalData(data []map[string]interface{}) {
// 使用副本
u.allLocalData = make([]map[string]interface{}, len(data))
copy(u.allLocalData, data)
}
func (u *UserSelectHandler) SetLoadPolicy(policy dataSource) {
u.loadingPolicy = policy
}
func (u *UserSelectHandler) MoveNextPage() {
if u.HasNext() {
offset := u.CurrentOffSet()
newPageSize := getPageSize(u.h.term, u.h.terminalConf)
u.currentResult = u.Retrieve(newPageSize, offset, u.searchKeys...)
}
u.DisplayCurrentResult()
}
func (u *UserSelectHandler) MovePrePage() {
if u.HasPrev() {
offset := u.CurrentOffSet()
newPageSize := getPageSize(u.h.term, u.h.terminalConf)
start := offset - newPageSize*2
if start <= 0 {
start = 0
}
u.currentResult = u.Retrieve(newPageSize, start, u.searchKeys...)
}
u.DisplayCurrentResult()
}
func (u *UserSelectHandler) Search(key string) {
newPageSize := getPageSize(u.h.term, u.h.terminalConf)
u.currentResult = u.Retrieve(newPageSize, 0, key)
u.searchKeys = []string{key}
u.DisplayCurrentResult()
}
func (u *UserSelectHandler) SearchAgain(key string) {
u.searchKeys = append(u.searchKeys, key)
newPageSize := getPageSize(u.h.term, u.h.terminalConf)
u.currentResult = u.Retrieve(newPageSize, 0, u.searchKeys...)
u.DisplayCurrentResult()
}
func (u *UserSelectHandler) SearchOrProxy(key string) {
if indexNum, err := strconv.Atoi(key); err == nil && len(u.currentResult) > 0 {
if indexNum > 0 && indexNum <= len(u.currentResult) {
u.Proxy(u.currentResult[indexNum-1])
return
}
}
newPageSize := getPageSize(u.h.term, u.h.terminalConf)
currentResult := u.Retrieve(newPageSize, 0, key)
u.currentResult = currentResult
u.searchKeys = []string{key}
if len(currentResult) == 1 {
u.Proxy(currentResult[0])
return
}
// 资产类型, 返回结果 ip 或者 hostname 与 key 完全一样则直接登录
switch u.currentType {
case TypeAsset:
if strings.TrimSpace(key) != "" {
if ret, ok := getUniqueAssetFromKey(key, currentResult); ok {
u.Proxy(ret)
return
}
}
}
u.DisplayCurrentResult()
}
func (u *UserSelectHandler) HasPrev() bool {
return u.hasPre
}
func (u *UserSelectHandler) HasNext() bool {
return u.hasNext
}
func (u *UserSelectHandler) DisplayCurrentResult() {
lang := i18n.NewLang(u.h.i18nLang)
searchHeader := fmt.Sprintf(lang.T("Search: %s"), strings.Join(u.searchKeys, " "))
switch u.currentType {
case TypeDatabase:
u.displayDatabaseResult(searchHeader)
case TypeK8s:
u.displayK8sResult(searchHeader)
case TypeNodeAsset:
u.displayNodeAssetResult(searchHeader)
case TypeAsset:
u.displayAssetResult(searchHeader)
default:
logger.Error("Display unknown type")
}
}
func (u *UserSelectHandler) Proxy(target map[string]interface{}) {
targetId := target["id"].(string)
lang := i18n.NewLang(u.h.i18nLang)
switch u.currentType {
case TypeAsset, TypeNodeAsset:
asset, err := u.h.jmsService.GetAssetById(targetId)
if err != nil || asset.ID == "" {
logger.Errorf("Select asset %s not found", targetId)
return
}
if !asset.IsActive {
logger.Debugf("Select asset %s is inactive", targetId)
msg := lang.T("The asset is inactive")
_, _ = u.h.term.Write([]byte(msg))
return
}
u.proxyAsset(asset)
case TypeK8s, TypeDatabase:
app, err := u.h.jmsService.GetApplicationById(targetId)
if err != nil {
logger.Errorf("Select application %s err: %s", targetId, err)
return
}
u.proxyApp(app)
default:
logger.Errorf("Select unknown type for target id %s", targetId)
}
}
func (u *UserSelectHandler) Retrieve(pageSize, offset int, searches ...string) []map[string]interface{} {
switch u.loadingPolicy {
case loadingFromLocal:
return u.retrieveFromLocal(pageSize, offset, searches...)
default:
return u.retrieveFromRemote(pageSize, offset, searches...)
}
}
func (u *UserSelectHandler) retrieveFromLocal(pageSize, offset int, searches ...string) []map[string]interface{} {
if pageSize <= 0 {
pageSize = PAGESIZEALL
}
if offset < 0 {
offset = 0
}
searchResult := u.retrieveLocal(searches...)
var (
totalData []map[string]interface{}
total int
currentOffset int
currentPageSize int
)
if offset < len(searchResult) {
totalData = searchResult[offset:]
}
total = len(totalData)
currentPageSize = pageSize
currentData := totalData
if currentPageSize < 0 || currentPageSize == PAGESIZEALL {
currentPageSize = len(totalData)
}
if total > currentPageSize {
currentData = totalData[:currentPageSize]
}
currentOffset = offset + len(currentData)
u.updatePageInfo(currentPageSize, total, currentOffset)
u.hasPre = false
u.hasNext = false
if u.currentPage > 1 {
u.hasPre = true
}
if u.currentPage < u.totalPage {
u.hasNext = true
}
return currentData
}
func (u *UserSelectHandler) retrieveLocal(searches ...string) []map[string]interface{} {
switch u.currentType {
case TypeDatabase:
return u.searchLocalDatabase(searches...)
case TypeK8s:
return u.searchLocalK8s(searches...)
case TypeAsset:
return u.searchLocalAsset(searches...)
default:
// TypeAsset
u.SetSelectType(TypeAsset)
logger.Info("Retrieve default local data type: Asset")
return u.searchLocalAsset(searches...)
}
}
func (u *UserSelectHandler) searchLocalFromFields(fields map[string]struct{}, searches ...string) []map[string]interface{} {
items := make([]map[string]interface{}, 0, len(u.allLocalData))
for i := range u.allLocalData {
if containKeysInMapItemFields(u.allLocalData[i], fields, searches...) {
items = append(items, u.allLocalData[i])
}
}
return items
}
func (u *UserSelectHandler) retrieveFromRemote(pageSize, offset int, searches ...string) []map[string]interface{} {
reqParam := model.PaginationParam{
PageSize: pageSize,
Offset: offset,
Searches: searches,
}
switch u.currentType {
case TypeDatabase:
return u.retrieveRemoteDatabase(reqParam)
case TypeK8s:
return u.retrieveRemoteK8s(reqParam)
case TypeNodeAsset:
return u.retrieveRemoteNodeAsset(reqParam)
case TypeAsset:
return u.retrieveRemoteAsset(reqParam)
default:
// TypeAsset
u.SetSelectType(TypeAsset)
logger.Info("Retrieve default remote data type: Asset")
return u.retrieveRemoteAsset(reqParam)
}
}
func (u *UserSelectHandler) updateRemotePageData(reqParam model.PaginationParam,
res model.PaginationResponse) []map[string]interface{} {
u.hasNext = false
u.hasPre = false
if res.NextURL != "" {
u.hasNext = true
}
if res.PreviousURL != "" {
u.hasPre = true
}
total := res.Total
currentPageSize := reqParam.PageSize
currentData := res.Data
if currentPageSize < 0 || currentPageSize == PAGESIZEALL {
currentPageSize = len(res.Data)
}
if len(res.Data) > currentPageSize {
currentData = currentData[:currentPageSize]
}
currentOffset := reqParam.Offset + len(currentData)
u.updatePageInfo(currentPageSize, total, currentOffset)
return currentData
}
func containKeysInMapItemFields(item map[string]interface{},
searchFields map[string]struct{}, matchedKeys ...string) bool {
if len(matchedKeys) == 0 {
return true
}
if len(matchedKeys) == 1 && matchedKeys[0] == "" {
return true
}
for key, value := range item {
if _, ok := searchFields[key]; ok {
switch result := value.(type) {
case string:
for i := range matchedKeys {
if strings.Contains(result, matchedKeys[i]) {
return true
}
}
case map[string]interface{}:
if containKeysInMapItemFields(result, searchFields, matchedKeys...) {
return true
}
}
}
}
return false
}
func convertMapItemToRow(item map[string]interface{}, fields map[string]string, row map[string]string) map[string]string {
for key, value := range item {
if rowKey, ok := fields[key]; ok {
switch ret := value.(type) {
case string:
row[rowKey] = ret
case int:
row[rowKey] = strconv.Itoa(ret)
}
continue
}
switch ret := value.(type) {
case map[string]interface{}:
row = convertMapItemToRow(ret, fields, row)
}
}
return row
}
func joinMultiLineString(lines string) string {
lines = strings.ReplaceAll(lines, "\r", "\n")
lines = strings.ReplaceAll(lines, "\n\n", "\n")
lineArray := strings.Split(strings.TrimSpace(lines), "\n")
lineSlice := make([]string, 0, len(lineArray))
for _, item := range lineArray {
cleanLine := strings.TrimSpace(item)
if cleanLine == "" {
continue
}
lineSlice = append(lineSlice, strings.ReplaceAll(cleanLine, " ", ","))
}
return strings.Join(lineSlice, "|")
}
func getUniqueAssetFromKey(key string, currentResult []map[string]interface{}) (data map[string]interface{}, ok bool) {
result := make([]int, 0, len(currentResult))
for i := range currentResult {
ip := currentResult[i]["ip"].(string)
hostname := currentResult[i]["hostname"].(string)
switch key {
case ip, hostname:
result = append(result, i)
}
}
if len(result) == 1 {
return currentResult[result[0]], true
}
return nil, false
}