main.rs
8.9 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
use anyhow::{Context, Result};
use chrono::Utc;
use clap::{Arg, Command};
use dotenv::dotenv;
use log::{error, info, trace, warn};
use std::path::Path;
use std::{env, fs};
use tokio_postgres::{Client, NoTls};
#[tokio::main]
async fn main() {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "info")
}
env_logger::init();
dotenv().ok();
let matches = Command::new("Clean Utility")
.version("1.0")
.about("Cleans old files and database rows based on retention policies")
.arg(
Arg::new("data_dir")
.long("data-dir")
.env("MATTERMOST_DATA_DIRECTORY")
.help("Path to the Mattermost data directory")
.required(true),
)
.arg(
Arg::new("db_name")
.short('n')
.long("db-name")
.env("DATABASE_NAME")
.help("Database name")
.required(true),
)
.arg(
Arg::new("db_user")
.short('u')
.long("db-user")
.env("DATABASE_USER")
.help("Database user")
.required(true),
)
.arg(
Arg::new("db_password")
.short('p')
.long("db-password")
.env("PGPASSWORD")
.help("Database password")
.required(true),
)
.arg(
Arg::new("db_host")
.short('h')
.long("db-host")
.env("DATABASE_HOST")
.help("Database host")
.required(true),
)
.arg(
Arg::new("db_port")
.short('P')
.long("db-port")
.env("DATABASE_PORT")
.help("Database port")
.required(true),
)
.arg(
Arg::new("retention_days")
.short('D')
.long("retention-days")
.env("RETENTION_DAYS")
.help("Number of days to retain data")
.required(true),
)
.arg(
Arg::new("file_batch_size")
.short('b')
.long("file-batch-size")
.env("FILE_BATCH_SIZE")
.help("Batch size for file deletion")
.required(true),
)
.arg(
Arg::new("remove_posts")
.long("remove-posts")
.help("Wipe posts older than timestamp")
.required(false),
)
.arg(
Arg::new("dry_run")
.long("dry-run")
.help("Perform a dry run without making any changes")
.required(false),
)
.get_matches();
let mattermost_data_directory = matches.get_one::<String>("data_dir").unwrap();
let database_name = matches.get_one::<String>("db_name").unwrap();
let database_user = matches.get_one::<String>("db_user").unwrap();
let database_password = matches.get_one::<String>("db_password").unwrap();
let database_host = matches.get_one::<String>("db_host").unwrap();
let database_port = matches.get_one::<String>("db_port").unwrap();
let retention_days = matches.get_one::<String>("retention_days").unwrap();
let file_batch_size = matches.get_one::<String>("file_batch_size").unwrap();
let remove_posts = matches.contains_id("remove_posts");
let dry_run = matches.contains_id("dry_run");
let retention_days = retention_days
.parse::<i64>()
.expect("fucking hell retention");
let file_batch_size = file_batch_size
.parse::<usize>()
.expect("fucking hell batch size");
if let Err(err) = clean(
mattermost_data_directory,
database_name,
database_user,
database_password,
database_host,
database_port,
retention_days,
file_batch_size,
remove_posts,
dry_run,
)
.await
{
error!("Cleaning operation failed: {}", err);
} else {
info!("Cleaning operation completed successfully.");
}
}
pub async fn clean(
mattermost_data_directory: &str,
database_name: &str,
database_user: &str,
database_password: &str,
database_host: &str,
database_port: &str,
retention_days: i64,
file_batch_size: usize,
remove_posts: bool,
dry_run: bool,
) -> Result<()> {
validate(
mattermost_data_directory,
database_name,
database_user,
database_host,
retention_days,
file_batch_size,
)?;
let connection_string = format!(
"postgres://{}:{}@{}:{}/{}?sslmode=disable",
database_user, database_password, database_host, database_port, database_name
);
trace!("Connection string: {}", &connection_string);
let (client, connection) = tokio_postgres::connect(&connection_string, NoTls)
.await
.context("Failed to connect to the database")?;
tokio::spawn(async move {
if let Err(e) = connection.await {
warn!("error happened at spawn {e}");
eprintln!("connection error: {}", e);
}
});
info!("Connection established: OK");
let millisecond_epoch = (Utc::now() - chrono::Duration::days(retention_days)).timestamp_millis();
clean_files(
&client,
millisecond_epoch,
mattermost_data_directory,
file_batch_size,
dry_run,
)
.await?;
delete_file_info_rows(&client, millisecond_epoch, dry_run).await?;
if remove_posts {
delete_post_rows(&client, millisecond_epoch, dry_run).await?;
} else {
info!("Skipping posts removal")
}
Ok(())
}
async fn clean_files(
client: &Client,
millisecond_epoch: i64,
mattermost_data_directory: &str,
file_batch_size: usize,
dry_run: bool,
) -> Result<()> {
let mut batch = 0;
let mut more_results = true;
while more_results {
more_results = clean_files_batch(
client,
millisecond_epoch,
mattermost_data_directory,
file_batch_size,
batch,
dry_run,
)
.await?;
batch += 1;
}
Ok(())
}
async fn clean_files_batch(
client: &Client,
millisecond_epoch: i64,
mattermost_data_directory: &str,
file_batch_size: usize,
batch: usize,
dry_run: bool,
) -> Result<bool> {
let query = "
SELECT path, thumbnailpath, previewpath
FROM fileinfo
WHERE createat < $1
OFFSET $2
LIMIT $3;
";
trace!("Querying: {}", &query);
let offset = (batch * file_batch_size) as i64;
let limit = file_batch_size as i64;
trace!("params: {} {} {}", &millisecond_epoch, &offset, &limit);
let rows = client
.query(query, &[&millisecond_epoch, &offset, &limit])
.await
.context("Failed to fetch file info rows")?;
let mut more_results = false;
for row in rows {
more_results = true;
let path: String = row.get("path");
let thumbnail_path: String = row.get("thumbnailpath");
let preview_path: String = row.get("previewpath");
if dry_run {
info!(
"[DRY RUN] Would remove: {:?}, {:?}, {:?}",
path, thumbnail_path, preview_path
);
} else {
remove_files(
mattermost_data_directory,
&path,
&thumbnail_path,
&preview_path,
)
.context("Failed to remove files")?;
}
}
Ok(more_results)
}
fn remove_files(
base_dir: &str,
path: &str,
thumbnail_path: &str,
preview_path: &str,
) -> Result<()> {
let files = [path, thumbnail_path, preview_path];
let mut num_deleted = 0;
for file in files {
if !file.is_empty() {
let full_path = Path::new(base_dir).join(file);
if full_path.exists() {
fs::remove_file(full_path.clone())
.context(format!("Failed to delete file: {:?}", &full_path))?;
trace!("Removed: {:#?} ", &full_path);
num_deleted += 1;
} else {
trace!("Path does not exist: {:#?} ", &full_path);
}
}
}
if num_deleted > 0 {
info!("Deleted: {} files. Main file: {}", num_deleted, path);
} else {
trace!("No files to be deleted");
}
Ok(())
}
async fn delete_file_info_rows(
client: &Client,
millisecond_epoch: i64,
dry_run: bool,
) -> Result<()> {
let query = "
DELETE FROM fileinfo
WHERE createat < $1;
";
trace!("Querying: {}", &query);
trace!("Params: {:#?}", &millisecond_epoch);
if dry_run {
info!(
"[DRY RUN] Would delete file info rows older than {}",
millisecond_epoch
);
return Ok(());
}
let result = client
.execute(query, &[&millisecond_epoch])
.await
.context("Failed to delete file info rows")?;
info!("Removed {} file information rows", result);
Ok(())
}
async fn delete_post_rows(client: &Client, millisecond_epoch: i64, dry_run: bool) -> Result<()> {
let query = "
DELETE FROM posts
WHERE createat < $1;
";
trace!("Querying: {}", &query);
trace!("Params: {:#?}", &millisecond_epoch);
if dry_run {
info!(
"[DRY RUN] Would delete post rows older than {}",
millisecond_epoch
);
return Ok(());
}
let result = client
.execute(query, &[&millisecond_epoch])
.await
.context("Failed to delete post rows")?;
info!("Removed {} post rows", result);
Ok(())
}
fn validate(
mattermost_data_directory: &str,
database_name: &str,
database_user: &str,
database_host: &str,
retention_days: i64,
file_batch_size: usize,
) -> Result<()> {
if mattermost_data_directory.is_empty()
|| database_name.is_empty()
|| database_user.is_empty()
|| database_host.is_empty()
|| retention_days <= 0
|| file_batch_size == 0
{
anyhow::bail!("Invalid input parameters");
}
Ok(())
}