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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::sync::Arc;
use std::time::Duration;

use anyhow::Result;
use parse_duration::parse;
use tokio::time::Instant;
use tokio::time::sleep_until;

use crate::cli::RunCommandOptions;
use crate::config::FaultConfig;
use crate::config::FaultKind;
use crate::errors::SchedulingError;
use crate::fault::FaultInjector;
use crate::plugin::load_injector;
use crate::proxy::ProxyState;
use crate::types::FaultConfiguration;
use crate::types::FaultPeriod;
use crate::types::FaultPeriodSpec;
use crate::types::TimeSpec; // from the 'parse_duration' crate

fn fraction_to_duration(frac: f64, total: Duration) -> Duration {
    let secs = total.as_secs_f64() * frac;
    Duration::from_secs_f64(secs)
}

fn parse_time_spec(s: &str) -> Result<TimeSpec, SchedulingError> {
    let s = s.trim();
    if let Some(pct_str) = s.strip_suffix('%') {
        // e.g. "5%"
        // remove '%'
        let fraction = pct_str
            .parse::<f64>()
            .map_err(|_| SchedulingError::InvalidFraction(s.to_string()))?
            / 100.0;
        Ok(TimeSpec::Fraction(fraction))
    } else {
        // Try parse as e.g. "30s" or "5m" or "45"
        // parse returns an error if it can't parse,
        // so we fallback to a plain integer check.
        match parse(s) {
            Ok(d) => Ok(TimeSpec::Absolute(d)),
            Err(_) => {
                // Maybe it's a bare integer => seconds
                if let Ok(secs) = s.parse::<u64>() {
                    Ok(TimeSpec::Absolute(Duration::from_secs(secs)))
                } else {
                    Err(SchedulingError::FailedParsing(s.to_string()))
                }
            }
        }
    }
}

/// Parse a DSL string with multiple periods separated by `;`,
/// each with "start:..., duration:..." pairs separated by `,`.
fn parse_periods(s: &str) -> Result<Vec<FaultPeriodSpec>, SchedulingError> {
    let mut specs = Vec::new();

    for part in s.split(';') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        let mut start_spec: Option<TimeSpec> = None;
        let mut duration_spec: Option<TimeSpec> = None;

        for kv in part.split(',') {
            let kv = kv.trim();
            if kv.is_empty() {
                continue;
            }
            // e.g. "start:5%" or "duration:25%"
            let mut iter = kv.splitn(2, ':');
            let key = iter.next().unwrap();
            let val = iter.next().unwrap_or("").trim();

            match key {
                "start" => {
                    start_spec = Some(parse_time_spec(val)?);
                }
                "duration" => {
                    duration_spec = Some(parse_time_spec(val)?);
                }
                k => {
                    return Err(SchedulingError::UnknownKey(k.to_string()));
                }
            }
        }

        // If no "start" was given, default to 0
        let start = start_spec
            .unwrap_or_else(|| TimeSpec::Absolute(Duration::from_secs(0)));
        specs.push(FaultPeriodSpec { start, duration: duration_spec });
    }

    Ok(specs)
}

pub fn parse_period(period: &str) -> Result<Option<FaultPeriodSpec>> {
    match parse_periods(period) {
        Ok(periods) => {
            if periods.is_empty() {
                Ok(None)
            } else {
                Ok(Some(periods[0].clone()))
            }
        }
        Err(_) => Ok(None),
    }
}

/// Convert the parse result (FaultPeriodSpec) into final (FaultPeriod).
/// If we see a `Fraction` but `total_run_time` is None, we fail.
fn resolve_periods(
    specs: &[FaultPeriodSpec],
    total_run_time: Option<Duration>,
) -> Result<Vec<FaultPeriod>, SchedulingError> {
    let mut output = Vec::new();

    for s in specs {
        let start = match &s.start {
            TimeSpec::Absolute(d) => *d,
            TimeSpec::Fraction(f) => {
                if let Some(total) = total_run_time {
                    fraction_to_duration(*f, total)
                } else {
                    return Err(SchedulingError::MissingDuration(format!(
                        "{}%",
                        f * 100.0
                    )));
                }
            }
        };

        let duration_opt = match &s.duration {
            Some(TimeSpec::Absolute(d)) => Some(*d),
            Some(TimeSpec::Fraction(f)) => {
                if let Some(total) = total_run_time {
                    Some(fraction_to_duration(*f, total))
                } else {
                    return Err(SchedulingError::MissingDuration(format!(
                        "{}%",
                        f * 100.0
                    )));
                }
            }
            None => None,
        };

        output.push(FaultPeriod { start, duration: duration_opt });
    }

    Ok(output)
}

fn build_events_for_fault(
    fault_type: FaultKind,
    fault_config: FaultConfig,
    periods: &[FaultPeriod],
    base_instant: Instant,
) -> Vec<FaultPeriodEvent> {
    let mut events = Vec::new();

    for p in periods {
        let start_time = base_instant + p.start;
        events.push(FaultPeriodEvent {
            time: start_time,
            fault_type,
            fault_config: fault_config.clone(),
            event_type: EventType::Start,
        });

        if let Some(d) = p.duration {
            events.push(FaultPeriodEvent {
                time: start_time + d,
                fault_type,
                fault_config: fault_config.clone(),
                event_type: EventType::Stop,
            });
        }
    }

    events
}

pub async fn run_fault_schedule(
    mut events: Vec<FaultPeriodEvent>,
    state: Arc<ProxyState>,
    injectors: Vec<Box<dyn FaultInjector>>,
) {
    events.sort_by_key(|e| e.time);

    for event in events {
        let mut injectors = injectors.clone();

        let now = Instant::now();
        if event.time > now {
            sleep_until(event.time).await;
        }

        let fault_config = event.fault_config;
        let fault_type = fault_config.kind();

        match event.event_type {
            EventType::Start => {
                if let Some(existing_injector) =
                    injectors.iter_mut().find(|f| f.kind() == fault_type)
                {
                    existing_injector.enable();
                } else {
                    let mut injector = load_injector(&fault_config);
                    injector.enable();
                    injectors.push(injector);
                }
            }
            EventType::Stop => {
                if let Some(existing_injector) =
                    injectors.iter_mut().find(|f| f.kind() == fault_type)
                {
                    existing_injector.disable();
                }
            }
        }

        state.set_injectors(injectors).await;
    }
}

/// Whether we are starting or stopping that fault
#[derive(Debug, Clone, PartialEq)]
pub enum EventType {
    Start,
    Stop,
}

#[derive(Debug, Clone)]
pub struct FaultPeriodEvent {
    pub time: Instant,
    pub fault_type: FaultKind,
    pub fault_config: FaultConfig,
    pub event_type: EventType,
}

pub fn build_schedule_events(
    cli: &RunCommandOptions,
    total_duration: Option<Duration>,
) -> Result<Vec<FaultPeriodEvent>> {
    let mut events: Vec<FaultPeriodEvent> = Vec::<FaultPeriodEvent>::new();

    let start = Instant::now();

    if cli.bandwidth.enabled {
        let period = match &cli.bandwidth.bandwidth_sched {
            Some(p) => p,
            None => match total_duration {
                Some(_) => "duration:100%",
                None => "",
            },
        };

        if !period.is_empty() {
            let specs = parse_periods(period)?;
            let periods = resolve_periods(&specs, total_duration)?;
            let fault_config = FaultConfig::Bandwidth((&cli.bandwidth).into());
            let fault_events = build_events_for_fault(
                FaultKind::Bandwidth,
                fault_config,
                &periods,
                start,
            );

            events.extend(fault_events);
        }
    }

    if cli.latency.enabled {
        let period = match &cli.latency.latency_sched {
            Some(p) => p,
            None => match total_duration {
                Some(_) => "duration:100%",
                None => "",
            },
        };

        if !period.is_empty() {
            let specs = parse_periods(period)?;
            let periods = resolve_periods(&specs, total_duration)?;
            let fault_config = FaultConfig::Latency((&cli.latency).into());
            let fault_events = build_events_for_fault(
                FaultKind::Latency,
                fault_config,
                &periods,
                start,
            );

            events.extend(fault_events);
        }
    }

    if cli.dns.enabled {
        let period = match &cli.dns.dns_sched {
            Some(p) => p,
            None => match total_duration {
                Some(_) => "duration:100%",
                None => "",
            },
        };

        if !period.is_empty() {
            let specs = parse_periods(period)?;
            let periods = resolve_periods(&specs, total_duration)?;
            let fault_config = FaultConfig::Dns((&cli.dns).into());
            let fault_events = build_events_for_fault(
                FaultKind::Dns,
                fault_config,
                &periods,
                start,
            );

            events.extend(fault_events);
        }
    }

    if cli.packet_loss.enabled {
        let period = match &cli.packet_loss.packet_loss_sched {
            Some(p) => p,
            None => match total_duration {
                Some(_) => "duration:100%",
                None => "",
            },
        };

        if !period.is_empty() {
            let specs = parse_periods(period)?;
            let periods = resolve_periods(&specs, total_duration)?;
            let fault_config =
                FaultConfig::PacketLoss((&cli.packet_loss).into());
            let fault_events = build_events_for_fault(
                FaultKind::PacketLoss,
                fault_config,
                &periods,
                start,
            );

            events.extend(fault_events);
        }
    }

    if cli.jitter.enabled {
        let period = match &cli.jitter.jitter_sched {
            Some(p) => p,
            None => match total_duration {
                Some(_) => "duration:100%",
                None => "",
            },
        };

        if !period.is_empty() {
            let specs = parse_periods(period)?;
            let periods = resolve_periods(&specs, total_duration)?;
            let fault_config = FaultConfig::Jitter((&cli.jitter).into());
            let fault_events = build_events_for_fault(
                FaultKind::Jitter,
                fault_config,
                &periods,
                start,
            );

            events.extend(fault_events);
        }
    }

    if cli.http_error.enabled {
        let period = match &cli.http_error.http_response_sched {
            Some(p) => p,
            None => match total_duration {
                Some(_) => "duration:100%",
                None => "",
            },
        };

        if !period.is_empty() {
            let specs = parse_periods(period)?;
            let periods = resolve_periods(&specs, total_duration)?;
            let fault_config = FaultConfig::HttpError((&cli.http_error).into());
            let fault_events = build_events_for_fault(
                FaultKind::HttpError,
                fault_config,
                &periods,
                start,
            );

            events.extend(fault_events);
        }
    }

    if cli.blackhole.enabled {
        let period = match &cli.blackhole.blackhole_sched {
            Some(p) => p,
            None => match total_duration {
                Some(_) => "duration:100%",
                None => "",
            },
        };

        if !period.is_empty() {
            let specs = parse_periods(period)?;
            let periods = resolve_periods(&specs, total_duration)?;
            let fault_config = FaultConfig::Blackhole((&cli.blackhole).into());
            let fault_events = build_events_for_fault(
                FaultKind::Blackhole,
                fault_config,
                &periods,
                start,
            );

            events.extend(fault_events);
        }
    }

    Ok(events)
}

pub fn build_schedule_events_from_scenario_item(
    faults: &Vec<FaultConfiguration>,
    starting_point: Instant,
    total_duration: Duration,
) -> Vec<FaultPeriodEvent> {
    let mut events: Vec<FaultPeriodEvent> = Vec::<FaultPeriodEvent>::new();

    let total_run = Some(total_duration);

    for f in faults {
        let p = f.get_period();

        let mut periods = Vec::new();

        if let Some(period) = p {
            // these expect() shouldn't happen because at this point, we have
            // already parsed the period spec
            periods.extend(
                resolve_periods(&[period.clone()], total_run)
                    .expect("failed to resolve period"),
            );
        } else {
            periods.push(FaultPeriod {
                start: Duration::from_millis(0),
                duration: None,
            });
        }

        let fault_config = f.build().expect("invalid fault config");
        let fault_events = build_events_for_fault(
            fault_config.kind(),
            fault_config,
            periods.as_ref(),
            starting_point,
        );

        events.extend(fault_events);
    }

    events
}