-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathes.ml
More file actions
2347 lines (2180 loc) · 77.3 KB
/
es.ml
File metadata and controls
2347 lines (2180 loc) · 77.3 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
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
open Devkit
open ExtLib
open Printf
module J = Yojson.Safe
module SS = Set.Make(String)
let log = Log.from "es"
let http_timeout = ref (Time.seconds 60)
type common_args = {
es_version : Config_t.version option;
verbose : bool;
}
let args =
ExtArg.[
"-T", String (fun t -> http_timeout := Time.of_compact_duration t), " set HTTP request timeout (format: 45s, 2m, or 1m30s)";
]
let json_content_type = "application/json"
let ndjson_content_type = "application/x-ndjson"
type content_type =
| JSON of string
| NDJSON of string
let json_body_opt = function
| Some JSON body -> Some (`Raw (json_content_type, body))
| Some NDJSON body -> Some (`Raw (ndjson_content_type, body))
| None -> None
let make_url host path args =
let args =
List.filter_map begin function
| name, Some Some value -> Some (String.concat "=" Web.[ urlencode name; urlencode value; ])
| name, Some None -> Some (Web.urlencode name)
| _name, None -> None
end args
in
let args = match args with [] -> [] | _ -> [ String.concat "&" args; ] in
let path = String.concat "/" ("" :: List.filter_map id path) in
let path = String.concat "?" (path :: args) in
String.concat "" [ host; path; ]
let request ?verbose ?body action host path args =
Web.http_request_lwt' ?verbose ~timeout:(Time.to_sec !http_timeout) ?body:(json_body_opt body) action (make_url host path args)
let request ?verbose ?body action host path args unformat =
match%lwt request ?verbose ?body action host path args with
| `Error code -> Exn_lwt.fail "(%d) %s" (Curl.errno code) (Curl.strerror code)
| `Ok (code, result) ->
let is_error_response result = Elastic_j.((response''_of_string result).error) <> None in
let is_severe_error code result = code / 100 <> 2 && (code <> 404 || is_error_response result) in
match is_severe_error code result with
| exception exn -> Exn_lwt.fail ~exn "http %d : %s" code result
| true -> Lwt.return_error result
| false ->
match unformat result with
| exception exn -> Exn_lwt.fail ~exn "unformat %s" result
| docs -> Lwt.return_ok docs
exception ErrorExit
let fail_lwt fmt =
ksprintf begin fun s ->
let%lwt () = Lwt_io.eprintl s in
Lwt.fail ErrorExit
end fmt
let default_doc_type = "_doc"
type 't json_reader = J.lexer_state -> Lexing.lexbuf -> 't
type 't json_writer = Buffer.t -> 't -> unit
type es_version_config = {
read_total : Elastic_t.total json_reader;
write_total : Elastic_t.total json_writer;
default_get_doc_type : string;
default_put_doc_type : string option;
}
let es6_config = {
read_total = Elastic_j.read_es6_total;
write_total = Elastic_j.write_es6_total;
default_get_doc_type = "_all";
default_put_doc_type = None;
}
let es7_config = {
read_total = Elastic_j.read_total;
write_total = Elastic_j.write_total;
default_get_doc_type = default_doc_type;
default_put_doc_type = Some default_doc_type;
}
let rec coalesce = function Some _ as hd :: _ -> hd | None :: tl -> coalesce tl | [] -> None
let get_es_version { verbose; _ } host =
match%lwt request ~verbose `GET host [] [] Elastic_j.main_of_string with
| Error error -> fail_lwt "could not get ES version:\n%s" error
| Ok { Elastic_t.version = { number; }; } ->
match Stre.nsplitc number '.' with
| [] -> Exn_lwt.fail "empty ES version number"
| "5" :: _ -> Lwt.return `ES5
| "6" :: _ -> Lwt.return `ES6
| "7" :: _ -> Lwt.return `ES7
| "8" :: _ -> Lwt.return `ES8
| other :: _ ->
match int_of_string other with
| exception exn -> Exn_lwt.fail ~exn "invalid ES version number : %s" number
| _ -> Exn_lwt.fail "unsupported ES version number : %s" number
let get_es_version_config' = function
| `ES5 | `ES6 -> es6_config
| `ES7 | `ES8 -> es7_config
let get_es_version_config common_args host es_version { Config_t.version = config_version; _ } cluster_version =
let version = coalesce [ es_version; cluster_version; config_version; ] in
let%lwt version =
match version with
| Some (#Wrap.Version.exact as version) -> Lwt.return version
| None | Some `Auto -> get_es_version common_args host
in
Lwt.return (get_es_version_config' version)
let get_body_query_file body_query =
match body_query <> "" && body_query.[0] = '@' with
| true -> Control.with_input_txt (String.slice ~first:1 body_query) IO.read_all
| false -> body_query
let usage tools =
fprintf stderr "Usage: %s {<tool>|-help|version}\n" Sys.executable_name;
fprintf stderr "where <tool> is one of:\n";
List.sort ~cmp:compare tools |>
List.iter (fun (s,_) -> fprintf stderr " %s\n" s)
let str_list =
ExtArg.make_arg @@ object
method store v = Arg.String (tuck v)
method kind = "string"
method show v = match !v with [] -> "none" | l -> String.concat "," l
end
let csv ?(sep=",") = function [] -> None | l -> Some (String.concat sep l)
let int = Option.map string_of_int
let one = function [] -> None | [x] -> Some x | _ -> assert false
let flag ?(default=false) = function x when x = default -> None | true -> Some "true" | false -> Some "false"
type hit_format = [
| `FullID
| `ID
| `Type
| `Index
| `Routing
| `Hit
| `Source
]
type hit_formatter = J.t Elastic_t.option_hit -> string
let hit_format_of_string = function
| "full_id" -> `FullID
| "id" -> `ID
| "type" -> `Type
| "index" -> `Index
| "routing" -> `Routing
| "hit" -> `Hit
| "source" -> `Source
| s -> Exn.fail "unknown hit field \"%s\"" s
let string_of_hit_format = function
| `FullID -> "full_id"
| `ID -> "id"
| `Type -> "type"
| `Index -> "index"
| `Routing -> "routing"
| `Hit -> "hit"
| `Source -> "source"
let map_of_hit_format =
let open Elastic_t in function
| `FullID -> (fun ({ index; doc_type; id; _ } : 'a Elastic_t.option_hit) ->
sprintf "/%s/%s/%s" index (Option.default default_doc_type doc_type) id)
| `ID -> (fun hit -> hit.id)
| `Type -> (fun hit -> Option.default default_doc_type hit.doc_type)
| `Index -> (fun hit -> hit.index)
| `Routing -> (fun hit -> Option.default "" hit.routing)
| `Hit -> (fun hit -> Elastic_j.string_of_option_hit J.write_json hit)
| `Source -> (fun { source; _ } -> Option.map_default J.to_string "" source)
type index_shard_format = [
| `Index
| `Shard
| `Time
| `Type
| `Stage
| `SourceHost
| `SourceNode
| `TargetHost
| `TargetNode
| `Repository
| `Snapshot
| `Files
| `FilesRecovered
| `FilesPercent
| `FilesTotal
| `Bytes
| `BytesRecovered
| `BytesPercent
| `BytesTotal
| `TranslogOps
| `TranslogOpsRecovered
| `TranslogOpsPercent
]
let index_shard_format_of_string = function
| "index" -> `Index
| "shard" -> `Shard
| "time" -> `Time
| "type" -> `Type
| "stage" -> `Stage
| "source_host" -> `SourceHost
| "source_node" -> `SourceNode
| "target_host" -> `TargetHost
| "target_node" -> `TargetNode
| "repository" -> `Repository
| "snapshot" -> `Snapshot
| "files" -> `Files
| "files_recovered" -> `FilesRecovered
| "files_percent" -> `FilesPercent
| "files_total" -> `FilesTotal
| "bytes" -> `Bytes
| "bytes_recovered" -> `BytesRecovered
| "bytes_percent" -> `BytesPercent
| "bytes_total" -> `BytesTotal
| "translog_ops" -> `TranslogOps
| "translog_ops_recovered" -> `TranslogOpsRecovered
| "translog_ops_percent" -> `TranslogOpsPercent
| s -> Exn.fail "unknown index shard field \"%s\"" s
let string_of_index_shard_format = function
| `Index -> "index"
| `Shard -> "shard"
| `Time -> "time"
| `Type -> "type"
| `Stage -> "stage"
| `SourceHost -> "source_host"
| `SourceNode -> "source_node"
| `TargetHost -> "target_host"
| `TargetNode -> "target_node"
| `Repository -> "repository"
| `Snapshot -> "snapshot"
| `Files -> "files"
| `FilesRecovered -> "files_recovered"
| `FilesPercent -> "files_percent"
| `FilesTotal -> "files_total"
| `Bytes -> "bytes"
| `BytesRecovered -> "bytes_recovered"
| `BytesPercent -> "bytes_percent"
| `BytesTotal -> "bytes_total"
| `TranslogOps -> "translog_ops"
| `TranslogOpsRecovered -> "translog_ops_recovered"
| `TranslogOpsPercent -> "translog_ops_percent"
let map_of_index_shard_format =
let open Elastic_t in function
| `Index -> (fun index (_shard : index_shard) -> `String index)
| `Shard -> (fun _index shard -> `Int shard.id)
| `Time -> (fun _index shard -> `Duration (Time.msec shard.index.total_time_in_millis))
| `Type -> (fun _index shard -> `Symbol shard.kind)
| `Stage -> (fun _index shard -> `Symbol shard.stage)
| `SourceHost -> (fun _index shard -> match shard.source.host with Some host -> `String host | None -> `None)
| `SourceNode -> (fun _index shard -> match shard.source.name with Some name -> `String name | None -> `None)
| `TargetHost -> (fun _index shard -> match shard.target.host with Some host -> `String host | None -> `None)
| `TargetNode -> (fun _index shard -> match shard.target.name with Some name -> `String name | None -> `None)
| `Repository -> (fun _index _shard -> `None) (* FIXME what is repository? *)
| `Snapshot -> (fun _index _shard -> `None) (* FIXME what is snapshot? *)
| `Files -> (fun _index shard -> `Int shard.index.files.total) (* FIXME what's the difference w/ files_total? *)
| `FilesRecovered -> (fun _index shard -> `Int shard.index.files.recovered)
| `FilesPercent -> (fun _index shard -> `String shard.index.files.percent)
| `FilesTotal -> (fun _index shard -> `Int shard.index.files.total)
| `Bytes -> (fun _index shard -> `Int shard.index.size.total_in_bytes) (* FIXME what's the difference w/ bytes_total? *)
| `BytesRecovered -> (fun _index shard -> `Int shard.index.size.recovered_in_bytes)
| `BytesPercent -> (fun _index shard -> `String shard.index.size.percent)
| `BytesTotal -> (fun _index shard -> `Int shard.index.size.total_in_bytes)
| `TranslogOps -> (fun _index shard -> `Int shard.translog.total)
| `TranslogOpsRecovered -> (fun _index shard -> `Int shard.translog.recovered)
| `TranslogOpsPercent -> (fun _index shard -> `String shard.translog.percent)
let default_index_shard_format = [
`Index; `Shard; `Time; `Type; `Stage;
`SourceHost; `SourceNode; `TargetHost; `TargetNode;
`Repository; `Snapshot;
`Files; `FilesRecovered; `FilesPercent; `FilesTotal;
`Bytes; `BytesRecovered; `BytesPercent; `BytesTotal;
`TranslogOps; `TranslogOpsRecovered; `TranslogOpsPercent;
]
let map_show = function
| `String x | `Symbol x -> x
| `Int x -> string_of_int x
| `Float x -> string_of_float x
| `Duration x -> Time.compact_duration x
| `None -> "n/a"
let compare_fmt = function
| `String x -> String.equal x
| `Symbol x -> String.equal (String.lowercase_ascii x) $ String.lowercase_ascii
| `Int x -> Factor.Int.equal x $ int_of_string
| `Float x -> Factor.Float.equal x $ float_of_string
| `Duration x -> Factor.Float.equal x $ float_of_string (* FIXME parse time? *)
| `None -> (fun _ -> false)
let split doc_id = Stre.nsplitc doc_id '/'
let join doc_id = String.concat "/" doc_id
let is_pure_id' doc_id =
match doc_id with
| [ _doc_id; ] | [ ""; _doc_id; ] -> true
| _ -> false
let is_pure_id doc_id = is_pure_id' (split doc_id)
let map_index_doc_id' doc_type doc_id =
match doc_id with
| [ doc_id; ] | [ ""; doc_id; ] -> Exn_lwt.fail "document id missing index name : /%s" doc_id
| [ index; doc_id; ] | [ ""; index; doc_id; ] -> Lwt.return (index, doc_type, doc_id)
| [ index; doc_type; doc_id; ] | [ ""; index; doc_type; doc_id; ] -> Lwt.return (index, Some doc_type, doc_id)
| _ -> Exn_lwt.fail "invalid document id : %s" (join doc_id)
let map_index_doc_id doc_type doc_id = map_index_doc_id' doc_type (split doc_id)
let map_doc_id' index doc_type doc_id =
match doc_id with
| [ doc_id; ] | [ ""; doc_id; ] -> Lwt.return (index, doc_type, doc_id)
| [ doc_type; doc_id; ] | [ ""; doc_type; doc_id; ] -> Lwt.return (index, Some doc_type, doc_id)
| _ -> Exn_lwt.fail "invalid document id : /%s/%s" index (join doc_id)
let map_doc_id index doc_type doc_id = map_doc_id' index doc_type (split doc_id)
let map_doc_id_opt' index doc_type doc_id =
let%lwt (index, doc_type, doc_id) = map_doc_id' index doc_type doc_id in
Lwt.return (index, doc_type, Some doc_id)
let map_doc_id_opt index doc_type doc_id = map_doc_id_opt' index doc_type (split doc_id)
let map_typed_doc_id' index doc_type doc_id =
match doc_id with
| [ doc_id; ] | [ ""; doc_id; ] -> Lwt.return (index, Some doc_type, doc_id)
| _ -> Exn_lwt.fail "invalid document id : /%s/%s/%s" index doc_type (join doc_id)
let map_typed_doc_id index doc_type doc_id = map_typed_doc_id' index doc_type (split doc_id)
let map_typed_doc_id_opt' index doc_type doc_id =
let%lwt (index, doc_type, doc_id) = map_typed_doc_id' index doc_type doc_id in
Lwt.return (index, doc_type, Some doc_id)
let map_typed_doc_id_opt index doc_type doc_id = map_typed_doc_id_opt' index doc_type (split doc_id)
let map_index_mode index =
match Stre.nsplitc index '/' with
| [ index; ] | [ ""; index; ] -> `Index index
| [ index; doc_type_or_id; ] | [ ""; index; doc_type_or_id; ] -> `IndexOrID (index, doc_type_or_id)
| [ index; doc_type; doc_id; ] | [ ""; index; doc_type; doc_id; ] -> `ID (index, doc_type, doc_id)
| _ -> Exn.fail "invalid index name or document id : %s" index
let map_ids ~default_get_doc_type index doc_type doc_ids =
let multiple (first_index, first_doc_type, _doc_id as first_doc) other_doc_ids =
let first_doc_type = Option.default default_get_doc_type first_doc_type in
let merge_equal x y = match x with Some x' when String.equal x' y -> x | _ -> None in
let (docs, common_index, common_doc_type) =
List.fold_left begin fun (docs, common_index, common_doc_type) (index, doc_type, _doc_id as doc) ->
let common_index = merge_equal common_index index in
let common_doc_type = merge_equal common_doc_type (Option.default default_get_doc_type doc_type) in
doc :: docs, common_index, common_doc_type
end ([ first_doc; ], Some first_index, Some first_doc_type) other_doc_ids
in
let (docs, index, doc_type) =
match common_index, common_doc_type with
| Some _, Some _ ->
let docs = List.map (fun (_index, _doc_type, doc_id) -> None, None, doc_id) docs in
docs, common_index, common_doc_type
| Some _, None ->
let docs = List.map (fun (_index, doc_type, doc_id) -> None, doc_type, doc_id) docs in
docs, common_index, None
| None, _ ->
let docs = List.map (fun (index, doc_type, doc_id) -> Some index, doc_type, doc_id) docs in
docs, None, None
in
Lwt.return (`Multi (docs, index, doc_type))
in
let%lwt mode = Lwt.wrap1 map_index_mode index in
let doc_ids = List.map split doc_ids in
match mode, doc_ids with
| `Index _, [] ->
let%lwt () = Lwt_io.eprintl "only INDEX is provided and no DOC_ID" in
Lwt.return `None
| `Index index, [ doc_id; ] ->
let%lwt (index, doc_type, doc_id) = map_doc_id' index doc_type doc_id in
let doc_type = Option.default default_get_doc_type doc_type in
Lwt.return (`Single (Some index, Some doc_type, Some doc_id))
| `Index index, doc_id :: doc_ids ->
let%lwt doc_id = map_doc_id' index doc_type doc_id in
let%lwt doc_ids = Lwt_list.map_s (map_doc_id' index doc_type) doc_ids in
multiple doc_id doc_ids
| `IndexOrID (index, doc_id), [] ->
let doc_type = Option.default default_get_doc_type doc_type in
Lwt.return (`Single (Some index, Some doc_type, Some doc_id))
| `IndexOrID (index, doc_type), doc_id :: doc_ids when List.for_all is_pure_id' (doc_id :: doc_ids) ->
begin match doc_ids with
| [] ->
let%lwt (index, doc_type, doc_id) = map_typed_doc_id' index doc_type doc_id in
Lwt.return (`Single (Some index, doc_type, Some doc_id))
| _ ->
let%lwt doc_id = map_typed_doc_id' index doc_type doc_id in
let%lwt doc_ids = Lwt_list.map_s (map_typed_doc_id' index doc_type) doc_ids in
multiple doc_id doc_ids
end
| `IndexOrID (index, doc_id), doc_ids ->
let%lwt doc_ids = Lwt_list.map_s (map_index_doc_id' doc_type) doc_ids in
multiple (index, doc_type, doc_id) doc_ids
| `ID (index, doc_type, doc_id), [] ->
Lwt.return (`Single (Some index, Some doc_type, Some doc_id))
| `ID (index, doc_type', doc_id), doc_ids ->
let%lwt doc_ids = Lwt_list.map_s (map_index_doc_id' doc_type) doc_ids in
multiple (index, Some doc_type', doc_id) doc_ids
module Common_args = struct
open Cmdliner
let host = Arg.(required & pos 0 (some string) None & info [] ~docv:"HOST" ~doc:"host")
let index = Arg.(required & pos 1 (some string) None & info [] ~docv:"INDEX" ~doc:"index")
let doc_type = Arg.(value & opt (some string) None & info [ "T"; "doctype"; ] ~docv:"DOC_TYPE" ~doc:"document type")
let doc_id = Arg.(pos 2 (some string) None & info [] ~docv:"DOC_ID" ~doc:"document id")
let doc_ids =
let doc = "document ids" in
Arg.(value & pos_right 1 string [] & info [] ~docv:"DOC_ID1[ DOC_ID2[ DOC_ID3...]]" ~doc)
let timeout = Arg.(value & opt (some string) None & info [ "t"; "timeout"; ] ~doc:"timeout")
let source_includes = Arg.(value & opt_all string [] & info [ "i"; "source-includes"; ] ~doc:"source_includes")
let source_excludes = Arg.(value & opt_all string [] & info [ "e"; "source-excludes"; ] ~doc:"source_excludes")
let routing = Arg.(value & opt (some string) None & info [ "r"; "routing"; ] ~doc:"routing")
let preference = Arg.(value & opt_all string [] & info [ "p"; "preference"; ] ~doc:"preference")
let sort = Arg.(value & opt_all string [] & info [ "s"; "sort"; ] ~doc:"sort")
let format =
let parse format =
match hit_format_of_string format with
| exception Failure msg -> Error (`Msg msg)
| format -> Ok format
in
let print fmt format =
Format.fprintf fmt "%s" (string_of_hit_format format)
in
Arg.(list (conv (parse, print)))
let format = Arg.(value & opt_all format [] & info [ "f"; "format"; ] ~doc:"map hits according to specified format (hit|id|source)")
type expand_wildcards =
| All
| Open
| Closed
| Hidden
| None_
let string_of_expand_wildcards = function
| All -> "all"
| Open -> "open"
| Closed -> "closed"
| Hidden -> "hidden"
| None_ -> "none"
let expand_wildcards =
let conv_expand_wildcards =
let parse = function
| "all" -> Ok All
| "open" -> Ok Open
| "closed" -> Ok Closed
| "hidden" -> Ok Hidden
| "none" -> Ok None_
| x -> Error (`Msg x)
in
Arg.conv (parse, (fun fmt x -> Format.fprintf fmt "%s" (string_of_expand_wildcards x)))
in
Arg.(value & opt (some conv_expand_wildcards) None & info [ "w"; "expand-wildcards"; ] ~doc:"expand_wildcards")
end (* Common_args *)
type alias_action = {
action : [ `Add | `Remove ];
index : string;
alias : string;
}
type alias_args = {
host : string;
actions : alias_action list;
}
let alias { verbose; _ } {
host;
actions;
} =
let config = Common.load_config () in
let { Common.host; _ } = Common.get_cluster config host in
let (action, body) =
match actions with
| [] -> `GET, None
| actions ->
let actions = List.map (fun { action; index; alias; } -> [ action, { Elastic_t.index; alias; }; ]) actions in
`POST, Some (JSON (Elastic_j.string_of_aliases { Elastic_t.actions; }) : content_type)
in
Lwt_main.run @@
match%lwt request ~verbose ?body action host [ Some "_aliases"; ] [] id with
| Error error -> fail_lwt "alias error:\n%s" error
| Ok result -> Lwt_io.printl result
type cat_format =
| Text
| JSON
| Smile
| YAML
| CBOR
let string_of_cat_format = function
| Text -> "text"
| JSON -> "json"
| Smile -> "smile"
| YAML -> "yaml"
| CBOR -> "cbor"
type cat_args = {
host : string;
query : string list;
help : bool;
headers : bool;
columns : string list;
sort : string list;
format : cat_format option;
time_units : string option;
size_units : string option;
byte_units : string option;
expand_wildcards : Common_args.expand_wildcards option;
args : (string * string option) list;
}
let cat ({ verbose; _ } as _common_args) {
host;
query;
help;
headers;
columns;
sort;
format;
time_units;
size_units;
byte_units;
expand_wildcards;
args;
} =
let config = Common.load_config () in
let { Common.host; _ } = Common.get_cluster config host in
let flag name ?value x l = if x then (name, Some value) :: l else l in
let args =
List.map (fun (k, v) -> k, Option.map some v) [
"h", csv columns;
"s", csv sort;
"time", time_units;
"size", size_units;
"bytes", byte_units;
"format", Option.map string_of_cat_format format;
"expand_wildcards", Option.map Common_args.string_of_expand_wildcards expand_wildcards;
] @
flag "help" help @@
flag "v" headers @@
List.map (fun (k, v) -> k, Some v) args
in
Lwt_main.run @@
match%lwt request ~verbose `GET host (Some "_cat" :: List.map some query) args id with
| Error error -> fail_lwt "cat error:\n%s" error
| Ok result -> Lwt_io.print result
type count_args = {
host : string;
index : string;
doc_type : string option;
timeout : string option;
routing : string option;
preference : string list;
query : string option;
body_query : string option;
analyzer : string option;
analyze_wildcard : bool;
default_field : string option;
default_operator : string option;
retry : bool;
}
let count ({ verbose; _ } as _common_args) {
host;
index;
doc_type;
timeout;
routing;
preference;
query;
body_query;
analyzer;
analyze_wildcard;
default_field;
default_operator;
retry = _;
} =
let config = Common.load_config () in
let { Common.host; _ } = Common.get_cluster config host in
Lwt_main.run @@
let body_query = Option.map get_body_query_file body_query in
let args =
List.map (fun (k, v) -> k, Option.map some v) [
"timeout", timeout;
"routing", routing;
"preference", csv ~sep:"|" preference;
"analyzer", analyzer;
"analyze_wildcard", flag analyze_wildcard;
"df", default_field;
"default_operator", default_operator;
"q", query;
]
in
let body_query = match body_query with Some query -> Some (JSON query : content_type) | None -> None in
let count () =
match%lwt request ~verbose ?body:body_query `POST host [ Some index; doc_type; Some "_count"; ] args id with
| Error error -> fail_lwt "count error:\n%s" error
| Ok result ->
let { Elastic_t.count; shards = { Elastic_t.failed = _; _ }; } = Elastic_j.count_of_string result in
Lwt_io.printlf "%d" count
(* TODO check failed > 0 && retry *)
in
count ()
type delete_args = {
host : string;
index : string;
doc_type : string option;
doc_ids : string list;
timeout : string option;
routing : string option;
}
let delete ({ verbose; es_version; _ } as common_args) {
host;
index;
doc_type;
doc_ids;
timeout;
routing;
} =
let config = Common.load_config () in
let { Common.host; version; _ } = Common.get_cluster config host in
Lwt_main.run @@
let%lwt ({ default_get_doc_type; _ }) =
get_es_version_config common_args host es_version config version
in
match%lwt map_ids ~default_get_doc_type index doc_type doc_ids with
| `None -> Lwt.return_unit
| `Single _ | `Multi _ as mode ->
let (action, body, path) =
match mode with
| `Single (index, doc_type, doc_id) -> `DELETE, None, [ index; doc_type; doc_id; ]
| `Multi (docs, index, doc_type) ->
let body =
List.fold_left begin fun acc (index, doc_type, doc_id) ->
let delete = { Elastic_t.index; doc_type; id = doc_id; routing = None; } in
let bulk = { Elastic_t.index = None; create = None; update = None; delete = Some delete; } in
"\n" :: Elastic_j.string_of_bulk bulk :: acc
end [] docs |>
List.rev |>
String.concat ""
in
`POST, Some (NDJSON body), [ index; doc_type; Some "_bulk"; ]
in
let args =
List.map (fun (k, v) -> k, Option.map some v) [
"timeout", timeout;
"routing", routing;
]
in
match%lwt request ~verbose ?body action host path args id with
| Error response -> Lwt_io.eprintl response
| Ok response -> Lwt_io.printl response
type flush_args = {
host : string;
indices : string list;
force : bool;
synced : bool;
wait : bool;
}
let flush { verbose; _ } {
host;
indices;
force;
synced;
wait;
} =
let config = Common.load_config () in
let { Common.host; _ } = Common.get_cluster config host in
let bool' v = function true -> Some v | false -> None in
let bool = bool' "true" in
let args =
List.map (fun (k, v) -> k, Option.map some v) [
"force", bool force;
"wait_if_ongoing", bool wait;
]
in
let path = [ csv indices; Some "_flush"; bool' "synced" synced; ] in
Lwt_main.run @@
match%lwt request ~verbose `POST host path args id with
| Error error -> fail_lwt "flush error:\n%s" error
| Ok result -> Lwt_io.printl result
type get_args = {
host : string;
index : string;
doc_type : string option;
doc_ids : string list;
timeout : string option;
source_includes : string list;
source_excludes : string list;
routing : string option;
preference : string list;
format : hit_format list list;
}
let get ({ verbose; es_version; _ } as common_args) {
host;
index;
doc_type;
doc_ids;
timeout;
source_includes;
source_excludes;
routing;
preference;
format;
} =
let config = Common.load_config () in
let { Common.host; version; _ } = Common.get_cluster config host in
Lwt_main.run @@
let%lwt ({ default_get_doc_type; _ }) =
get_es_version_config common_args host es_version config version
in
match%lwt map_ids ~default_get_doc_type index doc_type doc_ids with
| `None -> Lwt.return_unit
| `Single _ | `Multi _ as mode ->
let (body, path, unformat) =
match mode with
| `Single (index, doc_type, doc_id) ->
let path = [ index; doc_type; doc_id; ] in
let unformat x = [ Elastic_j.option_hit_of_string J.read_json x; ] in
None, path, unformat
| `Multi (docs, index, doc_type) ->
let (docs, ids) =
match index, doc_type with
| Some _, Some _ ->
let ids = List.map (fun (_index, _doc_type, doc_id) -> doc_id) docs in
[], ids
| _ ->
let docs =
List.map begin fun (index, doc_type, id) ->
{ Elastic_t.index; doc_type; id; routing = None; source = None; stored_fields = None; }
end docs
in
docs, []
in
let path = [ index; doc_type; Some "_mget"; ] in
let unformat x =
let { Elastic_t.docs; } = Elastic_j.docs_of_string (Elastic_j.read_option_hit J.read_json) x in
docs
in
Some (JSON (Elastic_j.string_of_multiget { docs; ids; }) : content_type), path, unformat
in
let args =
List.map (fun (k, v) -> k, Option.map some v) [
"timeout", timeout;
(if source_excludes = [] then "_source" else "_source_includes"), csv source_includes;
"_source_excludes", csv source_excludes;
"routing", routing;
"preference", csv ~sep:"|" preference;
]
in
let request unformat = request ~verbose ?body `GET host path args unformat in
match format with
| [] ->
begin match%lwt request id with
| Error response -> Lwt_io.eprintl response
| Ok response -> Lwt_io.printl response
end
| _ ->
match%lwt request unformat with
| Error response -> Lwt_io.eprintl response
| Ok docs ->
Lwt_list.iter_s begin fun hit ->
List.map (List.map map_of_hit_format) format |>
List.concat |>
List.map (fun f -> f hit) |>
String.join " " |>
Lwt_io.printl
end docs
type health_args = {
hosts : string list;
}
let health { verbose; _ } {
hosts;
} =
let config = Common.load_config () in
let all_hosts = lazy (List.map (fun (name, _) -> Common.get_cluster config name) config.Config_t.clusters) in
let hosts =
match List.rev hosts with
| [] -> !!all_hosts
| hosts ->
List.map begin function
| "_all" -> !!all_hosts
| name -> [ Common.get_cluster config name; ]
end hosts |>
List.concat
in
Lwt_main.run @@
let%lwt results =
Lwt_list.mapi_p begin fun i { Common.host; _ } ->
let columns = [
"cluster"; "status";
"node.total"; "node.data";
"shards"; "pri"; "relo"; "init"; "unassign";
"pending_tasks"; "max_task_wait_time";
"active_shards_percent";
] in
let args = [ "h", Some (Some (String.concat "," columns)); ] in
match%lwt request ~verbose `GET host [ Some "_cat"; Some "health"; ] args id with
| Error error -> Lwt.return (i, sprintf "%s error %s\n" host error)
| Ok result -> Lwt.return (i, sprintf "%s %s" host result)
end hosts
in
List.sort ~cmp:(Factor.Int.compare $$ fst) results |>
Lwt_list.iter_s (fun (_i, result) -> Lwt_io.print result)
type index_action =
| Get
| Create
| Delete
| Open
| Close
| Freeze
| Unfreeze
| Settings
| Mappings
type index_args = {
host : string;
index : string;
action : index_action;
expand_wildcards : Common_args.expand_wildcards option;
body : string option;
}
let index_tool { verbose; _ } {
host;
index;
action;
expand_wildcards;
body;
} =
let config = Common.load_config () in
let { Common.host; _ } = Common.get_cluster config host in
Lwt_main.run @@
let (meth, body) = match body with Some body -> `PUT, Some (JSON body : content_type) | None -> `GET, None in
let (meth, path) =
match action with
| Get -> `GET, None
| Create -> `PUT, None
| Delete -> `DELETE, None
| Open -> `POST, Some "_open"
| Close -> `POST, Some "_close"
| Freeze -> `POST, Some "_freeze"
| Unfreeze -> `POST, Some "_unfreeze"
| Settings -> meth, Some "_settings"
| Mappings -> meth, Some "_mappings"
in
let path = Some index :: path :: [] in
let args =
List.map (fun (k, v) -> k, Option.map some v) [
"expand_wildcards", Option.map Common_args.string_of_expand_wildcards expand_wildcards;
]
in
match%lwt request ~verbose ?body meth host path args id with
| Error error -> fail_lwt "index error:\n%s" error
| Ok result -> Lwt_io.printl result
type nodes_args = {
host : string;
check_nodes : string list;
}
let nodes { verbose; _ } {
host;
check_nodes;
} =
let config = Common.load_config () in
let { Common.host; nodes; _ } = Common.get_cluster config host in
let check_nodes = match check_nodes with [] -> Option.default [] nodes | nodes -> nodes in
let check_nodes = SS.of_list (List.concat (List.map Common.expand_node check_nodes)) in
Lwt_main.run @@
match%lwt request ~verbose `GET host [ Some "_nodes"; ] [] J.from_string with
| Error error -> fail_lwt "nodes error:\n%s" error
| Ok result ->
J.Util.member "nodes" result |>
J.Util.to_assoc |>
List.fold_left begin fun (missing, present) (_node_id, node) ->
let name = J.Util.member "name" node |> J.Util.to_string in
SS.remove name missing, SS.add name present
end (check_nodes, SS.empty) |>
fun (missing, present) ->
let%lwt () =
match SS.is_empty missing with
| true -> Lwt.return_unit
| false -> Lwt_io.printlf "missing: %s" (String.concat " " (SS.elements missing))
in
let%lwt () =
let unlisted = SS.diff present check_nodes in
match SS.is_empty unlisted with
| true -> Lwt.return_unit
| false -> Lwt_io.printlf "unlisted: %s" (String.concat " " (SS.elements unlisted))
in
Lwt.return_unit
type put_args = {
host : string;
index : string;
doc_type : string option;
doc_id : string option;
routing : string option;
body : string option;
}
let put ({ verbose; es_version; _ } as common_args) {
host;
index;
doc_type;
doc_id;
routing;
body;
} =
let config = Common.load_config () in
let { Common.host; version; _ } = Common.get_cluster config host in
Lwt_main.run @@
let%lwt { default_put_doc_type; _ } =
get_es_version_config common_args host es_version config version
in
let%lwt (index, doc_type, doc_id) =
let%lwt mode = Lwt.wrap1 map_index_mode index in
match mode, doc_id with
| `Index index, None -> Lwt.return (index, doc_type, None)
| `Index index, Some doc_id -> map_doc_id_opt index doc_type doc_id
| `IndexOrID (index, doc_id), None -> Lwt.return (index, doc_type, Some doc_id)
| `IndexOrID (index, doc_type), Some doc_id -> map_typed_doc_id_opt index doc_type doc_id
| `ID (index, doc_type, doc_id), None -> Lwt.return (index, Some doc_type, Some doc_id)
| `ID (index, doc_type, doc_id1), Some doc_id2 ->
Exn_lwt.fail "invalid document id : /%s/%s/%s/%s" index doc_type doc_id1 doc_id2
in
let%lwt doc_type =
match coalesce [ doc_type; default_put_doc_type; ] with
| Some doc_type -> Lwt.return doc_type
| None -> Exn_lwt.fail "DOC_TYPE is not provided"
in
let args = [ "routing", Option.map some routing; ] in
let%lwt body = match body with Some body -> Lwt.return body | None -> Lwt_io.read Lwt_io.stdin in
let action = if doc_id <> None then `PUT else `POST in
match%lwt request ~verbose ~body:(JSON body) action host [ Some index; Some doc_type; doc_id; ] args id with
| Error error -> fail_lwt "put error:\n%s" error