diff --git a/back/methods/image/scrub.js b/back/methods/image/scrub.js index 893c536ff..2eb9c4312 100644 --- a/back/methods/image/scrub.js +++ b/back/methods/image/scrub.js @@ -52,19 +52,16 @@ module.exports = Self => { const container = await $.ImageContainer.container(collection); const rootPath = container.client.root; - const conn = await getConnection(); + const tx = await Self.beginTransaction({}); + const opts = {transaction: tx}; + const lockName = 'salix.Image.scrub'; - let lockObtained; + const [row] = await Self.rawSql( + `SELECT GET_LOCK(?, 10) hasLock`, [lockName], opts); + if (!row.hasLock) + throw new UserError('Cannot obtain exclusive lock'); try { - const [row] = await query(conn, - `SELECT GET_LOCK(?, 0) hasLock`, - [lockName] - ); - lockObtained = !!row.hasLock; - if (!lockObtained) - throw new UserError('Cannot obtain exclusive lock'); - const now = Date.vnNew().toJSON(); const scrubDir = path.join(rootPath, '.scrub', now); @@ -81,7 +78,7 @@ module.exports = Self => { const count = await Self.count({ collectionFk: collection, name: imageName - }); + }, opts); const exists = count > 0; let scrubDirCreated = false; if (!exists) { @@ -96,8 +93,13 @@ module.exports = Self => { if (!dryRun) await fs.rename(srcFile, dstFile); } else { - if (!dryRun) - await fs.unlink(srcFile); + if (!dryRun) { + try { + await fs.unlink(srcFile); + } catch (err) { + console.error(err); + } + } } cleanCount++; @@ -109,29 +111,8 @@ module.exports = Self => { return cleanCount; } finally { - if (lockObtained) - await query(conn, `DO RELEASE_LOCK(?)`, [lockName]); - conn.release(); - } - - // Promisified datasource functions - - function getConnection() { - return new Promise((resolve, reject) => { - Self.dataSource.connector.client.getConnection((err, conn) => { - if (err) return reject(err); - resolve(conn); - }); - }); - } - - function query(conn, sql, params) { - return new Promise((resolve, reject) => { - conn.query(sql, params, (err, res) => { - if (err) return reject(err); - resolve(res); - }); - }); + await Self.rawSql(`DO RELEASE_LOCK(?)`, [lockName], opts); + await tx.rollback(); } }; };