mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b89d7e36bf | ||
|
|
b067266e6b | ||
|
|
b3a58506aa | ||
|
|
b42993d24a | ||
|
|
fd4603d657 | ||
|
|
53377bcb5d | ||
|
|
1167ca8cf5 | ||
|
|
512f898600 | ||
|
|
858f8cbad8 | ||
|
|
c819e3fbea | ||
|
|
6ad4b07598 | ||
|
|
65ecb6aa12 | ||
|
|
0a38738076 | ||
|
|
10f8b2d5b1 |
No files matched your search
@@ -271,6 +271,10 @@ curl "http://localhost:9333/vol/vacuum?garbageThreshold=0.4"
|
||||
Vacuuming makes a volume read-only, copies live needles to a new volume, and
|
||||
swaps it in.
|
||||
|
||||
The master runs one vacuum at a time. A request that arrives while the
|
||||
automatic vacuum or another request is running does nothing and gets
|
||||
`409 Conflict` with `{"error":"another vacuum is running, try again later"}`.
|
||||
|
||||
### Delete a collection
|
||||
|
||||
```bash
|
||||
|
||||
+9
-19
@@ -157,19 +157,16 @@ worker_asset_name() {
|
||||
echo "weed-worker_${os}_${arch}.tar.gz"
|
||||
}
|
||||
|
||||
# The vector engine behind the S3 Vectors API, built like the worker.
|
||||
# The vector engine behind the S3 Vectors API, published for linux only like
|
||||
# the worker.
|
||||
vector_asset_name() {
|
||||
local os="$1" arch="$2"
|
||||
if [ "$os" = "windows" ]; then
|
||||
echo "weed-vector_${os}_${arch}.zip"
|
||||
else
|
||||
echo "weed-vector_${os}_${arch}.tar.gz"
|
||||
fi
|
||||
echo "weed-vector_${os}_${arch}.tar.gz"
|
||||
}
|
||||
|
||||
vector_platform_supported() {
|
||||
case "$1/$2" in
|
||||
linux/amd64|linux/arm64|darwin/amd64|darwin/arm64|windows/amd64) return 0 ;;
|
||||
linux/amd64|linux/arm64) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
@@ -283,26 +280,19 @@ install_component() {
|
||||
;;
|
||||
|
||||
vector)
|
||||
vector_platform_supported "$os" "$arch" || error "The vector engine is not available for ${os}/${arch}"
|
||||
vector_platform_supported "$os" "$arch" || error "The vector engine is not available for ${os}/${arch}. Supported: linux/amd64, linux/arm64"
|
||||
|
||||
asset_name="$(vector_asset_name "$os" "$arch")"
|
||||
download_url="https://github.com/${REPO}/releases/download/${VERSION}/${asset_name}"
|
||||
download "$download_url" "${tmpdir}/${asset_name}"
|
||||
|
||||
info "Extracting ${asset_name}..."
|
||||
local vector_name="weed-vector"
|
||||
if [ "$os" = "windows" ]; then
|
||||
command -v unzip >/dev/null || error "unzip is required for Windows vector archives"
|
||||
unzip -q "${tmpdir}/${asset_name}" -d "$tmpdir"
|
||||
vector_name="weed-vector.exe"
|
||||
else
|
||||
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
|
||||
fi
|
||||
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
|
||||
local vector_bin
|
||||
vector_bin="$(find "$tmpdir" -name "$vector_name" -type f | head -1)"
|
||||
[ -n "$vector_bin" ] || error "Could not find $vector_name binary in archive"
|
||||
vector_bin="$(find "$tmpdir" -name weed-vector -type f | head -1)"
|
||||
[ -n "$vector_bin" ] || error "Could not find weed-vector binary in archive"
|
||||
chmod +x "$vector_bin"
|
||||
install_binary "$vector_bin" "$vector_name"
|
||||
install_binary "$vector_bin" weed-vector
|
||||
VECTOR_INSTALLED=true
|
||||
ok "Installed weed-vector to ${INSTALL_DIR}/weed-vector"
|
||||
;;
|
||||
|
||||
@@ -10263,6 +10263,102 @@
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Time Since Last Full Lifecycle Pass",
|
||||
"description": "Time since a pass covered every shard and lifecycle policy without an error; never excluded",
|
||||
"type": "timeseries",
|
||||
"id": 261,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 51
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "s",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "time() - max(SeaweedFS_s3_lifecycle_daily_run_last_full_pass_timestamp_seconds{cluster=~\"$cluster\"} > 0)",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "last full pass"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -44,12 +44,22 @@ func vacuumVolumes(t *testing.T) {
|
||||
require.NotEmpty(t, defaultConfig.MasterEndpoint, "vacuum needs a master endpoint; set MASTER_ENDPOINT")
|
||||
endpoint := strings.TrimRight(defaultConfig.MasterEndpoint, "/") + "/vol/vacuum?garbageThreshold=0.001"
|
||||
httpClient := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := httpClient.Get(endpoint)
|
||||
require.NoError(t, err, "vacuum request to %s", endpoint)
|
||||
defer resp.Body.Close()
|
||||
_, err = io.Copy(io.Discard, resp.Body)
|
||||
require.NoError(t, err, "reading the vacuum response")
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "vacuum request to %s", endpoint)
|
||||
// The master runs one vacuum at a time and answers 409 to a request it
|
||||
// dropped because its automatic vacuum was running. Ask until ours runs.
|
||||
deadline := time.Now().Add(time.Minute)
|
||||
for {
|
||||
resp, err := httpClient.Get(endpoint)
|
||||
require.NoError(t, err, "vacuum request to %s", endpoint)
|
||||
_, err = io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
require.NoError(t, err, "reading the vacuum response")
|
||||
if resp.StatusCode == http.StatusConflict && time.Now().Before(deadline) {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "vacuum request to %s", endpoint)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func requireVersionBody(t *testing.T, client *s3.Client, bucketName, objectKey, versionId string, want []byte, msg string) {
|
||||
|
||||
@@ -983,11 +983,21 @@ func TestTusAbortedPatchKeepsStoredChunks(t *testing.T) {
|
||||
require.Equal(t, http.StatusNoContent, patchResp.StatusCode)
|
||||
|
||||
// A vacuum reclaims whatever the filer deleted, so the file survives this
|
||||
// only if the chunks the session kept are still stored.
|
||||
vacuumResp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%s/vol/vacuum?garbageThreshold=0.001", testMasterPort))
|
||||
require.NoError(t, err)
|
||||
vacuumResp.Body.Close()
|
||||
require.Equal(t, http.StatusOK, vacuumResp.StatusCode)
|
||||
// only if the chunks the session kept are still stored. The master answers
|
||||
// 409 to a request it dropped because its automatic vacuum was running, so
|
||||
// ask until ours runs.
|
||||
vacuumDeadline := time.Now().Add(time.Minute)
|
||||
for {
|
||||
vacuumResp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%s/vol/vacuum?garbageThreshold=0.001", testMasterPort))
|
||||
require.NoError(t, err)
|
||||
vacuumResp.Body.Close()
|
||||
if vacuumResp.StatusCode == http.StatusConflict && time.Now().Before(vacuumDeadline) {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
require.Equal(t, http.StatusOK, vacuumResp.StatusCode)
|
||||
break
|
||||
}
|
||||
|
||||
getResp, err := client.Get(cluster.FilerURL() + targetPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -1120,13 +1120,15 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr
|
||||
if completed.RequestId != "" {
|
||||
tracked.RequestID = completed.RequestId
|
||||
}
|
||||
if completed.Result != nil {
|
||||
tracked.ResultSummary = completed.Result.Summary
|
||||
} else {
|
||||
tracked.ResultSummary = ""
|
||||
}
|
||||
if completed.Success {
|
||||
tracked.State = strings.ToLower(plugin_pb.JobState_JOB_STATE_SUCCEEDED.String())
|
||||
tracked.Progress = 100
|
||||
tracked.Stage = "completed"
|
||||
if completed.Result != nil {
|
||||
tracked.ResultSummary = completed.Result.Summary
|
||||
}
|
||||
tracked.Message = tracked.ResultSummary
|
||||
if tracked.Message == "" {
|
||||
tracked.Message = "completed"
|
||||
@@ -1159,7 +1161,7 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr
|
||||
detail.Message = clone.Message
|
||||
detail.ErrorMessage = clone.ErrorMessage
|
||||
detail.ResultSummary = clone.ResultSummary
|
||||
if completed.Success && completed.Result != nil {
|
||||
if completed.Result != nil {
|
||||
detail.ResultOutputValues = configValueMapToPlain(completed.Result.OutputValues)
|
||||
} else {
|
||||
detail.ResultOutputValues = nil
|
||||
|
||||
@@ -594,6 +594,95 @@ func TestBuildJobDetailIncludesActivitiesAndRunRecord(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildJobDetailKeepsFailedJobResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pluginSvc, err := New(Options{DataDir: t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
pluginSvc.trackExecutionStart("req-failed", "worker-f", &plugin_pb.JobSpec{
|
||||
JobId: "job-failed",
|
||||
JobType: "s3_lifecycle",
|
||||
}, 1)
|
||||
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
|
||||
RequestId: "req-failed",
|
||||
JobId: "job-failed",
|
||||
JobType: "s3_lifecycle",
|
||||
Success: false,
|
||||
ErrorMessage: "walk bad-a: filer down",
|
||||
Result: &plugin_pb.JobResult{
|
||||
Summary: "pass failed",
|
||||
OutputValues: map[string]*plugin_pb.ConfigValue{
|
||||
"buckets_failed": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 2}},
|
||||
},
|
||||
},
|
||||
CompletedAt: timestamppb.Now(),
|
||||
})
|
||||
pluginSvc.Shutdown()
|
||||
|
||||
detail, found, err := pluginSvc.BuildJobDetail("job-failed", 100, 5)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildJobDetail error: %v", err)
|
||||
}
|
||||
if !found || detail == nil || detail.Job == nil {
|
||||
t.Fatalf("expected job detail")
|
||||
}
|
||||
if detail.Job.State != "job_state_failed" || detail.Job.ErrorMessage != "walk bad-a: filer down" {
|
||||
t.Fatalf("expected the failure to be kept, got state=%q error=%q", detail.Job.State, detail.Job.ErrorMessage)
|
||||
}
|
||||
if detail.Job.ResultSummary != "pass failed" {
|
||||
t.Fatalf("expected the failed job's result summary, got %q", detail.Job.ResultSummary)
|
||||
}
|
||||
if detail.Job.ResultOutputValues["buckets_failed"] == nil {
|
||||
t.Fatalf("expected the failed job's result output values, got %+v", detail.Job.ResultOutputValues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryWithoutResultDropsFailedAttemptSummary(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pluginSvc, err := New(Options{DataDir: t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
job := &plugin_pb.JobSpec{JobId: "job-retry", JobType: "s3_lifecycle"}
|
||||
pluginSvc.trackExecutionStart("req-retry", "worker-r", job, 1)
|
||||
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
|
||||
RequestId: "req-retry",
|
||||
JobId: "job-retry",
|
||||
JobType: "s3_lifecycle",
|
||||
Success: false,
|
||||
ErrorMessage: "walk bad-a: filer down",
|
||||
Result: &plugin_pb.JobResult{Summary: "pass failed"},
|
||||
CompletedAt: timestamppb.Now(),
|
||||
})
|
||||
pluginSvc.trackExecutionStart("req-retry", "worker-r", job, 2)
|
||||
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
|
||||
RequestId: "req-retry",
|
||||
JobId: "job-retry",
|
||||
JobType: "s3_lifecycle",
|
||||
Success: true,
|
||||
CompletedAt: timestamppb.Now(),
|
||||
})
|
||||
pluginSvc.Shutdown()
|
||||
|
||||
detail, found, err := pluginSvc.BuildJobDetail("job-retry", 100, 5)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildJobDetail error: %v", err)
|
||||
}
|
||||
if !found || detail == nil || detail.Job == nil {
|
||||
t.Fatalf("expected job detail")
|
||||
}
|
||||
if detail.Job.ResultSummary != "" || detail.Job.Message != "completed" {
|
||||
t.Fatalf("expected the failed attempt's summary to be dropped, got summary=%q message=%q", detail.Job.ResultSummary, detail.Job.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildJobDetailLoadsFromDiskWhenMemoryCleared(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -704,6 +793,64 @@ func TestExpireStaleJobsCancelsTheJobOnItsWorker(t *testing.T) {
|
||||
expectCancelFor(t, session, "req-stale")
|
||||
}
|
||||
|
||||
// A job older than the stale limit stays active while its worker reports
|
||||
// progress for it; the worker's heartbeat alone does not keep it alive.
|
||||
func TestExpireStaleJobsKeepsAJobThatReportsProgress(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pluginSvc, err := New(Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
const workerID = "worker-1"
|
||||
session := &streamSession{workerID: workerID, outgoing: make(chan *plugin_pb.AdminToWorkerMessage, 8), done: make(chan struct{})}
|
||||
pluginSvc.putSession(session)
|
||||
pluginSvc.handleWorkerMessage(session, &plugin_pb.WorkerToAdminMessage{
|
||||
Body: &plugin_pb.WorkerToAdminMessage_Hello{Hello: &plugin_pb.WorkerHello{WorkerId: workerID}},
|
||||
})
|
||||
pluginSvc.trackExecutionStart("req-working", workerID, &plugin_pb.JobSpec{JobId: "job-working", JobType: "s3_lifecycle"}, 1)
|
||||
pluginSvc.trackExecutionStart("req-stalled", workerID, &plugin_pb.JobSpec{JobId: "job-stalled", JobType: "s3_lifecycle"}, 1)
|
||||
|
||||
startedAt := time.Now().UTC().Add(-defaultStaleActiveJobTimeout - time.Hour)
|
||||
pluginSvc.jobsMu.Lock()
|
||||
for _, job := range pluginSvc.jobs {
|
||||
job.CreatedAt = timeToPtr(startedAt)
|
||||
job.UpdatedAt = timeToPtr(startedAt)
|
||||
}
|
||||
pluginSvc.jobsMu.Unlock()
|
||||
|
||||
pluginSvc.handleWorkerMessage(session, &plugin_pb.WorkerToAdminMessage{
|
||||
Body: &plugin_pb.WorkerToAdminMessage_Heartbeat{Heartbeat: &plugin_pb.WorkerHeartbeat{
|
||||
WorkerId: workerID,
|
||||
ExecutionSlotsTotal: 4,
|
||||
ExecutionSlotsUsed: 2,
|
||||
RunningWork: []*plugin_pb.RunningWork{
|
||||
{WorkId: "job-working", Kind: plugin_pb.WorkKind_WORK_KIND_EXECUTION, JobType: "s3_lifecycle"},
|
||||
{WorkId: "job-stalled", Kind: plugin_pb.WorkKind_WORK_KIND_EXECUTION, JobType: "s3_lifecycle"},
|
||||
},
|
||||
}},
|
||||
})
|
||||
pluginSvc.handleWorkerMessage(session, &plugin_pb.WorkerToAdminMessage{
|
||||
Body: &plugin_pb.WorkerToAdminMessage_JobProgressUpdate{JobProgressUpdate: &plugin_pb.JobProgressUpdate{
|
||||
JobId: "job-working", JobType: "s3_lifecycle", RequestId: "req-working",
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "walk", Message: "entries=10",
|
||||
}},
|
||||
})
|
||||
|
||||
if n := pluginSvc.expireStaleJobs(time.Now().UTC()); n != 1 {
|
||||
t.Fatalf("expired %d jobs, want only the stalled one", n)
|
||||
}
|
||||
if got, _ := pluginSvc.GetTrackedJob("job-working"); got == nil || got.State != "job_state_running" {
|
||||
t.Fatalf("expected the job reporting progress to stay running, got %+v", got)
|
||||
}
|
||||
if got, _ := pluginSvc.GetTrackedJob("job-stalled"); got == nil || got.State != StateFailed {
|
||||
t.Fatalf("expected the heartbeat-only job to be failed, got %+v", got)
|
||||
}
|
||||
expectCancelFor(t, session, "req-stalled")
|
||||
}
|
||||
|
||||
func expectNoCancel(t *testing.T, session *streamSession) {
|
||||
t.Helper()
|
||||
select {
|
||||
|
||||
@@ -428,6 +428,7 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context,
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
stoppedEarly := false
|
||||
for rows.Next() {
|
||||
var name string
|
||||
var data []byte
|
||||
@@ -452,10 +453,20 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context,
|
||||
}
|
||||
|
||||
if !resEachEntryFunc {
|
||||
stoppedEarly = true
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
// rows.Next also returns false when the result set fails partway, for
|
||||
// example on a lost connection; that must not read as the end of the
|
||||
// directory. A listing the callback stopped on purpose has no such error
|
||||
// to report (rows.Err would return a canceled context's error instead).
|
||||
if err == nil && !stoppedEarly {
|
||||
if rowsErr := rows.Err(); rowsErr != nil {
|
||||
err = fmt.Errorf("list %s: %w", dirPath, rowsErr)
|
||||
}
|
||||
}
|
||||
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
@@ -2,10 +2,13 @@ package abstract_sql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -140,3 +143,74 @@ func TestBucketHooksSkipInvalidBucketNames(t *testing.T) {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
type listGen struct{ SqlGenerator }
|
||||
|
||||
func (listGen) GetSqlListExclusive(string) string { return "SELECT name, meta" }
|
||||
func (listGen) GetSqlListInclusive(string) string { return "SELECT name, meta" }
|
||||
|
||||
// A listing that loses its connection partway through must report the error,
|
||||
// not return the rows read so far as if the directory ended there.
|
||||
func TestListDirectoryEntriesReportsRowIterationError(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
meta, err := (&filer.Entry{}).EncodeAttributesAndChunks()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
connLost := errors.New("connection reset by peer")
|
||||
mock.ExpectQuery("SELECT name, meta").WillReturnRows(
|
||||
sqlmock.NewRows([]string{"name", "meta"}).
|
||||
AddRow("a.txt", meta).
|
||||
AddRow("b.txt", meta).
|
||||
RowError(1, connLost))
|
||||
|
||||
store := &AbstractSqlStore{SqlGenerator: listGen{}, DB: db}
|
||||
var listed []string
|
||||
_, err = store.ListDirectoryEntries(context.Background(), "/dir", "", true, 100, func(entry *filer.Entry) (bool, error) {
|
||||
listed = append(listed, entry.Name())
|
||||
return true, nil
|
||||
})
|
||||
if !errors.Is(err, connLost) {
|
||||
t.Fatalf("ListDirectoryEntries error = %v, want %v (listed %v)", err, connLost, listed)
|
||||
}
|
||||
}
|
||||
|
||||
// A listing the callback stops on purpose is not a failure, even if the
|
||||
// request context is canceled before the rows are closed.
|
||||
func TestListDirectoryEntriesStoppedByCallbackWithCanceledContext(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
meta, err := (&filer.Entry{}).EncodeAttributesAndChunks()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mock.ExpectQuery("SELECT name, meta").WillReturnRows(
|
||||
sqlmock.NewRows([]string{"name", "meta"}).AddRow("a.txt", meta).AddRow("b.txt", meta))
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store := &AbstractSqlStore{SqlGenerator: listGen{}, DB: db}
|
||||
_, err = store.ListDirectoryEntries(ctx, "/dir", "", true, 100, func(entry *filer.Entry) (bool, error) {
|
||||
cancel()
|
||||
// database/sql closes the rows on a background goroutine; once the
|
||||
// connection is back in the pool, rows.Err reports the cancellation.
|
||||
for deadline := time.Now().Add(5 * time.Second); db.Stats().InUse > 0; time.Sleep(time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the canceled listing still holds its connection")
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ListDirectoryEntries error = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
@@ -204,9 +204,10 @@ func (f *Filer) LocalFlushedThroughTsNs(nowNs int64) int64 {
|
||||
}
|
||||
|
||||
// LocalDeliveredThroughTsNs caps a delivery-freshness claim (an idle
|
||||
// heartbeat's timestamp) by the oldest in-flight stamp: a stamped-but-
|
||||
// unappended event has not been streamed to anyone, and a peer aggregator
|
||||
// turns the claim into its delivery low-watermark.
|
||||
// heartbeat's timestamp, a listing snapshot) by the oldest in-flight stamp: a
|
||||
// stamped-but-unappended event has not been streamed to anyone, nor is its
|
||||
// write certain to be visible yet, and a peer aggregator turns the claim into
|
||||
// its delivery low-watermark.
|
||||
func (f *Filer) LocalDeliveredThroughTsNs(nowNs int64) int64 {
|
||||
return f.metaLogInflight.claimThrough(nowNs)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import (
|
||||
type contentPublication struct {
|
||||
refused bool
|
||||
failure *atomic.Bool
|
||||
// writes is the handle's pageWrites before its pages were flushed. A
|
||||
// later write is not in the published chunks, so it keeps the handle dirty.
|
||||
writes uint64
|
||||
}
|
||||
|
||||
func (p *contentPublication) retire(err error) {
|
||||
|
||||
@@ -58,6 +58,9 @@ type FileHandle struct {
|
||||
// could not be read; the next flush reads it before publishing.
|
||||
linkRefresh []byte
|
||||
|
||||
// pageWrites counts the pages added to dirtyPages, under the handle lock.
|
||||
pageWrites atomic.Uint64
|
||||
|
||||
// entryVersionTsNs is the filer log position the handle's entry reflects.
|
||||
// State at or below it must not replace the entry — that rolls it back.
|
||||
entryVersionTsNs atomic.Int64
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//go:build !freebsd
|
||||
|
||||
package mount
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// A FLUSH from another fd of the open file uploads its pages, then a WRITE
|
||||
// lands before it commits. The commit carries the new size but not the
|
||||
// write's chunk, so the next flush must still publish that chunk.
|
||||
func TestFlushRacingWriteKeepsHandleDirty(t *testing.T) {
|
||||
base := attributeAppendEntry(1)
|
||||
base.CommitTsNs = 100
|
||||
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
|
||||
w, handle := g6AppendHandle(t, peer, base, 100)
|
||||
fh := w.GetHandle(FileHandleId(handle))
|
||||
write := func(offset uint64, value byte) {
|
||||
t.Helper()
|
||||
n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: offset, Size: 256}, bytes.Repeat([]byte{value}, 256))
|
||||
if n != 256 || code != fuse.OK {
|
||||
t.Fatalf("write at %d: %d %v", offset, n, code)
|
||||
}
|
||||
}
|
||||
flush := func() fuse.Status {
|
||||
return w.Flush(nil, &fuse.FlushIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle})
|
||||
}
|
||||
|
||||
uploading, resume := make(chan struct{}), make(chan struct{})
|
||||
upload := fh.dirtyPages.randomWriter.(*ChunkedDirtyPages).saveDataAsChunk
|
||||
first := true
|
||||
fh.dirtyPages.randomWriter.(*ChunkedDirtyPages).saveDataAsChunk = func(p util.FullPath) filer.SaveDataAsChunkFunctionType {
|
||||
save := upload(p)
|
||||
return func(r io.Reader, name string, offset, ts int64, ttl uint64) (*filer_pb.FileChunk, error) {
|
||||
if first {
|
||||
first = false
|
||||
close(uploading)
|
||||
<-resume
|
||||
}
|
||||
return save(r, name, offset, ts, ttl)
|
||||
}
|
||||
}
|
||||
|
||||
write(256, 'A')
|
||||
racing := make(chan fuse.Status, 1)
|
||||
go func() { racing <- flush() }()
|
||||
<-uploading
|
||||
write(512, 'B')
|
||||
close(resume)
|
||||
if code := <-racing; code != fuse.OK {
|
||||
t.Fatalf("racing flush: %v", code)
|
||||
}
|
||||
if code := flush(); code != fuse.OK {
|
||||
t.Fatalf("owner flush: %v", code)
|
||||
}
|
||||
|
||||
peer.mu.Lock()
|
||||
defer peer.mu.Unlock()
|
||||
want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...)
|
||||
want = append(want, bytes.Repeat([]byte{'B'}, 256)...)
|
||||
if got := g6StoredBytes(t, peer); !bytes.Equal(got, want) {
|
||||
t.Fatalf("stored size %d chunks %v: the racing write's bytes were not published", peer.entry.Attributes.FileSize, peer.entry.Chunks)
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ func NewActivityScore() *ActivityScore {
|
||||
func (as *ActivityScore) MarkRead() {
|
||||
now := time.Now().UnixNano()
|
||||
last := atomic.SwapInt64(&as.lastActiveTsNs, now)
|
||||
deltaTime := (now - last) >> 30 // about number of seconds
|
||||
// Concurrent timestamp swaps or a clock adjustment can make last newer than now.
|
||||
deltaTime := max(0, min(63, (now-last)>>30)) // about number of seconds
|
||||
for {
|
||||
old := atomic.LoadInt64(&as.decayedActivenessScore)
|
||||
score := old>>deltaTime + 256
|
||||
@@ -33,7 +34,7 @@ func (as *ActivityScore) MarkRead() {
|
||||
func (as *ActivityScore) MarkWrite() {
|
||||
now := time.Now().UnixNano()
|
||||
last := atomic.SwapInt64(&as.lastActiveTsNs, now)
|
||||
deltaTime := (now - last) >> 30 // about number of seconds
|
||||
deltaTime := max(0, min(63, (now-last)>>30)) // about number of seconds
|
||||
for {
|
||||
old := atomic.LoadInt64(&as.decayedActivenessScore)
|
||||
score := old>>deltaTime + 1024
|
||||
@@ -47,6 +48,6 @@ func (as *ActivityScore) MarkWrite() {
|
||||
}
|
||||
|
||||
func (as *ActivityScore) ActivityScore() int64 {
|
||||
deltaTime := (time.Now().UnixNano() - atomic.LoadInt64(&as.lastActiveTsNs)) >> 30
|
||||
deltaTime := max(0, min(63, (time.Now().UnixNano()-atomic.LoadInt64(&as.lastActiveTsNs))>>30))
|
||||
return atomic.LoadInt64(&as.decayedActivenessScore) >> deltaTime
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package page_writer
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestActivityScoreHandlesFutureTimestamp(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
call func(*ActivityScore) int64
|
||||
want int64
|
||||
}{
|
||||
{"MarkRead", func(score *ActivityScore) int64 {
|
||||
score.MarkRead()
|
||||
return score.ActivityScore()
|
||||
}, 4352},
|
||||
{"MarkWrite", func(score *ActivityScore) int64 {
|
||||
score.MarkWrite()
|
||||
return score.ActivityScore()
|
||||
}, 5120},
|
||||
{"ActivityScore", (*ActivityScore).ActivityScore, 4096},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
score := NewActivityScore()
|
||||
atomic.StoreInt64(&score.lastActiveTsNs, time.Now().Add(time.Hour).UnixNano())
|
||||
atomic.StoreInt64(&score.decayedActivenessScore, 4096)
|
||||
defer func() {
|
||||
if caught := recover(); caught != nil {
|
||||
t.Fatalf("future last-active timestamp must not panic: %v", caught)
|
||||
}
|
||||
}()
|
||||
if got := test.call(score); got != test.want {
|
||||
t.Fatalf("score=%d, want %d without backwards-time decay", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ func isFilerUnreachable(err error) bool {
|
||||
// nothing else holds these references: like the writeback chunk uploads, it
|
||||
// keeps retrying for as long as the filer is unreachable.
|
||||
func (wfs *WFS) flushMetadataWithRetry(fh *FileHandle, dir, name string, fileFullPath util.FullPath) error {
|
||||
publication := &contentPublication{failure: fh.writebackContentError}
|
||||
publication := &contentPublication{failure: fh.writebackContentError, writes: fh.pageWrites.Load()}
|
||||
attempts := 0
|
||||
err := retryMetadataFlushUntil(context.Background(), func() error {
|
||||
attempts++
|
||||
@@ -155,7 +155,9 @@ func (wfs *WFS) flushMetadataWithRetry(fh *FileHandle, dir, name string, fileFul
|
||||
fileFullPath, nextAttempt, totalAttempts, backoff, err)
|
||||
})
|
||||
if err != nil {
|
||||
publication.abandon()
|
||||
if fh.dirtyContent {
|
||||
publication.abandon()
|
||||
}
|
||||
glog.Errorf("completeAsyncFlush %s: metadata flush failed after %d attempts: %v - "+
|
||||
"chunks are uploaded but NOT referenced in filer metadata; "+
|
||||
"they will appear as orphans in volume.fsck",
|
||||
|
||||
@@ -89,37 +89,43 @@ func TestAbandonedWritebackFlushFencesInode(t *testing.T) {
|
||||
})
|
||||
metadataFlushSleep = func(ctx context.Context, d time.Duration) {}
|
||||
|
||||
const name = "abandoned-writeback.log"
|
||||
wfs, _ := newCreateTestWFS(t)
|
||||
fake := &rejectingCreateFiler{rejections: 1 << 20, refuse: func(req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
return nil, status.Error(codes.PermissionDenied, "denied")
|
||||
}}
|
||||
startFakeFiler(t, wfs, fake)
|
||||
for _, content := range []bool{true, false} {
|
||||
const name = "abandoned-writeback.log"
|
||||
wfs, _ := newCreateTestWFS(t)
|
||||
fake := &rejectingCreateFiler{rejections: 1 << 20, refuse: func(req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
return nil, status.Error(codes.PermissionDenied, "denied")
|
||||
}}
|
||||
startFakeFiler(t, wfs, fake)
|
||||
|
||||
out := &fuse.CreateOut{}
|
||||
if code := wfs.Create(make(chan struct{}), &fuse.CreateIn{
|
||||
InHeader: fuse.InHeader{NodeId: 1},
|
||||
Flags: syscall.O_WRONLY | syscall.O_CREAT,
|
||||
Mode: 0o644,
|
||||
}, name, out); code != fuse.OK {
|
||||
t.Fatalf("Create status = %v, want OK", code)
|
||||
}
|
||||
fh := wfs.GetHandle(FileHandleId(out.Fh))
|
||||
if fh == nil {
|
||||
t.Fatal("Create did not register an open file handle")
|
||||
}
|
||||
wfs.option.WritebackCache = true
|
||||
fh.writebackContentError = new(atomic.Bool)
|
||||
fh.dirtyMetadata = true
|
||||
out := &fuse.CreateOut{}
|
||||
if code := wfs.Create(make(chan struct{}), &fuse.CreateIn{
|
||||
InHeader: fuse.InHeader{NodeId: 1},
|
||||
Flags: syscall.O_WRONLY | syscall.O_CREAT,
|
||||
Mode: 0o644,
|
||||
}, name, out); code != fuse.OK {
|
||||
t.Fatalf("Create status = %v, want OK", code)
|
||||
}
|
||||
fh := wfs.GetHandle(FileHandleId(out.Fh))
|
||||
if fh == nil {
|
||||
t.Fatal("Create did not register an open file handle")
|
||||
}
|
||||
wfs.option.WritebackCache = true
|
||||
fh.writebackContentError = new(atomic.Bool)
|
||||
fh.dirtyMetadata = true
|
||||
fh.dirtyContent = content
|
||||
|
||||
if err := wfs.flushMetadataWithRetry(fh, "/", name, util.FullPath("/").Child(name)); err == nil {
|
||||
t.Fatal("flush against a refusing filer succeeded")
|
||||
}
|
||||
if !fh.writebackContentError.Load() {
|
||||
t.Fatal("abandoned writeback flush left the inode unfenced")
|
||||
}
|
||||
if err := wfs.checkContentPublication(fh, nil); !errors.Is(err, filer_pb.ErrPreconditionFailed) {
|
||||
t.Fatalf("checkContentPublication after abandonment = %v, want a precondition refusal", err)
|
||||
if err := wfs.flushMetadataWithRetry(fh, "/", name, util.FullPath("/").Child(name)); err == nil {
|
||||
t.Fatal("flush against a refusing filer succeeded")
|
||||
}
|
||||
if got := fh.writebackContentError.Load(); got != content {
|
||||
t.Fatalf("content=%v: fenced after abandoned writeback flush = %v, want %v", content, got, content)
|
||||
}
|
||||
if !content {
|
||||
continue
|
||||
}
|
||||
if err := wfs.checkContentPublication(fh, nil); !errors.Is(err, filer_pb.ErrPreconditionFailed) {
|
||||
t.Fatalf("checkContentPublication after abandonment = %v, want a precondition refusal", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,10 +139,12 @@ func TestFailedFlockReleaseFencesInode(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
content bool
|
||||
truncate bool
|
||||
wantFenced bool
|
||||
}{
|
||||
{"content", true, true},
|
||||
{"metadata only", false, false},
|
||||
{"content", true, false, true},
|
||||
{"metadata only", false, false, false},
|
||||
{"truncate", false, true, true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
const name = "flock-release.log"
|
||||
@@ -164,6 +172,16 @@ func TestFailedFlockReleaseFencesInode(t *testing.T) {
|
||||
fh.writebackContentError = fenced
|
||||
fh.dirtyMetadata = true
|
||||
fh.dirtyContent = c.content
|
||||
if c.truncate {
|
||||
if code := wfs.SetAttr(make(chan struct{}), &fuse.SetAttrIn{SetAttrInCommon: fuse.SetAttrInCommon{
|
||||
InHeader: fuse.InHeader{NodeId: out.NodeId},
|
||||
Valid: fuse.FATTR_SIZE | fuse.FATTR_FH,
|
||||
Fh: out.Fh,
|
||||
Size: 64,
|
||||
}}, &fuse.AttrOut{}); code != fuse.OK {
|
||||
t.Fatalf("SetAttr size = %v, want OK", code)
|
||||
}
|
||||
}
|
||||
|
||||
wfs.Release(make(chan struct{}), &fuse.ReleaseIn{
|
||||
InHeader: fuse.InHeader{NodeId: out.NodeId},
|
||||
|
||||
@@ -191,6 +191,9 @@ func (wfs *WFS) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse
|
||||
|
||||
if fh != nil {
|
||||
fh.dirtyMetadata = true
|
||||
if includeSize {
|
||||
fh.dirtyContent = true
|
||||
}
|
||||
return fuse.OK
|
||||
}
|
||||
if path == "" {
|
||||
|
||||
@@ -188,9 +188,11 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
|
||||
glog.Errorf("AddPage error: %v", err)
|
||||
return 0, writeErrorToFuseStatus(err)
|
||||
}
|
||||
fhOut.pageWrites.Add(1)
|
||||
|
||||
// Accumulate for the next loop iteration
|
||||
totalCopied += numBytesRead
|
||||
fhOut.dirtyContent = true
|
||||
}
|
||||
|
||||
if totalCopied == 0 {
|
||||
@@ -203,13 +205,16 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
|
||||
))
|
||||
fhOut.entry.Content = nil
|
||||
fhOut.dirtyMetadata = true
|
||||
fhOut.dirtyContent = true
|
||||
|
||||
written = uint32(totalCopied)
|
||||
return written, fuse.OK
|
||||
}
|
||||
|
||||
func (wfs *WFS) tryServerSideWholeFileCopy(cancel <-chan struct{}, in *fuse.CopyFileRangeIn, fhIn, fhOut *FileHandle) (written uint32, handled bool, code fuse.Status) {
|
||||
if err := wfs.checkContentPublication(fhOut, nil); err != nil {
|
||||
glog.V(4).Infof("server-side copy: skipped (%v)", err)
|
||||
return 0, false, fuse.OK
|
||||
}
|
||||
copyRequest, ok := wholeFileServerCopyCandidate(fhIn, fhOut, in)
|
||||
if !ok {
|
||||
return 0, false, fuse.OK
|
||||
@@ -318,8 +323,8 @@ func wholeFileServerCopyCandidate(fhIn, fhOut *FileHandle, in *fuse.CopyFileRang
|
||||
glog.V(4).Infof("server-side copy: skipped (same file handle)")
|
||||
return wholeFileServerCopyRequest{}, false
|
||||
}
|
||||
if fhIn.dirtyMetadata || fhOut.dirtyMetadata {
|
||||
glog.V(4).Infof("server-side copy: skipped (dirty metadata: in=%v out=%v)", fhIn.dirtyMetadata, fhOut.dirtyMetadata)
|
||||
if fhIn.dirtyMetadata || fhIn.dirtyContent || fhOut.dirtyMetadata || fhOut.dirtyContent {
|
||||
glog.V(4).Infof("server-side copy: skipped (dirty handle: in=%v/%v out=%v/%v)", fhIn.dirtyMetadata, fhIn.dirtyContent, fhOut.dirtyMetadata, fhOut.dirtyContent)
|
||||
return wholeFileServerCopyRequest{}, false
|
||||
}
|
||||
if in.OffIn != 0 || in.OffOut != 0 {
|
||||
|
||||
@@ -72,6 +72,14 @@ func TestWholeFileServerCopyCandidate(t *testing.T) {
|
||||
}
|
||||
srcHandle.dirtyMetadata = false
|
||||
|
||||
for _, h := range []*FileHandle{srcHandle, dstHandle} {
|
||||
h.dirtyContent = true
|
||||
if _, ok := wholeFileServerCopyCandidate(srcHandle, dstHandle, in); ok {
|
||||
t.Fatal("handle with unpublished content should disable whole-file server copy")
|
||||
}
|
||||
h.dirtyContent = false
|
||||
}
|
||||
|
||||
in.Len = 4
|
||||
if _, ok := wholeFileServerCopyCandidate(srcHandle, dstHandle, in); ok {
|
||||
t.Fatal("short copy request should disable whole-file server copy")
|
||||
@@ -355,3 +363,81 @@ func newCopyRangeTestWFSWithMetaCache(t *testing.T) *WFS {
|
||||
|
||||
return wfs
|
||||
}
|
||||
|
||||
func TestStreamingCopyMarksOnlyAcceptedContentDirty(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
addFails bool
|
||||
wantOK bool
|
||||
wantDirty bool
|
||||
}{
|
||||
{"accepted", false, true, true},
|
||||
{"rejected first page", true, false, false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
wfs := newCopyRangeTestWFS()
|
||||
srcInode := wfs.inodeToPath.Lookup(util.FullPath("/src.txt"), 1, false, false, 0, true)
|
||||
dstInode := wfs.inodeToPath.Lookup(util.FullPath("/dst.txt"), 1, false, false, 0, true)
|
||||
srcHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
Name: "src.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 5, Inode: srcInode},
|
||||
Content: []byte("hello"),
|
||||
}, 0, 0)
|
||||
dstHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
Name: "dst.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: dstInode},
|
||||
}, 0, 0)
|
||||
if c.addFails {
|
||||
dstHandle.dirtyPages.randomWriter.(*ChunkedDirtyPages).setLastError(errors.New("swap file unavailable"))
|
||||
}
|
||||
|
||||
_, status := wfs.CopyFileRange(make(chan struct{}), &fuse.CopyFileRangeIn{
|
||||
FhIn: uint64(srcHandle.fh),
|
||||
FhOut: uint64(dstHandle.fh),
|
||||
OffIn: 1,
|
||||
OffOut: 0,
|
||||
Len: 4,
|
||||
})
|
||||
if (status == fuse.OK) != c.wantOK {
|
||||
t.Fatalf("CopyFileRange status = %v, want OK = %v", status, c.wantOK)
|
||||
}
|
||||
if dstHandle.dirtyContent != c.wantDirty {
|
||||
t.Fatalf("dirtyContent = %v, want %v", dstHandle.dirtyContent, c.wantDirty)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerSideCopySkipsFencedDestination(t *testing.T) {
|
||||
wfs := newCopyRangeTestWFS()
|
||||
wfs.option.WritebackCache = true
|
||||
srcInode := wfs.inodeToPath.Lookup(util.FullPath("/src.txt"), 1, false, false, 0, true)
|
||||
dstInode := wfs.inodeToPath.Lookup(util.FullPath("/dst.txt"), 1, false, false, 0, true)
|
||||
srcHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
Name: "src.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 5, Inode: srcInode},
|
||||
Content: []byte("hello"),
|
||||
}, 0, 0)
|
||||
dstHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
Name: "dst.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: dstInode},
|
||||
}, 0, 0)
|
||||
srcHandle.RememberPath("/src.txt")
|
||||
dstHandle.RememberPath("/dst.txt")
|
||||
dstHandle.writebackContentError.Store(true)
|
||||
|
||||
originalCopy := performServerSideWholeFileCopy
|
||||
t.Cleanup(func() { performServerSideWholeFileCopy = originalCopy })
|
||||
performServerSideWholeFileCopy = func(<-chan struct{}, *WFS, wholeFileServerCopyRequest) (*filer_pb.Entry, entryVersion, serverSideWholeFileCopyOutcome, error) {
|
||||
t.Fatal("fenced destination must not publish through the filer copy")
|
||||
return nil, entryVersion{}, serverSideWholeFileCopyCommitted, nil
|
||||
}
|
||||
|
||||
if _, handled, _ := wfs.tryServerSideWholeFileCopy(make(chan struct{}), &fuse.CopyFileRangeIn{
|
||||
FhIn: uint64(srcHandle.fh),
|
||||
FhOut: uint64(dstHandle.fh),
|
||||
Len: 8,
|
||||
}, srcHandle, dstHandle); handled {
|
||||
t.Fatal("fenced destination should fall back to the streaming copy")
|
||||
}
|
||||
}
|
||||
@@ -191,6 +191,7 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
|
||||
|
||||
// Synchronous flush path (normal mode, fsync, or no dirty data)
|
||||
fh.asyncFlushPending = false
|
||||
publication := &contentPublication{failure: fh.writebackContentError, writes: fh.pageWrites.Load()}
|
||||
|
||||
// Check quota including uncommitted writes for real-time enforcement
|
||||
isOverQuota := wfs.IsOverQuotaWithUncommitted()
|
||||
@@ -222,7 +223,6 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
|
||||
commit = &commitBudget{left: metadataTimeout}
|
||||
}
|
||||
|
||||
publication := &contentPublication{failure: fh.writebackContentError}
|
||||
if err := retryMetadataFlushIf(ctx, func() error {
|
||||
return wfs.flushMetadataToFiler(ctx, fh, dir, name, uid, gid, commit, publication)
|
||||
}, func(err error) bool {
|
||||
@@ -231,7 +231,9 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
|
||||
glog.Warningf("%v fh %d flush: retrying metadata flush (attempt %d/%d) after %v: %v",
|
||||
fileFullPath, fh.fh, nextAttempt, totalAttempts, backoff, err)
|
||||
}); err != nil {
|
||||
publication.retire(err)
|
||||
if fh.dirtyContent {
|
||||
publication.retire(err)
|
||||
}
|
||||
glog.Errorf("%v fh %d flush: %v", fileFullPath, fh.fh, err)
|
||||
return grpcErrorToFuseStatus(err)
|
||||
}
|
||||
@@ -253,7 +255,7 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
|
||||
// commit bounds the filer calls made here, over all attempts of one flush; nil
|
||||
// leaves them to the per-call filer timeouts.
|
||||
func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, name string, uid, gid uint32, commit *commitBudget, publications ...*contentPublication) error {
|
||||
publication := &contentPublication{}
|
||||
publication := &contentPublication{writes: fh.pageWrites.Load()}
|
||||
if len(publications) > 0 {
|
||||
publication = publications[0]
|
||||
}
|
||||
@@ -389,7 +391,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
|
||||
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(dir))
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
if err == nil && fh.pageWrites.Load() == publication.writes {
|
||||
fh.pendingAppend = false
|
||||
fh.dirtyMetadata = false
|
||||
fh.dirtyContent = false
|
||||
|
||||
@@ -102,6 +102,7 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
|
||||
glog.Errorf("AddPage error: %v", err)
|
||||
return 0, writeErrorToFuseStatus(err)
|
||||
}
|
||||
fh.pageWrites.Add(1)
|
||||
|
||||
written = uint32(len(data))
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@ enum ActionKind {
|
||||
// to the appropriate internal helper.
|
||||
service SeaweedS3LifecycleInternal {
|
||||
rpc LifecycleDelete(LifecycleDeleteRequest) returns (LifecycleDeleteResponse);
|
||||
// LifecycleReady runs LifecycleDelete's authorization and nothing else,
|
||||
// so a worker can check a front before it starts a pass.
|
||||
rpc LifecycleReady(LifecycleReadyRequest) returns (LifecycleReadyResponse);
|
||||
}
|
||||
|
||||
// LifecycleDeleteOutcome captures every per-event verdict the worker needs.
|
||||
@@ -93,6 +96,10 @@ message LifecycleDeleteResponse {
|
||||
string reason = 2;
|
||||
}
|
||||
|
||||
message LifecycleReadyRequest {}
|
||||
|
||||
message LifecycleReadyResponse {}
|
||||
|
||||
// MessagePosition mirrors weed/util/log_buffer.MessagePosition for durable
|
||||
// storage. ts_ns + offset uniquely identifies a position within a per-filer
|
||||
// log buffer; per-shard cursors (see ReaderState) use this shape to skip past
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v6.33.4
|
||||
// protoc v3.21.12
|
||||
// source: s3_lifecycle.proto
|
||||
|
||||
package s3_lifecycle_pb
|
||||
@@ -270,7 +270,7 @@ func (x LifecycleState_RuleMode) Number() protoreflect.EnumNumber {
|
||||
|
||||
// Deprecated: Use LifecycleState_RuleMode.Descriptor instead.
|
||||
func (LifecycleState_RuleMode) EnumDescriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5, 0}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7, 0}
|
||||
}
|
||||
|
||||
// DEGRADED_REASON_UNSPECIFIED replaces the old NONE sentinel: an unset
|
||||
@@ -334,7 +334,7 @@ func (x LifecycleState_DegradedReason) Number() protoreflect.EnumNumber {
|
||||
|
||||
// Deprecated: Use LifecycleState_DegradedReason.Descriptor instead.
|
||||
func (LifecycleState_DegradedReason) EnumDescriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5, 1}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7, 1}
|
||||
}
|
||||
|
||||
type LifecycleDeleteRequest struct {
|
||||
@@ -524,6 +524,78 @@ func (x *LifecycleDeleteResponse) GetReason() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
type LifecycleReadyRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LifecycleReadyRequest) Reset() {
|
||||
*x = LifecycleReadyRequest{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LifecycleReadyRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LifecycleReadyRequest) ProtoMessage() {}
|
||||
|
||||
func (x *LifecycleReadyRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LifecycleReadyRequest.ProtoReflect.Descriptor instead.
|
||||
func (*LifecycleReadyRequest) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
type LifecycleReadyResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LifecycleReadyResponse) Reset() {
|
||||
*x = LifecycleReadyResponse{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LifecycleReadyResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LifecycleReadyResponse) ProtoMessage() {}
|
||||
|
||||
func (x *LifecycleReadyResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LifecycleReadyResponse.ProtoReflect.Descriptor instead.
|
||||
func (*LifecycleReadyResponse) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
// MessagePosition mirrors weed/util/log_buffer.MessagePosition for durable
|
||||
// storage. ts_ns + offset uniquely identifies a position within a per-filer
|
||||
// log buffer; per-shard cursors (see ReaderState) use this shape to skip past
|
||||
@@ -538,7 +610,7 @@ type MessagePosition struct {
|
||||
|
||||
func (x *MessagePosition) Reset() {
|
||||
*x = MessagePosition{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[2]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[4]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -550,7 +622,7 @@ func (x *MessagePosition) String() string {
|
||||
func (*MessagePosition) ProtoMessage() {}
|
||||
|
||||
func (x *MessagePosition) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[2]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[4]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -563,7 +635,7 @@ func (x *MessagePosition) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use MessagePosition.ProtoReflect.Descriptor instead.
|
||||
func (*MessagePosition) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{2}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{4}
|
||||
}
|
||||
|
||||
func (x *MessagePosition) GetTsNs() int64 {
|
||||
@@ -593,7 +665,7 @@ type FilerShardCursor struct {
|
||||
|
||||
func (x *FilerShardCursor) Reset() {
|
||||
*x = FilerShardCursor{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[3]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[5]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -605,7 +677,7 @@ func (x *FilerShardCursor) String() string {
|
||||
func (*FilerShardCursor) ProtoMessage() {}
|
||||
|
||||
func (x *FilerShardCursor) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[3]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[5]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -618,7 +690,7 @@ func (x *FilerShardCursor) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use FilerShardCursor.ProtoReflect.Descriptor instead.
|
||||
func (*FilerShardCursor) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{3}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5}
|
||||
}
|
||||
|
||||
func (x *FilerShardCursor) GetFilerId() string {
|
||||
@@ -650,7 +722,7 @@ type EntryIdentity struct {
|
||||
|
||||
func (x *EntryIdentity) Reset() {
|
||||
*x = EntryIdentity{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[4]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[6]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -662,7 +734,7 @@ func (x *EntryIdentity) String() string {
|
||||
func (*EntryIdentity) ProtoMessage() {}
|
||||
|
||||
func (x *EntryIdentity) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[4]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[6]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -675,7 +747,7 @@ func (x *EntryIdentity) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use EntryIdentity.ProtoReflect.Descriptor instead.
|
||||
func (*EntryIdentity) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{4}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{6}
|
||||
}
|
||||
|
||||
func (x *EntryIdentity) GetMtimeNs() int64 {
|
||||
@@ -730,15 +802,15 @@ type LifecycleState struct {
|
||||
LastSafetyScanTsNs int64 `protobuf:"varint,10,opt,name=last_safety_scan_ts_ns,json=lastSafetyScanTsNs,proto3" json:"last_safety_scan_ts_ns,omitempty"`
|
||||
NextSafetyScanTsNs int64 `protobuf:"varint,11,opt,name=next_safety_scan_ts_ns,json=nextSafetyScanTsNs,proto3" json:"next_safety_scan_ts_ns,omitempty"`
|
||||
// Counters for observability; no behavior depends on these.
|
||||
// - evaluated_total: live entries the worker considered for this action
|
||||
// (filter-matched + due-checked); includes objects that ended up not
|
||||
// yet eligible.
|
||||
// - expired_total: successful DONE outcomes (object/version/marker/MPU
|
||||
// removed) under this action.
|
||||
// - metadata_only_total: subset of expired_total where the worker
|
||||
// short-circuited via volume-TTL routing (chunks left to volume GC).
|
||||
// - error_total: outcomes that did NOT advance the cursor under this
|
||||
// action (RETRY_LATER, BLOCKED, FATAL_EVENT_ERROR).
|
||||
// - evaluated_total: live entries the worker considered for this action
|
||||
// (filter-matched + due-checked); includes objects that ended up not
|
||||
// yet eligible.
|
||||
// - expired_total: successful DONE outcomes (object/version/marker/MPU
|
||||
// removed) under this action.
|
||||
// - metadata_only_total: subset of expired_total where the worker
|
||||
// short-circuited via volume-TTL routing (chunks left to volume GC).
|
||||
// - error_total: outcomes that did NOT advance the cursor under this
|
||||
// action (RETRY_LATER, BLOCKED, FATAL_EVENT_ERROR).
|
||||
EvaluatedTotal int64 `protobuf:"varint,12,opt,name=evaluated_total,json=evaluatedTotal,proto3" json:"evaluated_total,omitempty"`
|
||||
ExpiredTotal int64 `protobuf:"varint,13,opt,name=expired_total,json=expiredTotal,proto3" json:"expired_total,omitempty"`
|
||||
MetadataOnlyTotal int64 `protobuf:"varint,14,opt,name=metadata_only_total,json=metadataOnlyTotal,proto3" json:"metadata_only_total,omitempty"`
|
||||
@@ -749,7 +821,7 @@ type LifecycleState struct {
|
||||
|
||||
func (x *LifecycleState) Reset() {
|
||||
*x = LifecycleState{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[5]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[7]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -761,7 +833,7 @@ func (x *LifecycleState) String() string {
|
||||
func (*LifecycleState) ProtoMessage() {}
|
||||
|
||||
func (x *LifecycleState) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[5]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[7]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -774,7 +846,7 @@ func (x *LifecycleState) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use LifecycleState.ProtoReflect.Descriptor instead.
|
||||
func (*LifecycleState) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7}
|
||||
}
|
||||
|
||||
func (x *LifecycleState) GetRuleHash() []byte {
|
||||
@@ -897,7 +969,7 @@ type PendingItem struct {
|
||||
|
||||
func (x *PendingItem) Reset() {
|
||||
*x = PendingItem{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[6]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[8]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -909,7 +981,7 @@ func (x *PendingItem) String() string {
|
||||
func (*PendingItem) ProtoMessage() {}
|
||||
|
||||
func (x *PendingItem) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[6]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[8]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -922,7 +994,7 @@ func (x *PendingItem) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use PendingItem.ProtoReflect.Descriptor instead.
|
||||
func (*PendingItem) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{6}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{8}
|
||||
}
|
||||
|
||||
func (x *PendingItem) GetObjectPath() string {
|
||||
@@ -967,7 +1039,7 @@ type BootstrapState struct {
|
||||
|
||||
func (x *BootstrapState) Reset() {
|
||||
*x = BootstrapState{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[7]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[9]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -979,7 +1051,7 @@ func (x *BootstrapState) String() string {
|
||||
func (*BootstrapState) ProtoMessage() {}
|
||||
|
||||
func (x *BootstrapState) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[7]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[9]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -992,7 +1064,7 @@ func (x *BootstrapState) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use BootstrapState.ProtoReflect.Descriptor instead.
|
||||
func (*BootstrapState) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{9}
|
||||
}
|
||||
|
||||
func (x *BootstrapState) GetLastScannedPath() string {
|
||||
@@ -1038,7 +1110,7 @@ type ReaderState struct {
|
||||
|
||||
func (x *ReaderState) Reset() {
|
||||
*x = ReaderState{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[8]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[10]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1050,7 +1122,7 @@ func (x *ReaderState) String() string {
|
||||
func (*ReaderState) ProtoMessage() {}
|
||||
|
||||
func (x *ReaderState) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[8]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[10]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1063,7 +1135,7 @@ func (x *ReaderState) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use ReaderState.ProtoReflect.Descriptor instead.
|
||||
func (*ReaderState) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{8}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{10}
|
||||
}
|
||||
|
||||
func (x *ReaderState) GetPrimaryFilerEndpoint() string {
|
||||
@@ -1110,7 +1182,7 @@ type FilerShardCursorList struct {
|
||||
|
||||
func (x *FilerShardCursorList) Reset() {
|
||||
*x = FilerShardCursorList{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[9]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[11]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1122,7 +1194,7 @@ func (x *FilerShardCursorList) String() string {
|
||||
func (*FilerShardCursorList) ProtoMessage() {}
|
||||
|
||||
func (x *FilerShardCursorList) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[9]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[11]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1135,7 +1207,7 @@ func (x *FilerShardCursorList) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use FilerShardCursorList.ProtoReflect.Descriptor instead.
|
||||
func (*FilerShardCursorList) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{9}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{11}
|
||||
}
|
||||
|
||||
func (x *FilerShardCursorList) GetCursors() []*FilerShardCursor {
|
||||
@@ -1159,7 +1231,7 @@ type TailDrainedKey struct {
|
||||
|
||||
func (x *TailDrainedKey) Reset() {
|
||||
*x = TailDrainedKey{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[10]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[12]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1171,7 +1243,7 @@ func (x *TailDrainedKey) String() string {
|
||||
func (*TailDrainedKey) ProtoMessage() {}
|
||||
|
||||
func (x *TailDrainedKey) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[10]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[12]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1184,7 +1256,7 @@ func (x *TailDrainedKey) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TailDrainedKey.ProtoReflect.Descriptor instead.
|
||||
func (*TailDrainedKey) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{10}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{12}
|
||||
}
|
||||
|
||||
func (x *TailDrainedKey) GetStreamKind() StreamKind {
|
||||
@@ -1241,7 +1313,7 @@ type BlockerRecord struct {
|
||||
|
||||
func (x *BlockerRecord) Reset() {
|
||||
*x = BlockerRecord{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[11]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[13]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1253,7 +1325,7 @@ func (x *BlockerRecord) String() string {
|
||||
func (*BlockerRecord) ProtoMessage() {}
|
||||
|
||||
func (x *BlockerRecord) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[11]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[13]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1266,7 +1338,7 @@ func (x *BlockerRecord) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use BlockerRecord.ProtoReflect.Descriptor instead.
|
||||
func (*BlockerRecord) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{11}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{13}
|
||||
}
|
||||
|
||||
func (x *BlockerRecord) GetStreamKind() StreamKind {
|
||||
@@ -1384,7 +1456,7 @@ type StreamKey struct {
|
||||
|
||||
func (x *StreamKey) Reset() {
|
||||
*x = StreamKey{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[12]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[14]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1396,7 +1468,7 @@ func (x *StreamKey) String() string {
|
||||
func (*StreamKey) ProtoMessage() {}
|
||||
|
||||
func (x *StreamKey) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[12]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[14]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1409,7 +1481,7 @@ func (x *StreamKey) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use StreamKey.ProtoReflect.Descriptor instead.
|
||||
func (*StreamKey) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{12}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{14}
|
||||
}
|
||||
|
||||
func (x *StreamKey) GetKey() isStreamKey_Key {
|
||||
@@ -1494,7 +1566,7 @@ type OriginalKey struct {
|
||||
|
||||
func (x *OriginalKey) Reset() {
|
||||
*x = OriginalKey{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[13]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[15]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1506,7 +1578,7 @@ func (x *OriginalKey) String() string {
|
||||
func (*OriginalKey) ProtoMessage() {}
|
||||
|
||||
func (x *OriginalKey) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[13]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[15]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1519,7 +1591,7 @@ func (x *OriginalKey) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use OriginalKey.ProtoReflect.Descriptor instead.
|
||||
func (*OriginalKey) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{13}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{15}
|
||||
}
|
||||
|
||||
func (x *OriginalKey) GetShard() string {
|
||||
@@ -1553,7 +1625,7 @@ type PredicateKey struct {
|
||||
|
||||
func (x *PredicateKey) Reset() {
|
||||
*x = PredicateKey{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[14]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[16]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1565,7 +1637,7 @@ func (x *PredicateKey) String() string {
|
||||
func (*PredicateKey) ProtoMessage() {}
|
||||
|
||||
func (x *PredicateKey) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[14]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[16]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1578,7 +1650,7 @@ func (x *PredicateKey) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use PredicateKey.ProtoReflect.Descriptor instead.
|
||||
func (*PredicateKey) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{14}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{16}
|
||||
}
|
||||
|
||||
func (x *PredicateKey) GetShard() string {
|
||||
@@ -1608,7 +1680,7 @@ type BootstrapKey struct {
|
||||
|
||||
func (x *BootstrapKey) Reset() {
|
||||
*x = BootstrapKey{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[15]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[17]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1620,7 +1692,7 @@ func (x *BootstrapKey) String() string {
|
||||
func (*BootstrapKey) ProtoMessage() {}
|
||||
|
||||
func (x *BootstrapKey) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[15]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[17]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1633,7 +1705,7 @@ func (x *BootstrapKey) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use BootstrapKey.ProtoReflect.Descriptor instead.
|
||||
func (*BootstrapKey) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{15}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{17}
|
||||
}
|
||||
|
||||
func (x *BootstrapKey) GetBucket() string {
|
||||
@@ -1684,7 +1756,7 @@ type PendingKey struct {
|
||||
|
||||
func (x *PendingKey) Reset() {
|
||||
*x = PendingKey{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[16]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[18]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1696,7 +1768,7 @@ func (x *PendingKey) String() string {
|
||||
func (*PendingKey) ProtoMessage() {}
|
||||
|
||||
func (x *PendingKey) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[16]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[18]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1709,7 +1781,7 @@ func (x *PendingKey) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use PendingKey.ProtoReflect.Descriptor instead.
|
||||
func (*PendingKey) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{16}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{18}
|
||||
}
|
||||
|
||||
func (x *PendingKey) GetBucket() string {
|
||||
@@ -1762,7 +1834,7 @@ type RetryBudgetEntry struct {
|
||||
|
||||
func (x *RetryBudgetEntry) Reset() {
|
||||
*x = RetryBudgetEntry{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[17]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[19]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1774,7 +1846,7 @@ func (x *RetryBudgetEntry) String() string {
|
||||
func (*RetryBudgetEntry) ProtoMessage() {}
|
||||
|
||||
func (x *RetryBudgetEntry) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[17]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[19]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1787,7 +1859,7 @@ func (x *RetryBudgetEntry) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use RetryBudgetEntry.ProtoReflect.Descriptor instead.
|
||||
func (*RetryBudgetEntry) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{17}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{19}
|
||||
}
|
||||
|
||||
func (x *RetryBudgetEntry) GetKey() *StreamKey {
|
||||
@@ -1836,7 +1908,7 @@ type RetryTarget struct {
|
||||
|
||||
func (x *RetryTarget) Reset() {
|
||||
*x = RetryTarget{}
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[18]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[20]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1848,7 +1920,7 @@ func (x *RetryTarget) String() string {
|
||||
func (*RetryTarget) ProtoMessage() {}
|
||||
|
||||
func (x *RetryTarget) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[18]
|
||||
mi := &file_s3_lifecycle_proto_msgTypes[20]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1861,7 +1933,7 @@ func (x *RetryTarget) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use RetryTarget.ProtoReflect.Descriptor instead.
|
||||
func (*RetryTarget) Descriptor() ([]byte, []int) {
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{18}
|
||||
return file_s3_lifecycle_proto_rawDescGZIP(), []int{20}
|
||||
}
|
||||
|
||||
func (x *RetryTarget) GetKey() *StreamKey {
|
||||
@@ -1929,7 +2001,9 @@ const file_s3_lifecycle_proto_rawDesc = "" +
|
||||
"\x12engine_snapshot_id\x18\x15 \x01(\x04R\x10engineSnapshotId\"t\n" +
|
||||
"\x17LifecycleDeleteResponse\x12A\n" +
|
||||
"\aoutcome\x18\x01 \x01(\x0e2'.s3_lifecycle_pb.LifecycleDeleteOutcomeR\aoutcome\x12\x16\n" +
|
||||
"\x06reason\x18\x02 \x01(\tR\x06reason\">\n" +
|
||||
"\x06reason\x18\x02 \x01(\tR\x06reason\"\x17\n" +
|
||||
"\x15LifecycleReadyRequest\"\x18\n" +
|
||||
"\x16LifecycleReadyResponse\">\n" +
|
||||
"\x0fMessagePosition\x12\x13\n" +
|
||||
"\x05ts_ns\x18\x01 \x01(\x03R\x04tsNs\x12\x16\n" +
|
||||
"\x06offset\x18\x02 \x01(\x03R\x06offset\"k\n" +
|
||||
@@ -2093,9 +2167,10 @@ const file_s3_lifecycle_proto_rawDesc = "" +
|
||||
"\bORIGINAL\x10\x01\x12\r\n" +
|
||||
"\tPREDICATE\x10\x02\x12\r\n" +
|
||||
"\tBOOTSTRAP\x10\x03\x12\v\n" +
|
||||
"\aPENDING\x10\x042\x82\x01\n" +
|
||||
"\aPENDING\x10\x042\xe5\x01\n" +
|
||||
"\x1aSeaweedS3LifecycleInternal\x12d\n" +
|
||||
"\x0fLifecycleDelete\x12'.s3_lifecycle_pb.LifecycleDeleteRequest\x1a(.s3_lifecycle_pb.LifecycleDeleteResponseB\\\n" +
|
||||
"\x0fLifecycleDelete\x12'.s3_lifecycle_pb.LifecycleDeleteRequest\x1a(.s3_lifecycle_pb.LifecycleDeleteResponse\x12a\n" +
|
||||
"\x0eLifecycleReady\x12&.s3_lifecycle_pb.LifecycleReadyRequest\x1a'.s3_lifecycle_pb.LifecycleReadyResponseB\\\n" +
|
||||
"\x10seaweedfs.clientB\x10S3LifecycleProtoZ6github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pbb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -2111,7 +2186,7 @@ func file_s3_lifecycle_proto_rawDescGZIP() []byte {
|
||||
}
|
||||
|
||||
var file_s3_lifecycle_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
|
||||
var file_s3_lifecycle_proto_msgTypes = make([]protoimpl.MessageInfo, 20)
|
||||
var file_s3_lifecycle_proto_msgTypes = make([]protoimpl.MessageInfo, 22)
|
||||
var file_s3_lifecycle_proto_goTypes = []any{
|
||||
(ActionKind)(0), // 0: s3_lifecycle_pb.ActionKind
|
||||
(LifecycleDeleteOutcome)(0), // 1: s3_lifecycle_pb.LifecycleDeleteOutcome
|
||||
@@ -2120,58 +2195,62 @@ var file_s3_lifecycle_proto_goTypes = []any{
|
||||
(LifecycleState_DegradedReason)(0), // 4: s3_lifecycle_pb.LifecycleState.DegradedReason
|
||||
(*LifecycleDeleteRequest)(nil), // 5: s3_lifecycle_pb.LifecycleDeleteRequest
|
||||
(*LifecycleDeleteResponse)(nil), // 6: s3_lifecycle_pb.LifecycleDeleteResponse
|
||||
(*MessagePosition)(nil), // 7: s3_lifecycle_pb.MessagePosition
|
||||
(*FilerShardCursor)(nil), // 8: s3_lifecycle_pb.FilerShardCursor
|
||||
(*EntryIdentity)(nil), // 9: s3_lifecycle_pb.EntryIdentity
|
||||
(*LifecycleState)(nil), // 10: s3_lifecycle_pb.LifecycleState
|
||||
(*PendingItem)(nil), // 11: s3_lifecycle_pb.PendingItem
|
||||
(*BootstrapState)(nil), // 12: s3_lifecycle_pb.BootstrapState
|
||||
(*ReaderState)(nil), // 13: s3_lifecycle_pb.ReaderState
|
||||
(*FilerShardCursorList)(nil), // 14: s3_lifecycle_pb.FilerShardCursorList
|
||||
(*TailDrainedKey)(nil), // 15: s3_lifecycle_pb.TailDrainedKey
|
||||
(*BlockerRecord)(nil), // 16: s3_lifecycle_pb.BlockerRecord
|
||||
(*StreamKey)(nil), // 17: s3_lifecycle_pb.StreamKey
|
||||
(*OriginalKey)(nil), // 18: s3_lifecycle_pb.OriginalKey
|
||||
(*PredicateKey)(nil), // 19: s3_lifecycle_pb.PredicateKey
|
||||
(*BootstrapKey)(nil), // 20: s3_lifecycle_pb.BootstrapKey
|
||||
(*PendingKey)(nil), // 21: s3_lifecycle_pb.PendingKey
|
||||
(*RetryBudgetEntry)(nil), // 22: s3_lifecycle_pb.RetryBudgetEntry
|
||||
(*RetryTarget)(nil), // 23: s3_lifecycle_pb.RetryTarget
|
||||
nil, // 24: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
|
||||
(*LifecycleReadyRequest)(nil), // 7: s3_lifecycle_pb.LifecycleReadyRequest
|
||||
(*LifecycleReadyResponse)(nil), // 8: s3_lifecycle_pb.LifecycleReadyResponse
|
||||
(*MessagePosition)(nil), // 9: s3_lifecycle_pb.MessagePosition
|
||||
(*FilerShardCursor)(nil), // 10: s3_lifecycle_pb.FilerShardCursor
|
||||
(*EntryIdentity)(nil), // 11: s3_lifecycle_pb.EntryIdentity
|
||||
(*LifecycleState)(nil), // 12: s3_lifecycle_pb.LifecycleState
|
||||
(*PendingItem)(nil), // 13: s3_lifecycle_pb.PendingItem
|
||||
(*BootstrapState)(nil), // 14: s3_lifecycle_pb.BootstrapState
|
||||
(*ReaderState)(nil), // 15: s3_lifecycle_pb.ReaderState
|
||||
(*FilerShardCursorList)(nil), // 16: s3_lifecycle_pb.FilerShardCursorList
|
||||
(*TailDrainedKey)(nil), // 17: s3_lifecycle_pb.TailDrainedKey
|
||||
(*BlockerRecord)(nil), // 18: s3_lifecycle_pb.BlockerRecord
|
||||
(*StreamKey)(nil), // 19: s3_lifecycle_pb.StreamKey
|
||||
(*OriginalKey)(nil), // 20: s3_lifecycle_pb.OriginalKey
|
||||
(*PredicateKey)(nil), // 21: s3_lifecycle_pb.PredicateKey
|
||||
(*BootstrapKey)(nil), // 22: s3_lifecycle_pb.BootstrapKey
|
||||
(*PendingKey)(nil), // 23: s3_lifecycle_pb.PendingKey
|
||||
(*RetryBudgetEntry)(nil), // 24: s3_lifecycle_pb.RetryBudgetEntry
|
||||
(*RetryTarget)(nil), // 25: s3_lifecycle_pb.RetryTarget
|
||||
nil, // 26: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
|
||||
}
|
||||
var file_s3_lifecycle_proto_depIdxs = []int32{
|
||||
0, // 0: s3_lifecycle_pb.LifecycleDeleteRequest.action_kind:type_name -> s3_lifecycle_pb.ActionKind
|
||||
9, // 1: s3_lifecycle_pb.LifecycleDeleteRequest.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
|
||||
11, // 1: s3_lifecycle_pb.LifecycleDeleteRequest.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
|
||||
1, // 2: s3_lifecycle_pb.LifecycleDeleteResponse.outcome:type_name -> s3_lifecycle_pb.LifecycleDeleteOutcome
|
||||
7, // 3: s3_lifecycle_pb.FilerShardCursor.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
9, // 3: s3_lifecycle_pb.FilerShardCursor.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
0, // 4: s3_lifecycle_pb.LifecycleState.action_kind:type_name -> s3_lifecycle_pb.ActionKind
|
||||
3, // 5: s3_lifecycle_pb.LifecycleState.mode:type_name -> s3_lifecycle_pb.LifecycleState.RuleMode
|
||||
4, // 6: s3_lifecycle_pb.LifecycleState.degraded_reason:type_name -> s3_lifecycle_pb.LifecycleState.DegradedReason
|
||||
9, // 7: s3_lifecycle_pb.PendingItem.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
|
||||
24, // 8: s3_lifecycle_pb.ReaderState.last_processed_original:type_name -> s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
|
||||
8, // 9: s3_lifecycle_pb.ReaderState.last_processed_predicate:type_name -> s3_lifecycle_pb.FilerShardCursor
|
||||
15, // 10: s3_lifecycle_pb.ReaderState.tail_drained_streams:type_name -> s3_lifecycle_pb.TailDrainedKey
|
||||
8, // 11: s3_lifecycle_pb.FilerShardCursorList.cursors:type_name -> s3_lifecycle_pb.FilerShardCursor
|
||||
11, // 7: s3_lifecycle_pb.PendingItem.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
|
||||
26, // 8: s3_lifecycle_pb.ReaderState.last_processed_original:type_name -> s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
|
||||
10, // 9: s3_lifecycle_pb.ReaderState.last_processed_predicate:type_name -> s3_lifecycle_pb.FilerShardCursor
|
||||
17, // 10: s3_lifecycle_pb.ReaderState.tail_drained_streams:type_name -> s3_lifecycle_pb.TailDrainedKey
|
||||
10, // 11: s3_lifecycle_pb.FilerShardCursorList.cursors:type_name -> s3_lifecycle_pb.FilerShardCursor
|
||||
2, // 12: s3_lifecycle_pb.TailDrainedKey.stream_kind:type_name -> s3_lifecycle_pb.StreamKind
|
||||
2, // 13: s3_lifecycle_pb.BlockerRecord.stream_kind:type_name -> s3_lifecycle_pb.StreamKind
|
||||
7, // 14: s3_lifecycle_pb.BlockerRecord.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
9, // 14: s3_lifecycle_pb.BlockerRecord.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
0, // 15: s3_lifecycle_pb.BlockerRecord.action_kind:type_name -> s3_lifecycle_pb.ActionKind
|
||||
18, // 16: s3_lifecycle_pb.StreamKey.original:type_name -> s3_lifecycle_pb.OriginalKey
|
||||
19, // 17: s3_lifecycle_pb.StreamKey.predicate:type_name -> s3_lifecycle_pb.PredicateKey
|
||||
20, // 18: s3_lifecycle_pb.StreamKey.bootstrap:type_name -> s3_lifecycle_pb.BootstrapKey
|
||||
21, // 19: s3_lifecycle_pb.StreamKey.pending:type_name -> s3_lifecycle_pb.PendingKey
|
||||
7, // 20: s3_lifecycle_pb.OriginalKey.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
7, // 21: s3_lifecycle_pb.PredicateKey.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
20, // 16: s3_lifecycle_pb.StreamKey.original:type_name -> s3_lifecycle_pb.OriginalKey
|
||||
21, // 17: s3_lifecycle_pb.StreamKey.predicate:type_name -> s3_lifecycle_pb.PredicateKey
|
||||
22, // 18: s3_lifecycle_pb.StreamKey.bootstrap:type_name -> s3_lifecycle_pb.BootstrapKey
|
||||
23, // 19: s3_lifecycle_pb.StreamKey.pending:type_name -> s3_lifecycle_pb.PendingKey
|
||||
9, // 20: s3_lifecycle_pb.OriginalKey.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
9, // 21: s3_lifecycle_pb.PredicateKey.position:type_name -> s3_lifecycle_pb.MessagePosition
|
||||
0, // 22: s3_lifecycle_pb.BootstrapKey.action_kind:type_name -> s3_lifecycle_pb.ActionKind
|
||||
0, // 23: s3_lifecycle_pb.PendingKey.action_kind:type_name -> s3_lifecycle_pb.ActionKind
|
||||
17, // 24: s3_lifecycle_pb.RetryBudgetEntry.key:type_name -> s3_lifecycle_pb.StreamKey
|
||||
17, // 25: s3_lifecycle_pb.RetryTarget.key:type_name -> s3_lifecycle_pb.StreamKey
|
||||
19, // 24: s3_lifecycle_pb.RetryBudgetEntry.key:type_name -> s3_lifecycle_pb.StreamKey
|
||||
19, // 25: s3_lifecycle_pb.RetryTarget.key:type_name -> s3_lifecycle_pb.StreamKey
|
||||
0, // 26: s3_lifecycle_pb.RetryTarget.action_kind:type_name -> s3_lifecycle_pb.ActionKind
|
||||
14, // 27: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry.value:type_name -> s3_lifecycle_pb.FilerShardCursorList
|
||||
16, // 27: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry.value:type_name -> s3_lifecycle_pb.FilerShardCursorList
|
||||
5, // 28: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleDelete:input_type -> s3_lifecycle_pb.LifecycleDeleteRequest
|
||||
6, // 29: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleDelete:output_type -> s3_lifecycle_pb.LifecycleDeleteResponse
|
||||
29, // [29:30] is the sub-list for method output_type
|
||||
28, // [28:29] is the sub-list for method input_type
|
||||
7, // 29: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleReady:input_type -> s3_lifecycle_pb.LifecycleReadyRequest
|
||||
6, // 30: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleDelete:output_type -> s3_lifecycle_pb.LifecycleDeleteResponse
|
||||
8, // 31: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleReady:output_type -> s3_lifecycle_pb.LifecycleReadyResponse
|
||||
30, // [30:32] is the sub-list for method output_type
|
||||
28, // [28:30] is the sub-list for method input_type
|
||||
28, // [28:28] is the sub-list for extension type_name
|
||||
28, // [28:28] is the sub-list for extension extendee
|
||||
0, // [0:28] is the sub-list for field type_name
|
||||
@@ -2182,7 +2261,7 @@ func file_s3_lifecycle_proto_init() {
|
||||
if File_s3_lifecycle_proto != nil {
|
||||
return
|
||||
}
|
||||
file_s3_lifecycle_proto_msgTypes[12].OneofWrappers = []any{
|
||||
file_s3_lifecycle_proto_msgTypes[14].OneofWrappers = []any{
|
||||
(*StreamKey_Original)(nil),
|
||||
(*StreamKey_Predicate)(nil),
|
||||
(*StreamKey_Bootstrap)(nil),
|
||||
@@ -2194,7 +2273,7 @@ func file_s3_lifecycle_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_s3_lifecycle_proto_rawDesc), len(file_s3_lifecycle_proto_rawDesc)),
|
||||
NumEnums: 5,
|
||||
NumMessages: 20,
|
||||
NumMessages: 22,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.33.4
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v3.21.12
|
||||
// source: s3_lifecycle.proto
|
||||
|
||||
package s3_lifecycle_pb
|
||||
@@ -20,6 +20,7 @@ const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
SeaweedS3LifecycleInternal_LifecycleDelete_FullMethodName = "/s3_lifecycle_pb.SeaweedS3LifecycleInternal/LifecycleDelete"
|
||||
SeaweedS3LifecycleInternal_LifecycleReady_FullMethodName = "/s3_lifecycle_pb.SeaweedS3LifecycleInternal/LifecycleReady"
|
||||
)
|
||||
|
||||
// SeaweedS3LifecycleInternalClient is the client API for SeaweedS3LifecycleInternal service.
|
||||
@@ -34,6 +35,9 @@ const (
|
||||
// to the appropriate internal helper.
|
||||
type SeaweedS3LifecycleInternalClient interface {
|
||||
LifecycleDelete(ctx context.Context, in *LifecycleDeleteRequest, opts ...grpc.CallOption) (*LifecycleDeleteResponse, error)
|
||||
// LifecycleReady runs LifecycleDelete's authorization and nothing else,
|
||||
// so a worker can check a front before it starts a pass.
|
||||
LifecycleReady(ctx context.Context, in *LifecycleReadyRequest, opts ...grpc.CallOption) (*LifecycleReadyResponse, error)
|
||||
}
|
||||
|
||||
type seaweedS3LifecycleInternalClient struct {
|
||||
@@ -54,6 +58,16 @@ func (c *seaweedS3LifecycleInternalClient) LifecycleDelete(ctx context.Context,
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedS3LifecycleInternalClient) LifecycleReady(ctx context.Context, in *LifecycleReadyRequest, opts ...grpc.CallOption) (*LifecycleReadyResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(LifecycleReadyResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedS3LifecycleInternal_LifecycleReady_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SeaweedS3LifecycleInternalServer is the server API for SeaweedS3LifecycleInternal service.
|
||||
// All implementations must embed UnimplementedSeaweedS3LifecycleInternalServer
|
||||
// for forward compatibility.
|
||||
@@ -66,6 +80,9 @@ func (c *seaweedS3LifecycleInternalClient) LifecycleDelete(ctx context.Context,
|
||||
// to the appropriate internal helper.
|
||||
type SeaweedS3LifecycleInternalServer interface {
|
||||
LifecycleDelete(context.Context, *LifecycleDeleteRequest) (*LifecycleDeleteResponse, error)
|
||||
// LifecycleReady runs LifecycleDelete's authorization and nothing else,
|
||||
// so a worker can check a front before it starts a pass.
|
||||
LifecycleReady(context.Context, *LifecycleReadyRequest) (*LifecycleReadyResponse, error)
|
||||
mustEmbedUnimplementedSeaweedS3LifecycleInternalServer()
|
||||
}
|
||||
|
||||
@@ -77,7 +94,10 @@ type SeaweedS3LifecycleInternalServer interface {
|
||||
type UnimplementedSeaweedS3LifecycleInternalServer struct{}
|
||||
|
||||
func (UnimplementedSeaweedS3LifecycleInternalServer) LifecycleDelete(context.Context, *LifecycleDeleteRequest) (*LifecycleDeleteResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method LifecycleDelete not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method LifecycleDelete not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedS3LifecycleInternalServer) LifecycleReady(context.Context, *LifecycleReadyRequest) (*LifecycleReadyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method LifecycleReady not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedS3LifecycleInternalServer) mustEmbedUnimplementedSeaweedS3LifecycleInternalServer() {
|
||||
}
|
||||
@@ -91,7 +111,7 @@ type UnsafeSeaweedS3LifecycleInternalServer interface {
|
||||
}
|
||||
|
||||
func RegisterSeaweedS3LifecycleInternalServer(s grpc.ServiceRegistrar, srv SeaweedS3LifecycleInternalServer) {
|
||||
// If the following call pancis, it indicates UnimplementedSeaweedS3LifecycleInternalServer was
|
||||
// If the following call panics, it indicates UnimplementedSeaweedS3LifecycleInternalServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
@@ -119,6 +139,24 @@ func _SeaweedS3LifecycleInternal_LifecycleDelete_Handler(srv interface{}, ctx co
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedS3LifecycleInternal_LifecycleReady_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LifecycleReadyRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedS3LifecycleInternalServer).LifecycleReady(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedS3LifecycleInternal_LifecycleReady_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedS3LifecycleInternalServer).LifecycleReady(ctx, req.(*LifecycleReadyRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// SeaweedS3LifecycleInternal_ServiceDesc is the grpc.ServiceDesc for SeaweedS3LifecycleInternal service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -130,6 +168,10 @@ var SeaweedS3LifecycleInternal_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "LifecycleDelete",
|
||||
Handler: _SeaweedS3LifecycleInternal_LifecycleDelete_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "LifecycleReady",
|
||||
Handler: _SeaweedS3LifecycleInternal_LifecycleReady_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "s3_lifecycle.proto",
|
||||
|
||||
@@ -59,6 +59,15 @@ func (s3a *S3ApiServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_p
|
||||
return s3a.lifecycleDispatch(ctx, req, entry)
|
||||
}
|
||||
|
||||
// LifecycleReady authorizes the caller as LifecycleDelete does and touches
|
||||
// no bucket or object metadata.
|
||||
func (s3a *S3ApiServer) LifecycleReady(ctx context.Context, _ *s3_lifecycle_pb.LifecycleReadyRequest) (*s3_lifecycle_pb.LifecycleReadyResponse, error) {
|
||||
if err := s3a.checkAdminAuth(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s3_lifecycle_pb.LifecycleReadyResponse{}, nil
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest, entry *filer_pb.Entry) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
metadataOnly := entryUsesMetadataOnlyDelete(entry)
|
||||
switch req.ActionKind {
|
||||
|
||||
@@ -384,6 +384,38 @@ func TestLifecycleDelete_NoSigningKey_LocalPeerOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleReady_AuthorizesLikeLifecycleDelete(t *testing.T) {
|
||||
good := security.GenJwtForFilerAdmin(security.SigningKey(testS3IamCacheSigningKey), 60)
|
||||
bad := security.GenJwtForFilerAdmin(security.SigningKey("a-different-key"), 60)
|
||||
remoteCtx := peer.NewContext(context.Background(),
|
||||
&peer.Peer{Addr: &net.TCPAddr{IP: net.ParseIP("203.0.113.7"), Port: 11111}})
|
||||
cases := []struct {
|
||||
name string
|
||||
signingKey string
|
||||
ctx context.Context
|
||||
want codes.Code
|
||||
}{
|
||||
{"key, no token", testS3IamCacheSigningKey, context.Background(), codes.Unauthenticated},
|
||||
{"key, mis-signed token", testS3IamCacheSigningKey, s3IamCacheBearerCtx(string(bad)), codes.Unauthenticated},
|
||||
{"key, valid token", testS3IamCacheSigningKey, s3IamCacheBearerCtx(string(good)), codes.OK},
|
||||
{"no key, remote peer", "", remoteCtx, codes.Unauthenticated},
|
||||
{"no key, loopback peer", "", s3LocalPeerCtx(), codes.OK},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := newTestS3IamCacheServer(t, tc.signingKey)
|
||||
_, err := s.LifecycleReady(tc.ctx, &s3_lifecycle_pb.LifecycleReadyRequest{})
|
||||
if got := status.Code(err); got != tc.want {
|
||||
t.Fatalf("LifecycleReady: got code %v, want %v (err=%v)", got, tc.want, err)
|
||||
}
|
||||
_, deleteErr := s.LifecycleDelete(tc.ctx, &s3_lifecycle_pb.LifecycleDeleteRequest{})
|
||||
if got := status.Code(deleteErr); got != tc.want {
|
||||
t.Fatalf("LifecycleDelete disagrees: got code %v, want %v (err=%v)", got, tc.want, deleteErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleDelete_CurrentExpirationRequiresLatestVersion(t *testing.T) {
|
||||
listed := &filer_pb.Entry{
|
||||
Name: "v_old",
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
|
||||
@@ -161,3 +162,58 @@ func (p *FilerCursorPersister) Save(ctx context.Context, shardID int, c Cursor)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const fullPassFileName = "full-pass.json"
|
||||
|
||||
// FullPass is the last pass that covered every shard and every lifecycle
|
||||
// policy without an error. Shard cursors advance on partial passes too,
|
||||
// so they cannot answer that.
|
||||
type FullPass struct {
|
||||
StartedAt time.Time
|
||||
CompletedAt time.Time
|
||||
}
|
||||
|
||||
type fullPassFile struct {
|
||||
Version int `json:"version"`
|
||||
StartedAtNs int64 `json:"started_at_ns"`
|
||||
CompletedAtNs int64 `json:"completed_at_ns"`
|
||||
}
|
||||
|
||||
func (p *FilerCursorPersister) LoadFullPass(ctx context.Context) (FullPass, bool, error) {
|
||||
if p.Store == nil {
|
||||
return FullPass{}, false, errors.New("FilerCursorPersister: nil Store")
|
||||
}
|
||||
content, err := p.Store.Read(ctx, CursorDir, fullPassFileName)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return FullPass{}, false, nil
|
||||
}
|
||||
return FullPass{}, false, fmt.Errorf("full pass read: %w", err)
|
||||
}
|
||||
var f fullPassFile
|
||||
if err := json.Unmarshal(content, &f); err != nil {
|
||||
return FullPass{}, false, fmt.Errorf("full pass decode: %w", err)
|
||||
}
|
||||
if f.Version != cursorFileVersion {
|
||||
return FullPass{}, false, fmt.Errorf("full pass version: got %d, want %d", f.Version, cursorFileVersion)
|
||||
}
|
||||
return FullPass{StartedAt: time.Unix(0, f.StartedAtNs).UTC(), CompletedAt: time.Unix(0, f.CompletedAtNs).UTC()}, true, nil
|
||||
}
|
||||
|
||||
func (p *FilerCursorPersister) SaveFullPass(ctx context.Context, fp FullPass) error {
|
||||
if p.Store == nil {
|
||||
return errors.New("FilerCursorPersister: nil Store")
|
||||
}
|
||||
content, err := json.Marshal(fullPassFile{
|
||||
Version: cursorFileVersion,
|
||||
StartedAtNs: fp.StartedAt.UnixNano(),
|
||||
CompletedAtNs: fp.CompletedAt.UnixNano(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("full pass encode: %w", err)
|
||||
}
|
||||
if err := p.Store.Save(ctx, CursorDir, fullPassFileName, content); err != nil {
|
||||
return fmt.Errorf("full pass save: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -153,3 +154,32 @@ func TestFilerCursorPersister_NilStoreErrors(t *testing.T) {
|
||||
require.Error(t, err)
|
||||
require.Error(t, p.Save(context.Background(), 0, Cursor{}))
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_FullPassRoundTrip(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
p := &FilerCursorPersister{Store: store}
|
||||
_, found, err := p.LoadFullPass(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.False(t, found)
|
||||
|
||||
want := FullPass{
|
||||
StartedAt: time.Unix(1_700_000_000, 123).UTC(),
|
||||
CompletedAt: time.Unix(1_700_003_600, 456).UTC(),
|
||||
}
|
||||
require.NoError(t, p.SaveFullPass(context.Background(), want))
|
||||
got, found, err := p.LoadFullPass(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
assert.Equal(t, want, got)
|
||||
|
||||
_, found, err = p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, found, "the full-pass record must not read as a shard cursor")
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_FullPassRejectsUnknownVersion(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
require.NoError(t, store.Save(context.Background(), CursorDir, fullPassFileName, []byte(`{"version":99,"completed_at_ns":1}`)))
|
||||
_, _, err := (&FilerCursorPersister{Store: store}).LoadFullPass(context.Background())
|
||||
assert.Error(t, err)
|
||||
}
|
||||
@@ -91,6 +91,10 @@ type Config struct {
|
||||
|
||||
// 0 -> defaultSubscriptionReceiveTimeout.
|
||||
SubscriptionReceiveTimeout time.Duration
|
||||
|
||||
// nil -> no per-pass summary. Share it with the walker's
|
||||
// WalkBuckets and WalkerDispatcher to cover both paths.
|
||||
Stats *RunStats
|
||||
}
|
||||
|
||||
// Above the filer's 15m maxGapStall, so a subscriber parked on a gap is
|
||||
@@ -240,6 +244,7 @@ func Run(ctx context.Context, cfg Config) error {
|
||||
first = readerErr
|
||||
}
|
||||
}
|
||||
cfg.Stats.setShardErrors(errCount)
|
||||
status := "ok"
|
||||
if first != nil {
|
||||
status = "error"
|
||||
@@ -562,6 +567,8 @@ func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow tim
|
||||
lastWalkedNs = runNow.UnixNano()
|
||||
walkedThisPass = true
|
||||
}
|
||||
} else if cfg.Walker != nil {
|
||||
countDeferredWalk(cfg.Stats, snap, shardID, retentionWindow)
|
||||
}
|
||||
_ = walkedThisPass // empty-replay branch returns; no downstream walker.
|
||||
return saveCursorAndPublish(ctx, cfg.Persister, shardID, Cursor{
|
||||
@@ -625,6 +632,8 @@ func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow tim
|
||||
}
|
||||
lastWalkedNs = runNow.UnixNano()
|
||||
}
|
||||
} else if cfg.Walker != nil && !walkedThisPass {
|
||||
countDeferredWalk(cfg.Stats, snap, shardID, retentionWindow)
|
||||
}
|
||||
|
||||
// Cold start: scan from now-maxTTL so already-due objects within
|
||||
@@ -644,7 +653,10 @@ func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow tim
|
||||
// Walk-bound rules are never due inside the retention window; keep them
|
||||
// out of the drain so their matches don't pin the cursor.
|
||||
replayView := snap.ReplayView(retentionWindow)
|
||||
lastOK, _, drainErr := drainShardEvents(ctx, cfg, runNow, shardID, replayView, startTsNs, events)
|
||||
lastOK, halted, drainErr := drainShardEvents(ctx, cfg, runNow, shardID, replayView, startTsNs, events)
|
||||
if halted && drainErr == nil {
|
||||
cfg.Stats.shardHalted()
|
||||
}
|
||||
// Fresh ctx: a wall-clock cap on the pass (the shell driver's
|
||||
// -runtime) cancels the drain's, and saving with it would drop the
|
||||
// cursor and re-replay from the same floor next pass.
|
||||
@@ -684,6 +696,17 @@ func saveCursorAndPublish(ctx context.Context, p CursorPersister, shardID int, c
|
||||
return nil
|
||||
}
|
||||
|
||||
// countDeferredWalk counts a shard whose walk-only rules waited for
|
||||
// WalkerInterval, so the pass left them unevaluated.
|
||||
func countDeferredWalk(s *RunStats, snap *engine.Snapshot, shardID int, retentionWindow time.Duration) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if _, walkView := snap.RulesForShard(shardID, retentionWindow); walkView != nil && len(walkView.AllActions()) > 0 {
|
||||
s.walkDeferred()
|
||||
}
|
||||
}
|
||||
|
||||
// walkerDue answers the persisted-state throttle: has enough time
|
||||
// elapsed since the last walker fire on this shard? interval == 0
|
||||
// means "fire every pass" (the prior, unconditional behavior).
|
||||
@@ -719,6 +742,7 @@ func drainShardEvents(ctx context.Context, cfg Config, runNow time.Time, shardID
|
||||
cursorAdvanceTo := startTsNs
|
||||
stuck := false
|
||||
halted := false
|
||||
cfg.Stats.startReplay()
|
||||
|
||||
drain:
|
||||
for {
|
||||
@@ -739,6 +763,7 @@ drain:
|
||||
continue
|
||||
}
|
||||
stats.S3LifecycleDailyRunEventsScanned.WithLabelValues(strconv.Itoa(shardID)).Inc()
|
||||
cfg.Stats.scanEvent()
|
||||
matches := router.Route(ctx, snap, ev, runNow, cfg.Lister)
|
||||
eventSkipped, eventHalted, eventErr := processMatches(ctx, cfg, runNow, ev, matches)
|
||||
if eventErr != nil {
|
||||
@@ -786,10 +811,10 @@ func processMatches(ctx context.Context, cfg Config, runNow time.Time, ev *reade
|
||||
// "RPC_ERROR" matches the streaming dispatcher's label
|
||||
// (dispatcher/dispatcher.go) so transport failures
|
||||
// aggregate under one outcome key across paths.
|
||||
stats.S3LifecycleDispatchCounter.WithLabelValues(m.Bucket, m.Key.ActionKind.String(), "RPC_ERROR").Inc()
|
||||
countDispatch(cfg.Stats, m.Bucket, m.Key.ActionKind.String(), "RPC_ERROR")
|
||||
return skippedAny, true, nil
|
||||
}
|
||||
stats.S3LifecycleDispatchCounter.WithLabelValues(m.Bucket, m.Key.ActionKind.String(), outcome.String()).Inc()
|
||||
countDispatch(cfg.Stats, m.Bucket, m.Key.ActionKind.String(), outcome.String())
|
||||
switch outcome {
|
||||
case s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
|
||||
|
||||
@@ -126,6 +126,7 @@ func TestRun_HaltedShardDoesNotStarveOthers(t *testing.T) {
|
||||
Persister: persister,
|
||||
Lister: stubSiblingLister{},
|
||||
Now: func() time.Time { return runNow },
|
||||
Stats: &RunStats{},
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
@@ -145,4 +146,11 @@ func TestRun_HaltedShardDoesNotStarveOthers(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
assert.Greater(t, starvedCursor.TsNs, seeded.TsNs, "starved shard's cursor must advance")
|
||||
|
||||
sum := cfg.Stats.Summary()
|
||||
assert.Equal(t, PhaseReplay, sum.Phase)
|
||||
assert.Equal(t, int64(2), sum.EventsScanned, "the halted shard stops after its first event")
|
||||
assert.Equal(t, map[string]int64{"BLOCKED": 1, "DONE": 1}, sum.Outcomes)
|
||||
assert.Zero(t, sum.ShardErrors)
|
||||
assert.Equal(t, 1, sum.ShardsHalted, "a BLOCKED delete halts its shard without an error")
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
)
|
||||
|
||||
// Bounds what a summary carries per pass; the counts stay exact.
|
||||
const (
|
||||
maxReportedBucketFailures = 10
|
||||
maxReportedErrorLen = 256
|
||||
)
|
||||
|
||||
const (
|
||||
PhaseWalk = "walk"
|
||||
PhaseReplay = "replay"
|
||||
)
|
||||
|
||||
type bucketState uint8
|
||||
|
||||
const (
|
||||
bucketSkipped bucketState = iota + 1
|
||||
bucketWalked
|
||||
bucketFailed
|
||||
)
|
||||
|
||||
type BucketFailure struct {
|
||||
Bucket string
|
||||
Error string
|
||||
}
|
||||
|
||||
// RunSummary is a copy of a RunStats at one point in time. A bucket walked
|
||||
// more than once in a pass counts once, as failed if any walk failed.
|
||||
type RunSummary struct {
|
||||
Phase string
|
||||
Bucket string
|
||||
BucketsWalked int
|
||||
BucketsFailed int
|
||||
BucketsSkipped int
|
||||
// The first maxReportedBucketFailures failed buckets.
|
||||
BucketFailures []BucketFailure
|
||||
// Every listed entry, versions and delete markers included.
|
||||
EntriesVisited int64
|
||||
// Distinct object keys among the listed entries.
|
||||
ObjectsVisited int64
|
||||
// Every entry read from the filer, including the ones a walk skips
|
||||
// without visiting (versioned pre-pass, resume start, other shards).
|
||||
EntriesListed int64
|
||||
EventsScanned int64
|
||||
// LifecycleDelete outcomes keyed by the dispatch_total outcome label.
|
||||
// They count RPC results, not reclaimed space.
|
||||
Outcomes map[string]int64
|
||||
ShardErrors int
|
||||
// Shards whose replay stopped on an unresolved delete; their due
|
||||
// events wait for a later pass.
|
||||
ShardsHalted int
|
||||
// Shards whose walk-only rules waited for WalkerInterval.
|
||||
WalksDeferred int
|
||||
}
|
||||
|
||||
// RunStats collects one pass's work. Safe for concurrent use; a nil
|
||||
// *RunStats ignores every call.
|
||||
type RunStats struct {
|
||||
entries atomic.Int64
|
||||
objects atomic.Int64
|
||||
listed atomic.Int64
|
||||
events atomic.Int64
|
||||
|
||||
mu sync.Mutex
|
||||
phase string
|
||||
bucket string
|
||||
buckets map[string]bucketState
|
||||
failures []BucketFailure
|
||||
outcomes map[string]int64
|
||||
shardErrors int
|
||||
shardsHalted int
|
||||
deferred int
|
||||
}
|
||||
|
||||
func (s *RunStats) startBucket(bucket string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.phase, s.bucket = PhaseWalk, bucket
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *RunStats) finishBucket(bucket string, state bucketState, err error) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.buckets == nil {
|
||||
s.buckets = map[string]bucketState{}
|
||||
}
|
||||
prev := s.buckets[bucket]
|
||||
if state <= prev {
|
||||
return
|
||||
}
|
||||
s.buckets[bucket] = state
|
||||
if state == bucketFailed && len(s.failures) < maxReportedBucketFailures {
|
||||
s.failures = append(s.failures, BucketFailure{Bucket: bucket, Error: truncateError(err)})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RunStats) startReplay() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.phase, s.bucket = PhaseReplay, ""
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *RunStats) visitEntry(newObject bool) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.entries.Add(1)
|
||||
if newObject {
|
||||
s.objects.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
// CountListed returns client with its ListEntries results counted as
|
||||
// EntriesListed.
|
||||
func (s *RunStats) CountListed(client filer_pb.SeaweedFilerClient) filer_pb.SeaweedFilerClient {
|
||||
if s == nil || client == nil {
|
||||
return client
|
||||
}
|
||||
return &listCountingClient{SeaweedFilerClient: client, stats: s}
|
||||
}
|
||||
|
||||
type listCountingClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
stats *RunStats
|
||||
}
|
||||
|
||||
func (c *listCountingClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (filer_pb.SeaweedFiler_ListEntriesClient, error) {
|
||||
stream, err := c.SeaweedFilerClient.ListEntries(ctx, in, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &listCountingStream{SeaweedFiler_ListEntriesClient: stream, stats: c.stats}, nil
|
||||
}
|
||||
|
||||
type listCountingStream struct {
|
||||
filer_pb.SeaweedFiler_ListEntriesClient
|
||||
stats *RunStats
|
||||
}
|
||||
|
||||
func (s *listCountingStream) Recv() (*filer_pb.ListEntriesResponse, error) {
|
||||
resp, err := s.SeaweedFiler_ListEntriesClient.Recv()
|
||||
if err == nil && resp.GetEntry() != nil {
|
||||
s.stats.listed.Add(1)
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (s *RunStats) scanEvent() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.events.Add(1)
|
||||
}
|
||||
|
||||
func (s *RunStats) recordOutcome(outcome string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.outcomes == nil {
|
||||
s.outcomes = map[string]int64{}
|
||||
}
|
||||
s.outcomes[outcome]++
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *RunStats) setShardErrors(n int) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.shardErrors = n
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *RunStats) shardHalted() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.shardsHalted++
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *RunStats) walkDeferred() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.deferred++
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *RunStats) Summary() RunSummary {
|
||||
if s == nil {
|
||||
return RunSummary{}
|
||||
}
|
||||
out := RunSummary{
|
||||
EntriesVisited: s.entries.Load(),
|
||||
ObjectsVisited: s.objects.Load(),
|
||||
EntriesListed: s.listed.Load(),
|
||||
EventsScanned: s.events.Load(),
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out.Phase, out.Bucket = s.phase, s.bucket
|
||||
for _, state := range s.buckets {
|
||||
switch state {
|
||||
case bucketWalked:
|
||||
out.BucketsWalked++
|
||||
case bucketFailed:
|
||||
out.BucketsFailed++
|
||||
case bucketSkipped:
|
||||
out.BucketsSkipped++
|
||||
}
|
||||
}
|
||||
out.BucketFailures = append([]BucketFailure(nil), s.failures...)
|
||||
if len(s.outcomes) > 0 {
|
||||
out.Outcomes = make(map[string]int64, len(s.outcomes))
|
||||
for k, v := range s.outcomes {
|
||||
out.Outcomes[k] = v
|
||||
}
|
||||
}
|
||||
out.ShardErrors = s.shardErrors
|
||||
out.ShardsHalted = s.shardsHalted
|
||||
out.WalksDeferred = s.deferred
|
||||
return out
|
||||
}
|
||||
|
||||
func countDispatch(s *RunStats, bucket, kind, outcome string) {
|
||||
stats.S3LifecycleDispatchCounter.WithLabelValues(bucket, kind, outcome).Inc()
|
||||
s.recordOutcome(outcome)
|
||||
}
|
||||
|
||||
func truncateError(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
msg := err.Error()
|
||||
if len(msg) <= maxReportedErrorLen {
|
||||
return msg
|
||||
}
|
||||
return strings.ToValidUTF8(msg[:maxReportedErrorLen], "") + "..."
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/bootstrap"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func allShards() []int {
|
||||
out := make([]int, s3lifecycle.ShardCount)
|
||||
for i := range out {
|
||||
out[i] = i
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestWalkBuckets_RecordsEveryBucketFailure(t *testing.T) {
|
||||
list := func(_ context.Context, bucket, _ string, _ func(*bootstrap.Entry) error) error {
|
||||
if strings.HasPrefix(bucket, "bad") {
|
||||
return errors.New("list " + bucket + " failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
runStats := &RunStats{}
|
||||
err := WalkBuckets(context.Background(), snapshotForBucketRule(t, "good", 7), []int{0},
|
||||
[]string{"bad-a", "good", "bad-b"}, list, &recordingDispatcher{}, runStats)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "bad-a", "the returned error stays the first bucket's")
|
||||
|
||||
sum := runStats.Summary()
|
||||
assert.Equal(t, 1, sum.BucketsWalked)
|
||||
assert.Equal(t, 2, sum.BucketsFailed)
|
||||
assert.Equal(t, 0, sum.BucketsSkipped)
|
||||
require.Len(t, sum.BucketFailures, 2)
|
||||
assert.Equal(t, "bad-a", sum.BucketFailures[0].Bucket)
|
||||
assert.Contains(t, sum.BucketFailures[0].Error, "list bad-a failed")
|
||||
assert.Equal(t, "bad-b", sum.BucketFailures[1].Bucket)
|
||||
assert.Equal(t, PhaseWalk, sum.Phase)
|
||||
assert.Equal(t, "bad-b", sum.Bucket)
|
||||
}
|
||||
|
||||
func TestWalkBuckets_CancelMarksRemainingBucketsSkipped(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
list := func(ctx context.Context, bucket, _ string, _ func(*bootstrap.Entry) error) error {
|
||||
if bucket == "second" {
|
||||
cancel()
|
||||
return ctx.Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
runStats := &RunStats{}
|
||||
err := WalkBuckets(ctx, snapshotForBucketRule(t, "first", 7), []int{0},
|
||||
[]string{"first", "second", "third"}, list, &recordingDispatcher{}, runStats)
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
|
||||
sum := runStats.Summary()
|
||||
assert.Equal(t, 1, sum.BucketsWalked)
|
||||
assert.Equal(t, 0, sum.BucketsFailed, "a cancelled walk is not a bucket failure")
|
||||
assert.Equal(t, 2, sum.BucketsSkipped)
|
||||
assert.Empty(t, sum.BucketFailures)
|
||||
}
|
||||
|
||||
func TestRunStats_FailedWalkWinsAcrossWalksOfOneBucket(t *testing.T) {
|
||||
runStats := &RunStats{}
|
||||
runStats.finishBucket("b", bucketSkipped, nil)
|
||||
runStats.finishBucket("b", bucketWalked, nil)
|
||||
runStats.finishBucket("b", bucketFailed, errors.New("first"))
|
||||
runStats.finishBucket("b", bucketFailed, errors.New("second"))
|
||||
runStats.finishBucket("b", bucketWalked, nil)
|
||||
|
||||
sum := runStats.Summary()
|
||||
assert.Equal(t, 1, sum.BucketsFailed)
|
||||
assert.Equal(t, 0, sum.BucketsWalked)
|
||||
require.Len(t, sum.BucketFailures, 1)
|
||||
assert.Equal(t, "first", sum.BucketFailures[0].Error)
|
||||
}
|
||||
|
||||
func TestRunStats_BoundsReportedFailures(t *testing.T) {
|
||||
runStats := &RunStats{}
|
||||
long := strings.Repeat("x", 2*maxReportedErrorLen)
|
||||
for i := 0; i < maxReportedBucketFailures+5; i++ {
|
||||
runStats.finishBucket("b-"+intToStr(i), bucketFailed, errors.New(long))
|
||||
}
|
||||
sum := runStats.Summary()
|
||||
assert.Equal(t, maxReportedBucketFailures+5, sum.BucketsFailed, "the count stays exact")
|
||||
require.Len(t, sum.BucketFailures, maxReportedBucketFailures)
|
||||
assert.LessOrEqual(t, len(sum.BucketFailures[0].Error), maxReportedErrorLen+len("..."))
|
||||
}
|
||||
|
||||
func TestWalkBuckets_CountsEntriesAndObjects(t *testing.T) {
|
||||
old := time.Now().Add(-90 * 24 * time.Hour)
|
||||
entries := []*bootstrap.Entry{
|
||||
{Path: "a", VersionID: "v3", ModTime: old, IsLatest: true},
|
||||
{Path: "a", VersionID: "v2", ModTime: old},
|
||||
{Path: "a", VersionID: "v1", ModTime: old},
|
||||
{Path: "b", ModTime: old, IsLatest: true},
|
||||
{Path: "dir", IsDirectory: true},
|
||||
{Path: ".uploads/u1", DestKey: "c", IsDirectory: true, IsMPUInit: true, ModTime: old},
|
||||
}
|
||||
runStats := &RunStats{}
|
||||
require.NoError(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "bkt", 7), allShards(),
|
||||
[]string{"bkt"}, bootstrap.EntryCallback(entries), &recordingDispatcher{}, runStats))
|
||||
|
||||
sum := runStats.Summary()
|
||||
assert.Equal(t, int64(5), sum.EntriesVisited, "versions and upload records count, plain directories do not")
|
||||
assert.Equal(t, int64(2), sum.ObjectsVisited, "versions of one key count as one object")
|
||||
assert.Equal(t, 1, sum.BucketsWalked)
|
||||
}
|
||||
|
||||
func TestWalkerDispatcher_CountsOutcomes(t *testing.T) {
|
||||
runStats := &RunStats{}
|
||||
a := sampleAction(t, s3lifecycle.ActionKindExpirationDays)
|
||||
e := &bootstrap.Entry{Path: "obj"}
|
||||
|
||||
d := &WalkerDispatcher{Client: &walkerStubClient{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, Stats: runStats}
|
||||
require.NoError(t, d.Delete(context.Background(), a, e))
|
||||
require.NoError(t, d.Delete(context.Background(), a, e))
|
||||
d.Client = &walkerStubClient{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK}
|
||||
require.NoError(t, d.Delete(context.Background(), a, e))
|
||||
d.Client = &walkerStubClient{err: errors.New("unavailable")}
|
||||
require.Error(t, d.Delete(context.Background(), a, e))
|
||||
d.Client = &walkerStubClient{nilResp: true}
|
||||
require.Error(t, d.Delete(context.Background(), a, e))
|
||||
|
||||
assert.Equal(t, map[string]int64{"DONE": 2, "SKIPPED_OBJECT_LOCK": 1, "RPC_ERROR": 2}, runStats.Summary().Outcomes)
|
||||
}
|
||||
|
||||
func TestProcessMatches_CountsOutcomes(t *testing.T) {
|
||||
runNow := time.Now()
|
||||
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: [8]byte{1}, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
matches := []router.Match{
|
||||
{Key: rule, Bucket: "b", ObjectKey: "a", DueTime: runNow.Add(-time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "b", DueTime: runNow.Add(-time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "c", DueTime: runNow.Add(-time.Hour)},
|
||||
}
|
||||
client := &recordingClient{responses: []s3_lifecycle_pb.LifecycleDeleteOutcome{
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER,
|
||||
}}
|
||||
runStats := &RunStats{}
|
||||
_, halted, err := processMatches(context.Background(), Config{Client: client, Stats: runStats}, runNow, &reader.Event{}, matches)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, halted)
|
||||
assert.Equal(t, map[string]int64{"DONE": 1, "NOOP_RESOLVED": 1, "RETRY_LATER": 1}, runStats.Summary().Outcomes)
|
||||
}
|
||||
|
||||
func TestRunStats_NilIsANoOp(t *testing.T) {
|
||||
var runStats *RunStats
|
||||
runStats.startBucket("b")
|
||||
runStats.finishBucket("b", bucketFailed, errors.New("x"))
|
||||
runStats.startReplay()
|
||||
runStats.visitEntry(true)
|
||||
runStats.scanEvent()
|
||||
runStats.recordOutcome("DONE")
|
||||
runStats.setShardErrors(1)
|
||||
assert.Equal(t, RunSummary{}, runStats.Summary())
|
||||
}
|
||||
|
||||
// A walk can read a bucket without visiting anything: the versioned
|
||||
// pre-pass reads plain files without emitting them, and a resumed walk
|
||||
// skips every key up to its start.
|
||||
func TestRunStats_CountListedCountsSkippedEntries(t *testing.T) {
|
||||
mtime := time.Now().Add(-7 * 24 * time.Hour)
|
||||
client := &fakeFiler{tree: map[string][]*filer_pb.Entry{
|
||||
"/buckets/bkt": {file("a.txt", mtime, 1), file("b.txt", mtime, 1), file("c.txt", mtime, 1)},
|
||||
}}
|
||||
stats := &RunStats{}
|
||||
emitted := 0
|
||||
require.NoError(t, FilerListFunc(stats.CountListed(client), "/buckets", nil)(context.Background(), "bkt", "c.txt", func(*bootstrap.Entry) error {
|
||||
emitted++
|
||||
return nil
|
||||
}))
|
||||
|
||||
assert.Zero(t, emitted)
|
||||
assert.Equal(t, int64(6), stats.Summary().EntriesListed, "both passes over the versioned bucket")
|
||||
var nilStats *RunStats
|
||||
assert.Same(t, client, nilStats.CountListed(client))
|
||||
}
|
||||
@@ -14,12 +14,13 @@ import (
|
||||
// WalkBuckets runs bootstrap.Walk for each bucket using a per-bucket
|
||||
// ListFunc wrapped to drop entries whose ShardID isn't in shards.
|
||||
// Returns the first bucket error; remaining buckets log and continue
|
||||
// so one bucket's filer error doesn't kill the whole walk.
|
||||
// so one bucket's filer error doesn't kill the whole walk. Every
|
||||
// bucket's result goes to runStats when it is non-nil.
|
||||
//
|
||||
// Composable shape: callers (the worker handler) supply a real
|
||||
// filer-backed ListFunc and a real Dispatcher (WalkerDispatcher).
|
||||
// Tests pass bootstrap.EntryCallback and a stub Dispatcher.
|
||||
func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, buckets []string, list bootstrap.ListFunc, dispatch bootstrap.Dispatcher) error {
|
||||
func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, buckets []string, list bootstrap.ListFunc, dispatch bootstrap.Dispatcher, runStats *RunStats) error {
|
||||
if view == nil {
|
||||
return errors.New("WalkBuckets: nil view")
|
||||
}
|
||||
@@ -33,13 +34,26 @@ func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, bucke
|
||||
for _, sh := range shards {
|
||||
shardSet[sh] = true
|
||||
}
|
||||
filtered := perShardListFunc(list, shardSet)
|
||||
filtered := perShardListFunc(list, shardSet, runStats)
|
||||
var firstErr error
|
||||
for _, b := range buckets {
|
||||
for i, b := range buckets {
|
||||
if err := ctx.Err(); err != nil {
|
||||
for _, rest := range buckets[i:] {
|
||||
runStats.finishBucket(rest, bucketSkipped, nil)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if _, err := bootstrap.Walk(ctx, view, b, filtered, dispatch, bootstrap.WalkOptions{}); err != nil {
|
||||
runStats.startBucket(b)
|
||||
_, err := bootstrap.Walk(ctx, view, b, filtered, dispatch, bootstrap.WalkOptions{})
|
||||
switch {
|
||||
case err == nil:
|
||||
runStats.finishBucket(b, bucketWalked, nil)
|
||||
case ctx.Err() != nil:
|
||||
runStats.finishBucket(b, bucketSkipped, nil)
|
||||
default:
|
||||
runStats.finishBucket(b, bucketFailed, err)
|
||||
}
|
||||
if err != nil {
|
||||
if firstErr == nil {
|
||||
firstErr = fmt.Errorf("walk %s: %w", b, err)
|
||||
} else {
|
||||
@@ -57,8 +71,10 @@ func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, bucke
|
||||
// MPU init records carry the user's destination in DestKey, so the
|
||||
// shard predicate must use DestKey there to match what the dispatcher
|
||||
// will send.
|
||||
func perShardListFunc(inner bootstrap.ListFunc, shardSet map[int]bool) bootstrap.ListFunc {
|
||||
func perShardListFunc(inner bootstrap.ListFunc, shardSet map[int]bool, runStats *RunStats) bootstrap.ListFunc {
|
||||
return func(ctx context.Context, bucket, start string, cb func(*bootstrap.Entry) error) error {
|
||||
// Listings emit every version of a key back to back.
|
||||
lastPath := ""
|
||||
return inner(ctx, bucket, start, func(e *bootstrap.Entry) error {
|
||||
if e == nil {
|
||||
return nil
|
||||
@@ -66,6 +82,10 @@ func perShardListFunc(inner bootstrap.ListFunc, shardSet map[int]bool) bootstrap
|
||||
if !shardSet[entryShardID(bucket, e)] {
|
||||
return nil
|
||||
}
|
||||
if !e.IsDirectory || e.IsMPUInit {
|
||||
runStats.visitEntry(!e.IsMPUInit && e.Path != lastPath)
|
||||
lastPath = e.Path
|
||||
}
|
||||
return cb(e)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ func TestWalkBuckets_DispatchesOnlyShardMatchingEntries(t *testing.T) {
|
||||
snap := snapshotForBucketRule(t, bucket, 7) // 30-day-old objects expire
|
||||
d := &recordingDispatcher{}
|
||||
err := WalkBuckets(context.Background(), snap, []int{targetShard}, []string{bucket},
|
||||
bootstrap.EntryCallback(all), d)
|
||||
bootstrap.EntryCallback(all), d, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
gotPaths := make([]string, 0, len(d.calls))
|
||||
@@ -124,9 +124,9 @@ func TestWalkBuckets_DispatchesOnlyShardMatchingEntries(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWalkBuckets_NilGuards(t *testing.T) {
|
||||
require.Error(t, WalkBuckets(context.Background(), nil, []int{0}, nil, bootstrap.EntryCallback(nil), &recordingDispatcher{}))
|
||||
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, nil, &recordingDispatcher{}))
|
||||
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, bootstrap.EntryCallback(nil), nil))
|
||||
require.Error(t, WalkBuckets(context.Background(), nil, []int{0}, nil, bootstrap.EntryCallback(nil), &recordingDispatcher{}, nil))
|
||||
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, nil, &recordingDispatcher{}, nil))
|
||||
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, bootstrap.EntryCallback(nil), nil, nil))
|
||||
}
|
||||
|
||||
func TestWalkBuckets_OneBucketErrorDoesNotStopOthers(t *testing.T) {
|
||||
@@ -141,7 +141,7 @@ func TestWalkBuckets_OneBucketErrorDoesNotStopOthers(t *testing.T) {
|
||||
}
|
||||
|
||||
snap := snapshotForBucketRule(t, "good", 7)
|
||||
err := WalkBuckets(context.Background(), snap, []int{0}, []string{"bad", "good"}, list, &recordingDispatcher{})
|
||||
err := WalkBuckets(context.Background(), snap, []int{0}, []string{"bad", "good"}, list, &recordingDispatcher{}, nil)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, listErr)
|
||||
}
|
||||
@@ -153,7 +153,7 @@ func TestWalkBuckets_HonorsContextCancellationBetweenBuckets(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
err := WalkBuckets(ctx, snapshotForBucketRule(t, "b", 7), []int{0}, []string{"b"},
|
||||
bootstrap.EntryCallback(nil), &recordingDispatcher{})
|
||||
bootstrap.EntryCallback(nil), &recordingDispatcher{}, nil)
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ type WalkerDispatcher struct {
|
||||
// daily-run's processMatches uses so the walker and replay paths
|
||||
// can't combine to burst past the cap. nil disables throttling.
|
||||
Limiter *rate.Limiter
|
||||
// nil skips per-pass outcome counts.
|
||||
Stats *RunStats
|
||||
}
|
||||
|
||||
// Compile-time check.
|
||||
@@ -75,17 +77,17 @@ func (d *WalkerDispatcher) Delete(ctx context.Context, action *engine.CompiledAc
|
||||
if err != nil {
|
||||
// "RPC_ERROR" matches the streaming dispatcher and processMatches
|
||||
// labels so transport-class failures aggregate under one key.
|
||||
stats.S3LifecycleDispatchCounter.WithLabelValues(action.Bucket, kindLabel, "RPC_ERROR").Inc()
|
||||
countDispatch(d.Stats, action.Bucket, kindLabel, "RPC_ERROR")
|
||||
return fmt.Errorf("walker dispatch %s/%s %s: %w", action.Bucket, objectPath, action.Key.ActionKind, err)
|
||||
}
|
||||
if resp == nil {
|
||||
// A misbehaving server stub returning (nil, nil) would panic on
|
||||
// the switch below. Bucket under RPC_ERROR rather than a new
|
||||
// label — operationally it's the same class of failure.
|
||||
stats.S3LifecycleDispatchCounter.WithLabelValues(action.Bucket, kindLabel, "RPC_ERROR").Inc()
|
||||
countDispatch(d.Stats, action.Bucket, kindLabel, "RPC_ERROR")
|
||||
return fmt.Errorf("walker dispatch %s/%s %s: nil response", action.Bucket, objectPath, action.Key.ActionKind)
|
||||
}
|
||||
stats.S3LifecycleDispatchCounter.WithLabelValues(action.Bucket, kindLabel, resp.Outcome.String()).Inc()
|
||||
countDispatch(d.Stats, action.Bucket, kindLabel, resp.Outcome.String())
|
||||
switch resp.Outcome {
|
||||
case s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
|
||||
|
||||
@@ -136,13 +136,16 @@ func TestRunShard_WalkerThrottle(t *testing.T) {
|
||||
runNow2 := runNow.Add(tc.secondPassAfter)
|
||||
closedEvents2 := make(chan *readerEventAlias)
|
||||
close(closedEvents2)
|
||||
cfg.Stats = &RunStats{}
|
||||
require.NoError(t, runShard(context.Background(), cfg, snap, runNow2, 0, closedEvents2, nil))
|
||||
afterPass2, _, _ := p.Load(context.Background(), 0)
|
||||
assert.Equal(t, tc.wantTotalCalls, calls, "walker calls after 2 passes")
|
||||
if tc.wantSecondAdvNs {
|
||||
assert.Equal(t, runNow2.UnixNano(), afterPass2.LastWalkedNs, "throttle allowed the second walk")
|
||||
assert.Zero(t, cfg.Stats.Summary().WalksDeferred)
|
||||
} else {
|
||||
assert.Equal(t, runNow.UnixNano(), afterPass2.LastWalkedNs, "throttle suppressed the second walk; anchor unchanged")
|
||||
assert.Equal(t, 1, cfg.Stats.Summary().WalksDeferred, "a throttled walk leaves its rules unevaluated")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream file
|
||||
includeLastFile := req.InclusiveStartFrom
|
||||
snapshotTsNs := req.SnapshotTsNs
|
||||
if snapshotTsNs == 0 {
|
||||
snapshotTsNs = time.Now().UnixNano()
|
||||
snapshotTsNs = fs.filer.LocalDeliveredThroughTsNs(time.Now().UnixNano())
|
||||
}
|
||||
sentSnapshot := false
|
||||
var listErr error
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
type captureListStream struct {
|
||||
grpc.ServerStream
|
||||
responses []*filer_pb.ListEntriesResponse
|
||||
trailer metadata.MD
|
||||
}
|
||||
|
||||
func (s *captureListStream) Context() context.Context { return context.Background() }
|
||||
|
||||
func (s *captureListStream) Send(resp *filer_pb.ListEntriesResponse) error {
|
||||
s.responses = append(s.responses, resp)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *captureListStream) SetTrailer(md metadata.MD) { s.trailer = md }
|
||||
|
||||
func (s *captureListStream) snapshotTsNs(t *testing.T) int64 {
|
||||
t.Helper()
|
||||
values := s.trailer.Get(filer_pb.ListSnapshotTsNsTrailerKey)
|
||||
if len(values) != 1 {
|
||||
t.Fatalf("snapshot trailer = %v", values)
|
||||
}
|
||||
tsNs, err := strconv.ParseInt(values[0], 10, 64)
|
||||
if err != nil {
|
||||
t.Fatalf("snapshot trailer %q: %v", values[0], err)
|
||||
}
|
||||
return tsNs
|
||||
}
|
||||
|
||||
// A listing snapshot tells the client every event at or below it is in the
|
||||
// listing, so the client drops those events. It must stay below a create that
|
||||
// is stamped but may not be in the store yet, and below every stamp issued
|
||||
// after it, or a create landing right after the listing never reaches the
|
||||
// client's cache.
|
||||
func TestListEntriesSnapshotBelowUnfinishedAndLaterStamps(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
store.entries["/dir"] = newDirectoryEntry("/dir", 100)
|
||||
f := newRenameTestFiler(t, store)
|
||||
fs := &FilerServer{filer: f, option: &FilerOption{DirListingLimit: 1000}}
|
||||
|
||||
inFlightTsNs := f.StampMetaLogInflightForTest()
|
||||
stream := &captureListStream{}
|
||||
if err := fs.ListEntries(&filer_pb.ListEntriesRequest{Directory: "/dir"}, stream); err != nil {
|
||||
t.Fatalf("ListEntries: %v", err)
|
||||
}
|
||||
f.DoneMetaLogInflightForTest(inFlightTsNs)
|
||||
snapshotTsNs := stream.snapshotTsNs(t)
|
||||
if snapshotTsNs >= inFlightTsNs {
|
||||
t.Fatalf("snapshot %d covers the unfinished stamp %d", snapshotTsNs, inFlightTsNs)
|
||||
}
|
||||
|
||||
stream = &captureListStream{}
|
||||
if err := fs.ListEntries(&filer_pb.ListEntriesRequest{Directory: "/dir"}, stream); err != nil {
|
||||
t.Fatalf("ListEntries: %v", err)
|
||||
}
|
||||
snapshotTsNs = stream.snapshotTsNs(t)
|
||||
laterTsNs := f.StampMetaLogInflightForTest()
|
||||
f.DoneMetaLogInflightForTest(laterTsNs)
|
||||
if laterTsNs <= snapshotTsNs {
|
||||
t.Fatalf("stamp %d issued after the listing is not above its snapshot %d", laterTsNs, snapshotTsNs)
|
||||
}
|
||||
}
|
||||
@@ -407,7 +407,11 @@ func (ms *MasterServer) VacuumVolume(ctx context.Context, req *master_pb.VacuumV
|
||||
|
||||
resp := &master_pb.VacuumVolumeResponse{}
|
||||
|
||||
ms.Topo.Vacuum(ms.grpcDialOption, float64(req.GarbageThreshold), ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, req.VolumeId, req.Collection, ms.preallocateSize, false, 0)
|
||||
// A request that lost the vacuum guard to the automatic vacuum or to another
|
||||
// request did nothing. Returning success would tell the caller it ran.
|
||||
if err := ms.Topo.Vacuum(ms.grpcDialOption, float64(req.GarbageThreshold), ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, req.VolumeId, req.Collection, ms.preallocateSize, false, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
@@ -61,7 +61,10 @@ func (ms *MasterServer) volumeVacuumHandler(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
}
|
||||
// glog.Infoln("garbageThreshold =", gcThreshold)
|
||||
ms.Topo.Vacuum(ms.grpcDialOption, gcThreshold, ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, 0, "", ms.preallocateSize, false, 0)
|
||||
if err := ms.Topo.Vacuum(ms.grpcDialOption, gcThreshold, ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, 0, "", ms.preallocateSize, false, 0); err != nil {
|
||||
writeJsonError(w, r, http.StatusConflict, err)
|
||||
return
|
||||
}
|
||||
ms.dirStatusHandler(w, r)
|
||||
}
|
||||
|
||||
|
||||
@@ -34,13 +34,13 @@ func (c *commandS3CircuitBreaker) Help() string {
|
||||
|
||||
# examples
|
||||
# add circuit breaker config for global
|
||||
s3.circuitBreaker -global -type count -actions Read,Write -values 500,200 -apply
|
||||
s3.circuitBreaker -global -type Count -actions Read,Write -values 500,200 -apply
|
||||
|
||||
# disable global config
|
||||
s3.circuitBreaker -global -disable -apply
|
||||
|
||||
# add circuit breaker config for buckets x,y,z
|
||||
s3.circuitBreaker -buckets x,y,z -type count -actions Read,Write -values 200,100 -apply
|
||||
s3.circuitBreaker -buckets x,y,z -type Count -actions Read,Write -values 200,100 -apply
|
||||
|
||||
# disable circuit breaker config of x
|
||||
s3.circuitBreaker -buckets x -disable -apply
|
||||
@@ -207,7 +207,7 @@ func loadConfig(commandEnv *CommandEnv, dir string, file string, buf *bytes.Buff
|
||||
|
||||
func insertOrUpdateValues(cbOptions *s3_pb.S3CircuitBreakerOptions, cmdActions []string, cmdValues []int64, limitType *string) error {
|
||||
if len(*limitType) == 0 {
|
||||
return fmt.Errorf("type not valid, only 'count' and 'bytes' are allowed")
|
||||
return fmt.Errorf("type not valid, only 'Count' and 'MB' are allowed")
|
||||
}
|
||||
|
||||
if cbOptions.Actions == nil {
|
||||
@@ -289,7 +289,7 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, nil, nil, fmt.Errorf("value(%s) of flag[-action] not valid, allowed actions: %v", *actions, s3_constants.AllowedActions)
|
||||
return nil, nil, nil, fmt.Errorf("value(%s) of flag[-actions] not valid, allowed actions: %v", action, s3_constants.AllowedActions)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,7 +307,7 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
|
||||
elements := strings.Split(*values, ",")
|
||||
if len(cmdActions) != len(elements) {
|
||||
if len(elements) != 1 || len(elements) == 0 {
|
||||
return nil, nil, nil, fmt.Errorf("count of flag[-actions] and flag[-counts] not equal")
|
||||
return nil, nil, nil, fmt.Errorf("count of flag[-actions] and flag[-values] not equal")
|
||||
}
|
||||
v, err := strconv.Atoi(elements[0])
|
||||
if err != nil {
|
||||
@@ -333,7 +333,7 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
|
||||
}
|
||||
v, err := parseMBToBytes(elements[0])
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("value of -max must be a legal number(s)")
|
||||
return nil, nil, nil, fmt.Errorf("value of -values must be a legal number(s)")
|
||||
}
|
||||
for range cmdActions {
|
||||
cmdValues = append(cmdValues, v)
|
||||
@@ -342,13 +342,13 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
|
||||
for _, value := range elements {
|
||||
v, err := parseMBToBytes(value)
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("value of -max must be a legal number(s)")
|
||||
return nil, nil, nil, fmt.Errorf("value of -values must be a legal number(s)")
|
||||
}
|
||||
cmdValues = append(cmdValues, v)
|
||||
}
|
||||
}
|
||||
default:
|
||||
return nil, nil, nil, fmt.Errorf("type not valid, only 'count' and 'bytes' are allowed")
|
||||
return nil, nil, nil, fmt.Errorf("type not valid, only 'Count' and 'MB' are allowed")
|
||||
}
|
||||
} else {
|
||||
*limitType = ""
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Every example in the s3.circuitBreaker help text has to run as written.
|
||||
func TestCircuitBreakerHelpExamplesRun(t *testing.T) {
|
||||
originalLoadConfig := LoadConfig
|
||||
t.Cleanup(func() { LoadConfig = originalLoadConfig })
|
||||
LoadConfig = func(*CommandEnv, string, string, *bytes.Buffer) error { return nil }
|
||||
|
||||
cmd := &commandS3CircuitBreaker{}
|
||||
examples := 0
|
||||
for _, line := range strings.Split(cmd.Help(), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 0 || fields[0] != cmd.Name() {
|
||||
continue
|
||||
}
|
||||
examples++
|
||||
// Leave out -apply: it saves the result inside the filer.
|
||||
var args []string
|
||||
for _, f := range fields[1:] {
|
||||
if f != "-apply" {
|
||||
args = append(args, f)
|
||||
}
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := cmd.Do(args, nil, &out); err != nil {
|
||||
t.Errorf("%s: %v", strings.TrimSpace(line), err)
|
||||
}
|
||||
}
|
||||
if examples == 0 {
|
||||
t.Fatal("found no examples in the help text")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCircuitBreakerInvalidActionError(t *testing.T) {
|
||||
originalLoadConfig := LoadConfig
|
||||
t.Cleanup(func() { LoadConfig = originalLoadConfig })
|
||||
LoadConfig = func(*CommandEnv, string, string, *bytes.Buffer) error { return nil }
|
||||
|
||||
cmd := &commandS3CircuitBreaker{}
|
||||
err := cmd.Do([]string{"-global", "-type", "Count", "-actions", "Read,Bogus", "-values", "1,2"}, nil, &bytes.Buffer{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for an unknown action")
|
||||
}
|
||||
if msg := err.Error(); !strings.Contains(msg, "value(Bogus)") || !strings.Contains(msg, "flag[-actions]") {
|
||||
t.Errorf("error should name the bad action and -actions: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@ package shell
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type Case struct {
|
||||
@@ -256,6 +259,8 @@ var (
|
||||
func TestCircuitBreakerShell(t *testing.T) {
|
||||
var writeBuf bytes.Buffer
|
||||
cmd := &commandS3CircuitBreaker{}
|
||||
originalLoadConfig := LoadConfig
|
||||
t.Cleanup(func() { LoadConfig = originalLoadConfig })
|
||||
LoadConfig = func(commandEnv *CommandEnv, dir string, file string, buf *bytes.Buffer) error {
|
||||
_, err := buf.Write(writeBuf.Bytes())
|
||||
if err != nil {
|
||||
@@ -270,23 +275,20 @@ func TestCircuitBreakerShell(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if i != 0 {
|
||||
result := writeBuf.String()
|
||||
|
||||
actual := make(map[string]interface{})
|
||||
err := json.Unmarshal([]byte(result), &actual)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
expect := make(map[string]interface{})
|
||||
err = json.Unmarshal([]byte(result), &expect)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if !reflect.DeepEqual(actual, expect) {
|
||||
t.Fatal("result of s3 circuit breaker shell command is unexpected!")
|
||||
}
|
||||
// Compare as configs: the command writes default fields such as
|
||||
// "enabled": false that the expected JSON leaves out.
|
||||
actual := &s3_pb.S3CircuitBreakerConfig{}
|
||||
if err := filer.ParseS3ConfigurationFromBytes(writeBuf.Bytes(), actual); err != nil {
|
||||
t.Fatalf("case %d %v: parse output: %v", i, tc.args, err)
|
||||
}
|
||||
// Strict parsing, so a misspelled field in the expected JSON fails.
|
||||
expect := &s3_pb.S3CircuitBreakerConfig{}
|
||||
if err := protojson.Unmarshal([]byte(tc.result), expect); err != nil {
|
||||
t.Fatalf("case %d: parse expected result: %v", i, err)
|
||||
}
|
||||
if !proto.Equal(actual, expect) {
|
||||
t.Fatalf("case %d %v:\ngot %v\nwant %v", i, tc.args, actual, expect)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,7 @@ func (c *commandS3LifecycleRunShard) Do(args []string, env *CommandEnv, writer i
|
||||
}
|
||||
walker := dailyrun.WalkerFunc(func(walkCtx context.Context, view *engine.Snapshot, shards []int) error {
|
||||
return dailyrun.WalkBuckets(walkCtx, view, shards, buckets,
|
||||
dailyrun.FilerListFunc(filerClient, bucketsPath, view), walkerDispatch)
|
||||
dailyrun.FilerListFunc(filerClient, bucketsPath, view), walkerDispatch, nil)
|
||||
})
|
||||
return dailyrun.Run(passCtx, dailyrun.Config{
|
||||
Shards: shards,
|
||||
|
||||
@@ -38,6 +38,10 @@ func (c *commandVacuum) Help() string {
|
||||
Without -volumeId this runs the same sweep as the automatic vacuum, which skips
|
||||
read-only volumes. Name a read-only volume with -volumeId to vacuum it anyway.
|
||||
|
||||
The master runs one vacuum at a time. While the automatic vacuum or another
|
||||
request is running, this command fails instead of waiting for its turn. Run it
|
||||
again later, or pause the automatic vacuum first with volume.vacuum.disable.
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
@@ -157,13 +161,27 @@ func (c *commandVacuum) Do(args []string, commandEnv *CommandEnv, writer io.Writ
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
// A list of volumes or collections is several requests, and a vacuum
|
||||
// that starts in between only fails the ones after it.
|
||||
return fmt.Errorf("vacuum %s: %w", describeVacuumRequest(req), err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func describeVacuumRequest(req *master_pb.VacuumVolumeRequest) string {
|
||||
switch {
|
||||
case req.VolumeId != 0 && req.Collection != "":
|
||||
return fmt.Sprintf("volume %d in collection %s", req.VolumeId, req.Collection)
|
||||
case req.VolumeId != 0:
|
||||
return fmt.Sprintf("volume %d", req.VolumeId)
|
||||
case req.Collection != "":
|
||||
return "collection " + req.Collection
|
||||
}
|
||||
return "all volumes"
|
||||
}
|
||||
|
||||
// vidReplica pairs a volume replica's read-only state with the server that
|
||||
// reports it, so the unnamed-collection sweep can reproduce the master's
|
||||
// low-disk-space exception client-side.
|
||||
|
||||
@@ -954,6 +954,18 @@ var (
|
||||
Help: "Per-shard timestamp (UnixNano) of the most recent successful walker fire. 0 means the shard hasn't completed a walk yet.",
|
||||
}, []string{"shard"})
|
||||
|
||||
// S3LifecycleDailyRunLastFullPassTimestampSeconds is when the last
|
||||
// lifecycle pass that covered every shard and every lifecycle policy
|
||||
// without an error finished. Partial, failed and cancelled passes leave
|
||||
// it alone, unlike the per-shard cursor and walk gauges.
|
||||
S3LifecycleDailyRunLastFullPassTimestampSeconds = prometheus.NewGauge(
|
||||
prometheus.GaugeOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: subsystemS3Lifecycle,
|
||||
Name: "daily_run_last_full_pass_timestamp_seconds",
|
||||
Help: "Unix time the last fully successful lifecycle pass finished. 0 means none is known yet.",
|
||||
})
|
||||
|
||||
AdminMaintenanceTasksByStatus = prometheus.NewGaugeVec(
|
||||
prometheus.GaugeOpts{
|
||||
Namespace: Namespace,
|
||||
@@ -1141,6 +1153,7 @@ func init() {
|
||||
Gather.MustRegister(S3LifecycleDailyRunShardDurationSeconds)
|
||||
Gather.MustRegister(S3LifecycleDailyRunEventsScanned)
|
||||
Gather.MustRegister(S3LifecycleDailyRunLastWalkedNs)
|
||||
Gather.MustRegister(S3LifecycleDailyRunLastFullPassTimestampSeconds)
|
||||
|
||||
Gather.MustRegister(UploadErrorCounter)
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package topology
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -255,13 +256,22 @@ func (t *Topology) batchVacuumVolumeCleanup(grpcDialOption grpc.DialOption, vl *
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float64, maxParallelVacuumPerServer int, maxParallelVacuumPerRack int, volumeId uint32, collection string, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) {
|
||||
// ErrVacuumRunning is what Vacuum returns when another vacuum holds the
|
||||
// topology-wide guard. The request was dropped, not queued: nothing waits for
|
||||
// the running vacuum, so the caller has to ask again.
|
||||
var ErrVacuumRunning = errors.New("another vacuum is running, try again later")
|
||||
|
||||
// Vacuum runs one vacuum at a time. A call that finds another one running,
|
||||
// the automatic vacuum or an earlier request, does nothing and returns
|
||||
// ErrVacuumRunning, so that a request for a volume cannot look done when it
|
||||
// never started.
|
||||
func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float64, maxParallelVacuumPerServer int, maxParallelVacuumPerRack int, volumeId uint32, collection string, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) error {
|
||||
|
||||
// if there is vacuum going on, return immediately
|
||||
swapped := atomic.CompareAndSwapInt64(&t.vacuumLockCounter, 0, 1)
|
||||
if !swapped {
|
||||
glog.V(0).Infof("Vacuum is already running")
|
||||
return
|
||||
return ErrVacuumRunning
|
||||
}
|
||||
defer atomic.StoreInt64(&t.vacuumLockCounter, 0)
|
||||
|
||||
@@ -301,6 +311,7 @@ func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Topology) vacuumOneVolumeLayout(grpcDialOption grpc.DialOption, volumeLayout *VolumeLayout, c *Collection, garbageThreshold float64, maxParallelVacuumPerServer int, maxParallelVacuumPerRack int, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) {
|
||||
|
||||
@@ -518,6 +518,83 @@ func TestVacuumStalledVolumeServerReleasesGuard(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A request that finds another vacuum running is dropped, not queued. It has
|
||||
// to say so: returning as if it had run leaves the caller believing its volume
|
||||
// was compacted.
|
||||
func TestVacuumReportsAnotherVacuumRunning(t *testing.T) {
|
||||
fake := &fakeVacuumServer{
|
||||
checks: map[uint32]*volume_server_pb.VacuumVolumeCheckResponse{
|
||||
1: {GarbageRatio: 0.9},
|
||||
2: {GarbageRatio: 0.9},
|
||||
},
|
||||
entered: make(chan string, 1),
|
||||
compactGate: make(chan struct{}),
|
||||
compactTracker: &compactTracker{},
|
||||
}
|
||||
grpcPort, dialOption := startFakeVolumeServer(t, fake)
|
||||
|
||||
topo := NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5, false)
|
||||
dn := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
|
||||
GetOrCreateDataNode("127.0.0.1", 8080, grpcPort, "127.0.0.1", "dn", map[string]uint32{"": 10})
|
||||
var volumes []storage.VolumeInfo
|
||||
for vid := 1; vid <= 2; vid++ {
|
||||
volumes = append(volumes, storage.VolumeInfo{
|
||||
Id: needle.VolumeId(vid),
|
||||
Size: 1 << 20,
|
||||
Collection: "c",
|
||||
ModifiedAtSecond: time.Now().Unix(),
|
||||
Version: needle.GetCurrentVersion(),
|
||||
ReplicaPlacement: &super_block.ReplicaPlacement{},
|
||||
Ttl: needle.EMPTY_TTL,
|
||||
})
|
||||
}
|
||||
dn.UpdateVolumes(volumes)
|
||||
for _, v := range volumes {
|
||||
topo.RegisterVolumeLayout(v, dn)
|
||||
}
|
||||
committed := func() []uint32 {
|
||||
fake.mu.Lock()
|
||||
defer fake.mu.Unlock()
|
||||
return append([]uint32(nil), fake.committed...)
|
||||
}
|
||||
|
||||
// the first request holds the guard for as long as its compaction is gated
|
||||
first := make(chan error, 1)
|
||||
go func() {
|
||||
first <- topo.Vacuum(dialOption, 0.3, 1, 0, 1, "c", 0, false, 0)
|
||||
}()
|
||||
select {
|
||||
case <-fake.entered:
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("the first vacuum never reached the compact phase")
|
||||
}
|
||||
|
||||
if err := topo.Vacuum(dialOption, 0.3, 1, 0, 2, "c", 0, false, 0); !errors.Is(err, ErrVacuumRunning) {
|
||||
t.Fatalf("vacuum of volume 2 while volume 1 is compacting: err = %v, want ErrVacuumRunning", err)
|
||||
}
|
||||
if got := committed(); len(got) != 0 {
|
||||
t.Fatalf("committed volumes = %v, want none while the first vacuum is gated", got)
|
||||
}
|
||||
|
||||
close(fake.compactGate)
|
||||
select {
|
||||
case err := <-first:
|
||||
if err != nil {
|
||||
t.Fatalf("the first vacuum: %v", err)
|
||||
}
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("the first vacuum did not finish after the gate opened")
|
||||
}
|
||||
|
||||
// with the guard free again, the same request runs
|
||||
if err := topo.Vacuum(dialOption, 0.3, 1, 0, 2, "c", 0, false, 0); err != nil {
|
||||
t.Fatalf("vacuum of volume 2 after the first one finished: %v", err)
|
||||
}
|
||||
if got := committed(); len(got) != 2 || got[0] != 1 || got[1] != 2 {
|
||||
t.Fatalf("committed volumes = %v, want [1 2]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A replica tiered to remote storage is never compacted by a vacuum, not even
|
||||
// on an explicit request with a zero threshold: its .dat is the remote object.
|
||||
// volume.tier.compact is the way to reclaim its garbage.
|
||||
|
||||
@@ -2,6 +2,7 @@ package s3_lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"golang.org/x/time/rate"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
@@ -248,34 +250,43 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
|
||||
return fmt.Errorf("buckets path: %w", err)
|
||||
}
|
||||
|
||||
dialCtx, dialCancel = context.WithTimeout(runCtx, 30*time.Second)
|
||||
s3Conn, err := pb.GrpcDial(dialCtx, s3Endpoints[0], false, h.grpcDialOption)
|
||||
dialCancel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial s3 %s: %w", s3Endpoints[0], err)
|
||||
s3Conn, s3Endpoint, skipped := h.selectS3Front(runCtx, s3Endpoints)
|
||||
if s3Conn == nil {
|
||||
return noReadyS3Error(skipped)
|
||||
}
|
||||
defer s3Conn.Close()
|
||||
if len(skipped) > 0 {
|
||||
skippedErr := errors.Join(skipped...)
|
||||
glog.Warningf("s3 lifecycle: using s3 %s, skipped: %v", s3Endpoint, skippedErr)
|
||||
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
|
||||
JobId: request.Job.JobId, JobType: jobType,
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "starting",
|
||||
Message: fmt.Sprintf("using s3 %s, skipped: %v", s3Endpoint, skippedErr),
|
||||
})
|
||||
}
|
||||
rpc := s3_lifecycle_pb.NewSeaweedS3LifecycleInternalClient(s3Conn)
|
||||
|
||||
if err := h.executeDailyReplay(runCtx, request, bucketsPath, filerClient, rpc, cfg, sender); err != nil {
|
||||
report, err := h.executeDailyReplay(runCtx, request, bucketsPath, filerClient, rpc, cfg, sender)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return sendSuccessCompletion(request, sender)
|
||||
return sendCompletion(request, sender, report)
|
||||
}
|
||||
|
||||
const dailyReplaySuccessSummary = "s3 lifecycle daily replay completed"
|
||||
|
||||
// JobCompleted must set JobType to the handler's jobType constant;
|
||||
// routed requests may leave request.Job.JobType empty, and the admin
|
||||
// ignores completions with empty JobType.
|
||||
func sendSuccessCompletion(request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender) error {
|
||||
// ignores completions with empty JobType. Failed passes carry their
|
||||
// result too, so every bucket failure stays in the job record.
|
||||
func sendCompletion(request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender, report *runReport) error {
|
||||
return sender.SendCompleted(&plugin_pb.JobCompleted{
|
||||
JobId: request.Job.JobId,
|
||||
JobType: jobType,
|
||||
Success: true,
|
||||
JobId: request.Job.JobId,
|
||||
JobType: jobType,
|
||||
Success: report.err == nil,
|
||||
ErrorMessage: report.errorMessage(),
|
||||
Result: &plugin_pb.JobResult{
|
||||
Summary: dailyReplaySuccessSummary,
|
||||
Summary: report.summaryLine(),
|
||||
OutputValues: report.outputValues(),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -283,14 +294,17 @@ func sendSuccessCompletion(request *plugin_pb.ExecuteJobRequest, sender pluginwo
|
||||
// executeDailyReplay runs one bounded daily-replay pass via
|
||||
// dailyrun.Run. The walker fires inside runShard on rule-content edits
|
||||
// and against the steady-state walk view; all rule kinds are serviced.
|
||||
func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.ExecuteJobRequest, bucketsPath string, filerClient filer_pb.SeaweedFilerClient, rpc s3_lifecycle_pb.SeaweedS3LifecycleInternalClient, cfg Config, sender pluginworker.ExecutionSender) error {
|
||||
// The returned error covers setup only; the pass's own error is in the
|
||||
// report.
|
||||
func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.ExecuteJobRequest, bucketsPath string, filerClient filer_pb.SeaweedFilerClient, rpc s3_lifecycle_pb.SeaweedS3LifecycleInternalClient, cfg Config, sender pluginworker.ExecutionSender) (*runReport, error) {
|
||||
startedAt := time.Now()
|
||||
eng := engine.New()
|
||||
inputs, parseErrors, err := scheduler.LoadCompileInputs(ctx, filerClient, bucketsPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("daily_replay: load lifecycle inputs: %w", err)
|
||||
return nil, fmt.Errorf("daily_replay: load lifecycle inputs: %w", err)
|
||||
}
|
||||
for _, pe := range parseErrors {
|
||||
glog.V(1).Infof("daily_replay: %s: %v", pe.Bucket, pe.Err)
|
||||
glog.Warningf("daily_replay: invalid lifecycle policy on bucket %s: %v", pe.Bucket, pe.Err)
|
||||
}
|
||||
eng.Compile(inputs, engine.CompileOptions{PriorStates: scheduler.AllActivePriorStates(inputs)})
|
||||
|
||||
@@ -313,28 +327,34 @@ func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.Exe
|
||||
buckets = append(buckets, in.Bucket)
|
||||
}
|
||||
}
|
||||
persister := &dailyrun.FilerCursorPersister{Store: dispatcher.NewFilerStoreClient(filerClient)}
|
||||
report := &runReport{bucketsTotal: len(buckets) + len(parseErrors), invalidPolicies: parseErrors}
|
||||
loadLastFullPass(ctx, persister, report)
|
||||
|
||||
runStats := &dailyrun.RunStats{}
|
||||
// Share the limiter with processMatches so walker + replay can't
|
||||
// combine to burst past the cluster cap.
|
||||
walkerDispatch := &dailyrun.WalkerDispatcher{Client: client, Limiter: limiter}
|
||||
walkerDispatch := &dailyrun.WalkerDispatcher{Client: client, Limiter: limiter, Stats: runStats}
|
||||
walker := dailyrun.WalkerFunc(func(walkCtx context.Context, view *engine.Snapshot, shards []int) error {
|
||||
return dailyrun.WalkBuckets(walkCtx, view, shards, buckets,
|
||||
dailyrun.FilerListFunc(filerClient, bucketsPath, view), walkerDispatch)
|
||||
dailyrun.FilerListFunc(runStats.CountListed(filerClient), bucketsPath, view), walkerDispatch, runStats)
|
||||
})
|
||||
|
||||
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
|
||||
JobId: request.Job.JobId, JobType: jobType,
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "starting",
|
||||
Message: fmt.Sprintf("daily_replay shards=%d workers=%d rate=%s buckets=%d walker=on",
|
||||
len(shards), cfg.Workers, limiterDesc, len(buckets)),
|
||||
Message: fmt.Sprintf("daily_replay shards=%d workers=%d rate=%s buckets=%d invalid_policies=%d walker=on",
|
||||
len(shards), cfg.Workers, limiterDesc, len(buckets), len(parseErrors)),
|
||||
})
|
||||
|
||||
runErr := dailyrun.Run(ctx, dailyrun.Config{
|
||||
stopProgress := startProgressReporter(request, sender, runStats.Summary, progressInterval)
|
||||
report.err = dailyrun.Run(ctx, dailyrun.Config{
|
||||
Shards: shards,
|
||||
BucketsPath: bucketsPath,
|
||||
Engine: eng,
|
||||
FilerClient: filerClient,
|
||||
Client: client,
|
||||
Persister: &dailyrun.FilerCursorPersister{Store: dispatcher.NewFilerStoreClient(filerClient)},
|
||||
Persister: persister,
|
||||
Lister: dispatcher.NewFilerSiblingLister(filerClient, bucketsPath),
|
||||
Workers: cfg.Workers,
|
||||
Limiter: limiter,
|
||||
@@ -342,12 +362,51 @@ func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.Exe
|
||||
Walker: walker,
|
||||
WalkerInterval: cfg.WalkerInterval,
|
||||
ClientName: "worker-s3-lifecycle-daily",
|
||||
Stats: runStats,
|
||||
})
|
||||
if runErr != nil {
|
||||
glog.Warningf("daily_replay: %v", runErr)
|
||||
return runErr
|
||||
stopProgress()
|
||||
report.canceled = ctx.Err() != nil
|
||||
report.elapsed = time.Since(startedAt)
|
||||
report.summary = runStats.Summary()
|
||||
if report.err != nil {
|
||||
glog.Warningf("daily_replay: %v", report.err)
|
||||
}
|
||||
return nil
|
||||
recordFullPass(ctx, persister, report, startedAt)
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func loadLastFullPass(ctx context.Context, persister *dailyrun.FilerCursorPersister, report *runReport) {
|
||||
fp, found, err := persister.LoadFullPass(ctx)
|
||||
if err != nil {
|
||||
glog.Warningf("daily_replay: %v", err)
|
||||
return
|
||||
}
|
||||
if found {
|
||||
report.lastFullPass = fp.CompletedAt
|
||||
publishFullPass(fp)
|
||||
}
|
||||
}
|
||||
|
||||
// recordFullPass advances the full-pass record only when the pass
|
||||
// covered every shard and every policy.
|
||||
func recordFullPass(ctx context.Context, persister *dailyrun.FilerCursorPersister, report *runReport, startedAt time.Time) {
|
||||
if !report.fullPass() {
|
||||
return
|
||||
}
|
||||
fp := dailyrun.FullPass{StartedAt: startedAt.UTC(), CompletedAt: time.Now().UTC()}
|
||||
saveCtx, saveCancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer saveCancel()
|
||||
if err := persister.SaveFullPass(saveCtx, fp); err != nil {
|
||||
glog.Warningf("daily_replay: %v", err)
|
||||
report.fullPassSaveErr = err
|
||||
return
|
||||
}
|
||||
report.lastFullPass = fp.CompletedAt
|
||||
publishFullPass(fp)
|
||||
}
|
||||
|
||||
func publishFullPass(fp dailyrun.FullPass) {
|
||||
stats.S3LifecycleDailyRunLastFullPassTimestampSeconds.Set(float64(fp.CompletedAt.UnixNano()) / 1e9)
|
||||
}
|
||||
|
||||
// buildLimiterFromClusterContext parses the per-worker share the admin
|
||||
@@ -404,8 +463,9 @@ func parsePositiveInt(s string) (int, bool) {
|
||||
}
|
||||
|
||||
// clusterS3Endpoints returns the master-discovered S3 gRPC addresses for the
|
||||
// cluster. The handler dials the first reachable one; the master refreshes
|
||||
// the list on KeepConnected so a stale entry self-heals on the next run.
|
||||
// cluster. The handler uses the first one that passes checkLifecycleReady;
|
||||
// the master refreshes the list on KeepConnected so a stale entry self-heals
|
||||
// on the next run.
|
||||
func clusterS3Endpoints(cc *plugin_pb.ClusterContext) []string {
|
||||
if cc == nil {
|
||||
return nil
|
||||
|
||||
@@ -4,10 +4,16 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
@@ -468,15 +474,15 @@ func TestExecute_EmptyJobTypeAccepted(t *testing.T) {
|
||||
assert.Contains(t, err.Error(), "no s3 servers", "validation flowed past the type check")
|
||||
}
|
||||
|
||||
// ---------- sendSuccessCompletion ----------
|
||||
// ---------- sendCompletion ----------
|
||||
|
||||
func TestSendSuccessCompletion_EmitsCanonicalCompletion(t *testing.T) {
|
||||
func TestSendCompletion_EmitsCanonicalCompletion(t *testing.T) {
|
||||
sender := &recordingExecSender{}
|
||||
request := &plugin_pb.ExecuteJobRequest{
|
||||
Job: &plugin_pb.JobSpec{JobId: "job-123"}, // empty JobType (broadcast routing)
|
||||
}
|
||||
|
||||
require.NoError(t, sendSuccessCompletion(request, sender))
|
||||
require.NoError(t, sendCompletion(request, sender, &runReport{bucketsTotal: 2}))
|
||||
|
||||
require.Len(t, sender.completed, 1, "exactly one completion must be sent")
|
||||
c := sender.completed[0]
|
||||
@@ -484,20 +490,140 @@ func TestSendSuccessCompletion_EmitsCanonicalCompletion(t *testing.T) {
|
||||
assert.NotEmpty(t, c.JobType, "an empty JobType is dropped by the admin")
|
||||
assert.Equal(t, "job-123", c.JobId, "completion must echo the original JobId")
|
||||
assert.True(t, c.Success, "a clean replay is a success completion")
|
||||
assert.Empty(t, c.ErrorMessage)
|
||||
require.NotNil(t, c.Result)
|
||||
assert.NotEmpty(t, c.Result.Summary, "admin UI surfaces a non-empty Result.Summary")
|
||||
assert.True(t, strings.HasPrefix(c.Result.Summary, "s3 lifecycle daily replay completed:"), c.Result.Summary)
|
||||
assert.Equal(t, runStatusComplete, c.Result.OutputValues["status"].GetStringValue())
|
||||
assert.Equal(t, int64(2), c.Result.OutputValues["buckets_total"].GetInt64Value())
|
||||
}
|
||||
|
||||
func TestSendSuccessCompletion_PropagatesSendError(t *testing.T) {
|
||||
func TestSendCompletion_PropagatesSendError(t *testing.T) {
|
||||
sentinel := errors.New("stream closed")
|
||||
sender := &recordingExecSender{completedErr: sentinel}
|
||||
request := &plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{JobId: "job-456"}}
|
||||
|
||||
err := sendSuccessCompletion(request, sender)
|
||||
err := sendCompletion(request, sender, &runReport{})
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, sentinel)
|
||||
}
|
||||
|
||||
func TestSendCompletion_FailedPassKeepsEveryBucketFailure(t *testing.T) {
|
||||
sender := &recordingExecSender{}
|
||||
report := &runReport{
|
||||
err: errors.New("shard=3: steady walk: walk bad-a: filer down"),
|
||||
bucketsTotal: 3,
|
||||
summary: dailyrun.RunSummary{
|
||||
BucketsWalked: 1,
|
||||
BucketsFailed: 2,
|
||||
BucketFailures: []dailyrun.BucketFailure{
|
||||
{Bucket: "bad-a", Error: "filer down"},
|
||||
{Bucket: "bad-b", Error: "outcome=BLOCKED"},
|
||||
},
|
||||
Outcomes: map[string]int64{"DONE": 4, "RPC_ERROR": 1},
|
||||
},
|
||||
}
|
||||
require.NoError(t, sendCompletion(&plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{JobId: "j"}}, sender, report))
|
||||
|
||||
require.Len(t, sender.completed, 1)
|
||||
c := sender.completed[0]
|
||||
assert.False(t, c.Success)
|
||||
assert.Contains(t, c.ErrorMessage, "walk bad-a: filer down")
|
||||
assert.Contains(t, c.ErrorMessage, "2 of 3 buckets failed")
|
||||
require.NotNil(t, c.Result, "a failed pass still reports its result")
|
||||
values := c.Result.OutputValues
|
||||
assert.Equal(t, runStatusFailed, values["status"].GetStringValue())
|
||||
assert.Equal(t, int64(2), values["buckets_failed"].GetInt64Value())
|
||||
assert.Equal(t, []string{"bad-a: filer down", "bad-b: outcome=BLOCKED"}, values["bucket_failures"].GetStringList().GetValues())
|
||||
assert.Equal(t, int64(4), values["rpc_done"].GetInt64Value())
|
||||
assert.Equal(t, int64(1), values["rpc_error"].GetInt64Value())
|
||||
assert.True(t, strings.HasPrefix(c.Result.Summary, "s3 lifecycle daily replay failed:"), c.Result.Summary)
|
||||
}
|
||||
|
||||
func TestRunReport_InvalidPolicyIsPartial(t *testing.T) {
|
||||
report := &runReport{
|
||||
bucketsTotal: 2,
|
||||
invalidPolicies: []scheduler.ParseError{{Bucket: "broken", Err: errors.New("bad xml")}},
|
||||
}
|
||||
assert.Equal(t, runStatusPartial, report.status())
|
||||
assert.True(t, strings.HasPrefix(report.summaryLine(), "s3 lifecycle daily replay partial:"), report.summaryLine())
|
||||
assert.Contains(t, report.summaryLine(), "invalid_policies=1")
|
||||
values := report.outputValues()
|
||||
assert.Equal(t, int64(1), values["invalid_policies"].GetInt64Value())
|
||||
assert.Equal(t, []string{"broken: bad xml"}, values["invalid_policy_buckets"].GetStringList().GetValues())
|
||||
}
|
||||
|
||||
func TestRunReport_CanceledWinsOverError(t *testing.T) {
|
||||
report := &runReport{canceled: true, err: context.Canceled}
|
||||
assert.Equal(t, runStatusCanceled, report.status())
|
||||
report.err = nil
|
||||
assert.Equal(t, runStatusCanceled, report.status(), "a drain cut short returns no error")
|
||||
}
|
||||
|
||||
// ---------- full pass record ----------
|
||||
|
||||
type memFilerStore struct {
|
||||
files map[string][]byte
|
||||
saveErr error
|
||||
}
|
||||
|
||||
func (s *memFilerStore) Read(_ context.Context, dir, name string) ([]byte, error) {
|
||||
b, ok := s.files[dir+"/"+name]
|
||||
if !ok {
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (s *memFilerStore) Save(_ context.Context, dir, name string, content []byte) error {
|
||||
if s.saveErr != nil {
|
||||
return s.saveErr
|
||||
}
|
||||
s.files[dir+"/"+name] = content
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestRecordFullPass_OnlyACompletePassAdvances(t *testing.T) {
|
||||
previous := dailyrun.FullPass{StartedAt: time.Unix(1_700_000_000, 0).UTC(), CompletedAt: time.Unix(1_700_000_600, 0).UTC()}
|
||||
for name, report := range map[string]*runReport{
|
||||
"failed": {err: errors.New("walk failed")},
|
||||
"canceled": {canceled: true},
|
||||
"partial": {invalidPolicies: []scheduler.ParseError{{Bucket: "b", Err: errors.New("bad")}}},
|
||||
"halted": {summary: dailyrun.RunSummary{ShardsHalted: 1}},
|
||||
"deferred": {summary: dailyrun.RunSummary{WalksDeferred: 16}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
persister := &dailyrun.FilerCursorPersister{Store: &memFilerStore{files: map[string][]byte{}}}
|
||||
require.NoError(t, persister.SaveFullPass(context.Background(), previous))
|
||||
loadLastFullPass(context.Background(), persister, report)
|
||||
recordFullPass(context.Background(), persister, report, time.Now())
|
||||
|
||||
got, found, err := persister.LoadFullPass(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
assert.Equal(t, previous, got)
|
||||
assert.Equal(t, previous.CompletedAt, report.lastFullPass)
|
||||
assert.Equal(t, "2023-11-14T22:23:20Z", report.outputValues()["last_full_pass_at"].GetStringValue())
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("complete", func(t *testing.T) {
|
||||
persister := &dailyrun.FilerCursorPersister{Store: &memFilerStore{files: map[string][]byte{}}}
|
||||
require.NoError(t, persister.SaveFullPass(context.Background(), previous))
|
||||
report := &runReport{}
|
||||
startedAt := time.Now().Add(-time.Minute)
|
||||
recordFullPass(context.Background(), persister, report, startedAt)
|
||||
|
||||
got, found, err := persister.LoadFullPass(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
assert.True(t, got.CompletedAt.After(previous.CompletedAt))
|
||||
assert.Equal(t, startedAt.UTC(), got.StartedAt)
|
||||
assert.Equal(t, got.CompletedAt, report.lastFullPass)
|
||||
assert.InDelta(t, float64(got.CompletedAt.UnixNano())/1e9,
|
||||
testutil.ToFloat64(stats.S3LifecycleDailyRunLastFullPassTimestampSeconds), 1e-3)
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- lookupBucketsPath ----------
|
||||
|
||||
// stubFilerConfigClient implements filer_pb.SeaweedFilerClient for the
|
||||
@@ -548,3 +674,19 @@ func TestLookupBucketsPath_EmptyDirBucketsFallsBackToDefault(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/buckets", got)
|
||||
}
|
||||
|
||||
func TestRecordFullPass_FailedSaveKeepsThePreviousTimestamp(t *testing.T) {
|
||||
store := &memFilerStore{files: map[string][]byte{}}
|
||||
persister := &dailyrun.FilerCursorPersister{Store: store}
|
||||
previous := dailyrun.FullPass{StartedAt: time.Unix(1_700_000_000, 0).UTC(), CompletedAt: time.Unix(1_700_000_600, 0).UTC()}
|
||||
require.NoError(t, persister.SaveFullPass(context.Background(), previous))
|
||||
|
||||
report := &runReport{}
|
||||
loadLastFullPass(context.Background(), persister, report)
|
||||
store.saveErr = errors.New("filer unavailable")
|
||||
recordFullPass(context.Background(), persister, report, time.Now())
|
||||
|
||||
assert.Equal(t, previous.CompletedAt, report.lastFullPass, "an unsaved pass must not replace the saved timestamp")
|
||||
assert.InDelta(t, float64(previous.CompletedAt.Unix()), testutil.ToFloat64(stats.S3LifecycleDailyRunLastFullPassTimestampSeconds), 1e-3)
|
||||
assert.Contains(t, report.outputValues()["full_pass_save_error"].GetStringValue(), "filer unavailable")
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package s3_lifecycle
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
|
||||
)
|
||||
|
||||
// A long pass must keep refreshing the admin's stale-job clock, but only
|
||||
// with work it actually did: an idle tick sends nothing.
|
||||
const progressInterval = 5 * time.Minute
|
||||
|
||||
func runWork(s dailyrun.RunSummary) int64 {
|
||||
work := s.EntriesVisited + s.EntriesListed + s.EventsScanned
|
||||
for _, n := range s.Outcomes {
|
||||
work += n
|
||||
}
|
||||
return work
|
||||
}
|
||||
|
||||
func progressMessage(s dailyrun.RunSummary) string {
|
||||
return fmt.Sprintf("s3 lifecycle daily replay running: last_phase=%s last_bucket=%s entries=%d objects=%d listed=%d events=%d rpc_done=%d rpc_errors=%d",
|
||||
s.Phase, s.Bucket, s.EntriesVisited, s.ObjectsVisited, s.EntriesListed, s.EventsScanned, s.Outcomes["DONE"], s.Outcomes["RPC_ERROR"])
|
||||
}
|
||||
|
||||
// startProgressReporter returns stop, which returns only once no further
|
||||
// progress can be sent, so the caller can send the completion after it.
|
||||
func startProgressReporter(request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender, summarize func() dailyrun.RunSummary, interval time.Duration) (stop func()) {
|
||||
done := make(chan struct{})
|
||||
finished := make(chan struct{})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
var reported int64
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
summary := summarize()
|
||||
work := runWork(summary)
|
||||
if work == reported {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
default:
|
||||
}
|
||||
if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
|
||||
JobId: request.Job.JobId, JobType: jobType,
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "running",
|
||||
Message: progressMessage(summary),
|
||||
}); err != nil {
|
||||
glog.V(1).Infof("s3 lifecycle job %s: send progress: %v", request.Job.JobId, err)
|
||||
continue
|
||||
}
|
||||
reported = work
|
||||
}
|
||||
}()
|
||||
return func() {
|
||||
close(done)
|
||||
<-finished
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package s3_lifecycle
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type progressSender struct {
|
||||
mu sync.Mutex
|
||||
progress []*plugin_pb.JobProgressUpdate
|
||||
failures int
|
||||
attempts int
|
||||
}
|
||||
|
||||
func (s *progressSender) SendProgress(p *plugin_pb.JobProgressUpdate) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.attempts++
|
||||
if s.failures > 0 {
|
||||
s.failures--
|
||||
return errors.New("stream closed")
|
||||
}
|
||||
s.progress = append(s.progress, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *progressSender) SendCompleted(*plugin_pb.JobCompleted) error { return nil }
|
||||
|
||||
func (s *progressSender) sent() []*plugin_pb.JobProgressUpdate {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]*plugin_pb.JobProgressUpdate(nil), s.progress...)
|
||||
}
|
||||
|
||||
func (s *progressSender) tries() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.attempts
|
||||
}
|
||||
|
||||
type fakeRun struct {
|
||||
entries, listed, events, done, rpcErrors atomic.Int64
|
||||
}
|
||||
|
||||
func (f *fakeRun) summary() dailyrun.RunSummary {
|
||||
return dailyrun.RunSummary{
|
||||
Phase: dailyrun.PhaseWalk,
|
||||
Bucket: "b1",
|
||||
EntriesVisited: f.entries.Load(),
|
||||
EntriesListed: f.listed.Load(),
|
||||
EventsScanned: f.events.Load(),
|
||||
Outcomes: map[string]int64{"DONE": f.done.Load(), "RPC_ERROR": f.rpcErrors.Load()},
|
||||
}
|
||||
}
|
||||
|
||||
func progressRequest() *plugin_pb.ExecuteJobRequest {
|
||||
return &plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{JobId: "job-1"}}
|
||||
}
|
||||
|
||||
const testInterval = 5 * time.Millisecond
|
||||
|
||||
func TestProgressReporter_IdleTicksSendNothing(t *testing.T) {
|
||||
sender := &progressSender{}
|
||||
run := &fakeRun{}
|
||||
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
|
||||
time.Sleep(20 * testInterval)
|
||||
stop()
|
||||
require.Empty(t, sender.sent())
|
||||
}
|
||||
|
||||
func TestProgressReporter_ReportsEachKindOfWork(t *testing.T) {
|
||||
sender := &progressSender{}
|
||||
run := &fakeRun{}
|
||||
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
|
||||
defer stop()
|
||||
|
||||
bumps := []*atomic.Int64{&run.entries, &run.listed, &run.events, &run.done, &run.rpcErrors}
|
||||
for i, counter := range bumps {
|
||||
counter.Add(1)
|
||||
require.Eventually(t, func() bool { return len(sender.sent()) == i+1 }, time.Second, testInterval)
|
||||
}
|
||||
time.Sleep(10 * testInterval)
|
||||
updates := sender.sent()
|
||||
require.Len(t, updates, len(bumps), "unchanged work must not refresh the job")
|
||||
|
||||
last := updates[len(updates)-1]
|
||||
require.Equal(t, "job-1", last.JobId)
|
||||
require.Equal(t, jobType, last.JobType)
|
||||
require.Equal(t, plugin_pb.JobState_JOB_STATE_RUNNING, last.State)
|
||||
require.Equal(t, "running", last.Stage)
|
||||
require.Contains(t, last.Message, "last_phase=walk last_bucket=b1")
|
||||
require.Contains(t, last.Message, "entries=1")
|
||||
require.Contains(t, last.Message, "listed=1")
|
||||
require.Contains(t, last.Message, "events=1")
|
||||
require.Contains(t, last.Message, "rpc_done=1")
|
||||
require.Contains(t, last.Message, "rpc_errors=1")
|
||||
}
|
||||
|
||||
func TestProgressReporter_RetriesAFailedSendWithoutNewWork(t *testing.T) {
|
||||
sender := &progressSender{failures: 2}
|
||||
run := &fakeRun{}
|
||||
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
|
||||
defer stop()
|
||||
|
||||
run.entries.Add(3)
|
||||
require.Eventually(t, func() bool { return len(sender.sent()) == 1 }, time.Second, testInterval)
|
||||
require.Equal(t, 3, sender.tries())
|
||||
time.Sleep(10 * testInterval)
|
||||
require.Equal(t, 3, sender.tries(), "a delivered report must not be resent")
|
||||
require.Contains(t, sender.sent()[0].Message, "entries=3")
|
||||
}
|
||||
|
||||
func TestProgressReporter_NoProgressAfterStop(t *testing.T) {
|
||||
sender := &progressSender{}
|
||||
run := &fakeRun{}
|
||||
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
|
||||
run.done.Add(1)
|
||||
require.Eventually(t, func() bool { return len(sender.sent()) == 1 }, time.Second, testInterval)
|
||||
|
||||
stop()
|
||||
tries := sender.tries()
|
||||
run.done.Add(1)
|
||||
run.entries.Add(1)
|
||||
time.Sleep(10 * testInterval)
|
||||
require.Equal(t, tries, sender.tries())
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package s3_lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
var lifecycleReadyTimeout = 10 * time.Second
|
||||
|
||||
// checkLifecycleReady authenticates to one S3 front with the credentials
|
||||
// LifecycleDelete uses, without touching bucket or object metadata.
|
||||
func checkLifecycleReady(ctx context.Context, c s3_lifecycle_pb.SeaweedS3LifecycleInternalClient) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, lifecycleReadyTimeout)
|
||||
defer cancel()
|
||||
ctx, _ = credential.WithS3InternalAdminAuth(ctx)
|
||||
_, err := c.LifecycleReady(ctx, &s3_lifecycle_pb.LifecycleReadyRequest{})
|
||||
if status.Code(err) == codes.Unimplemented {
|
||||
// Older fronts authorize an empty delete, then reject it before any lookup.
|
||||
_, err = c.LifecycleDelete(ctx, &s3_lifecycle_pb.LifecycleDeleteRequest{})
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// selectS3Front returns a connection to the first front that passes
|
||||
// checkLifecycleReady, plus why each earlier front was skipped. A nil
|
||||
// connection means none passed.
|
||||
func (h *Handler) selectS3Front(ctx context.Context, endpoints []string) (*grpc.ClientConn, string, []error) {
|
||||
var skipped []error
|
||||
for _, addr := range endpoints {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, "", append(skipped, err)
|
||||
}
|
||||
dialCtx, dialCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
conn, err := pb.GrpcDial(dialCtx, addr, false, h.grpcDialOption)
|
||||
dialCancel()
|
||||
if err != nil {
|
||||
skipped = append(skipped, fmt.Errorf("dial s3 %s: %w", addr, err))
|
||||
continue
|
||||
}
|
||||
if err := checkLifecycleReady(ctx, s3_lifecycle_pb.NewSeaweedS3LifecycleInternalClient(conn)); err != nil {
|
||||
conn.Close()
|
||||
skipped = append(skipped, readinessError(addr, err))
|
||||
continue
|
||||
}
|
||||
return conn, addr, skipped
|
||||
}
|
||||
return nil, "", skipped
|
||||
}
|
||||
|
||||
func readinessError(addr string, err error) error {
|
||||
switch status.Code(err) {
|
||||
case codes.Unauthenticated, codes.PermissionDenied:
|
||||
workerKey := "is not set"
|
||||
if util.GetViper().GetString("jwt.filer_signing.key") != "" {
|
||||
workerKey = "is set"
|
||||
}
|
||||
return fmt.Errorf("s3 %s rejected lifecycle credentials: %w; this worker's jwt.filer_signing.key %s, and it must match the key in the s3 server's security.toml (an s3 server without the key accepts only local callers)", addr, err, workerKey)
|
||||
}
|
||||
return fmt.Errorf("s3 %s readiness check: %w", addr, err)
|
||||
}
|
||||
|
||||
func noReadyS3Error(skipped []error) error {
|
||||
return fmt.Errorf("no s3 server is ready for lifecycle deletes: %w", errors.Join(skipped...))
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package s3_lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
frontKey = "readiness-test-front-key"
|
||||
otherKey = "readiness-test-other-key"
|
||||
)
|
||||
|
||||
type testFront struct {
|
||||
s3_lifecycle_pb.UnimplementedSeaweedS3LifecycleInternalServer
|
||||
key string
|
||||
legacy bool
|
||||
block bool
|
||||
readies atomic.Int32
|
||||
deletes atomic.Int32
|
||||
}
|
||||
|
||||
func (f *testFront) LifecycleReady(ctx context.Context, _ *s3_lifecycle_pb.LifecycleReadyRequest) (*s3_lifecycle_pb.LifecycleReadyResponse, error) {
|
||||
f.readies.Add(1)
|
||||
if f.legacy {
|
||||
return nil, status.Error(codes.Unimplemented, "method LifecycleReady not implemented")
|
||||
}
|
||||
if f.block {
|
||||
<-ctx.Done()
|
||||
return nil, status.FromContextError(ctx.Err()).Err()
|
||||
}
|
||||
if err := security.CheckGrpcAdminToken(ctx, security.SigningKey(f.key)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s3_lifecycle_pb.LifecycleReadyResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *testFront) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
f.deletes.Add(1)
|
||||
if err := security.CheckGrpcAdminToken(ctx, security.SigningKey(f.key)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.Bucket == "" || req.ObjectPath == "" {
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED}, nil
|
||||
}
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
|
||||
}
|
||||
|
||||
type countingFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
lists atomic.Int32
|
||||
}
|
||||
|
||||
func (f *countingFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
|
||||
return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets"}, nil
|
||||
}
|
||||
|
||||
func (f *countingFiler) ListEntries(*filer_pb.ListEntriesRequest, grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
|
||||
f.lists.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func serveGrpc(t *testing.T, register func(*grpc.Server)) string {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := grpc.NewServer()
|
||||
register(s)
|
||||
go s.Serve(lis)
|
||||
t.Cleanup(s.Stop)
|
||||
return lis.Addr().String()
|
||||
}
|
||||
|
||||
func startFront(t *testing.T, f *testFront) string {
|
||||
return serveGrpc(t, func(s *grpc.Server) { s3_lifecycle_pb.RegisterSeaweedS3LifecycleInternalServer(s, f) })
|
||||
}
|
||||
|
||||
func setWorkerKey(t *testing.T, key string) {
|
||||
t.Helper()
|
||||
v := util.GetViper()
|
||||
prev := v.GetString("jwt.filer_signing.key")
|
||||
v.Set("jwt.filer_signing.key", key)
|
||||
t.Cleanup(func() { v.Set("jwt.filer_signing.key", prev) })
|
||||
}
|
||||
|
||||
func newTestHandler() *Handler {
|
||||
return NewHandler(grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
}
|
||||
|
||||
func assertNoSecrets(t *testing.T, msg string) {
|
||||
t.Helper()
|
||||
for _, secret := range []string{frontKey, otherKey, "Bearer", "eyJ"} {
|
||||
if strings.Contains(msg, secret) {
|
||||
t.Fatalf("error exposes %q: %s", secret, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectS3Front_SharedKeyPassesWithoutDeletes(t *testing.T) {
|
||||
setWorkerKey(t, frontKey)
|
||||
front := &testFront{key: frontKey}
|
||||
addr := startFront(t, front)
|
||||
|
||||
conn, got, skipped := newTestHandler().selectS3Front(context.Background(), []string{addr})
|
||||
if conn == nil {
|
||||
t.Fatalf("expected a ready front, skipped: %v", skipped)
|
||||
}
|
||||
conn.Close()
|
||||
if got != addr || len(skipped) != 0 {
|
||||
t.Fatalf("got front %q skipped %v, want %q and none", got, skipped, addr)
|
||||
}
|
||||
if front.deletes.Load() != 0 {
|
||||
t.Fatalf("readiness check sent %d LifecycleDelete calls", front.deletes.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectS3Front_KeyProblemsNameTheConfig(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, workerKey, wantState string
|
||||
}{
|
||||
{"missing worker key", "", "is not set"},
|
||||
{"mismatched worker key", otherKey, "is set"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
setWorkerKey(t, tc.workerKey)
|
||||
addr := startFront(t, &testFront{key: frontKey})
|
||||
|
||||
conn, _, skipped := newTestHandler().selectS3Front(context.Background(), []string{addr})
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
t.Fatal("front with a different key was selected")
|
||||
}
|
||||
if len(skipped) != 1 || status.Code(errors.Unwrap(skipped[0])) != codes.Unauthenticated {
|
||||
t.Fatalf("want one Unauthenticated skip, got %v", skipped)
|
||||
}
|
||||
msg := noReadyS3Error(skipped).Error()
|
||||
for _, want := range []string{addr, "jwt.filer_signing.key " + tc.wantState, "security.toml"} {
|
||||
if !strings.Contains(msg, want) {
|
||||
t.Fatalf("error %q does not mention %q", msg, want)
|
||||
}
|
||||
}
|
||||
assertNoSecrets(t, msg)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectS3Front_SkipsFrontWithOtherKey(t *testing.T) {
|
||||
setWorkerKey(t, frontKey)
|
||||
bad := &testFront{key: otherKey}
|
||||
good := &testFront{key: frontKey}
|
||||
badAddr, goodAddr := startFront(t, bad), startFront(t, good)
|
||||
|
||||
conn, got, skipped := newTestHandler().selectS3Front(context.Background(), []string{badAddr, goodAddr})
|
||||
if conn == nil {
|
||||
t.Fatalf("expected the second front, skipped: %v", skipped)
|
||||
}
|
||||
conn.Close()
|
||||
if got != goodAddr {
|
||||
t.Fatalf("selected %q, want %q", got, goodAddr)
|
||||
}
|
||||
if len(skipped) != 1 || !strings.Contains(skipped[0].Error(), badAddr) || !strings.Contains(skipped[0].Error(), "rejected lifecycle credentials") {
|
||||
t.Fatalf("want the first front reported as a credential problem, got %v", skipped)
|
||||
}
|
||||
if bad.deletes.Load() != 0 || good.deletes.Load() != 0 {
|
||||
t.Fatal("readiness check sent LifecycleDelete calls")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectS3Front_OlderFrontUsesEmptyDelete(t *testing.T) {
|
||||
setWorkerKey(t, frontKey)
|
||||
ok := &testFront{key: frontKey, legacy: true}
|
||||
okAddr := startFront(t, ok)
|
||||
conn, _, skipped := newTestHandler().selectS3Front(context.Background(), []string{okAddr})
|
||||
if conn == nil {
|
||||
t.Fatalf("older front with the shared key was skipped: %v", skipped)
|
||||
}
|
||||
conn.Close()
|
||||
if ok.deletes.Load() != 1 {
|
||||
t.Fatalf("want one empty LifecycleDelete, got %d", ok.deletes.Load())
|
||||
}
|
||||
|
||||
mismatched := &testFront{key: otherKey, legacy: true}
|
||||
conn, _, skipped = newTestHandler().selectS3Front(context.Background(), []string{startFront(t, mismatched)})
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
t.Fatal("older front with another key was selected")
|
||||
}
|
||||
if len(skipped) != 1 || !strings.Contains(skipped[0].Error(), "rejected lifecycle credentials") {
|
||||
t.Fatalf("want a credential problem, got %v", skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectS3Front_TimeoutMovesOn(t *testing.T) {
|
||||
setWorkerKey(t, frontKey)
|
||||
prev := lifecycleReadyTimeout
|
||||
lifecycleReadyTimeout = 200 * time.Millisecond
|
||||
t.Cleanup(func() { lifecycleReadyTimeout = prev })
|
||||
stuckAddr := startFront(t, &testFront{key: frontKey, block: true})
|
||||
goodAddr := startFront(t, &testFront{key: frontKey})
|
||||
|
||||
start := time.Now()
|
||||
conn, got, skipped := newTestHandler().selectS3Front(context.Background(), []string{stuckAddr, goodAddr})
|
||||
if conn == nil {
|
||||
t.Fatalf("expected the second front, skipped: %v", skipped)
|
||||
}
|
||||
conn.Close()
|
||||
if elapsed := time.Since(start); elapsed > 5*time.Second {
|
||||
t.Fatalf("readiness check took %v", elapsed)
|
||||
}
|
||||
if got != goodAddr || len(skipped) != 1 || status.Code(errors.Unwrap(skipped[0])) != codes.DeadlineExceeded {
|
||||
t.Fatalf("got %q skipped %v, want %q after a DeadlineExceeded skip", got, skipped, goodAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectS3Front_ParentCancelStops(t *testing.T) {
|
||||
setWorkerKey(t, frontKey)
|
||||
next := &testFront{key: frontKey}
|
||||
stuckAddr := startFront(t, &testFront{key: frontKey, block: true})
|
||||
nextAddr := startFront(t, next)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
time.AfterFunc(100*time.Millisecond, cancel)
|
||||
start := time.Now()
|
||||
conn, _, skipped := newTestHandler().selectS3Front(ctx, []string{stuckAddr, nextAddr})
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
t.Fatal("selected a front after the parent was cancelled")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 5*time.Second {
|
||||
t.Fatalf("cancelled selection took %v", elapsed)
|
||||
}
|
||||
if !errors.Is(noReadyS3Error(skipped), context.Canceled) {
|
||||
t.Fatalf("want context.Canceled, got %v", skipped)
|
||||
}
|
||||
if next.readies.Load() != 0 {
|
||||
t.Fatal("tried another front after the parent was cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecute_RejectedCredentialsFailBeforeListing(t *testing.T) {
|
||||
setWorkerKey(t, otherKey)
|
||||
filer := &countingFiler{}
|
||||
filerAddr := serveGrpc(t, func(s *grpc.Server) { filer_pb.RegisterSeaweedFilerServer(s, filer) })
|
||||
front := &testFront{key: frontKey}
|
||||
frontAddr := startFront(t, front)
|
||||
|
||||
err := newTestHandler().Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
|
||||
Job: &plugin_pb.JobSpec{
|
||||
JobId: "j1", JobType: jobType,
|
||||
Parameters: map[string]*plugin_pb.ConfigValue{
|
||||
"filer_grpc_address": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: filerAddr}},
|
||||
},
|
||||
},
|
||||
ClusterContext: &plugin_pb.ClusterContext{S3GrpcAddresses: []string{frontAddr}},
|
||||
}, &recordingExecSender{})
|
||||
if err == nil || !strings.Contains(err.Error(), "jwt.filer_signing.key") {
|
||||
t.Fatalf("want a signing-key error, got %v", err)
|
||||
}
|
||||
assertNoSecrets(t, err.Error())
|
||||
if filer.lists.Load() != 0 || front.deletes.Load() != 0 {
|
||||
t.Fatalf("pass started anyway: %d listings, %d deletes", filer.lists.Load(), front.deletes.Load())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package s3_lifecycle
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
)
|
||||
|
||||
const (
|
||||
runStatusComplete = "complete"
|
||||
runStatusPartial = "partial"
|
||||
runStatusFailed = "failed"
|
||||
runStatusCanceled = "canceled"
|
||||
)
|
||||
|
||||
const maxReportedInvalidPolicies = 10
|
||||
|
||||
// runReport is one pass's outcome as the job record shows it.
|
||||
type runReport struct {
|
||||
err error
|
||||
canceled bool
|
||||
elapsed time.Duration
|
||||
bucketsTotal int
|
||||
invalidPolicies []scheduler.ParseError
|
||||
summary dailyrun.RunSummary
|
||||
lastFullPass time.Time
|
||||
fullPassSaveErr error
|
||||
}
|
||||
|
||||
// Bucket walk and shard failures always surface as err. A pass without
|
||||
// one is still partial when a policy could not be loaded or a shard's
|
||||
// replay halted on an unresolved delete.
|
||||
func (r *runReport) status() string {
|
||||
switch {
|
||||
case r.canceled:
|
||||
return runStatusCanceled
|
||||
case r.err != nil:
|
||||
return runStatusFailed
|
||||
case len(r.invalidPolicies) > 0, r.summary.ShardsHalted > 0:
|
||||
return runStatusPartial
|
||||
}
|
||||
return runStatusComplete
|
||||
}
|
||||
|
||||
// fullPass also needs every walk-only rule evaluated: a walk deferred by
|
||||
// WalkerInterval is by design, but it leaves those rules unchecked.
|
||||
func (r *runReport) fullPass() bool {
|
||||
return r.status() == runStatusComplete && r.summary.WalksDeferred == 0
|
||||
}
|
||||
|
||||
func (r *runReport) summaryLine() string {
|
||||
verb := r.status()
|
||||
if verb == runStatusComplete {
|
||||
verb = "completed"
|
||||
}
|
||||
s := r.summary
|
||||
return fmt.Sprintf("s3 lifecycle daily replay %s: buckets=%d walked=%d failed=%d skipped=%d invalid_policies=%d entries=%d events=%d rpc_done=%d rpc_errors=%d elapsed=%s",
|
||||
verb, r.bucketsTotal, s.BucketsWalked, s.BucketsFailed, s.BucketsSkipped, len(r.invalidPolicies),
|
||||
s.EntriesVisited, s.EventsScanned, s.Outcomes["DONE"], s.Outcomes["RPC_ERROR"], r.elapsed.Round(time.Second))
|
||||
}
|
||||
|
||||
func (r *runReport) errorMessage() string {
|
||||
if r.err == nil {
|
||||
return ""
|
||||
}
|
||||
if n := r.summary.BucketsFailed; n > 1 {
|
||||
return fmt.Sprintf("%v (%d of %d buckets failed)", r.err, n, r.bucketsTotal)
|
||||
}
|
||||
return r.err.Error()
|
||||
}
|
||||
|
||||
func (r *runReport) outputValues() map[string]*plugin_pb.ConfigValue {
|
||||
s := r.summary
|
||||
out := map[string]*plugin_pb.ConfigValue{
|
||||
"status": stringValue(r.status()),
|
||||
"buckets_total": int64Value(int64(r.bucketsTotal)),
|
||||
"buckets_walked": int64Value(int64(s.BucketsWalked)),
|
||||
"buckets_failed": int64Value(int64(s.BucketsFailed)),
|
||||
"buckets_skipped": int64Value(int64(s.BucketsSkipped)),
|
||||
"invalid_policies": int64Value(int64(len(r.invalidPolicies))),
|
||||
"entries_visited": int64Value(s.EntriesVisited),
|
||||
"objects_visited": int64Value(s.ObjectsVisited),
|
||||
"events_scanned": int64Value(s.EventsScanned),
|
||||
"shard_errors": int64Value(int64(s.ShardErrors)),
|
||||
"shards_halted": int64Value(int64(s.ShardsHalted)),
|
||||
"walks_deferred": int64Value(int64(s.WalksDeferred)),
|
||||
"full_pass": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: r.fullPass()}},
|
||||
"elapsed": {Kind: &plugin_pb.ConfigValue_DurationValue{DurationValue: durationpb.New(r.elapsed.Round(time.Millisecond))}},
|
||||
}
|
||||
for outcome, n := range s.Outcomes {
|
||||
out["rpc_"+strings.ToLower(strings.TrimPrefix(outcome, "RPC_"))] = int64Value(n)
|
||||
}
|
||||
if len(s.BucketFailures) > 0 {
|
||||
failures := make([]string, 0, len(s.BucketFailures))
|
||||
for _, f := range s.BucketFailures {
|
||||
failures = append(failures, f.Bucket+": "+f.Error)
|
||||
}
|
||||
out["bucket_failures"] = stringListValue(failures)
|
||||
}
|
||||
if len(r.invalidPolicies) > 0 {
|
||||
invalid := make([]string, 0, maxReportedInvalidPolicies)
|
||||
for _, pe := range r.invalidPolicies {
|
||||
if len(invalid) == maxReportedInvalidPolicies {
|
||||
break
|
||||
}
|
||||
invalid = append(invalid, fmt.Sprintf("%s: %v", pe.Bucket, pe.Err))
|
||||
}
|
||||
sort.Strings(invalid)
|
||||
out["invalid_policy_buckets"] = stringListValue(invalid)
|
||||
}
|
||||
if s.Phase != "" {
|
||||
out["last_phase"] = stringValue(s.Phase)
|
||||
}
|
||||
if s.Bucket != "" {
|
||||
out["last_bucket"] = stringValue(s.Bucket)
|
||||
}
|
||||
if r.fullPassSaveErr != nil {
|
||||
out["full_pass_save_error"] = stringValue(r.fullPassSaveErr.Error())
|
||||
}
|
||||
if !r.lastFullPass.IsZero() {
|
||||
out["last_full_pass_at"] = stringValue(r.lastFullPass.UTC().Format(time.RFC3339))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func stringValue(v string) *plugin_pb.ConfigValue {
|
||||
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_StringValue{StringValue: v}}
|
||||
}
|
||||
|
||||
func int64Value(v int64) *plugin_pb.ConfigValue {
|
||||
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: v}}
|
||||
}
|
||||
|
||||
func stringListValue(v []string) *plugin_pb.ConfigValue {
|
||||
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_StringList{StringList: &plugin_pb.StringList{Values: v}}}
|
||||
}
|
||||
Reference in new issue
Block a user