Skip to main content

openstack_sdk_load_balancer/v2/l7policy/
create.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Creates a L7 policy.
19//!
20//! This operation provisions a new L7 policy by using the configuration that
21//! you define in the request object. After the API validates the request and
22//! starts the provisioning process, the API returns a response object that
23//! contains a unique ID and the status of provisioning the L7 policy.
24//!
25//! In the response, the L7 policy [provisioning status](#prov-status) is
26//! `ACTIVE`, `PENDING_CREATE`, or `ERROR`.
27//!
28//! If the status is `PENDING_CREATE`, issue GET
29//! `/v2/lbaas/l7policies/{l7policy_id}` to view the progress of the
30//! provisioning operation. When the L7 policy status changes to `ACTIVE`, the
31//! L7 policy is successfully provisioned and is ready for further
32//! configuration.
33//!
34//! If the API cannot fulfill the request due to insufficient data or data that
35//! is not valid, the service returns the HTTP `Bad Request (400)` response
36//! code with information about the failure in the response body. Validation
37//! errors require that you correct the error and submit the request again.
38//!
39//! All the rules associated with a given policy are logically ANDead together.
40//! A request must match all the policy’s rules to match the policy.
41//!
42//! If you need to express a logical OR operation between rules, then do this
43//! by creating multiple policies with the same action.
44//!
45//! If a new policy is created with a position that matches that of an existing
46//! policy, then the new policy is inserted at the given position.
47//!
48//! L7 policies with `action` of `REDIRECT_TO_URL` will return the default HTTP
49//! `Found (302)` response code with the `redirect_url`. Also, specify
50//! `redirect_http_code` to configure the needed HTTP response code, such as,
51//! 301, 302, 303, 307 and 308.
52//!
53//! L7 policies with `action` of `REJECT` will return a `Forbidden (403)`
54//! response code to the requester.
55//!
56use derive_builder::Builder;
57use http::{HeaderMap, HeaderName, HeaderValue};
58
59use openstack_sdk_core::api::rest_endpoint_prelude::*;
60
61use serde::Deserialize;
62use serde::Serialize;
63use std::borrow::Cow;
64
65#[derive(Debug, Deserialize, Clone, Serialize)]
66pub enum Action {
67    #[serde(rename = "REDIRECT_PREFIX")]
68    RedirectPrefix,
69    #[serde(rename = "REDIRECT_TO_POOL")]
70    RedirectToPool,
71    #[serde(rename = "REDIRECT_TO_URL")]
72    RedirectToUrl,
73    #[serde(rename = "REJECT")]
74    Reject,
75}
76
77#[derive(Debug, Deserialize, Clone, Serialize)]
78pub enum CompareType {
79    #[serde(rename = "CONTAINS")]
80    Contains,
81    #[serde(rename = "ENDS_WITH")]
82    EndsWith,
83    #[serde(rename = "EQUAL_TO")]
84    EqualTo,
85    #[serde(rename = "REGEX")]
86    Regex,
87    #[serde(rename = "STARTS_WITH")]
88    StartsWith,
89}
90
91#[derive(Debug, Deserialize, Clone, Serialize)]
92pub enum Type {
93    #[serde(rename = "COOKIE")]
94    Cookie,
95    #[serde(rename = "FILE_TYPE")]
96    FileType,
97    #[serde(rename = "HEADER")]
98    Header,
99    #[serde(rename = "HOST_NAME")]
100    HostName,
101    #[serde(rename = "PATH")]
102    Path,
103    #[serde(rename = "SSL_CONN_HAS_CERT")]
104    SslConnHasCert,
105    #[serde(rename = "SSL_DN_FIELD")]
106    SslDnField,
107    #[serde(rename = "SSL_VERIFY_RESULT")]
108    SslVerifyResult,
109}
110
111/// Defines mandatory and optional attributes of a POST request.
112#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
113#[builder(setter(strip_option))]
114pub struct Rules<'a> {
115    #[serde(skip_serializing_if = "Option::is_none")]
116    #[builder(default, setter(into))]
117    pub(crate) admin_state_up: Option<bool>,
118
119    #[serde()]
120    #[builder()]
121    pub(crate) compare_type: CompareType,
122
123    #[serde(skip_serializing_if = "Option::is_none")]
124    #[builder(default, setter(into))]
125    pub(crate) invert: Option<bool>,
126
127    #[serde(skip_serializing_if = "Option::is_none")]
128    #[builder(default, setter(into))]
129    pub(crate) key: Option<Cow<'a, str>>,
130
131    /// A list of simple strings assigned to the resource.
132    ///
133    /// **New in version 2.5**
134    #[serde(skip_serializing_if = "Option::is_none")]
135    #[builder(default, setter(into))]
136    pub(crate) tags: Option<Vec<Cow<'a, str>>>,
137
138    #[serde(rename = "type")]
139    #[builder()]
140    pub(crate) _type: Type,
141
142    #[serde()]
143    #[builder(setter(into))]
144    pub(crate) value: Cow<'a, str>,
145}
146
147/// Defines mandatory and optional attributes of a POST request.
148#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
149#[builder(setter(strip_option))]
150pub struct L7policy<'a> {
151    /// The L7 policy action. One of `REDIRECT_PREFIX`, `REDIRECT_TO_POOL`,
152    /// `REDIRECT_TO_URL`, or `REJECT`.
153    #[serde()]
154    #[builder()]
155    pub(crate) action: Action,
156
157    /// The administrative state of the resource, which is up (`true`) or down
158    /// (`false`). Default is `true`.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    #[builder(default, setter(into))]
161    pub(crate) admin_state_up: Option<bool>,
162
163    /// A human-readable description for the resource.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    #[builder(default, setter(into))]
166    pub(crate) description: Option<Cow<'a, str>>,
167
168    /// The ID of the listener.
169    #[serde()]
170    #[builder(setter(into))]
171    pub(crate) listener_id: Cow<'a, str>,
172
173    /// Human-readable name of the resource.
174    #[serde(skip_serializing_if = "Option::is_none")]
175    #[builder(default, setter(into))]
176    pub(crate) name: Option<Cow<'a, str>>,
177
178    /// The position of this policy on the listener. Positions start at 1.
179    #[serde(skip_serializing_if = "Option::is_none")]
180    #[builder(default, setter(into))]
181    pub(crate) position: Option<i32>,
182
183    /// The ID of the project owning this resource.
184    #[serde(skip_serializing_if = "Option::is_none")]
185    #[builder(default, setter(into))]
186    pub(crate) project_id: Option<Cow<'a, str>>,
187
188    /// Requests matching this policy will be redirected to the specified URL
189    /// or Prefix URL with the HTTP response code. Valid if `action` is
190    /// `REDIRECT_TO_URL` or `REDIRECT_PREFIX`. Valid options are: 301, 302,
191    /// 303, 307, or 308. Default is 302.
192    ///
193    /// **New in version 2.9**
194    #[serde(skip_serializing_if = "Option::is_none")]
195    #[builder(default, setter(into))]
196    pub(crate) redirect_http_code: Option<i32>,
197
198    /// Requests matching this policy will be redirected to the pool with this
199    /// ID. Only valid if `action` is `REDIRECT_TO_POOL`. The pool has some
200    /// restrictions, See
201    /// [Protocol Combinations (Listener/Pool)](#valid-protocol).
202    #[serde(skip_serializing_if = "Option::is_none")]
203    #[builder(default, setter(into))]
204    pub(crate) redirect_pool_id: Option<Cow<'a, str>>,
205
206    /// Requests matching this policy will be redirected to this Prefix URL.
207    /// Only valid if `action` is `REDIRECT_PREFIX`.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    #[builder(default, setter(into))]
210    pub(crate) redirect_prefix: Option<Cow<'a, str>>,
211
212    /// Requests matching this policy will be redirected to this URL. Only
213    /// valid if `action` is `REDIRECT_TO_URL`.
214    #[serde(skip_serializing_if = "Option::is_none")]
215    #[builder(default, setter(into))]
216    pub(crate) redirect_url: Option<Cow<'a, str>>,
217
218    #[serde(skip_serializing_if = "Option::is_none")]
219    #[builder(default, setter(into))]
220    pub(crate) rules: Option<Vec<Rules<'a>>>,
221
222    #[serde(skip_serializing_if = "Option::is_none")]
223    #[builder(default, setter(into))]
224    pub(crate) tags: Option<Vec<Cow<'a, str>>>,
225
226    #[serde(skip_serializing_if = "Option::is_none")]
227    #[builder(default, setter(into))]
228    pub(crate) tenant_id: Option<Cow<'a, str>>,
229}
230
231#[derive(Builder, Debug, Clone)]
232#[builder(setter(strip_option))]
233pub struct Request<'a> {
234    /// Defines mandatory and optional attributes of a POST request.
235    #[builder(setter(into))]
236    pub(crate) l7policy: L7policy<'a>,
237
238    #[builder(setter(name = "_headers"), default, private)]
239    _headers: Option<HeaderMap>,
240}
241impl<'a> Request<'a> {
242    /// Create a builder for the endpoint.
243    pub fn builder() -> RequestBuilder<'a> {
244        RequestBuilder::default()
245    }
246}
247
248impl<'a> RequestBuilder<'a> {
249    /// Add a single header to the L7Policy.
250    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
251    where
252        K: Into<HeaderName>,
253        V: Into<HeaderValue>,
254    {
255        self._headers
256            .get_or_insert(None)
257            .get_or_insert_with(HeaderMap::new)
258            .insert(header_name.into(), header_value.into());
259        self
260    }
261
262    /// Add multiple headers.
263    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
264    where
265        I: Iterator<Item = T>,
266        T: Into<(Option<HeaderName>, HeaderValue)>,
267    {
268        self._headers
269            .get_or_insert(None)
270            .get_or_insert_with(HeaderMap::new)
271            .extend(iter.map(Into::into));
272        self
273    }
274}
275
276impl RestEndpoint for Request<'_> {
277    fn method(&self) -> http::Method {
278        http::Method::POST
279    }
280
281    fn endpoint(&self) -> Cow<'static, str> {
282        "lbaas/l7policies".to_string().into()
283    }
284
285    fn parameters(&self) -> QueryParams<'_> {
286        QueryParams::default()
287    }
288
289    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
290        let mut params = JsonBodyParams::default();
291
292        params.push("l7policy", serde_json::to_value(&self.l7policy)?);
293
294        params.into_body()
295    }
296
297    fn service_type(&self) -> ServiceType {
298        ServiceType::LoadBalancer
299    }
300
301    fn response_key(&self) -> Option<Cow<'static, str>> {
302        Some("l7policy".into())
303    }
304
305    /// Returns headers to be set into the request
306    fn request_headers(&self) -> Option<&HeaderMap> {
307        self._headers.as_ref()
308    }
309
310    /// Returns required API version
311    fn api_version(&self) -> Option<ApiVersion> {
312        Some(ApiVersion::new(2, 0))
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use http::{HeaderName, HeaderValue};
320    use httpmock::MockServer;
321    #[cfg(feature = "sync")]
322    use openstack_sdk_core::api::Query;
323    use openstack_sdk_core::test::client::FakeOpenStackClient;
324    use openstack_sdk_core::types::ServiceType;
325    use serde_json::json;
326
327    #[test]
328    fn test_service_type() {
329        assert_eq!(
330            Request::builder()
331                .l7policy(
332                    L7policyBuilder::default()
333                        .action(Action::RedirectPrefix)
334                        .listener_id("foo")
335                        .build()
336                        .unwrap()
337                )
338                .build()
339                .unwrap()
340                .service_type(),
341            ServiceType::LoadBalancer
342        );
343    }
344
345    #[test]
346    fn test_response_key() {
347        assert_eq!(
348            Request::builder()
349                .l7policy(
350                    L7policyBuilder::default()
351                        .action(Action::RedirectPrefix)
352                        .listener_id("foo")
353                        .build()
354                        .unwrap()
355                )
356                .build()
357                .unwrap()
358                .response_key()
359                .unwrap(),
360            "l7policy"
361        );
362    }
363
364    #[cfg(feature = "sync")]
365    #[test]
366    fn endpoint() {
367        let server = MockServer::start();
368        let client = FakeOpenStackClient::new(server.base_url());
369        let mock = server.mock(|when, then| {
370            when.method(httpmock::Method::POST)
371                .path("/lbaas/l7policies".to_string());
372
373            then.status(200)
374                .header("content-type", "application/json")
375                .json_body(json!({ "l7policy": {} }));
376        });
377
378        let endpoint = Request::builder()
379            .l7policy(
380                L7policyBuilder::default()
381                    .action(Action::RedirectPrefix)
382                    .listener_id("foo")
383                    .build()
384                    .unwrap(),
385            )
386            .build()
387            .unwrap();
388        let _: serde_json::Value = endpoint.query(&client).unwrap();
389        mock.assert();
390    }
391
392    #[cfg(feature = "sync")]
393    #[test]
394    fn endpoint_headers() {
395        let server = MockServer::start();
396        let client = FakeOpenStackClient::new(server.base_url());
397        let mock = server.mock(|when, then| {
398            when.method(httpmock::Method::POST)
399                .path("/lbaas/l7policies".to_string())
400                .header("foo", "bar")
401                .header("not_foo", "not_bar");
402            then.status(200)
403                .header("content-type", "application/json")
404                .json_body(json!({ "l7policy": {} }));
405        });
406
407        let endpoint = Request::builder()
408            .l7policy(
409                L7policyBuilder::default()
410                    .action(Action::RedirectPrefix)
411                    .listener_id("foo")
412                    .build()
413                    .unwrap(),
414            )
415            .headers(
416                [(
417                    Some(HeaderName::from_static("foo")),
418                    HeaderValue::from_static("bar"),
419                )]
420                .into_iter(),
421            )
422            .header(
423                HeaderName::from_static("not_foo"),
424                HeaderValue::from_static("not_bar"),
425            )
426            .build()
427            .unwrap();
428        let _: serde_json::Value = endpoint.query(&client).unwrap();
429        mock.assert();
430    }
431}