/
logical.rs
336 lines (310 loc) · 12 KB
/
logical.rs
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
use super::{Concrete, Endpoint, Logical};
use crate::{endpoint, resolve, Outbound};
use linkerd_app_core::{
config, drain, io, profiles,
proxy::{
api_resolve::{ConcreteAddr, Metadata},
core::Resolve,
resolve::map_endpoint,
tcp,
},
svc, Conditional, Error, Never,
};
use tracing::debug_span;
impl<C> Outbound<C>
where
C: svc::Service<Endpoint> + Clone + Send + 'static,
C::Response: io::AsyncRead + io::AsyncWrite + Send + Unpin,
C::Error: Into<Error>,
C::Future: Send,
{
/// Constructs a TCP load balancer.
pub fn push_tcp_logical<I, R>(
self,
resolve: R,
) -> Outbound<
svc::BoxNewService<
Logical,
impl svc::Service<I, Response = (), Error = Error, Future = impl Send> + Clone,
>,
>
where
I: io::AsyncRead + io::AsyncWrite + std::fmt::Debug + Send + Unpin + 'static,
R: Resolve<ConcreteAddr, Endpoint = Metadata, Error = Error>
+ Clone
+ Send
+ Sync
+ 'static,
R::Resolution: Send,
R::Future: Send + Unpin,
C: Send + Sync + 'static,
{
let Self {
config,
runtime: rt,
stack: connect,
} = self;
let config::ProxyConfig {
buffer_capacity,
cache_max_idle_age,
dispatch_timeout,
..
} = config.proxy;
let identity_disabled = rt.identity.is_none();
let resolve = svc::stack(resolve.into_service())
.check_service::<ConcreteAddr>()
.push_request_filter(|c: Concrete| Ok::<_, Never>(c.resolve))
.push(svc::layer::mk(move |inner| {
map_endpoint::Resolve::new(endpoint::FromMetadata { identity_disabled }, inner)
}))
.check_service::<Concrete>()
.into_inner();
let stack = connect
.push_make_thunk()
.instrument(|t: &Endpoint| match t.tls.as_ref() {
Conditional::Some(tls) => {
debug_span!("endpoint", server.addr = %t.addr, server.id = ?tls.server_id)
}
Conditional::None(_) => {
debug_span!("endpoint", server.addr = %t.addr)
}
})
.push(resolve::layer(resolve, config.proxy.cache_max_idle_age * 2))
.push_on_response(
svc::layers()
.push(tcp::balance::layer(
crate::EWMA_DEFAULT_RTT,
crate::EWMA_DECAY,
))
.push(
rt.metrics
.stack
.layer(crate::stack_labels("tcp", "balancer")),
)
.push(tcp::Forward::layer())
.push(drain::Retain::layer(rt.drain.clone())),
)
.into_new_service()
.push_map_target(Concrete::from)
.push(svc::BoxNewService::layer())
.check_new_service::<(ConcreteAddr, Logical), I>()
.push(profiles::split::layer())
.push_on_response(
svc::layers()
.push(
rt.metrics
.stack
.layer(crate::stack_labels("tcp", "logical")),
)
.push(svc::layer::mk(svc::SpawnReady::new))
.push(svc::FailFast::layer("TCP Logical", dispatch_timeout))
.push_spawn_buffer(buffer_capacity),
)
.push_cache(cache_max_idle_age)
.check_new_service::<Logical, I>()
.instrument(|_: &Logical| debug_span!("tcp"))
.check_new_service::<Logical, I>()
.push(svc::BoxNewService::layer());
Outbound {
config,
runtime: rt,
stack,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::*;
use io::AsyncWriteExt;
use linkerd_app_core::{
io::{self, AsyncReadExt},
profiles::{LogicalAddr, Profile},
svc::{self, timeout::FailFastError, NewService, ServiceExt},
transport::addrs::*,
};
use std::net::SocketAddr;
use tokio::time;
/// Tests that the logical stack forwards connections to services with a single endpoint.
#[tokio::test]
async fn forward() {
let _trace = linkerd_tracing::test::trace_init();
time::pause();
// We create a logical target to be resolved to endpoints.
let logical_addr = LogicalAddr("xyz.example.com:4444".parse().unwrap());
let (_tx, rx) = tokio::sync::watch::channel(Profile {
addr: Some(logical_addr.clone()),
..Default::default()
});
let logical = Logical {
profile: rx.into(),
logical_addr: logical_addr.clone(),
protocol: (),
};
// The resolution resolves a single endpoint.
let ep_addr = SocketAddr::new([192, 0, 2, 30].into(), 3333);
let resolve =
support::resolver().endpoint_exists(logical_addr.clone(), ep_addr, Default::default());
let resolved = resolve.handle();
// Build the TCP logical stack with a mocked connector.
let (rt, _shutdown) = runtime();
let mut stack = Outbound::new(default_config(), rt)
.with_stack(svc::mk(move |ep: Endpoint| {
assert_eq!(*ep.addr.as_ref(), ep_addr);
let mut io = support::io();
io.write(b"hola").read(b"mundo");
future::ok::<_, support::io::Error>(io.build())
}))
.push_tcp_logical(resolve)
.into_inner();
// Build a client to the endpoint and proxy a connection.
let mut io = support::io();
io.read(b"hola").write(b"mundo");
stack
.new_service(logical.clone())
.oneshot(io.build())
.await
.expect("forwarding must not fail");
assert!(resolved.only_configured(), "endpoint not discovered?");
// Rebuilding it succeeds and reuses a cached service.
let mut io = support::io();
io.read(b"hola").write(b"mundo");
stack
.new_service(logical)
.oneshot(io.build())
.await
.expect("forwarding must not fail");
assert!(resolved.only_configured(), "Resolution not reused");
}
/// Tests that the logical stack forwards connections to services with an arbitrary number of
/// endpoints.
///
/// - Initially one endpoint is used.
/// - Then, another endpoint is introduced and we confirm that we use both.
/// - Then, the first endpoint is removed and we confirm that we only use the second.
/// - Then, all endpoints are removed and we confirm that we hit fail-fast error.
#[tokio::test]
async fn balances() {
let _trace = linkerd_tracing::test::trace_init();
time::pause();
// We create a logical target to be resolved to endpoints.
let logical_addr = LogicalAddr("xyz.example.com:4444".parse().unwrap());
let (_tx, rx) = tokio::sync::watch::channel(Profile {
addr: Some(logical_addr.clone()),
..Default::default()
});
let logical = Logical {
profile: rx.into(),
logical_addr: logical_addr.clone(),
protocol: (),
};
// The resolution resolves a single endpoint.
let ep0_addr = SocketAddr::new([192, 0, 2, 30].into(), 3333);
let ep1_addr = SocketAddr::new([192, 0, 2, 31].into(), 3333);
let resolve = support::resolver();
let resolved = resolve.handle();
let mut resolve_tx = resolve.endpoint_tx(logical_addr);
// Build the TCP logical stack with a mocked endpoint stack that alters its response stream
// based on the address.
let (rt, _shutdown) = runtime();
let svc = Outbound::new(default_config(), rt)
.with_stack(svc::mk(move |ep: Endpoint| match ep.addr {
Remote(ServerAddr(addr)) if addr == ep0_addr => {
tracing::debug!(%addr, "writing ep0");
let mut io = support::io();
io.write(b"who r u?").read(b"ep0");
future::ok::<_, support::io::Error>(io.build())
}
Remote(ServerAddr(addr)) if addr == ep1_addr => {
tracing::debug!(%addr, "writing ep1");
let mut io = support::io();
io.write(b"who r u?").read(b"ep1");
future::ok::<_, support::io::Error>(io.build())
}
addr => unreachable!("unexpected endpoint: {}", addr),
}))
.push_tcp_logical(resolve)
.into_inner()
.new_service(logical);
// We add a single endpoint to the balancer and it is used:
resolve_tx
.add(Some((ep0_addr, Default::default())))
.unwrap();
tokio::task::yield_now().await; // Let the balancer observe the update.
let (io, task) = spawn_io();
svc.clone().oneshot(io).await.unwrap();
let msg = task.await.unwrap().unwrap();
assert_eq!(msg, "ep0");
// When we add a second endpoint, traffic is sent to both endpoints:
resolve_tx
.add(Some((ep1_addr, Default::default())))
.unwrap();
tokio::task::yield_now().await; // Let the balancer observe the update.
let mut seen0 = false;
let mut seen1 = false;
for i in 1..=100 {
let (io, task) = spawn_io();
svc.clone().oneshot(io).await.unwrap();
let msg = task.await.unwrap().unwrap();
match msg.as_str() {
"ep0" => {
seen0 = true;
}
"ep1" => {
seen1 = true;
}
msg => unreachable!("unexpected read: {}", msg),
}
assert!(resolved.only_configured(), "Resolution must be reused");
if seen0 && seen1 {
tracing::info!("Both endpoints observed after {} iters", i);
break;
}
if i % 10 == 0 {
tracing::debug!(iters = i, ep0 = seen0, ep1 = seen1);
}
}
assert!(
seen0 && seen1,
"Both endpoints must be used; ep0={} ep1={}",
seen0,
seen1
);
// When we remove the ep0, all traffic goes to ep1:
resolve_tx.remove(Some(ep0_addr)).unwrap();
tokio::task::yield_now().await; // Let the balancer observe the update.
for _ in 1..=100 {
let (io, task) = spawn_io();
svc.clone().oneshot(io).await.unwrap();
let msg = task.await.unwrap().unwrap();
assert_eq!(msg, "ep1", "Communicating with a defunct endpoint");
assert!(resolved.only_configured(), "Resolution must be reused");
}
// Empty load balancers hit fail-fast errors:
resolve_tx.remove(Some(ep1_addr)).unwrap();
tokio::task::yield_now().await; // Let the balancer observe the update.
let (io, task) = spawn_io();
let err = svc
.clone()
.oneshot(io)
.await
.expect_err("Empty balancer must timeout");
task.abort();
assert!(err.downcast_ref::<FailFastError>().is_some());
assert!(resolved.only_configured(), "Resolution must be reused");
}
/// Balancer test helper that runs client I/O on a task.
fn spawn_io() -> (
io::DuplexStream,
tokio::task::JoinHandle<io::Result<String>>,
) {
let (mut client_io, server_io) = io::duplex(100);
let task = tokio::spawn(async move {
client_io.write_all(b"who r u?").await?;
let mut buf = String::with_capacity(100);
client_io.read_to_string(&mut buf).await?;
Ok(buf)
});
(server_io, task)
}
}