aboutsummaryrefslogtreecommitdiff
path: root/src/garage/repair/online.rs
blob: 2c5227d2d2f3688c1bafb9a52b08f1538fbf9c08 (plain) (blame)
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use tokio::sync::watch;

use garage_block::manager::BlockManager;
use garage_block::repair::ScrubWorkerCommand;

use garage_model::garage::Garage;
use garage_model::s3::block_ref_table::*;
use garage_model::s3::mpu_table::*;
use garage_model::s3::object_table::*;
use garage_model::s3::version_table::*;

use garage_table::replication::*;
use garage_table::*;

use garage_util::background::*;
use garage_util::data::*;
use garage_util::error::Error;
use garage_util::migrate::Migrate;

use crate::*;

const RC_REPAIR_ITER_COUNT: usize = 64;

pub async fn launch_online_repair(
	garage: &Arc<Garage>,
	bg: &BackgroundRunner,
	opt: RepairOpt,
) -> Result<(), Error> {
	match opt.what {
		RepairWhat::Tables => {
			info!("Launching a full sync of tables");
			garage.bucket_table.syncer.add_full_sync()?;
			garage.object_table.syncer.add_full_sync()?;
			garage.version_table.syncer.add_full_sync()?;
			garage.block_ref_table.syncer.add_full_sync()?;
			garage.key_table.syncer.add_full_sync()?;
		}
		RepairWhat::Versions => {
			info!("Repairing the versions table");
			bg.spawn_worker(TableRepairWorker::new(garage.clone(), RepairVersions));
		}
		RepairWhat::MultipartUploads => {
			info!("Repairing the multipart uploads table");
			bg.spawn_worker(TableRepairWorker::new(garage.clone(), RepairMpu));
		}
		RepairWhat::BlockRefs => {
			info!("Repairing the block refs table");
			bg.spawn_worker(TableRepairWorker::new(garage.clone(), RepairBlockRefs));
		}
		RepairWhat::BlockRc => {
			info!("Repairing the block reference counters");
			bg.spawn_worker(BlockRcRepair::new(
				garage.block_manager.clone(),
				garage.block_ref_table.clone(),
			));
		}
		RepairWhat::Blocks => {
			info!("Repairing the stored blocks");
			bg.spawn_worker(garage_block::repair::RepairWorker::new(
				garage.block_manager.clone(),
			));
		}
		RepairWhat::Scrub { cmd } => {
			let cmd = match cmd {
				ScrubCmd::Start => ScrubWorkerCommand::Start,
				ScrubCmd::Pause => ScrubWorkerCommand::Pause(Duration::from_secs(3600 * 24)),
				ScrubCmd::Resume => ScrubWorkerCommand::Resume,
				ScrubCmd::Cancel => ScrubWorkerCommand::Cancel,
				ScrubCmd::SetTranquility { tranquility } => {
					garage
						.block_manager
						.scrub_persister
						.set_with(|x| x.tranquility = tranquility)?;
					return Ok(());
				}
			};
			info!("Sending command to scrub worker: {:?}", cmd);
			garage.block_manager.send_scrub_command(cmd).await?;
		}
		RepairWhat::Rebalance => {
			info!("Rebalancing the stored blocks among storage locations");
			bg.spawn_worker(garage_block::repair::RebalanceWorker::new(
				garage.block_manager.clone(),
			));
		}
	}
	Ok(())
}

// ----

#[async_trait]
trait TableRepair: Send + Sync + 'static {
	type T: TableSchema;

	fn table(garage: &Garage) -> &Table<Self::T, TableShardedReplication>;

	async fn process(
		&mut self,
		garage: &Garage,
		entry: <<Self as TableRepair>::T as TableSchema>::E,
	) -> Result<bool, Error>;
}

struct TableRepairWorker<T: TableRepair> {
	garage: Arc<Garage>,
	pos: Vec<u8>,
	counter: usize,
	repairs: usize,
	inner: T,
}

impl<R: TableRepair> TableRepairWorker<R> {
	fn new(garage: Arc<Garage>, inner: R) -> Self {
		Self {
			garage,
			inner,
			pos: vec![],
			counter: 0,
			repairs: 0,
		}
	}
}

#[async_trait]
impl<R: TableRepair> Worker for TableRepairWorker<R> {
	fn name(&self) -> String {
		format!("{} repair worker", R::T::TABLE_NAME)
	}

	fn status(&self) -> WorkerStatus {
		WorkerStatus {
			progress: Some(format!("{} ({})", self.counter, self.repairs)),
			..Default::default()
		}
	}

	async fn work(&mut self, _must_exit: &mut watch::Receiver<bool>) -> Result<WorkerState, Error> {
		let (item_bytes, next_pos) = match R::table(&self.garage).data.store.get_gt(&self.pos)? {
			Some((k, v)) => (v, k),
			None => {
				info!(
					"{}: finished, done {}, fixed {}",
					self.name(),
					self.counter,
					self.repairs
				);
				return Ok(WorkerState::Done);
			}
		};

		let entry = <R::T as TableSchema>::E::decode(&item_bytes)
			.ok_or_message("Cannot decode table entry")?;
		if self.inner.process(&self.garage, entry).await? {
			self.repairs += 1;
		}

		self.counter += 1;
		self.pos = next_pos;

		Ok(WorkerState::Busy)
	}

	async fn wait_for_work(&mut self) -> WorkerState {
		unreachable!()
	}
}

// ----

struct RepairVersions;

#[async_trait]
impl TableRepair for RepairVersions {
	type T = VersionTable;

	fn table(garage: &Garage) -> &Table<Self::T, TableShardedReplication> {
		&garage.version_table
	}

	async fn process(&mut self, garage: &Garage, version: Version) -> Result<bool, Error> {
		if !version.deleted.get() {
			let ref_exists = match &version.backlink {
				VersionBacklink::Object { bucket_id, key } => garage
					.object_table
					.get(bucket_id, key)
					.await?
					.map(|o| {
						o.versions().iter().any(|x| {
							x.uuid == version.uuid && x.state != ObjectVersionState::Aborted
						})
					})
					.unwrap_or(false),
				VersionBacklink::MultipartUpload { upload_id } => garage
					.mpu_table
					.get(upload_id, &EmptyKey)
					.await?
					.map(|u| !u.deleted.get())
					.unwrap_or(false),
			};

			if !ref_exists {
				info!("Repair versions: marking version as deleted: {:?}", version);
				garage
					.version_table
					.insert(&Version::new(version.uuid, version.backlink, true))
					.await?;
				return Ok(true);
			}
		}

		Ok(false)
	}
}

// ----

struct RepairBlockRefs;

#[async_trait]
impl TableRepair for RepairBlockRefs {
	type T = BlockRefTable;

	fn table(garage: &Garage) -> &Table<Self::T, TableShardedReplication> {
		&garage.block_ref_table
	}

	async fn process(&mut self, garage: &Garage, mut block_ref: BlockRef) -> Result<bool, Error> {
		if !block_ref.deleted.get() {
			let ref_exists = garage
				.version_table
				.get(&block_ref.version, &EmptyKey)
				.await?
				.map(|v| !v.deleted.get())
				.unwrap_or(false);

			if !ref_exists {
				info!(
					"Repair block ref: marking block_ref as deleted: {:?}",
					block_ref
				);
				block_ref.deleted.set();
				garage.block_ref_table.insert(&block_ref).await?;
				return Ok(true);
			}
		}

		Ok(false)
	}
}

// ----

struct RepairMpu;

#[async_trait]
impl TableRepair for RepairMpu {
	type T = MultipartUploadTable;

	fn table(garage: &Garage) -> &Table<Self::T, TableShardedReplication> {
		&garage.mpu_table
	}

	async fn process(&mut self, garage: &Garage, mut mpu: MultipartUpload) -> Result<bool, Error> {
		if !mpu.deleted.get() {
			let ref_exists = garage
				.object_table
				.get(&mpu.bucket_id, &mpu.key)
				.await?
				.map(|o| {
					o.versions()
						.iter()
						.any(|x| x.uuid == mpu.upload_id && x.is_uploading(Some(true)))
				})
				.unwrap_or(false);

			if !ref_exists {
				info!(
					"Repair multipart uploads: marking mpu as deleted: {:?}",
					mpu
				);
				mpu.parts.clear();
				mpu.deleted.set();
				garage.mpu_table.insert(&mpu).await?;
				return Ok(true);
			}
		}

		Ok(false)
	}
}

// ===== block reference counter repair =====

pub struct BlockRcRepair {
	block_manager: Arc<BlockManager>,
	block_ref_table: Arc<Table<BlockRefTable, TableShardedReplication>>,
	cursor: Hash,
	counter: u64,
	repairs: u64,
}

impl BlockRcRepair {
	fn new(
		block_manager: Arc<BlockManager>,
		block_ref_table: Arc<Table<BlockRefTable, TableShardedReplication>>,
	) -> Self {
		Self {
			block_manager,
			block_ref_table,
			cursor: [0u8; 32].into(),
			counter: 0,
			repairs: 0,
		}
	}
}

#[async_trait]
impl Worker for BlockRcRepair {
	fn name(&self) -> String {
		format!("Block refcount repair worker")
	}

	fn status(&self) -> WorkerStatus {
		WorkerStatus {
			progress: Some(format!("{} ({})", self.counter, self.repairs)),
			..Default::default()
		}
	}

	async fn work(&mut self, _must_exit: &mut watch::Receiver<bool>) -> Result<WorkerState, Error> {
		for _i in 0..RC_REPAIR_ITER_COUNT {
			let next1 = self
				.block_manager
				.rc
				.rc_table
				.range(self.cursor.as_slice()..)?
				.next()
				.transpose()?
				.map(|(k, _)| Hash::try_from(k.as_slice()).unwrap());
			let next2 = self
				.block_ref_table
				.data
				.store
				.range(self.cursor.as_slice()..)?
				.next()
				.transpose()?
				.map(|(k, _)| Hash::try_from(&k[..32]).unwrap());
			let next = match (next1, next2) {
				(Some(k1), Some(k2)) => std::cmp::min(k1, k2),
				(Some(k), None) | (None, Some(k)) => k,
				(None, None) => {
					info!(
						"{}: finished, done {}, fixed {}",
						self.name(),
						self.counter,
						self.repairs
					);
					return Ok(WorkerState::Done);
				}
			};

			if self.block_manager.rc.recalculate_rc(&next)?.1 {
				self.repairs += 1;
			}
			self.counter += 1;
			if let Some(next_incr) = next.increment() {
				self.cursor = next_incr;
			} else {
				info!(
					"{}: finished, done {}, fixed {}",
					self.name(),
					self.counter,
					self.repairs
				);
				return Ok(WorkerState::Done);
			}
		}

		Ok(WorkerState::Busy)
	}

	async fn wait_for_work(&mut self) -> WorkerState {
		unreachable!()
	}
}