This repository has been archived by the owner on Jan 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathaaa.py
executable file
·1406 lines (1156 loc) · 47.2 KB
/
aaa.py
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import sys
import os
import json
import datetime, time
import re
import copy
from time import sleep
import argparse
from urllib.parse import urlparse
import bisect
import threading
import queue
import agency
import trie
from controls import *
from client import *
from history import History
ARANGO_LOG_ZERO = "00000000000000000000"
def format_ms_timestamp(ms):
dt = datetime.datetime.utcfromtimestamp(ms/1000.0)
return dt.isoformat(timespec='milliseconds') + "Z"
def decode_rev(rev):
s = "-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
n = 0
for j in range(0, len(rev)):
n = n * 64 + s.find(rev[j])
f = 1024 * 1024
return (n // f, n % f)
def decode_rev_timestamp(ref):
ms, tick = decode_rev(ref)
return f"{format_ms_timestamp(ms)}@{tick}"
class HighlightCommand:
def __init__(self, color, clear, save, regex, expr, only_path):
self.color = color
self.clear = clear
self.save = save
self.regex = regex
self.expr = expr
self.only_path = only_path
class AgencyLogList(Control):
FILTER_NONE = 0
FILTER_GREP = 1
FILTER_REGEX = 2
def __init__(self, app, rect, args):
super().__init__(app, rect)
self.app = app
self.top = 0
self.highlight = 0
self.filterStr = None
# list contains all displayed log indexes
self.list = None
self.filterType = AgencyLogList.FILTER_NONE
self.filterHistory = History()
self.formatString = "[{ts}|{term}] {_key} {urls}"
self.last_predicate = None
self.marked = dict()
self.follow = args.follow
self.highlight_predicate = dict()
self.highlight_string = None
self.highlight_history = History()
def title(self):
return "Agency Log"
def serialize(self):
return {
'top': self.top,
'highlight': self.highlight,
'filterStr': self.filterStr,
'filterType': self.filterType,
'filterHistory': self.filterHistory.history,
'formatString': self.formatString,
'marked': copy.deepcopy(self.marked)
}
def restore(self, state):
self.top = state['top']
self.highlight = state['highlight']
self.filterStr = state['filterStr']
self.filterType = state['filterType']
self.filterHistory.history = state['filterHistory']
self.formatString = state['formatString']
self.marked = copy.deepcopy(state['marked'])
self.__rebuildFilterList()
def __rebuildFilterList(self):
if self.filterType == AgencyLogList.FILTER_NONE:
self.list = None
elif self.filterType == AgencyLogList.FILTER_GREP:
self.grep(self.filterStr)
elif self.filterType == AgencyLogList.FILTER_REGEX:
self.regexp(self.filterStr)
else:
raise NotImplementedError()
def layout(self, rect):
super().layout(rect)
def __getIndexRelative(self, i):
idx = self.top + i
if self.list is not None:
if idx >= len(self.list):
return None
idx = self.list[idx]
if idx >= len(self.app.log):
return None
return idx
def __getIndex(self, i):
idx = i
if not self.list == None:
if idx >= len(self.list):
return None
idx = self.list[idx]
if idx >= len(self.app.log):
return None
return idx
def __getListLen(self):
if not self.list == None:
return len(self.list)
return len(self.app.log)
def update(self):
# Update top
maxPos = self.__getListLen() - 1
maxTop = max(0, maxPos - self.rect.height + 1)
# update highlight if follow
if self.follow:
self.highlight = maxPos
if not self.highlight == None:
if self.highlight > maxPos:
self.highlight = maxPos
if self.highlight < 0:
self.highlight = 0
if self.highlight < self.top:
self.top = self.highlight
bottom = self.top + self.rect.height - 1
if self.highlight >= bottom:
self.top = self.highlight - self.rect.height + 1
if self.top > maxTop:
self.top = maxTop
if self.top < 0:
self.top = 0
if self.rect.width == 0:
return
maxlen = self.rect.width
# Paint all lines from top up to height many
for i in range(0, self.rect.height):
idx = self.__getIndexRelative(i)
y = self.rect.y + i
x = self.rect.x
if not idx == None:
ent = self.app.log[idx]
is_selected = idx == self.getSelectedIndex()
text = " ".join(x for x in ent["request"])
if "epoch_millis" in ent:
ts = format_ms_timestamp(ent["epoch_millis"])
else:
ts = ent["timestamp"]
prefix = ">" if is_selected else " "
msg = prefix + self.formatString.format(**ent, urls=text, i=idx, ts = ts).ljust(maxlen)[0:maxlen]
attr = 0
if is_selected:
attr |= curses.A_STANDOUT | curses.A_UNDERLINE
colors = self.__get_line_highlight(idx)
if not self.app.snapshot is None and not self.app.log[0]["_key"] == ARANGO_LOG_ZERO:
if ent["_key"] < self.app.snapshot["_key"]:
attr |= curses.A_DIM
if len(colors) == 0:
self.app.stdscr.addnstr(y, x, msg, maxlen, attr)
else:
chunk_size = len(msg)/len(colors)
parts = [msg[int(chunk_size * i):int(chunk_size * i+chunk_size)] for i in range(0, len(colors))]
for idx, part in enumerate(parts):
attr_part = attr | colors[idx]
self.app.stdscr.addnstr(y, x, part, len(part), attr_part)
x += len(part)
elif i == 0:
self.app.stdscr.addnstr(y, x, "Nothing to display".ljust(maxlen), maxlen,
curses.A_BOLD | ColorFormat.CF_ERROR)
else:
self.app.stdscr.addnstr(y, x, "".ljust(maxlen), maxlen, 0)
def __get_line_highlight(self, idx):
if idx in self.marked:
return [ColorFormat.MARKING_ATTR_LIST[self.marked[idx]]]
ent_string = json.dumps(self.app.log[idx])
ent_paths = " ".join(x for x in self.app.log[idx]["request"])
colors = {
"r": ColorFormat.MARKING_ATTR_LIST[0],
"g": ColorFormat.MARKING_ATTR_LIST[1],
"b": ColorFormat.MARKING_ATTR_LIST[2],
"y": ColorFormat.MARKING_ATTR_LIST[3],
"c": ColorFormat.MARKING_ATTR_LIST[4],
"m": ColorFormat.MARKING_ATTR_LIST[5],
}
active = []
for color in colors:
# find the first color that matches
if color not in self.highlight_predicate:
continue
pred = self.highlight_predicate[color]
if pred(ent_string, ent_paths):
active.append(colors[color])
return active
def filter(self, predicate):
# Make sure that the highlighted entry is the previously selected
# entry or the closest entry above that one.
lastHighlighted = self.__getIndex(self.highlight)
if lastHighlighted == None:
lastHighlighted = 0
self.list = []
self.highlight = 0
self.last_predicate = predicate
for i, e in enumerate(self.app.log):
match = predicate(e)
if match:
if i <= lastHighlighted:
self.highlight = len(self.list)
self.list.append(i)
def regexp(self, regexStr):
self.reset()
if not regexStr:
return
# try to compile the regex
self.filterStr = regexStr
pattern = re.compile(regexStr)
predicate = lambda e: any(not pattern.search(path) == None for path in e["request"])
self.filterType = AgencyLogList.FILTER_REGEX
self.filter(predicate)
def grep(self, string):
self.reset()
if not string:
return
predicate = lambda e: string in json.dumps(e)
self.filterStr = string
self.filterType = AgencyLogList.FILTER_GREP
self.filter(predicate)
def reset(self):
# get the current index to keep the selected entry
self.highlight = self.getSelectedIndex()
if self.highlight is None:
self.highlight = 0
self.list = None
self.filterStr = None
self.filterType = AgencyLogList.FILTER_NONE
self.last_predicate = None
def filter_new_entries(self, new_entries):
if self.filterType == AgencyLogList.FILTER_NONE:
return
self.filter(self.last_predicate)
def highlight_entries(self, string):
color = "r"
assert len(string) > 0
if string[0] in ["r", "g", "b", "y", "c", "m"]:
if len(string) == 1:
color = string[0]
string = None
if len(string) > 2 and string[1] == " ":
color = string[0]
string = string[2:]
cmd = HighlightCommand(color, False, False, False, string, False)
self.execute_highlight_command(cmd)
def input(self, c):
if c == curses.KEY_UP:
self.follow = False
self.highlight -= 1
elif c == curses.KEY_DOWN:
self.follow = False
self.highlight += 1
elif c == curses.KEY_NPAGE:
self.follow = False
self.highlight += self.rect.height
self.top += self.rect.height
elif c == curses.KEY_PPAGE:
self.follow = False
self.highlight -= self.rect.height
self.top -= self.rect.height
elif c == curses.KEY_END:
self.follow = False
self.highlight = self.__getListLen() - 1
elif c == curses.KEY_HOME:
self.follow = False
self.highlight = 0
elif False:
regexStr = self.app.userStringLine(label="Regular Search Expr", default=self.filterStr, prompt="> ",
history=self.filterHistory)
if not regexStr == None:
if regexStr:
self.filterHistory.append(regexStr)
self.regexp(regexStr)
elif c == ord('g') or c == ord('f'):
self.run_filter_prompt()
elif c == ord('r'):
yesNo = self.app.userStringLine(label="Reset all filters", prompt="[Y/n] ")
if yesNo == "Y" or yesNo == "y" or yesNo == "":
self.reset()
elif c == ord('R'):
self.reset()
elif c == ord('m'):
self.toggleMarkLine()
elif c == ord('M'):
self.deleteMarkLine()
elif c == ord('h'):
string = self.app.userStringLine(label="Highlight Search Expr", prompt="> ", default=self.highlight_string,
history=self.highlight_history)
if string is not None and len(string) > 0:
self.highlight_entries(string)
elif c == ord('H'):
yesNo = self.app.userStringLine(label="Reset all highlights", prompt="[Y/n] ")
if yesNo == "Y" or yesNo == "y" or yesNo == "":
self.highlight_predicate = dict()
def run_filter_prompt(self, string=None):
if string is None:
string = self.app.userStringLine(label="Global Search Expr", default=self.filterStr, prompt="> ",
history=self.filterHistory)
if not string == None:
if string:
self.filterHistory.append(string)
self.grep(string)
# Returns the index of the selected log entry.
# This value is always with respect to the app.log array.
# You do not need to worry about filtering
def getSelectedIndex(self):
if not self.list == None:
if self.highlight < len(self.list):
return self.list[self.highlight]
return None
return self.highlight
def toggleMarkLine(self):
idx = self.getSelectedIndex()
if idx in self.marked:
self.marked[idx] += 1
if self.marked[idx] == len(ColorFormat.MARKING_ATTR_LIST):
del self.marked[idx]
else:
self.marked[idx] = 0
def deleteMarkLine(self):
idx = self.getSelectedIndex()
if idx in self.marked:
del self.marked[idx]
def selectClosest(self, idx):
if not self.list == None:
for i in self.list:
if i <= idx:
self.highlight = i
self.top = i
else:
self.highlight = idx
self.top = idx
def goto(self, idx):
# get global index of first log entry
startgidx = int(self.app.log[0]["_key"])
self.selectClosest(idx - startgidx)
@staticmethod
def parse_highlight_command(cmd, argv):
try:
cmd = cmd.lower()
assert len(cmd) >= 2
assert cmd[0] == "h"
idx = 1
# parse color
color = None
if cmd[idx] in ["r", "g", "b", "y", "c", "m"]:
color = cmd[idx]
idx += 1
# parse clear
clear = False
if idx < len(cmd) and cmd[idx] == "c":
clear = True
idx += 1
# parse save
save = False
if idx < len(cmd) and cmd[idx] == "s":
save = True
idx += 1
# parse regex
regex = False
if idx < len(cmd) and cmd[idx] == "r":
regex = True
idx += 1
# only consider path names
only_paths = False
if idx < len(cmd) and cmd[idx] == "p":
only_paths = True
idx += 1
if idx != len(cmd):
raise RuntimeError("to many chars")
expr = None
if len(argv) > 0:
expr = argv[0]
return HighlightCommand(color, clear, save, regex, expr, only_paths)
except Exception as e:
raise RuntimeError(
"Invalid highlight command, expected something that matches h[r|g|b|y|c|m]c?s?r?p? - " + str(e))
def execute_highlight_command(self, cmd: HighlightCommand):
if cmd.save or cmd.clear:
raise RuntimeError("save and clear not yet implemented")
if cmd.expr is None:
# delete that highlight
del self.highlight_predicate[cmd.color]
else:
# update
if cmd.regex:
pattern = re.compile(cmd.expr)
find_predicate = lambda x: pattern.search(x) is not None
else:
find_predicate = lambda x: cmd.expr in x
if cmd.only_path:
select_predicate = lambda json, paths: paths
else:
select_predicate = lambda json, paths: json
self.highlight_predicate[cmd.color] = lambda json, paths: find_predicate(select_predicate(json, paths))
class AgencyLogView(LineView):
def __init__(self, app, rect):
super().__init__(app, rect)
self.idx = None
self.lastIdx = None
self.head = None
def title(self):
key = self.app.log[self.idx]['_key'] if not self.idx == None else ""
return "Agency Log View {}".format(key)
def serialize(self):
return {
'idx': self.idx,
'head': self.head
}
def restore(self, state):
self.idx = state['idx']
self.head = state['head']
def update(self):
self.idx = self.app.list.getSelectedIndex()
if not self.idx == self.lastIdx:
if self.idx == None:
self.jsonLines(None)
elif not self.idx == None and self.idx < len(self.app.log):
entry = self.app.log[self.idx]
fields = ["_key", "_rev", "term", "clientId", "timestamp", "epoch_millis", "request"]
json = dict()
for name in fields:
if name in entry:
json[name] = entry[name]
self.head = None # entry['_key']
loglist = self.app.list
if loglist.filterType == AgencyLogList.FILTER_GREP:
self.findStr = loglist.filterStr
else:
self.findStr = None
self.jsonLines(json)
self.lastIdx = self.idx
super().update()
def getLineAnnotation(self, line):
if "epoch_millis" in line:
return format_ms_timestamp(int(line[line.find(":")+1: -1]))
if "_rev" in line:
entry = self.app.log[self.idx]
return decode_rev_timestamp(entry['_rev'])
return None
def set(self, idx):
self.idx = idx
class StoreCache:
def __init__(self, maxSize):
self.maxSize = maxSize
self.cache = dict()
self.list = list()
self.indexes = list()
def refresh(self, idx):
try:
self.list.remove(idx)
except:
pass
self.list.append(idx)
def get(self, idx):
if idx in self.cache:
self.refresh(idx)
return self.cache[idx]
return None
def has(self, idx):
return idx in self.cache
def closest(self, idx):
i = bisect_left(self.indexes, idx)
if i == 0:
return None
return self.indexes[i - 1]
def set(self, idx, store):
self.refresh(idx)
if len(self.list) > self.maxSize:
oldIdx = self.list.pop(0)
try:
self.indexes.remove(oldIdx)
except:
pass
del self.cache[oldIdx]
self.cache[idx] = store
bisect.insort_left(self.indexes, idx)
class StoreUpdateResult:
OK = 0
UPDATE_JSON = 1
NO_SNAPSHOT = 2
NOT_COVERED = 3
class StoreProvider:
def __init__(self, app, rect):
self.app = app
self.store = None
self.cache = StoreCache(512)
self.lastIdx = None
self.lastWasCopy = False
self.rect = rect
def updateIndex(self, idx):
updateJson = True
if self.lastIdx != idx:
updateJson = True
# if the id of the first log entry is ARANGO_LOG_ZERO,
# generate the agency from empty store
# otherwise check if the log entry is after (>=) the
log = self.app.log
if log == None or len(log) == 0:
return StoreUpdateResult.NO_SNAPSHOT
snapshot = self.app.snapshot
startidx = None
snapshotRequired = True
if log[0]["_key"] == ARANGO_LOG_ZERO:
snapshotRequired = False
# early out for cases where we can not produce a store
if snapshotRequired:
if snapshot == None:
return StoreUpdateResult.NO_SNAPSHOT
elif log[idx]["_key"] < snapshot["_key"]:
return StoreUpdateResult.NOT_COVERED
# first check cache
cache = self.cache.get(idx)
if not cache == None:
self.lastWasCopy = False
self.store = cache
else:
# check if we can use last index
startidx = self.lastIdx + 1 if not self.lastIdx == None else None
doCopyLastSnapshot = False
if self.lastIdx == None or self.store == None or idx < self.lastIdx:
startidx = self.app.firstValidLogIdx
if snapshotRequired:
doCopyLastSnapshot = True
else:
self.store = agency.AgencyStore()
startidx = 0
self.lastWasCopy = True
# lets ask cache
cache = self.cache.closest(idx)
if not cache == None and not startidx == None:
if cache > startidx:
startidx = cache + 1
self.app.showProgress(0.0, "Copy index {} from cache".format(cache), rect=self.rect)
self.store = agency.AgencyStore.copyFrom(self.cache.get(cache))
self.lastWasCopy = True
doCopyLastSnapshot = False
if doCopyLastSnapshot:
self.app.showProgress(0.0, "Copy from snapshot", rect=self.rect)
self.store = agency.AgencyStore(snapshot["readDB"][0])
elif not self.lastWasCopy:
self.store = agency.AgencyStore.copyFrom(self.store)
lastProgress = time.process_time()
for i in range(startidx, idx + 1):
now = time.process_time()
# if log[idx]["_key"] >= snapshot["_key"]:
ent = self.app.log[i]
try:
self.store.applyLog(self.app.log[i])
except Exception as e:
raise Exception("In log entry {idx}: {text} - {content}".format(idx=ent["_key"], text=repr(e), content=json.dumps(ent)))
storeIntermediate = i % 5000 == 0 and not self.cache.has(i)
if not storeIntermediate:
didx = idx - i
if didx < 500:
storeIntermediate = didx % 200 == 0
elif didx < 2500:
storeIntermediate = didx % 1000 == 0
if storeIntermediate:
self.app.showProgress((i - startidx) / (idx + 1 - startidx),
"Generating store {}/{} - writing to cache".format(i, idx + 1),
rect=self.rect)
self.cache.set(i, agency.AgencyStore.copyFrom(self.store))
elif now - lastProgress > 0.1:
self.app.showProgress((i - startidx) / (idx + 1 - startidx),
"Generating store {}/{}".format(i, idx + 1), rect=self.rect)
lastProgress = now
self.app.showProgress(1.0, "Generating store done - writing to cache", rect=self.rect)
self.cache.set(idx, agency.AgencyStore.copyFrom(self.store))
self.app.showProgress(1.0, "Dumping json", rect=self.rect)
self.lastIdx = idx
return StoreUpdateResult.UPDATE_JSON if updateJson else \
StoreUpdateResult.OK
def get(self, path):
return self.store.get(path)
def _ref(self, path):
return self.store._ref(path)
def has_store(self):
return self.store is not None
class AgencyStoreView(LineView):
def __init__(self, app, rect):
super().__init__(app, rect)
self.store = app.storeProvider
self.path = []
self.pathHistory = History()
self.annotations = dict()
self.annotationCache = StoreCache(64)
self.annotationsTrie = None
self.annotations_format = {
"server": "{ShortName}, {Endpoint}, {Status}",
"collection": "Collection `{database}/{name}`, grp={groupId}",
"shard": "Shard of `{database}/{name}`, grp={groupId}, sheaf={sheaf}, idx={shard_idx}"
}
def title(self):
return "Agency Store View"
def serialize(self):
return {
'path': self.path,
'pathHistory': self.pathHistory.history
}
def restore(self, state):
self.path = state['path']
self.pathHistory.history = state['pathHistory']
self.lastIdx = None
def layout(self, rect):
self.store.rect = rect
super().layout(rect)
def updateStore(self, updateJson=False):
idx = self.app.list.getSelectedIndex()
if idx == None:
return
result = self.store.updateIndex(idx)
if result == StoreUpdateResult.NO_SNAPSHOT:
self.head = None
self.lines = [(ColorFormat.CF_ERROR, "No snapshot available")]
return
elif result == StoreUpdateResult.NOT_COVERED:
self.head = None
self.lines = [(ColorFormat.CF_ERROR, "Can not replicate agency state. Not covered by snapshot.")]
return
elif result == StoreUpdateResult.UPDATE_JSON:
updateJson = True
else:
assert result == StoreUpdateResult.OK
if updateJson:
self.load_annotations()
self.jsonLines(self.store._ref(self.path))
def update(self):
self.head = "/" + "/".join(self.path)
self.updateStore()
super().update()
def update_format_string(self, what):
if what not in self.annotations_format:
raise ValueError("Unknown format topic `{}`".format(what))
new_str = self.app.userStringLine(label="Format string for {}".format(what),
default=self.annotations_format[what])
if new_str is not None:
self.annotations_format[what] = new_str
def load_annotations(self, flush=False):
def format_user_string(format_str, kvs):
try:
from collections import defaultdict
return format_str.format_map(defaultdict(str, **kvs))
except Exception as ex:
return "<bad format string: {}>".format(repr(ex))
idx = self.app.list.getSelectedIndex()
if idx is None:
return
if not flush and self.annotationCache.has(idx):
self.annotations = self.annotationCache.get(idx)
return
new_annotations = dict()
all_servers = self.store.get(["arango", "Supervision", "Health"])
if all_servers is not None:
for serverId, data in all_servers.items():
new_annotations[serverId] = format_user_string(self.annotations_format["server"], data)
collections = self.store._ref(["arango", "Plan", "Collections"])
if collections is not None:
for dbname, database_collections in collections.items():
for collection_id, data in database_collections.items():
format_dict = {"database": dbname, **data}
new_annotations[collection_id] = format_user_string(self.annotations_format["collection"],
format_dict)
shardsR2 = []
if "shardsR2" in data:
shardsR2 = data["shardsR2"]
group = None
if "groupId" in data:
gid = data["groupId"]
group = self.store._ref(["arango", "Plan", "CollectionGroups", dbname, str(gid)])
assert group is not None
for shardId, servers in data["shards"].items():
idx = shardsR2.index(shardId) if shardId in shardsR2 else -1
sheaf = -1
if group is not None:
sheaf = group["shardSheaves"][idx]["replicatedLog"]
shard_format_dict = {**format_dict, "servers": servers, "shardId": shardId, "shard_idx": idx, "sheaf": sheaf}
new_annotations[shardId] = format_user_string(self.annotations_format["shard"],
shard_format_dict)
self.annotations = new_annotations
self.annotationsTrie = trie.Trie(['"{}"'.format(x) for x in new_annotations.keys()])
self.annotationCache.set(idx, new_annotations)
def getLineAnnotation(self, line):
if not self.store.has_store():
return None
annotation = []
for w in self.annotationsTrie.find_all(line):
annotation.append(self.annotations[w[1:-1]])
if len(annotation) == 0:
return None
return "; ".join(annotation)
def input(self, c):
if c == ord('p'):
pathstr = self.app.userStringLine(prompt="> ", label="Agency Path:", default=self.head,
complete=self.completePath, history=self.pathHistory)
self.path = agency.AgencyStore.parsePath(pathstr)
self.pathHistory.append(pathstr)
self.updateStore(updateJson=True)
else:
super().input(c)
def set(self, store):
self.store = store
def __common_prefix_idx(self, strings):
if len(strings) == 0:
return None
maxlen = min(len(s) for s in strings)
for i in range(0, maxlen):
c = strings[0][i]
if not all(s[i] == c for s in strings):
return i
return maxlen
def completePath(self, pathstr):
if self.store == None:
return
if len(pathstr) == 0:
return "/"
path = agency.AgencyStore.parsePath(pathstr)
if pathstr[-1] == "/":
ref = self.store._ref(path)
if not ref == None and isinstance(ref, dict):
return list(ref.keys())
else:
ref = self.store._ref(path[:-1])
if not ref == None and isinstance(ref, dict):
word = path[-1]
# Now find all key that start with word
keys = [h for h in ref.keys() if h.startswith(word)]
if len(keys) == 0:
return None
if len(keys) > 1:
# first complete to the common sub
common = keys[0][:self.__common_prefix_idx(keys)]
if path[-1] == common:
return list(keys)
return "/" + "/".join(path[:-1] + [common])
elif path[-1] == keys[0] and not pathstr[-1] == "/":
ref = self.store._ref(path)
if not ref == None and isinstance(ref, dict):
return (pathstr + "/", ref.keys())
else:
return "/" + "/".join(path[:-1] + [keys[0]])
return None
class AgencyDiffView(PureLineView):
def __init__(self, app, rect):
super().__init__(app, rect)
self.store = app.storeProvider
self.last_idx = None
def layout(self, rect):
self.store.rect = rect
super().layout(rect)
def title(self):
return "Agency Store Diff"
def getStoreRef(self, idx):
result = self.store.updateIndex(idx)
if result == StoreUpdateResult.NO_SNAPSHOT:
self.head = None
self.lines = [(ColorFormat.CF_ERROR, "No snapshot available")]
return None
elif result == StoreUpdateResult.NOT_COVERED:
self.head = None
self.lines = [(ColorFormat.CF_ERROR, "Can not replicate agency state. Not covered by snapshot.")]
return None
else:
return self.store.store
def update(self):
idx = self.app.list.getSelectedIndex()
if idx == None or idx == 0:
return
if self.last_idx == idx:
super().update()
return
oldStore = self.getStoreRef(idx-1)
newStore = self.getStoreRef(idx)
if oldStore is None or newStore is None:
return
entry = self.app.log[idx]
lines = []
for path in entry["request"]:
lines.append([(curses.A_BOLD, path)])
parsedPath = agency.AgencyStore.parsePath(path)
oldLines = AgencyDiffView.split_json(oldStore._ref(parsedPath))
newLines = AgencyDiffView.split_json(newStore._ref(parsedPath))
diffLines = self.computeDiff(oldLines, newLines)
lines.extend(diffLines)
self.lines = lines
self.last_idx = idx
super().update()
@staticmethod
def computeDiff(old, new):
def estimate(x, y):
return 0 # abs(len(old)-x+(len(new)-y))
found = set()
cred = ColorPairs.getPair(curses.COLOR_RED, curses.COLOR_BLACK)
cgreen = ColorPairs.getPair(curses.COLOR_GREEN, curses.COLOR_BLACK)
try:
queue = [(0, 0, 0, estimate(0, 0), [])]
i = 0
while i < 300:
# i += 1
queue.sort(key=lambda x: (x[2] + x[3], -x[0]))
x, y, cost, est, path = queue.pop(0)
if (x, y) in found:
continue
found.add((x, y))
# print(x, y, cost + est)
if x == len(old) and y == len(new):
return path
if x != len(old) and y != len(new) and old[x] == new[y]:
queue.append((x + 1, y + 1, cost, estimate(x + 1, y + 1), path + [" " + old[x]]))
else:
if x < len(old):
new_est = estimate(x + 1, y)
queue.append((x + 1, y, cost + 1, new_est, path + [[(cred, "-" + old[x])]]))
if y < len(new):
new_est = estimate(x, y + 1)
queue.append((x, y + 1, cost + 1, new_est, path + [[(cgreen, "+" + new[y])]]))