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 request::Handler;
use serde_json::{self, Value};
use ::find_path;
use error::ConsulResult;
use std::error::Error;
use super::HealthService;
pub struct Health{
handler: Handler
}
impl Health {
pub fn new(address: &str) -> Health {
Health {
handler: Handler::new(&format!("{}/v1/health", address))
}
}
fn request(&self, uri: &str) -> ConsulResult<Vec<HealthService>> {
let result = self.handler.get(uri)?;
serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())
}
pub fn service(&self, name: &str, o_tag: Option<&str>) -> ConsulResult<Vec<HealthService>> {
let uri = match o_tag {
Some(value) => format!("service/{}?tag={}", name, value),
None => format!("service/{}", name)
};
self.request(&uri)
}
pub fn healthy_nodes_by_service(&self, service_id: &str) -> ConsulResult<Vec<String>> {
let uri = format!("service/{}", service_id);
let result = self.handler.get(&uri)?;
let json_data: Value = serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())?;
let v_nodes = json_data.as_array()
.ok_or("Cannot get Node array")?;
let mut filtered: Vec<String> = Vec::new();
for node in v_nodes.iter() {
let ip = match super::get_string(node, &["Node", "Address"]) {
Some(val) => val,
None => continue
};
let checks = match find_path(node, &["Checks"]) {
Some(val) => val.as_array().ok_or("Cannot get Checks array")?,
None => continue
};
let mut healthy = true;
for check in checks {
let status = match super::get_string(check, &["Status"]) {
Some(val) => val,
None => {
healthy = false;
break;
}
};
if !healthy {
break;
}
if status != "passing" {
healthy = false;
break;
}
}
if healthy {
filtered.push(ip.to_owned());
}
}
Ok(filtered)
}
pub fn get_healthy_nodes(&self, service_id: &str) -> Result<Vec<String>, String> {
let uri = format!("checks/{}", service_id);
let result = self.handler.get(&uri)?;
let json_data: Value = serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())?;
let v_nodes = json_data.as_array()
.ok_or("Cannot get Node array")?;
let mut filtered: Vec<String> = Vec::new();
for node in v_nodes.iter() {
if let Some(status) = super::get_string(node, &["Status"]) {
if status == "passing" {
if let Some(node_value) = super::get_string(node, &["Node"]) {
filtered.push(node_value);
}
}
}
}
Ok(filtered)
}
}