fix(api): skip orphan files and speed up storage import (#4401)

This commit is contained in:
Hampus authored and GitHub committed 2026-12-04 14:31:56 +01:00
1 parent fe343ea003
commit 51271f12fa
7 files changed
+409 -79

No files matched your search

@@ -64,6 +64,8 @@ export interface FilesystemStorageOptions {
buckets: StorageBuckets;
readOnly: boolean;
requireLayout?: boolean;
fsyncConcurrency?: number;
deferSync?: boolean;
logger?: LoggerInterface;
statfs?: (root: string) => Promise<fs.StatsFs>;
}
@@ -96,7 +98,7 @@ async function ignoreMissing<T>(operation: Promise<T>): Promise<T | null> {
}
}
class Semaphore {
export class Semaphore {
private available: number;
private readonly waiters: Array<() => void> = [];
@@ -127,7 +129,8 @@ export class FilesystemStorageService implements IStorageService {
private readonly tmpDir: string;
private readonly multipartDir: string;
private readonly trashDir: string;
private readonly fsyncs = new Semaphore(FSYNC_CONCURRENCY);
private readonly fsyncs: Semaphore;
private readonly deferSync: boolean;
private readonly logger: LoggerInterface | undefined;
private readonly statfs: (root: string) => Promise<fs.StatsFs>;
private space: StorageSpace | null = null;
@@ -147,6 +150,8 @@ export class FilesystemStorageService implements IStorageService {
this.root = options.root;
this.buckets = options.buckets;
this.readOnly = options.readOnly;
this.fsyncs = new Semaphore(options.fsyncConcurrency ?? FSYNC_CONCURRENCY);
this.deferSync = options.deferSync ?? false;
this.tmpDir = path.join(options.root, STAGING_DIR, STAGING_TMP);
this.multipartDir = path.join(options.root, STAGING_DIR, STAGING_MULTIPART);
this.trashDir = path.join(options.root, STAGING_DIR, STAGING_TRASH);
@@ -252,10 +257,12 @@ export class FilesystemStorageService implements IStorageService {
}
private async fsync(handle: FileHandle): Promise<void> {
if (this.deferSync) return;
await this.fsyncs.run(() => handle.sync());
}
private async syncDir(dir: string): Promise<void> {
if (this.deferSync) return;
const handle = await fs.promises.open(dir, fs.constants.O_RDONLY);
try {
await this.fsync(handle);
@@ -1,11 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {execFile} from 'node:child_process';
import {createHash} from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import {Readable} from 'node:stream';
import {setTimeout as delay} from 'node:timers/promises';
import {parseArgs} from 'node:util';
import {parseArgs, promisify} from 'node:util';
import {Config} from '@app/api/Config';
import {
DIRECTORY_MODE,
@@ -20,7 +21,7 @@ import {
type StorageBuckets,
writeLayoutSync,
} from '@app/api/infrastructure/FilesystemStorageLayout';
import {FilesystemStorageService} from '@app/api/infrastructure/FilesystemStorageService';
import {FilesystemStorageService, Semaphore} from '@app/api/infrastructure/FilesystemStorageService';
import {ATTACHMENT_SAMPLE, parseFolders, pickAttachments, withFolders} from '@app/api/migrate/FilesystemS3Migration';
import {type MigrationOutput, MigrationUsageError, positiveInteger} from '@app/api/migrate/MigrationCli';
import {GetObjectCommand, ListObjectsV2Command, S3Client} from '@aws-sdk/client-s3';
@@ -32,6 +33,8 @@ const STORAGE_MIGRATION_FREE_SPACE_FACTOR = 1.1;
const WEED_MULTIPART_PREFIX = '.uploads/';
const PROGRESS_EVERY = 1000;
const STORAGE_MIGRATION_CONCURRENCY = 32;
const STORAGE_MIGRATION_MAX_CONCURRENCY = 128;
const ROOT_ENTRIES_ALLOWED_BEFORE_IMPORT = new Set([LAYOUT_FILE, STAGING_DIR, META_DIR, 'lost+found']);
const PLACEMENT_ERROR_CODES = new Set(['EEXIST', 'ENOTDIR', 'EISDIR', 'ENOTEMPTY']);
const SOURCE_ATTEMPTS = 7;
@@ -67,6 +70,8 @@ export interface S3FilesystemMigrationOptions {
samplePercent: number;
sampleMin: number;
uploadsTtlMs: number | null;
concurrency?: number;
fsyncEach?: boolean;
}
type StorageMigrationSkipReason =
@@ -74,7 +79,8 @@ type StorageMigrationSkipReason =
| 'trailing-slash'
| 'expired-upload'
| 'invalid-segment'
| 'object-and-prefix';
| 'object-and-prefix'
| 'missing-at-source';
interface StorageMigrationSkip {
bucket: string;
@@ -90,6 +96,7 @@ interface StorageMigrationBucketReport {
mappedNames: number;
sampled: number;
copied: number;
missingAtSource: number;
mismatches: Array<string>;
}
@@ -101,7 +108,7 @@ export interface S3FilesystemMigrationReport {
attachments: Array<string>;
}
export const STORAGE_MIGRATION_USAGE = `usage: MigrateEntrypoint storage [--root <dir>] [--verify-only] [--check] [--add-missing] [--sample-percent <n>] [--sample-min <n>]
export const STORAGE_MIGRATION_USAGE = `usage: MigrateEntrypoint storage [--root <dir>] [--verify-only] [--check] [--add-missing] [--sample-percent <n>] [--sample-min <n>] [--concurrency <n>] [--fsync-each]
--root the folder to write the files into, FLUXER_STORAGE_ROOT by default
--folders the folder of each kind of file when it differs from its bucket, such as cdn=fluxer,uploads=fluxer-uploads
@@ -110,6 +117,8 @@ export const STORAGE_MIGRATION_USAGE = `usage: MigrateEntrypoint storage [--root
--add-missing copy only the objects the folder doesn't have yet, into a folder that may hold files
--sample-percent share of objects whose sha256 is compared, ${STORAGE_MIGRATION_SAMPLE_PERCENT} by default
--sample-min least number of objects per bucket whose sha256 is compared, ${STORAGE_MIGRATION_SAMPLE_MIN} by default
--concurrency objects copied and checked at once, FLUXER_STORAGE_MIGRATION_CONCURRENCY or ${STORAGE_MIGRATION_CONCURRENCY} by default, at most ${STORAGE_MIGRATION_MAX_CONCURRENCY}
--fsync-each flush each file to disk as it is copied, instead of flushing the whole folder once after copying
Uploads older than FLUXER_STORAGE_UPLOADS_TTL (or FLUXER_SEAWEEDFS_UPLOADS_TTL, 1d by default) are not copied.`;
@@ -132,6 +141,14 @@ export function parseS3FilesystemArgs(
if (samplePercent > 100) {
throw new MigrationUsageError('--sample-percent must be at most 100');
}
const concurrency = positiveInteger(
'concurrency',
values.concurrency ?? (env.FLUXER_STORAGE_MIGRATION_CONCURRENCY || undefined),
STORAGE_MIGRATION_CONCURRENCY,
);
if (concurrency > STORAGE_MIGRATION_MAX_CONCURRENCY) {
throw new MigrationUsageError(`--concurrency must be at most ${STORAGE_MIGRATION_MAX_CONCURRENCY}`);
}
let uploadsTtlMs: number | null;
try {
uploadsTtlMs = parseUploadsTtlMs(env.FLUXER_STORAGE_UPLOADS_TTL || env.FLUXER_SEAWEEDFS_UPLOADS_TTL || '1d');
@@ -147,6 +164,8 @@ export function parseS3FilesystemArgs(
samplePercent,
sampleMin: positiveInteger('sample-min', values['sample-min'], STORAGE_MIGRATION_SAMPLE_MIN),
uploadsTtlMs,
concurrency,
fsyncEach: values['fsync-each'] ?? false,
};
}
@@ -163,6 +182,8 @@ function parseStorageArgs(args: ReadonlyArray<string>) {
'add-missing': {type: 'boolean'},
'sample-percent': {type: 'string'},
'sample-min': {type: 'string'},
concurrency: {type: 'string'},
'fsync-each': {type: 'boolean'},
},
});
}
@@ -182,7 +203,9 @@ interface BucketPlan {
directories: number;
mappedNames: number;
samples: Array<string>;
conflicts: Set<string>;
sampleSizes: Map<string, number>;
excluded: Set<string>;
missingAtSource: number;
}
export interface StorageMigrationSource {
@@ -218,6 +241,13 @@ function sourceErrorCode(fault: unknown): string {
return status === undefined ? name : `${name} (HTTP ${status})`;
}
function isMissingAtSource(fault: unknown): boolean {
if (!(fault instanceof Error)) return false;
if (fault.name === 'NoSuchKey' || fault.name === 'NotFound') return true;
const status = (fault as {$metadata?: {httpStatusCode?: number}}).$metadata?.httpStatusCode;
return status === 404 && fault.name !== 'NoSuchBucket';
}
function isTransientSourceError(fault: unknown): boolean {
if (!(fault instanceof Error)) return false;
const status = (fault as {$metadata?: {httpStatusCode?: number}}).$metadata?.httpStatusCode;
@@ -235,6 +265,32 @@ async function fromSource<T>(call: Promise<T>): Promise<T> {
}
}
type SourceRead = Awaited<ReturnType<StorageMigrationSource['read']>>;
async function readSource(source: StorageMigrationSource, bucket: string, key: string): Promise<SourceRead | null> {
try {
return await source.read(bucket, key);
} catch (error) {
if (isMissingAtSource(error)) return null;
throw new SourceFault(error);
}
}
function excludeObject(
plan: BucketPlan,
object: SourceObject,
reason: StorageMigrationSkipReason,
skipped: Array<StorageMigrationSkip>,
): void {
skipped.push({bucket: plan.bucket, key: object.key, reason});
plan.objects -= 1;
plan.bytes -= object.size;
plan.samples = plan.samples.filter((key) => key !== object.key);
if (mapKey(object.key).mapped) plan.mappedNames -= 1;
plan.excluded.add(object.key);
if (reason === 'missing-at-source') plan.missingAtSource += 1;
}
async function retrySource<T>(bucket: string, key: string | null, run: () => Promise<T>): Promise<T> {
for (let attempt = 1; ; attempt += 1) {
try {
@@ -318,6 +374,35 @@ function skipReason(
return null;
}
async function eachLimit<T>(
items: AsyncIterable<T> | Iterable<T>,
limit: number,
run: (item: T) => Promise<void>,
): Promise<void> {
const running = new Set<Promise<void>>();
const failures: Array<unknown> = [];
for await (const item of items) {
if (failures.length > 0) break;
const task: Promise<void> = run(item).then(
() => {
running.delete(task);
},
(error: unknown) => {
running.delete(task);
failures.push(error);
},
);
running.add(task);
if (running.size >= limit) await Promise.race(running);
}
await Promise.all(running);
if (failures.length > 0) throw failures[0];
}
function concurrencyOf(options: S3FilesystemMigrationOptions): number {
return options.concurrency ?? STORAGE_MIGRATION_CONCURRENCY;
}
function inSample(key: string, percent: number): boolean {
return createHash('sha256').update(key).digest().readUInt16BE(0) % 100 < percent;
}
@@ -330,30 +415,118 @@ async function sha256Of(stream: Readable): Promise<string> {
return hash.digest('hex');
}
async function countFiles(dir: string): Promise<{objects: number; bytes: number}> {
async function countFiles(root: string, limit: number): Promise<{objects: number; bytes: number}> {
let objects = 0;
let bytes = 0;
let handle: fs.Dir;
try {
handle = await fs.promises.opendir(dir);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {objects, bytes};
throw error;
}
for await (const entry of handle) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
const inner = await countFiles(full);
objects += inner.objects;
bytes += inner.bytes;
} else if (entry.isFile()) {
await walkTree(root, limit, {
file: async (file) => {
const {size} = await fs.promises.lstat(file);
objects += 1;
bytes += (await fs.promises.lstat(full)).size;
}
}
bytes += size;
},
});
return {objects, bytes};
}
async function walkTree(
root: string,
limit: number,
visitor: {file?: (file: string) => Promise<void>; dir?: (dir: string) => Promise<void>},
): Promise<void> {
const dirs: Array<string> = [root];
let busy = 0;
let wake: Array<() => void> = [];
const notify = (): void => {
const waiting = wake;
wake = [];
for (const resolve of waiting) resolve();
};
const visit = async (dir: string): Promise<void> => {
let handle: fs.Dir;
try {
handle = await fs.promises.opendir(dir, {bufferSize: 256});
} catch (error) {
if (dir === root && (error as NodeJS.ErrnoException).code === 'ENOENT') return;
throw error;
}
const files: Array<string> = [];
const flush = async (): Promise<void> => {
const batch = files.splice(0);
if (visitor.file) await Promise.all(batch.map(visitor.file));
};
for await (const entry of handle) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
dirs.push(full);
notify();
} else if (entry.isFile()) {
files.push(full);
if (files.length >= limit) await flush();
}
}
await flush();
if (visitor.dir) await visitor.dir(dir);
};
const worker = async (): Promise<void> => {
for (;;) {
const dir = dirs.pop();
if (dir === undefined) {
if (busy === 0) {
notify();
return;
}
await new Promise<void>((resolve) => wake.push(resolve));
continue;
}
busy += 1;
try {
await visit(dir);
} finally {
busy -= 1;
notify();
}
}
};
await Promise.all(Array.from({length: limit}, worker));
}
async function fsyncPath(target: string): Promise<void> {
const handle = await fs.promises.open(target, fs.constants.O_RDONLY);
try {
await handle.sync();
} finally {
await handle.close();
}
}
async function syncFilesystem(root: string): Promise<boolean> {
if (process.platform !== 'linux') return false;
try {
await promisify(execFile)('sync', ['-f', root]);
return true;
} catch {
return false;
}
}
async function flushImport(
root: string,
folders: Array<string>,
limit: number,
output: MigrationOutput,
): Promise<void> {
const synced = await syncFilesystem(root);
const fileSyncs = new Semaphore(limit);
if (!synced) output.info(`sync -f ${root} did not run, flushing each file to disk instead`);
for (const folder of new Set([...folders, META_DIR])) {
await walkTree(path.join(root, folder), limit, {
...(synced ? {} : {file: (file: string) => fileSyncs.run(() => fsyncPath(file))}),
dir: fsyncPath,
});
}
await fsyncPath(root);
}
async function assertImportTarget(root: string): Promise<void> {
let entries: Array<string>;
try {
@@ -454,6 +627,8 @@ async function importInto(
buckets: folders,
readOnly: false,
requireLayout: options.verifyOnly || options.addMissing === true,
fsyncConcurrency: concurrencyOf(options),
deferSync: options.fsyncEach !== true,
});
const names = [...new Set([buckets.cdn, buckets.uploads, buckets.reports, buckets.harvests])];
if (await source.hasBucket(GEOIP_BUCKET)) names.push(GEOIP_BUCKET);
@@ -470,7 +645,9 @@ async function importInto(
directories: 1,
mappedNames: 0,
samples: [],
conflicts: new Set(),
sampleSizes: new Map(),
excluded: new Set(),
missingAtSource: 0,
};
const parents: Array<string> = [];
let folders: Array<string> = [];
@@ -483,7 +660,7 @@ async function importInto(
}
while (parents.length > 0 && !object.key.startsWith(parents[parents.length - 1]!)) parents.pop();
if (parents.some((parent) => object.key.startsWith(`${parent}/`))) {
plan.conflicts.add(object.key);
plan.excluded.add(object.key);
skipped.push({bucket, key: object.key, reason: 'object-and-prefix'});
continue;
}
@@ -500,6 +677,7 @@ async function importInto(
if (mapped) plan.mappedNames += 1;
if (mapped || plan.samples.length < options.sampleMin || inSample(object.key, options.samplePercent)) {
plan.samples.push(object.key);
plan.sampleSizes.set(object.key, object.size);
}
}
if (bucket === buckets.cdn) attachments = pickAttachments(attachmentKeys, ATTACHMENT_SAMPLE);
@@ -523,6 +701,7 @@ async function importInto(
mappedNames: plan.mappedNames,
sampled: 0,
copied: 0,
missingAtSource: 0,
mismatches: [],
})),
skipped,
@@ -544,11 +723,19 @@ async function importInto(
for (const plan of plans) {
await copyBucket(plan, source, target, options, buckets, now, skipped, output);
}
if (options.fsyncEach !== true) {
await flushImport(
options.root,
plans.map((plan) => plan.folder),
concurrencyOf(options),
output,
);
}
writeLayoutSync(options.root);
}
const reports: Array<StorageMigrationBucketReport> = [];
for (const plan of plans) {
reports.push(await verifyBucket(plan, source, target, options, buckets, now));
reports.push(await verifyBucket(plan, source, target, options, buckets, now, skipped));
}
return {
root: options.root,
@@ -570,11 +757,14 @@ async function copyBucket(
output: MigrationOutput,
): Promise<void> {
let copied = 0;
for await (const object of source.list(plan.bucket)) {
if (skipReason(plan.bucket, object, buckets, options.uploadsTtlMs, now) || plan.conflicts.has(object.key)) continue;
if (options.addMissing && (await target.getObjectMetadata(plan.folder, object.key)) !== null) continue;
const placed = await retrySource(plan.bucket, object.key, async () => {
const read = await fromSource(source.read(plan.bucket, object.key));
const wanted = filterObjects(source.list(plan.bucket), (object) => {
return !skipReason(plan.bucket, object, buckets, options.uploadsTtlMs, now) && !plan.excluded.has(object.key);
});
await eachLimit(wanted, concurrencyOf(options), async (object) => {
if (options.addMissing && (await target.getObjectMetadata(plan.folder, object.key)) !== null) return;
const placed = await retrySource(plan.bucket, object.key, async (): Promise<StorageMigrationSkipReason | null> => {
const read = await readSource(source, plan.bucket, object.key);
if (read === null) return 'missing-at-source';
const contentType =
read.contentType === 'application/octet-stream' && inferContentType(object.key) === null
? undefined
@@ -589,29 +779,33 @@ async function copyBucket(
? {lastModified: read.lastModified ?? object.lastModified}
: {}),
});
return true;
return null;
} catch (error) {
const failed = read.body.errored;
read.body.destroy();
if (failed) throw new SourceFault(failed);
if (!PLACEMENT_ERROR_CODES.has((error as NodeJS.ErrnoException).code ?? '')) throw error;
return false;
return 'object-and-prefix';
}
});
if (!placed) {
skipped.push({bucket: plan.bucket, key: object.key, reason: 'object-and-prefix'});
plan.objects -= 1;
plan.bytes -= object.size;
plan.samples = plan.samples.filter((key) => key !== object.key);
if (mapKey(object.key).mapped) plan.mappedNames -= 1;
plan.conflicts.add(object.key);
continue;
if (placed !== null) {
excludeObject(plan, object, placed, skipped);
return;
}
copied += 1;
plan.copied = copied;
if (copied % PROGRESS_EVERY === 0) {
output.info(`${plan.bucket}: copied ${copied} of ${plan.objects}`);
}
});
}
async function* filterObjects(
objects: AsyncIterable<SourceObject>,
keep: (object: SourceObject) => boolean,
): AsyncIterable<SourceObject> {
for await (const object of objects) {
if (keep(object)) yield object;
}
}
@@ -622,44 +816,47 @@ async function verifyBucket(
options: S3FilesystemMigrationOptions,
buckets: StorageBuckets,
now: number,
skipped: Array<StorageMigrationSkip>,
): Promise<StorageMigrationBucketReport> {
const mismatches: Array<string> = [];
if (options.addMissing) {
let missing = 0;
for await (const object of source.list(plan.bucket)) {
if (skipReason(plan.bucket, object, buckets, options.uploadsTtlMs, now) || plan.conflicts.has(object.key))
continue;
const meta = await target.getObjectMetadata(plan.folder, object.key);
if (meta === null) {
missing += 1;
if (missing <= 5) mismatches.push(`${object.key}: not in the folder`);
} else if (meta.contentLength !== object.size) {
mismatches.push(`${object.key}: ${object.size} bytes in the object store, ${meta.contentLength} in the folder`);
}
}
if (missing > 5) mismatches.push(`${missing - 5} more objects are not in the folder`);
} else {
const stored = await countFiles(path.join(target.root, plan.folder));
if (stored.objects !== plan.objects) {
mismatches.push(`${plan.objects} objects in the object store, ${stored.objects} files in the folder`);
}
if (stored.bytes !== plan.bytes) {
mismatches.push(`${plan.bytes} bytes in the object store, ${stored.bytes} bytes in the folder`);
}
}
for (const key of plan.samples) {
await eachLimit([...plan.samples], concurrencyOf(options), async (key) => {
const expected = await retrySource(plan.bucket, key, async () => {
const read = await fromSource(source.read(plan.bucket, key));
return await fromSource(sha256Of(read.body));
const read = await readSource(source, plan.bucket, key);
return read === null ? null : await fromSource(sha256Of(read.body));
});
if (expected === null) {
const meta = await target.getObjectMetadata(plan.folder, key);
if (meta === null) {
excludeObject(plan, {key, size: plan.sampleSizes.get(key) ?? 0}, 'missing-at-source', skipped);
} else {
plan.samples = plan.samples.filter((sample) => sample !== key);
}
return;
}
let actual: string;
try {
actual = await target.computeObjectSha256(plan.folder, key);
} catch (error) {
mismatches.push(`${key}: ${error instanceof Error ? error.message : String(error)}`);
continue;
return;
}
if (actual !== expected) mismatches.push(`${key}: sha256 differs`);
});
mismatches.sort();
if (options.addMissing) {
mismatches.push(...(await compareKeys(plan, source, target, options, buckets, now, skipped)));
} else {
const stored = await countFiles(path.join(target.root, plan.folder), concurrencyOf(options));
if (stored.objects !== plan.objects || stored.bytes !== plan.bytes) {
const details = await compareKeys(plan, source, target, options, buckets, now, skipped);
if (stored.objects !== plan.objects) {
mismatches.push(`${plan.objects} objects in the object store, ${stored.objects} files in the folder`);
}
if (stored.bytes !== plan.bytes) {
mismatches.push(`${plan.bytes} bytes in the object store, ${stored.bytes} bytes in the folder`);
}
mismatches.push(...details);
}
}
return {
bucket: plan.bucket,
@@ -669,10 +866,51 @@ async function verifyBucket(
mappedNames: plan.mappedNames,
sampled: plan.samples.length,
copied: plan.copied,
missingAtSource: plan.missingAtSource,
mismatches,
};
}
async function compareKeys(
plan: BucketPlan,
source: StorageMigrationSource,
target: FilesystemStorageService,
options: S3FilesystemMigrationOptions,
buckets: StorageBuckets,
now: number,
skipped: Array<StorageMigrationSkip>,
): Promise<Array<string>> {
const mismatches: Array<string> = [];
let missing = 0;
const listed = filterObjects(source.list(plan.bucket), (object) => {
return !skipReason(plan.bucket, object, buckets, options.uploadsTtlMs, now) && !plan.excluded.has(object.key);
});
await eachLimit(listed, concurrencyOf(options), async (object) => {
const meta = await target.getObjectMetadata(plan.folder, object.key);
if (meta === null) {
if (await goneAtSource(source, plan.bucket, object.key)) {
excludeObject(plan, object, 'missing-at-source', skipped);
return;
}
missing += 1;
if (missing <= 5) mismatches.push(`${object.key}: not in the folder`);
} else if (meta.contentLength !== object.size) {
mismatches.push(`${object.key}: ${object.size} bytes in the object store, ${meta.contentLength} in the folder`);
}
});
if (missing > 5) mismatches.push(`${missing - 5} more objects are not in the folder`);
return mismatches;
}
async function goneAtSource(source: StorageMigrationSource, bucket: string, key: string): Promise<boolean> {
return await retrySource(bucket, key, async () => {
const read = await readSource(source, bucket, key);
if (read === null) return true;
read.body.destroy();
return false;
});
}
export async function runS3FilesystemMigration(
options: S3FilesystemMigrationOptions,
output: MigrationOutput,
+18
View File
@@ -426,6 +426,11 @@ func importData(ctx context.Context, t backup.Target, cc children.Config, old ol
Buckets []struct {
Objects int `json:"objects"`
} `json:"buckets"`
Skipped []struct {
Bucket string `json:"bucket"`
Key string `json:"key"`
Reason string `json:"reason"`
} `json:"skipped"`
}
if err := runMigration(ctx, api, from, &files, "storage", "--root", t.Layout.ObjectsDir()); err != nil {
return fmt.Errorf("copying uploads: %w", err)
@@ -438,6 +443,19 @@ func importData(ctx context.Context, t backup.Target, cc children.Config, old ol
n += b.Objects
}
fmt.Fprintf(os.Stderr, "import: copied %d files\n", n)
var missing []string
for _, f := range files.Skipped {
if f.Reason == "missing-at-source" {
missing = append(missing, f.Bucket+"/"+f.Key)
}
}
if len(missing) > 0 {
list := filepath.Join(t.Layout.Data, "import-missing-uploads.txt")
if err := os.WriteFile(list, []byte(strings.Join(missing, "\n")+"\n"), 0o600); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "import: the old object store listed %d files that it couldn't return, so they were left out. The list is in %s\n", len(missing), list)
}
return nil
}
+1 -1
View File
@@ -558,7 +558,7 @@ func (c *conversion) run(ctx context.Context, inst *instance.Instance, r rt.Runt
if err != nil {
return err
}
note, err := migrate.CopyStorage(ctx, t.importer(c.old.s3Env()), t.root, migrate.BucketEnv(c.old.settings), migrate.BucketEnv(to), log)
note, err := migrate.CopyStorage(ctx, t.importer(c.old.s3Env()), inst.Dir, t.root, migrate.BucketEnv(c.old.settings), migrate.BucketEnv(to), log)
if err != nil {
return err
}
+18 -1
View File
@@ -104,6 +104,19 @@ func (r objectsReport) totals() ObjectsTotals {
return t
}
func (r objectsReport) missing() int {
n := 0
for _, raw := range r.Skipped {
var s struct {
Reason string `json:"reason"`
}
if json.Unmarshal(raw, &s) == nil && s.Reason == missingAtSource {
n++
}
}
return n
}
func (r objectsReport) copied() int {
n := 0
for _, b := range r.Buckets {
@@ -370,9 +383,13 @@ func (o *ObjectsRun) Execute(ctx context.Context) error {
}
t := rep.totals()
o.note("Copied %d files (%s) with their keys and content types.", t.Objects, ui.Bytes(t.Bytes))
if n := len(rep.Skipped); n > 0 {
missing := rep.missing()
if n := len(rep.Skipped) - missing; n > 0 {
o.note("Left out %d expired uploads that Fluxer no longer needs.", n)
}
if missing > 0 {
o.note("Left out %d files that the object store listed but couldn't return.", missing)
}
o.attachmentNote(att)
return nil
}
+9 -3
View File
@@ -4,6 +4,8 @@ package migrate
import (
"context"
"errors"
"fmt"
"io"
"slices"
"strings"
@@ -30,16 +32,20 @@ func CopyKV(ctx context.Context, imp Importer, from string, log io.Writer) (stri
return rep.note(), nil
}
func CopyStorage(ctx context.Context, imp Importer, root string, from, to map[string]string, log io.Writer) (string, error) {
func CopyStorage(ctx context.Context, imp Importer, dir, root string, from, to map[string]string, log io.Writer) (string, error) {
args := []string{importStorage, "--root", root}
if folderArg(from) != folderArg(to) {
args = append(args, "--folders", folderArg(to))
}
rep, err := copyStorage(ctx, imp, args, log)
list, lerr := writeMissingList(dir, rep)
if err != nil {
return "", err
return "", errors.Join(err, lerr)
}
return rep.note(), nil
if lerr != nil {
return "", fmt.Errorf("writing the list of files missing in SeaweedFS: %w", lerr)
}
return rep.note(list), nil
}
func BucketEnv(values map[string]string) map[string]string {
+48 -4
View File
@@ -7,10 +7,14 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
@@ -20,6 +24,8 @@ const (
StorageReadOnlyVar = "FLUXER_STORAGE_READ_ONLY"
geoIPBucket = "fluxer-geoip"
attachmentChecks = 50
missingAtSource = "missing-at-source"
missingListFile = "storage-missing-in-seaweedfs.txt"
)
var (
@@ -99,6 +105,31 @@ func (r storageReport) problems() string {
return strings.Join(out, ", ")
}
func (r storageReport) missing() []string {
var out []string
for _, s := range r.Skipped {
if s.Reason == missingAtSource {
out = append(out, s.Bucket+"/"+s.Key)
}
}
return out
}
func writeMissingList(dir string, rep storageReport) (string, error) {
path := filepath.Join(dir, instance.StateDirName, missingListFile)
keys := rep.missing()
if len(keys) == 0 {
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
return "", err
}
return "", nil
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return "", err
}
return path, os.WriteFile(path, []byte(strings.Join(keys, "\n")+"\n"), 0o600)
}
func (r storageReport) totals() (objects int, bytes int64) {
for _, b := range r.Buckets {
objects += b.Objects
@@ -167,16 +198,29 @@ func (s *StorageStep) Migrate(ctx context.Context, r *Run) error {
return err
}
rep, err := copyStorage(ctx, r.Host.Importer(), []string{importStorage, "--root", r.Host.ObjectsRoot()}, r.Log)
list, lerr := writeMissingList(r.Host.Dir(), rep)
if err != nil {
return err
return errors.Join(err, lerr)
}
r.note("%s", rep.note())
if lerr != nil {
return fmt.Errorf("writing the list of files missing in SeaweedFS: %w", lerr)
}
r.note("%s", rep.note(list))
return nil
}
func (r storageReport) note() string {
func (r storageReport) note(list string) string {
objects, bytes := r.totals()
return fmt.Sprintf("Moved %d files (%s) out of SeaweedFS, and left out %d that Fluxer no longer needs.", objects, ui.Bytes(bytes), len(r.Skipped))
missing := len(r.missing())
out := fmt.Sprintf("Moved %d files (%s) out of SeaweedFS, and left out %d that Fluxer no longer needs.", objects, ui.Bytes(bytes), len(r.Skipped)-missing)
if missing == 0 {
return out
}
what := fmt.Sprintf("%d files", missing)
if missing == 1 {
what = "1 file"
}
return out + fmt.Sprintf(" SeaweedFS listed %s that it couldn't return, so rexctl left them out. You can find the list in %s.", what, list)
}
func (s *StorageStep) Verify(context.Context, *Run) error { return nil }