-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy patheshell
executable file
·5473 lines (5094 loc) · 190 KB
/
eshell
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
# -*- coding: utf-8 -*-
__title__ = "eshell"
__description__ = "Elasticsearch API available via Python interactive shell."
__url__ = "https://github.com/nfsec/eshell"
__version__ = "0.7.10.2"
__license__ = "Apache License (2.0)"
__author__ = "Patryk Krawaczyński <[email protected]>"
__help__ = (
"Help menu descriptions are from the official Elasticsearch documentation: "
"https://www.elastic.co/guide/index.html"
)
import argparse
import atexit
import cmd
import getpass
import json
import logging.handlers
import math
import operator
import os
import re
import readline
import socket
import ssl
import subprocess
import sys
import traceback
import warnings
import elasticsearch
# little helpers
class BColors:
"""
Colors for terminal
"""
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def error():
"""
Print error and traceback.
"""
print(format(BColors.FAIL))
print("-" * 60)
print(traceback.print_exc(file=sys.stderr, limit=1))
print("-" * 60)
print(format(BColors.ENDC))
def isopen(ip, port):
"""
Check if address have open port.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((ip, port))
s.settimeout(None)
s.shutdown(2)
print("Connected to: {0} on port: {1}".format(str(ip), str(port)))
return True
except socket.error as s_err:
print(
"Problem with connection to: {0} on port: {1}. Error code:".format(
str(ip), str(port)
),
s_err,
)
return False
def check_hostname(hostname):
"""
Check if DNS address is valid one.
"""
try:
socket.gethostbyname(hostname)
return True
except socket.error:
return False
def check_ip(ip):
"""
Check if IP address is valid one.
"""
try:
socket.inet_aton(ip)
return True
except socket.error:
return False
def check_env(directory):
"""
Check and create environment directory and files
"""
log_file = os.path.expanduser(directory + "/es.log")
history_file = os.path.expanduser(directory + "/history")
try:
if not os.path.exists(os.path.expanduser(directory)):
os.makedirs(os.path.expanduser(directory), exist_ok=True)
if not os.path.exists(history_file):
f = open(history_file, "w+")
f.write("_HiStOrY_V2_\n\n")
f.close()
return history_file, log_file
except Exception:
error()
def commandlist(subcommand):
"""
Return command list from menu.
"""
commands = []
for i in dir(subcommand):
if i.startswith("do_"):
commands.append(i.replace("do_", ""))
return commands
def pretty_print(dictionary, indent=0):
"""
Pretty print all the complexities.
"""
for k, v in sorted(dictionary.items()):
if type(v) == dict:
if len(v) == 0:
print(" " * indent, str(k) + ": {empty}")
else:
print(" " * indent, str(k) + ": ")
pretty_print(v, indent + len(k) + 1)
elif type(v) == list:
if len(v) == 0:
print(" " * indent, str(k) + ": [empty]")
elif type(v[0]) == dict:
print(" " * indent, str(k) + ": ")
for x in v:
pretty_print(x, indent + len(k) + 1)
else:
print(" " * indent, str(k) + ": " + str.join(", ", v))
else:
print(" " * indent, str(k) + ": " + str(v))
def parse_string(string):
"""
Convert string in format: key=value to dictionary: {'key': 'value'}
"""
return dict(i.split("=") for i in string.split())
def parse_list(list_string):
"""
Convert list in format: ['key=value'] to directory: {'key': 'value'}
"""
return dict(map(lambda s: s.split("="), list_string))
def less(text):
"""
Filter long text with the <less> tool
"""
try:
pager = subprocess.Popen(
["less", "-F", "-R", "-S", "-X", "-K", "-N"],
stdin=subprocess.PIPE,
stdout=sys.stdout,
)
for line in text:
pager.stdin.write(line.encode("utf-8"))
pager.stdin.close()
pager.wait()
except IOError:
print("Exiting...")
except KeyboardInterrupt:
print("Exiting...")
def convert_size(bytes_unit):
"""
Convert bytes to human-readable unit.
"""
if bytes_unit == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(bytes_unit, 1024)))
p = math.pow(1024, i)
s = round(bytes_unit / p, 2)
return "{0} {1}".format(s, size_name[i])
# autocomplete functions
def indexlist():
indices = []
for i in es.cat.indices(h="index").split("\n"):
if i:
indices.append(i.replace(" ", ""))
return indices
def nodelist():
nodes = []
for i in es.cat.nodes(h="name").split("\n"):
if i:
nodes.append(i)
return nodes
# elasticsearch main-console
class ES(cmd.Cmd):
intro = (
'{0}\n### Welcome to elasticsearch shell console!\n### For more information, type "help" or "?".\n'
"### Session will be logged to ~/.e7/es.log.\n"
"### Command history will be saved to ~/.e7/history.\n{1}".format(
BColors.BOLD, BColors.ENDC
)
)
prompt = "e7:~$ "
ruler = "-"
doc_header = "Available commands (type: help <command>):"
def default(self, line):
"""
Called on an input line when the command prefix is not recognized.
In that case we execute the line as Python code.
"""
try:
exec(line) in self._locals, self._globals
except NameError:
print("Command {0} not found.".format(line))
except SyntaxError:
print("Command not found or invalid syntax.")
except KeyboardInterrupt:
print("Detected Ctrl+D. Exiting...")
except Exception:
error()
def preloop(self):
"""
Initialization before prompting user for commands.
"""
self._history = []
self._locals = {}
self._globals = {}
def precmd(self, line):
"""
This method is called after the line has been input but before
it has been interpreted. If you want to modify the input line
before execution (for example, variable substitution) do it here.
"""
self._history += [line.strip()]
return line
def postloop(self):
"""
Take care of any unfinished business.
"""
cmd.Cmd.postloop(self)
print("Exiting...")
def postcmd(self, stop, line):
"""
If you want to stop the console, return something that evaluates to true.
If you want to do some post command processing, do it here.
"""
return stop
def emptyline(self):
"""
Do nothing on empty line input.
"""
pass
def do_prompt(self, arg):
"""
Change console prompt.
$ prompt [new prompt] - set new prompt.
"""
self.prompt = "{0}:~$ ".format(arg)
def do_help(self, arg):
"""
Get help on commands:
'help' or '?' with no arguments prints a list of commands for which help is available
'help [command]' or '? [command]' gives help on [command]
"""
cmd.Cmd.do_help(self, arg)
def do_history(self, arg):
"""
Print a list of commands that have been entered into console.
"""
print(self._history)
def do_history_file(self, arg):
"""
Print a list of commands that have been recorded into history file.
$ history_file 10 - show last 10 commands.
$ history_file - show all commands.
"""
if arg:
history_length = readline.get_current_history_length()
for i in range((history_length - int(arg)), history_length):
print(readline.get_history_item(i + 1))
else:
for i in range(readline.get_current_history_length()):
print(readline.get_history_item(i + 1))
def do_history_search(self, arg):
"""
Search for [term] in history file.
$ history_search [term]
"""
for i in range(readline.get_current_history_length()):
if re.search(arg, str(readline.get_history_item(i + 1))):
print(readline.get_history_item(i + 1))
def do_clear(self, arg):
"""
Clear the screen.
"""
os.system("clear")
def do_shell(self, line):
"""
Pass command to a system shell when line begins with '!'
"""
print("Running shell command: {0}\n".format(line))
sub_cmd = subprocess.Popen(line, shell=True, stdout=subprocess.PIPE)
output = sub_cmd.communicate()[0].decode("utf-8")
print(output)
self.last_output = output
def do_echo(self, line):
"""
Print the input, replacing '$out' with the output of the last shell command.
$ echo $out - print last output for shell command.
"""
print(line.replace("$out", self.last_output))
def do_quit(self, arg):
"""
Quits from the console.
"""
return True
def do_exit(self, arg):
"""
Exits from the console.
"""
return True
def do_EOF(self, line):
"""
Exit on system end of file character (Ctrl+D).
"""
return True
def do_show(self, arg):
"""
Enter to cluster information submenu.
"""
show_cli = Show()
show_cli.cmdloop()
def do_exec(self, arg):
"""
Enter to cluster execution submenu.
"""
exec_cli = Exec()
exec_cli.cmdloop()
# elasticsearch show-console
class Show(cmd.Cmd):
intro = '\n{0}### Entering to cluster information menu!\n### For more information, type "help" or "?".\n{1}'.format(
BColors.BOLD, BColors.ENDC
)
prompt = "es7:show~$ "
ruler = "-"
doc_header = "Available commands (type: help <command>):"
def default(self, line):
"""
Called on an input line when the command prefix is not recognized.
In that case we execute the line as Python code.
"""
try:
exec(line) in self._locals, self._globals
except NameError:
print("Command {0} not found.".format(line))
except SyntaxError:
print("Command not found or invalid syntax.")
except KeyboardInterrupt:
print("Detected Ctrl+D. Exiting...")
except Exception:
error()
def preloop(self):
"""
Initialization before prompting user for commands.
"""
cmd.Cmd.preloop(self)
self._history = []
self._locals = {}
self._globals = {}
def precmd(self, line):
"""
This method is called after the line has been input but before
it has been interpreted. If you want to modify the input line
before execution (for example, variable substitution) do it here.
"""
self._history += [line.strip()]
return line
def postloop(self):
"""
Take care of any unfinished business.
"""
cmd.Cmd.postloop(self)
print("Exiting...")
def postcmd(self, stop, line):
"""
If you want to stop the console, return something that evaluates to true.
If you want to do some post command processing, do it here.
"""
return stop
def emptyline(self):
"""
Do nothing on empty line input.
"""
pass
def do_prompt(self, arg):
"""
Change console prompt.
$ prompt [new prompt] - set new prompt.
"""
self.prompt = "{0}:~$ ".format(arg)
def do_help(self, arg):
"""
Get help on commands:
'help' or '?' with no arguments prints a list of commands for which help is available
'help <command>' or '? <command>' gives help on <command>
"""
cmd.Cmd.do_help(self, arg)
def do_history(self, arg):
"""
Print a list of commands that have been entered into console.
"""
print(self._history)
def do_history_file(self, arg):
"""
Print a list of commands that have been recorded into history file.
$ history_file 10 - show last 10 commands.
$ history_file - show all commands.
"""
if arg:
history_length = readline.get_current_history_length()
for i in range((history_length - int(arg)), history_length):
print(readline.get_history_item(i + 1))
else:
for i in range(readline.get_current_history_length()):
print(readline.get_history_item(i + 1))
def do_history_search(self, arg):
"""
Search for [term] in history file.
$ history_search [term]
"""
for i in range(readline.get_current_history_length()):
if re.search(arg, str(readline.get_history_item(i + 1))):
print(readline.get_history_item(i + 1))
def do_clear(self, arg):
"""
Clear the screen.
"""
os.system("clear")
def do_shell(self, line):
"""
Pass command to a system shell when line begins with '!'
"""
print("Running shell command: {0}\n".format(line))
sub_cmd = subprocess.Popen(line, shell=True, stdout=subprocess.PIPE)
output = sub_cmd.communicate()[0].decode("utf-8")
print(output)
self.last_output = output
def do_echo(self, line):
"""
Print the input, replacing '$out' with the output of the last shell command.
$ echo $out - print last output for shell command.
"""
print(line.replace("$out", self.last_output))
def do_quit(self, arg):
"""
Quits from the console.
"""
return True
def do_exit(self, arg):
"""
Exits from the console.
"""
return True
def do_EOF(self, line):
"""
Exit on system end of file character (Ctrl+D).
"""
return True
def do_leave(self, line):
"""
Leave submenu.
"""
return True
def do_exec(self, line):
"""
Execute command in cluster execution menu.
"""
Exec().onecmd(line)
def complete_exec(self, text, line, begidx, endidx):
"""
Complete commands from exec menu.
"""
return [i for i in commandlist(Exec()) if i.startswith(text)]
# elasticsearch script-show-console
def do_script_context(self, arg):
"""
Returns all script contexts.
"""
try:
print()
pretty_print(es.get_script_context(), indent=2)
print()
except Exception:
error()
def do_script_languages(self, arg):
"""
Returns available script types, languages and contexts.
"""
try:
print()
pretty_print(es.get_script_languages(), indent=2)
print()
except Exception:
error()
def do_script(self, arg):
"""
Returns a script.
$ script id - returns a script with id.
"""
if arg:
try:
print()
es.get_script(id=arg)
print()
except Exception:
error()
else:
print()
print("Please provide script ID.")
print()
# elasticsearch cluster-show-console
def do_cluster_allocation_explain(self, arg):
"""
The purpose of the cluster allocation explain API is to provide explanations for shard allocations in the
cluster.
$ cluster_allocation_explain (args) - explain the first unassigned shard.
- include_disk_info=true - returns information about disk usage and shard sizes (default: false).
- include_yes_decisions=true - returns YES decisions in explanation (default: false).
"""
try:
print()
pretty_print(
es.cluster.allocation_explain(params=parse_string(arg)), indent=2
)
print()
except Exception:
error()
def do_cluster_allocation_explain_shard(self, arg):
"""
$ cluster_allocation_explain [index] [shard] [true/false] (args) - specify the index and shard id of the
shard you would like a explanation for, as well as the primary flag to indicate whether to explain
the primary shard for the given shard id or one of its replica shards. These three request parameters
are required.
* [index] - specifies the name of the index that you would like an explanation for.
* [shard] - specifies the ID of the shard that you would like an explanation for.
* [true/false] - if true, returns explanation for the primary shard for the given shard ID.
- include_disk_info=true - returns information about disk usage and shard sizes (default: false).
- include_yes_decisions=true - returns YES decisions in explanation (default: false).
"""
argv = arg.split()
if len(argv) < 3:
print()
print(
"Please provide [index] name, [shard] and [true] or [false] if primary."
)
print()
else:
try:
payload = '{{ "index": "{0}", "shard": {1}, "primary": {2} }}'.format(
str(argv[0]), str(argv[1]), str(argv[2])
)
print()
pretty_print(
es.cluster.allocation_explain(
body=payload, params=(parse_list(argv[3:]))
)
)
print()
except Exception:
error()
def do_cluster_repositories(self, arg):
"""
The repositories command shows the snapshot repositories registered in the cluster.
"""
try:
print()
print(es.cat.repositories(v=True, s="id"))
except Exception:
error()
def do_cluster_snapshots(self, arg):
"""
The cluster_snapshots command shows all snapshots that belong to a specific repository.
$ cluster_snapshots [repository_name] - show information about each snapshot in repository.
"""
if arg:
try:
print()
print(
es.cat.snapshots(
repository=arg, ignore_unavailable=True, v=True, s="id"
)
)
except Exception:
error()
else:
print()
print("Please provide name of repository to show its snapshots. ")
print(
"To find a list of available repositories to query, the command 'cluster_repositories' can be used."
)
print()
def do_cluster_ping(self, arg):
"""
Returns 'UP' if the cluster is up, 'DOWN' otherwise.
"""
try:
if es.ping():
print("\nUP!\n")
else:
print("\nDOWN!\n")
except Exception:
error()
def do_cluster_info(self, arg):
"""
Get the basic info from the current cluster.
"""
try:
print()
pretty_print(es.info(), indent=2)
print()
except Exception:
error()
def do_cluster_master(self, arg):
"""
Displays the master’s node ID, bound IP address, and node name.
"""
try:
print()
print(es.cat.master(v=True))
except Exception:
error()
def do_cluster_health(self, arg):
"""
Get a very simple status on the health of the cluster.
$ cluster_health - show cluster health.
$ cluster_health [table] - one-line representation of the same information from cluster_health.
"""
try:
if arg == "table":
print()
print(es.cat.health(v=True))
else:
print()
pretty_print(es.cluster.health(level="cluster"), indent=2)
print()
except Exception:
error()
def do_cluster_tasks(self, arg):
"""
Show all pending cluster tasks which have not yet been executed.
$ cluster_tasks - show all tasks.
$ cluster_tasks urgent - show urgent tasks.
$ cluster_tasks high - show high tasks.
$ cluster_tasks normal - show normal tasks.
"""
try:
task_list = es.cat.pending_tasks(v=True)
if arg in ["urgent", "high", "normal"]:
print()
print(task_list.split("\n")[0])
for line in task_list.split("\n"):
if arg.upper() in line:
print(line)
print()
else:
print()
less(es.cat.pending_tasks())
print()
except Exception:
error()
def do_cluster_tasks_stats(self, arg):
"""
Show cluster tasks statistics.
"""
task_list = str(es.cluster.pending_tasks())
ustats = re.compile("URGENT")
umatch = ustats.findall(task_list)
hstats = re.compile("HIGH")
hmatch = hstats.findall(task_list)
nstats = re.compile("NORMAL")
nmatch = nstats.findall(task_list)
print(
"Tasks statistics: URGENT: {0} HIGH: {1} NORMAL: {2}".format(
str(len(umatch)), str(len(hmatch)), str(len(nmatch))
)
)
def do_cluster_settings(self, arg):
"""
Get current cluster settings.
$ cluster_settings - get cluster custom settings.
"""
try:
print()
pretty_print(es.cluster.get_settings(flat_settings=True), indent=2)
print()
except Exception:
error()
def do_cluster_settings_with_defaults(self, arg):
"""
Get current cluster settings.
$ cluster_settings_with_defaults - get cluster settings with default values.
"""
try:
print()
pretty_print(
es.cluster.get_settings(flat_settings=True, include_defaults=True),
indent=2,
)
print()
except Exception:
error(arg)
def do_cluster_stats(self, arg):
"""
The Cluster stats allows to retrieve statistics from a cluster wide perspective.
$ cluster_stats [node_id] - show stats for node_id.
$ cluster_stats _all - show stats for all nodes.
$ cluster_stats _local - show stats only for local node.
$ cluster_stats _master - show stats for the currently-elected master node.
$ cluster_stats master:true/false - show/hide stats for all master-eligible nodes.
$ cluster_stats data:true/false - show/hide stats for all data nodes.
$ cluster_stats ingest:true/false - show/hide for all ingest nodes.
$ cluster_stats coordinating_only:true/false - show/hide for all coordinating-only nodes.
"""
if arg:
try:
print()
pretty = es.cluster.stats(node_id=arg)
pretty_print(pretty, indent=7)
print()
except Exception:
error()
else:
try:
print()
pretty = es.cluster.stats(human=True)
print("cluster_name: {0}".format(str(pretty["cluster_name"])))
print("status: {0}".format(str(pretty["status"])))
print("timestamp: {0}".format(str(pretty["timestamp"])))
print("_nodes")
pretty_print(pretty["_nodes"], indent=7)
print("nodes:")
pretty_print(pretty["nodes"], indent=6)
print("indices:")
pretty_print(pretty["indices"], indent=8)
print()
except Exception:
error()
def do_cluster_state(self, arg):
"""
Shows the cluster state.
$ cluster_state - returns all metadata about the state of the cluster.
$ cluster_state [metrics] [target] - returns filtered part of the response.
[metrics]:
- _all - show all metrics.
- blocks - show the blocks part of the response.
- master_node - shows the elected master_node part of the response.
- metadata - shows the metadata part of the response.
- nodes - shows the node part of the response.
- routing_nodes - shows the routing_nodes part of the response.
- routing_table - shows the routing_table part of the response.
- version - shows the cluster state version.
[target]:
- comma-separated list of indices or index aliases used to limit the request.
- wildcard expressions (*) are supported.
- to target all data streams and indices in a cluster, omit this parameter or use _all or *.
"""
if arg:
argv = arg.split()
if len(argv) != 2:
print()
print("Please provide [metrics] and [target]")
print()
else:
try:
print()
pretty_print(
es.cluster.state(
metric=argv[0], index=argv[1], flat_settings=True
),
indent=2,
)
print()
except Exception:
error()
else:
try:
print()
pretty_print(
es.cluster.state(metric="_all", flat_settings=True), indent=2
)
print()
except Exception:
error()
def do_cluster_state_size(self, arg):
"""
Show cluster state size in MB
"""
try:
state_size = str(es.cluster.state(metric="_all"))
print()
print("Approximately: " + convert_size(len(state_size)))
print()
except Exception:
error()
def do_cluster_remote(self, arg):
"""
This command returns connection and endpoint information keyed to the configured remote cluster alias.
- seeds - the configured initial seed transport addresses of the remote cluster.
- http_addresses - the published http addresses of all connected remote nodes.
- connected - true if there is at least one connection to the remote cluster.
- num_nodes_connected - the number of connected nodes in the remote cluster.
- max_connections_per_cluster - the maximum number of connections maintained for the remote cluster.
- initial_connect_timeout - the initial connect timeout for remote cluster connections.
- skip_unavailable - whether the remote cluster is skipped in case it is searched through a cross-cluster search
request but none of its nodes are available.
- proxy_address - address for remote connections when proxy mode is configured.
- num_proxy_sockets_connected - number of open socket connections to the remote cluster in proxy mode is
configured.
- max_proxy_socket_connections - the maximum number of socket connections to the remote cluster when proxy mode
is configured.
"""
try:
print()
pretty_print(es.cluster.remote_info())
print()
except Exception:
error()
# elasticsearch indices-show-console
def do_indices_recovery(self, arg):
"""
The indices recovery API provides insight into on-going index shard recoveries.
$ indices_recovery [index] (args) - recovery status reported for specific indices.
* [index] - comma-separated list or wildcard expression of index names used to limit the request.
- active_only=true - the response only includes ongoing shard recoveries.
- detailed=true - the response includes detailed information about shard recoveries.
- human=true - statistics are returned in a format suitable for humans.
"""
argv = arg.split()
if len(argv) >= 1:
try:
print()
pretty_print(
es.indices.recovery(index=argv[0], params=(parse_list(argv[1:])))
)
print()
except Exception:
error()
else:
print()
print("Please provide [index] name.")
print()
def complete_indices_recovery(self, text, line, begidx, endidx):
return [i for i in indexlist() if i.startswith(text)]
def do_indices_head(self, arg):
"""
Show the [number] of first documents in the [index].
$ indices_head [index] [number] - show the [number] of first documents in [index].
"""
argv = arg.split()
if len(argv) == 2:
try:
print()
print(
json.dumps(es.search(index=argv[0], size=argv[1], q="*"), indent=4)
)
print()
except Exception:
error()
else:
print()
print("Please enter [index] name and [number] of documents.")
print()
def complete_indices_head(self, text, line, begidx, endidx):
return [i for i in indexlist() if i.startswith(text)]
def do_indices_tail(self, arg):
"""
Show the [number] of recent documents in the [index].
$ indices_tail [index] [number] [field] - show the [number] of recent documents in [index] sorted by [field].
"""
argv = arg.split()
if len(argv) == 3:
try:
print()
print(
json.dumps(
es.search(
index=argv[0], size=argv[1], q="*", sort=argv[2] + ":desc"
),
indent=4,
)
)
print()
except Exception:
error()
else:
print()
print(
"Please enter [index] name, [number] of documents and [field] for sorting."
)
print()
def complete_indices_tail(self, text, line, begidx, endidx):
return [i for i in indexlist() if i.startswith(text)]