Skip to main content

openstack_cli_load_balancer/v2/l7policy/
set.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//! Set L7Policy command
19//!
20//! Wraps invoking of the `v2/lbaas/l7policies/{l7policy_id}` with `PUT` method
21
22use clap::Args;
23use eyre::WrapErr;
24use tracing::info;
25
26use openstack_cli_core::cli::CliArgs;
27use openstack_cli_core::error::OpenStackCliError;
28use openstack_cli_core::output::OutputProcessor;
29use openstack_sdk::AsyncOpenStack;
30
31use clap::ValueEnum;
32use openstack_sdk::api::QueryAsync;
33use openstack_sdk::api::find;
34use openstack_sdk::api::load_balancer::v2::l7policy::find;
35use openstack_sdk::api::load_balancer::v2::l7policy::set;
36use openstack_types::load_balancer::v2::l7policy::response;
37
38/// Updates a L7 policy.
39///
40/// If the request is valid, the service returns the `Accepted (202)` response
41/// code. To confirm the update, check that the L7 policy provisioning status
42/// is `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation to poll
43/// the L7 policy object for changes.
44///
45/// This operation returns the updated L7 policy object with the `ACTIVE`,
46/// `PENDING_UPDATE`, or `ERROR` provisioning status.
47///
48/// If a policy is updated with a position that matches that of an existing
49/// policy, then the updated policy is inserted at the given position.
50#[derive(Args)]
51#[command(about = "Update a L7 Policy")]
52pub struct L7PolicyCommand {
53    /// Request Query parameters
54    #[command(flatten)]
55    query: QueryParameters,
56
57    /// Path parameters
58    #[command(flatten)]
59    path: PathParameters,
60
61    /// Defines attributes that are acceptable of a PUT request.
62    #[command(flatten)]
63    l7policy: L7policy,
64}
65
66/// Query parameters
67#[derive(Args)]
68struct QueryParameters {}
69
70/// Path parameters
71#[derive(Args)]
72struct PathParameters {
73    /// l7policy_id parameter for /v2/lbaas/l7policies/{l7policy_id} API
74    #[arg(
75        help_heading = "Path parameters",
76        id = "path_param_id",
77        value_name = "ID"
78    )]
79    id: String,
80}
81
82#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
83enum Action {
84    RedirectPrefix,
85    RedirectToPool,
86    RedirectToUrl,
87    Reject,
88}
89
90/// L7policy Body data
91#[derive(Args, Clone)]
92struct L7policy {
93    /// The L7 policy action. One of `REDIRECT_PREFIX`, `REDIRECT_TO_POOL`,
94    /// `REDIRECT_TO_URL`, or `REJECT`.
95    #[arg(help_heading = "Body parameters", long)]
96    action: Option<Action>,
97
98    /// The administrative state of the resource, which is up (`true`) or down
99    /// (`false`). Default is `true`.
100    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
101    admin_state_up: Option<bool>,
102
103    /// A human-readable description for the resource.
104    #[arg(help_heading = "Body parameters", long)]
105    description: Option<String>,
106
107    /// Human-readable name of the resource.
108    #[arg(help_heading = "Body parameters", long)]
109    name: Option<String>,
110
111    /// The position of this policy on the listener. Positions start at 1.
112    #[arg(help_heading = "Body parameters", long)]
113    position: Option<i32>,
114
115    /// Requests matching this policy will be redirected to the specified URL
116    /// or Prefix URL with the HTTP response code. Valid if `action` is
117    /// `REDIRECT_TO_URL` or `REDIRECT_PREFIX`. Valid options are: 301, 302,
118    /// 303, 307, or 308. Default is 302.
119    ///
120    /// **New in version 2.9**
121    #[arg(help_heading = "Body parameters", long)]
122    redirect_http_code: Option<i32>,
123
124    /// Requests matching this policy will be redirected to the pool with this
125    /// ID. Only valid if `action` is `REDIRECT_TO_POOL`. The pool has some
126    /// restrictions, See
127    /// [Protocol Combinations (Listener/Pool)](#valid-protocol).
128    #[arg(help_heading = "Body parameters", long)]
129    redirect_pool_id: Option<String>,
130
131    /// Requests matching this policy will be redirected to this Prefix URL.
132    /// Only valid if `action` is `REDIRECT_PREFIX`.
133    #[arg(help_heading = "Body parameters", long)]
134    redirect_prefix: Option<String>,
135
136    /// Requests matching this policy will be redirected to this URL. Only
137    /// valid if `action` is `REDIRECT_TO_URL`.
138    #[arg(help_heading = "Body parameters", long)]
139    redirect_url: Option<String>,
140
141    /// A list of simple strings assigned to the resource.
142    ///
143    /// **New in version 2.5**
144    ///
145    /// Parameter is an array, may be provided multiple times.
146    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
147    tags: Option<Vec<String>>,
148}
149
150impl L7PolicyCommand {
151    /// Perform command action
152    pub async fn take_action<C: CliArgs>(
153        &self,
154        parsed_args: &C,
155        client: &mut AsyncOpenStack,
156    ) -> Result<(), OpenStackCliError> {
157        info!("Set L7Policy");
158
159        let op =
160            OutputProcessor::from_args(parsed_args, Some("load-balancer.l7policy"), Some("set"));
161        op.validate_args(parsed_args)?;
162
163        let mut find_builder = find::Request::builder();
164
165        find_builder.id(&self.path.id);
166
167        let find_ep = find_builder
168            .build()
169            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
170        let find_data: serde_json::Value = find(find_ep).query_async(client).await?;
171
172        let mut ep_builder = set::Request::builder();
173
174        let resource_id = find_data["id"]
175            .as_str()
176            .ok_or_else(|| eyre::eyre!("resource ID must be a string"))?
177            .to_string();
178        ep_builder.id(resource_id.clone());
179
180        // Set body parameters
181        // Set Request.l7policy data
182        let args = &self.l7policy;
183        let mut l7policy_builder = set::L7policyBuilder::default();
184        if let Some(val) = &args.action {
185            let tmp = match val {
186                Action::RedirectPrefix => set::Action::RedirectPrefix,
187                Action::RedirectToPool => set::Action::RedirectToPool,
188                Action::RedirectToUrl => set::Action::RedirectToUrl,
189                Action::Reject => set::Action::Reject,
190            };
191            l7policy_builder.action(tmp);
192        }
193
194        if let Some(val) = &args.admin_state_up {
195            l7policy_builder.admin_state_up(*val);
196        }
197
198        if let Some(val) = &args.description {
199            l7policy_builder.description(val);
200        }
201
202        if let Some(val) = &args.name {
203            l7policy_builder.name(val);
204        }
205
206        if let Some(val) = &args.position {
207            l7policy_builder.position(*val);
208        }
209
210        if let Some(val) = &args.redirect_http_code {
211            l7policy_builder.redirect_http_code(*val);
212        }
213
214        if let Some(val) = &args.redirect_pool_id {
215            l7policy_builder.redirect_pool_id(val);
216        }
217
218        if let Some(val) = &args.redirect_prefix {
219            l7policy_builder.redirect_prefix(val);
220        }
221
222        if let Some(val) = &args.redirect_url {
223            l7policy_builder.redirect_url(val);
224        }
225
226        if let Some(val) = &args.tags {
227            l7policy_builder.tags(val.iter().map(Into::into).collect::<Vec<_>>());
228        }
229
230        ep_builder.l7policy(
231            l7policy_builder
232                .build()
233                .wrap_err("error preparing the request data")?,
234        );
235
236        let ep = ep_builder
237            .build()
238            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
239
240        let data: serde_json::Value = ep.query_async(client).await?;
241
242        op.output_single::<response::set::L7policyResponse>(data.clone())?;
243        // Show command specific hints
244        op.show_command_hint()?;
245        Ok(())
246    }
247}