datadog_api_client/datadogV2/api/
api_processes.rs

1// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
2// This product includes software developed at Datadog (https://www.datadoghq.com/).
3// Copyright 2019-Present Datadog, Inc.
4use crate::datadog;
5use async_stream::try_stream;
6use futures_core::stream::Stream;
7use reqwest::header::{HeaderMap, HeaderValue};
8use serde::{Deserialize, Serialize};
9
10/// ListProcessesOptionalParams is a struct for passing parameters to the method [`ProcessesAPI::list_processes`]
11#[non_exhaustive]
12#[derive(Clone, Default, Debug)]
13pub struct ListProcessesOptionalParams {
14    /// String to search processes by.
15    pub search: Option<String>,
16    /// Comma-separated list of tags to filter processes by.
17    pub tags: Option<String>,
18    /// Unix timestamp (number of seconds since epoch) of the start of the query window.
19    /// If not provided, the start of the query window will be 15 minutes before the `to` timestamp. If neither
20    /// `from` nor `to` are provided, the query window will be `[now - 15m, now]`.
21    pub from: Option<i64>,
22    /// Unix timestamp (number of seconds since epoch) of the end of the query window.
23    /// If not provided, the end of the query window will be 15 minutes after the `from` timestamp. If neither
24    /// `from` nor `to` are provided, the query window will be `[now - 15m, now]`.
25    pub to: Option<i64>,
26    /// Maximum number of results returned.
27    pub page_limit: Option<i32>,
28    /// String to query the next page of results.
29    /// This key is provided with each valid response from the API in `meta.page.after`.
30    pub page_cursor: Option<String>,
31}
32
33impl ListProcessesOptionalParams {
34    /// String to search processes by.
35    pub fn search(mut self, value: String) -> Self {
36        self.search = Some(value);
37        self
38    }
39    /// Comma-separated list of tags to filter processes by.
40    pub fn tags(mut self, value: String) -> Self {
41        self.tags = Some(value);
42        self
43    }
44    /// Unix timestamp (number of seconds since epoch) of the start of the query window.
45    /// If not provided, the start of the query window will be 15 minutes before the `to` timestamp. If neither
46    /// `from` nor `to` are provided, the query window will be `[now - 15m, now]`.
47    pub fn from(mut self, value: i64) -> Self {
48        self.from = Some(value);
49        self
50    }
51    /// Unix timestamp (number of seconds since epoch) of the end of the query window.
52    /// If not provided, the end of the query window will be 15 minutes after the `from` timestamp. If neither
53    /// `from` nor `to` are provided, the query window will be `[now - 15m, now]`.
54    pub fn to(mut self, value: i64) -> Self {
55        self.to = Some(value);
56        self
57    }
58    /// Maximum number of results returned.
59    pub fn page_limit(mut self, value: i32) -> Self {
60        self.page_limit = Some(value);
61        self
62    }
63    /// String to query the next page of results.
64    /// This key is provided with each valid response from the API in `meta.page.after`.
65    pub fn page_cursor(mut self, value: String) -> Self {
66        self.page_cursor = Some(value);
67        self
68    }
69}
70
71/// ListProcessesError is a struct for typed errors of method [`ProcessesAPI::list_processes`]
72#[derive(Debug, Clone, Serialize, Deserialize)]
73#[serde(untagged)]
74pub enum ListProcessesError {
75    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
76    UnknownValue(serde_json::Value),
77}
78
79/// The processes API allows you to query processes data for your organization. See the [Live Processes page](<https://docs.datadoghq.com/infrastructure/process/>) for more information.
80#[derive(Debug, Clone)]
81pub struct ProcessesAPI {
82    config: datadog::Configuration,
83    client: reqwest_middleware::ClientWithMiddleware,
84}
85
86impl Default for ProcessesAPI {
87    fn default() -> Self {
88        Self::with_config(datadog::Configuration::default())
89    }
90}
91
92impl ProcessesAPI {
93    pub fn new() -> Self {
94        Self::default()
95    }
96    pub fn with_config(config: datadog::Configuration) -> Self {
97        let mut reqwest_client_builder = reqwest::Client::builder();
98
99        if let Some(proxy_url) = &config.proxy_url {
100            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
101            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
102        }
103
104        let mut middleware_client_builder =
105            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
106
107        if config.enable_retry {
108            struct RetryableStatus;
109            impl reqwest_retry::RetryableStrategy for RetryableStatus {
110                fn handle(
111                    &self,
112                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
113                ) -> Option<reqwest_retry::Retryable> {
114                    match res {
115                        Ok(success) => reqwest_retry::default_on_request_success(success),
116                        Err(_) => None,
117                    }
118                }
119            }
120            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
121                .build_with_max_retries(config.max_retries);
122
123            let retry_middleware =
124                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
125                    backoff_policy,
126                    RetryableStatus,
127                );
128
129            middleware_client_builder = middleware_client_builder.with(retry_middleware);
130        }
131
132        let client = middleware_client_builder.build();
133
134        Self { config, client }
135    }
136
137    pub fn with_client_and_config(
138        config: datadog::Configuration,
139        client: reqwest_middleware::ClientWithMiddleware,
140    ) -> Self {
141        Self { config, client }
142    }
143
144    /// Get all processes for your organization.
145    pub async fn list_processes(
146        &self,
147        params: ListProcessesOptionalParams,
148    ) -> Result<crate::datadogV2::model::ProcessSummariesResponse, datadog::Error<ListProcessesError>>
149    {
150        match self.list_processes_with_http_info(params).await {
151            Ok(response_content) => {
152                if let Some(e) = response_content.entity {
153                    Ok(e)
154                } else {
155                    Err(datadog::Error::Serde(serde::de::Error::custom(
156                        "response content was None",
157                    )))
158                }
159            }
160            Err(err) => Err(err),
161        }
162    }
163
164    pub fn list_processes_with_pagination(
165        &self,
166        mut params: ListProcessesOptionalParams,
167    ) -> impl Stream<
168        Item = Result<crate::datadogV2::model::ProcessSummary, datadog::Error<ListProcessesError>>,
169    > + '_ {
170        try_stream! {
171            let mut page_size: i32 = 1000;
172            if params.page_limit.is_none() {
173                params.page_limit = Some(page_size);
174            } else {
175                page_size = params.page_limit.unwrap().clone();
176            }
177            loop {
178                let resp = self.list_processes(params.clone()).await?;
179                let Some(data) = resp.data else { break };
180
181                let r = data;
182                let count = r.len();
183                for team in r {
184                    yield team;
185                }
186
187                if count < page_size as usize {
188                    break;
189                }
190                let Some(meta) = resp.meta else { break };
191                let Some(page) = meta.page else { break };
192                let Some(after) = page.after else { break };
193
194                params.page_cursor = Some(after);
195            }
196        }
197    }
198
199    /// Get all processes for your organization.
200    pub async fn list_processes_with_http_info(
201        &self,
202        params: ListProcessesOptionalParams,
203    ) -> Result<
204        datadog::ResponseContent<crate::datadogV2::model::ProcessSummariesResponse>,
205        datadog::Error<ListProcessesError>,
206    > {
207        let local_configuration = &self.config;
208        let operation_id = "v2.list_processes";
209
210        // unbox and build optional parameters
211        let search = params.search;
212        let tags = params.tags;
213        let from = params.from;
214        let to = params.to;
215        let page_limit = params.page_limit;
216        let page_cursor = params.page_cursor;
217
218        let local_client = &self.client;
219
220        let local_uri_str = format!(
221            "{}/api/v2/processes",
222            local_configuration.get_operation_host(operation_id)
223        );
224        let mut local_req_builder =
225            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
226
227        if let Some(ref local_query_param) = search {
228            local_req_builder =
229                local_req_builder.query(&[("search", &local_query_param.to_string())]);
230        };
231        if let Some(ref local_query_param) = tags {
232            local_req_builder =
233                local_req_builder.query(&[("tags", &local_query_param.to_string())]);
234        };
235        if let Some(ref local_query_param) = from {
236            local_req_builder =
237                local_req_builder.query(&[("from", &local_query_param.to_string())]);
238        };
239        if let Some(ref local_query_param) = to {
240            local_req_builder = local_req_builder.query(&[("to", &local_query_param.to_string())]);
241        };
242        if let Some(ref local_query_param) = page_limit {
243            local_req_builder =
244                local_req_builder.query(&[("page[limit]", &local_query_param.to_string())]);
245        };
246        if let Some(ref local_query_param) = page_cursor {
247            local_req_builder =
248                local_req_builder.query(&[("page[cursor]", &local_query_param.to_string())]);
249        };
250
251        // build headers
252        let mut headers = HeaderMap::new();
253        headers.insert("Accept", HeaderValue::from_static("application/json"));
254
255        // build user agent
256        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
257            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
258            Err(e) => {
259                log::warn!("Failed to parse user agent header: {e}, falling back to default");
260                headers.insert(
261                    reqwest::header::USER_AGENT,
262                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
263                )
264            }
265        };
266
267        // build auth
268        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
269            headers.insert(
270                "DD-API-KEY",
271                HeaderValue::from_str(local_key.key.as_str())
272                    .expect("failed to parse DD-API-KEY header"),
273            );
274        };
275        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
276            headers.insert(
277                "DD-APPLICATION-KEY",
278                HeaderValue::from_str(local_key.key.as_str())
279                    .expect("failed to parse DD-APPLICATION-KEY header"),
280            );
281        };
282
283        local_req_builder = local_req_builder.headers(headers);
284        let local_req = local_req_builder.build()?;
285        log::debug!("request content: {:?}", local_req.body());
286        let local_resp = local_client.execute(local_req).await?;
287
288        let local_status = local_resp.status();
289        let local_content = local_resp.text().await?;
290        log::debug!("response content: {}", local_content);
291
292        if !local_status.is_client_error() && !local_status.is_server_error() {
293            match serde_json::from_str::<crate::datadogV2::model::ProcessSummariesResponse>(
294                &local_content,
295            ) {
296                Ok(e) => {
297                    return Ok(datadog::ResponseContent {
298                        status: local_status,
299                        content: local_content,
300                        entity: Some(e),
301                    })
302                }
303                Err(e) => return Err(datadog::Error::Serde(e)),
304            };
305        } else {
306            let local_entity: Option<ListProcessesError> =
307                serde_json::from_str(&local_content).ok();
308            let local_error = datadog::ResponseContent {
309                status: local_status,
310                content: local_content,
311                entity: local_entity,
312            };
313            Err(datadog::Error::ResponseError(local_error))
314        }
315    }
316}