cortexflow-cli 0.1.4

CortexFlow command line interface made to interact with the CortexBrain core components
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::{ str, process::Command, result::Result::Ok };
use colored::Colorize;
use clap::Args;
use kube::{ Error, core::ErrorResponse };
use crate::essential::{ connect_to_client, BASE_COMMAND, CliError };

#[derive(Args, Debug, Clone)]
pub struct LogsArgs {
    #[arg(long)]
    pub service: Option<String>,
    #[arg(long)]
    pub component: Option<String>,
    #[arg(long)]
    pub namespace: Option<String>,
}

#[derive(Debug, Clone)]
pub enum Component {
    ControlPlane,
    DataPlane,
}

impl From<String> for Component {
    fn from(s: String) -> Self {
        match s.to_lowercase().as_str() {
            "control-plane" => Component::ControlPlane,
            "data-plane" => Component::DataPlane,
            //default will be control plane.
            _ => Component::ControlPlane,
        }
    }
}

impl Component {
    fn to_label_selector(&self) -> &str {
        match self {
            Component::ControlPlane => "component=control-plane",
            Component::DataPlane => "component=data-plane",
        }
    }
}

// docs:
//
// This is the main function for the logs command
// Steps:
//      - connects to kubernetes client
//      - returns the list of namespaces in Vec<String> format
//
//
// Returns a CliError if the connectiion to the kubeapi fails

pub async fn logs_command(
    service: Option<String>,
    component: Option<String>,
    namespace: Option<String>
) -> Result<(), CliError> {
    match connect_to_client().await {
        Ok(_) => {
            let ns = namespace.unwrap_or_else(|| "cortexflow".to_string());

            if !check_namespace_exists(&ns).await? {
                let available_namespaces = get_available_namespaces().await?;
                println!("\n❌ Namespace '{}' not found", ns);
                println!("{}", "=".repeat(50));
                if !available_namespaces.is_empty() {
                    println!("\n📋 Available namespaces:");
                    for available_ns in &available_namespaces {
                        println!("{}", available_ns);
                    }
                } else {
                    println!("No namespaces found in the cluster.");
                }
                std::process::exit(1);
            }

            let pods = match (service, component) {
                (Some(service_name), Some(component_str)) => {
                    let comp = Component::from(component_str);
                    println!(
                        "{} Getting logs for service '{}' with component '{:?}' in namespace '{}'",
                        "=====>".blue().bold(),
                        service_name,
                        comp,
                        ns
                    );
                    let service_pods = get_pods_for_service(&ns, &service_name).await?;
                    let component_pods = get_pods_for_component(&ns, &comp).await?;
                    service_pods
                        .into_iter()
                        .filter(|pod| component_pods.contains(pod))
                        .collect()
                }
                (Some(service_name), None) => {
                    println!("Getting logs for service '{}' in namespace '{}'", service_name, ns);
                    get_pods_for_service(&ns, &service_name).await?
                }
                (None, Some(component_str)) => {
                    let comp = Component::from(component_str);
                    println!("Getting logs for component '{:?}' in namespace '{}'", comp, ns);
                    get_pods_for_component(&ns, &comp).await?
                }
                (None, None) => {
                    println!(
                        "{} Getting logs for all pods in namespace '{}'",
                        "=====>".blue().bold(),
                        ns
                    );
                    get_all_pods(&ns).await?
                }
            };

            if pods.is_empty() {
                println!("No pods found matching the specified criteria");
                return Ok(());
            }

            for pod in pods {
                println!("{} Logs for pod: {:?}", "=====>".blue().bold(), pod);
                match
                    Command::new(BASE_COMMAND).args(["logs", &pod, "-n", &ns, "--tail=50"]).output()
                {
                    Ok(output) => {
                        if output.status.success() {
                            let stdout = str::from_utf8(&output.stdout).unwrap_or("");
                            if stdout.trim().is_empty() {
                                println!("No logs available for pod '{:?}'", pod);
                            } else {
                                println!("{}", stdout);
                            }
                        } else {
                            let stderr = str::from_utf8(&output.stderr).unwrap_or("Unknown error");
                            eprintln!("Error getting logs for pod '{:?}': {}", pod, stderr);
                        }
                    }
                    Err(err) => {
                        eprintln!(
                            "Failed to execute {} logs for pod '{:?}': {}",
                            BASE_COMMAND,
                            pod,
                            err
                        );
                    }
                }
            }

            Ok(())
        }
        Err(_) => {
            Err(
                CliError::ClientError(
                    Error::Api(ErrorResponse {
                        status: "failed".to_string(),
                        message: "Failed to connect to kubernetes client".to_string(),
                        reason: "Your cluster is probably disconnected".to_string(),
                        code: 404,
                    })
                )
            )
        }
    }
}

// docs:
//
// This is an auxiliary function used in the logs_command
// Steps:
//      - connects to kubernetes client
//      - returns true if the namespace exists or false if the namespace doesn't exists
//
//
// Returns a CliError if the connection fails

pub async fn check_namespace_exists(namespace: &str) -> Result<bool, CliError> {
    match connect_to_client().await {
        Ok(_) => {
            let output = Command::new(BASE_COMMAND).args(["get", "namespace", namespace]).output();

            match output {
                Ok(output) => Ok(output.status.success()),
                Err(_) => Ok(false),
            }
        }
        Err(_) => {
            Err(
                CliError::ClientError(
                    Error::Api(ErrorResponse {
                        status: "failed".to_string(),
                        message: "Failed to connect to kubernetes client".to_string(),
                        reason: "Your cluster is probably disconnected".to_string(),
                        code: 404,
                    })
                )
            )
        }
    }
}

// docs:
//
// This function returns the available namespaces:
// Steps:
//      - connects to kubernetes client
//      - returns the list of namespaces in Vec<String> format
//
//
// Returns a CliError if the connectiion to the kubeapi fails

pub async fn get_available_namespaces() -> Result<Vec<String>, CliError> {
    match connect_to_client().await {
        Ok(_) => {
            let output = Command::new(BASE_COMMAND)
                .args([
                    "get",
                    "namespaces",
                    "--no-headers",
                    "-o",
                    "custom-columns=NAME:.metadata.name",
                ])
                .output();

            match output {
                Ok(output) if output.status.success() => {
                    let stdout = str::from_utf8(&output.stdout).unwrap_or("");
                    let ns = stdout
                        .lines()
                        .map(|line| line.trim().to_string())
                        .filter(|line| !line.is_empty())
                        .collect();
                    Ok(ns)
                }
                _ => Ok(Vec::new()),
            }
        }
        Err(_) => {
            Err(
                CliError::ClientError(
                    Error::Api(ErrorResponse {
                        status: "failed".to_string(),
                        message: "Failed to connect to kubernetes client".to_string(),
                        reason: "Your cluster is probably disconnected".to_string(),
                        code: 404,
                    })
                )
            )
        }
    }
}

// docs:
//
// This function returns the pods:
// Steps:
//      - connects to kubernetes client
//      - returns the list of pods associated with a kubernetes service filtering by labels in Vec<String> format
//
//
// Returns a CliError if the connectiion to the kubeapi fails

async fn get_pods_for_service(
    namespace: &str,
    service_name: &str
) -> Result<Vec<String>, CliError> {
    match connect_to_client().await {
        Ok(_) => {
            let output = Command::new(BASE_COMMAND)
                .args([
                    "get",
                    "pods",
                    "-n",
                    namespace,
                    "-l",
                    &format!("app={}", service_name),
                    "--no-headers",
                    "-o",
                    "custom-columns=NAME:.metadata.name",
                ])
                .output();

            match output {
                Ok(output) if output.status.success() => {
                    let stdout = str::from_utf8(&output.stdout).unwrap_or("");
                    let pods = stdout
                        .lines()
                        .map(|line| line.trim().to_string())
                        .filter(|line| !line.is_empty())
                        .collect();
                    Ok(pods)
                }
                _ => Ok(Vec::new()),
            }
        }
        Err(_) => {
            Err(
                CliError::ClientError(
                    Error::Api(ErrorResponse {
                        status: "failed".to_string(),
                        message: "Failed to connect to kubernetes client".to_string(),
                        reason: "Your cluster is probably disconnected".to_string(),
                        code: 404,
                    })
                )
            )
        }
    }
}

// docs:
//
// This function returns the pods:
// Steps:
//      - connects to kubernetes client
//      - returns the list of pods associated with a componet object to dynamically construct the
//        label selector,in Vec<String> format
//
//
// Returns a CliError if the connectiion to the kubeapi fails

async fn get_pods_for_component(
    namespace: &str,
    component: &Component
) -> Result<Vec<String>, CliError> {
    match connect_to_client().await {
        Ok(_) => {
            let output = Command::new(BASE_COMMAND)
                .args([
                    "get",
                    "pods",
                    "-n",
                    namespace,
                    "-l",
                    component.to_label_selector(),
                    "--no-headers",
                    "-o",
                    "custom-columns=NAME:.metadata.name",
                ])
                .output();

            match output {
                Ok(output) if output.status.success() => {
                    let stdout = str::from_utf8(&output.stdout).unwrap_or("");
                    let pods = stdout
                        .lines()
                        .map(|line| line.trim().to_string())
                        .filter(|line| !line.is_empty())
                        .collect();
                    Ok(pods)
                }
                _ => Ok(Vec::new()),
            }
        }
        Err(_) => {
            Err(
                CliError::ClientError(
                    Error::Api(ErrorResponse {
                        status: "failed".to_string(),
                        message: "Failed to connect to kubernetes client".to_string(),
                        reason: "Your cluster is probably disconnected".to_string(),
                        code: 404,
                    })
                )
            )
        }
    }
}

// docs:
//
// This function returns the available namespaces:
// Steps:
//      - connects to kubernetes client
//      - returns the list of all pods in Vec<String> format
//
//
// Returns a CliError if the connectiion to the kubeapi fails

async fn get_all_pods(namespace: &str) -> Result<Vec<String>, CliError> {
    match connect_to_client().await {
        Ok(_) => {
            let output = Command::new(BASE_COMMAND)
                .args([
                    "get",
                    "pods",
                    "-n",
                    namespace,
                    "--no-headers",
                    "-o",
                    "custom-columns=NAME:.metadata.name",
                ])
                .output();

            match output {
                Ok(output) if output.status.success() => {
                    let stdout = str::from_utf8(&output.stdout).unwrap_or("");
                    let pods = stdout
                        .lines()
                        .map(|line| line.trim().to_string())
                        .filter(|line| !line.is_empty())
                        .collect();
                    Ok(pods)
                }
                _ => Ok(Vec::new()),
            }
        }
        Err(_) => {
            Err(
                CliError::ClientError(
                    Error::Api(ErrorResponse {
                        status: "failed".to_string(),
                        message: "Failed to connect to kubernetes client".to_string(),
                        reason: "Your cluster is probably disconnected".to_string(),
                        code: 404,
                    })
                )
            )
        }
    }
}