aboutsummaryrefslogtreecommitdiff
path: root/src/rpc/layout/history.rs
blob: 69348873086f5144ac9aa84bed6babdadf65d132 (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
use std::borrow::Cow;
use std::collections::HashSet;

use garage_util::crdt::{Crdt, Lww, LwwMap};
use garage_util::data::*;
use garage_util::encode::nonversioned_encode;
use garage_util::error::*;

use super::schema::*;
use super::*;

impl LayoutHistory {
	pub fn new(replication_factor: usize) -> Self {
		let version = LayoutVersion::new(replication_factor);

		let staging = LayoutStaging {
			parameters: Lww::<LayoutParameters>::new(version.parameters),
			roles: LwwMap::new(),
		};

		let mut ret = LayoutHistory {
			versions: vec![version],
			update_trackers: Default::default(),
			trackers_hash: [0u8; 32].into(),
			staging: Lww::raw(0, staging),
			staging_hash: [0u8; 32].into(),
		};
		ret.update_hashes();
		ret
	}

	pub fn current(&self) -> &LayoutVersion {
		self.versions.last().as_ref().unwrap()
	}

	pub fn update_hashes(&mut self) {
		self.trackers_hash = self.calculate_trackers_hash();
		self.staging_hash = self.calculate_staging_hash();
	}

	pub(crate) fn calculate_trackers_hash(&self) -> Hash {
		blake2sum(&nonversioned_encode(&self.update_trackers).unwrap()[..])
	}

	pub(crate) fn calculate_staging_hash(&self) -> Hash {
		blake2sum(&nonversioned_encode(&self.staging).unwrap()[..])
	}

	// ------------------ who stores what now? ---------------

	pub fn all_ack(&self) -> u64 {
		self.calculate_global_min(&self.update_trackers.ack_map)
	}

	pub fn min_stored(&self) -> u64 {
		self.versions.first().as_ref().unwrap().version
	}

	pub fn sync_versions(&self) -> (u64, u64, u64) {
		(self.current().version, self.all_ack(), self.min_stored())
	}

	pub fn all_nodes(&self) -> Cow<'_, [Uuid]> {
		// TODO: cache this
		if self.versions.len() == 1 {
			self.versions[0].all_nodes().into()
		} else {
			let set = self
				.versions
				.iter()
				.map(|x| x.all_nodes())
				.flatten()
				.collect::<HashSet<_>>();
			set.into_iter().copied().collect::<Vec<_>>().into()
		}
	}

	pub fn all_nongateway_nodes(&self) -> Cow<'_, [Uuid]> {
		// TODO: cache this
		if self.versions.len() == 1 {
			self.versions[0].nongateway_nodes().into()
		} else {
			let set = self
				.versions
				.iter()
				.map(|x| x.nongateway_nodes())
				.flatten()
				.collect::<HashSet<_>>();
			set.into_iter().copied().collect::<Vec<_>>().into()
		}
	}

	pub fn read_nodes_of(&self, position: &Hash) -> Vec<Uuid> {
		let sync_min = self.calculate_global_min(&self.update_trackers.sync_map);
		let version = self
			.versions
			.iter()
			.find(|x| x.version == sync_min)
			.or(self.versions.last())
			.unwrap();
		version.nodes_of(position, version.replication_factor)
	}

	pub fn write_sets_of<'a>(&'a self, position: &'a Hash) -> impl Iterator<Item = Vec<Uuid>> + 'a {
		self.versions
			.iter()
			.map(move |x| x.nodes_of(position, x.replication_factor))
	}

	// ------------------ update tracking ---------------

	pub(crate) fn update_trackers(&mut self, node_id: Uuid) {
		// Ensure trackers for this node's values are up-to-date

		// 1. Acknowledge the last layout version in the history
		self.ack_last(node_id);

		// 2. Assume the data on this node is sync'ed up at least to
		//    the first layout version in the history
		self.sync_first(node_id);

		// 3. Acknowledge everyone has synced up to min(self.sync_map)
		self.sync_ack(node_id);

		// 4. Cleanup layout versions that are not needed anymore
		self.cleanup_old_versions();

		info!("ack_map: {:?}", self.update_trackers.ack_map);
		info!("sync_map: {:?}", self.update_trackers.sync_map);
		info!("sync_ack_map: {:?}", self.update_trackers.sync_ack_map);

		// Finally, update hashes
		self.update_hashes();
	}

	pub(crate) fn ack_last(&mut self, node: Uuid) {
		let last_version = self.current().version;
		self.update_trackers.ack_map.set_max(node, last_version);
	}

	pub(crate) fn sync_first(&mut self, node: Uuid) {
		let first_version = self.versions.first().as_ref().unwrap().version;
		self.update_trackers.sync_map.set_max(node, first_version);
	}

	pub(crate) fn sync_ack(&mut self, node: Uuid) {
		self.update_trackers.sync_ack_map.set_max(
			node,
			self.calculate_global_min(&self.update_trackers.sync_map),
		);
	}

	pub(crate) fn cleanup_old_versions(&mut self) {
		let min_sync_ack = self.calculate_global_min(&self.update_trackers.sync_ack_map);
		while self.versions.first().as_ref().unwrap().version < min_sync_ack {
			let removed = self.versions.remove(0);
			info!("Layout history: pruning old version {}", removed.version);
		}
	}

	pub(crate) fn calculate_global_min(&self, tracker: &UpdateTracker) -> u64 {
		// TODO: for TableFullReplication, counting gateway nodes might be
		// necessary? Think about this more.
		let storage_nodes = self.all_nongateway_nodes();
		storage_nodes
			.iter()
			.map(|x| tracker.0.get(x).copied().unwrap_or(0))
			.min()
			.unwrap_or(0)
	}

	// ================== updates to layout, public interface ===================

	pub fn merge(&mut self, other: &LayoutHistory) -> bool {
		let mut changed = false;

		// Add any new versions to history
		for v2 in other.versions.iter() {
			if let Some(v1) = self.versions.iter().find(|v| v.version == v2.version) {
				if v1 != v2 {
					error!("Inconsistent layout histories: different layout compositions for version {}. Your cluster will be broken as long as this layout version is not replaced.", v2.version);
				}
			} else if self.versions.iter().all(|v| v.version != v2.version - 1) {
				error!(
					"Cannot receive new layout version {}, version {} is missing",
					v2.version,
					v2.version - 1
				);
			} else {
				self.versions.push(v2.clone());
				changed = true;
			}
		}

		// Merge trackers
		if self.update_trackers != other.update_trackers {
			let c = self.update_trackers.merge(&other.update_trackers);
			changed = changed || c;
		}

		// Merge staged layout changes
		if self.staging != other.staging {
			self.staging.merge(&other.staging);
			changed = true;
		}

		changed
	}

	pub fn apply_staged_changes(mut self, version: Option<u64>) -> Result<(Self, Message), Error> {
		match version {
			None => {
				let error = r#"
Please pass the new layout version number to ensure that you are writing the correct version of the cluster layout.
To know the correct value of the new layout version, invoke `garage layout show` and review the proposed changes.
				"#;
				return Err(Error::Message(error.into()));
			}
			Some(v) => {
				if v != self.current().version + 1 {
					return Err(Error::Message("Invalid new layout version".into()));
				}
			}
		}

		// Compute new version and add it to history
		let (new_version, msg) = self
			.current()
			.clone()
			.calculate_next_version(&self.staging.get())?;

		self.versions.push(new_version);
		if self.current().check().is_ok() {
			while self.versions.first().unwrap().check().is_err() {
				self.versions.remove(0);
			}
		}

		// Reset the staged layout changes
		self.staging.update(LayoutStaging {
			parameters: self.staging.get().parameters.clone(),
			roles: LwwMap::new(),
		});
		self.update_hashes();

		Ok((self, msg))
	}

	pub fn revert_staged_changes(mut self) -> Result<Self, Error> {
		self.staging.update(LayoutStaging {
			parameters: Lww::new(self.current().parameters.clone()),
			roles: LwwMap::new(),
		});
		self.update_hashes();

		Ok(self)
	}

	pub fn check(&self) -> Result<(), String> {
		// Check that the hash of the staging data is correct
		if self.trackers_hash != self.calculate_trackers_hash() {
			return Err("trackers_hash is incorrect".into());
		}
		if self.staging_hash != self.calculate_staging_hash() {
			return Err("staging_hash is incorrect".into());
		}

		for version in self.versions.iter() {
			version.check()?;
		}

		// TODO: anything more ?
		Ok(())
	}
}