ftdc 0.1.5

Crate to download ftdc data for mongodb clusters.
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#![allow(clippy::manual_try_fold)]
use std::env;
use std::fs::File;
use std::io;
use std::str::FromStr;
use std::thread;
use std::time;

use async_recursion::async_recursion;
use async_trait::async_trait;
use diqwest::DigestAuthSession;
use diqwest::WithDigestAuth;
use indicatif::ProgressBar;
use reqwest::Client;
use reqwest::StatusCode;

use crate::error::Error;
use crate::model::Clusters;
use crate::model::JobId;
use crate::model::JobState;
use crate::model::JobStatus;
use crate::model::LogCollectionJob;
use crate::model::Shard;
use crate::progress::SpinnerHelper;

const MONGODB_URL: &str = "https://cloud.mongodb.com/api/atlas/v1.0/groups";

#[async_trait]
pub trait FtdcLoader {
    async fn get_ftdc_data(
        &self,
        group_key: &str,
        replica_set_name: &str,
        byte_size: u64,
        public: &str,
        private: &str,
    ) -> Result<String, Error>;
}

pub struct FtdcDataService {
    pub client: Client,
    base_url: String,
}

impl FtdcDataService {
    pub fn new(client: Client) -> Self {
        Self { client, base_url: MONGODB_URL.to_string() }
    }

    #[cfg(test)]
    fn with_base_url(client: Client, base_url: String) -> Self {
        Self { client, base_url }
    }
}

#[async_trait]
impl FtdcLoader for FtdcDataService {
    async fn get_ftdc_data(
        &self,
        group_key: &str,
        replica_set_name: &str,
        byte_size: u64,
        public: &str,
        private: &str,
    ) -> Result<String, Error> {
        let session = DigestAuthSession::new(public, private);

        let replica_set = self
            .get_replica_set(group_key, replica_set_name, &session)
            .await?;
        let job_id = self
            .create_ftdc_job(group_key, &replica_set, byte_size, &session)
            .await?
            .id;

        let check_job_status_spinner =
            SpinnerHelper::create(format!("Check job status of job with id: {job_id}"));
        let _download_url = self
            .check_job_state(group_key, &job_id, &check_job_status_spinner?, &session)
            .await?;

        let download_ftdc_data_spinner = SpinnerHelper::create(format!(
            "Start to download FTDC data for job with id: {job_id}"
        ));

        self.download_ftdc_data(
            group_key,
            &job_id,
            &replica_set,
            &download_ftdc_data_spinner?,
            &session,
        )
        .await
    }
}

impl FtdcDataService {
    async fn get_replica_set(
        &self,
        group_key: &str,
        replica_set_name: &str,
        session: &DigestAuthSession,
    ) -> Result<String, Error> {
        let processes = self
            .client
            .get(format!("{}/{group_key}/processes", self.base_url))
            .send_digest_auth(session)
            .await?;

        match processes.status() {
            StatusCode::OK => {
                let response_body = processes.text().await?;
                let shards = serde_json::from_str::<Clusters>(&response_body)?.results;
                let shards: Vec<Shard> = shards
                    .into_iter()
                    .filter(|s| {
                        s.replica_set_name.is_some()
                            && (s.user_alias.contains(replica_set_name)
                                || s.replica_set_name == Some(replica_set_name.to_string()))
                    })
                    .collect();

                shards
                    .first()
                    .and_then(|s| s.replica_set_name.as_ref())
                    .iter()
                    .fold(
                        Err(Error::ReplicaSetNotFound(format!(
                            "No replica set found that corresponds to {replica_set_name}"
                        ))),
                        |_, s| Ok(s.to_string()),
                    )
            }
            _ => Err(Error::ReplicaSetNotFound(format!(
                "Something went wrong trying to get the list of running processes. Please try later. Currently running processes: {processes}",
                processes = processes.text().await?
            ))),
        }
    }

    async fn create_ftdc_job(
        &self,
        group_key: &str,
        replica_set: &str,
        byte_size: u64,
        session: &DigestAuthSession,
    ) -> Result<JobId, Error> {
        println!("Starting FTDC data job for ReplicaSet: {replica_set}");

        let create_ftdc_job = self
            .client
            .post(format!("{}/{group_key}/logCollectionJobs", self.base_url))
            .header("Content-type", "application/json; charset=utf-8")
            .json(&LogCollectionJob::from(replica_set, byte_size))
            .send_digest_auth(session)
            .await?;

        match create_ftdc_job.status() {
            StatusCode::CREATED => {
                let response_body = create_ftdc_job.text().await?;
                Ok(serde_json::from_str::<JobId>(&response_body)?)
            }
            _ => Err(Error::CreateJob(format!(
                "Something went wrong creating the FTDC job: {error}",
                error = create_ftdc_job.text().await?
            ))),
        }
    }

    #[async_recursion]
    async fn check_job_state(
        &self,
        group_key: &str,
        job_id: &str,
        spinner: &ProgressBar,
        session: &DigestAuthSession,
    ) -> Result<String, Error> {
        let check_job_status = self
            .client
            .get(format!(
                "{}/{group_key}/logCollectionJobs/{job_id}",
                self.base_url
            ))
            .send_digest_auth(session)
            .await?;

        match check_job_status.status() {
            StatusCode::OK => {
                let job_status = check_job_status.text().await?;
                let job_status = serde_json::from_str::<JobStatus>(&job_status)?;

                match JobState::from_str(job_status.status)? {
                    JobState::InProgress => {
                        spinner.set_message(format!("IN_PROGRESS – job id: {job_id}"));
                        thread::sleep(time::Duration::from_millis(3000));
                        self.check_job_state(group_key, job_id, spinner, session)
                            .await
                    }
                    JobState::Succcess | JobState::MarkedForExpiry => {
                        spinner.finish_with_message(format!(
                            "SUCCESS – FTDC data for job with id {job_id} will be downloaded."
                        ));
                        Ok(String::from(job_status.download_url))
                    }
                    JobState::Failure | JobState::Expired => {
                        spinner.abandon_with_message(format!(
                            "FAILURE – Something went wrong creating job with id {job_id}."
                        ));
                        Err(Error::MongoJob(
                            "Failure while job creation. Please try again.".to_string(),
                        ))
                    }
                }
            }
            _ => Err(Error::CheckJobStatus(format!(
                "Something went wrong checking the jobs status. Try again later. Error message: {error}",
                error = check_job_status.text().await?
            ))),
        }
    }

    async fn download_ftdc_data(
        &self,
        group_key: &str,
        job_id: &str,
        replica_set: &str,
        spinner: &ProgressBar,
        session: &DigestAuthSession,
    ) -> Result<String, Error> {
        let download_url = format!(
            "{}/{group_key}/logCollectionJobs/{job_id}/download",
            self.base_url
        );
        let response = self
            .client
            .get(&download_url)
            .send_digest_auth(session)
            .await?;

        match response.status() {
            StatusCode::OK => {
                spinner.set_message(format!(
                    "PROGRESS – Download FTDC data for job with id: {job_id}"
                ));

                let bytes = response.bytes().await?;
                let mut slice: &[u8] = bytes.as_ref();
                let file_name = format!("ftdc_data_{replica_set}_job_{job_id}.tar.gz");
                let file_name = file_name.as_str();
                let mut out = File::create(file_name)?;
                io::copy(&mut slice, &mut out)?;

                spinner.finish_with_message(format!(
                    "SUCCESS – FTDC data for job with id {job_id} downloaded."
                ));

                Ok(format!(
                    "{current_dir}/{file_name}",
                    current_dir = env::current_dir()?.display()
                ))
            }
            _ => Err(Error::Download(format!(
                "Something went wrong downloading the FTDC data. Try to download at: {url}. Status code: {status}. Body: {body}",
                url = download_url,
                status = response.status(),
                body = response.text().await?
            ))),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::model::Clusters;
    use crate::model::JobId;
    use crate::model::JobStatus;
    use crate::model::Shard;
    use crate::service::FtdcDataService;
    use diqwest::DigestAuthSession;
    use indicatif::ProgressBar;
    use mockito::Server;
    use reqwest::Client;

    fn ftdc_data_service(base_url: String) -> FtdcDataService {
        FtdcDataService::with_base_url(Client::new(), base_url)
    }

    #[tokio::test]
    async fn given_explicit_replica_set_name_when_get_replica_set_then_get_the_same_name() {
        // Given
        let mut server = Server::new_async().await;
        let clusters = Clusters {
            results: vec![Shard {
                user_alias: "something that does not matter".to_string(),
                type_name: "".to_string(),
                replica_set_name: Some("my-replica-set".to_string()),
            }],
        };
        let _m = server
            .mock("GET", "/my-group-key/processes")
            .with_status(200)
            .with_header("content-type", "application/json; charset=utf-8")
            .with_body(serde_json::to_string(&clusters).unwrap())
            .create_async()
            .await;
        let session = DigestAuthSession::new("", "");

        // When
        let response = ftdc_data_service(server.url())
            .get_replica_set("my-group-key", "my-replica-set", &session)
            .await
            .unwrap();

        // Then
        assert_eq!(&response, "my-replica-set");
    }

    #[tokio::test]
    async fn given_shard_name_when_get_replica_set_then_get_corresponding_replica_set() {
        // Given
        let mut server = Server::new_async().await;
        let clusters = Clusters {
            results: vec![Shard {
                user_alias: "my-rs-shard-00".to_string(),
                type_name: "".to_string(),
                replica_set_name: Some("my-replica-set".to_string()),
            }],
        };
        let _m = server
            .mock("GET", "/my-group-key/processes")
            .with_status(200)
            .with_header("content-type", "application/json; charset=utf-8")
            .with_body(serde_json::to_string(&clusters).unwrap())
            .create_async()
            .await;
        let session = DigestAuthSession::new("", "");

        // When
        let response = ftdc_data_service(server.url())
            .get_replica_set("my-group-key", "my-rs-shard-00", &session)
            .await
            .unwrap();

        // Then
        assert_eq!(&response, "my-replica-set");
    }

    #[tokio::test]
    async fn given_wrong_name_when_get_replica_set_then_no_rs_error() {
        // Given
        let mut server = Server::new_async().await;
        let clusters = Clusters {
            results: vec![Shard {
                user_alias: "my-rs-shard-00".to_string(),
                type_name: "".to_string(),
                replica_set_name: Some("my-replica-set".to_string()),
            }],
        };
        let _m = server
            .mock("GET", "/my-group-key/processes")
            .with_status(200)
            .with_header("content-type", "application/json; charset=utf-8")
            .with_body(serde_json::to_string(&clusters).unwrap())
            .create_async()
            .await;
        let session = DigestAuthSession::new("", "");

        // When
        let replica_set_not_found_error = ftdc_data_service(server.url())
            .get_replica_set("my-group-key", "another-rs-shard-00", &session)
            .await
            .unwrap_err()
            .to_string();

        // Then
        assert_eq!(
            replica_set_not_found_error,
            "No replica set found that corresponds to another-rs-shard-00"
        );
    }

    #[tokio::test]
    async fn given_no_processes_in_the_given_group_when_get_replica_set_then_no_rs_error() {
        // Given
        let mut server = Server::new_async().await;
        let clusters = Clusters { results: vec![] };
        let _m = server
            .mock("GET", "/my-group-key/processes")
            .with_status(200)
            .with_header("content-type", "application/json; charset=utf-8")
            .with_body(serde_json::to_string(&clusters).unwrap())
            .create_async()
            .await;
        let session = DigestAuthSession::new("", "");

        // When
        let replica_set_not_found_error = ftdc_data_service(server.url())
            .get_replica_set("my-group-key", "another-rs-shard-00", &session)
            .await
            .unwrap_err()
            .to_string();

        // Then
        assert_eq!(
            replica_set_not_found_error,
            "No replica set found that corresponds to another-rs-shard-00"
        );
    }

    #[tokio::test]
    async fn given_replica_set_when_create_ftdc_job_then_give_job_id() {
        // Given
        let mut server = Server::new_async().await;
        let job_id = JobId { id: String::from("new-job-id-73") };
        let _m = server
            .mock("POST", "/my-group-key/logCollectionJobs")
            .with_status(201)
            .with_header("content-type", "application/json; charset=utf-8")
            .with_body(serde_json::to_string(&job_id).unwrap())
            .create_async()
            .await;
        let session = DigestAuthSession::new("", "");

        // When
        let response = ftdc_data_service(server.url())
            .create_ftdc_job("my-group-key", "another-rs-shard-00", 10, &session)
            .await
            .unwrap();

        // Then
        assert_eq!(response, JobId { id: String::from("new-job-id-73") });
    }

    #[tokio::test]
    async fn given_job_id_when_check_job_state_then_give_success() {
        // Given
        let mut server = Server::new_async().await;
        let job_id = "new-job-id-73";
        let job_status =
            JobStatus { id: "any id", download_url: "download from here", status: "SUCCESS" };
        let spinner = ProgressBar::new_spinner();
        let _m = server
            .mock("GET", "/my-group-key/logCollectionJobs/new-job-id-73")
            .with_status(200)
            .with_header("content-type", "application/json; charset=utf-8")
            .with_body(serde_json::to_string(&job_status).unwrap())
            .create_async()
            .await;
        let session = DigestAuthSession::new("", "");

        // When
        let response = ftdc_data_service(server.url())
            .check_job_state("my-group-key", job_id, &spinner, &session)
            .await
            .unwrap();

        // Then
        assert_eq!(response, String::from("download from here"));
    }
}