-
Notifications
You must be signed in to change notification settings - Fork 0
/
deployment.rs
273 lines (240 loc) · 8.86 KB
/
deployment.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
268
269
270
271
272
273
use super::*;
use std::collections::BTreeMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceConfig {
pub name: String,
pub port: u16,
pub target_port: u16,
pub namespace: String,
}
impl ServiceConfig {
pub fn new(name: String, namespace: String, external_port: u16) -> Self {
Self {
name,
port: external_port,
target_port: 8080,
namespace,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeploymentConfig {
pub resource: ResourceConfig,
pub container: ContainerConfig,
pub service: ServiceConfig,
pub replicas: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceConfig {
pub name: String,
pub namespace: String,
pub labels: BTreeMap<String, String>,
pub annotations: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContainerConfig {
pub image: String,
pub port: u16,
pub env: Vec<(String, String)>,
pub resources: Option<ResourceRequirements>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceRequirements {
pub cpu: String,
pub memory: String,
}
pub struct DeploymentManager {
client: Client,
namespace: String,
}
impl DeploymentManager {
pub fn new(client: Client, namespace: String) -> Self {
Self { client, namespace }
}
pub async fn create(&self, config: &DeploymentConfig) -> Result<(), K8sError> {
let deployment = self.build_deployment(config);
let deployments: Api<Deployment> =
Api::namespaced(self.client.clone(), &config.resource.namespace);
match deployments
.create(&PostParams::default(), &deployment)
.await
{
Ok(_) => (),
Err(kube::Error::Api(err)) if err.code == 409 => {
return Err(K8sError::AlreadyExists(config.resource.name.clone()))
}
Err(e) => return Err(K8sError::ClientError(e)),
}
let service = self.build_service(config)?;
let services: Api<k8s_openapi::api::core::v1::Service> =
Api::namespaced(self.client.clone(), &config.resource.namespace);
match services.create(&PostParams::default(), &service).await {
Ok(_) => Ok(()),
Err(kube::Error::Api(err)) if err.code == 409 => {
Err(K8sError::AlreadyExists(config.resource.name.clone()))
}
Err(e) => Err(K8sError::ClientError(e)),
}
}
fn build_deployment(&self, config: &DeploymentConfig) -> Deployment {
Deployment {
metadata: metadata(
&config.resource.name,
&config.resource.namespace,
&config.resource.labels,
&config.resource.annotations,
),
spec: Some(deployment_spec(
&config.container.image,
config.container.port,
&config.container.env,
config.replicas,
config.container.resources.clone(),
)),
..Default::default()
}
}
fn build_service(
&self,
config: &DeploymentConfig,
) -> Result<k8s_openapi::api::core::v1::Service, K8sError> {
let mut labels = config.resource.labels.clone();
labels.insert("app".to_string(), config.resource.name.clone());
Ok(k8s_openapi::api::core::v1::Service {
metadata: ObjectMeta {
name: Some(config.resource.name.clone()),
namespace: Some(config.resource.namespace.clone()),
labels: Some(labels.clone()),
..Default::default()
},
spec: Some(k8s_openapi::api::core::v1::ServiceSpec {
ports: Some(vec![k8s_openapi::api::core::v1::ServicePort {
port: config.service.port as i32,
target_port: Some(
k8s_openapi::apimachinery::pkg::util::intstr::IntOrString::Int(
config.container.port as i32,
),
),
..Default::default()
}]),
selector: Some(labels),
type_: Some("ClusterIP".to_string()),
..Default::default()
}),
status: None,
})
}
}
#[async_trait::async_trait]
impl ResourceManager for DeploymentManager {
type Config = DeploymentConfig;
type Output = Deployment;
async fn create(&self, config: &Self::Config) -> Result<Self::Output, K8sError> {
let api: Api<Deployment> = Api::namespaced(self.client.clone(), &config.resource.namespace);
let pp = PostParams::default();
let deployment = self.build_deployment(config);
let res = api.create(&pp, &deployment).await?;
Ok(res)
}
async fn delete(&self, name: &str) -> Result<(), K8sError> {
let api: Api<Deployment> = Api::namespaced(self.client.clone(), &self.namespace);
let dp = DeleteParams::default();
api.delete(name, &dp).await?;
Ok(())
}
async fn get(&self, name: &str) -> Result<Self::Output, K8sError> {
let api: Api<Deployment> = Api::namespaced(self.client.clone(), &self.namespace);
api.get(name).await.map_err(|e| match e {
kube::Error::Api(err) if err.code == 404 => K8sError::NotFound(name.to_string()),
e => K8sError::ClientError(e),
})
}
async fn list(&self) -> Result<Vec<Self::Output>, K8sError> {
let api: Api<Deployment> = Api::namespaced(self.client.clone(), &self.namespace);
let lp = ListParams::default();
let res = api.list(&lp).await?;
Ok(res.items)
}
}
#[cfg(test)]
mod tests {
use super::*;
use kube::{Client, Config};
use rustls::crypto::aws_lc_rs::default_provider;
async fn setup_test_client() -> (Client, String) {
let provider = default_provider();
let _ = provider.install_default();
let config = Config::infer().await.expect("Failed to infer kube config");
let client = Client::try_from(config).expect("Failed to create kube client");
(client, "test-namespace".to_string())
}
fn create_test_config() -> DeploymentConfig {
DeploymentConfig {
resource: ResourceConfig {
name: "test-indexer".to_string(),
namespace: "test-namespace".to_string(),
labels: Default::default(),
annotations: Default::default(),
},
container: ContainerConfig {
image: "localhost:5000/test-image:latest".to_string(),
port: 8080,
env: vec![
("BLOCKCHAIN".to_string(), "ethereum".to_string()),
("RPC_URL".to_string(), "http://localhost:8545".to_string()),
],
resources: None,
},
service: ServiceConfig::new(
"test-indexer".to_string(),
"test-namespace".to_string(),
8080,
),
replicas: 1,
}
}
#[tokio::test]
async fn test_build_deployment() {
let (client, namespace) = setup_test_client().await;
let manager = DeploymentManager::new(client, namespace);
let config = create_test_config();
let deployment = manager.build_deployment(&config);
// Verify deployment metadata
assert_eq!(deployment.metadata.name, Some("test-indexer".to_string()));
assert_eq!(
deployment.metadata.namespace,
Some("test-namespace".to_string())
);
// Verify deployment spec
let spec = deployment.spec.unwrap();
assert_eq!(spec.replicas, Some(1));
let container = &spec.template.spec.unwrap().containers[0];
assert_eq!(
container.image,
Some("localhost:5000/test-image:latest".to_string())
);
assert_eq!(container.ports.as_ref().unwrap()[0].container_port, 8080);
}
#[tokio::test]
async fn test_build_service() {
let (client, namespace) = setup_test_client().await;
let manager = DeploymentManager::new(client, namespace);
let config = create_test_config();
let service = manager
.build_service(&config)
.expect("Failed to build service");
assert_eq!(service.metadata.name, Some("test-indexer".to_string()));
assert_eq!(
service.metadata.namespace,
Some("test-namespace".to_string())
);
let spec = service.spec.unwrap();
assert_eq!(spec.type_, Some("ClusterIP".to_string()));
let port = &spec.ports.unwrap()[0];
assert_eq!(port.port, 8080);
assert_eq!(
port.target_port,
Some(k8s_openapi::apimachinery::pkg::util::intstr::IntOrString::Int(8080))
);
}
}