-
Notifications
You must be signed in to change notification settings - Fork 5
/
ingress.rs
267 lines (254 loc) · 8.09 KB
/
ingress.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
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
266
267
use std::collections::HashMap;
use async_channel::Receiver;
use k8s_openapi::api::networking::v1::{HTTPIngressPath, Ingress, IngressRule, IngressServiceBackend, IngressTLS};
use kube::{Api, Client};
use futures::prelude::*;
use kube::runtime::{watcher, WatchStreamExt};
use kube::runtime::watcher::{ Event};
use serde::{Deserialize, Serialize};
use wd_tools::PFSome;
const INGRESS_CLASS_NAME_PINGORA:&'static str = "pingora";
#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct IngressEvent{
pub ty:u8, //1:init 2:update 3:delete
pub default_backend:Option<IngRule>,
pub hosts:Vec<IngHost>,
pub sni:IngSni,
#[serde(skip)]
pub ing:Option<Event<Ingress>>,
}
impl IngressEvent{
pub fn init(mut self)->Self{
match self.ing.as_ref().unwrap() {
Event::Applied(ref k) => {
let (default_backend,hosts,sni) = IngressEvent::ing_to_host_backend(k);
self.ty = 2;
self.default_backend = default_backend;
self.hosts = hosts;
self.sni = sni;
},
Event::Deleted(ref k) => {
let (default_backend,hosts,sni) = IngressEvent::ing_to_host_backend(k);
self.ty = 3;
self.default_backend = default_backend;
self.hosts = hosts;
self.sni = sni;
},
Event::Restarted(ref k) => {
let mut default_backend = None;
let mut hosts = vec![];
let mut sni = IngSni::default();
for i in k.iter(){
let (db, mut hs,is) = IngressEvent::ing_to_host_backend(i);
if db.is_some() {
default_backend = db;
}
hosts.append(&mut hs);
sni.append(is);
}
self.ty = 1;
self.default_backend = default_backend;
self.hosts = hosts;
self.sni = sni;
},
};
self
}
pub fn ing_to_host_backend(ing:&Ingress)->(Option<IngRule>,Vec<IngHost>,IngSni){
let i = if let Some(ref i) = ing.spec{
i
}else{
return (None,vec![],IngSni::default())
};
if let Some(ref n) = i.ingress_class_name {
if n != INGRESS_CLASS_NAME_PINGORA {
return (None,vec![],IngSni::default())
}
}
let default_backend = if let Some(ref d) = i.default_backend{
if let Some(ref s) = d.service{Some(IngRule::from(s))}else{None}
}else{None};
let mut hosts = vec![];
if let Some(ref i) = i.rules{
for i in i.iter(){
let ih = IngHost::from(i);
if !ih.rules.is_empty() {
hosts.push(ih);
}
}
}
let sni = if let Some(ref s) = i.tls{
IngSni::from_ingress_tls(s)
}else{
IngSni::default()
};
(default_backend,hosts,sni)
}
pub fn json(&self)->String{
serde_json::to_string(self).unwrap_or_else(|e| {
wd_log::log_error_ln!("IngressEvent json error:{}",e);
"".to_string()
})
}
}
impl From<Event<Ingress>> for IngressEvent {
fn from(value: Event<Ingress>) -> Self {
let ie = IngressEvent{
ty: 0,
default_backend: None,
hosts: vec![],
sni: Default::default(),
ing: Some(value),
};
ie.init()
}
}
#[derive(Default,Debug,Clone,Serialize,Deserialize)]
pub struct IngSni{
pub sni : HashMap<String,String>
}
impl IngSni{
pub fn from_ingress_tls(tls:&Vec<IngressTLS>)->IngSni{
let mut sni = HashMap::new();
for i in tls.iter(){
let secret = if let Some(ref s) = i.secret_name {
s.clone()
}else{
continue
};
if let Some(ref hs) = i.hosts{
for j in hs.iter(){
sni.insert(j.clone(),secret.clone());
}
}
}
Self{sni}
}
pub fn append(&mut self,other:Self){
self.sni.extend(other.sni);
}
}
#[derive(Default,Debug,Clone,Serialize,Deserialize)]
pub struct IngHost{
pub host:String,
pub rules:Vec<IngRule>,
}
impl From<&IngressRule> for IngHost {
fn from(value: &IngressRule) -> Self {
let host = if let Some(ref s) = value.host{
s.clone()
}else{"".to_string()};
let mut rules = vec![];
if let Some(ref list) = value.http{
for p in list.paths.iter(){
if let Some(r) = IngRule::new_from_path(p){
rules.push(r)
}
}
}
Self{host,rules}
}
}
#[derive(Default,Debug,Clone,Serialize,Deserialize)]
pub struct IngRule{
pub path: String,
pub ty:u8, //1:prefix 2:exact 3:specific
pub backend: String,
pub port:i32,
}
impl From<&IngressServiceBackend> for IngRule {
fn from(value: &IngressServiceBackend) -> Self {
let mut this = Self{
path: "".to_string(),
ty: 1,
backend: value.name.clone(),
port: 80,
};
if let Some(ref i) = value.port{
if let Some(i) = i.number{
this.port = i
}
}
this
}
}
impl IngRule{
pub fn new_from_path(value:&HTTPIngressPath)->Option<Self>{
let ty = match value.path_type.as_str().to_lowercase().as_str() {
"prefix" => 1u8,
"exact" => 2u8,
"implementationspecific" => 3u8,
_ => 99u8,
};
let path = value.path.clone().unwrap_or("".to_string());
let mut this = if let Some(ref s) = value.backend.service{
IngRule::from(s)
}else{
return None
};
this.ty = ty;
this.path = path;
this.some()
}
}
#[derive(Default,Debug,Clone)]
pub struct WatchIngress{
namespace:Option<String>,
selector_labels:Option<String>,
}
impl WatchIngress {
#[allow(dead_code)]
pub fn from_namespace<S:Into<String>>(ns:S)->Self{
let namespace = Some(ns.into());
Self{namespace,
.. Default::default()}
}
pub fn add_label_selector(mut self,key:&str,value:&str)->Self{
self.selector_labels = match self.selector_labels {
None => Some(format!("{}={}",key,value)),
Some(s) => {Some(format!("{},{}={}",s,key,value))}
};self
}
pub async fn start_watch(&self)-> anyhow::Result<Receiver<IngressEvent>> {
let (sender,receiver) = async_channel::bounded(8);
let client = Client::try_default().await?;
let api:Api<Ingress> = match self.namespace {
None =>{
Api::all(client)
} ,
Some(ref s) => Api::namespaced(client,s)
};
let mut wc = watcher::Config::default();
if let Some(ref s) = self.selector_labels{
wc = wc.labels(s)
};
let mut watch = watcher(api, wc)
// .applied_objects()
.default_backoff().boxed();
tokio::spawn(async move {
while let Some(result) = watch.next().await{
let event = match result{
Ok(o) => o,
Err(e) => {
wd_log::log_error_ln!("watch ingress event error:{:?}",e);
continue
}
};
let event = IngressEvent::from(event);
if let Err(e) = sender.send(event).await{
wd_log::log_error_ln!("watch ingress event to sender error:{:?}",e)
}
}
});
// let mut watch = watcher(api, wc).boxed();
// #[allow(irrefutable_let_patterns)]
// while let res = watch.try_next().await {
// if let Ok(Some(event)) = res{
// wd_log::log_info_ln!("event-->{:?}",event);
// }else{
// wd_log::log_warn_ln!("watch unknown error");
// }
// }
Ok(receiver)
}
}