-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
265 lines (233 loc) · 7.2 KB
/
client.rs
File metadata and controls
265 lines (233 loc) · 7.2 KB
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
use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;
#[derive(Debug, Deserialize, Clone)]
#[allow(dead_code)]
pub struct AssignedVolume {
pub id: String,
pub name: String,
pub pool: String,
pub image_name: String,
pub status: String,
pub mapped_device: Option<String>,
}
#[derive(Debug, Serialize)]
struct RegisterRequest<'a> {
registration_token: &'a str,
name: &'a str,
hostname: &'a str,
os_type: &'a str,
os_version: &'a str,
architecture: &'a str,
agent_version: &'a str,
csr_pem: &'a str,
}
#[derive(Debug, Deserialize)]
pub struct RegisterResponse {
pub agent_id: Uuid,
pub api_key: String,
pub certificate_pem: Option<String>,
pub ca_cert_pem: Option<String>,
}
#[derive(Debug, Serialize)]
struct HeartbeatRequest {
status: Option<String>,
container_statuses: Option<Vec<ContainerStatus>>,
cpu_usage_percent: Option<f32>,
cpu_cores: Option<u32>,
memory_total_bytes: Option<u64>,
memory_used_bytes: Option<u64>,
disk_total_bytes: Option<u64>,
disk_used_bytes: Option<u64>,
network_rx_bytes: Option<u64>,
network_tx_bytes: Option<u64>,
uptime_seconds: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ContainerStatus {
pub workload_id: String,
pub container_id: String,
pub status: String,
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct AssignedWorkload {
pub id: String,
pub name: String,
pub image: String,
pub cpu_millicores: i32,
pub memory_bytes: i64,
pub disk_bytes: i64,
pub env_vars: Option<HashMap<String, String>>,
pub ports: Option<Vec<crate::docker::PortMapping>>,
pub status: String,
pub container_id: Option<String>,
}
pub struct ApiClient {
client: Client,
gateway_url: String,
cert_pem: Option<String>,
}
impl ApiClient {
pub fn new(gateway_url: String) -> Result<Self> {
let client = Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.context("Failed to build HTTP client")?;
Ok(Self {
client,
gateway_url,
cert_pem: None,
})
}
pub fn with_certificate(mut self, cert_pem: String) -> Self {
self.cert_pem = Some(cert_pem);
self
}
#[allow(clippy::too_many_arguments)]
pub async fn register(
&self,
token: &str,
name: &str,
hostname: &str,
os_type: &str,
os_version: &str,
architecture: &str,
csr_pem: &str,
) -> Result<RegisterResponse> {
let url = format!("{}/api/registry/agents/register", self.gateway_url);
let body = RegisterRequest {
registration_token: token,
name,
hostname,
os_type,
os_version,
architecture,
agent_version: env!("CARGO_PKG_VERSION"),
csr_pem,
};
let resp = self
.client
.post(&url)
.json(&body)
.send()
.await
.context("Failed to send registration request")?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("Registration failed status={} body={}", status, body);
}
resp.json::<RegisterResponse>()
.await
.context("Failed to parse registration response")
}
pub async fn heartbeat(
&self,
agent_id: Uuid,
api_key: &str,
container_statuses: Option<Vec<ContainerStatus>>,
metrics: Option<crate::system::SystemMetrics>,
) -> Result<()> {
let url = format!(
"{}/api/registry/agents/{}/heartbeat",
self.gateway_url, agent_id
);
let (cpu_usage_percent, cpu_cores, memory_total_bytes, memory_used_bytes,
disk_total_bytes, disk_used_bytes, network_rx_bytes, network_tx_bytes,
uptime_seconds) = metrics.map(|m| (
Some(m.cpu_usage_percent), Some(m.cpu_cores),
Some(m.memory_total_bytes), Some(m.memory_used_bytes),
Some(m.disk_total_bytes), Some(m.disk_used_bytes),
Some(m.network_rx_bytes), Some(m.network_tx_bytes),
Some(m.uptime_seconds),
)).unwrap_or_default();
let mut req = self
.client
.post(&url)
.header("X-API-Key", api_key)
.json(&HeartbeatRequest {
status: None,
container_statuses,
cpu_usage_percent,
cpu_cores,
memory_total_bytes,
memory_used_bytes,
disk_total_bytes,
disk_used_bytes,
network_rx_bytes,
network_tx_bytes,
uptime_seconds,
});
if let Some(ref cert_pem) = self.cert_pem {
req = req.header("X-Client-Cert", cert_pem.as_str());
}
let resp = req.send().await.context("Failed to send heartbeat")?;
if !resp.status().is_success() {
let status = resp.status();
anyhow::bail!("Heartbeat failed status={}", status);
}
Ok(())
}
pub async fn fetch_assigned_workloads(
&self,
api_key: &str,
) -> Result<Vec<AssignedWorkload>> {
let url = format!("{}/api/workloads", self.gateway_url);
let resp = self
.client
.get(&url)
.header("X-API-Key", api_key)
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.context("Failed to fetch workloads")?;
if !resp.status().is_success() {
let status = resp.status();
anyhow::bail!("Failed to fetch workloads status={}", status);
}
let all: Vec<AssignedWorkload> = resp
.json()
.await
.context("Failed to parse workloads response")?;
Ok(all
.into_iter()
.filter(|w| {
w.status == "scheduled"
&& w.container_id.is_none()
})
.collect())
}
pub async fn fetch_assigned_volumes(
&self,
_agent_id: Uuid,
api_key: &str,
) -> Result<Vec<AssignedVolume>> {
let url = format!("{}/api/volumes", self.gateway_url);
let resp = self
.client
.get(&url)
.header("X-API-Key", api_key)
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.context("Failed to fetch volumes")?;
if !resp.status().is_success() {
let status = resp.status();
anyhow::bail!("Failed to fetch volumes status={}", status);
}
let all: Vec<AssignedVolume> = resp
.json()
.await
.context("Failed to parse volumes response")?;
Ok(all
.into_iter()
.filter(|v| {
v.status == "in_use"
&& v.mapped_device.is_none()
})
.collect())
}
}