-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.rs
210 lines (194 loc) · 6.32 KB
/
utils.rs
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
use anyhow::{anyhow, Ok, Result};
use resources::{
informer::{EventHandler, Informer, ListerWatcher, ResyncHandler, Store},
models,
models::ErrResponse,
objects::{pod::Pod, service::Service, KubeObject, Object},
};
use tokio::sync::mpsc::Sender;
use tokio_tungstenite::connect_async;
use crate::{Notification, PodNtf, ResyncNtf, ServiceNtf, CONFIG};
pub fn create_services_informer(
tx: Sender<Notification>,
resync_tx: Sender<ResyncNtf>,
) -> Informer<Service> {
let lw = ListerWatcher {
lister: Box::new(|_| {
Box::pin(async {
let res = reqwest::get(CONFIG.api_server_endpoint.join("/api/v1/services")?)
.await?
.json::<models::Response<Vec<Service>>>()
.await?;
let res = res.data.ok_or_else(|| anyhow!("Lister failed"))?;
Ok(res)
})
}),
watcher: Box::new(|_| {
Box::pin(async {
let mut url = CONFIG.api_server_endpoint.join("/api/v1/watch/services")?;
url.set_scheme("ws").ok();
let (stream, _) = connect_async(url).await?;
Ok(stream)
})
}),
};
// create event handler closures
let tx_add = tx;
let eh = EventHandler {
add_cls: Box::new(move |new| {
let tx_add = tx_add.clone();
Box::pin(async move {
tx_add
.send(Notification::Service(ServiceNtf::Add(new)))
.await?;
Ok(())
})
}),
update_cls: Box::new(move |_| Box::pin(async move { Ok(()) })),
delete_cls: Box::new(move |_| Box::pin(async move { Ok(()) })),
};
let rh = ResyncHandler(Box::new(move |()| {
let resync_tx = resync_tx.clone();
Box::pin(async move {
resync_tx.send(ResyncNtf::Svc).await?;
Ok(())
})
}));
// start the informer
Informer::new(lw, eh, rh)
}
pub fn create_pods_informer(
tx: Sender<Notification>,
resync_tx: Sender<ResyncNtf>,
) -> Informer<Pod> {
let lw = ListerWatcher {
lister: Box::new(|_| {
Box::pin(async {
let res = reqwest::get(CONFIG.api_server_endpoint.join("/api/v1/pods")?)
.await?
.json::<models::Response<Vec<Pod>>>()
.await?;
let res = res.data.ok_or_else(|| anyhow!("Lister failed"))?;
Ok(res)
})
}),
watcher: Box::new(|_| {
Box::pin(async {
let mut url = CONFIG.api_server_endpoint.join("/api/v1/watch/pods")?;
url.set_scheme("ws").ok();
let (stream, _) = connect_async(url).await?;
Ok(stream)
})
}),
};
// create event handler closures
let tx_add = tx.clone();
let tx_update = tx.clone();
let tx_delete = tx;
let eh = EventHandler {
add_cls: Box::new(move |new| {
let tx_add = tx_add.clone();
Box::pin(async move {
tx_add.send(Notification::Pod(PodNtf::Add(new))).await?;
Ok(())
})
}),
update_cls: Box::new(move |(old, new)| {
let tx_update = tx_update.clone();
Box::pin(async move {
tx_update
.send(Notification::Pod(PodNtf::Update(old, new)))
.await?;
Ok(())
})
}),
delete_cls: Box::new(move |old| {
let tx_delete = tx_delete.clone();
Box::pin(async move {
tx_delete
.send(Notification::Pod(PodNtf::Delete(old)))
.await?;
Ok(())
})
}),
};
let rh = ResyncHandler(Box::new(move |()| {
let resync_tx = resync_tx.clone();
Box::pin(async move {
resync_tx.send(ResyncNtf::Pod).await?;
Ok(())
})
}));
// start the informer
Informer::new(lw, eh, rh)
}
pub async fn add_svc_endpoint(svc_store: Store<Service>, pod: Pod) -> Result<()> {
let pod_ip = if let Some(ip) = pod.get_ip() {
ip
} else {
return Ok(());
};
let mut store = svc_store.write().await;
for (_, svc) in store.iter_mut() {
if svc.spec.selector.matches(&pod.metadata.labels) && !svc.spec.endpoints.contains(&pod_ip)
{
svc.spec.endpoints.insert(pod_ip);
update_service(svc).await?;
tracing::info!("Add endpoint {} for service {}", pod_ip, svc.name());
}
}
Ok(())
}
pub async fn del_svc_endpoint(svc_store: Store<Service>, pod: Pod) -> Result<()> {
let pod_ip = if let Some(ip) = pod.get_ip() {
ip
} else {
return Ok(());
};
let mut store = svc_store.write().await;
for (_, svc) in store.iter_mut() {
if svc.spec.selector.matches(&pod.metadata.labels) && svc.spec.endpoints.contains(&pod_ip) {
svc.spec.endpoints.retain(|ip| ip != &pod_ip);
update_service(svc).await?;
tracing::info!(
"Remove endpoint {} for service {}",
pod_ip,
svc.metadata.name
);
}
}
Ok(())
}
pub async fn update_service(svc: &Service) -> Result<()> {
let client = reqwest::Client::new();
let res = client
.put(CONFIG.api_server_endpoint.join(svc.uri().as_str())?)
.json(&KubeObject::Service(svc.to_owned()))
.send()
.await?;
if res.error_for_status_ref().is_err() {
let res = res.json::<ErrResponse>().await?;
tracing::error!("Error update service: {}", res.msg);
}
Ok(())
}
pub async fn add_enpoints(pod_store: Store<Pod>, mut svc: Service) -> Result<()> {
let mut svc_changed = false;
let mut store = pod_store.write().await;
for (_, pod) in store.iter_mut() {
let pod_ip = if let Some(ip) = pod.get_ip() {
ip
} else {
continue;
};
if svc.spec.selector.matches(&pod.metadata.labels) {
svc_changed = true;
svc.spec.endpoints.insert(pod_ip);
tracing::info!("Add endpoint {} for service {}", pod_ip, svc.metadata.name);
}
}
if svc_changed {
update_service(&svc).await?
}
Ok(())
}