~nickbp/originz

ref: 5dd7b397fc6f03ffa881424b6d84e6de73605ac6 originz/benches/server.rs -rw-r--r-- 11.8 KiB
5dd7b397Nick Parker Support filter params at the root config level again 1 year, 1 month ago
                                                                                
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
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket as SyncUdpSocket};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use async_lock::Barrier;
use async_net::UdpSocket;
use bytes::BytesMut;
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use futures_lite::FutureExt;
use lazy_static::lazy_static;
use packed_struct::prelude::*;
use tempfile;
use tracing::{debug, error, info};

use kapiti::codec::{domain_name, encoder::DNSMessageEncoder, message};
use kapiti::config::Config;
use kapiti::logging;
use kapiti::runner::Runner;
use kapiti::specs::enums_generated::{OpCode, ResourceClass, ResourceType, ResponseCode};
use kapiti::specs::message::{IntEnum, Question};

const LOCAL_EPHEMERAL_ENDPOINT: &str = "127.0.0.1:0";

const STUB_QUESTION_NAME: &str = "kapiti.io.";
const STUB_QUERY_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(1, 2, 4, 8));

const UPSTREAM_LATENCY_FAST: Duration = Duration::from_nanos(1);
const UPSTREAM_LATENCY_SLOW: Duration = Duration::from_millis(25);

lazy_static! {
    static ref STUB_REQUEST: BytesMut =
        write_stub_request().expect("Failed to create stub request");
}

/// Writes a DNS response/answer into the provided buffer
fn write_stub_response() -> Result<BytesMut> {
    let mut buf = BytesMut::with_capacity(4096);
    DNSMessageEncoder::new().encode_local_response(
        ResponseCode::NOERROR,
        0,
        &Question {
            name: STUB_QUESTION_NAME.to_string(),
            resource_type: IntEnum::Enum(ResourceType::A),
            resource_class: IntEnum::Enum(ResourceClass::INTERNET),
        },
        &None,
        Some(STUB_QUERY_IP),
        None,
        &mut buf,
    )?;

    Ok(buf)
}

/// Writes a DNS request/question into the provided buffer
fn write_stub_request() -> Result<BytesMut> {
    let mut buf = BytesMut::with_capacity(4096);
    message::write_header_bits(
        message::HeaderBits {
            id: 12345,

            is_response: true,
            op_code: Integer::from(OpCode::QUERY as u8),
            authoritative: false,
            truncated: false,
            recursion_desired: true,
            recursion_available: true,
            reserved_9: false,
            authentic_data: false,
            checking_disabled: false,
            response_code: Integer::from(ResponseCode::NOERROR as u8),

            question_count: 1,
            answer_count: 0,
            authority_count: 0,
            additional_count: 0,
        },
        &mut buf,
    )?;

    let mut ptr_offsets = domain_name::LabelOffsets::new();
    message::write_question(
        &Question {
            name: STUB_QUESTION_NAME.to_string(),
            resource_type: IntEnum::Enum(ResourceType::A),
            resource_class: IntEnum::Enum(ResourceClass::INTERNET),
        },
        &mut buf,
        &mut ptr_offsets,
    )?;

    Ok(buf)
}

#[derive(Debug)]
struct ResponseInfo {
    dest: SocketAddr,
    request0: u8,
    request1: u8,
}

enum UpstreamEvent {
    GotRequest(ResponseInfo),
    ResponseDue(ResponseInfo),
    Stop,
}

async fn run_udp_upstream(
    udp_sock: UdpSocket,
    latency: Duration,
    stop_upstream_rx: async_channel::Receiver<()>,
) -> Result<()> {
    let mut response_buffer = write_stub_response().expect("Failed to construct response buffer");
    let mut request_buffer: [u8; 4096] = [0; 4096];

    let (response_queue, queue_rx) = futures_delay_queue::delay_queue::<ResponseInfo>();
    // Wait until the queue is empty before trying to exit
    let mut queued_count: usize = 0;

    loop {
        let fut = (
            // Check if the queue has anything scheduled...
            async {
                match queue_rx.receive().await {
                    Some(item) => Ok(UpstreamEvent::ResponseDue(item)),
                    None => bail!("channel closed"),
                }
            }
        ).or(
            // Check if the socket has something to receive, or...
            async {
                let (size, dest) = udp_sock.recv_from(&mut request_buffer).await?;
                // Ensure that the response has a matching request ID (first two bytes)
                if size < 2 {
                    return Err(anyhow!("Expected request to have at least 2 bytes, but got {}", size));
                }
                let msg = ResponseInfo {
                    dest,
                    request0: request_buffer[0],
                    request1: request_buffer[1],
                };
                Ok(UpstreamEvent::GotRequest(msg))
            }
        ).or(
            // ... or check if we should be stopping.
            async {
                stop_upstream_rx.recv().await?;
                Ok(UpstreamEvent::Stop)
            }
        );

        match fut.await {
            Ok(UpstreamEvent::GotRequest(response_info)) => {
                queued_count += 1;
                debug!(
                    "Upstream got request from {:?}, scheduling reply for {:?} (queued: {})",
                    response_info.dest,
                    latency,
                    queued_count
                );
                response_queue.insert(response_info, latency);
            },
            Ok(UpstreamEvent::ResponseDue(response_info)) => {
                // Send the response we got back to the original requestor.
                queued_count -= 1;
                response_buffer[0] = response_info.request0;
                response_buffer[1] = response_info.request1;
                udp_sock
                    .send_to(&mut response_buffer, &response_info.dest)
                    .await
                    .expect("Failed to send DNS response");
                debug!(
                    "Upstream sent {} bytes to {:?} (queued: {})",
                    response_buffer.len(),
                    response_info.dest,
                    queued_count
                );
            },
            Ok(UpstreamEvent::Stop) => {
                return Ok(());
            },
            Err(e) => {
                error!("Upstream got error while waiting for next event: {}", e);
            }
        }
    }

}

fn start_udp_upstream(
    latency: Duration,
    stop_upstream_rx: async_channel::Receiver<()>,
) -> Result<(SocketAddr, JoinHandle<Result<()>>)> {
    let listen_addr_ephemeral = LOCAL_EPHEMERAL_ENDPOINT
        .to_socket_addrs()?
        .next()
        .with_context(|| "Invalid listen address")?;
    let upstream_sock = smol::block_on(UdpSocket::bind(listen_addr_ephemeral))
        .with_context(|| format!("Failed to listen on {}", listen_addr_ephemeral))?;
    let listen_addr_actual = upstream_sock.local_addr()?;
    debug!("Upstream running at {:?}", listen_addr_actual);

    Ok((
        listen_addr_actual,
        thread::spawn(move || {
            smol::block_on(run_udp_upstream(upstream_sock, latency, stop_upstream_rx))
                .with_context(|| format!("run_udp_upstream failed"))
        }),
    ))
}

struct RunInputs {
    client_sock: SyncUdpSocket,
    response_buffer: BytesMut,
}

fn setup_udp_requests(count: u64) -> Result<Vec<RunInputs>> {
    let client_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0);
    let mut inputs_vec = Vec::new();
    for _i in 0..count {
        let client_sock = SyncUdpSocket::bind(client_addr)?;
        client_sock.set_read_timeout(Some(Duration::from_millis(5000)))?;
        client_sock.set_write_timeout(Some(Duration::from_millis(5000)))?;
        let mut response_buffer = BytesMut::with_capacity(4096);
        // Ensure that the buffer has a SIZE suitable for socket.recv_from().
        // If we just leave it with the CAPACITY then it drops data.
        response_buffer.resize(response_buffer.capacity(), 0);
        inputs_vec.push(RunInputs {
            client_sock,
            response_buffer,
        });
    }
    Ok(inputs_vec)
}

/// Sets up and runs `count` requests, waiting for a response after each request.
/// Reinitializes every time so that `move` will work.
fn run_udp_requests(inputs_vec: Vec<RunInputs>, kapiti_udp_endpoint: SocketAddr) -> Result<()> {
    // Send requests for each entry in the batch
    for inputs in &inputs_vec {
        let sendsize = inputs
            .client_sock
            .send_to(&STUB_REQUEST[..], kapiti_udp_endpoint)
            .with_context(|| "send_to failed")?;
        debug!(
            "Bench client sent {} bytes to {:?}",
            sendsize, kapiti_udp_endpoint
        );
    }
    // Wait for responses to come back
    for mut inputs in inputs_vec {
        let (recvsize, recvfrom) = inputs
            .client_sock
            .recv_from(&mut inputs.response_buffer)
            .with_context(|| "recv_from failed: no response from kapiti")?;
        debug!("Bench client got {} bytes from {:?}", recvsize, recvfrom);
        if inputs.response_buffer[0] != STUB_REQUEST[0]
            || inputs.response_buffer[1] != STUB_REQUEST[1]
        {
            bail!(
                "Response doesn't have expected request ID:\n- request: {:?}\n-response: {:?}",
                &STUB_REQUEST[..],
                inputs.response_buffer
            );
        }
    }
    Ok(())
}

/// Requests coming in over UDP, upstream endpoint over UDP
fn run_udp_udp_test(
    c: &mut Criterion,
    name: &str,
    upstream_latency: Duration,
    samples: usize,
) -> Result<()> {
    let tmpstorage = tempfile::tempdir()?;

    // Use channels to notify threads to stop
    // In the stop_upstream case using a Barrier had false positives, probably because of multiple wait()
    // calls across the loop. So instead we use a channel since it supports repeated read checks.
    let (stop_upstream_tx, stop_upstream_rx): (
        async_channel::Sender<()>,
        async_channel::Receiver<()>,
    ) = async_channel::bounded(1);
    let stop_kapiti = Arc::new(Barrier::new(2));

    // Start upstream harness
    let (upstream_addr, upstream_join_handle) =
        start_udp_upstream(upstream_latency, stop_upstream_rx)?;
    let config = Config::new_for_test(
        tmpstorage
            .path()
            .to_str()
            .expect("invalid temp storage path"),
        upstream_addr.to_string(),
    );

    // Start kapiti server
    let runner = smol::block_on(async {
        return Runner::new("benchmark".to_string(), config).await;
    })?;
    let kapiti_udp_endpoint = runner.get_udp_endpoint()?;
    let stop_kapiti_copy = stop_kapiti.clone();
    let kapiti_join_handle = thread::spawn(move || smol::block_on(runner.run(stop_kapiti_copy)));

    // Run benchmark: See how quickly we can get responses from kapiti
    let run_count: u64 = 30;
    let mut group = c.benchmark_group("server");
    group.throughput(Throughput::Elements(run_count));
    group.sample_size(samples);
    group.bench_function(name, |b| {
        b.iter_batched(
            move || setup_udp_requests(run_count).expect("setup failed"),
            move |inputs_vec| {
                run_udp_requests(inputs_vec, kapiti_udp_endpoint).expect("client run failed")
            },
            BatchSize::LargeInput,
        )
    });
    group.finish();

    info!("Waiting for kapiti thread to exit...");
    smol::block_on(stop_kapiti.wait());
    kapiti_join_handle
        .join()
        .expect("failed to join kapiti thread")?;

    info!("Waiting for upstream thread to exit...");
    smol::block_on(stop_upstream_tx.send(()))?;
    upstream_join_handle
        .join()
        .expect("failed to join upstream harness thread")?;

    Ok(())
}

fn udp_udp_fast(c: &mut Criterion) {
    logging::init_logging(); // init once in first bench, then leave alone
    run_udp_udp_test(c, "fast", UPSTREAM_LATENCY_FAST, 50).expect("udp_udp test failed");
}

fn udp_udp_slow(c: &mut Criterion) {
    run_udp_udp_test(c, "slow", UPSTREAM_LATENCY_SLOW, 10).expect("udp_udp_slow test failed");
}

criterion_group!(benches, udp_udp_fast, udp_udp_slow);
criterion_main!(benches);