datadog_api_client/datadogV1/api/api_monitors.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 flate2::{
7 write::{GzEncoder, ZlibEncoder},
8 Compression,
9};
10use futures_core::stream::Stream;
11use reqwest::header::{HeaderMap, HeaderValue};
12use serde::{Deserialize, Serialize};
13use std::io::Write;
14
15/// DeleteMonitorOptionalParams is a struct for passing parameters to the method [`MonitorsAPI::delete_monitor`]
16#[non_exhaustive]
17#[derive(Clone, Default, Debug)]
18pub struct DeleteMonitorOptionalParams {
19 /// Delete the monitor even if it's referenced by other resources (for example SLO, composite monitor).
20 pub force: Option<String>,
21}
22
23impl DeleteMonitorOptionalParams {
24 /// Delete the monitor even if it's referenced by other resources (for example SLO, composite monitor).
25 pub fn force(mut self, value: String) -> Self {
26 self.force = Some(value);
27 self
28 }
29}
30
31/// GetMonitorOptionalParams is a struct for passing parameters to the method [`MonitorsAPI::get_monitor`]
32#[non_exhaustive]
33#[derive(Clone, Default, Debug)]
34pub struct GetMonitorOptionalParams {
35 /// When specified, shows additional information about the group states. Choose one or more from `all`, `alert`, `warn`, and `no data`.
36 pub group_states: Option<String>,
37 /// If this argument is set to true, then the returned data includes all current active downtimes for the monitor.
38 pub with_downtimes: Option<bool>,
39}
40
41impl GetMonitorOptionalParams {
42 /// When specified, shows additional information about the group states. Choose one or more from `all`, `alert`, `warn`, and `no data`.
43 pub fn group_states(mut self, value: String) -> Self {
44 self.group_states = Some(value);
45 self
46 }
47 /// If this argument is set to true, then the returned data includes all current active downtimes for the monitor.
48 pub fn with_downtimes(mut self, value: bool) -> Self {
49 self.with_downtimes = Some(value);
50 self
51 }
52}
53
54/// ListMonitorsOptionalParams is a struct for passing parameters to the method [`MonitorsAPI::list_monitors`]
55#[non_exhaustive]
56#[derive(Clone, Default, Debug)]
57pub struct ListMonitorsOptionalParams {
58 /// When specified, shows additional information about the group states.
59 /// Choose one or more from `all`, `alert`, `warn`, and `no data`.
60 pub group_states: Option<String>,
61 /// A string to filter monitors by name.
62 pub name: Option<String>,
63 /// A comma separated list indicating what tags, if any, should be used to filter the list of monitors by scope.
64 /// For example, `host:host0`.
65 pub tags: Option<String>,
66 /// A comma separated list indicating what service and/or custom tags, if any, should be used to filter the list of monitors.
67 /// Tags created in the Datadog UI automatically have the service key prepended. For example, `service:my-app`.
68 pub monitor_tags: Option<String>,
69 /// If this argument is set to true, then the returned data includes all current active downtimes for each monitor.
70 pub with_downtimes: Option<bool>,
71 /// Use this parameter for paginating through large sets of monitors. Start with a value of zero, make a request, set the value to the last ID of result set, and then repeat until the response is empty.
72 pub id_offset: Option<i64>,
73 /// The page to start paginating from. If this argument is not specified, the request returns all monitors without pagination.
74 pub page: Option<i64>,
75 /// The number of monitors to return per page. If the page argument is not specified, the default behavior returns all monitors without a `page_size` limit. However, if page is specified and `page_size` is not, the argument defaults to 100.
76 pub page_size: Option<i32>,
77}
78
79impl ListMonitorsOptionalParams {
80 /// When specified, shows additional information about the group states.
81 /// Choose one or more from `all`, `alert`, `warn`, and `no data`.
82 pub fn group_states(mut self, value: String) -> Self {
83 self.group_states = Some(value);
84 self
85 }
86 /// A string to filter monitors by name.
87 pub fn name(mut self, value: String) -> Self {
88 self.name = Some(value);
89 self
90 }
91 /// A comma separated list indicating what tags, if any, should be used to filter the list of monitors by scope.
92 /// For example, `host:host0`.
93 pub fn tags(mut self, value: String) -> Self {
94 self.tags = Some(value);
95 self
96 }
97 /// A comma separated list indicating what service and/or custom tags, if any, should be used to filter the list of monitors.
98 /// Tags created in the Datadog UI automatically have the service key prepended. For example, `service:my-app`.
99 pub fn monitor_tags(mut self, value: String) -> Self {
100 self.monitor_tags = Some(value);
101 self
102 }
103 /// If this argument is set to true, then the returned data includes all current active downtimes for each monitor.
104 pub fn with_downtimes(mut self, value: bool) -> Self {
105 self.with_downtimes = Some(value);
106 self
107 }
108 /// Use this parameter for paginating through large sets of monitors. Start with a value of zero, make a request, set the value to the last ID of result set, and then repeat until the response is empty.
109 pub fn id_offset(mut self, value: i64) -> Self {
110 self.id_offset = Some(value);
111 self
112 }
113 /// The page to start paginating from. If this argument is not specified, the request returns all monitors without pagination.
114 pub fn page(mut self, value: i64) -> Self {
115 self.page = Some(value);
116 self
117 }
118 /// The number of monitors to return per page. If the page argument is not specified, the default behavior returns all monitors without a `page_size` limit. However, if page is specified and `page_size` is not, the argument defaults to 100.
119 pub fn page_size(mut self, value: i32) -> Self {
120 self.page_size = Some(value);
121 self
122 }
123}
124
125/// SearchMonitorGroupsOptionalParams is a struct for passing parameters to the method [`MonitorsAPI::search_monitor_groups`]
126#[non_exhaustive]
127#[derive(Clone, Default, Debug)]
128pub struct SearchMonitorGroupsOptionalParams {
129 /// After entering a search query on the [Triggered Monitors page][1], use the query parameter value in the
130 /// URL of the page as a value for this parameter. For more information, see the [Manage Monitors documentation][2].
131 ///
132 /// The query can contain any number of space-separated monitor attributes, for instance: `query="type:metric group_status:alert"`.
133 ///
134 /// [1]: <https://app.datadoghq.com/monitors/triggered>
135 /// [2]: /monitors/manage/#triggered-monitors
136 pub query: Option<String>,
137 /// Page to start paginating from.
138 pub page: Option<i64>,
139 /// Number of monitors to return per page.
140 pub per_page: Option<i64>,
141 /// String for sort order, composed of field and sort order separate by a comma, for example `name,asc`. Supported sort directions: `asc`, `desc`. Supported fields:
142 ///
143 /// * `name`
144 /// * `status`
145 /// * `tags`
146 pub sort: Option<String>,
147}
148
149impl SearchMonitorGroupsOptionalParams {
150 /// After entering a search query on the [Triggered Monitors page][1], use the query parameter value in the
151 /// URL of the page as a value for this parameter. For more information, see the [Manage Monitors documentation][2].
152 ///
153 /// The query can contain any number of space-separated monitor attributes, for instance: `query="type:metric group_status:alert"`.
154 ///
155 /// [1]: <https://app.datadoghq.com/monitors/triggered>
156 /// [2]: /monitors/manage/#triggered-monitors
157 pub fn query(mut self, value: String) -> Self {
158 self.query = Some(value);
159 self
160 }
161 /// Page to start paginating from.
162 pub fn page(mut self, value: i64) -> Self {
163 self.page = Some(value);
164 self
165 }
166 /// Number of monitors to return per page.
167 pub fn per_page(mut self, value: i64) -> Self {
168 self.per_page = Some(value);
169 self
170 }
171 /// String for sort order, composed of field and sort order separate by a comma, for example `name,asc`. Supported sort directions: `asc`, `desc`. Supported fields:
172 ///
173 /// * `name`
174 /// * `status`
175 /// * `tags`
176 pub fn sort(mut self, value: String) -> Self {
177 self.sort = Some(value);
178 self
179 }
180}
181
182/// SearchMonitorsOptionalParams is a struct for passing parameters to the method [`MonitorsAPI::search_monitors`]
183#[non_exhaustive]
184#[derive(Clone, Default, Debug)]
185pub struct SearchMonitorsOptionalParams {
186 /// After entering a search query in your [Manage Monitor page][1] use the query parameter value in the
187 /// URL of the page as value for this parameter. Consult the dedicated [manage monitor documentation][2]
188 /// page to learn more.
189 ///
190 /// The query can contain any number of space-separated monitor attributes, for instance `query="type:metric status:alert"`.
191 ///
192 /// [1]: <https://app.datadoghq.com/monitors/manage>
193 /// [2]: /monitors/manage/#find-the-monitors
194 pub query: Option<String>,
195 /// Page to start paginating from.
196 pub page: Option<i64>,
197 /// Number of monitors to return per page.
198 pub per_page: Option<i64>,
199 /// String for sort order, composed of field and sort order separate by a comma, for example `name,asc`. Supported sort directions: `asc`, `desc`. Supported fields:
200 ///
201 /// * `name`
202 /// * `status`
203 /// * `tags`
204 pub sort: Option<String>,
205}
206
207impl SearchMonitorsOptionalParams {
208 /// After entering a search query in your [Manage Monitor page][1] use the query parameter value in the
209 /// URL of the page as value for this parameter. Consult the dedicated [manage monitor documentation][2]
210 /// page to learn more.
211 ///
212 /// The query can contain any number of space-separated monitor attributes, for instance `query="type:metric status:alert"`.
213 ///
214 /// [1]: <https://app.datadoghq.com/monitors/manage>
215 /// [2]: /monitors/manage/#find-the-monitors
216 pub fn query(mut self, value: String) -> Self {
217 self.query = Some(value);
218 self
219 }
220 /// Page to start paginating from.
221 pub fn page(mut self, value: i64) -> Self {
222 self.page = Some(value);
223 self
224 }
225 /// Number of monitors to return per page.
226 pub fn per_page(mut self, value: i64) -> Self {
227 self.per_page = Some(value);
228 self
229 }
230 /// String for sort order, composed of field and sort order separate by a comma, for example `name,asc`. Supported sort directions: `asc`, `desc`. Supported fields:
231 ///
232 /// * `name`
233 /// * `status`
234 /// * `tags`
235 pub fn sort(mut self, value: String) -> Self {
236 self.sort = Some(value);
237 self
238 }
239}
240
241/// CheckCanDeleteMonitorError is a struct for typed errors of method [`MonitorsAPI::check_can_delete_monitor`]
242#[derive(Debug, Clone, Serialize, Deserialize)]
243#[serde(untagged)]
244pub enum CheckCanDeleteMonitorError {
245 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
246 CheckCanDeleteMonitorResponse(crate::datadogV1::model::CheckCanDeleteMonitorResponse),
247 UnknownValue(serde_json::Value),
248}
249
250/// CreateMonitorError is a struct for typed errors of method [`MonitorsAPI::create_monitor`]
251#[derive(Debug, Clone, Serialize, Deserialize)]
252#[serde(untagged)]
253pub enum CreateMonitorError {
254 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
255 UnknownValue(serde_json::Value),
256}
257
258/// DeleteMonitorError is a struct for typed errors of method [`MonitorsAPI::delete_monitor`]
259#[derive(Debug, Clone, Serialize, Deserialize)]
260#[serde(untagged)]
261pub enum DeleteMonitorError {
262 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
263 UnknownValue(serde_json::Value),
264}
265
266/// GetMonitorError is a struct for typed errors of method [`MonitorsAPI::get_monitor`]
267#[derive(Debug, Clone, Serialize, Deserialize)]
268#[serde(untagged)]
269pub enum GetMonitorError {
270 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
271 UnknownValue(serde_json::Value),
272}
273
274/// ListMonitorsError is a struct for typed errors of method [`MonitorsAPI::list_monitors`]
275#[derive(Debug, Clone, Serialize, Deserialize)]
276#[serde(untagged)]
277pub enum ListMonitorsError {
278 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
279 UnknownValue(serde_json::Value),
280}
281
282/// SearchMonitorGroupsError is a struct for typed errors of method [`MonitorsAPI::search_monitor_groups`]
283#[derive(Debug, Clone, Serialize, Deserialize)]
284#[serde(untagged)]
285pub enum SearchMonitorGroupsError {
286 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
287 UnknownValue(serde_json::Value),
288}
289
290/// SearchMonitorsError is a struct for typed errors of method [`MonitorsAPI::search_monitors`]
291#[derive(Debug, Clone, Serialize, Deserialize)]
292#[serde(untagged)]
293pub enum SearchMonitorsError {
294 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
295 UnknownValue(serde_json::Value),
296}
297
298/// UpdateMonitorError is a struct for typed errors of method [`MonitorsAPI::update_monitor`]
299#[derive(Debug, Clone, Serialize, Deserialize)]
300#[serde(untagged)]
301pub enum UpdateMonitorError {
302 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
303 UnknownValue(serde_json::Value),
304}
305
306/// ValidateExistingMonitorError is a struct for typed errors of method [`MonitorsAPI::validate_existing_monitor`]
307#[derive(Debug, Clone, Serialize, Deserialize)]
308#[serde(untagged)]
309pub enum ValidateExistingMonitorError {
310 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
311 UnknownValue(serde_json::Value),
312}
313
314/// ValidateMonitorError is a struct for typed errors of method [`MonitorsAPI::validate_monitor`]
315#[derive(Debug, Clone, Serialize, Deserialize)]
316#[serde(untagged)]
317pub enum ValidateMonitorError {
318 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
319 UnknownValue(serde_json::Value),
320}
321
322/// [Monitors](<https://docs.datadoghq.com/monitors>) allow you to watch a metric or check that you care about and
323/// notifies your team when a defined threshold has exceeded.
324///
325/// For more information, see [Creating Monitors](<https://docs.datadoghq.com/monitors/create/types/>).
326///
327/// **Note:** `curl` commands require [url encoding](<https://curl.se/docs/url-syntax.html>).
328#[derive(Debug, Clone)]
329pub struct MonitorsAPI {
330 config: datadog::Configuration,
331 client: reqwest_middleware::ClientWithMiddleware,
332}
333
334impl Default for MonitorsAPI {
335 fn default() -> Self {
336 Self::with_config(datadog::Configuration::default())
337 }
338}
339
340impl MonitorsAPI {
341 pub fn new() -> Self {
342 Self::default()
343 }
344 pub fn with_config(config: datadog::Configuration) -> Self {
345 let mut reqwest_client_builder = reqwest::Client::builder();
346
347 if let Some(proxy_url) = &config.proxy_url {
348 let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
349 reqwest_client_builder = reqwest_client_builder.proxy(proxy);
350 }
351
352 let mut middleware_client_builder =
353 reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
354
355 if config.enable_retry {
356 struct RetryableStatus;
357 impl reqwest_retry::RetryableStrategy for RetryableStatus {
358 fn handle(
359 &self,
360 res: &Result<reqwest::Response, reqwest_middleware::Error>,
361 ) -> Option<reqwest_retry::Retryable> {
362 match res {
363 Ok(success) => reqwest_retry::default_on_request_success(success),
364 Err(_) => None,
365 }
366 }
367 }
368 let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
369 .build_with_max_retries(config.max_retries);
370
371 let retry_middleware =
372 reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
373 backoff_policy,
374 RetryableStatus,
375 );
376
377 middleware_client_builder = middleware_client_builder.with(retry_middleware);
378 }
379
380 let client = middleware_client_builder.build();
381
382 Self { config, client }
383 }
384
385 pub fn with_client_and_config(
386 config: datadog::Configuration,
387 client: reqwest_middleware::ClientWithMiddleware,
388 ) -> Self {
389 Self { config, client }
390 }
391
392 /// Check if the given monitors can be deleted.
393 pub async fn check_can_delete_monitor(
394 &self,
395 monitor_ids: Vec<i64>,
396 ) -> Result<
397 crate::datadogV1::model::CheckCanDeleteMonitorResponse,
398 datadog::Error<CheckCanDeleteMonitorError>,
399 > {
400 match self
401 .check_can_delete_monitor_with_http_info(monitor_ids)
402 .await
403 {
404 Ok(response_content) => {
405 if let Some(e) = response_content.entity {
406 Ok(e)
407 } else {
408 Err(datadog::Error::Serde(serde::de::Error::custom(
409 "response content was None",
410 )))
411 }
412 }
413 Err(err) => Err(err),
414 }
415 }
416
417 /// Check if the given monitors can be deleted.
418 pub async fn check_can_delete_monitor_with_http_info(
419 &self,
420 monitor_ids: Vec<i64>,
421 ) -> Result<
422 datadog::ResponseContent<crate::datadogV1::model::CheckCanDeleteMonitorResponse>,
423 datadog::Error<CheckCanDeleteMonitorError>,
424 > {
425 let local_configuration = &self.config;
426 let operation_id = "v1.check_can_delete_monitor";
427
428 let local_client = &self.client;
429
430 let local_uri_str = format!(
431 "{}/api/v1/monitor/can_delete",
432 local_configuration.get_operation_host(operation_id)
433 );
434 let mut local_req_builder =
435 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
436
437 local_req_builder = local_req_builder.query(&[(
438 "monitor_ids",
439 &monitor_ids
440 .iter()
441 .map(|p| p.to_string())
442 .collect::<Vec<String>>()
443 .join(",")
444 .to_string(),
445 )]);
446
447 // build headers
448 let mut headers = HeaderMap::new();
449 headers.insert("Accept", HeaderValue::from_static("application/json"));
450
451 // build user agent
452 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
453 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
454 Err(e) => {
455 log::warn!("Failed to parse user agent header: {e}, falling back to default");
456 headers.insert(
457 reqwest::header::USER_AGENT,
458 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
459 )
460 }
461 };
462
463 // build auth
464 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
465 headers.insert(
466 "DD-API-KEY",
467 HeaderValue::from_str(local_key.key.as_str())
468 .expect("failed to parse DD-API-KEY header"),
469 );
470 };
471 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
472 headers.insert(
473 "DD-APPLICATION-KEY",
474 HeaderValue::from_str(local_key.key.as_str())
475 .expect("failed to parse DD-APPLICATION-KEY header"),
476 );
477 };
478
479 local_req_builder = local_req_builder.headers(headers);
480 let local_req = local_req_builder.build()?;
481 log::debug!("request content: {:?}", local_req.body());
482 let local_resp = local_client.execute(local_req).await?;
483
484 let local_status = local_resp.status();
485 let local_content = local_resp.text().await?;
486 log::debug!("response content: {}", local_content);
487
488 if !local_status.is_client_error() && !local_status.is_server_error() {
489 match serde_json::from_str::<crate::datadogV1::model::CheckCanDeleteMonitorResponse>(
490 &local_content,
491 ) {
492 Ok(e) => {
493 return Ok(datadog::ResponseContent {
494 status: local_status,
495 content: local_content,
496 entity: Some(e),
497 })
498 }
499 Err(e) => return Err(datadog::Error::Serde(e)),
500 };
501 } else {
502 let local_entity: Option<CheckCanDeleteMonitorError> =
503 serde_json::from_str(&local_content).ok();
504 let local_error = datadog::ResponseContent {
505 status: local_status,
506 content: local_content,
507 entity: local_entity,
508 };
509 Err(datadog::Error::ResponseError(local_error))
510 }
511 }
512
513 /// Create a monitor using the specified options.
514 ///
515 /// #### Monitor Types
516 ///
517 /// The type of monitor chosen from:
518 ///
519 /// - anomaly: `query alert`
520 /// - APM: `query alert` or `trace-analytics alert`
521 /// - composite: `composite`
522 /// - custom: `service check`
523 /// - forecast: `query alert`
524 /// - host: `service check`
525 /// - integration: `query alert` or `service check`
526 /// - live process: `process alert`
527 /// - logs: `log alert`
528 /// - metric: `query alert`
529 /// - network: `service check`
530 /// - outlier: `query alert`
531 /// - process: `service check`
532 /// - rum: `rum alert`
533 /// - SLO: `slo alert`
534 /// - watchdog: `event-v2 alert`
535 /// - event-v2: `event-v2 alert`
536 /// - audit: `audit alert`
537 /// - error-tracking: `error-tracking alert`
538 /// - database-monitoring: `database-monitoring alert`
539 /// - network-performance: `network-performance alert`
540 /// - cloud cost: `cost alert`
541 ///
542 /// **Notes**:
543 /// - Synthetic monitors are created through the Synthetics API. See the [Synthetics API](<https://docs.datadoghq.com/api/latest/synthetics/>) documentation for more information.
544 /// - Log monitors require an unscoped App Key.
545 ///
546 /// #### Query Types
547 ///
548 /// ##### Metric Alert Query
549 ///
550 /// Example: `time_aggr(time_window):space_aggr:metric{tags} [by {key}] operator #`
551 ///
552 /// - `time_aggr`: avg, sum, max, min, change, or pct_change
553 /// - `time_window`: `last_#m` (with `#` between 1 and 10080 depending on the monitor type) or `last_#h`(with `#` between 1 and 168 depending on the monitor type) or `last_1d`, or `last_1w`
554 /// - `space_aggr`: avg, sum, min, or max
555 /// - `tags`: one or more tags (comma-separated), or *
556 /// - `key`: a 'key' in key:value tag syntax; defines a separate alert for each tag in the group (multi-alert)
557 /// - `operator`: <, <=, >, >=, ==, or !=
558 /// - `#`: an integer or decimal number used to set the threshold
559 ///
560 /// If you are using the `_change_` or `_pct_change_` time aggregator, instead use `change_aggr(time_aggr(time_window),
561 /// timeshift):space_aggr:metric{tags} [by {key}] operator #` with:
562 ///
563 /// - `change_aggr` change, pct_change
564 /// - `time_aggr` avg, sum, max, min [Learn more](<https://docs.datadoghq.com/monitors/create/types/#define-the-conditions>)
565 /// - `time_window` last\_#m (between 1 and 2880 depending on the monitor type), last\_#h (between 1 and 48 depending on the monitor type), or last_#d (1 or 2)
566 /// - `timeshift` #m_ago (5, 10, 15, or 30), #h_ago (1, 2, or 4), or 1d_ago
567 ///
568 /// Use this to create an outlier monitor using the following query:
569 /// `avg(last_30m):outliers(avg:system.cpu.user{role:es-events-data} by {host}, 'dbscan', 7) > 0`
570 ///
571 /// ##### Service Check Query
572 ///
573 /// Example: `"check".over(tags).last(count).by(group).count_by_status()`
574 ///
575 /// - `check` name of the check, for example `datadog.agent.up`
576 /// - `tags` one or more quoted tags (comma-separated), or "*". for example: `.over("env:prod", "role:db")`; `over` cannot be blank.
577 /// - `count` must be at greater than or equal to your max threshold (defined in the `options`). It is limited to 100.
578 /// For example, if you've specified to notify on 1 critical, 3 ok, and 2 warn statuses, `count` should be at least 3.
579 /// - `group` must be specified for check monitors. Per-check grouping is already explicitly known for some service checks.
580 /// For example, Postgres integration monitors are tagged by `db`, `host`, and `port`, and Network monitors by `host`, `instance`, and `url`. See [Service Checks](<https://docs.datadoghq.com/api/latest/service-checks/>) documentation for more information.
581 ///
582 /// ##### Event Alert Query
583 ///
584 /// **Note:** The Event Alert Query has been replaced by the Event V2 Alert Query. For more information, see the [Event Migration guide](<https://docs.datadoghq.com/service_management/events/guides/migrating_to_new_events_features/>).
585 ///
586 /// ##### Event V2 Alert Query
587 ///
588 /// Example: `events(query).rollup(rollup_method[, measure]).last(time_window) operator #`
589 ///
590 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
591 /// - `rollup_method` The stats roll-up method - supports `count`, `avg` and `cardinality`.
592 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
593 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
594 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
595 /// - `#` an integer or decimal number used to set the threshold.
596 ///
597 /// ##### Process Alert Query
598 ///
599 /// Example: `processes(search).over(tags).rollup('count').last(timeframe) operator #`
600 ///
601 /// - `search` free text search string for querying processes.
602 /// Matching processes match results on the [Live Processes](<https://docs.datadoghq.com/infrastructure/process/?tab=linuxwindows>) page.
603 /// - `tags` one or more tags (comma-separated)
604 /// - `timeframe` the timeframe to roll up the counts. Examples: 10m, 4h. Supported timeframes: s, m, h and d
605 /// - `operator` <, <=, >, >=, ==, or !=
606 /// - `#` an integer or decimal number used to set the threshold
607 ///
608 /// ##### Logs Alert Query
609 ///
610 /// Example: `logs(query).index(index_name).rollup(rollup_method[, measure]).last(time_window) operator #`
611 ///
612 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
613 /// - `index_name` For multi-index organizations, the log index in which the request is performed.
614 /// - `rollup_method` The stats roll-up method - supports `count`, `avg` and `cardinality`.
615 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
616 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
617 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
618 /// - `#` an integer or decimal number used to set the threshold.
619 ///
620 /// ##### Composite Query
621 ///
622 /// Example: `12345 && 67890`, where `12345` and `67890` are the IDs of non-composite monitors
623 ///
624 /// * `name` [*required*, *default* = **dynamic, based on query**]: The name of the alert.
625 /// * `message` [*required*, *default* = **dynamic, based on query**]: A message to include with notifications for this monitor.
626 /// Email notifications can be sent to specific users by using the same '@username' notation as events.
627 /// * `tags` [*optional*, *default* = **empty list**]: A list of tags to associate with your monitor.
628 /// When getting all monitor details via the API, use the `monitor_tags` argument to filter results by these tags.
629 /// It is only available via the API and isn't visible or editable in the Datadog UI.
630 ///
631 /// ##### SLO Alert Query
632 ///
633 /// Example: `error_budget("slo_id").over("time_window") operator #`
634 ///
635 /// - `slo_id`: The alphanumeric SLO ID of the SLO you are configuring the alert for.
636 /// - `time_window`: The time window of the SLO target you wish to alert on. Valid options: `7d`, `30d`, `90d`.
637 /// - `operator`: `>=` or `>`
638 ///
639 /// ##### Audit Alert Query
640 ///
641 /// Example: `audits(query).rollup(rollup_method[, measure]).last(time_window) operator #`
642 ///
643 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
644 /// - `rollup_method` The stats roll-up method - supports `count`, `avg` and `cardinality`.
645 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
646 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
647 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
648 /// - `#` an integer or decimal number used to set the threshold.
649 ///
650 /// ##### CI Pipelines Alert Query
651 ///
652 /// Example: `ci-pipelines(query).rollup(rollup_method[, measure]).last(time_window) operator #`
653 ///
654 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
655 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
656 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
657 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
658 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
659 /// - `#` an integer or decimal number used to set the threshold.
660 ///
661 /// ##### CI Tests Alert Query
662 ///
663 /// Example: `ci-tests(query).rollup(rollup_method[, measure]).last(time_window) operator #`
664 ///
665 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
666 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
667 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
668 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
669 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
670 /// - `#` an integer or decimal number used to set the threshold.
671 ///
672 /// ##### Error Tracking Alert Query
673 ///
674 /// "New issue" example: `error-tracking(query).source(issue_source).new().rollup(rollup_method[, measure]).by(group_by).last(time_window) operator #`
675 /// "High impact issue" example: `error-tracking(query).source(issue_source).impact().rollup(rollup_method[, measure]).by(group_by).last(time_window) operator #`
676 ///
677 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
678 /// - `issue_source` The issue source - supports `all`, `browser`, `mobile` and `backend` and defaults to `all` if omitted.
679 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality` and defaults to `count` if omitted.
680 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
681 /// - `group by` Comma-separated list of attributes to group by - should contain at least `issue.id`.
682 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
683 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
684 /// - `#` an integer or decimal number used to set the threshold.
685 ///
686 /// **Database Monitoring Alert Query**
687 ///
688 /// Example: `database-monitoring(query).rollup(rollup_method[, measure]).last(time_window) operator #`
689 ///
690 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
691 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
692 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
693 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
694 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
695 /// - `#` an integer or decimal number used to set the threshold.
696 ///
697 /// **Network Performance Alert Query**
698 ///
699 /// Example: `network-performance(query).rollup(rollup_method[, measure]).last(time_window) operator #`
700 ///
701 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
702 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
703 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
704 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
705 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
706 /// - `#` an integer or decimal number used to set the threshold.
707 ///
708 /// **Cost Alert Query**
709 ///
710 /// Example: `formula(query).timeframe_type(time_window).function(parameter) operator #`
711 ///
712 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
713 /// - `timeframe_type` The timeframe type to evaluate the cost
714 /// - for `forecast` supports `current`
715 /// - for `change`, `anomaly`, `threshold` supports `last`
716 /// - `time_window` - supports daily roll-up e.g. `7d`
717 /// - `function` - [optional, defaults to `threshold` monitor if omitted] supports `change`, `anomaly`, `forecast`
718 /// - `parameter` Specify the parameter of the type
719 /// - for `change`:
720 /// - supports `relative`, `absolute`
721 /// - [optional] supports `#`, where `#` is an integer or decimal number used to set the threshold
722 /// - for `anomaly`:
723 /// - supports `direction=both`, `direction=above`, `direction=below`
724 /// - [optional] supports `threshold=#`, where `#` is an integer or decimal number used to set the threshold
725 /// - `operator`
726 /// - for `threshold` supports `<`, `<=`, `>`, `>=`, `==`, or `!=`
727 /// - for `change` supports `>`, `<`
728 /// - for `anomaly` supports `>=`
729 /// - for `forecast` supports `>`
730 /// - `#` an integer or decimal number used to set the threshold.
731 pub async fn create_monitor(
732 &self,
733 body: crate::datadogV1::model::Monitor,
734 ) -> Result<crate::datadogV1::model::Monitor, datadog::Error<CreateMonitorError>> {
735 match self.create_monitor_with_http_info(body).await {
736 Ok(response_content) => {
737 if let Some(e) = response_content.entity {
738 Ok(e)
739 } else {
740 Err(datadog::Error::Serde(serde::de::Error::custom(
741 "response content was None",
742 )))
743 }
744 }
745 Err(err) => Err(err),
746 }
747 }
748
749 /// Create a monitor using the specified options.
750 ///
751 /// #### Monitor Types
752 ///
753 /// The type of monitor chosen from:
754 ///
755 /// - anomaly: `query alert`
756 /// - APM: `query alert` or `trace-analytics alert`
757 /// - composite: `composite`
758 /// - custom: `service check`
759 /// - forecast: `query alert`
760 /// - host: `service check`
761 /// - integration: `query alert` or `service check`
762 /// - live process: `process alert`
763 /// - logs: `log alert`
764 /// - metric: `query alert`
765 /// - network: `service check`
766 /// - outlier: `query alert`
767 /// - process: `service check`
768 /// - rum: `rum alert`
769 /// - SLO: `slo alert`
770 /// - watchdog: `event-v2 alert`
771 /// - event-v2: `event-v2 alert`
772 /// - audit: `audit alert`
773 /// - error-tracking: `error-tracking alert`
774 /// - database-monitoring: `database-monitoring alert`
775 /// - network-performance: `network-performance alert`
776 /// - cloud cost: `cost alert`
777 ///
778 /// **Notes**:
779 /// - Synthetic monitors are created through the Synthetics API. See the [Synthetics API](<https://docs.datadoghq.com/api/latest/synthetics/>) documentation for more information.
780 /// - Log monitors require an unscoped App Key.
781 ///
782 /// #### Query Types
783 ///
784 /// ##### Metric Alert Query
785 ///
786 /// Example: `time_aggr(time_window):space_aggr:metric{tags} [by {key}] operator #`
787 ///
788 /// - `time_aggr`: avg, sum, max, min, change, or pct_change
789 /// - `time_window`: `last_#m` (with `#` between 1 and 10080 depending on the monitor type) or `last_#h`(with `#` between 1 and 168 depending on the monitor type) or `last_1d`, or `last_1w`
790 /// - `space_aggr`: avg, sum, min, or max
791 /// - `tags`: one or more tags (comma-separated), or *
792 /// - `key`: a 'key' in key:value tag syntax; defines a separate alert for each tag in the group (multi-alert)
793 /// - `operator`: <, <=, >, >=, ==, or !=
794 /// - `#`: an integer or decimal number used to set the threshold
795 ///
796 /// If you are using the `_change_` or `_pct_change_` time aggregator, instead use `change_aggr(time_aggr(time_window),
797 /// timeshift):space_aggr:metric{tags} [by {key}] operator #` with:
798 ///
799 /// - `change_aggr` change, pct_change
800 /// - `time_aggr` avg, sum, max, min [Learn more](<https://docs.datadoghq.com/monitors/create/types/#define-the-conditions>)
801 /// - `time_window` last\_#m (between 1 and 2880 depending on the monitor type), last\_#h (between 1 and 48 depending on the monitor type), or last_#d (1 or 2)
802 /// - `timeshift` #m_ago (5, 10, 15, or 30), #h_ago (1, 2, or 4), or 1d_ago
803 ///
804 /// Use this to create an outlier monitor using the following query:
805 /// `avg(last_30m):outliers(avg:system.cpu.user{role:es-events-data} by {host}, 'dbscan', 7) > 0`
806 ///
807 /// ##### Service Check Query
808 ///
809 /// Example: `"check".over(tags).last(count).by(group).count_by_status()`
810 ///
811 /// - `check` name of the check, for example `datadog.agent.up`
812 /// - `tags` one or more quoted tags (comma-separated), or "*". for example: `.over("env:prod", "role:db")`; `over` cannot be blank.
813 /// - `count` must be at greater than or equal to your max threshold (defined in the `options`). It is limited to 100.
814 /// For example, if you've specified to notify on 1 critical, 3 ok, and 2 warn statuses, `count` should be at least 3.
815 /// - `group` must be specified for check monitors. Per-check grouping is already explicitly known for some service checks.
816 /// For example, Postgres integration monitors are tagged by `db`, `host`, and `port`, and Network monitors by `host`, `instance`, and `url`. See [Service Checks](<https://docs.datadoghq.com/api/latest/service-checks/>) documentation for more information.
817 ///
818 /// ##### Event Alert Query
819 ///
820 /// **Note:** The Event Alert Query has been replaced by the Event V2 Alert Query. For more information, see the [Event Migration guide](<https://docs.datadoghq.com/service_management/events/guides/migrating_to_new_events_features/>).
821 ///
822 /// ##### Event V2 Alert Query
823 ///
824 /// Example: `events(query).rollup(rollup_method[, measure]).last(time_window) operator #`
825 ///
826 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
827 /// - `rollup_method` The stats roll-up method - supports `count`, `avg` and `cardinality`.
828 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
829 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
830 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
831 /// - `#` an integer or decimal number used to set the threshold.
832 ///
833 /// ##### Process Alert Query
834 ///
835 /// Example: `processes(search).over(tags).rollup('count').last(timeframe) operator #`
836 ///
837 /// - `search` free text search string for querying processes.
838 /// Matching processes match results on the [Live Processes](<https://docs.datadoghq.com/infrastructure/process/?tab=linuxwindows>) page.
839 /// - `tags` one or more tags (comma-separated)
840 /// - `timeframe` the timeframe to roll up the counts. Examples: 10m, 4h. Supported timeframes: s, m, h and d
841 /// - `operator` <, <=, >, >=, ==, or !=
842 /// - `#` an integer or decimal number used to set the threshold
843 ///
844 /// ##### Logs Alert Query
845 ///
846 /// Example: `logs(query).index(index_name).rollup(rollup_method[, measure]).last(time_window) operator #`
847 ///
848 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
849 /// - `index_name` For multi-index organizations, the log index in which the request is performed.
850 /// - `rollup_method` The stats roll-up method - supports `count`, `avg` and `cardinality`.
851 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
852 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
853 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
854 /// - `#` an integer or decimal number used to set the threshold.
855 ///
856 /// ##### Composite Query
857 ///
858 /// Example: `12345 && 67890`, where `12345` and `67890` are the IDs of non-composite monitors
859 ///
860 /// * `name` [*required*, *default* = **dynamic, based on query**]: The name of the alert.
861 /// * `message` [*required*, *default* = **dynamic, based on query**]: A message to include with notifications for this monitor.
862 /// Email notifications can be sent to specific users by using the same '@username' notation as events.
863 /// * `tags` [*optional*, *default* = **empty list**]: A list of tags to associate with your monitor.
864 /// When getting all monitor details via the API, use the `monitor_tags` argument to filter results by these tags.
865 /// It is only available via the API and isn't visible or editable in the Datadog UI.
866 ///
867 /// ##### SLO Alert Query
868 ///
869 /// Example: `error_budget("slo_id").over("time_window") operator #`
870 ///
871 /// - `slo_id`: The alphanumeric SLO ID of the SLO you are configuring the alert for.
872 /// - `time_window`: The time window of the SLO target you wish to alert on. Valid options: `7d`, `30d`, `90d`.
873 /// - `operator`: `>=` or `>`
874 ///
875 /// ##### Audit Alert Query
876 ///
877 /// Example: `audits(query).rollup(rollup_method[, measure]).last(time_window) operator #`
878 ///
879 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
880 /// - `rollup_method` The stats roll-up method - supports `count`, `avg` and `cardinality`.
881 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
882 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
883 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
884 /// - `#` an integer or decimal number used to set the threshold.
885 ///
886 /// ##### CI Pipelines Alert Query
887 ///
888 /// Example: `ci-pipelines(query).rollup(rollup_method[, measure]).last(time_window) operator #`
889 ///
890 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
891 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
892 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
893 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
894 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
895 /// - `#` an integer or decimal number used to set the threshold.
896 ///
897 /// ##### CI Tests Alert Query
898 ///
899 /// Example: `ci-tests(query).rollup(rollup_method[, measure]).last(time_window) operator #`
900 ///
901 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
902 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
903 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
904 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
905 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
906 /// - `#` an integer or decimal number used to set the threshold.
907 ///
908 /// ##### Error Tracking Alert Query
909 ///
910 /// "New issue" example: `error-tracking(query).source(issue_source).new().rollup(rollup_method[, measure]).by(group_by).last(time_window) operator #`
911 /// "High impact issue" example: `error-tracking(query).source(issue_source).impact().rollup(rollup_method[, measure]).by(group_by).last(time_window) operator #`
912 ///
913 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
914 /// - `issue_source` The issue source - supports `all`, `browser`, `mobile` and `backend` and defaults to `all` if omitted.
915 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality` and defaults to `count` if omitted.
916 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
917 /// - `group by` Comma-separated list of attributes to group by - should contain at least `issue.id`.
918 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
919 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
920 /// - `#` an integer or decimal number used to set the threshold.
921 ///
922 /// **Database Monitoring Alert Query**
923 ///
924 /// Example: `database-monitoring(query).rollup(rollup_method[, measure]).last(time_window) operator #`
925 ///
926 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
927 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
928 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
929 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
930 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
931 /// - `#` an integer or decimal number used to set the threshold.
932 ///
933 /// **Network Performance Alert Query**
934 ///
935 /// Example: `network-performance(query).rollup(rollup_method[, measure]).last(time_window) operator #`
936 ///
937 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
938 /// - `rollup_method` The stats roll-up method - supports `count`, `avg`, and `cardinality`.
939 /// - `measure` For `avg` and cardinality `rollup_method` - specify the measure or the facet name you want to use.
940 /// - `time_window` #m (between 1 and 2880), #h (between 1 and 48).
941 /// - `operator` `<`, `<=`, `>`, `>=`, `==`, or `!=`.
942 /// - `#` an integer or decimal number used to set the threshold.
943 ///
944 /// **Cost Alert Query**
945 ///
946 /// Example: `formula(query).timeframe_type(time_window).function(parameter) operator #`
947 ///
948 /// - `query` The search query - following the [Log search syntax](<https://docs.datadoghq.com/logs/search_syntax/>).
949 /// - `timeframe_type` The timeframe type to evaluate the cost
950 /// - for `forecast` supports `current`
951 /// - for `change`, `anomaly`, `threshold` supports `last`
952 /// - `time_window` - supports daily roll-up e.g. `7d`
953 /// - `function` - [optional, defaults to `threshold` monitor if omitted] supports `change`, `anomaly`, `forecast`
954 /// - `parameter` Specify the parameter of the type
955 /// - for `change`:
956 /// - supports `relative`, `absolute`
957 /// - [optional] supports `#`, where `#` is an integer or decimal number used to set the threshold
958 /// - for `anomaly`:
959 /// - supports `direction=both`, `direction=above`, `direction=below`
960 /// - [optional] supports `threshold=#`, where `#` is an integer or decimal number used to set the threshold
961 /// - `operator`
962 /// - for `threshold` supports `<`, `<=`, `>`, `>=`, `==`, or `!=`
963 /// - for `change` supports `>`, `<`
964 /// - for `anomaly` supports `>=`
965 /// - for `forecast` supports `>`
966 /// - `#` an integer or decimal number used to set the threshold.
967 pub async fn create_monitor_with_http_info(
968 &self,
969 body: crate::datadogV1::model::Monitor,
970 ) -> Result<
971 datadog::ResponseContent<crate::datadogV1::model::Monitor>,
972 datadog::Error<CreateMonitorError>,
973 > {
974 let local_configuration = &self.config;
975 let operation_id = "v1.create_monitor";
976
977 let local_client = &self.client;
978
979 let local_uri_str = format!(
980 "{}/api/v1/monitor",
981 local_configuration.get_operation_host(operation_id)
982 );
983 let mut local_req_builder =
984 local_client.request(reqwest::Method::POST, local_uri_str.as_str());
985
986 // build headers
987 let mut headers = HeaderMap::new();
988 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
989 headers.insert("Accept", HeaderValue::from_static("application/json"));
990
991 // build user agent
992 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
993 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
994 Err(e) => {
995 log::warn!("Failed to parse user agent header: {e}, falling back to default");
996 headers.insert(
997 reqwest::header::USER_AGENT,
998 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
999 )
1000 }
1001 };
1002
1003 // build auth
1004 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1005 headers.insert(
1006 "DD-API-KEY",
1007 HeaderValue::from_str(local_key.key.as_str())
1008 .expect("failed to parse DD-API-KEY header"),
1009 );
1010 };
1011 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1012 headers.insert(
1013 "DD-APPLICATION-KEY",
1014 HeaderValue::from_str(local_key.key.as_str())
1015 .expect("failed to parse DD-APPLICATION-KEY header"),
1016 );
1017 };
1018
1019 // build body parameters
1020 let output = Vec::new();
1021 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1022 if body.serialize(&mut ser).is_ok() {
1023 if let Some(content_encoding) = headers.get("Content-Encoding") {
1024 match content_encoding.to_str().unwrap_or_default() {
1025 "gzip" => {
1026 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1027 let _ = enc.write_all(ser.into_inner().as_slice());
1028 match enc.finish() {
1029 Ok(buf) => {
1030 local_req_builder = local_req_builder.body(buf);
1031 }
1032 Err(e) => return Err(datadog::Error::Io(e)),
1033 }
1034 }
1035 "deflate" => {
1036 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1037 let _ = enc.write_all(ser.into_inner().as_slice());
1038 match enc.finish() {
1039 Ok(buf) => {
1040 local_req_builder = local_req_builder.body(buf);
1041 }
1042 Err(e) => return Err(datadog::Error::Io(e)),
1043 }
1044 }
1045 "zstd1" => {
1046 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1047 let _ = enc.write_all(ser.into_inner().as_slice());
1048 match enc.finish() {
1049 Ok(buf) => {
1050 local_req_builder = local_req_builder.body(buf);
1051 }
1052 Err(e) => return Err(datadog::Error::Io(e)),
1053 }
1054 }
1055 _ => {
1056 local_req_builder = local_req_builder.body(ser.into_inner());
1057 }
1058 }
1059 } else {
1060 local_req_builder = local_req_builder.body(ser.into_inner());
1061 }
1062 }
1063
1064 local_req_builder = local_req_builder.headers(headers);
1065 let local_req = local_req_builder.build()?;
1066 log::debug!("request content: {:?}", local_req.body());
1067 let local_resp = local_client.execute(local_req).await?;
1068
1069 let local_status = local_resp.status();
1070 let local_content = local_resp.text().await?;
1071 log::debug!("response content: {}", local_content);
1072
1073 if !local_status.is_client_error() && !local_status.is_server_error() {
1074 match serde_json::from_str::<crate::datadogV1::model::Monitor>(&local_content) {
1075 Ok(e) => {
1076 return Ok(datadog::ResponseContent {
1077 status: local_status,
1078 content: local_content,
1079 entity: Some(e),
1080 })
1081 }
1082 Err(e) => return Err(datadog::Error::Serde(e)),
1083 };
1084 } else {
1085 let local_entity: Option<CreateMonitorError> =
1086 serde_json::from_str(&local_content).ok();
1087 let local_error = datadog::ResponseContent {
1088 status: local_status,
1089 content: local_content,
1090 entity: local_entity,
1091 };
1092 Err(datadog::Error::ResponseError(local_error))
1093 }
1094 }
1095
1096 /// Delete the specified monitor
1097 pub async fn delete_monitor(
1098 &self,
1099 monitor_id: i64,
1100 params: DeleteMonitorOptionalParams,
1101 ) -> Result<crate::datadogV1::model::DeletedMonitor, datadog::Error<DeleteMonitorError>> {
1102 match self.delete_monitor_with_http_info(monitor_id, params).await {
1103 Ok(response_content) => {
1104 if let Some(e) = response_content.entity {
1105 Ok(e)
1106 } else {
1107 Err(datadog::Error::Serde(serde::de::Error::custom(
1108 "response content was None",
1109 )))
1110 }
1111 }
1112 Err(err) => Err(err),
1113 }
1114 }
1115
1116 /// Delete the specified monitor
1117 pub async fn delete_monitor_with_http_info(
1118 &self,
1119 monitor_id: i64,
1120 params: DeleteMonitorOptionalParams,
1121 ) -> Result<
1122 datadog::ResponseContent<crate::datadogV1::model::DeletedMonitor>,
1123 datadog::Error<DeleteMonitorError>,
1124 > {
1125 let local_configuration = &self.config;
1126 let operation_id = "v1.delete_monitor";
1127
1128 // unbox and build optional parameters
1129 let force = params.force;
1130
1131 let local_client = &self.client;
1132
1133 let local_uri_str = format!(
1134 "{}/api/v1/monitor/{monitor_id}",
1135 local_configuration.get_operation_host(operation_id),
1136 monitor_id = monitor_id
1137 );
1138 let mut local_req_builder =
1139 local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
1140
1141 if let Some(ref local_query_param) = force {
1142 local_req_builder =
1143 local_req_builder.query(&[("force", &local_query_param.to_string())]);
1144 };
1145
1146 // build headers
1147 let mut headers = HeaderMap::new();
1148 headers.insert("Accept", HeaderValue::from_static("application/json"));
1149
1150 // build user agent
1151 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1152 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1153 Err(e) => {
1154 log::warn!("Failed to parse user agent header: {e}, falling back to default");
1155 headers.insert(
1156 reqwest::header::USER_AGENT,
1157 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1158 )
1159 }
1160 };
1161
1162 // build auth
1163 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1164 headers.insert(
1165 "DD-API-KEY",
1166 HeaderValue::from_str(local_key.key.as_str())
1167 .expect("failed to parse DD-API-KEY header"),
1168 );
1169 };
1170 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1171 headers.insert(
1172 "DD-APPLICATION-KEY",
1173 HeaderValue::from_str(local_key.key.as_str())
1174 .expect("failed to parse DD-APPLICATION-KEY header"),
1175 );
1176 };
1177
1178 local_req_builder = local_req_builder.headers(headers);
1179 let local_req = local_req_builder.build()?;
1180 log::debug!("request content: {:?}", local_req.body());
1181 let local_resp = local_client.execute(local_req).await?;
1182
1183 let local_status = local_resp.status();
1184 let local_content = local_resp.text().await?;
1185 log::debug!("response content: {}", local_content);
1186
1187 if !local_status.is_client_error() && !local_status.is_server_error() {
1188 match serde_json::from_str::<crate::datadogV1::model::DeletedMonitor>(&local_content) {
1189 Ok(e) => {
1190 return Ok(datadog::ResponseContent {
1191 status: local_status,
1192 content: local_content,
1193 entity: Some(e),
1194 })
1195 }
1196 Err(e) => return Err(datadog::Error::Serde(e)),
1197 };
1198 } else {
1199 let local_entity: Option<DeleteMonitorError> =
1200 serde_json::from_str(&local_content).ok();
1201 let local_error = datadog::ResponseContent {
1202 status: local_status,
1203 content: local_content,
1204 entity: local_entity,
1205 };
1206 Err(datadog::Error::ResponseError(local_error))
1207 }
1208 }
1209
1210 /// Get details about the specified monitor from your organization.
1211 pub async fn get_monitor(
1212 &self,
1213 monitor_id: i64,
1214 params: GetMonitorOptionalParams,
1215 ) -> Result<crate::datadogV1::model::Monitor, datadog::Error<GetMonitorError>> {
1216 match self.get_monitor_with_http_info(monitor_id, params).await {
1217 Ok(response_content) => {
1218 if let Some(e) = response_content.entity {
1219 Ok(e)
1220 } else {
1221 Err(datadog::Error::Serde(serde::de::Error::custom(
1222 "response content was None",
1223 )))
1224 }
1225 }
1226 Err(err) => Err(err),
1227 }
1228 }
1229
1230 /// Get details about the specified monitor from your organization.
1231 pub async fn get_monitor_with_http_info(
1232 &self,
1233 monitor_id: i64,
1234 params: GetMonitorOptionalParams,
1235 ) -> Result<
1236 datadog::ResponseContent<crate::datadogV1::model::Monitor>,
1237 datadog::Error<GetMonitorError>,
1238 > {
1239 let local_configuration = &self.config;
1240 let operation_id = "v1.get_monitor";
1241
1242 // unbox and build optional parameters
1243 let group_states = params.group_states;
1244 let with_downtimes = params.with_downtimes;
1245
1246 let local_client = &self.client;
1247
1248 let local_uri_str = format!(
1249 "{}/api/v1/monitor/{monitor_id}",
1250 local_configuration.get_operation_host(operation_id),
1251 monitor_id = monitor_id
1252 );
1253 let mut local_req_builder =
1254 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1255
1256 if let Some(ref local_query_param) = group_states {
1257 local_req_builder =
1258 local_req_builder.query(&[("group_states", &local_query_param.to_string())]);
1259 };
1260 if let Some(ref local_query_param) = with_downtimes {
1261 local_req_builder =
1262 local_req_builder.query(&[("with_downtimes", &local_query_param.to_string())]);
1263 };
1264
1265 // build headers
1266 let mut headers = HeaderMap::new();
1267 headers.insert("Accept", HeaderValue::from_static("application/json"));
1268
1269 // build user agent
1270 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1271 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1272 Err(e) => {
1273 log::warn!("Failed to parse user agent header: {e}, falling back to default");
1274 headers.insert(
1275 reqwest::header::USER_AGENT,
1276 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1277 )
1278 }
1279 };
1280
1281 // build auth
1282 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1283 headers.insert(
1284 "DD-API-KEY",
1285 HeaderValue::from_str(local_key.key.as_str())
1286 .expect("failed to parse DD-API-KEY header"),
1287 );
1288 };
1289 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1290 headers.insert(
1291 "DD-APPLICATION-KEY",
1292 HeaderValue::from_str(local_key.key.as_str())
1293 .expect("failed to parse DD-APPLICATION-KEY header"),
1294 );
1295 };
1296
1297 local_req_builder = local_req_builder.headers(headers);
1298 let local_req = local_req_builder.build()?;
1299 log::debug!("request content: {:?}", local_req.body());
1300 let local_resp = local_client.execute(local_req).await?;
1301
1302 let local_status = local_resp.status();
1303 let local_content = local_resp.text().await?;
1304 log::debug!("response content: {}", local_content);
1305
1306 if !local_status.is_client_error() && !local_status.is_server_error() {
1307 match serde_json::from_str::<crate::datadogV1::model::Monitor>(&local_content) {
1308 Ok(e) => {
1309 return Ok(datadog::ResponseContent {
1310 status: local_status,
1311 content: local_content,
1312 entity: Some(e),
1313 })
1314 }
1315 Err(e) => return Err(datadog::Error::Serde(e)),
1316 };
1317 } else {
1318 let local_entity: Option<GetMonitorError> = serde_json::from_str(&local_content).ok();
1319 let local_error = datadog::ResponseContent {
1320 status: local_status,
1321 content: local_content,
1322 entity: local_entity,
1323 };
1324 Err(datadog::Error::ResponseError(local_error))
1325 }
1326 }
1327
1328 /// Get all monitors from your organization.
1329 pub async fn list_monitors(
1330 &self,
1331 params: ListMonitorsOptionalParams,
1332 ) -> Result<Vec<crate::datadogV1::model::Monitor>, datadog::Error<ListMonitorsError>> {
1333 match self.list_monitors_with_http_info(params).await {
1334 Ok(response_content) => {
1335 if let Some(e) = response_content.entity {
1336 Ok(e)
1337 } else {
1338 Err(datadog::Error::Serde(serde::de::Error::custom(
1339 "response content was None",
1340 )))
1341 }
1342 }
1343 Err(err) => Err(err),
1344 }
1345 }
1346
1347 pub fn list_monitors_with_pagination(
1348 &self,
1349 mut params: ListMonitorsOptionalParams,
1350 ) -> impl Stream<
1351 Item = Result<crate::datadogV1::model::Monitor, datadog::Error<ListMonitorsError>>,
1352 > + '_ {
1353 try_stream! {
1354 let mut page_size: i32 = 100;
1355 if params.page_size.is_none() {
1356 params.page_size = Some(page_size);
1357 } else {
1358 page_size = params.page_size.unwrap().clone();
1359 }
1360 if params.page.is_none() {
1361 params.page = Some(0);
1362 }
1363 loop {
1364 let resp = self.list_monitors(params.clone()).await?;
1365
1366 let r = resp;
1367 let count = r.len();
1368 for team in r {
1369 yield team;
1370 }
1371
1372 if count < page_size as usize {
1373 break;
1374 }
1375 params.page = Some(params.page.unwrap() + 1);
1376 }
1377 }
1378 }
1379
1380 /// Get all monitors from your organization.
1381 pub async fn list_monitors_with_http_info(
1382 &self,
1383 params: ListMonitorsOptionalParams,
1384 ) -> Result<
1385 datadog::ResponseContent<Vec<crate::datadogV1::model::Monitor>>,
1386 datadog::Error<ListMonitorsError>,
1387 > {
1388 let local_configuration = &self.config;
1389 let operation_id = "v1.list_monitors";
1390
1391 // unbox and build optional parameters
1392 let group_states = params.group_states;
1393 let name = params.name;
1394 let tags = params.tags;
1395 let monitor_tags = params.monitor_tags;
1396 let with_downtimes = params.with_downtimes;
1397 let id_offset = params.id_offset;
1398 let page = params.page;
1399 let page_size = params.page_size;
1400
1401 let local_client = &self.client;
1402
1403 let local_uri_str = format!(
1404 "{}/api/v1/monitor",
1405 local_configuration.get_operation_host(operation_id)
1406 );
1407 let mut local_req_builder =
1408 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1409
1410 if let Some(ref local_query_param) = group_states {
1411 local_req_builder =
1412 local_req_builder.query(&[("group_states", &local_query_param.to_string())]);
1413 };
1414 if let Some(ref local_query_param) = name {
1415 local_req_builder =
1416 local_req_builder.query(&[("name", &local_query_param.to_string())]);
1417 };
1418 if let Some(ref local_query_param) = tags {
1419 local_req_builder =
1420 local_req_builder.query(&[("tags", &local_query_param.to_string())]);
1421 };
1422 if let Some(ref local_query_param) = monitor_tags {
1423 local_req_builder =
1424 local_req_builder.query(&[("monitor_tags", &local_query_param.to_string())]);
1425 };
1426 if let Some(ref local_query_param) = with_downtimes {
1427 local_req_builder =
1428 local_req_builder.query(&[("with_downtimes", &local_query_param.to_string())]);
1429 };
1430 if let Some(ref local_query_param) = id_offset {
1431 local_req_builder =
1432 local_req_builder.query(&[("id_offset", &local_query_param.to_string())]);
1433 };
1434 if let Some(ref local_query_param) = page {
1435 local_req_builder =
1436 local_req_builder.query(&[("page", &local_query_param.to_string())]);
1437 };
1438 if let Some(ref local_query_param) = page_size {
1439 local_req_builder =
1440 local_req_builder.query(&[("page_size", &local_query_param.to_string())]);
1441 };
1442
1443 // build headers
1444 let mut headers = HeaderMap::new();
1445 headers.insert("Accept", HeaderValue::from_static("application/json"));
1446
1447 // build user agent
1448 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1449 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1450 Err(e) => {
1451 log::warn!("Failed to parse user agent header: {e}, falling back to default");
1452 headers.insert(
1453 reqwest::header::USER_AGENT,
1454 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1455 )
1456 }
1457 };
1458
1459 // build auth
1460 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1461 headers.insert(
1462 "DD-API-KEY",
1463 HeaderValue::from_str(local_key.key.as_str())
1464 .expect("failed to parse DD-API-KEY header"),
1465 );
1466 };
1467 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1468 headers.insert(
1469 "DD-APPLICATION-KEY",
1470 HeaderValue::from_str(local_key.key.as_str())
1471 .expect("failed to parse DD-APPLICATION-KEY header"),
1472 );
1473 };
1474
1475 local_req_builder = local_req_builder.headers(headers);
1476 let local_req = local_req_builder.build()?;
1477 log::debug!("request content: {:?}", local_req.body());
1478 let local_resp = local_client.execute(local_req).await?;
1479
1480 let local_status = local_resp.status();
1481 let local_content = local_resp.text().await?;
1482 log::debug!("response content: {}", local_content);
1483
1484 if !local_status.is_client_error() && !local_status.is_server_error() {
1485 match serde_json::from_str::<Vec<crate::datadogV1::model::Monitor>>(&local_content) {
1486 Ok(e) => {
1487 return Ok(datadog::ResponseContent {
1488 status: local_status,
1489 content: local_content,
1490 entity: Some(e),
1491 })
1492 }
1493 Err(e) => return Err(datadog::Error::Serde(e)),
1494 };
1495 } else {
1496 let local_entity: Option<ListMonitorsError> = serde_json::from_str(&local_content).ok();
1497 let local_error = datadog::ResponseContent {
1498 status: local_status,
1499 content: local_content,
1500 entity: local_entity,
1501 };
1502 Err(datadog::Error::ResponseError(local_error))
1503 }
1504 }
1505
1506 /// Search and filter your monitor groups details.
1507 pub async fn search_monitor_groups(
1508 &self,
1509 params: SearchMonitorGroupsOptionalParams,
1510 ) -> Result<
1511 crate::datadogV1::model::MonitorGroupSearchResponse,
1512 datadog::Error<SearchMonitorGroupsError>,
1513 > {
1514 match self.search_monitor_groups_with_http_info(params).await {
1515 Ok(response_content) => {
1516 if let Some(e) = response_content.entity {
1517 Ok(e)
1518 } else {
1519 Err(datadog::Error::Serde(serde::de::Error::custom(
1520 "response content was None",
1521 )))
1522 }
1523 }
1524 Err(err) => Err(err),
1525 }
1526 }
1527
1528 /// Search and filter your monitor groups details.
1529 pub async fn search_monitor_groups_with_http_info(
1530 &self,
1531 params: SearchMonitorGroupsOptionalParams,
1532 ) -> Result<
1533 datadog::ResponseContent<crate::datadogV1::model::MonitorGroupSearchResponse>,
1534 datadog::Error<SearchMonitorGroupsError>,
1535 > {
1536 let local_configuration = &self.config;
1537 let operation_id = "v1.search_monitor_groups";
1538
1539 // unbox and build optional parameters
1540 let query = params.query;
1541 let page = params.page;
1542 let per_page = params.per_page;
1543 let sort = params.sort;
1544
1545 let local_client = &self.client;
1546
1547 let local_uri_str = format!(
1548 "{}/api/v1/monitor/groups/search",
1549 local_configuration.get_operation_host(operation_id)
1550 );
1551 let mut local_req_builder =
1552 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1553
1554 if let Some(ref local_query_param) = query {
1555 local_req_builder =
1556 local_req_builder.query(&[("query", &local_query_param.to_string())]);
1557 };
1558 if let Some(ref local_query_param) = page {
1559 local_req_builder =
1560 local_req_builder.query(&[("page", &local_query_param.to_string())]);
1561 };
1562 if let Some(ref local_query_param) = per_page {
1563 local_req_builder =
1564 local_req_builder.query(&[("per_page", &local_query_param.to_string())]);
1565 };
1566 if let Some(ref local_query_param) = sort {
1567 local_req_builder =
1568 local_req_builder.query(&[("sort", &local_query_param.to_string())]);
1569 };
1570
1571 // build headers
1572 let mut headers = HeaderMap::new();
1573 headers.insert("Accept", HeaderValue::from_static("application/json"));
1574
1575 // build user agent
1576 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1577 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1578 Err(e) => {
1579 log::warn!("Failed to parse user agent header: {e}, falling back to default");
1580 headers.insert(
1581 reqwest::header::USER_AGENT,
1582 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1583 )
1584 }
1585 };
1586
1587 // build auth
1588 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1589 headers.insert(
1590 "DD-API-KEY",
1591 HeaderValue::from_str(local_key.key.as_str())
1592 .expect("failed to parse DD-API-KEY header"),
1593 );
1594 };
1595 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1596 headers.insert(
1597 "DD-APPLICATION-KEY",
1598 HeaderValue::from_str(local_key.key.as_str())
1599 .expect("failed to parse DD-APPLICATION-KEY header"),
1600 );
1601 };
1602
1603 local_req_builder = local_req_builder.headers(headers);
1604 let local_req = local_req_builder.build()?;
1605 log::debug!("request content: {:?}", local_req.body());
1606 let local_resp = local_client.execute(local_req).await?;
1607
1608 let local_status = local_resp.status();
1609 let local_content = local_resp.text().await?;
1610 log::debug!("response content: {}", local_content);
1611
1612 if !local_status.is_client_error() && !local_status.is_server_error() {
1613 match serde_json::from_str::<crate::datadogV1::model::MonitorGroupSearchResponse>(
1614 &local_content,
1615 ) {
1616 Ok(e) => {
1617 return Ok(datadog::ResponseContent {
1618 status: local_status,
1619 content: local_content,
1620 entity: Some(e),
1621 })
1622 }
1623 Err(e) => return Err(datadog::Error::Serde(e)),
1624 };
1625 } else {
1626 let local_entity: Option<SearchMonitorGroupsError> =
1627 serde_json::from_str(&local_content).ok();
1628 let local_error = datadog::ResponseContent {
1629 status: local_status,
1630 content: local_content,
1631 entity: local_entity,
1632 };
1633 Err(datadog::Error::ResponseError(local_error))
1634 }
1635 }
1636
1637 /// Search and filter your monitors details.
1638 pub async fn search_monitors(
1639 &self,
1640 params: SearchMonitorsOptionalParams,
1641 ) -> Result<crate::datadogV1::model::MonitorSearchResponse, datadog::Error<SearchMonitorsError>>
1642 {
1643 match self.search_monitors_with_http_info(params).await {
1644 Ok(response_content) => {
1645 if let Some(e) = response_content.entity {
1646 Ok(e)
1647 } else {
1648 Err(datadog::Error::Serde(serde::de::Error::custom(
1649 "response content was None",
1650 )))
1651 }
1652 }
1653 Err(err) => Err(err),
1654 }
1655 }
1656
1657 /// Search and filter your monitors details.
1658 pub async fn search_monitors_with_http_info(
1659 &self,
1660 params: SearchMonitorsOptionalParams,
1661 ) -> Result<
1662 datadog::ResponseContent<crate::datadogV1::model::MonitorSearchResponse>,
1663 datadog::Error<SearchMonitorsError>,
1664 > {
1665 let local_configuration = &self.config;
1666 let operation_id = "v1.search_monitors";
1667
1668 // unbox and build optional parameters
1669 let query = params.query;
1670 let page = params.page;
1671 let per_page = params.per_page;
1672 let sort = params.sort;
1673
1674 let local_client = &self.client;
1675
1676 let local_uri_str = format!(
1677 "{}/api/v1/monitor/search",
1678 local_configuration.get_operation_host(operation_id)
1679 );
1680 let mut local_req_builder =
1681 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1682
1683 if let Some(ref local_query_param) = query {
1684 local_req_builder =
1685 local_req_builder.query(&[("query", &local_query_param.to_string())]);
1686 };
1687 if let Some(ref local_query_param) = page {
1688 local_req_builder =
1689 local_req_builder.query(&[("page", &local_query_param.to_string())]);
1690 };
1691 if let Some(ref local_query_param) = per_page {
1692 local_req_builder =
1693 local_req_builder.query(&[("per_page", &local_query_param.to_string())]);
1694 };
1695 if let Some(ref local_query_param) = sort {
1696 local_req_builder =
1697 local_req_builder.query(&[("sort", &local_query_param.to_string())]);
1698 };
1699
1700 // build headers
1701 let mut headers = HeaderMap::new();
1702 headers.insert("Accept", HeaderValue::from_static("application/json"));
1703
1704 // build user agent
1705 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1706 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1707 Err(e) => {
1708 log::warn!("Failed to parse user agent header: {e}, falling back to default");
1709 headers.insert(
1710 reqwest::header::USER_AGENT,
1711 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1712 )
1713 }
1714 };
1715
1716 // build auth
1717 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1718 headers.insert(
1719 "DD-API-KEY",
1720 HeaderValue::from_str(local_key.key.as_str())
1721 .expect("failed to parse DD-API-KEY header"),
1722 );
1723 };
1724 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1725 headers.insert(
1726 "DD-APPLICATION-KEY",
1727 HeaderValue::from_str(local_key.key.as_str())
1728 .expect("failed to parse DD-APPLICATION-KEY header"),
1729 );
1730 };
1731
1732 local_req_builder = local_req_builder.headers(headers);
1733 let local_req = local_req_builder.build()?;
1734 log::debug!("request content: {:?}", local_req.body());
1735 let local_resp = local_client.execute(local_req).await?;
1736
1737 let local_status = local_resp.status();
1738 let local_content = local_resp.text().await?;
1739 log::debug!("response content: {}", local_content);
1740
1741 if !local_status.is_client_error() && !local_status.is_server_error() {
1742 match serde_json::from_str::<crate::datadogV1::model::MonitorSearchResponse>(
1743 &local_content,
1744 ) {
1745 Ok(e) => {
1746 return Ok(datadog::ResponseContent {
1747 status: local_status,
1748 content: local_content,
1749 entity: Some(e),
1750 })
1751 }
1752 Err(e) => return Err(datadog::Error::Serde(e)),
1753 };
1754 } else {
1755 let local_entity: Option<SearchMonitorsError> =
1756 serde_json::from_str(&local_content).ok();
1757 let local_error = datadog::ResponseContent {
1758 status: local_status,
1759 content: local_content,
1760 entity: local_entity,
1761 };
1762 Err(datadog::Error::ResponseError(local_error))
1763 }
1764 }
1765
1766 /// Edit the specified monitor.
1767 pub async fn update_monitor(
1768 &self,
1769 monitor_id: i64,
1770 body: crate::datadogV1::model::MonitorUpdateRequest,
1771 ) -> Result<crate::datadogV1::model::Monitor, datadog::Error<UpdateMonitorError>> {
1772 match self.update_monitor_with_http_info(monitor_id, body).await {
1773 Ok(response_content) => {
1774 if let Some(e) = response_content.entity {
1775 Ok(e)
1776 } else {
1777 Err(datadog::Error::Serde(serde::de::Error::custom(
1778 "response content was None",
1779 )))
1780 }
1781 }
1782 Err(err) => Err(err),
1783 }
1784 }
1785
1786 /// Edit the specified monitor.
1787 pub async fn update_monitor_with_http_info(
1788 &self,
1789 monitor_id: i64,
1790 body: crate::datadogV1::model::MonitorUpdateRequest,
1791 ) -> Result<
1792 datadog::ResponseContent<crate::datadogV1::model::Monitor>,
1793 datadog::Error<UpdateMonitorError>,
1794 > {
1795 let local_configuration = &self.config;
1796 let operation_id = "v1.update_monitor";
1797
1798 let local_client = &self.client;
1799
1800 let local_uri_str = format!(
1801 "{}/api/v1/monitor/{monitor_id}",
1802 local_configuration.get_operation_host(operation_id),
1803 monitor_id = monitor_id
1804 );
1805 let mut local_req_builder =
1806 local_client.request(reqwest::Method::PUT, local_uri_str.as_str());
1807
1808 // build headers
1809 let mut headers = HeaderMap::new();
1810 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1811 headers.insert("Accept", HeaderValue::from_static("application/json"));
1812
1813 // build user agent
1814 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1815 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1816 Err(e) => {
1817 log::warn!("Failed to parse user agent header: {e}, falling back to default");
1818 headers.insert(
1819 reqwest::header::USER_AGENT,
1820 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1821 )
1822 }
1823 };
1824
1825 // build auth
1826 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1827 headers.insert(
1828 "DD-API-KEY",
1829 HeaderValue::from_str(local_key.key.as_str())
1830 .expect("failed to parse DD-API-KEY header"),
1831 );
1832 };
1833 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1834 headers.insert(
1835 "DD-APPLICATION-KEY",
1836 HeaderValue::from_str(local_key.key.as_str())
1837 .expect("failed to parse DD-APPLICATION-KEY header"),
1838 );
1839 };
1840
1841 // build body parameters
1842 let output = Vec::new();
1843 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1844 if body.serialize(&mut ser).is_ok() {
1845 if let Some(content_encoding) = headers.get("Content-Encoding") {
1846 match content_encoding.to_str().unwrap_or_default() {
1847 "gzip" => {
1848 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1849 let _ = enc.write_all(ser.into_inner().as_slice());
1850 match enc.finish() {
1851 Ok(buf) => {
1852 local_req_builder = local_req_builder.body(buf);
1853 }
1854 Err(e) => return Err(datadog::Error::Io(e)),
1855 }
1856 }
1857 "deflate" => {
1858 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1859 let _ = enc.write_all(ser.into_inner().as_slice());
1860 match enc.finish() {
1861 Ok(buf) => {
1862 local_req_builder = local_req_builder.body(buf);
1863 }
1864 Err(e) => return Err(datadog::Error::Io(e)),
1865 }
1866 }
1867 "zstd1" => {
1868 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1869 let _ = enc.write_all(ser.into_inner().as_slice());
1870 match enc.finish() {
1871 Ok(buf) => {
1872 local_req_builder = local_req_builder.body(buf);
1873 }
1874 Err(e) => return Err(datadog::Error::Io(e)),
1875 }
1876 }
1877 _ => {
1878 local_req_builder = local_req_builder.body(ser.into_inner());
1879 }
1880 }
1881 } else {
1882 local_req_builder = local_req_builder.body(ser.into_inner());
1883 }
1884 }
1885
1886 local_req_builder = local_req_builder.headers(headers);
1887 let local_req = local_req_builder.build()?;
1888 log::debug!("request content: {:?}", local_req.body());
1889 let local_resp = local_client.execute(local_req).await?;
1890
1891 let local_status = local_resp.status();
1892 let local_content = local_resp.text().await?;
1893 log::debug!("response content: {}", local_content);
1894
1895 if !local_status.is_client_error() && !local_status.is_server_error() {
1896 match serde_json::from_str::<crate::datadogV1::model::Monitor>(&local_content) {
1897 Ok(e) => {
1898 return Ok(datadog::ResponseContent {
1899 status: local_status,
1900 content: local_content,
1901 entity: Some(e),
1902 })
1903 }
1904 Err(e) => return Err(datadog::Error::Serde(e)),
1905 };
1906 } else {
1907 let local_entity: Option<UpdateMonitorError> =
1908 serde_json::from_str(&local_content).ok();
1909 let local_error = datadog::ResponseContent {
1910 status: local_status,
1911 content: local_content,
1912 entity: local_entity,
1913 };
1914 Err(datadog::Error::ResponseError(local_error))
1915 }
1916 }
1917
1918 /// Validate the monitor provided in the request.
1919 pub async fn validate_existing_monitor(
1920 &self,
1921 monitor_id: i64,
1922 body: crate::datadogV1::model::Monitor,
1923 ) -> Result<
1924 std::collections::BTreeMap<String, serde_json::Value>,
1925 datadog::Error<ValidateExistingMonitorError>,
1926 > {
1927 match self
1928 .validate_existing_monitor_with_http_info(monitor_id, body)
1929 .await
1930 {
1931 Ok(response_content) => {
1932 if let Some(e) = response_content.entity {
1933 Ok(e)
1934 } else {
1935 Err(datadog::Error::Serde(serde::de::Error::custom(
1936 "response content was None",
1937 )))
1938 }
1939 }
1940 Err(err) => Err(err),
1941 }
1942 }
1943
1944 /// Validate the monitor provided in the request.
1945 pub async fn validate_existing_monitor_with_http_info(
1946 &self,
1947 monitor_id: i64,
1948 body: crate::datadogV1::model::Monitor,
1949 ) -> Result<
1950 datadog::ResponseContent<std::collections::BTreeMap<String, serde_json::Value>>,
1951 datadog::Error<ValidateExistingMonitorError>,
1952 > {
1953 let local_configuration = &self.config;
1954 let operation_id = "v1.validate_existing_monitor";
1955
1956 let local_client = &self.client;
1957
1958 let local_uri_str = format!(
1959 "{}/api/v1/monitor/{monitor_id}/validate",
1960 local_configuration.get_operation_host(operation_id),
1961 monitor_id = monitor_id
1962 );
1963 let mut local_req_builder =
1964 local_client.request(reqwest::Method::POST, local_uri_str.as_str());
1965
1966 // build headers
1967 let mut headers = HeaderMap::new();
1968 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1969 headers.insert("Accept", HeaderValue::from_static("application/json"));
1970
1971 // build user agent
1972 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1973 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1974 Err(e) => {
1975 log::warn!("Failed to parse user agent header: {e}, falling back to default");
1976 headers.insert(
1977 reqwest::header::USER_AGENT,
1978 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1979 )
1980 }
1981 };
1982
1983 // build auth
1984 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1985 headers.insert(
1986 "DD-API-KEY",
1987 HeaderValue::from_str(local_key.key.as_str())
1988 .expect("failed to parse DD-API-KEY header"),
1989 );
1990 };
1991 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1992 headers.insert(
1993 "DD-APPLICATION-KEY",
1994 HeaderValue::from_str(local_key.key.as_str())
1995 .expect("failed to parse DD-APPLICATION-KEY header"),
1996 );
1997 };
1998
1999 // build body parameters
2000 let output = Vec::new();
2001 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
2002 if body.serialize(&mut ser).is_ok() {
2003 if let Some(content_encoding) = headers.get("Content-Encoding") {
2004 match content_encoding.to_str().unwrap_or_default() {
2005 "gzip" => {
2006 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
2007 let _ = enc.write_all(ser.into_inner().as_slice());
2008 match enc.finish() {
2009 Ok(buf) => {
2010 local_req_builder = local_req_builder.body(buf);
2011 }
2012 Err(e) => return Err(datadog::Error::Io(e)),
2013 }
2014 }
2015 "deflate" => {
2016 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
2017 let _ = enc.write_all(ser.into_inner().as_slice());
2018 match enc.finish() {
2019 Ok(buf) => {
2020 local_req_builder = local_req_builder.body(buf);
2021 }
2022 Err(e) => return Err(datadog::Error::Io(e)),
2023 }
2024 }
2025 "zstd1" => {
2026 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
2027 let _ = enc.write_all(ser.into_inner().as_slice());
2028 match enc.finish() {
2029 Ok(buf) => {
2030 local_req_builder = local_req_builder.body(buf);
2031 }
2032 Err(e) => return Err(datadog::Error::Io(e)),
2033 }
2034 }
2035 _ => {
2036 local_req_builder = local_req_builder.body(ser.into_inner());
2037 }
2038 }
2039 } else {
2040 local_req_builder = local_req_builder.body(ser.into_inner());
2041 }
2042 }
2043
2044 local_req_builder = local_req_builder.headers(headers);
2045 let local_req = local_req_builder.build()?;
2046 log::debug!("request content: {:?}", local_req.body());
2047 let local_resp = local_client.execute(local_req).await?;
2048
2049 let local_status = local_resp.status();
2050 let local_content = local_resp.text().await?;
2051 log::debug!("response content: {}", local_content);
2052
2053 if !local_status.is_client_error() && !local_status.is_server_error() {
2054 match serde_json::from_str::<std::collections::BTreeMap<String, serde_json::Value>>(
2055 &local_content,
2056 ) {
2057 Ok(e) => {
2058 return Ok(datadog::ResponseContent {
2059 status: local_status,
2060 content: local_content,
2061 entity: Some(e),
2062 })
2063 }
2064 Err(e) => return Err(datadog::Error::Serde(e)),
2065 };
2066 } else {
2067 let local_entity: Option<ValidateExistingMonitorError> =
2068 serde_json::from_str(&local_content).ok();
2069 let local_error = datadog::ResponseContent {
2070 status: local_status,
2071 content: local_content,
2072 entity: local_entity,
2073 };
2074 Err(datadog::Error::ResponseError(local_error))
2075 }
2076 }
2077
2078 /// Validate the monitor provided in the request.
2079 ///
2080 /// **Note**: Log monitors require an unscoped App Key.
2081 pub async fn validate_monitor(
2082 &self,
2083 body: crate::datadogV1::model::Monitor,
2084 ) -> Result<
2085 std::collections::BTreeMap<String, serde_json::Value>,
2086 datadog::Error<ValidateMonitorError>,
2087 > {
2088 match self.validate_monitor_with_http_info(body).await {
2089 Ok(response_content) => {
2090 if let Some(e) = response_content.entity {
2091 Ok(e)
2092 } else {
2093 Err(datadog::Error::Serde(serde::de::Error::custom(
2094 "response content was None",
2095 )))
2096 }
2097 }
2098 Err(err) => Err(err),
2099 }
2100 }
2101
2102 /// Validate the monitor provided in the request.
2103 ///
2104 /// **Note**: Log monitors require an unscoped App Key.
2105 pub async fn validate_monitor_with_http_info(
2106 &self,
2107 body: crate::datadogV1::model::Monitor,
2108 ) -> Result<
2109 datadog::ResponseContent<std::collections::BTreeMap<String, serde_json::Value>>,
2110 datadog::Error<ValidateMonitorError>,
2111 > {
2112 let local_configuration = &self.config;
2113 let operation_id = "v1.validate_monitor";
2114
2115 let local_client = &self.client;
2116
2117 let local_uri_str = format!(
2118 "{}/api/v1/monitor/validate",
2119 local_configuration.get_operation_host(operation_id)
2120 );
2121 let mut local_req_builder =
2122 local_client.request(reqwest::Method::POST, local_uri_str.as_str());
2123
2124 // build headers
2125 let mut headers = HeaderMap::new();
2126 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
2127 headers.insert("Accept", HeaderValue::from_static("application/json"));
2128
2129 // build user agent
2130 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
2131 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
2132 Err(e) => {
2133 log::warn!("Failed to parse user agent header: {e}, falling back to default");
2134 headers.insert(
2135 reqwest::header::USER_AGENT,
2136 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
2137 )
2138 }
2139 };
2140
2141 // build auth
2142 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
2143 headers.insert(
2144 "DD-API-KEY",
2145 HeaderValue::from_str(local_key.key.as_str())
2146 .expect("failed to parse DD-API-KEY header"),
2147 );
2148 };
2149 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
2150 headers.insert(
2151 "DD-APPLICATION-KEY",
2152 HeaderValue::from_str(local_key.key.as_str())
2153 .expect("failed to parse DD-APPLICATION-KEY header"),
2154 );
2155 };
2156
2157 // build body parameters
2158 let output = Vec::new();
2159 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
2160 if body.serialize(&mut ser).is_ok() {
2161 if let Some(content_encoding) = headers.get("Content-Encoding") {
2162 match content_encoding.to_str().unwrap_or_default() {
2163 "gzip" => {
2164 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
2165 let _ = enc.write_all(ser.into_inner().as_slice());
2166 match enc.finish() {
2167 Ok(buf) => {
2168 local_req_builder = local_req_builder.body(buf);
2169 }
2170 Err(e) => return Err(datadog::Error::Io(e)),
2171 }
2172 }
2173 "deflate" => {
2174 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
2175 let _ = enc.write_all(ser.into_inner().as_slice());
2176 match enc.finish() {
2177 Ok(buf) => {
2178 local_req_builder = local_req_builder.body(buf);
2179 }
2180 Err(e) => return Err(datadog::Error::Io(e)),
2181 }
2182 }
2183 "zstd1" => {
2184 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
2185 let _ = enc.write_all(ser.into_inner().as_slice());
2186 match enc.finish() {
2187 Ok(buf) => {
2188 local_req_builder = local_req_builder.body(buf);
2189 }
2190 Err(e) => return Err(datadog::Error::Io(e)),
2191 }
2192 }
2193 _ => {
2194 local_req_builder = local_req_builder.body(ser.into_inner());
2195 }
2196 }
2197 } else {
2198 local_req_builder = local_req_builder.body(ser.into_inner());
2199 }
2200 }
2201
2202 local_req_builder = local_req_builder.headers(headers);
2203 let local_req = local_req_builder.build()?;
2204 log::debug!("request content: {:?}", local_req.body());
2205 let local_resp = local_client.execute(local_req).await?;
2206
2207 let local_status = local_resp.status();
2208 let local_content = local_resp.text().await?;
2209 log::debug!("response content: {}", local_content);
2210
2211 if !local_status.is_client_error() && !local_status.is_server_error() {
2212 match serde_json::from_str::<std::collections::BTreeMap<String, serde_json::Value>>(
2213 &local_content,
2214 ) {
2215 Ok(e) => {
2216 return Ok(datadog::ResponseContent {
2217 status: local_status,
2218 content: local_content,
2219 entity: Some(e),
2220 })
2221 }
2222 Err(e) => return Err(datadog::Error::Serde(e)),
2223 };
2224 } else {
2225 let local_entity: Option<ValidateMonitorError> =
2226 serde_json::from_str(&local_content).ok();
2227 let local_error = datadog::ResponseContent {
2228 status: local_status,
2229 content: local_content,
2230 entity: local_entity,
2231 };
2232 Err(datadog::Error::ResponseError(local_error))
2233 }
2234 }
2235}