1use crate::{
3 params::{DeleteParams, PostParams},
4 request::{Error, JSON_MIME, Request},
5};
6use jiff::{RoundMode, Timestamp, TimestampRound, Unit};
7use std::fmt::Debug;
8
9pub use k8s_openapi::api::autoscaling::v1::{Scale, ScaleSpec, ScaleStatus};
10
11#[derive(Default, Clone, Debug)]
17pub struct LogParams {
18 pub container: Option<String>,
20 pub follow: bool,
22 pub limit_bytes: Option<i64>,
25 pub pretty: bool,
27 pub previous: bool,
29 pub since_seconds: Option<i64>,
33 pub since_time: Option<Timestamp>,
38 pub tail_lines: Option<i64>,
41 pub timestamps: bool,
43}
44
45impl Request {
46 pub fn logs(&self, name: &str, lp: &LogParams) -> Result<http::Request<Vec<u8>>, Error> {
48 let target = format!("{}/{}/log?", self.url_path, name);
49 let mut qp = form_urlencoded::Serializer::new(target);
50
51 if let Some(container) = &lp.container {
52 qp.append_pair("container", container);
53 }
54
55 if lp.follow {
56 qp.append_pair("follow", "true");
57 }
58
59 if let Some(lb) = &lp.limit_bytes {
60 qp.append_pair("limitBytes", &lb.to_string());
61 }
62
63 if lp.pretty {
64 qp.append_pair("pretty", "true");
65 }
66
67 if lp.previous {
68 qp.append_pair("previous", "true");
69 }
70
71 if let Some(ss) = &lp.since_seconds {
72 qp.append_pair("sinceSeconds", &ss.to_string());
73 } else if let Some(st) = &lp.since_time {
74 let floor = TimestampRound::new()
80 .smallest(Unit::Second)
81 .mode(RoundMode::Floor);
82 qp.append_pair("sinceTime", &st.round(floor).unwrap().to_string());
83 }
84
85 if let Some(tl) = &lp.tail_lines {
86 qp.append_pair("tailLines", &tl.to_string());
87 }
88
89 if lp.timestamps {
90 qp.append_pair("timestamps", "true");
91 }
92
93 let urlstr = qp.finish();
94 let req = http::Request::get(urlstr);
95 req.body(vec![]).map_err(Error::BuildRequest)
96 }
97}
98
99#[derive(Default, Clone)]
105pub struct EvictParams {
106 pub delete_options: Option<DeleteParams>,
108 pub post_options: PostParams,
110}
111
112impl Request {
113 pub fn evict(&self, name: &str, ep: &EvictParams) -> Result<http::Request<Vec<u8>>, Error> {
115 let target = format!("{}/{}/eviction?", self.url_path, name);
116 let pp = &ep.post_options;
118 pp.validate()?;
119 let mut qp = form_urlencoded::Serializer::new(target);
120 pp.populate_qp(&mut qp);
121 let urlstr = qp.finish();
122 let data = serde_json::to_vec(&serde_json::json!({
124 "deleteOptions": ep.delete_options,
125 "metadata": { "name": name }
126 }))
127 .map_err(Error::SerializeBody)?;
128 let req = http::Request::post(urlstr).header(http::header::CONTENT_TYPE, JSON_MIME);
129 req.body(data).map_err(Error::BuildRequest)
130 }
131}
132
133#[cfg(feature = "ws")]
141#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
142#[derive(Debug)]
143pub struct AttachParams {
144 pub container: Option<String>,
147 pub stdin: bool,
151 pub stdout: bool,
155 pub stderr: bool,
159 pub tty: bool,
163
164 pub max_stdin_buf_size: Option<usize>,
170 pub max_stdout_buf_size: Option<usize>,
176 pub max_stderr_buf_size: Option<usize>,
182}
183
184#[cfg(feature = "ws")]
185#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
186impl Default for AttachParams {
187 fn default() -> Self {
189 Self {
190 container: None,
191 stdin: false,
192 stdout: true,
193 stderr: true,
194 tty: false,
195 max_stdin_buf_size: None,
196 max_stdout_buf_size: None,
197 max_stderr_buf_size: None,
198 }
199 }
200}
201
202#[cfg(feature = "ws")]
203#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
204impl AttachParams {
205 #[must_use]
207 pub fn interactive_tty() -> Self {
208 Self {
209 stdin: true,
210 stdout: true,
211 stderr: false,
212 tty: true,
213 ..Default::default()
214 }
215 }
216
217 #[must_use]
219 pub fn container<T: Into<String>>(mut self, container: T) -> Self {
220 self.container = Some(container.into());
221 self
222 }
223
224 #[must_use]
226 pub fn stdin(mut self, enable: bool) -> Self {
227 self.stdin = enable;
228 self
229 }
230
231 #[must_use]
233 pub fn stdout(mut self, enable: bool) -> Self {
234 self.stdout = enable;
235 self
236 }
237
238 #[must_use]
240 pub fn stderr(mut self, enable: bool) -> Self {
241 self.stderr = enable;
242 self
243 }
244
245 #[must_use]
247 pub fn tty(mut self, enable: bool) -> Self {
248 self.tty = enable;
249 self
250 }
251
252 #[must_use]
254 pub fn max_stdin_buf_size(mut self, size: usize) -> Self {
255 self.max_stdin_buf_size = Some(size);
256 self
257 }
258
259 #[must_use]
261 pub fn max_stdout_buf_size(mut self, size: usize) -> Self {
262 self.max_stdout_buf_size = Some(size);
263 self
264 }
265
266 #[must_use]
268 pub fn max_stderr_buf_size(mut self, size: usize) -> Self {
269 self.max_stderr_buf_size = Some(size);
270 self
271 }
272
273 pub(crate) fn validate(&self) -> Result<(), Error> {
274 if !self.stdin && !self.stdout && !self.stderr {
275 return Err(Error::Validation(
276 "AttachParams: one of stdin, stdout, or stderr must be true".into(),
277 ));
278 }
279
280 if self.stderr && self.tty {
281 return Err(Error::Validation(
283 "AttachParams: tty and stderr cannot both be true".into(),
284 ));
285 }
286
287 Ok(())
288 }
289
290 fn append_to_url_serializer(&self, qp: &mut form_urlencoded::Serializer<String>) {
291 if self.stdin {
292 qp.append_pair("stdin", "true");
293 }
294 if self.stdout {
295 qp.append_pair("stdout", "true");
296 }
297 if self.stderr {
298 qp.append_pair("stderr", "true");
299 }
300 if self.tty {
301 qp.append_pair("tty", "true");
302 }
303 if let Some(container) = &self.container {
304 qp.append_pair("container", container);
305 }
306 }
307
308 #[cfg(feature = "kubelet-debug")]
309 pub(crate) fn append_to_url_serializer_local(&self, qp: &mut form_urlencoded::Serializer<String>) {
311 if self.stdin {
312 qp.append_pair("input", "1");
313 }
314 if self.stdout {
315 qp.append_pair("output", "1");
316 }
317 if self.stderr {
318 qp.append_pair("error", "1");
319 }
320 if self.tty {
321 qp.append_pair("tty", "1");
322 }
323 }
324}
325
326#[cfg(feature = "ws")]
327#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
328impl Request {
329 pub fn attach(&self, name: &str, ap: &AttachParams) -> Result<http::Request<Vec<u8>>, Error> {
331 ap.validate()?;
332
333 let target = format!("{}/{}/attach?", self.url_path, name);
334 let mut qp = form_urlencoded::Serializer::new(target);
335 ap.append_to_url_serializer(&mut qp);
336
337 let req = http::Request::get(qp.finish());
338 req.body(vec![]).map_err(Error::BuildRequest)
339 }
340}
341
342#[cfg(feature = "ws")]
346#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
347impl Request {
348 pub fn exec<I, T>(
350 &self,
351 name: &str,
352 command: I,
353 ap: &AttachParams,
354 ) -> Result<http::Request<Vec<u8>>, Error>
355 where
356 I: IntoIterator<Item = T>,
357 T: Into<String>,
358 {
359 ap.validate()?;
360
361 let target = format!("{}/{}/exec?", self.url_path, name);
362 let mut qp = form_urlencoded::Serializer::new(target);
363 ap.append_to_url_serializer(&mut qp);
364
365 for c in command.into_iter() {
366 qp.append_pair("command", &c.into());
367 }
368
369 let req = http::Request::get(qp.finish());
370 req.body(vec![]).map_err(Error::BuildRequest)
371 }
372}
373
374#[cfg(feature = "ws")]
378#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
379impl Request {
380 pub fn portforward(&self, name: &str, ports: &[u16]) -> Result<http::Request<Vec<u8>>, Error> {
382 if ports.is_empty() {
383 return Err(Error::Validation("ports cannot be empty".into()));
384 }
385 if ports.len() > 128 {
386 return Err(Error::Validation(
387 "the number of ports cannot be more than 128".into(),
388 ));
389 }
390
391 if ports.len() > 1 {
392 let mut seen = std::collections::HashSet::with_capacity(ports.len());
393 for port in ports.iter() {
394 if seen.contains(port) {
395 return Err(Error::Validation(format!(
396 "ports must be unique, found multiple {port}"
397 )));
398 }
399 seen.insert(port);
400 }
401 }
402
403 let base_url = format!("{}/{}/portforward?", self.url_path, name);
404 let mut qp = form_urlencoded::Serializer::new(base_url);
405 qp.append_pair(
406 "ports",
407 &ports.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(","),
408 );
409
410 let req = http::Request::get(qp.finish());
411 req.body(vec![]).map_err(Error::BuildRequest)
412 }
413}
414
415#[cfg(test)]
421mod test {
422 use crate::{request::Request, resource::Resource};
423 use jiff::Timestamp;
424 use k8s::core::v1 as corev1;
425 use k8s_openapi::api as k8s;
426
427 use crate::{
428 params::{DeleteParams, Preconditions},
429 subresource::{EvictParams, LogParams},
430 };
431
432 #[test]
433 fn evict_body_carries_delete_options() {
434 let url = corev1::Pod::url_path(&(), Some("ns"));
435 let ep = EvictParams {
436 delete_options: Some(DeleteParams {
437 preconditions: Some(Preconditions {
438 uid: Some("u1".into()),
439 resource_version: None,
440 }),
441 ..Default::default()
442 }),
443 ..Default::default()
444 };
445 let req = Request::new(url).evict("mypod", &ep).unwrap();
446 let body: serde_json::Value = serde_json::from_slice(req.body()).unwrap();
447 assert_eq!(body["deleteOptions"]["preconditions"]["uid"], "u1");
448 assert_eq!(body["metadata"]["name"], "mypod");
449 assert!(body.get("delete_options").is_none());
450 }
451
452 #[test]
453 fn logs_all_params() {
454 let url = corev1::Pod::url_path(&(), Some("ns"));
455 let lp = LogParams {
456 container: Some("nginx".into()),
457 follow: true,
458 limit_bytes: Some(10 * 1024 * 1024),
459 pretty: true,
460 previous: true,
461 since_seconds: Some(3600),
462 since_time: None,
463 tail_lines: Some(4096),
464 timestamps: true,
465 };
466 let req = Request::new(url).logs("mypod", &lp).unwrap();
467 assert_eq!(
468 req.uri(),
469 "/api/v1/namespaces/ns/pods/mypod/log?&container=nginx&follow=true&limitBytes=10485760&pretty=true&previous=true&sinceSeconds=3600&tailLines=4096×tamps=true"
470 );
471 }
472
473 #[test]
474 fn logs_since_time() {
475 let url = corev1::Pod::url_path(&(), Some("ns"));
476 let date: Timestamp = "2023-10-19T13:14:26Z".parse().unwrap();
477 let lp = LogParams {
478 since_seconds: None,
479 since_time: Some(date),
480 ..Default::default()
481 };
482 let req = Request::new(url).logs("mypod", &lp).unwrap();
483 assert_eq!(
484 req.uri(),
485 "/api/v1/namespaces/ns/pods/mypod/log?&sinceTime=2023-10-19T13%3A14%3A26Z" );
487 }
488
489 #[test]
490 fn logs_since_time_rounds_down() {
491 let url = corev1::Pod::url_path(&(), Some("ns"));
492 let date: Timestamp = "2023-10-19T13:14:26.7Z".parse().unwrap();
493 let lp = LogParams {
494 since_time: Some(date),
495 ..Default::default()
496 };
497 let req = Request::new(url).logs("mypod", &lp).unwrap();
498 assert_eq!(
499 req.uri(),
500 "/api/v1/namespaces/ns/pods/mypod/log?&sinceTime=2023-10-19T13%3A14%3A26Z"
501 );
502 }
503}