Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions adapter/admin_grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,7 @@ var adminMethodPrefix = "/" + pb.Admin_ServiceDesc.ServiceName + "/"
// must present the same token.
func adminTokenProtectedMethod(fullMethod string) bool {
return strings.HasPrefix(fullMethod, adminMethodPrefix) ||
strings.HasPrefix(fullMethod, "/"+pb.LegacyRedisFenceGC_ServiceDesc.ServiceName+"/") ||
fullMethod == pb.Internal_ForwardAdminProposal_FullMethodName ||
fullMethod == pb.Internal_GetPrepareEvidenceState_FullMethodName ||
fullMethod == pb.Internal_ForwardLeaseRead_FullMethodName
Expand Down
3 changes: 3 additions & 0 deletions adapter/admin_grpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1017,6 +1017,9 @@ func TestAdminTokenAuthProtectsInternalAdminMethods(t *testing.T) {
methods := []string{
pb.Internal_ForwardAdminProposal_FullMethodName,
pb.Internal_ForwardLeaseRead_FullMethodName,
pb.LegacyRedisFenceGC_Inspect_FullMethodName,
pb.LegacyRedisFenceGC_Apply_FullMethodName,
pb.LegacyRedisFenceGC_Progress_FullMethodName,
}
for _, method := range methods {
t.Run(method, func(t *testing.T) {
Expand Down
187 changes: 187 additions & 0 deletions cmd/elastickv-legacy-fence-gc/input.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package main

import (
"bufio"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"math"
"os"
"strings"

"github.com/bootjp/elastickv/store"
"github.com/cockroachdb/errors"
)

const maxMetadataBytes = 64 << 10
const maxCandidateLineBytes = 2*store.MaxLegacyRedisFenceKeyBytes + 2

type captureManifest struct {
Snapshot string `json:"snapshot"`
Count uint64 `json:"candidate_count"`
SHA string `json:"hex_manifest_sha256"`
}

type checkpoint struct {
Cursor, Deleted, Protected, Updated, Absent uint64
CandidateSHA string `json:"candidate_sha256,omitempty"`
}

type writerEvidence struct {
Snapshot string `json:"snapshot"`
CandidateSHA string `json:"candidate_sha256"`
LegacyRedisWriterOnly bool `json:"legacy_redis_writer_only"`
Source string `json:"source"`
}

type inputs struct {
captureManifest
checkpoint
checkpointSHA, writerSHA string
}

func loadInputs(opts options) (inputs, error) {
manifest, err := loadCandidateManifest(opts.manifest)
in := inputs{captureManifest: manifest}
if err != nil {
return in, err
}
data, err := readSmallFile(opts.checkpoint)
if err != nil {
return in, err
}
in.Cursor = math.MaxUint64
if err := json.Unmarshal(data, &in.checkpoint); err != nil {
return in, errors.Wrap(err, "decode old checkpoint")
}
in.checkpointSHA = hexDigest(data)
if err := in.validateCheckpoint(opts.captureSnapshot); err != nil {
return in, err
}
if opts.writerEvidence != "" {
in.writerSHA, err = loadWriterEvidence(opts.writerEvidence, manifest)
}
return in, err
}

func loadCandidateManifest(path string) (captureManifest, error) {
var result captureManifest
data, err := readSmallFile(path)
if err != nil {
return result, err
}
if err := json.Unmarshal(data, &result); err != nil {
return result, errors.Wrap(err, "decode candidate manifest")
}
digest, err := hex.DecodeString(result.SHA)
if err != nil || len(digest) != sha256.Size || result.Snapshot == "" {
return result, errors.New("candidate manifest needs a SHA-256 and source snapshot name")
}
result.SHA = hex.EncodeToString(digest)
return result, nil
}

func loadWriterEvidence(path string, manifest captureManifest) (string, error) {
data, err := readSmallFile(path)
if err != nil {
return "", err
}
var evidence writerEvidence
if err := json.Unmarshal(data, &evidence); err != nil {
return "", errors.Wrap(err, "decode legacy writer evidence")
}
if evidence.Snapshot != manifest.Snapshot || evidence.CandidateSHA != manifest.SHA ||
!evidence.LegacyRedisWriterOnly || strings.TrimSpace(evidence.Source) == "" {
return "", errors.New("writer evidence does not establish Redis ownership for the captured candidate list")
}
return hexDigest(data), nil
}

func (in inputs) validateCheckpoint(snapshot string) error {
if in.Cursor > in.Count || in.CandidateSHA != "" && in.CandidateSHA != in.SHA {
return errors.New("checkpoint cursor or candidate hash does not match manifest")
}
remaining := in.Cursor
for _, count := range [...]uint64{in.Deleted, in.Protected, in.Updated, in.Absent} {
if count > remaining {
return errors.New("checkpoint counts exceed cursor")
}
remaining -= count
}
if remaining != 0 {
return errors.New("checkpoint counts do not account for the cursor")
}
if snapshot != "" && snapshot != in.Snapshot {
return errors.New("capture DB snapshot name does not match candidate manifest")
}
return nil
}

func hexDigest(data []byte) string {
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])
}

func readSmallFile(path string) (_ []byte, err error) {
file, err := os.Open(path)
if err != nil {
return nil, errors.WithStack(err)
}
defer func() { err = errors.Join(err, file.Close()) }()
data, err := io.ReadAll(io.LimitReader(file, maxMetadataBytes+1))
if err != nil {
return nil, errors.WithStack(err)
}
if len(data) == 0 || len(data) > maxMetadataBytes {
return nil, errors.Errorf("metadata file %q is empty or exceeds size limit", path)
}
return data, nil
}

func scanCandidates(ctx context.Context, path string, input inputs, visit func(uint64, []byte) error) (err error) {
file, err := os.Open(path)
if err != nil {
return errors.WithStack(err)
}
defer func() { err = errors.Join(err, file.Close()) }()
data, err := gzip.NewReader(file)
if err != nil {
return errors.WithStack(err)
}
defer func() { err = errors.Join(err, data.Close()) }()
sum := sha256.New()
reader := bufio.NewReaderSize(io.TeeReader(data, sum), maxCandidateLineBytes)
count, err := scanCandidateLines(ctx, reader, visit)
if err != nil {
return err
}
if count != input.Count || hex.EncodeToString(sum.Sum(nil)) != input.SHA {
return errors.New("candidate count or expanded SHA-256 does not match manifest")
}
return nil
}

func scanCandidateLines(ctx context.Context, reader *bufio.Reader, visit func(uint64, []byte) error) (uint64, error) {
var count uint64
for {
if err := ctx.Err(); err != nil {
return count, errors.WithStack(err)
}
line, err := reader.ReadSlice('\n')
if errors.Is(err, io.EOF) && len(line) == 0 {
return count, nil
}
if err != nil {
return count, errors.Wrapf(err, "read candidate line %d", count+1)
}
count++
if visit != nil {
if err := visit(count, line[:len(line)-1]); err != nil {
return count, err
}
}
}
}
164 changes: 164 additions & 0 deletions cmd/elastickv-legacy-fence-gc/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Command elastickv-legacy-fence-gc retires captured legacy Redis OCC fences.
package main

import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"os/signal"
"syscall"

"github.com/bootjp/elastickv/store"
"github.com/cockroachdb/errors"
)

const defaultRate = 16
const maxRate = 1024

type options struct {
addresses, token, ca, serverName string
candidates, manifest, checkpoint string
capture, captureSnapshot, writerEvidence string
plan, planSHA string
group, limit, maxBatches uint64
rate int
apply, plaintext bool
}

func main() {
os.Exit(runCLI())
}

func runCLI() int {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
err := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
if err == nil || errors.Is(err, flag.ErrHelp) {
return 0
}
fmt.Fprintf(os.Stderr, "elastickv-legacy-fence-gc: %v\n", err)
return 1
}

func run(ctx context.Context, args []string, stdout, stderr io.Writer) error {
opts, err := parseFlags(args, stderr)
if err != nil {
return err
}
input, err := loadInputs(opts)
if err != nil {
return err
}
client, err := openClients(opts)
if err != nil {
return err
}
defer client.close()
var result summary
if opts.apply {
result, err = applyPlan(ctx, client, opts, input)
} else {
result, err = dryRun(ctx, client, opts, input)
}
if err != nil {
return err
}
return errors.WithStack(json.NewEncoder(stdout).Encode(result))
}

func parseFlags(args []string, out io.Writer) (options, error) {
var opts options
fs := flag.NewFlagSet("elastickv-legacy-fence-gc", flag.ContinueOnError)
fs.SetOutput(out)
fs.StringVar(&opts.addresses, "endpoints", "", "Comma-separated admin host:port addresses for this Raft group")
fs.StringVar(&opts.token, "admin-token-file", "", "File containing the admin bearer token")
fs.StringVar(&opts.ca, "tls-ca", "", "PEM file with additional TLS roots")
fs.StringVar(&opts.serverName, "tls-server-name", "", "TLS certificate name override")
fs.BoolVar(&opts.plaintext, "plaintext-loopback", false, "Use plaintext only to literal loopback addresses")
fs.StringVar(&opts.candidates, "candidates", "", "Existing gzip file with one hex key per line")
fs.StringVar(&opts.manifest, "manifest", "", "Existing dry-run.json recording capture snapshot and candidate SHA-256")
fs.StringVar(&opts.checkpoint, "checkpoint", "", "Existing checkpoint.json from this candidate list")
fs.StringVar(&opts.capture, "capture-db", "", "Read-only local copy of the capture-time fsm.db")
fs.StringVar(&opts.captureSnapshot, "capture-snapshot", "", "Source snapshot name of --capture-db")
fs.StringVar(&opts.writerEvidence, "writer-evidence", "", "Reviewed record establishing Redis ownership of the legacy namespace at capture")
fs.StringVar(&opts.plan, "plan", "", "New dry-run output plan, or existing reviewed plan with --apply")
fs.StringVar(&opts.planSHA, "plan-sha256", "", "Reviewed plan SHA-256 from the dry run")
fs.Uint64Var(&opts.group, "group", 0, "Single Raft data-group ID")
fs.Uint64Var(&opts.limit, "limit", 0, "Maximum input rows to examine in this dry run (0 means all remaining)")
fs.Uint64Var(&opts.maxBatches, "max-batches", 0, "Maximum plan batches to apply in this invocation (0 means all remaining)")
fs.IntVar(&opts.rate, "rate", defaultRate, "Candidate rate per second, including retained rows in dry run")
fs.BoolVar(&opts.apply, "apply", false, "Explicitly apply a previously reviewed plan")
if err := fs.Parse(args); err != nil {
return opts, errors.WithStack(err)
}
if fs.NArg() != 0 {
return opts, errors.New("unexpected positional arguments")
}
return opts, opts.validate()
}

func (o options) validate() error {
for _, required := range []string{o.addresses, o.token, o.candidates, o.checkpoint, o.manifest} {
if required == "" {
return errors.New("endpoints, admin token file, candidates, manifest and checkpoint are required")
}
}
if o.group == 0 || o.rate < 1 || o.rate > maxRate {
return errors.New("group and a candidate rate within bounds are required")
}
if o.apply {
return o.validateApply()
}
if o.maxBatches != 0 || o.planSHA != "" || (o.capture == "") != (o.captureSnapshot == "") {
return errors.New("supply both capture DB and snapshot name; --max-batches and --plan-sha256 are apply options")
}
return nil
}

func (o options) validateApply() error {
if o.plan == "" || o.planSHA == "" || o.limit != 0 || o.capture != "" || o.captureSnapshot != "" {
return errors.New("--apply requires a reviewed plan and digest; capture and --limit are dry-run options")
}
return nil
}

type summary struct {
Mode string `json:"mode"`
CandidateSHA256 string `json:"candidate_sha256"`
CheckpointSHA string `json:"checkpoint_sha256"`
Checkpoint uint64 `json:"checkpoint_cursor"`
Remaining uint64 `json:"remaining_input"`
PlanSHA string `json:"plan_sha256,omitempty"`
CaptureIndex uint64 `json:"capture_applied_index,omitempty"`
CaptureThrough uint64 `json:"capture_through,omitempty"`
Examined uint64 `json:"examined"`
Eligible uint64 `json:"eligible"`
Protected uint64 `json:"protected"`
Updated uint64 `json:"updated"`
Absent uint64 `json:"absent"`
Unknown uint64 `json:"unknown"`
Acknowledged uint64 `json:"acknowledged"`
Retired uint64 `json:"retired"`
SkippedAtApply uint64 `json:"skipped_at_apply"`
}

func (s *summary) observe(verdict store.LegacyRedisFenceVerdict) {
s.Examined++
switch verdict {
case store.LegacyRedisFenceUnknown:
s.Unknown++
case store.LegacyRedisFenceEligible:
s.Eligible++
case store.LegacyRedisFenceProtected:
s.Protected++
case store.LegacyRedisFenceUpdated:
s.Updated++
case store.LegacyRedisFenceAbsent:
s.Absent++
default:
s.Unknown++
}
}
Loading
Loading