Skip to main content

kube_core/
subresource.rs

1//! Request builder types and parameters for subresources
2use 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// ----------------------------------------------------------------------------
12// Log subresource
13// ----------------------------------------------------------------------------
14
15/// Params for logging
16#[derive(Default, Clone, Debug)]
17pub struct LogParams {
18    /// The container for which to stream logs. Defaults to only container if there is one container in the pod.
19    pub container: Option<String>,
20    /// Follow the log stream of the pod. Defaults to `false`.
21    pub follow: bool,
22    /// If set, the number of bytes to read from the server before terminating the log output.
23    /// This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit.
24    pub limit_bytes: Option<i64>,
25    /// If `true`, then the output is pretty printed.
26    pub pretty: bool,
27    /// Return previous terminated container logs. Defaults to `false`.
28    pub previous: bool,
29    /// A relative time in seconds before the current time from which to show logs.
30    /// If this value precedes the time a pod was started, only logs since the pod start will be returned.
31    /// If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.
32    pub since_seconds: Option<i64>,
33    /// An RFC3339 timestamp from which to show logs. If this value
34    /// precedes the time a pod was started, only logs since the pod start will be returned.
35    /// If this value is in the future, no logs will be returned.
36    /// Only one of sinceSeconds or sinceTime may be specified.
37    pub since_time: Option<Timestamp>,
38    /// If set, the number of lines from the end of the logs to show.
39    /// If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime
40    pub tail_lines: Option<i64>,
41    /// If `true`, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to `false`.
42    pub timestamps: bool,
43}
44
45impl Request {
46    /// Get a pod logs
47    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            // Unwrapping here is ok as `round` only errors if a.) the smallest unit is larger than hour (we set second as smallest unit)
75            // or b.) a rounding increment is configured (which we don't set) that does not fit into 86400 seconds (a day)
76            // without any remainder.
77            // `jiff::Timestamp` provides RFC3339 via `Display`, docs: https://docs.rs/jiff/latest/jiff/struct.Timestamp.html#impl-Display-for-Timestamp
78            // Round down like client-go; rounding up would skip lines logged later in the same second.
79            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// ----------------------------------------------------------------------------
100// Eviction subresource
101// ----------------------------------------------------------------------------
102
103/// Params for evictable objects
104#[derive(Default, Clone)]
105pub struct EvictParams {
106    /// How the eviction should occur
107    pub delete_options: Option<DeleteParams>,
108    /// How the http post should occur
109    pub post_options: PostParams,
110}
111
112impl Request {
113    /// Create an eviction
114    pub fn evict(&self, name: &str, ep: &EvictParams) -> Result<http::Request<Vec<u8>>, Error> {
115        let target = format!("{}/{}/eviction?", self.url_path, name);
116        // This is technically identical to Request::create, but different url
117        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        // eviction body parameters are awkward, need metadata with name
123        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// ----------------------------------------------------------------------------
134// Attach subresource
135// ----------------------------------------------------------------------------
136/// Parameters for attaching to a container in a Pod.
137///
138/// - One of `stdin`, `stdout`, or `stderr` must be `true`.
139/// - `stderr` and `tty` cannot both be `true` because multiplexing is not supported with TTY.
140#[cfg(feature = "ws")]
141#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
142#[derive(Debug)]
143pub struct AttachParams {
144    /// The name of the container to attach.
145    /// Defaults to the only container if there is only one container in the pod.
146    pub container: Option<String>,
147    /// Attach to the container's standard input. Defaults to `false`.
148    ///
149    /// Call [`AttachedProcess::stdin`](https://docs.rs/kube/*/kube/api/struct.AttachedProcess.html#method.stdin) to obtain a writer.
150    pub stdin: bool,
151    /// Attach to the container's standard output. Defaults to `true`.
152    ///
153    /// Call [`AttachedProcess::stdout`](https://docs.rs/kube/*/kube/api/struct.AttachedProcess.html#method.stdout) to obtain a reader.
154    pub stdout: bool,
155    /// Attach to the container's standard error. Defaults to `true`.
156    ///
157    /// Call [`AttachedProcess::stderr`](https://docs.rs/kube/*/kube/api/struct.AttachedProcess.html#method.stderr) to obtain a reader.
158    pub stderr: bool,
159    /// Allocate TTY. Defaults to `false`.
160    ///
161    /// NOTE: Terminal resizing is not implemented yet.
162    pub tty: bool,
163
164    /// The maximum amount of bytes that can be written to the internal `stdin`
165    /// pipe before the write returns `Poll::Pending`.
166    /// Defaults to 1024.
167    ///
168    /// This is not sent to the server.
169    pub max_stdin_buf_size: Option<usize>,
170    /// The maximum amount of bytes that can be written to the internal `stdout`
171    /// pipe before the write returns `Poll::Pending`.
172    /// Defaults to 1024.
173    ///
174    /// This is not sent to the server.
175    pub max_stdout_buf_size: Option<usize>,
176    /// The maximum amount of bytes that can be written to the internal `stderr`
177    /// pipe before the write returns `Poll::Pending`.
178    /// Defaults to 1024.
179    ///
180    /// This is not sent to the server.
181    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    // Default matching the server's defaults.
188    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    /// Default parameters for an tty exec with stdin and stdout
206    #[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    /// Specify the container to execute in.
218    #[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    /// Set `stdin` field.
225    #[must_use]
226    pub fn stdin(mut self, enable: bool) -> Self {
227        self.stdin = enable;
228        self
229    }
230
231    /// Set `stdout` field.
232    #[must_use]
233    pub fn stdout(mut self, enable: bool) -> Self {
234        self.stdout = enable;
235        self
236    }
237
238    /// Set `stderr` field.
239    #[must_use]
240    pub fn stderr(mut self, enable: bool) -> Self {
241        self.stderr = enable;
242        self
243    }
244
245    /// Set `tty` field.
246    #[must_use]
247    pub fn tty(mut self, enable: bool) -> Self {
248        self.tty = enable;
249        self
250    }
251
252    /// Set `max_stdin_buf_size` field.
253    #[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    /// Set `max_stdout_buf_size` field.
260    #[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    /// Set `max_stderr_buf_size` field.
267    #[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            // Multiplexing is not supported with TTY
282            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    // https://github.com/kubernetes/kubernetes/blob/466d9378dbb0a185df9680657f5cd96d5e5aab57/pkg/apis/core/types.go#L6005-L6013
310    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    /// Attach to a pod
330    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// ----------------------------------------------------------------------------
343// Exec subresource
344// ----------------------------------------------------------------------------
345#[cfg(feature = "ws")]
346#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
347impl Request {
348    /// Execute command in a pod
349    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// ----------------------------------------------------------------------------
375// Portforward subresource
376// ----------------------------------------------------------------------------
377#[cfg(feature = "ws")]
378#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
379impl Request {
380    /// Request to forward ports of a pod
381    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// ----------------------------------------------------------------------------
416// tests
417// ----------------------------------------------------------------------------
418
419/// Cheap sanity check to ensure type maps work as expected
420#[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&timestamps=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" // cross-referenced with kubectl
486        );
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}