datadog_api_client/datadogV2/api/
api_containers.rs1use crate::datadog;
5use async_stream::try_stream;
6use futures_core::stream::Stream;
7use reqwest::header::{HeaderMap, HeaderValue};
8use serde::{Deserialize, Serialize};
9
10#[non_exhaustive]
12#[derive(Clone, Default, Debug)]
13pub struct ListContainersOptionalParams {
14 pub filter_tags: Option<String>,
16 pub group_by: Option<String>,
18 pub sort: Option<String>,
20 pub page_size: Option<i32>,
22 pub page_cursor: Option<String>,
25}
26
27impl ListContainersOptionalParams {
28 pub fn filter_tags(mut self, value: String) -> Self {
30 self.filter_tags = Some(value);
31 self
32 }
33 pub fn group_by(mut self, value: String) -> Self {
35 self.group_by = Some(value);
36 self
37 }
38 pub fn sort(mut self, value: String) -> Self {
40 self.sort = Some(value);
41 self
42 }
43 pub fn page_size(mut self, value: i32) -> Self {
45 self.page_size = Some(value);
46 self
47 }
48 pub fn page_cursor(mut self, value: String) -> Self {
51 self.page_cursor = Some(value);
52 self
53 }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
58#[serde(untagged)]
59pub enum ListContainersError {
60 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
61 UnknownValue(serde_json::Value),
62}
63
64#[derive(Debug, Clone)]
66pub struct ContainersAPI {
67 config: datadog::Configuration,
68 client: reqwest_middleware::ClientWithMiddleware,
69}
70
71impl Default for ContainersAPI {
72 fn default() -> Self {
73 Self::with_config(datadog::Configuration::default())
74 }
75}
76
77impl ContainersAPI {
78 pub fn new() -> Self {
79 Self::default()
80 }
81 pub fn with_config(config: datadog::Configuration) -> Self {
82 let mut reqwest_client_builder = reqwest::Client::builder();
83
84 if let Some(proxy_url) = &config.proxy_url {
85 let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
86 reqwest_client_builder = reqwest_client_builder.proxy(proxy);
87 }
88
89 let mut middleware_client_builder =
90 reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
91
92 if config.enable_retry {
93 struct RetryableStatus;
94 impl reqwest_retry::RetryableStrategy for RetryableStatus {
95 fn handle(
96 &self,
97 res: &Result<reqwest::Response, reqwest_middleware::Error>,
98 ) -> Option<reqwest_retry::Retryable> {
99 match res {
100 Ok(success) => reqwest_retry::default_on_request_success(success),
101 Err(_) => None,
102 }
103 }
104 }
105 let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
106 .build_with_max_retries(config.max_retries);
107
108 let retry_middleware =
109 reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
110 backoff_policy,
111 RetryableStatus,
112 );
113
114 middleware_client_builder = middleware_client_builder.with(retry_middleware);
115 }
116
117 let client = middleware_client_builder.build();
118
119 Self { config, client }
120 }
121
122 pub fn with_client_and_config(
123 config: datadog::Configuration,
124 client: reqwest_middleware::ClientWithMiddleware,
125 ) -> Self {
126 Self { config, client }
127 }
128
129 pub async fn list_containers(
131 &self,
132 params: ListContainersOptionalParams,
133 ) -> Result<crate::datadogV2::model::ContainersResponse, datadog::Error<ListContainersError>>
134 {
135 match self.list_containers_with_http_info(params).await {
136 Ok(response_content) => {
137 if let Some(e) = response_content.entity {
138 Ok(e)
139 } else {
140 Err(datadog::Error::Serde(serde::de::Error::custom(
141 "response content was None",
142 )))
143 }
144 }
145 Err(err) => Err(err),
146 }
147 }
148
149 pub fn list_containers_with_pagination(
150 &self,
151 mut params: ListContainersOptionalParams,
152 ) -> impl Stream<
153 Item = Result<crate::datadogV2::model::ContainerItem, datadog::Error<ListContainersError>>,
154 > + '_ {
155 try_stream! {
156 let mut page_size: i32 = 1000;
157 if params.page_size.is_none() {
158 params.page_size = Some(page_size);
159 } else {
160 page_size = params.page_size.unwrap().clone();
161 }
162 loop {
163 let resp = self.list_containers(params.clone()).await?;
164 let Some(data) = resp.data else { break };
165
166 let r = data;
167 let count = r.len();
168 for team in r {
169 yield team;
170 }
171
172 if count < page_size as usize {
173 break;
174 }
175 let Some(meta) = resp.meta else { break };
176 let Some(pagination) = meta.pagination else { break };
177 let Some(next_cursor) = pagination.next_cursor else { break };
178
179 params.page_cursor = Some(next_cursor);
180 }
181 }
182 }
183
184 pub async fn list_containers_with_http_info(
186 &self,
187 params: ListContainersOptionalParams,
188 ) -> Result<
189 datadog::ResponseContent<crate::datadogV2::model::ContainersResponse>,
190 datadog::Error<ListContainersError>,
191 > {
192 let local_configuration = &self.config;
193 let operation_id = "v2.list_containers";
194
195 let filter_tags = params.filter_tags;
197 let group_by = params.group_by;
198 let sort = params.sort;
199 let page_size = params.page_size;
200 let page_cursor = params.page_cursor;
201
202 let local_client = &self.client;
203
204 let local_uri_str = format!(
205 "{}/api/v2/containers",
206 local_configuration.get_operation_host(operation_id)
207 );
208 let mut local_req_builder =
209 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
210
211 if let Some(ref local_query_param) = filter_tags {
212 local_req_builder =
213 local_req_builder.query(&[("filter[tags]", &local_query_param.to_string())]);
214 };
215 if let Some(ref local_query_param) = group_by {
216 local_req_builder =
217 local_req_builder.query(&[("group_by", &local_query_param.to_string())]);
218 };
219 if let Some(ref local_query_param) = sort {
220 local_req_builder =
221 local_req_builder.query(&[("sort", &local_query_param.to_string())]);
222 };
223 if let Some(ref local_query_param) = page_size {
224 local_req_builder =
225 local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
226 };
227 if let Some(ref local_query_param) = page_cursor {
228 local_req_builder =
229 local_req_builder.query(&[("page[cursor]", &local_query_param.to_string())]);
230 };
231
232 let mut headers = HeaderMap::new();
234 headers.insert("Accept", HeaderValue::from_static("application/json"));
235
236 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
238 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
239 Err(e) => {
240 log::warn!("Failed to parse user agent header: {e}, falling back to default");
241 headers.insert(
242 reqwest::header::USER_AGENT,
243 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
244 )
245 }
246 };
247
248 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
250 headers.insert(
251 "DD-API-KEY",
252 HeaderValue::from_str(local_key.key.as_str())
253 .expect("failed to parse DD-API-KEY header"),
254 );
255 };
256 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
257 headers.insert(
258 "DD-APPLICATION-KEY",
259 HeaderValue::from_str(local_key.key.as_str())
260 .expect("failed to parse DD-APPLICATION-KEY header"),
261 );
262 };
263
264 local_req_builder = local_req_builder.headers(headers);
265 let local_req = local_req_builder.build()?;
266 log::debug!("request content: {:?}", local_req.body());
267 let local_resp = local_client.execute(local_req).await?;
268
269 let local_status = local_resp.status();
270 let local_content = local_resp.text().await?;
271 log::debug!("response content: {}", local_content);
272
273 if !local_status.is_client_error() && !local_status.is_server_error() {
274 match serde_json::from_str::<crate::datadogV2::model::ContainersResponse>(
275 &local_content,
276 ) {
277 Ok(e) => {
278 return Ok(datadog::ResponseContent {
279 status: local_status,
280 content: local_content,
281 entity: Some(e),
282 })
283 }
284 Err(e) => return Err(datadog::Error::Serde(e)),
285 };
286 } else {
287 let local_entity: Option<ListContainersError> =
288 serde_json::from_str(&local_content).ok();
289 let local_error = datadog::ResponseContent {
290 status: local_status,
291 content: local_content,
292 entity: local_entity,
293 };
294 Err(datadog::Error::ResponseError(local_error))
295 }
296 }
297}