aboutsummaryrefslogtreecommitdiff
path: root/src/garage/cli/cmd.rs
blob: c7f0ad2b0b15b0db9fe6d04040cb5c7418140fad (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
use std::collections::{HashMap, HashSet};
use std::time::Duration;

use format_table::format_table;
use garage_util::error::*;

use garage_rpc::layout::*;
use garage_rpc::system::*;
use garage_rpc::*;

use garage_model::helper::error::Error as HelperError;

use crate::admin::*;
use crate::cli::*;

pub async fn cli_command_dispatch(
	cmd: Command,
	system_rpc_endpoint: &Endpoint<SystemRpc, ()>,
	admin_rpc_endpoint: &Endpoint<AdminRpc, ()>,
	rpc_host: NodeID,
) -> Result<(), HelperError> {
	match cmd {
		Command::Status => Ok(cmd_status(system_rpc_endpoint, rpc_host).await?),
		Command::Node(NodeOperation::Connect(connect_opt)) => {
			Ok(cmd_connect(system_rpc_endpoint, rpc_host, connect_opt).await?)
		}
		Command::Layout(layout_opt) => {
			Ok(cli_layout_command_dispatch(layout_opt, system_rpc_endpoint, rpc_host).await?)
		}
		Command::Bucket(bo) => {
			cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::BucketOperation(bo)).await
		}
		Command::Key(ko) => {
			cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::KeyOperation(ko)).await
		}
		Command::Migrate(mo) => {
			cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::Migrate(mo)).await
		}
		Command::Repair(ro) => {
			cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::LaunchRepair(ro)).await
		}
		Command::Stats(so) => cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::Stats(so)).await,
		Command::Worker(wo) => cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::Worker(wo)).await,
		Command::Block(bo) => {
			cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::BlockOperation(bo)).await
		}
		_ => unreachable!(),
	}
}

pub async fn cmd_status(rpc_cli: &Endpoint<SystemRpc, ()>, rpc_host: NodeID) -> Result<(), Error> {
	let status = match rpc_cli
		.call(&rpc_host, SystemRpc::GetKnownNodes, PRIO_NORMAL)
		.await??
	{
		SystemRpc::ReturnKnownNodes(nodes) => nodes,
		resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
	};
	let layout = fetch_layout(rpc_cli, rpc_host).await?;

	println!("==== HEALTHY NODES ====");
	let mut healthy_nodes =
		vec!["ID\tHostname\tAddress\tTags\tZone\tCapacity\tDataAvail".to_string()];
	for adv in status.iter().filter(|adv| adv.is_up) {
		let host = adv.status.hostname.as_deref().unwrap_or("?");
		if let Some(NodeRoleV(Some(cfg))) = layout.current().roles.get(&adv.id) {
			let data_avail = match &adv.status.data_disk_avail {
				_ if cfg.capacity.is_none() => "N/A".into(),
				Some((avail, total)) => {
					let pct = (*avail as f64) / (*total as f64) * 100.;
					let avail = bytesize::ByteSize::b(*avail);
					format!("{} ({:.1}%)", avail, pct)
				}
				None => "?".into(),
			};
			healthy_nodes.push(format!(
				"{id:?}\t{host}\t{addr}\t[{tags}]\t{zone}\t{capacity}\t{data_avail}",
				id = adv.id,
				host = host,
				addr = adv.addr,
				tags = cfg.tags.join(","),
				zone = cfg.zone,
				capacity = cfg.capacity_string(),
				data_avail = data_avail,
			));
		} else {
			let prev_role = layout
				.versions
				.iter()
				.rev()
				.find_map(|x| match x.roles.get(&adv.id) {
					Some(NodeRoleV(Some(cfg))) => Some(cfg),
					_ => None,
				});
			if let Some(cfg) = prev_role {
				healthy_nodes.push(format!(
					"{id:?}\t{host}\t{addr}\t[{tags}]\t{zone}\tdraining metadata...",
					id = adv.id,
					host = host,
					addr = adv.addr,
					tags = cfg.tags.join(","),
					zone = cfg.zone,
				));
			} else {
				let new_role = match layout.staging.get().roles.get(&adv.id) {
					Some(NodeRoleV(Some(_))) => "pending...",
					_ => "NO ROLE ASSIGNED",
				};
				healthy_nodes.push(format!(
					"{id:?}\t{h}\t{addr}\t\t\t{new_role}",
					id = adv.id,
					h = host,
					addr = adv.addr,
					new_role = new_role,
				));
			}
		}
	}
	format_table(healthy_nodes);

	// Determine which nodes are unhealthy and print that to stdout
	let status_map = status
		.iter()
		.map(|adv| (adv.id, adv))
		.collect::<HashMap<_, _>>();

	let tf = timeago::Formatter::new();
	let mut drain_msg = false;
	let mut failed_nodes =
		vec!["ID\tHostname\tAddress\tTags\tZone\tCapacity\tLast seen".to_string()];
	let mut listed = HashSet::new();
	for ver in layout.versions.iter().rev() {
		for (node, _, role) in ver.roles.items().iter() {
			let cfg = match role {
				NodeRoleV(Some(role)) if role.capacity.is_some() => role,
				_ => continue,
			};

			if listed.contains(node) {
				continue;
			}
			listed.insert(*node);

			let adv = status_map.get(node);
			if adv.map(|x| x.is_up).unwrap_or(false) {
				continue;
			}

			// Node is in a layout version, is not a gateway node, and is not up:
			// it is in a failed state, add proper line to the output
			let (host, addr, last_seen) = match adv {
				Some(adv) => (
					adv.status.hostname.as_deref().unwrap_or("?"),
					adv.addr.to_string(),
					adv.last_seen_secs_ago
						.map(|s| tf.convert(Duration::from_secs(s)))
						.unwrap_or_else(|| "never seen".into()),
				),
				None => ("??", "??".into(), "never seen".into()),
			};
			let capacity = if ver.version == layout.current().version {
				cfg.capacity_string()
			} else {
				drain_msg = true;
				"draining metadata...".to_string()
			};
			failed_nodes.push(format!(
				"{id:?}\t{host}\t{addr}\t[{tags}]\t{zone}\t{capacity}\t{last_seen}",
				id = node,
				host = host,
				addr = addr,
				tags = cfg.tags.join(","),
				zone = cfg.zone,
				capacity = capacity,
				last_seen = last_seen,
			));
		}
	}

	if failed_nodes.len() > 1 {
		println!("\n==== FAILED NODES ====");
		format_table(failed_nodes);
		if drain_msg {
			println!();
			println!("Your cluster is expecting to drain data from nodes that are currently unavailable.");
			println!("If these nodes are definitely dead, please review the layout history with");
			println!(
				"`garage layout history` and use `garage layout assume-sync` to force progress."
			);
		}
	}

	if print_staging_role_changes(&layout) {
		println!();
		println!("Please use `garage layout show` to check the proposed new layout and apply it.");
		println!();
	}

	Ok(())
}

pub async fn cmd_connect(
	rpc_cli: &Endpoint<SystemRpc, ()>,
	rpc_host: NodeID,
	args: ConnectNodeOpt,
) -> Result<(), Error> {
	match rpc_cli
		.call(&rpc_host, SystemRpc::Connect(args.node), PRIO_NORMAL)
		.await??
	{
		SystemRpc::Ok => {
			println!("Success.");
			Ok(())
		}
		m => Err(Error::unexpected_rpc_message(m)),
	}
}

pub async fn cmd_admin(
	rpc_cli: &Endpoint<AdminRpc, ()>,
	rpc_host: NodeID,
	args: AdminRpc,
) -> Result<(), HelperError> {
	match rpc_cli.call(&rpc_host, args, PRIO_NORMAL).await?? {
		AdminRpc::Ok(msg) => {
			println!("{}", msg);
		}
		AdminRpc::BucketList(bl) => {
			print_bucket_list(bl);
		}
		AdminRpc::BucketInfo {
			bucket,
			relevant_keys,
			counters,
			mpu_counters,
		} => {
			print_bucket_info(&bucket, &relevant_keys, &counters, &mpu_counters);
		}
		AdminRpc::KeyList(kl) => {
			print_key_list(kl);
		}
		AdminRpc::KeyInfo(key, rb) => {
			print_key_info(&key, &rb);
		}
		AdminRpc::WorkerList(wi, wlo) => {
			print_worker_list(wi, wlo);
		}
		AdminRpc::WorkerVars(wv) => {
			print_worker_vars(wv);
		}
		AdminRpc::WorkerInfo(tid, wi) => {
			print_worker_info(tid, wi);
		}
		AdminRpc::BlockErrorList(el) => {
			print_block_error_list(el);
		}
		AdminRpc::BlockInfo {
			hash,
			refcount,
			versions,
			uploads,
		} => {
			print_block_info(hash, refcount, versions, uploads);
		}
		r => {
			error!("Unexpected response: {:?}", r);
		}
	}
	Ok(())
}