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
#![allow(non_snake_case)]
use std::collections::HashMap;
use request::Handler;
use serde_json;
use error::ConsulResult;
use std::error::Error;
use super::{Service, RegisterService, TtlHealthCheck};
pub struct Agent{
handler: Handler
}
#[derive(Serialize, Deserialize)]
pub struct AgentMember {
Name: String,
Addr: String,
Port: u16,
Tags: HashMap<String, String>,
Status: usize,
ProtocolMin: u8,
ProtocolMax: u8,
ProtocolCur: u8,
DelegateMin: u8,
DelegateMax: u8,
DelegateCur: u8
}
impl Agent {
pub fn new(address: &str) -> Agent {
Agent {
handler: Handler::new(&format!("{}/v1/agent", address))
}
}
pub fn services(&self) -> ConsulResult<HashMap<String, Service>> {
let result = self.handler.get("services")?;
serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())
}
pub fn members(&self) -> ConsulResult<Vec<AgentMember>> {
let result = self.handler.get("members")?;
serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())
}
pub fn register(&self, service: RegisterService) -> ConsulResult<()> {
let json_str = serde_json::to_string(&service)
.map_err(|e| e.description().to_owned())?;
if let Err(e) = self.handler.put("service/register", json_str, Some("application/json")) {
Err(format!("Consul: Error registering a service. Err:{}", e))
}
else {
Ok(())
}
}
pub fn register_ttl_check(&self, health_check: TtlHealthCheck) -> ConsulResult<()> {
let json_str = serde_json::to_string(&health_check)
.map_err(|e| e.description().to_owned())?;
if let Err(e) = self.handler.put("check/register", json_str, Some("application/json")) {
Err(format!("Consul: Error registering a health check. Err:{}", e))
}
else {
Ok(())
}
}
pub fn check_pass(&self, service_id: String) -> ConsulResult<()> {
let uri = format!("check/pass/{}", service_id);
self.handler.get(&uri)?;
Ok(())
}
pub fn get_self_name(&self) -> ConsulResult<Option<String>> {
let result = self.handler.get("self")?;
let json_data = serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())?;
Ok(super::get_string(&json_data, &["Config", "NodeName"]))
}
pub fn get_self_address(&self) -> ConsulResult<Option<String>> {
let result = self.handler.get("self")?;
let json_data = serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())?;
Ok(super::get_string(&json_data, &["Config", "AdvertiseAddr"]))
}
}