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
//
// Copyright (C) 2018 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use kubos_system::Config;
use kubos_telemetry_db::Database;
use rand::{thread_rng, Rng};
use serde_json::{json, ser};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
use std::thread;
use std::time::Duration;
use time::PreciseTime;

const ITERATIONS: i64 = 1000;

fn db_test(config: &Config) {
    let db_path = config
        .get("database")
        .expect("No database path found in config file");
    let db_path = db_path.as_str().unwrap_or("");

    let db = Database::new(&db_path);
    db.setup();

    let mut times: Vec<f64> = Vec::new();

    for _ in 0..ITERATIONS {
        let mut rng = thread_rng();
        let timestamp: f64 = rng.gen_range(0.0, ::std::f64::MAX);

        let start = PreciseTime::now();
        if db
            .insert(timestamp, "db-test", "parameter", "value")
            .is_ok()
        {
            times.push(start.to(PreciseTime::now()).num_seconds() as f64);
        }
    }

    let num_entries = times.len() as f64;
    let sum: f64 = times.iter().sum();

    let average = sum / num_entries;

    println!(
        "Average insert time after {} runs: {} us",
        num_entries, average
    );
}

fn graphql_test(config: &Config) {
    let mut times: Vec<i64> = Vec::new();

    for _ in 0..ITERATIONS {
        let mut rng = thread_rng();
        let timestamp = rng.gen_range(0, ::std::i32::MAX);

        let mutation = format!(
            r#"mutation {{
            insert(timestamp: {}, subsystem: "db-test", parameter: "voltage", value: "4.0") {{
                success,
                errors
            }}
        }}"#,
            timestamp
        );

        let remote_addr = config.hosturl();
        let local_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);

        let socket = UdpSocket::bind(local_addr).expect("Couldn't bind to address");

        let start = PreciseTime::now();
        socket
            .send_to(&mutation.as_bytes(), &remote_addr)
            .expect("Couldn't send message");
        socket.set_read_timeout(Some(Duration::new(1, 0))).unwrap();

        let mut buf = [0; 1024];
        match socket.recv_from(&mut buf) {
            Ok(_) => times.push(start.to(PreciseTime::now()).num_microseconds().unwrap()),
            Err(e) => panic!("recv function failed: {:?}", e),
        }
    }

    let num_entries = times.len() as i64;
    let sum: i64 = times.iter().sum();

    let average = sum / num_entries;

    println!(
        "Average mutation time after {} runs: {} us",
        num_entries, average
    );
}

fn direct_udp_test(config: &Config) {
    let mut times: Vec<i64> = Vec::new();

    for _ in 0..ITERATIONS {
        let remote_addr = config.hosturl();
        let local_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);

        let socket = UdpSocket::bind(local_addr).expect("Couldn't bind to address");

        let message = json!({
            "timestamp": 1,
            "subsystem": "db-test",
            "parameter": "voltage",
            "value": "3.3"
        });

        let start = PreciseTime::now();

        socket
            .send_to(&ser::to_vec(&message).unwrap(), remote_addr)
            .unwrap();

        times.push(start.to(PreciseTime::now()).num_microseconds().unwrap())
    }

    let num_entries = times.len() as i64;
    let sum: i64 = times.iter().sum();

    let average = sum / num_entries;

    println!(
        "Average UDP send time after {} runs: {} us",
        num_entries, average
    );
}

fn test_cleanup(config: &Config) {
    let mutation = r#"mutation {
            delete(subsystem: "db-test") {
                success,
                errors,
                entriesDeleted
            }
        }"#;

    let remote_addr = config.hosturl();
    let local_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);

    let socket = UdpSocket::bind(local_addr).expect("Couldn't bind to address");

    socket
        .send_to(&mutation.as_bytes(), &remote_addr)
        .expect("Couldn't send message");
    socket.set_read_timeout(Some(Duration::new(1, 0))).unwrap();

    let mut buf = [0; 1024];
    match socket.recv_from(&mut buf) {
        Ok((amt, _)) => {
            let v: serde_json::Value = serde_json::from_slice(&buf[0..(amt)]).unwrap();
            match v.get("data").and_then(|msg| msg.get("delete")) {
                Some(message) => {
                    let success =
                        serde_json::from_value::<bool>(message["success"].clone()).unwrap();

                    let errors =
                        serde_json::from_value::<String>(message["errors"].clone()).unwrap();

                    let entries_deleted =
                        serde_json::from_value::<i64>(message["entriesDeleted"].clone()).unwrap();

                    match success {
                        true => println!("Cleaned up {} test entries", entries_deleted),
                        false => eprintln!("Failed to deleted test entries: {}", errors),
                    }
                }
                None => eprintln!("Failed to process delete response"),
            }
        }
        Err(e) => panic!("recv function failed: {:?}", e),
    }
}

fn main() {
    let config = Config::new("telemetry-service");

    db_test(&config);

    // This sleep likely isn't necessary, but I'd like to make extra sure nothing about a test
    // lingers to affect the next one
    thread::sleep(Duration::new(1, 0));

    graphql_test(&config);

    thread::sleep(Duration::new(1, 0));

    direct_udp_test(&config);

    thread::sleep(Duration::new(1, 0));

    test_cleanup(&config);
}