forked from TheCacophonyProject/cacophony-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prune-objects.js
108 lines (89 loc) · 2.45 KB
/
prune-objects.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const process = require("process");
const args = require('commander');
const { Client } = require('pg');
const config = require('./config');
const modelsUtil = require('./models/util/util');
async function main() {
args
.option('--config <path>', 'Configuration file', './config/app.js')
.option('--delete', 'Actually delete objects (dry run by default)')
.parse(process.argv);
config.loadConfig(args.config);
const pgClient = await pgConnect();
const s3 = modelsUtil.openS3();
console.log("retrieving all keys from object store");
const storeKeys = await allBucketKeys(s3, config.s3.bucket);
console.log(`${storeKeys.size} keys in object store`);
console.log("retrieving all keys referenced in database");
const dbKeys = await allDBKeys(pgClient);
console.log(`${dbKeys.size} keys in database`);
const toDelete = new Set([...storeKeys].filter(x => !dbKeys.has(x)));
console.log(`${toDelete.size} keys to delete`);
if (toDelete.size < 1) {
return;
}
if (args.delete) {
await deleteObjects(s3, config.s3.bucket, toDelete);
console.log("objects deleted");
} else {
console.log("(no objects deleted without --delete)");
}
}
async function allBucketKeys(s3, bucket) {
const params = {
Bucket: bucket,
};
var keys = new Set();
for (;;) {
var data = await s3.listObjects(params).promise();
data.Contents.forEach((elem) => {
keys.add(elem.Key);
});
if (!data.IsTruncated) {
break;
}
params.Marker = data.NextMarker;
}
return keys;
}
async function deleteObjects(s3, bucket, keys) {
const params = {
Bucket: bucket,
};
for (const key of keys) {
params.Key = key;
await s3.deleteObject(params).promise();
}
}
async function pgConnect() {
const dbconf = config.database;
const client = new Client({
host: dbconf.host,
port: dbconf.port,
user: dbconf.username,
password: dbconf.password,
database: dbconf.database,
});
await client.connect();
return client;
}
async function allDBKeys(client) {
var keys = new Set();
const res = await client.query(`
select "fileKey" as fk, "rawFileKey" as rk from "Recordings"
union
select "fileKey" as fk, NULL as rk from "Files"
`);
for (const row of res.rows) {
if (row.fk) {
keys.add(row.fk);
}
if (row.rk) {
keys.add(row.rk);
}
}
return keys;
}
main()
.catch ((err) => { console.log(err); })
.then(() => { process.exit(0); });