sozu 0.14.2

sozu, a fast, reliable, hot reconfigurable HTTP reverse proxy
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
use anyhow::{self, bail, Context};
use prettytable::Table;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use serde::Serialize;

use sozu_command_lib::{
    command::{
        CommandRequest, CommandRequestOrder, CommandResponse, CommandResponseContent,
        CommandStatus, FrontendFilters, RunState, WorkerInfo,
    },
    proxy::{
        MetricsConfiguration, ProxyRequestOrder, Query, QueryCertificateType, QueryClusterDomain,
        QueryClusterType, QueryMetricsOptions,
    },
};

use crate::{
    cli::MetricsCmd,
    ctl::{
        create_channel,
        display::{
            print_available_metrics, print_certificates, print_frontend_list, print_json_response,
            print_metrics, print_query_response_data, print_status,
        },
        CommandManager,
    },
};

// Used to display the JSON response of the status command
#[derive(Serialize, Debug)]
struct WorkerStatus<'a> {
    pub worker: &'a WorkerInfo,
    pub status: &'a String,
}

fn generate_id() -> String {
    let s: String = thread_rng()
        .sample_iter(&Alphanumeric)
        .take(6)
        .map(|c| c as char)
        .collect();
    format!("ID-{}", s)
}

fn generate_tagged_id(tag: &str) -> String {
    let s: String = thread_rng()
        .sample_iter(&Alphanumeric)
        .take(6)
        .map(|c| c as char)
        .collect();
    format!("{}-{}", tag, s)
}

impl CommandManager {
    fn send_request(
        &mut self,
        id: &str,
        command_request_order: CommandRequestOrder,
    ) -> anyhow::Result<()> {
        let command_request = CommandRequest::new(id.to_string(), command_request_order, None);

        self.channel
            .write_message(&command_request)
            .with_context(|| "Could not write the request")
    }

    fn read_channel_message_with_timeout(&mut self) -> anyhow::Result<CommandResponse> {
        self.channel
            .read_message_blocking_timeout(Some(self.timeout))
            .with_context(|| "Command timeout. The proxy didn't send an answer")
    }

    pub fn save_state(&mut self, path: String) -> Result<(), anyhow::Error> {
        let id = generate_id();

        self.send_request(&id, CommandRequestOrder::SaveState { path })?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    bail!("could not save proxy state: {}", response.message)
                }
                CommandStatus::Ok => {
                    println!("{}", response.message);
                    break;
                }
            }
        }

        Ok(())
    }

    pub fn load_state(&mut self, path: String) -> Result<(), anyhow::Error> {
        let id = generate_id();

        self.send_request(&id, CommandRequestOrder::LoadState { path: path.clone() })?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    bail!("could not load proxy state: {}", response.message)
                }
                CommandStatus::Ok => {
                    println!("Proxy state loaded successfully from {}", path);
                    break;
                }
            }
        }

        Ok(())
    }

    pub fn dump_state(&mut self, json: bool) -> Result<(), anyhow::Error> {
        let id = generate_id();

        self.send_request(&id.clone(), CommandRequestOrder::DumpState)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    if json {
                        print_json_response(&response.message)?;
                    }
                    bail!("could not dump proxy state: {}", response.message);
                }
                CommandStatus::Ok => match response.content {
                    Some(CommandResponseContent::State(state)) => {
                        match json {
                            true => print_json_response(&state)?,
                            false => println!("{:#?}", state),
                        }
                        break;
                    }
                    _ => bail!("state dump was empty"),
                },
            }
        }
        Ok(())
    }

    pub fn soft_stop(&mut self, proxy_id: Option<u32>) -> Result<(), anyhow::Error> {
        println!("shutting down proxy");
        let id = generate_id();

        self.channel
            .write_message(&CommandRequest::new(
                id.clone(),
                CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::SoftStop)),
                proxy_id,
            ))
            .with_context(|| "Could not send the request using the channel")?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }

            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    bail!("could not stop the proxy: {}", response.message);
                }
                CommandStatus::Ok => {
                    println!("Proxy shut down with message: \"{}\"", response.message);
                    break;
                }
            }
        }

        Ok(())
    }

    pub fn hard_stop(&mut self, proxy_id: Option<u32>) -> Result<(), anyhow::Error> {
        println!("shutting down proxy");
        let id = generate_id();
        self.channel
            .write_message(&CommandRequest::new(
                id.clone(),
                CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::HardStop)),
                proxy_id,
            ))
            .with_context(|| "Could not send the request using the channel")?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    bail!("could not stop the proxy: {}", response.message);
                }
                CommandStatus::Ok => {
                    if id == response.id {
                        println!("Proxy shut down: {}", response.message);
                    }
                    break;
                }
            }
        }
        Ok(())
    }

    // 1. Request a list of workers
    // 2. Send an UpgradeMain
    // 3. Send an UpgradeWorker to each worker
    pub fn upgrade_main(&mut self) -> Result<(), anyhow::Error> {
        println!("Preparing to upgrade proxy...");

        let id = generate_tagged_id("LIST-WORKERS");

        self.send_request(&id, CommandRequestOrder::ListWorkers)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("Error: received unexpected message: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Processing: {}", response.message);
                }
                CommandStatus::Error => {
                    bail!(
                        "Error: failed to get the list of worker: {}",
                        response.message
                    );
                }
                CommandStatus::Ok => {
                    if let Some(CommandResponseContent::Workers(ref workers)) = response.content {
                        let mut table = Table::new();
                        table.set_format(*prettytable::format::consts::FORMAT_BOX_CHARS);
                        table.add_row(row!["Worker", "pid", "run state"]);
                        for worker in workers.iter() {
                            let run_state = format!("{:?}", worker.run_state);
                            table.add_row(row![worker.id, worker.pid, run_state]);
                        }
                        println!();
                        table.printstd();
                        println!();

                        let id = generate_tagged_id("UPGRADE-MAIN");
                        self.send_request(&id, CommandRequestOrder::UpgradeMain)?;

                        println!("Upgrading main process");

                        loop {
                            let response = self.read_channel_message_with_timeout()?;

                            if id != response.id {
                                bail!("Error: received unexpected message: {:?}", response);
                            }

                            match response.status {
                                CommandStatus::Processing => {
                                    println!("Main process is upgrading");
                                }
                                CommandStatus::Error => {
                                    bail!(
                                        "Error: failed to upgrade the main: {}",
                                        response.message
                                    );
                                }
                                CommandStatus::Ok => {
                                    println!(
                                        "Main process upgrade succeeded: {}",
                                        response.message
                                    );
                                    break;
                                }
                            }
                        }

                        // Reconnect to the new main
                        println!("Reconnecting to new main process...");
                        self.channel = create_channel(&self.config)
                            .with_context(|| "could not reconnect to the command unix socket")?;

                        // Do a rolling restart of the workers
                        let running_workers = workers
                            .iter()
                            .filter(|worker| worker.run_state == RunState::Running)
                            .collect::<Vec<_>>();
                        let running_count = running_workers.len();
                        for (i, worker) in running_workers.iter().enumerate() {
                            println!(
                                "Upgrading worker {} (#{} out of {})",
                                worker.id,
                                i + 1,
                                running_count
                            );

                            self.upgrade_worker(worker.id)
                                .with_context(|| "Upgrading the worker failed")?;
                            //thread::sleep(Duration::from_millis(1000));
                        }

                        println!("Proxy successfully upgraded!");
                    } else {
                        println!("Received a response of the wrong kind: {:?}", response);
                    }
                    break;
                }
            }
        }
        Ok(())
    }

    pub fn upgrade_worker(&mut self, worker_id: u32) -> Result<(), anyhow::Error> {
        println!("upgrading worker {}", worker_id);
        let id = generate_id();

        //FIXME: we should be able to soft stop one specific worker
        self.send_request(&id, CommandRequestOrder::UpgradeWorker(worker_id))?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            match response.status {
                CommandStatus::Processing => info!("Proxy is processing: {}", response.message),
                CommandStatus::Error => bail!(
                    "could not stop the worker {}: {}",
                    worker_id,
                    response.message
                ),
                CommandStatus::Ok => {
                    if id == response.id {
                        info!("Worker {} shut down: {}", worker_id, response.message);
                    }
                    break;
                }
            }
        }
        Ok(())
    }

    pub fn status(&mut self, json: bool) -> anyhow::Result<()> {
        let request_id = generate_id();

        self.send_request(&request_id, CommandRequestOrder::Status)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if request_id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }

            match response.status {
                CommandStatus::Processing => {
                    println!("server is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    if json {
                        print_json_response(&response.message)?;
                    }
                    bail!("could not get the worker list: {}", response.message);
                }
                CommandStatus::Ok => match response.content {
                    Some(CommandResponseContent::Status(worker_info_vec)) => {
                        print_status(worker_info_vec);
                        break;
                    }
                    Some(_) => {
                        bail!("Received the wrong kind of response data from the command server")
                    }
                    None => bail!("No data in the response"),
                },
            }
        }
        Ok(())
    }

    pub fn configure_metrics(&mut self, cmd: MetricsCmd) -> Result<(), anyhow::Error> {
        let id = generate_id();
        //println!("will send message for metrics with id {}", id);

        let configuration = match cmd {
            MetricsCmd::Enable => MetricsConfiguration::Enabled(true),
            MetricsCmd::Disable => MetricsConfiguration::Enabled(false),
            MetricsCmd::Clear => MetricsConfiguration::Clear,
            _ => bail!("The command passed to the configure_metrics function is wrong."),
        };

        self.send_request(
            &id,
            CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::ConfigureMetrics(
                configuration,
            ))),
        )?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    bail!("Error with metrics command: {}", response.message);
                }
                CommandStatus::Ok => {
                    if id == response.id {
                        println!("Successful metrics command: {}", response.message);
                    }
                    break;
                }
            }
        }
        Ok(())
    }

    pub fn get_metrics(
        &mut self,
        json: bool,
        list: bool,
        refresh: Option<u32>,
        metric_names: Vec<String>,
        cluster_ids: Vec<String>,
        backend_ids: Vec<String>,
    ) -> Result<(), anyhow::Error> {
        let command = CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::Query(
            Query::Metrics(QueryMetricsOptions {
                list,
                cluster_ids,
                backend_ids,
                metric_names,
            }),
        )));

        // a loop to reperform the query every refresh time
        loop {
            let id = generate_id();
            self.send_request(&id, command.clone())?;

            print!("{}", termion::cursor::Save);

            // a loop to process responses
            loop {
                let response = self.read_channel_message_with_timeout()?;

                if id != response.id {
                    bail!("received message with invalid id: {:?}", response);
                }
                match response.status {
                    CommandStatus::Processing => {
                        println!("Proxy is processing: {}", response.message);
                    }
                    CommandStatus::Error => {
                        if json {
                            return print_json_response(&response.message);
                        } else {
                            bail!("could not query proxy state: {}", response.message);
                        }
                    }
                    CommandStatus::Ok => {
                        match response.content {
                            Some(CommandResponseContent::Metrics(aggregated_metrics_data)) => {
                                print_metrics(aggregated_metrics_data, json)?
                            }
                            Some(CommandResponseContent::Query(lists_of_metrics)) => {
                                print_available_metrics(&lists_of_metrics)?;
                            }
                            _ => println!("Wrong kind of response here"),
                        }
                        break;
                    }
                }
            }

            match refresh {
                None => break,
                Some(seconds) => std::thread::sleep(std::time::Duration::from_secs(seconds as u64)),
            }

            print!(
                "{}{}",
                termion::cursor::Restore,
                termion::clear::BeforeCursor
            );
        }

        Ok(())
    }

    pub fn reload_configuration(
        &mut self,
        path: Option<String>,
        json: bool,
    ) -> Result<(), anyhow::Error> {
        let id = generate_id();

        self.send_request(&id, CommandRequestOrder::ReloadConfiguration { path })?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    if json {
                        return print_json_response(&response.message);
                    }
                    bail!("could not get the worker list: {}", response.message);
                }
                CommandStatus::Ok => {
                    match json {
                        true => print_json_response(&response.message)?,
                        false => println!("Reloaded configuration: {}", response.message),
                    }
                    break;
                }
            }
        }

        Ok(())
    }

    pub fn list_frontends(
        &mut self,
        http: bool,
        https: bool,
        tcp: bool,
        domain: Option<String>,
    ) -> Result<(), anyhow::Error> {
        let command = CommandRequestOrder::ListFrontends(FrontendFilters {
            http,
            https,
            tcp,
            domain,
        });

        let id = generate_id();
        self.send_request(&id, command)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    println!("could not query proxy state: {}", response.message)
                }
                CommandStatus::Ok => {
                    match response.content {
                        Some(CommandResponseContent::FrontendList(frontends)) => {
                            print_frontend_list(frontends)
                        }
                        _ => println!("Received a response of the wrong kind: {:?}", response),
                    }
                    break;
                }
            }
        }

        Ok(())
    }

    pub fn query_cluster(
        &mut self,
        json: bool,
        cluster_id: Option<String>,
        domain: Option<String>,
    ) -> Result<(), anyhow::Error> {
        if cluster_id.is_some() && domain.is_some() {
            bail!("Error: Either request an cluster ID or a domain name");
        }

        let command = if let Some(ref cluster_id) = cluster_id {
            CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::Query(Query::Clusters(
                QueryClusterType::ClusterId(cluster_id.to_string()),
            ))))
        } else if let Some(ref domain) = domain {
            let splitted: Vec<String> =
                domain.splitn(2, '/').map(|elem| elem.to_string()).collect();

            if splitted.is_empty() {
                bail!("Domain can't be empty");
            }

            let query_domain = QueryClusterDomain {
                hostname: splitted
                    .get(0)
                    .with_context(|| "Domain can't be empty")?
                    .clone(),
                path: splitted.get(1).cloned().map(|path| format!("/{}", path)), // We add the / again because of the splitn removing it
            };

            CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::Query(Query::Clusters(
                QueryClusterType::Domain(query_domain),
            ))))
        } else {
            CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::Query(Query::ClustersHashes)))
        };

        let id = generate_id();
        self.send_request(&id, command)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    if json {
                        print_json_response(&response.message)?;
                    }
                    bail!("could not query proxy state: {}", response.message);
                }
                CommandStatus::Ok => {
                    print_query_response_data(cluster_id, domain, response.content, json)?;
                    break;
                }
            }
        }

        Ok(())
    }

    pub fn query_certificate(
        &mut self,
        json: bool,
        fingerprint: Option<String>,
        domain: Option<String>,
    ) -> Result<(), anyhow::Error> {
        let query = match (fingerprint, domain) {
            (None, None) => QueryCertificateType::All,
            (Some(f), None) => match hex::decode(f) {
                Err(e) => {
                    bail!("invalid fingerprint: {:?}", e);
                }
                Ok(f) => QueryCertificateType::Fingerprint(f),
            },
            (None, Some(d)) => QueryCertificateType::Domain(d),
            (Some(_), Some(_)) => {
                bail!("Error: Either request a fingerprint or a domain name");
            }
        };

        let command = CommandRequestOrder::Proxy(Box::new(ProxyRequestOrder::Query(
            Query::Certificates(query),
        )));

        let id = generate_id();

        self.send_request(&id, command)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => {
                    println!("Proxy is processing: {}", response.message);
                }
                CommandStatus::Error => {
                    if json {
                        print_json_response(&response.message)?;
                        bail!("We received an error message");
                    } else {
                        bail!("could not query proxy state: {}", response.message);
                    }
                }
                CommandStatus::Ok => {
                    match response.content {
                        Some(CommandResponseContent::Query(data)) => {
                            print_certificates(data, json)?
                        }
                        _ => bail!("unexpected response: {:?}", response.content),
                    }
                    break;
                }
            }
        }
        Ok(())
    }

    pub fn events(&mut self) -> Result<(), anyhow::Error> {
        let id = generate_id();

        self.send_request(&id, CommandRequestOrder::SubscribeEvents)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;
            match response.status {
                CommandStatus::Processing => match response.content {
                    Some(CommandResponseContent::Event(event)) => {
                        println!("got event from worker({}): {:?}", response.message, event)
                    }
                    _ => {
                        println!("Received an unexpected response: {:?}", response)
                    }
                },
                CommandStatus::Error => {
                    bail!("could not get proxy events: {}", response.message);
                }
                CommandStatus::Ok => {
                    println!("{}", response.message);
                    break;
                }
            }
        }
        Ok(())
    }

    pub fn order_command(&mut self, order: ProxyRequestOrder) -> Result<(), anyhow::Error> {
        let id = generate_id();

        let request_order = CommandRequestOrder::Proxy(Box::new(order));
        println!("Sending request order: {:?}", request_order);
        self.send_request(&id, request_order)?;

        loop {
            let response = self.read_channel_message_with_timeout()?;

            if id != response.id {
                bail!("received message with invalid id: {:?}", response);
            }
            match response.status {
                CommandStatus::Processing => println!("Proxy is processing: {}", response.message),
                CommandStatus::Error => bail!("Order failed: {}", response.message),
                CommandStatus::Ok => {
                    println!("Success: {}", response.message);
                    break;
                }
            }
        }
        Ok(())
    }
}