forked from Shuffle/shuffle-shared
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopensearch_lifecycle.go
More file actions
2273 lines (2006 loc) · 85.7 KB
/
Copy pathopensearch_lifecycle.go
File metadata and controls
2273 lines (2006 loc) · 85.7 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
// This file contains all OpenSearch index lifecycle management: creation,
// mapping-drift migration, rollover, ISM retention policies, and the
// low-level index/alias/task helpers those flows are built from.
package shuffle
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/shuffle/opensearch-go/v4/opensearchapi"
)
// resolveAliasWriteIndex looks up whether the given alias already has a write
// index attached in OpenSearch.
func resolveAliasWriteIndex(aliasInfo map[string]map[string]opensearchAliasState, alias string) (writeIndex string, found bool) {
for indexName, aliases := range aliasInfo {
if state, ok := aliases[alias]; ok && state.Present && state.IsWriteIndex {
return indexName, true
}
}
return "", false
}
// resolveAppendIndexCreationTarget decides which concrete backing index the
// create-loop in InitOpensearchIndices should target for a given append
// (rollover) base index: either a brand new "-000001" generation (if none
// exists yet) or the highest existing generation (if the index has already
// been created/rolled/collapsed before).
//
// existingIndices is the full list of real index names currently in the
// cluster (from getOpensearchIndices).
func resolveAppendIndexCreationTarget(existingIndices []string, index string) (target string, alreadyExists bool) {
prefix := index + "-"
highestGen := -1
highestName := ""
for _, name := range existingIndices {
if !strings.HasPrefix(name, prefix) {
continue
}
gen := getOpensearchGeneration(name)
if gen <= 0 {
continue
}
if gen > highestGen {
highestGen = gen
highestName = name
}
}
if highestName == "" {
return fmt.Sprintf("%s-000001", index), false
}
return highestName, true
}
// InitOpensearchIndices is the entry point for OpenSearch startup
// bootstrapping: creates every base index (from GetOpensearchBaseIndices)
// that doesn't exist yet, attaches rollover aliases/ISM policies for the
// rollover-eligible subset, registers mapping templates for future rollover
// generations, and migrates any single/keyed index whose live mapping has
// drifted from opensearchCoreMappings.
//
// Safe to call on every backend restart and from multiple replicas
// concurrently - every step is idempotent or existence-checked first. No-op
// if DbType isn't "opensearch" or if SHUFFLE_SKIP_OPENSEARCH_INDEX_INIT is
// set.
func InitOpensearchIndices() {
if project.DbType != "opensearch" {
return
}
if os.Getenv("SHUFFLE_SKIP_OPENSEARCH_INDEX_INIT") == "true" {
return
}
// Check if the "workflowexecution" index exists and configuring rollovers if possible
log.Printf("[INFO] Configuring Opensearch indices for scaling")
ctx := context.Background()
opensearchUrl := strings.TrimRight(os.Getenv("SHUFFLE_OPENSEARCH_URL"), "/")
if len(opensearchUrl) == 0 {
opensearchUrl = "https://shuffle-opensearch:9200"
}
relevantScaleIndices := []string{}
for _, baseIndex := range GetOpensearchBaseIndices() {
relevantScaleIndices = append(relevantScaleIndices, GetESIndexPrefix(baseIndex))
}
// Only append-heavy stores get rollover. Stateful keyed stores stay on a
// single backing index (rollover there splits _id across generations
// and breaks single-document reads, e.g. org_statistics).
appendIndices := []string{}
for _, baseIndex := range GetOpensearchRolloverIndices() {
appendIndices = append(appendIndices, strings.ToLower(GetESIndexPrefix(baseIndex)))
}
singleIndices := []string{}
for _, index := range relevantScaleIndices {
index = strings.ToLower(index)
if !ArrayContains(appendIndices, index) {
singleIndices = append(singleIndices, index)
}
}
customConfig := os.Getenv("OPENSEARCH_INDEX_CONFIG")
if len(customConfig) > 0 {
checkValidJson := map[string]interface{}{}
if err := json.Unmarshal([]byte(customConfig), &checkValidJson); err != nil {
log.Printf("[ERROR] Invalid JSON in OPENSEARCH_INDEX_CONFIG: %s", err)
customConfig = ""
} else {
log.Printf("[DEBUG] Using custom index config for relevant scale indices: %s", customConfig)
}
}
customRollover := os.Getenv("OPENSEARCH_INDEX_ROLLOVER")
if len(customRollover) > 0 {
checkValidJson := map[string]interface{}{}
if err := json.Unmarshal([]byte(customRollover), &checkValidJson); err != nil {
log.Printf("[ERROR] Invalid JSON in OPENSEARCH_INDEX_ROLLOVER: %s", err)
customRollover = ""
} else {
log.Printf("[DEBUG] Using custom rollover config for relevant scale indices: %s", customRollover)
}
}
rolloverConfig, err := json.Marshal(map[string]interface{}{
"conditions": getOpensearchDefaultRolloverConditions(),
})
if err != nil {
log.Printf("[ERROR] Failed building default rollover config: %s", err)
return
}
if len(customRollover) > 0 {
rolloverConfig = []byte(customRollover)
}
ismEnabled := strings.ToLower(strings.TrimSpace(os.Getenv("OPENSEARCH_USE_ISM_ROLLOVER"))) != "false"
ismPolicyName := strings.TrimSpace(os.Getenv("OPENSEARCH_ISM_POLICY_NAME"))
if ismPolicyName == "" {
ismPolicyName = "shuffle-rollover"
}
// Ensure all ISM rollover policies exist and are up to date.
ismReady := false
if ismEnabled {
for _, baseIndex := range GetOpensearchRolloverIndices() {
alias := strings.ToLower(GetESIndexPrefix(baseIndex))
retention := getOpensearchRetentionDays(baseIndex)
ready, err := ensureOpensearchISMRolloverPolicy(ctx, opensearchUrl, alias, rolloverConfig, retention, ismPolicyName)
if err != nil {
log.Printf("[WARNING] Failed ensuring ISM rollover policy '%s': %s", ismPolicyName, err)
continue
}
if ready {
ismReady = true
}
}
}
// Fix existing indices
if fixResult, fixErr := FixOpensearchIndexPrefix(ctx); fixErr != nil {
log.Printf("[WARNING] Prefix repair before init failed: %s", fixErr)
} else if !fixResult.Success {
log.Printf("[WARNING] Prefix repair before init completed with verification warnings: %s", fixResult.Reason)
} else {
log.Printf("[INFO] Prefix repair before init: expected aliases=%d found=%d", fixResult.ExpectedAliases, fixResult.FoundAliases)
}
// Ensure an IndexTemplate exists for all rollover indices.
if len(customConfig) == 0 {
ensureOpensearchMappingTemplates(ctx, opensearchUrl)
}
existingOpensearchIndices, existingIndicesErr := getOpensearchIndices(project.Es, opensearchUrl)
if existingIndicesErr != nil {
log.Printf("[WARNING] Failed listing existing OpenSearch indices before create-loop (falling back to blind -000001 creation for all indices): %s", existingIndicesErr)
existingOpensearchIndices = []string{}
}
existingOpensearchAliases, existingAliasesErr := getOpensearchAliases(project.Es, opensearchUrl)
if existingAliasesErr != nil {
log.Printf("[WARNING] Failed listing existing OpenSearch aliases before create-loop (falling back to name-based existence checks only): %s", existingAliasesErr)
existingOpensearchAliases = map[string]map[string]opensearchAliasState{}
}
for _, index := range relevantScaleIndices {
indexConfig, err := json.Marshal(map[string]interface{}{
"aliases": map[string]interface{}{
index: map[string]bool{"is_write_index": true},
},
"settings": getOpensearchDefaultIndexSettings(),
"mappings": opensearchDynamicMappingSettings(),
})
if err != nil {
log.Printf("[ERROR] Failed building default index config for %s: %s", index, err)
continue
}
if len(customConfig) > 0 {
indexConfig = []byte(customConfig)
// Check if alias is in the index or not, otherwise inject it
unmarshalled := map[string]interface{}{}
if err := json.Unmarshal(indexConfig, &unmarshalled); err != nil {
log.Printf("[ERROR] Invalid JSON in OPENSEARCH_INDEX_CONFIG (2): %s", err)
} else {
if _, ok := unmarshalled["aliases"]; !ok {
// Inject it
aliasPart := map[string]interface{}{
index: map[string]bool{
"is_write_index": true,
},
}
unmarshalled["aliases"] = aliasPart
newConfig, err := json.Marshal(unmarshalled)
if err != nil {
log.Printf("[ERROR] Invalid JSON in OPENSEARCH_INDEX_CONFIG (3): %s", err)
} else {
indexConfig = newConfig
log.Printf("[INFO] Injected alias into OPENSEARCH_INDEX_CONFIG for index %s", index)
}
}
}
}
index = strings.ToLower(index)
isAppend := ArrayContains(appendIndices, index)
if len(customConfig) == 0 {
indexConfig = applyOpensearchCoreMappings(indexConfig, index)
}
initialIndexName, alreadyExists := resolveAppendIndexCreationTarget(existingOpensearchIndices, index)
if !alreadyExists {
// Name-prefix matching found nothing, but the alias may still
// already be served by a legacy, oddly-named backing index
// (e.g. from an old double-prefix bug).
//
// Check the alias's actual write-index assignment before
// attempting to create a new index - creating one now would
// give the alias two write indices and OpenSearch would reject
// it outright.
if writeIndex, aliasHasWriteIndex := resolveAliasWriteIndex(existingOpensearchAliases, index); aliasHasWriteIndex {
initialIndexName = writeIndex
alreadyExists = true
}
}
if isAppend {
indexConfig = ensureOpensearchIndexRolloverAlias(indexConfig, index)
}
// Directly try to force create it. Opensearch throws a 400 if it fails.
var resp *opensearchapi.IndicesCreateResp
var createErr error
if alreadyExists {
log.Printf("[INFO] Index %s already exists at generation %s - skipping creation, ensuring ISM/rollover on existing index", index, initialIndexName)
} else {
resp, createErr = project.Es.Indices.Create(ctx, opensearchapi.IndicesCreateReq{
Index: initialIndexName,
Body: bytes.NewReader(indexConfig),
})
res := resp.Inspect().Response
defer res.Body.Close()
if createErr != nil {
if !strings.Contains(fmt.Sprintf("%s", createErr), "serverless mode") && !strings.Contains(fmt.Sprintf("%s", createErr), "resource_already_exists_exception") {
log.Printf("[WARNING] Error creating index %s: %s", index, createErr)
}
// Make sure if the resource exist it is part of correct alias
if strings.Contains(fmt.Sprintf("%s", createErr), "resource_already_exists_exception") {
body := fmt.Sprintf(`{
"actions": [
{
"add": {
"index": "%s",
"alias": "%s",
"is_write_index": true
}
}
]
}`, initialIndexName, index)
aliasResp, aerr := project.Es.Aliases(ctx, opensearchapi.AliasesReq{
Body: strings.NewReader(body),
})
if aerr != nil {
log.Printf("[WARNING] Failed to ensure alias %s for index %s: %s", index, initialIndexName, aerr)
return
}
res := aliasResp.Inspect().Response
defer res.Body.Close()
if res.StatusCode >= 300 {
log.Printf("[WARNING] Alias enforcement failed: %s", res.String())
return
}
}
} else {
if res.IsError() {
if !strings.Contains(res.String(), "resource_already_exists_exception") {
log.Printf("[DEBUG] Error creating index %s with custom config: %s", index, res.String())
}
} else {
log.Printf("[DEBUG] Successfully created index %s with custom config", index)
}
}
}
// Non-append indices stay on a single backing index - no rollover/ISM.
if !isAppend {
continue
}
if ismReady {
if err := ensureOpensearchIndexRolloverAliasSetting(ctx, opensearchUrl, initialIndexName, index); err != nil {
log.Printf("[WARNING] Failed ensuring rollover_alias on index %s: %s", initialIndexName, err)
}
policyID := fmt.Sprintf("%s-%s", ismPolicyName, index)
if err := ensureOpensearchIndexISMPolicy(ctx, opensearchUrl, initialIndexName, policyID); err != nil {
log.Printf("[WARNING] Failed attaching ISM policy '%s' to %s: %s", policyID, initialIndexName, err)
}
continue
}
rolloverResp, err := project.Es.Indices.Rollover(ctx, opensearchapi.IndicesRolloverReq{
Alias: index,
Body: bytes.NewReader(rolloverConfig),
})
if err != nil {
if !strings.Contains(fmt.Sprintf("%s", err), "serverless mode") && !strings.Contains(fmt.Sprintf("%s", err), "status: 404") {
log.Printf("[WARNING] Problem during rollover config for %s: %s", index, err)
}
continue
}
rolloverRes := rolloverResp.Inspect().Response
defer rolloverRes.Body.Close()
if rolloverRes.IsError() {
log.Printf("[ERROR] Rollover config failed for %s: %s", index, rolloverRes.String())
} else {
log.Printf("[INFO] Rollover executed successfully for %s", index)
}
}
// Migrate existing deployments that rolled stateful indices in the past:
// collapse all generations of each single index into its newest backing
// index and detach ISM so it never rolls again. Idempotent.
for _, singleIndex := range singleIndices {
if err := collapseSingleIndexAliases(ctx, opensearchUrl, singleIndex); err != nil {
log.Printf("[WARNING] Failed collapsing single index %s: %s", singleIndex, err)
}
}
// Apply mapping migrations to existing single/keyed indices when the live
// mapping has drifted from opensearchCoreMappings. Skipped when a custom
// OPENSEARCH_INDEX_CONFIG is set (the operator owns those mappings).
if len(customConfig) == 0 {
for _, singleIndex := range singleIndices {
if err := migrateOpensearchSingleIndex(ctx, opensearchUrl, singleIndex); err != nil {
log.Printf("[WARNING] Failed migrating mapping for single index %s: %s", singleIndex, err)
}
}
}
if fixResult, fixErr := FixOpensearchIndexPrefix(ctx); fixErr != nil {
log.Printf("[WARNING] Alias verification after init failed: %s", fixErr)
} else if !fixResult.Success {
log.Printf("[WARNING] Alias verification after init completed with warnings: %s", fixResult.Reason)
} else {
log.Printf("[INFO] Alias verification after init passed: expected aliases=%d found=%d", fixResult.ExpectedAliases, fixResult.FoundAliases)
}
}
// getOpensearchIndexProperties returns the "properties" subtree of an index's live mappings.
func getOpensearchIndexProperties(foundClient opensearchapi.Client, opensearchUrl, indexName string) (map[string]interface{}, error) {
resp, err := foundClient.Indices.Mapping.Get(context.Background(), &opensearchapi.MappingGetReq{Indices: []string{indexName}})
if err != nil {
return nil, fmt.Errorf("failed reading mapping for %s: %w", indexName, err)
}
for _, idx := range resp.Indices {
mappings := map[string]interface{}{}
if len(idx.Mappings) > 0 {
if err := json.Unmarshal(idx.Mappings, &mappings); err != nil {
return nil, err
}
}
props, _ := mappings["properties"].(map[string]interface{})
return props, nil
}
return nil, nil
}
// createOpensearchIndexFromBody creates an index with an explicit create body.
func createOpensearchIndexFromBody(ctx context.Context, opensearchUrl, indexName string, body []byte) error {
if _, err := project.Es.Indices.Create(ctx, opensearchapi.IndicesCreateReq{
Index: indexName,
Body: bytes.NewReader(body),
}); err != nil {
return fmt.Errorf("failed creating index %s: %w", indexName, err)
}
return nil
}
// migrateOpensearchSingleIndex re-creates a single (keyed) index with the
// current core mappings when its live mapping has drifted.
//
// It bulk-copies the existing backing index into a fresh generation (via
// reindexOpensearchIndex's failure-aware async task polling - not a bare
// synchronous call, so a mapping rejection or task-level error, e.g. a batch
// overflowing OpenSearch's 2GB transport limit, aborts the migration instead
// of silently deleting a partially-copied source), then write-blocks the
// source for a final catch-up copy and verifies an exact document count
// match before atomically swapping the alias to the new generation and
// dropping the old one.
//
// Any failure at any step aborts without deleting the source or touching
// the alias, leaving the next automatic retry (this runs idempotently on
// every startup) to pick up from current state.
func migrateOpensearchSingleIndex(ctx context.Context, opensearchUrl, baseIndex string) error {
foundClient := project.Es
allIndices, err := getOpensearchIndices(foundClient, opensearchUrl)
if err != nil {
return err
}
generations := []string{}
for _, idx := range allIndices {
if idx == baseIndex || strings.HasPrefix(idx, baseIndex+"-") {
generations = append(generations, idx)
}
}
if len(generations) == 0 {
return nil
}
sort.Slice(generations, func(i, j int) bool {
return getOpensearchGeneration(generations[i]) > getOpensearchGeneration(generations[j])
})
// collapseSingleIndexAliases runs just before this; if multiple generations
// remain, defer to it rather than racing a partial collapse.
if len(generations) > 1 {
return nil
}
src := generations[0]
actualProps, err := getOpensearchIndexProperties(foundClient, opensearchUrl, src)
if err != nil {
return err
}
if !opensearchMappingsDiffer(baseIndex, actualProps) {
return nil
}
nextGen := getOpensearchGeneration(src) + 1
dest := fmt.Sprintf("%s-%06d", baseIndex, nextGen)
body := map[string]interface{}{
"settings": getOpensearchDefaultIndexSettings(),
"mappings": opensearchMappingsFor(baseIndex),
}
bodyJSON, err := json.Marshal(body)
if err != nil {
return err
}
if err := createOpensearchIndexFromBody(ctx, opensearchUrl, dest, bodyJSON); err != nil {
return err
}
log.Printf("[INFO] Opensearch single-index mapping migration: starting bulk copy %s -> %s", src, dest)
if err := reindexOpensearchIndex(ctx, opensearchUrl, src, dest); err != nil {
return fmt.Errorf("bulk copy: %w", err)
}
// Freeze the source so a final catch-up pass can close any gap opened
// by writes that landed concurrently during the bulk copy above, before
// we trust the document counts to match exactly and delete the source.
//
// This mirrors the same write-block/catch-up/verify pattern used for
// legacy alias-collision migrations (runOpensearchCollisionMigration) -
// without it, a write landing in src during the copy could be silently
// lost the moment src is deleted below.
if err := setOpensearchIndexWriteBlock(foundClient, opensearchUrl, src, true); err != nil {
return fmt.Errorf("write-blocking source before final catch-up: %w", err)
}
if err := reindexOpensearchIndex(ctx, opensearchUrl, src, dest); err != nil {
clearOpensearchIndexWriteBlockBestEffort(foundClient, opensearchUrl, src)
return fmt.Errorf("final write-blocked catch-up copy: %w", err)
}
// _count (like _search) only sees refreshed segments, not documents
// written moments ago - force a refresh on both indices before trusting
// the comparison below, otherwise the tail of the catch-up copy above
// can make destCount look behind even though the copy fully succeeded.
if err := refreshOpensearchIndex(foundClient, opensearchUrl, src); err != nil {
clearOpensearchIndexWriteBlockBestEffort(foundClient, opensearchUrl, src)
return fmt.Errorf("refreshing source before final count check: %w", err)
}
if err := refreshOpensearchIndex(foundClient, opensearchUrl, dest); err != nil {
clearOpensearchIndexWriteBlockBestEffort(foundClient, opensearchUrl, src)
return fmt.Errorf("refreshing target before final count check: %w", err)
}
srcCount, err := getOpensearchIndexCount(foundClient, opensearchUrl, src)
if err != nil {
clearOpensearchIndexWriteBlockBestEffort(foundClient, opensearchUrl, src)
return fmt.Errorf("getting final source count: %w", err)
}
destCount, err := getOpensearchIndexCount(foundClient, opensearchUrl, dest)
if err != nil {
clearOpensearchIndexWriteBlockBestEffort(foundClient, opensearchUrl, src)
return fmt.Errorf("getting final target count: %w", err)
}
if destCount < srcCount {
// Unblock and let the next automatic retry (this function is
// idempotent and reruns on every startup) redo the copy - something
// left the target still behind, and deleting the source with data
// still missing would be permanent data loss.
clearOpensearchIndexWriteBlockBestEffort(foundClient, opensearchUrl, src)
return fmt.Errorf("target count %d still behind source count %d after write-blocked catch-up - not deleting source", destCount, srcCount)
}
// atomically move the write alias from the old generation to the new one
write := true
actions := []OpensearchAliasAction{
{Remove: &OpensearchAliasActionTarget{Index: src, Alias: baseIndex}},
{Add: &OpensearchAliasActionTarget{Index: dest, Alias: baseIndex, IsWriteIndex: &write}},
}
if err := updateOpensearchAliases(foundClient, opensearchUrl, actions); err != nil {
// This request is atomic (OpenSearch applies remove+add as a single
// cluster-state update), so a failure here leaves src still holding
// the baseIndex alias, exactly as before the attempt - unblock it so
// the application can keep writing to it normally. Without this, src
// (the currently-serving index) would stay write-blocked until the
// next backend restart re-runs this idempotent migration, since
// nothing else retries it in between.
clearOpensearchIndexWriteBlockBestEffort(foundClient, opensearchUrl, src)
return err
}
if err := deleteOpensearchIndex(foundClient, opensearchUrl, src); err != nil {
return err
}
log.Printf("[INFO] Migrated mapping for %s: %s -> %s (%d documents verified)", baseIndex, src, dest, destCount)
return nil
}
// ensureOpensearchMappingTemplates registers an index mapping template per
// append/rollover base index so every future rollover generation is created
// with the current core mappings (existing generations are left untouched).
func ensureOpensearchMappingTemplates(ctx context.Context, opensearchUrl string) {
for _, baseIndex := range GetOpensearchRolloverIndices() {
alias := strings.ToLower(GetESIndexPrefix(baseIndex))
body := map[string]interface{}{
"index_patterns": []string{alias + "-*"},
"template": map[string]interface{}{
"mappings": opensearchMappingsFor(baseIndex),
},
"priority": 100,
}
bodyJSON, err := json.Marshal(body)
if err != nil {
log.Printf("[WARNING] Failed building mapping template for %s: %s", alias, err)
continue
}
templateName := fmt.Sprintf("shuffle-%s-mapping", baseIndex)
if _, err := project.Es.IndexTemplate.Create(ctx, opensearchapi.IndexTemplateCreateReq{
IndexTemplate: templateName,
Body: bytes.NewReader(bodyJSON),
}); err != nil {
log.Printf("[WARNING] Failed to register mapping template for %s: %s", alias, err)
continue
}
}
}
// collapseSingleIndexAliases migrates a stateful (non-append) index that may
// have rolled over in previous versions to a single backing index: it
// merges every older generation into the newest (newest document wins per
// _id), drops the older generations, and detaches rollover so the index
// stays single. Safe to run repeatedly.
func collapseSingleIndexAliases(ctx context.Context, opensearchUrl, fullIndex string) error {
foundClient := project.Es
allIndices, err := getOpensearchIndices(foundClient, opensearchUrl)
if err != nil {
return err
}
generations := []string{}
for _, idx := range allIndices {
if idx == fullIndex || strings.HasPrefix(idx, fullIndex+"-") {
generations = append(generations, idx)
}
}
if len(generations) == 1 {
// A single surviving index - just make sure it can't roll over.
return detachOpensearchRollover(ctx, opensearchUrl, generations[0])
}
if len(generations) == 0 {
return nil
}
sort.Slice(generations, func(i, j int) bool {
return getOpensearchGeneration(generations[i]) > getOpensearchGeneration(generations[j])
})
writeGen := generations[0]
olderGens := generations[1:]
// Merge older generations into the newest (the surviving write target).
// reindexOpensearchIndex uses op_type:create, so a source _id that
// already exists in the newest generation is skipped (conflicts=proceed)
// and the newest copy wins; _ids that only live in older generations are
// copied across.
//
// Iteration order does not matter because the destination always wins
// on collision.
for _, older := range olderGens {
if err := reindexOpensearchIndex(ctx, opensearchUrl, older, writeGen); err != nil {
return err
}
}
actions := []OpensearchAliasAction{}
for _, older := range olderGens {
actions = append(actions, OpensearchAliasAction{
Remove: &OpensearchAliasActionTarget{Index: older, Alias: fullIndex},
})
}
if err := updateOpensearchAliases(foundClient, opensearchUrl, actions); err != nil {
return err
}
for _, older := range olderGens {
if err := deleteOpensearchIndex(foundClient, opensearchUrl, older); err != nil {
return err
}
}
return detachOpensearchRollover(ctx, opensearchUrl, writeGen)
}
// reindexOpensearchIndex copies documents from source into dest via
// runOpensearchReindexToCompletion
//
// ctx is accepted for API compatibility with existing callers but the
// underlying poll loop is not currently context-aware.
func reindexOpensearchIndex(ctx context.Context, opensearchUrl, source, dest string) error {
return runOpensearchReindexToCompletion(project.Es, opensearchUrl, source, dest)
}
// detachOpensearchRollover removes the ISM rollover policy and clears the
// rollover_alias index setting so a single (non-append) index never rolls over.
func detachOpensearchRollover(ctx context.Context, opensearchUrl, indexName string) error {
// Remove the ISM rollover policy, if any. Missing policy / missing plugin
// (4xx) is fine - clearing the rollover_alias setting below is what truly
// stops rollover.
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("%s/_plugins/_ism/remove/%s", opensearchUrl, indexName), strings.NewReader("{}"))
if err == nil {
req.Header.Set("Content-Type", "application/json")
if removeResp, performErr := project.Es.Client.Transport.Perform(req); performErr == nil {
_ = removeResp.Body.Close()
}
}
settingsBody := map[string]interface{}{
"index": map[string]interface{}{
"plugins.index_state_management.rollover_alias": nil,
},
}
bodyData, marshalErr := json.Marshal(settingsBody)
if marshalErr != nil {
return marshalErr
}
if _, err := project.Es.Indices.Settings.Put(ctx, opensearchapi.SettingsPutReq{
Indices: []string{indexName},
Body: bytes.NewReader(bodyData),
}); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "index_not_found_exception") {
return nil
}
return fmt.Errorf("clear rollover_alias on %s failed: %w", indexName, err)
}
return nil
}
// getOpensearchISMRolloverConditions parses the "conditions" object from a
// custom OPENSEARCH_INDEX_ROLLOVER JSON payload (accepting both ISM's native
// min_* keys and the more intuitive max_* aliases), falling back to
// Shuffle's defaults (90d / 40gb / 1,000,000 docs) for any condition not
// set, or if rolloverConfig is empty/invalid.
func getOpensearchISMRolloverConditions(rolloverConfig []byte) map[string]interface{} {
defaultConditions := map[string]interface{}{
"min_index_age": opensearchDefaultRolloverMaxAge,
"min_size": opensearchDefaultRolloverMaxSize,
"min_doc_count": opensearchDefaultRolloverMaxDocs,
}
parsed := struct {
Conditions map[string]interface{} `json:"conditions"`
}{}
if err := json.Unmarshal(rolloverConfig, &parsed); err != nil {
return defaultConditions
}
if len(parsed.Conditions) == 0 {
return defaultConditions
}
conditions := map[string]interface{}{}
if value, ok := parsed.Conditions["min_index_age"]; ok {
conditions["min_index_age"] = value
} else if value, ok := parsed.Conditions["max_age"]; ok {
conditions["min_index_age"] = value
}
if value, ok := parsed.Conditions["min_size"]; ok {
conditions["min_size"] = value
} else if value, ok := parsed.Conditions["max_size"]; ok {
conditions["min_size"] = value
}
if value, ok := parsed.Conditions["min_doc_count"]; ok {
conditions["min_doc_count"] = value
} else if value, ok := parsed.Conditions["max_docs"]; ok {
conditions["min_doc_count"] = value
}
if len(conditions) == 0 {
return defaultConditions
}
return conditions
}
// getOpensearchRetentionDays returns how long rolled-over generations of
// baseIndex should be kept before ISM deletes them (e.g. "90d"), preferring
// a per-index override from OPENSEARCH_INDEX_RETENTION_DAYS (a JSON map) over
// Shuffle's built-in defaults. Returns "" (no retention/keep forever) for any
// base index without a default and without an override.
func getOpensearchRetentionDays(baseIndex string) string {
defaults := map[string]string{
"shuffle_logs": "90d",
"workflowexecution": "365d",
}
value := defaults[baseIndex]
if value == "" {
return ""
}
custom := strings.TrimSpace(os.Getenv("OPENSEARCH_INDEX_RETENTION_DAYS"))
if custom == "" {
return value
}
parsed := map[string]interface{}{}
if err := json.Unmarshal([]byte(custom), &parsed); err != nil {
log.Printf("[WARNING] Invalid JSON in OPENSEARCH_INDEX_RETENTION_DAYS: %s", err)
return value
}
raw, ok := parsed[baseIndex]
if !ok {
return value
}
if days, ok := raw.(float64); ok {
return fmt.Sprintf("%dd", int(days))
}
if str, ok := raw.(string); ok {
return str
}
return value
}
// existingOpensearchISMPolicy holds the parts of a GET
// /_plugins/_ism/policies/<id> response needed to decide whether the policy
// needs updating, and (if so) to perform a conflict-safe PUT.
type existingOpensearchISMPolicy struct {
SeqNo int64 `json:"_seq_no"`
PrimaryTerm int64 `json:"_primary_term"`
RawConditions map[string]interface{} // hot state's rollover conditions
RawRetention string // delete transition's min_index_age, if any
}
// getExistingOpensearchISMPolicy fetches the current ISM policy document for
// policyID, if any, and extracts just the "hot" state's rollover conditions
// and delete-transition retention age (plus the _seq_no/_primary_term
// needed for a conflict-safe PUT). Returns (nil, false, nil) if the policy
// doesn't exist yet, and a distinct "ism plugin not available" error if the
// ISM plugin itself isn't installed on the cluster.
func getExistingOpensearchISMPolicy(ctx context.Context, opensearchUrl, policyID string) (*existingOpensearchISMPolicy, bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/_plugins/_ism/policies/%s", opensearchUrl, policyID), nil)
if err != nil {
return nil, false, err
}
resp, err := project.Es.Client.Transport.Perform(req)
if err != nil {
return nil, false, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode >= 300 {
if resp.StatusCode == 404 || resp.StatusCode == 400 {
if strings.Contains(strings.ToLower(string(body)), "_plugins/_ism") || strings.Contains(strings.ToLower(string(body)), "no handler found") {
// ISM plugin isn't installed at all.
return nil, false, fmt.Errorf("ism plugin not available")
}
}
if resp.StatusCode == 404 {
// Genuinely doesn't exist yet - needs to be created.
return nil, false, nil
}
return nil, false, fmt.Errorf("status: %d, body: %s", resp.StatusCode, string(body))
}
parsed := struct {
SeqNo int64 `json:"_seq_no"`
PrimaryTerm int64 `json:"_primary_term"`
Policy struct {
States []struct {
Name string `json:"name"`
Actions []struct {
Rollover map[string]interface{} `json:"rollover"`
} `json:"actions"`
Transitions []struct {
Conditions struct {
MinIndexAge string `json:"min_index_age"`
} `json:"conditions"`
} `json:"transitions"`
} `json:"states"`
} `json:"policy"`
}{}
if err := json.Unmarshal(body, &parsed); err != nil {
return nil, false, err
}
existing := &existingOpensearchISMPolicy{
SeqNo: parsed.SeqNo,
PrimaryTerm: parsed.PrimaryTerm,
}
for _, state := range parsed.Policy.States {
if state.Name != "hot" {
continue
}
if len(state.Actions) > 0 {
existing.RawConditions = state.Actions[0].Rollover
}
if len(state.Transitions) > 0 {
existing.RawRetention = state.Transitions[0].Conditions.MinIndexAge
}
}
return existing, true, nil
}
// ensureOpensearchISMRolloverPolicy creates (or updates, if its rollover
// conditions or retention no longer match) the ISM policy that rolls over
// and eventually deletes generations of alias. Returns (true, nil) if a
// usable policy is in place, or (false, nil) - not an error - if the ISM
// plugin isn't installed, so callers can fall back to direct shard rollover.
func ensureOpensearchISMRolloverPolicy(ctx context.Context, opensearchUrl, alias string, rolloverConfig []byte, retentionAge, policyName string) (bool, error) {
conditions := getOpensearchISMRolloverConditions(rolloverConfig)
policyID := fmt.Sprintf("%s-%s", policyName, alias)
states := []map[string]interface{}{
{
"name": "hot",
"actions": []map[string]interface{}{{"rollover": conditions}},
"transitions": []interface{}{},
},
}
if retentionAge != "" {
states[0]["transitions"] = []map[string]interface{}{
{
"state_name": "delete",
"conditions": map[string]interface{}{"min_index_age": retentionAge},
},
}
states = append(states, map[string]interface{}{
"name": "delete",
"actions": []map[string]interface{}{{"delete": map[string]interface{}{}}},
"transitions": []interface{}{},
})
}
policyBody := map[string]interface{}{
"policy": map[string]interface{}{
"description": "Shuffle rollover + retention policy",
"default_state": "hot",
"states": states,
"ism_template": []map[string]interface{}{
{
"index_patterns": []string{fmt.Sprintf("%s-*", alias)},
"priority": 100,
},
},
},
}
policyData, err := json.Marshal(policyBody)
if err != nil {
return false, err
}
// Check whether the policy already exists, and if so, whether its
// rollover conditions/retention already match what we'd write - this
// lets us both (a) avoid a needless PUT (and its 409) when nothing
// changed, and (b) actually apply changes to OPENSEARCH_INDEX_ROLLOVER /
// OPENSEARCH_INDEX_RETENTION_DAYS on restart when something did change,
// which a blind "create-only" PUT can never do once the policy exists.
existing, found, err := getExistingOpensearchISMPolicy(ctx, opensearchUrl, policyID)
if err != nil {
if err.Error() == "ism plugin not available" {
log.Printf("[INFO] ISM plugin not available. Falling back to direct rollover")
return false, nil
}
return false, err
}
putUrl := fmt.Sprintf("%s/_plugins/_ism/policies/%s", opensearchUrl, policyID)
if found {
// Compare only the specific rollover condition keys Shuffle manages,
// not a full deep-equal of the stored object: OpenSearch enriches
// the stored rollover conditions with its own extra fields we never
// set (e.g. "copy_alias": false), so a full-map compare would never
// match and would cause a needless PUT (and misleading "changed -
// updating" log) on every single restart.
//
// %v formatting sidesteps int (our defaults) vs float64 (values
// decoded from OpenSearch's JSON response) type mismatches on
// otherwise-equal numbers.
conditionsMatch := true
for _, key := range []string{"min_index_age", "min_size", "min_doc_count"} {
if fmt.Sprintf("%v", existing.RawConditions[key]) != fmt.Sprintf("%v", conditions[key]) {
conditionsMatch = false
break
}
}
retentionMatches := existing.RawRetention == retentionAge
if conditionsMatch && retentionMatches {
log.Printf("[DEBUG] ISM rollover policy '%s' already up to date for alias %s - skipping", policyID, alias)
return true, nil
}
log.Printf("[INFO] ISM rollover policy '%s' conditions/retention changed for alias %s - updating", policyID, alias)
putUrl = fmt.Sprintf("%s?if_seq_no=%d&if_primary_term=%d", putUrl, existing.SeqNo, existing.PrimaryTerm)
}
req, err := http.NewRequestWithContext(ctx, "PUT", putUrl, bytes.NewReader(policyData))
if err != nil {
return false, err
}
req.Header.Set("Content-Type", "application/json")