aboutsummaryrefslogtreecommitdiff
path: root/src/proxy_config.rs
blob: deb2ffe4a369fbea937077334d8e1a7b41cc6151 (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
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{atomic, Arc};
use std::{cmp, time::Duration};

use anyhow::Result;

use futures::future::BoxFuture;
use futures::stream::{FuturesUnordered, StreamExt};

use log::*;
use tokio::{sync::watch, time::sleep};

use crate::consul::*;

// ---- Extract proxy config from Consul catalog ----

#[derive(Debug)]
pub enum HostDescription {
	Hostname(String),
	Pattern(glob::Pattern),
}

impl HostDescription {
	fn new(desc: &str) -> Result<Self> {
		if desc.chars().any(|x| matches!(x, '*' | '?' | '[' | ']')) {
			Ok(Self::Pattern(glob::Pattern::new(desc)?))
		} else {
			Ok(Self::Hostname(desc.to_string()))
		}
	}

	pub fn matches(&self, v: &str) -> bool {
		match self {
			Self::Pattern(p) => p.matches(v),
			Self::Hostname(s) => s == v,
		}
	}
}

#[derive(Debug)]
pub struct ProxyEntry {
	pub target_addr: SocketAddr,
	pub https_target: bool,

	pub host: HostDescription,
	pub path_prefix: Option<String>,
	pub priority: u32,
	pub add_headers: Vec<(String, String)>,

	// Counts the number of times this proxy server has been called to
	// This implements a round-robin load balancer if there are multiple
	// entries for the same host and same path prefix.
	pub calls: atomic::AtomicI64,
}

impl std::fmt::Display for ProxyEntry {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		if self.https_target {
			write!(f, "https://")?;
		}
		write!(f, "{} ", self.target_addr)?;
		match &self.host {
			HostDescription::Hostname(h) => write!(f, "{}", h)?,
			HostDescription::Pattern(p) => write!(f, "Pattern('{}')", p.as_str())?,
		}
		write!(
			f,
			"{} {}",
			self.path_prefix.as_ref().unwrap_or(&String::new()),
			self.priority
		)?;
		if !self.add_headers.is_empty() {
			write!(f, " +Headers: {:?}", self.add_headers)?;
		}
		write!(f, " ({})", self.calls.load(atomic::Ordering::Relaxed))
	}
}

#[derive(Debug)]
pub struct ProxyConfig {
	pub entries: Vec<ProxyEntry>,
}

fn retry_to_time(retries: u32, max_time: Duration) -> Duration {
	// 1.2^x seems to be a good value to exponentially increase time at a good pace
	// eg. 1.2^32 = 341 seconds ~= 5 minutes - ie. after 32 retries we wait 5
	// minutes
	Duration::from_secs(cmp::min(
		max_time.as_secs(),
		1.2f64.powf(retries as f64) as u64,
	))
}

fn parse_tricot_tag(
	tag: &str,
	target_addr: SocketAddr,
	add_headers: &[(String, String)],
) -> Option<ProxyEntry> {
	let splits = tag.split(' ').collect::<Vec<_>>();
	if (splits.len() != 2 && splits.len() != 3)
		|| (splits[0] != "tricot" && splits[0] != "tricot-https")
	{
		return None;
	}

	let (host, path_prefix) = match splits[1].find('/') {
		Some(i) => {
			let (host, pp) = splits[1].split_at(i);
			(host, Some(pp.to_string()))
		}
		None => (splits[1], None),
	};

	let priority = match splits.len() {
		3 => splits[2].parse().ok()?,
		_ => 100,
	};

	let host = match HostDescription::new(host) {
		Ok(h) => h,
		Err(e) => {
			warn!("Invalid hostname pattern {}: {}", host, e);
			return None;
		}
	};

	Some(ProxyEntry {
		target_addr,
		https_target: (splits[0] == "tricot-https"),
		host,
		path_prefix,
		priority,
		add_headers: add_headers.to_vec(),
		calls: atomic::AtomicI64::from(0),
	})
}

fn parse_tricot_add_header_tag(tag: &str) -> Option<(String, String)> {
	let splits = tag.split(' ').collect::<Vec<_>>();
	if splits.len() == 3 && splits[0] == "tricot-add-header" {
		Some((splits[1].to_string(), splits[2].to_string()))
	} else {
		None
	}
}

fn parse_consul_catalog(catalog: &ConsulNodeCatalog) -> Vec<ProxyEntry> {
	trace!("Parsing node catalog: {:#?}", catalog);

	let mut entries = vec![];

	for (_, svc) in catalog.services.iter() {
		let ip_addr = match svc.address.parse() {
			Ok(ip) => ip,
			_ => match catalog.node.address.parse() {
				Ok(ip) => ip,
				_ => {
					warn!(
						"Could not get address for service {} at node {}",
						svc.service, catalog.node.node
					);
					continue;
				}
			},
		};
		let addr = SocketAddr::new(ip_addr, svc.port);

		let mut add_headers = vec![];
		for tag in svc.tags.iter() {
			if let Some(pair) = parse_tricot_add_header_tag(tag) {
				add_headers.push(pair);
			}
		}

		for tag in svc.tags.iter() {
			if let Some(ent) = parse_tricot_tag(tag, addr, &add_headers[..]) {
				entries.push(ent);
			}
		}
	}

	trace!("Result of parsing catalog:");
	for ent in entries.iter() {
		trace!("    {}", ent);
	}

	entries
}

#[derive(Default)]
struct NodeWatchState {
	last_idx: Option<usize>,
	last_catalog: Option<ConsulNodeCatalog>,
	retries: u32,
}

pub fn spawn_proxy_config_task(consul: Consul) -> watch::Receiver<Arc<ProxyConfig>> {
	let (tx, rx) = watch::channel(Arc::new(ProxyConfig {
		entries: Vec::new(),
	}));

	let consul = Arc::new(consul);

	tokio::spawn(async move {
		let mut nodes = HashMap::new();
		let mut watches = FuturesUnordered::<BoxFuture<'static, (String, Result<_>)>>::new();

		loop {
			match consul.list_nodes().await {
				Ok(consul_nodes) => {
					info!("Watched consul nodes: {:?}", consul_nodes);
					for node in consul_nodes {
						if !nodes.contains_key(&node) {
							nodes.insert(node.clone(), NodeWatchState::default());

							let node = node.to_string();
							let consul = consul.clone();

							watches.push(Box::pin(async move {
								let res = consul.watch_node(&node, None).await;
								(node, res)
							}));
						}
					}
				}
				Err(e) => {
					warn!("Could not get Consul node list: {}", e);
				}
			}

			let (node, res): (String, Result<_>) = match watches.next().await {
				Some(v) => v,
				None => {
					warn!("No nodes currently watched in proxy_config.rs");
					sleep(Duration::from_secs(10)).await;
					continue;
				}
			};

			match res {
				Ok((catalog, new_idx)) => {
					let mut watch_state = nodes.get_mut(&node).unwrap();
					watch_state.last_idx = Some(new_idx);
					watch_state.last_catalog = Some(catalog);
					watch_state.retries = 0;

					let idx = watch_state.last_idx;
					let consul = consul.clone();
					watches.push(Box::pin(async move {
						let res = consul.watch_node(&node, idx).await;
						(node, res)
					}));
				}
				Err(e) => {
					let mut watch_state = nodes.get_mut(&node).unwrap();
					watch_state.retries += 1;
					watch_state.last_idx = None;

					let will_retry_in =
						retry_to_time(watch_state.retries, Duration::from_secs(600));
					error!(
						"Failed to query consul for node {}. Will retry in {}s. {}",
						node,
						will_retry_in.as_secs(),
						e
					);

					let consul = consul.clone();
					watches.push(Box::pin(async move {
						sleep(will_retry_in).await;
						let res = consul.watch_node(&node, None).await;
						(node, res)
					}));
					continue;
				}
			}

			let mut entries = vec![];
			for (_, watch_state) in nodes.iter() {
				if let Some(catalog) = &watch_state.last_catalog {
					entries.extend(parse_consul_catalog(catalog));
				}
			}
			let config = ProxyConfig { entries };

			tx.send(Arc::new(config)).expect("Internal error");
		}
	});

	rx
}