Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Prune storage without having to stop peertube

Chocobozzz5f60f1488aee
diff --git a/packages/tests/src/cli/prune-storage.ts b/packages/tests/src/cli/prune-storage.ts
index 2a48e61256..1da86db191 100644
--- a/packages/tests/src/cli/prune-storage.ts
+++ b/packages/tests/src/cli/prune-storage.ts
@@ -71,7 +71,8 @@ describe('Test prune storage CLI', function () {
})
describe('On filesystem', function () {
- const badNames: { [directory: string]: string[] } = {}
+ const badCommonNames: { [directory: string]: string[] } = {}
+ const badTmpPersistentNames: { [directory: string]: string[] } = {}
async function assertNotExists (server: PeerTubeServer, directory: string, substring: string) {
const files = await readdir(server.servers.buildDirectory(directory))
@@ -115,9 +116,6 @@ describe('Test prune storage CLI', function () {
const captionsCount = await server.servers.countFiles('captions')
expect(captionsCount).to.equal(1)
-
- const userExportFilesCount = await server.servers.countFiles('tmp-persistent')
- expect(userExportFilesCount).to.equal(1)
}
async function checkCacheFilesCountBeforeLazyLoad () {
@@ -137,6 +135,9 @@ describe('Test prune storage CLI', function () {
it('Should have the files on the disk', async function () {
await checkLocalFilesCount()
await checkCacheFilesCountBeforeLazyLoad()
+
+ const userExportFilesCount = await servers[0].servers.countFiles('tmp-persistent')
+ expect(userExportFilesCount).to.equal(1)
})
it('Should lazy load remote files', async function () {
@@ -190,7 +191,7 @@ describe('Test prune storage CLI', function () {
await createFile(join(basePrivate, n1))
await createFile(join(basePrivate, n2))
- badNames['web-videos'] = [ n1, n2 ]
+ badCommonNames['web-videos'] = [ n1, n2 ]
}
{
@@ -202,7 +203,7 @@ describe('Test prune storage CLI', function () {
await createFile(join(base, n1))
await createFile(join(base, n2))
- badNames['torrents'] = [ n1, n2 ]
+ badCommonNames['torrents'] = [ n1, n2 ]
}
for (const name of [ 'thumbnails', 'avatars', 'storyboards' ]) {
@@ -214,7 +215,7 @@ describe('Test prune storage CLI', function () {
await createFile(join(base, n1))
await createFile(join(base, n2))
- badNames[name] = [ n1, n2 ]
+ badCommonNames[name] = [ n1, n2 ]
}
{
@@ -225,7 +226,7 @@ describe('Test prune storage CLI', function () {
const n1 = buildUUID()
await createFile(join(basePublic, n1))
await createFile(join(basePrivate, n1))
- badNames[directory] = [ n1 ]
+ badCommonNames[directory] = [ n1 ]
}
{
@@ -234,7 +235,7 @@ describe('Test prune storage CLI', function () {
const n1 = buildUUID() + '.mp4'
await createFile(join(base, n1))
- badNames['original-video-files'] = [ n1 ]
+ badCommonNames['original-video-files'] = [ n1 ]
}
{
@@ -246,7 +247,7 @@ describe('Test prune storage CLI', function () {
await createFile(join(base, n1))
await createFile(join(base, n2))
- badNames['captions'] = [ n1, n2 ]
+ badCommonNames['captions'] = [ n1, n2 ]
}
{
@@ -258,7 +259,7 @@ describe('Test prune storage CLI', function () {
await createFile(join(base, n1))
await createFile(join(base, n2))
- badNames['tmp-persistent'] = [ n1, n2 ]
+ badTmpPersistentNames['tmp-persistent'] = [ n1, n2 ]
}
}
})
@@ -274,8 +275,31 @@ describe('Test prune storage CLI', function () {
await checkLocalFilesCount()
await checkCacheFilesCountAfterLazyLoad()
- for (const directory of Object.keys(badNames)) {
- for (const name of badNames[directory]) {
+ // Must use the --offline option to also remove files from this directory
+ const userExportFilesCount = await servers[0].servers.countFiles('tmp-persistent')
+ expect(userExportFilesCount).to.equal(3)
+
+ for (const directory of Object.keys(badCommonNames)) {
+ for (const name of badCommonNames[directory]) {
+ await assertNotExists(servers[0], directory, name)
+ }
+ }
+ })
+
+ it('Should remove files with `--offline` option', async function () {
+ const env = servers[0].cli.getEnv()
+
+ await CLICommand.exec(`echo y | ${env} npm run prune-storage -- --offline`)
+
+ await checkLocalFilesCount()
+ await checkCacheFilesCountAfterLazyLoad()
+
+ // Must use the --offline option to also remove files from this directory
+ const userExportFilesCount = await servers[0].servers.countFiles('tmp-persistent')
+ expect(userExportFilesCount).to.equal(1)
+
+ for (const directory of Object.keys(badTmpPersistentNames)) {
+ for (const name of badTmpPersistentNames[directory]) {
await assertNotExists(servers[0], directory, name)
}
}
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.ts
index c6d13957b4..a3ef3522f4 100644
--- a/server/core/initializers/constants.ts
+++ b/server/core/initializers/constants.ts
@@ -933,6 +933,7 @@ export const NSFW_POLICY_TYPES: { [id: string]: NSFWPolicyType } = {
export const USER_EXPORT_MAX_ITEMS = 1000
export const USER_EXPORT_FILE_PREFIX = 'user-export-'
+export const USER_IMPORT_FILE_PREFIX = 'user-import-'
// ---------------------------------------------------------------------------
diff --git a/server/core/initializers/installer.ts b/server/core/initializers/installer.ts
index 4ae8a2f630..2c1e2b25b5 100644
--- a/server/core/initializers/installer.ts
+++ b/server/core/initializers/installer.ts
@@ -32,7 +32,6 @@ async function installApplication () {
])
}),
- // Directories
removeTmpDirectory()
.then(() => createDirectoriesIfNotExist())
])
diff --git a/server/core/models/user/user-import.ts b/server/core/models/user/user-import.ts
index 8ad67c32e8..5cbbb4f437 100644
--- a/server/core/models/user/user-import.ts
+++ b/server/core/models/user/user-import.ts
@@ -1,10 +1,10 @@
-import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
-import { MUserImport } from '@server/types/models/index.js'
-import { SequelizeModel } from '../shared/index.js'
-import { UserModel } from './user.js'
import type { UserImportResultSummary, UserImportStateType } from '@peertube/peertube-models'
+import { USER_IMPORT_FILE_PREFIX, USER_IMPORT_STATES } from '@server/initializers/constants.js'
+import { MUserImport } from '@server/types/models/index.js'
+import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
+import { doesExist, SequelizeModel } from '../shared/index.js'
import { getSort } from '../shared/sort.js'
-import { USER_IMPORT_STATES } from '@server/initializers/constants.js'
+import { UserModel } from './user.js'
@Table({
tableName: 'userImport',
@@ -68,11 +68,20 @@ export class UserImportModel extends SequelizeModel<UserImportModel> {
// ---------------------------------------------------------------------------
+ static async doesOwnedFileExist (filename: string) {
+ const query = 'SELECT 1 FROM "userImport" ' +
+ `WHERE "filename" = $filename LIMIT 1`
+
+ return doesExist({ sequelize: this.sequelize, query, bind: { filename } })
+ }
+
+ // ---------------------------------------------------------------------------
+
generateAndSetFilename () {
if (!this.userId) throw new Error('Cannot generate filename without userId')
if (!this.createdAt) throw new Error('Cannot generate filename without createdAt')
- this.filename = `user-import-${this.userId}-${this.createdAt.toISOString()}.zip`
+ this.filename = `${USER_IMPORT_FILE_PREFIX}${this.userId}-${this.createdAt.toISOString()}.zip`
}
toFormattedJSON () {
diff --git a/server/scripts/house-keeping.ts b/server/scripts/house-keeping.ts
index 16d5430ba3..297c1c19a4 100644
--- a/server/scripts/house-keeping.ts
+++ b/server/scripts/house-keeping.ts
@@ -113,4 +113,6 @@ async function deleteRemoteFiles () {
}, { concurrency: 20 })
console.log('Remote storyboard files deleted!')
+
+ console.log('All remote files deleted! Please restart PeerTube.')
}
diff --git a/server/scripts/prune-storage.ts b/server/scripts/prune-storage.ts
index 6109f98c18..0cb4e1ed56 100755
--- a/server/scripts/prune-storage.ts
+++ b/server/scripts/prune-storage.ts
@@ -1,9 +1,10 @@
import { createCommand } from '@commander-js/extra-typings'
-import { uniqify } from '@peertube/peertube-core-utils'
+import { uniqify, wait } from '@peertube/peertube-core-utils'
import { FileStorage } from '@peertube/peertube-models'
-import { DIRECTORIES, USER_EXPORT_FILE_PREFIX } from '@server/initializers/constants.js'
+import { DIRECTORIES, USER_EXPORT_FILE_PREFIX, USER_IMPORT_FILE_PREFIX } from '@server/initializers/constants.js'
import { BucketInfo, listKeysOfPrefix, removeObjectByFullKey } from '@server/lib/object-storage/object-storage-helpers.js'
import { UserExportModel } from '@server/models/user/user-export.js'
+import { UserImportModel } from '@server/models/user/user-import.js'
import { StoryboardModel } from '@server/models/video/storyboard.js'
import { VideoCaptionModel } from '@server/models/video/video-caption.js'
import { VideoFileModel } from '@server/models/video/video-file.js'
@@ -24,6 +25,7 @@ import { askConfirmation, displayPeerTubeMustBeStoppedWarning } from './shared/c
const program = createCommand()
.description('Remove unused local objects (video files, captions, user exports...) from object storage or file system')
+ .option('--offline', 'Confirm PeerTube instance is stopped, so this script can prune more directories')
.option('-y, --yes', 'Auto confirm files deletion')
.parse(process.argv)
@@ -53,26 +55,27 @@ async function run () {
// ---------------------------------------------------------------------------
class ObjectStoragePruner {
- private readonly keysToDelete: { bucket: string, key: string }[] = []
-
async prune () {
if (!CONFIG.OBJECT_STORAGE.ENABLED) return
console.log('Pruning object storage.')
- await this.findFilesToDelete(CONFIG.OBJECT_STORAGE.WEB_VIDEOS, this.doesWebVideoFileExistFactory())
- await this.findFilesToDelete(CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS, this.doesStreamingPlaylistFileExistFactory())
- await this.findFilesToDelete(CONFIG.OBJECT_STORAGE.ORIGINAL_VIDEO_FILES, this.doesOriginalFileExistFactory())
- await this.findFilesToDelete(CONFIG.OBJECT_STORAGE.USER_EXPORTS, this.doesUserExportFileExistFactory())
- await this.findFilesToDelete(CONFIG.OBJECT_STORAGE.CAPTIONS, this.doesCaptionFileExistFactory())
+ const pathsToDeletePass1 = await this.buildKeysToDelete()
+ await wait(1000)
+ const pathsToDeletePass2 = await this.buildKeysToDelete()
+
+ // Intersect paths to delete to prevent deleting transient files
+ const pathsToDelete = pathsToDeletePass1.filter(({ bucket, key }) =>
+ pathsToDeletePass2.some(({ bucket: b, key: k }) => b === bucket && k === key)
+ )
- if (this.keysToDelete.length === 0) {
+ if (pathsToDelete.length === 0) {
console.log('No unknown object storage files to delete.')
return
}
- const formattedKeysToDelete = this.keysToDelete.map(({ bucket, key }) => ` In bucket ${bucket}: ${key}`).join('\n')
- console.log(`${this.keysToDelete.length} unknown files from object storage can be deleted:\n${formattedKeysToDelete}\n`)
+ const formattedKeysToDelete = pathsToDelete.map(({ bucket, key }) => ` In bucket ${bucket}: ${key}`).join('\n')
+ console.log(`${pathsToDelete.length} unknown files from object storage can be deleted:\n${formattedKeysToDelete}\n`)
const res = await askPruneConfirmation(options.yes)
if (res !== true) {
@@ -82,31 +85,51 @@ class ObjectStoragePruner {
console.log('Deleting object storage files...\n')
- for (const { bucket, key } of this.keysToDelete) {
+ for (const { bucket, key } of pathsToDelete) {
await removeObjectByFullKey(key, { BUCKET_NAME: bucket })
}
- console.log(`${this.keysToDelete.length} object storage files deleted.`)
+ console.log(`${pathsToDelete.length} object storage files deleted.`)
+ }
+
+ private async buildKeysToDelete () {
+ return [
+ ...(await this.findKeysToDeleteInBucket(CONFIG.OBJECT_STORAGE.WEB_VIDEOS, this.doesWebVideoFileExistFactory())),
+
+ ...(await this.findKeysToDeleteInBucket(CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS, this.doesStreamingPlaylistFileExistFactory())),
+
+ ...(await this.findKeysToDeleteInBucket(CONFIG.OBJECT_STORAGE.ORIGINAL_VIDEO_FILES, this.doesOriginalFileExistFactory())),
+
+ ...(await this.findKeysToDeleteInBucket(CONFIG.OBJECT_STORAGE.USER_EXPORTS, this.doesUserExportFileExistFactory())),
+
+ ...(await this.findKeysToDeleteInBucket(CONFIG.OBJECT_STORAGE.CAPTIONS, this.doesCaptionFileExistFactory()))
+ ]
}
- private async findFilesToDelete (
+ private async findKeysToDeleteInBucket (
config: BucketInfo,
existFun: (file: string) => Promise<boolean> | boolean
) {
+ const keysToDelete: { bucket: string, key: string }[] = []
+
try {
const keys = await listKeysOfPrefix('', config)
await Bluebird.map(keys, async key => {
if (await existFun(key) !== true) {
- this.keysToDelete.push({ bucket: config.BUCKET_NAME, key })
+ keysToDelete.push({ bucket: config.BUCKET_NAME, key })
}
}, { concurrency: 20 })
+
+ return keysToDelete
} catch (err) {
const prefixMessage = config.PREFIX
? ` and prefix ${config.PREFIX}`
: ''
- console.error('Cannot find files to delete in bucket ' + config.BUCKET_NAME + prefixMessage, { err })
+ console.error('Cannot find keys to delete in bucket ' + config.BUCKET_NAME + prefixMessage, { err })
+
+ return []
}
}
@@ -161,8 +184,6 @@ class ObjectStoragePruner {
// ---------------------------------------------------------------------------
class FSPruner {
- private pathsToDelete: string[] = []
-
async prune () {
const dirs = Object.values(CONFIG.STORAGE)
@@ -175,38 +196,20 @@ class FSPruner {
console.log('Detecting files to remove, it can take a while...')
- await this.findFilesToDelete(DIRECTORIES.WEB_VIDEOS.PUBLIC, this.doesWebVideoFileExistFactory())
- await this.findFilesToDelete(DIRECTORIES.WEB_VIDEOS.PRIVATE, this.doesWebVideoFileExistFactory())
-
- await this.findFilesToDelete(DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE, this.doesHLSPlaylistExistFactory())
- await this.findFilesToDelete(DIRECTORIES.HLS_STREAMING_PLAYLIST.PUBLIC, this.doesHLSPlaylistExistFactory())
-
- await this.findFilesToDelete(DIRECTORIES.ORIGINAL_VIDEOS, this.doesOriginalVideoExistFactory())
-
- await this.findFilesToDelete(CONFIG.STORAGE.TORRENTS_DIR, this.doesTorrentFileExistFactory())
-
- await this.findFilesToDelete(CONFIG.STORAGE.REDUNDANCY_DIR, this.doesRedundancyExistFactory())
-
- await this.findFilesToDelete(CONFIG.STORAGE.THUMBNAILS_DIR, this.doesThumbnailExistFactory())
-
- await this.findFilesToDelete(CONFIG.STORAGE.CAPTIONS_DIR, this.doesCaptionExistFactory())
-
- await this.findFilesToDelete(CONFIG.STORAGE.STORYBOARDS_DIR, this.doesStoryboardExistFactory())
-
- await this.findFilesToDelete(CONFIG.STORAGE.ACTOR_IMAGES_DIR, this.doesActorImageExistFactory())
+ const pathsToDeletePass1 = await this.buildFilesToDelete()
+ await wait(1000)
+ const pathsToDeletePass2Set = new Set(await this.buildFilesToDelete())
- await this.findFilesToDelete(CONFIG.STORAGE.TMP_PERSISTENT_DIR, this.doesUserExportExistFactory())
+ // Intersect paths to delete to prevent deleting transient files
+ const pathsToDelete = pathsToDeletePass1.filter(path => pathsToDeletePass2Set.has(path))
- const tmpFiles = await readdir(CONFIG.STORAGE.TMP_DIR)
- this.pathsToDelete = [ ...this.pathsToDelete, ...tmpFiles.map(t => join(CONFIG.STORAGE.TMP_DIR, t)) ]
-
- if (this.pathsToDelete.length === 0) {
+ if (pathsToDelete.length === 0) {
console.log('No unknown filesystem files to delete.')
return
}
- const formattedKeysToDelete = this.pathsToDelete.map(p => ` ${p}`).join('\n')
- console.log(`${this.pathsToDelete.length} unknown files from filesystem can be deleted:\n${formattedKeysToDelete}\n`)
+ const formattedKeysToDelete = pathsToDelete.map(p => ` ${p}`).join('\n')
+ console.log(`${pathsToDelete.length} unknown files from filesystem can be deleted:\n${formattedKeysToDelete}\n`)
const res = await askPruneConfirmation(options.yes)
if (res !== true) {
@@ -216,23 +219,58 @@ class FSPruner {
console.log('Deleting filesystem files...\n')
- for (const path of this.pathsToDelete) {
+ for (const path of pathsToDelete) {
await remove(path)
}
- console.log(`${this.pathsToDelete.length} filesystem files deleted.`)
+ console.log(`${pathsToDelete.length} filesystem files deleted.`)
}
- private async findFilesToDelete (directory: string, existFun: (file: string) => Promise<boolean> | boolean) {
+ private async buildFilesToDelete () {
+ let filesToDelete: string[] = [
+ ...(await this.findFilesToDeleteInDir(DIRECTORIES.WEB_VIDEOS.PUBLIC, this.doesWebVideoFileExistFactory())),
+ ...(await this.findFilesToDeleteInDir(DIRECTORIES.WEB_VIDEOS.PRIVATE, this.doesWebVideoFileExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE, this.doesHLSPlaylistExistFactory())),
+ ...(await this.findFilesToDeleteInDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PUBLIC, this.doesHLSPlaylistExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(DIRECTORIES.ORIGINAL_VIDEOS, this.doesOriginalVideoExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(CONFIG.STORAGE.TORRENTS_DIR, this.doesTorrentFileExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(CONFIG.STORAGE.REDUNDANCY_DIR, this.doesRedundancyExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(CONFIG.STORAGE.THUMBNAILS_DIR, this.doesThumbnailExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(CONFIG.STORAGE.CAPTIONS_DIR, this.doesCaptionExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(CONFIG.STORAGE.STORYBOARDS_DIR, this.doesStoryboardExistFactory())),
+
+ ...(await this.findFilesToDeleteInDir(CONFIG.STORAGE.ACTOR_IMAGES_DIR, this.doesActorImageExistFactory()))
+ ]
+
+ if (options.offline === true) {
+ filesToDelete = filesToDelete.concat(
+ await this.findFilesToDeleteInDir(CONFIG.STORAGE.TMP_PERSISTENT_DIR, this.doesUserExportOrImportExistFactory())
+ )
+ }
+
+ return filesToDelete
+ }
+
+ private async findFilesToDeleteInDir (directory: string, existFun: (file: string) => Promise<boolean> | boolean) {
+ const pathsToDelete: string[] = []
const files = await readdir(directory)
await Bluebird.map(files, async file => {
const filePath = join(directory, file)
if (await existFun(filePath) !== true) {
- this.pathsToDelete.push(filePath)
+ pathsToDelete.push(filePath)
}
}, { concurrency: 20 })
+
+ return pathsToDelete
}
private doesWebVideoFileExistFactory () {
@@ -327,15 +365,18 @@ class FSPruner {
}
}
- private doesUserExportExistFactory () {
- return (filePath: string) => {
+ private doesUserExportOrImportExistFactory () {
+ return async (filePath: string) => {
const filename = basename(filePath)
- // Only detect user exports, since we're in the persistent tmp directory
+ // Only detect user exports and imports, since we're in the persistent tmp directory
// We don't want to delete other files that could be in this directory for other reasons
- if (!filename.startsWith(USER_EXPORT_FILE_PREFIX)) return true
+ if (!filename.startsWith(USER_EXPORT_FILE_PREFIX) && !filename.startsWith(USER_IMPORT_FILE_PREFIX)) return true
- return UserExportModel.doesOwnedFileExist(filename, FileStorage.FILE_SYSTEM)
+ if (await UserExportModel.doesOwnedFileExist(filename, FileStorage.FILE_SYSTEM)) return true
+ if (await UserImportModel.doesOwnedFileExist(filename)) return true
+
+ return false
}
}
}
diff --git a/support/doc/tools.md b/support/doc/tools.md
index 1c9b1b5bd5..851dc9a8f6 100644
--- a/support/doc/tools.md
+++ b/support/doc/tools.md
@@ -602,7 +602,9 @@ cd /var/www/peertube-docker; \
**PeerTube >= 6.2**
-Use this script to recover disk space by removing remote files (thumbnails, avatars...) that can be re-fetched later by your PeerTube instance on-demand:
+Use this script to recover disk space by removing remote files (thumbnails, avatars...) that can be re-fetched later by your PeerTube instance on-demand.
+
+Restart PeerTube after running this script.
::: code-group
@@ -674,6 +676,22 @@ cd /var/www/peertube-docker; \
:::
+It's also possible to remove more local files if your stop PeerTube using the `--offline` option:
+
+::: code-group
+
+```bash [Classic installation]
+cd /var/www/peertube/peertube-latest; \
+ sudo -u peertube NODE_CONFIG_DIR=/var/www/peertube/config NODE_ENV=production npm run prune-storage -- --offline
+```
+
+```bash [Docker]
+cd /var/www/peertube-docker; \
+ docker compose exec -u peertube peertube npm run prune-storage -- --offline
+```
+
+:::
+
### Update PeerTube instance domain name
**Changing the hostname is unsupported and may be a risky operation, especially if you have already federated.**