summaryrefslogtreecommitdiffstats
path: root/plugins/c8y_configuration_plugin/src/download.rs
blob: 807d0cdbc8a6d2f0939888a6a3ab0b192142f19a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
use crate::config::FileEntry;
use crate::error::ConfigManagementError;
use crate::{error, PluginConfig, CONFIG_CHANGE_TOPIC};
use c8y_api::http_proxy::C8YHttpProxy;
use c8y_smartrest::error::SmartRestSerializerError;
use c8y_smartrest::smartrest_deserializer::SmartRestConfigDownloadRequest;
use c8y_smartrest::smartrest_serializer::{
    CumulocitySupportedOperations, SmartRest, SmartRestSerializer,
    SmartRestSetOperationToExecuting, SmartRestSetOperationToFailed,
    SmartRestSetOperationToSuccessful, TryIntoOperationStatusMessage,
};
use download::{Auth, DownloadInfo, Downloader};
use mqtt_channel::{Connection, Message, SinkExt, Topic};
use serde_json::json;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use tedge_utils::file::{get_filename, get_metadata, PermissionEntry};
use tracing::{info, warn};

pub async fn handle_config_download_request(
    plugin_config: &PluginConfig,
    smartrest_request: SmartRestConfigDownloadRequest,
    tmp_dir: PathBuf,
    mqtt_client: &mut Connection,
    http_client: &mut impl C8YHttpProxy,
) -> Result<(), anyhow::Error> {
    let executing_message = DownloadConfigFileStatusMessage::executing()?;
    let () = mqtt_client.published.send(executing_message).await?;

    let target_config_type = smartrest_request.config_type.clone();
    let mut target_file_entry = FileEntry::default();

    let download_result = {
        match plugin_config.get_file_entry_from_type(&target_config_type) {
            Ok(file_entry) => {
                target_file_entry = file_entry;
                download_config_file(
                    smartrest_request.url.as_str(),
                    PathBuf::from(&target_file_entry.path),
                    tmp_dir,
                    target_file_entry.file_permissions,
                    http_client,
                )
                .await
            }
            Err(err) => Err(err.into()),
        }
    };

    match download_result {
        Ok(_) => {
            info!("The configuration download for '{target_config_type}' is successful.");

            let successful_message = DownloadConfigFileStatusMessage::successful(None)?;
            let () = mqtt_client.published.send(successful_message).await?;

            let notification_message =
                get_file_change_notification_message(&target_file_entry.path, &target_config_type);
            let () = mqtt_client.published.send(notification_message).await?;
            Ok(())
        }
        Err(err) => {
            error!("The configuration download for '{target_config_type}' failed.",);

            let failed_message = DownloadConfigFileStatusMessage::failed(err.to_string())?;
            let () = mqtt_client.published.send(failed_message).await?;
            Err(err)
        }
    }
}

async fn download_config_file(
    download_url: &str,
    file_path: PathBuf,
    tmp_dir: PathBuf,
    file_permissions: PermissionEntry,
    http_client: &mut impl C8YHttpProxy,
) -> Result<(), anyhow::Error> {
    // Convert smartrest request to config download request struct
    let mut config_download_request =
        ConfigDownloadRequest::try_new(download_url, file_path, tmp_dir, file_permissions)?;

    // Confirm that the file has write access before any http request attempt
    let () = config_download_request.has_write_access()?;

    // If the provided url is c8y, add auth
    if http_client.url_is_in_my_tenant_domain(config_download_request.download_info.url()) {
        let token = http_client.get_jwt_token().await?;
        config_download_request.download_info.auth = Some(Auth::new_bearer(&token.token()));
    }

    // Download a file to tmp dir
    let downloader = config_download_request.create_downloader();
    let () = downloader
        .download(&config_download_request.download_info)
        .await?;

    // Move the downloaded file to the final destination
    let () = config_download_request.move_file()?;

    Ok(())
}

#[derive(Debug, Clone, PartialEq)]
pub struct ConfigDownloadRequest {
    pub download_info: DownloadInfo,
    pub file_path: PathBuf,
    pub tmp_dir: PathBuf,
    pub file_permissions: PermissionEntry,
    pub file_name: String,
}

impl ConfigDownloadRequest {
    fn try_new(
        download_url: &str,
        file_path: PathBuf,
        tmp_dir: PathBuf,
        file_permissions: PermissionEntry,
    ) -> Result<Self, ConfigManagementError> {
        let file_name = get_filename(file_path.clone()).ok_or_else(|| {
            ConfigManagementError::FileNameNotFound {
                path: file_path.clone(),
            }
        })?;

        Ok(Self {
            download_info: DownloadInfo {
                url: download_url.into(),
                auth: None,
            },
            file_path,
            tmp_dir,
            file_permissions,
            file_name,
        })
    }

    fn has_write_access(&self) -> Result<(), ConfigManagementError> {
        let metadata =
            if self.file_path.is_file() {
                get_metadata(&self.file_path)?
            } else {
                // If the file does not exist before downloading file, check the directory perms
                let parent_dir = &self.file_path.parent().ok_or_else(|| {
                    ConfigManagementError::NoWriteAccess {
                        path: self.file_path.clone(),
                    }
                })?;
                get_metadata(parent_dir)?
            };

        // Write permission check
        if metadata.permissions().readonly() {
            Err(ConfigManagementError::NoWriteAccess {
                path: self.file_path.clone(),
            })
        } else {
            Ok(())
        }
    }

    fn create_downloader(&self) -> Downloader {
        Downloader::new(&self.file_name, &None, &self.tmp_dir)
    }

    fn move_file(&self) -> Result<(), ConfigManagementError> {
        let src = &self.tmp_dir.join(&self.file_name);
        let dest = &self.file_path;

        let original_permission_mode = match self.file_path.is_file() {
            true => {
                let metadata = get_metadata(&self.file_path)?;
                let mode = metadata.permissions().mode();
                Some(mode)
            }
            false => None,
        };

        let _ = fs::copy(src, dest).map_err(|_| ConfigManagementError::FileCopyFailed {
            src: src.to_path_buf(),
            dest: dest.to_path_buf(),
        })?;

        let file_permissions = if let Some(mode) = original_permission_mode {
            // Use the same file permission as the original one
            PermissionEntry::new(None, None, Some(mode))
        } else {
            // Set the user, group, and mode as given for a new file
            self.file_permissions.clone()
        };

        let () = file_permissions.apply(&self.file_path)?;

        Ok(())
    }
}

pub fn get_file_change_notification_message(file_path: &str, config_type: &str) -> Message {
    let notification = json!({ "path": file_path }).to_string();
    let topic = Topic::new(format!("{CONFIG_CHANGE_TOPIC}/{config_type}").as_str())
        .unwrap_or_else(|_err| {
            warn!("The type cannot be used as a part of the topic name. Using {CONFIG_CHANGE_TOPIC} instead.");
            Topic::new_unchecked(CONFIG_CHANGE_TOPIC)
        });
    Message::new(&topic, notification)
}

struct DownloadConfigFileStatusMessage {}

impl TryIntoOperationStatusMessage for DownloadConfigFileStatusMessage {
    fn status_executing() -> Result<SmartRest, SmartRestSerializerError> {
        SmartRestSetOperationToExecuting::new(CumulocitySupportedOperations::C8yDownloadConfigFile)
            .to_smartrest()
    }

    fn status_successful(
        _parameter: Option<String>,
    ) -> Result<SmartRest, SmartRestSerializerError> {
        SmartRestSetOperationToSuccessful::new(CumulocitySupportedOperations::C8yDownloadConfigFile)
            .to_smartrest()
    }

    fn status_failed(failure_reason: String) -> Result<SmartRest, SmartRestSerializerError> {
        SmartRestSetOperationToFailed::new(
            </