~nickbp/originz

ref: fbaed2a25114cf06aaa5d509c0d19d28ac4faa6d originz/benches/server.rs -rw-r--r-- 9.3 KiB
fbaed2a2Nick Parker Implement benchmark test for UDP client/UDP upstream (#10) 1 year, 11 months 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
#![deny(warnings, rust_2018_idioms)]

use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::Duration;

use anyhow::{bail, Context, Result};
use bytes::BytesMut;
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use crossbeam_queue::ArrayQueue;
use lazy_static::lazy_static;
use packed_struct::prelude::*;
use tempfile;
use tokio::runtime::Runtime;
use tracing::debug;

use kapiti::codec::{domain_name, encoder::DNSMessageEncoder, message};
use kapiti::config::Config;
use kapiti::fbs::dns_enums_generated::{ResourceClass, ResourceType, ResponseCode};
use kapiti::fbs::dns_message_generated::{Question, QuestionArgs};
use kapiti::logging;
use kapiti::runner::Runner;

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

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

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

fn build_stub_question<'a>() -> flatbuffers::FlatBufferBuilder<'a> {
    let mut fbb = flatbuffers::FlatBufferBuilder::new_with_capacity(1024);
    let question_args = QuestionArgs {
        name: Some(fbb.create_string(STUB_QUERY_NAME)),
        resource_type: ResourceType::TYPE_A as u16,
        resource_class: ResourceClass::CLASS_INTERNET as u16,
    };
    let question_offset = Question::create(&mut fbb, &question_args);
    fbb.finish_minimal(question_offset);
    fbb
}

/// Writes a DNS response/answer into the provided buffer
fn write_stub_response() -> Result<BytesMut> {
    let question_fbb = build_stub_question();
    let question: Question<'_> = flatbuffers::get_root::<Question<'_>>(question_fbb.finished_data());

    let mut buf = BytesMut::with_capacity(4096);
    DNSMessageEncoder::new().encode_local_response(
        ResponseCode::RESPONSE_NOERROR,
        0,
        &question,
        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(0 /*QUERY*/),
            authoritative: false,
            truncated: false,
            recursion_desired: true,
            recursion_available: true,
            reserved_9: false,
            authentic_data: false,
            checking_disabled: false,
            response_code: Integer::from(ResponseCode::RESPONSE_NOERROR as u8),

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

    let question_fbb = build_stub_question();
    let question: Question<'_> = flatbuffers::get_root::<Question<'_>>(question_fbb.finished_data());
    let mut ptr_offsets = domain_name::LabelOffsets::new();
    message::write_question(&question, &mut buf, &mut ptr_offsets)?;

    Ok(buf)
}

fn run_udp_upstream(udp_sock: UdpSocket, stop: Arc<ArrayQueue<()>>) -> Result<()> {
    let mut request_buffer = BytesMut::with_capacity(4096);
    let mut response_buffer = write_stub_response()?;

    loop {
        // Ensure that the buffer has a SIZE suitable for socket.recv_from().
        // If we just leave it with the CAPACITY then it drops data.
        request_buffer.resize(request_buffer.capacity(), 0);
        debug!("Harness reading...");
        match udp_sock.recv_from(&mut request_buffer) {
            Ok((recvsize, recvfrom)) => {
                debug!("Harness got {} bytes from {:?}", recvsize, recvfrom);
                // Ensure that the response has a matching request ID (first two bytes)
                if recvsize < 2 {
                    bail!("Expected request to have at least 2 bytes, but got {}", recvsize);
                }
                response_buffer[0] = request_buffer[0];
                response_buffer[1] = request_buffer[1];

                request_buffer.clear();

                debug!("Harness replying...");
                let sendsize = udp_sock.send_to(&mut response_buffer, recvfrom)?;
                debug!("Harness sent {} bytes to {:?}", sendsize, recvfrom);
            },
            Err(_e) => {
                // Might be a timeout where upstream is waiting for us to exit, or might not be
                if stop.pop().is_ok() {
                    debug!("Stopping harness thread");
                    return Ok(());
                }
            }
        }
    }
}

fn start_udp_upstream(stop: Arc<ArrayQueue<()>>) -> Result<(SocketAddr, JoinHandle<Result<()>>)> {
    let listen_addr_ephemeral = LOCAL_EPHEMERAL_ENDPOINT
        .to_socket_addrs()?
        .next()
        .with_context(|| "Invalid listen address")?;
    let upstream_sock = UdpSocket::bind(listen_addr_ephemeral)
        .with_context(|| format!("Failed to listen on {}", listen_addr_ephemeral))?;
    upstream_sock.set_read_timeout(Some(Duration::from_millis(1000)))?;
    upstream_sock.set_write_timeout(Some(Duration::from_millis(1000)))?;
    let listen_addr_actual = upstream_sock.local_addr()?;
    debug!("Harness running at {:?}", listen_addr_actual);

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

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

fn setup_udp_requests() -> Result<RunInputs> {
    let client_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127,0,0,1)), 0);
    let client_sock = UdpSocket::bind(client_addr)?;
    client_sock.set_read_timeout(Some(Duration::from_millis(5000)))?;
    client_sock.set_write_timeout(Some(Duration::from_millis(5000)))?;
    let response_buffer = BytesMut::with_capacity(4096);
    Ok(RunInputs {
        client_sock,
        response_buffer,
    })
}

/// 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(mut inputs: RunInputs, kapiti_udp_endpoint: SocketAddr, count: u64) -> Result<()> {
    for _i in 0..count {
        debug!("Harness sending...");
        let sendsize = inputs.client_sock.send_to(&STUB_REQUEST[..], kapiti_udp_endpoint).with_context(|| "send_to failed")?;
        debug!("Harness sent {} bytes to {:?}", sendsize, kapiti_udp_endpoint);
        // Ensure that the buffer has a SIZE suitable for socket.recv_from().
        // If we just leave it with the CAPACITY then it drops data.
        inputs.response_buffer.resize(inputs.response_buffer.capacity(), 0);
        debug!("Client reading...");
        let (recvsize, recvfrom) = inputs.client_sock.recv_from(&mut inputs.response_buffer).with_context(|| "recv_from failed: no response from kapiti")?;
        debug!("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) -> Result<()> {
    logging::init_logging();
    let tmpstorage = tempfile::tempdir()?;

    // Use queue to notify threads to stop
    let stop = Arc::new(ArrayQueue::new(2));

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

    // Start kapiti server
    let mut runtime = Runtime::new()?;
    let mut runner = runtime.block_on(Runner::new("benchmark".to_string(), config))?;
    runner.set_stop(stop.clone());
    let kapiti_udp_endpoint = runner.get_udp_endpoint()?;
    let kapiti_join_handle = thread::spawn(move || {
        runtime.block_on(runner.run())
    });

    // 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(50);
    group.bench_function("udp_udp", |b| b.iter_batched(
        move || setup_udp_requests().expect("setup failed"),
        move |inputs| run_udp_requests(inputs, kapiti_udp_endpoint, run_count).expect("client run failed"),
        BatchSize::PerIteration
    ));
    group.finish();

    // Send shutdown messages to be consumed by the kapiti thread and the upstream thread (not necessarily in that order)
    stop.push(()).expect("unable to fit first message on stop queue");
    stop.push(()).expect("unable to fit second message on stop queue");

    // Wait for kapiti thread to get the message
    debug!("Waiting for kapiti thread to exit...");
    kapiti_join_handle.join().expect("failed to join kapiti thread")?;

    // Wait for upstream thread to get the message
    debug!("Waiting for upstream thread to exit...");
    upstream_join_handle.join().expect("failed to join upstream harness thread")?;

    Ok(())
}

fn udp_udp(c: &mut Criterion) {
    run_udp_udp_test(c).expect("udp_udp test failed");
}

criterion_group!(benches, udp_udp);
criterion_main!(benches);