aboutsummaryrefslogtreecommitdiff
path: root/src/consul_actor.rs
blob: 241a643bcee7fe217505dbf8df744ec9e7db936e (plain) (blame)
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
use std::cmp;
use std::time::Duration;
use log::*;
use tokio::sync::watch;
use tokio::time::delay_for;
use anyhow::Result;
use serde::{Serialize, Deserialize};
use serde_lexpr::{from_str,to_string,error};
use crate::messages;
use crate::consul;

#[derive(Serialize, Deserialize, Debug)]
pub enum DiplonatParameter {
  tcp_port(Vec<u16>),
  udp_port(Vec<u16>)
}

#[derive(Serialize, Deserialize, Debug)]
pub enum DiplonatConsul {
  diplonat(Vec<DiplonatParameter>)
}

pub struct ConsulActor {
  pub rx_open_ports: watch::Receiver<messages::PublicExposedPorts>,

  consul: consul::Consul,
  node: String,
  retries: u32,
  tx_open_ports: watch::Sender<messages::PublicExposedPorts>
}

fn retry_to_time(retries: u32, max_time: Duration) -> Duration {
  // 1.2^x seems to be a good value to exponentially increase time at a good pace
  // eg. 1.2^32 = 341 seconds ~= 5 minutes - ie. after 32 retries we wait 5 minutes
  return Duration::from_secs(cmp::min(max_time.as_secs(), 1.2f64.powf(retries as f64) as u64))
}

fn from_catalog_to_open_ports(catalog: &consul::CatalogNode) -> messages::PublicExposedPorts {
  let mut op = messages::PublicExposedPorts { 
    tcp_ports: Vec::new(),
    udp_ports: Vec::new()
  };

  for (_, service_info) in &catalog.Services {
    for tag in &service_info.Tags {
      let diplo_conf: error::Result<DiplonatConsul> = from_str(tag);
      match diplo_conf {
        Ok(conf) => {
          let DiplonatConsul::diplonat(c) = conf;
          for parameter in &c {
            match parameter {
              DiplonatParameter::tcp_port(p) => op.tcp_ports.extend(p),
              DiplonatParameter::udp_port(p) => op.udp_ports.extend(p),
            }
          }
        }
        Err(e) => debug!("Failed to parse entry {}. {}", tag, e),
      };
    }
  }
  return op;
}

impl ConsulActor {
  pub fn new(url: &str, node: &str) -> Self {
    let (tx, rx) = watch::channel(messages::PublicExposedPorts{
      tcp_ports: Vec::new(),
      udp_ports: Vec::new()
    });

    return Self {
      consul: consul::Consul::new(url),
      rx_open_ports: rx,
      tx_open_ports: tx,
      node: node.to_string(),
      retries: 0,
    };
  }

  pub async fn listen(&mut self) -> Result<()> {
    loop {
      let catalog = match self.consul.watch_node(&self.node).await {
        Ok(c) => c,
        Err(e) => {
          self.consul.watch_node_reset();
          self.retries = cmp::min(u32::MAX - 1, self.retries) + 1;
          let will_retry_in = retry_to_time(self.retries, Duration::from_secs(600));
          error!("Failed to query consul. Will retry in {}s. {}", will_retry_in.as_secs(), e);
          delay_for(will_retry_in).await;
          continue;
        }
      };
      self.retries = 0;
      info!("{:#?}", from_catalog_to_open_ports(&catalog));
    }
  }
}