openstack-cli-image 0.13.8

OpenStack CLI Image commands
Documentation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
// WARNING: This file is automatically generated from OpenAPI schema using
// `openstack-codegenerator`.

//! Download File command
//!
//! Wraps invoking of the `v2/images/{image_id}/file` with `GET` method

use clap::Args;
use tracing::info;

use openstack_cli_core::cli::CliArgs;
use openstack_cli_core::error::OpenStackCliError;
use openstack_cli_core::output::OutputProcessor;
use openstack_sdk::AsyncOpenStack;

use openstack_cli_core::common::download_file;
use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::download;
use openstack_sdk::api::find;
use openstack_sdk::api::image::v2::image::file::download;
use openstack_sdk::api::image::v2::image::find;

/// Downloads binary image data. *(Since Image API v2.0)*
///
/// Starting with the 2026.1 (Gazpacho) release, a store preference feature is
/// introduced to allow services to suggest which stores to try when
/// downloading images. This enables services like Nova and Cinder to prefer
/// stores that are close to them or have better performance characteristics.
///
/// An optional `prefer` query parameter may be added to the request. When
/// present, it contains a comma-separated list of store identifiers suggesting
/// the ordering of stores to try when downloading the image. Glance will try
/// stores from the list in order. If the image is not found in any of the
/// specified stores, the system will fall back to the default behavior (trying
/// all stores).
///
/// Example call:
/// `curl -i -X GET -H "X-Auth-Token: $token" $image_url/v2/images/{image_id}/file`
///
/// Example call with store preference:
/// `curl -i -X GET -H "X-Auth-Token: $token" $image_url/v2/images/{image_id}/file?prefer=local-store,backup-store`
///
/// The response body contains the raw binary data that represents the actual
/// virtual disk. The `Content-Type` header contains the
/// `application/octet-stream` value. The `Content-MD5` header contains an MD5
/// checksum of the image data. Use this checksum to verify the integrity of
/// the image data.
///
/// **Preconditions**
///
/// **Synchronous Postconditions**
///
/// Normal response codes: 200, 204, 206
///
/// Error response codes: 400, 403, 404, 416
///
/// **Error Responses**
#[derive(Args)]
#[command(about = "Download binary image data")]
pub struct FileCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

    /// Request Headers parameters
    #[command(flatten)]
    headers: HeaderParameters,

    /// Path parameters
    #[command(flatten)]
    path: PathParameters,

    /// Destination filename (using "-" will print object to stdout)
    #[arg(long)]
    file: Option<String>,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {}

/// Header parameters
#[derive(Args)]
struct HeaderParameters {
    /// The range of image data requested. Note that multi range requests are
    /// not supported.
    #[arg(long)]
    range: Option<String>,
}

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// image_id parameter for /v2/images/{image_id}/file API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_image_id",
        value_name = "IMAGE_ID"
    )]
    image_id: String,
}

impl FileCommand {
    /// Perform command action
    pub async fn take_action<C: CliArgs>(
        &self,
        parsed_args: &C,
        client: &mut AsyncOpenStack,
    ) -> Result<(), OpenStackCliError> {
        info!("Download File");

        let op =
            OutputProcessor::from_args(parsed_args, Some("image.image/file"), Some("download"));
        op.validate_args(parsed_args)?;
        let find_ep = find::Request::builder()
            .id(&self.path.image_id)
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
        let image_data: serde_json::Value = find(find_ep).query_async(client).await?;

        let image_id = image_data["id"]
            .as_str()
            .ok_or_else(|| eyre::eyre!("image ID must be a string"))?
            .to_string();
        let image_name = image_data["name"]
            .as_str()
            .ok_or_else(|| eyre::eyre!("image name must be a string"))?
            .to_string();

        let ep = download::Request::builder()
            .image_id(image_id)
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
        let (headers, data) = download(ep).query_async(client).await?;

        let size: u64 = headers
            .get("content-length")
            .and_then(|x| {
                x.to_str()
                    .inspect_err(|e| {
                        tracing::warn!("content-length header cannot be treated as string: {}", e)
                    })
                    .ok()
            })
            .unwrap_or("0")
            .parse()
            .inspect_err(|e| {
                tracing::warn!("content-length header mut represent u64 number: {}", e)
            })
            .unwrap_or_default();
        download_file(self.file.clone().unwrap_or(image_name), size, data).await?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}