csm-rs 0.43.22

A library for Shasta
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/// struct representing CSM API payload related to CFS configuration

pub mod v2 {

    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize, Clone, Default)]
    pub struct Layer {
        pub name: String,
        #[serde(rename = "cloneUrl")]
        pub clone_url: String,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub commit: Option<String>,
        pub playbook: String,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub branch: Option<String>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone, Default)]
    pub struct AdditionalInventory {
        #[serde(rename = "cloneUrl")]
        pub clone_url: String,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub commit: Option<String>,
        pub name: String,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub branch: Option<String>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone)]
    pub struct CfsConfigurationResponse {
        pub name: String,
        #[serde(rename = "lastUpdated")]
        pub last_updated: String,
        pub layers: Vec<Layer>,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub additional_inventory: Option<AdditionalInventory>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone)]
    pub struct CfsConfigurationVecResponse {
        pub configurations: Vec<CfsConfigurationResponse>,
        pub next: Option<Next>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone)]
    pub struct Next {
        limit: Option<u8>,
        after_id: Option<String>,
        in_use: Option<bool>,
    }

    impl Layer {
        pub fn new(
            clone_url: String,
            // source: Option<String>,
            commit: Option<String>,
            name: String,
            playbook: String,
            branch: Option<String>,
        ) -> Self {
            Self {
                clone_url,
                // source,
                commit,
                name,
                playbook,
                branch,
            }
        }
    }

    impl AdditionalInventory {
        pub fn new(
            clone_url: String,
            commit: Option<String>,
            name: String,
            branch: Option<String>,
        ) -> Self {
            Self {
                clone_url,
                commit,
                name,
                branch,
            }
        }
    }

    impl Default for CfsConfigurationResponse {
        fn default() -> Self {
            Self::new()
        }
    }

    impl CfsConfigurationResponse {
        pub fn new() -> Self {
            Self {
                name: String::default(),
                last_updated: String::default(),
                layers: Vec::default(),
                additional_inventory: None,
            }
        }

        pub fn add_layer(&mut self, layer: Layer) {
            self.layers.push(layer);
        }

        pub fn from_sat_file_serde_yaml(configuration_yaml: &serde_yaml::Value) -> Self {
            let mut cfs_configuration = Self::new();

            cfs_configuration.name = configuration_yaml["name"].as_str().unwrap().to_string();

            for layer_yaml in configuration_yaml["layers"].as_sequence().unwrap() {
                // println!("\n\n### Layer:\n{:#?}\n", layer_json);

                if layer_yaml.get("git").is_some() {
                    // Git layer
                    let repo_name = layer_yaml["name"].as_str().unwrap().to_string();
                    let repo_url = layer_yaml["git"]["url"].as_str().unwrap().to_string();
                    let layer = Layer::new(
                        repo_url,
                        // None, // TODO: replace with real source value
                        // Some(layer_json["git"]["commit"].as_str().unwrap_or_default().to_string()),
                        None,
                        repo_name,
                        layer_yaml["playbook"]
                            .as_str()
                            .unwrap_or_default()
                            .to_string(),
                        Some(
                            layer_yaml["git"]["branch"]
                                .as_str()
                                .unwrap_or_default()
                                .to_string(),
                        ),
                    );
                    cfs_configuration.add_layer(layer);
                } else {
                    // Product layer
                    let repo_url = format!(
                        "https://api-gw-service-nmn.local/vcs/cray/{}-config-management.git",
                        layer_yaml["name"].as_str().unwrap()
                    );
                    let layer = Layer::new(
                        repo_url,
                        // None, // TODO: replace with real source value
                        // Some(layer_json["product"]["commit"].as_str().unwrap_or_default().to_string()),
                        None,
                        layer_yaml["product"]["name"]
                            .as_str()
                            .unwrap_or_default()
                            .to_string(),
                        layer_yaml["playbook"].as_str().unwrap().to_string(),
                        Some(
                            layer_yaml["product"]["branch"]
                                .as_str()
                                .unwrap_or_default()
                                .to_string(),
                        ),
                    );
                    cfs_configuration.add_layer(layer);
                }
            }
            cfs_configuration
        }

        /* pub async fn create_from_repos(
            gitea_token: &str,
            gitea_base_url: &str,
            shasta_root_cert: &[u8],
            repos: Vec<PathBuf>,
            cfs_configuration_name: &String,
        ) -> Self {
            // Create CFS configuration
            let mut cfs_configuration = CfsConfigurationResponse::new();
            cfs_configuration.name = cfs_configuration_name.to_string();

            for repo_path in &repos {
                // Get repo from path
                let repo = match local_git_repo::get_repo(&repo_path.to_string_lossy()) {
                    Ok(repo) => repo,
                    Err(_) => {
                        eprintln!(
                            "Could not find a git repo in {}",
                            repo_path.to_string_lossy()
                        );
                        std::process::exit(1);
                    }
                };

                // Get last (most recent) commit
                let local_last_commit = local_git_repo::get_last_commit(&repo).unwrap();

                // Get repo name
                let repo_ref_origin = repo.find_remote("origin").unwrap();

                log::info!("Repo ref origin URL: {}", repo_ref_origin.url().unwrap());

                let repo_ref_origin_url = repo_ref_origin.url().unwrap();

                let repo_name = repo_ref_origin_url.substring(
                    repo_ref_origin_url.rfind(|c| c == '/').unwrap() + 1, // repo name should not include URI '/' separator
                    repo_ref_origin_url.len(), // repo_ref_origin_url.rfind(|c| c == '.').unwrap(),
                );

                let api_url = "cray/".to_owned() + repo_name;

                // Check if repo and local commit id exists in Shasta cvs
                let shasta_commitid_details_resp =
                    gitea::http_client::get_commit_details_from_internal_url(
                        &api_url,
                        // &format!("/cray/{}", repo_name),
                        &local_last_commit.id().to_string(),
                        gitea_token,
                        shasta_root_cert,
                    )
                    .await;

                // Check sync status between user face and shasta VCS
                let shasta_commitid_details: serde_json::Value = match shasta_commitid_details_resp
                {
                    Ok(_) => {
                        log::debug!(
                            "Local latest commit id {} for repo {} exists in shasta",
                            local_last_commit.id(),
                            repo_name
                        );
                        shasta_commitid_details_resp.unwrap()
                    }
                    Err(e) => {
                        eprintln!("{}", e);
                        std::process::exit(1);
                    }
                };

                let clone_url = gitea_base_url.to_owned() + "/cray/" + repo_name;

                // Create CFS layer
                let cfs_layer = Layer::new(
                    clone_url,
                    None, // TODO: replace with real source value
                    Some(shasta_commitid_details["sha"].as_str().unwrap().to_string()),
                    format!(
                        "{}-{}",
                        repo_name.substring(0, repo_name.len()),
                        chrono::offset::Local::now()
                            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
                    ),
                    String::from("site.yml"),
                    None,
                );

                CfsConfigurationResponse::add_layer(&mut cfs_configuration, cfs_layer);
            }

            cfs_configuration
        } */
    }
}

pub mod v3 {

    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize, Clone, Default)] // TODO: investigate why serde can Deserialize dynamically syzed structs `Vec<Layer>`
    pub struct Layer {
        pub name: String,
        // #[serde(rename = "cloneUrl")]
        pub clone_url: String,
        pub source: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub commit: Option<String>,
        pub playbook: String,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub branch: Option<String>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone, Default)] // TODO: investigate why serde can Deserialize dynamically syzed structs `Vec<Layer>`
    pub struct AdditionalInventory {
        #[serde(rename = "cloneUrl")]
        pub clone_url: String,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub commit: Option<String>,
        pub name: String,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub branch: Option<String>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone)] // TODO: investigate why serde can Deserialize dynamically syzed structs `Vec<Layer>`
    pub struct CfsConfigurationResponse {
        pub name: String,
        // #[serde(rename = "lastUpdated")]
        pub last_updated: String,
        pub layers: Vec<Layer>,
        #[serde(skip_serializing_if = "Option::is_none")] // Either commit or branch is passed
        pub additional_inventory: Option<AdditionalInventory>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone)] // TODO: investigate why serde can Deserialize dynamically syzed structs `Vec<Layer>`
    pub struct CfsConfigurationVecResponse {
        pub configurations: Vec<CfsConfigurationResponse>,
        pub next: Option<Next>,
    }

    #[derive(Debug, Serialize, Deserialize, Clone)] // TODO: investigate why serde can Deserialize dynamically syzed structs `Vec<Layer>`
    pub struct Next {
        limit: Option<u8>,
        after_id: Option<String>,
        in_use: Option<bool>,
    }

    impl Layer {
        pub fn new(
            clone_url: String,
            source: Option<String>,
            commit: Option<String>,
            name: String,
            playbook: String,
            branch: Option<String>,
        ) -> Self {
            Self {
                clone_url,
                source,
                commit,
                name,
                playbook,
                branch,
            }
        }
    }

    impl AdditionalInventory {
        pub fn new(
            clone_url: String,
            commit: Option<String>,
            name: String,
            branch: Option<String>,
        ) -> Self {
            Self {
                clone_url,
                commit,
                name,
                branch,
            }
        }
    }

    impl Default for CfsConfigurationResponse {
        fn default() -> Self {
            Self::new()
        }
    }

    impl CfsConfigurationResponse {
        pub fn new() -> Self {
            Self {
                name: String::default(),
                last_updated: String::default(),
                layers: Vec::default(),
                additional_inventory: None,
            }
        }

        pub fn add_layer(&mut self, layer: Layer) {
            self.layers.push(layer);
        }

        pub fn from_sat_file_serde_yaml(configuration_yaml: &serde_yaml::Value) -> Self {
            let mut cfs_configuration = Self::new();

            cfs_configuration.name = configuration_yaml["name"].as_str().unwrap().to_string();

            for layer_yaml in configuration_yaml["layers"].as_sequence().unwrap() {
                // println!("\n\n### Layer:\n{:#?}\n", layer_json);

                if layer_yaml.get("git").is_some() {
                    // Git layer
                    let repo_name = layer_yaml["name"].as_str().unwrap().to_string();
                    let repo_url = layer_yaml["git"]["url"].as_str().unwrap().to_string();
                    let layer = Layer::new(
                        repo_url,
                        None, // TODO: replace with real source value
                        // Some(layer_json["git"]["commit"].as_str().unwrap_or_default().to_string()),
                        None,
                        repo_name,
                        layer_yaml["playbook"]
                            .as_str()
                            .unwrap_or_default()
                            .to_string(),
                        Some(
                            layer_yaml["git"]["branch"]
                                .as_str()
                                .unwrap_or_default()
                                .to_string(),
                        ),
                    );
                    cfs_configuration.add_layer(layer);
                } else {
                    // Product layer
                    let repo_url = format!(
                        "https://api-gw-service-nmn.local/vcs/cray/{}-config-management.git",
                        layer_yaml["name"].as_str().unwrap()
                    );
                    let layer = Layer::new(
                        repo_url,
                        None, // TODO: replace with real source value
                        // Some(layer_json["product"]["commit"].as_str().unwrap_or_default().to_string()),
                        None,
                        layer_yaml["product"]["name"]
                            .as_str()
                            .unwrap_or_default()
                            .to_string(),
                        layer_yaml["playbook"].as_str().unwrap().to_string(),
                        Some(
                            layer_yaml["product"]["branch"]
                                .as_str()
                                .unwrap_or_default()
                                .to_string(),
                        ),
                    );
                    cfs_configuration.add_layer(layer);
                }
            }
            cfs_configuration
        }

        /* pub async fn create_from_repos(
            gitea_token: &str,
            gitea_base_url: &str,
            shasta_root_cert: &[u8],
            repos: Vec<PathBuf>,
            cfs_configuration_name: &String,
        ) -> Self {
            // Create CFS configuration
            let mut cfs_configuration = CfsConfigurationResponse::new();
            cfs_configuration.name = cfs_configuration_name.to_string();

            for repo_path in &repos {
                // Get repo from path
                let repo = match local_git_repo::get_repo(&repo_path.to_string_lossy()) {
                    Ok(repo) => repo,
                    Err(_) => {
                        eprintln!(
                            "Could not find a git repo in {}",
                            repo_path.to_string_lossy()
                        );
                        std::process::exit(1);
                    }
                };

                // Get last (most recent) commit
                let local_last_commit = local_git_repo::get_last_commit(&repo).unwrap();

                // Get repo name
                let repo_ref_origin = repo.find_remote("origin").unwrap();

                log::info!("Repo ref origin URL: {}", repo_ref_origin.url().unwrap());

                let repo_ref_origin_url = repo_ref_origin.url().unwrap();

                let repo_name = repo_ref_origin_url.substring(
                    repo_ref_origin_url.rfind(|c| c == '/').unwrap() + 1, // repo name should not include URI '/' separator
                    repo_ref_origin_url.len(), // repo_ref_origin_url.rfind(|c| c == '.').unwrap(),
                );

                let api_url = "cray/".to_owned() + repo_name;

                // Check if repo and local commit id exists in Shasta cvs
                let shasta_commitid_details_resp =
                    gitea::http_client::get_commit_details_from_internal_url(
                        &api_url,
                        // &format!("/cray/{}", repo_name),
                        &local_last_commit.id().to_string(),
                        gitea_token,
                        shasta_root_cert,
                    )
                    .await;

                // Check sync status between user face and shasta VCS
                let shasta_commitid_details: serde_json::Value = match shasta_commitid_details_resp
                {
                    Ok(_) => {
                        log::debug!(
                            "Local latest commit id {} for repo {} exists in shasta",
                            local_last_commit.id(),
                            repo_name
                        );
                        shasta_commitid_details_resp.unwrap()
                    }
                    Err(e) => {
                        eprintln!("{}", e);
                        std::process::exit(1);
                    }
                };

                let clone_url = gitea_base_url.to_owned() + "/cray/" + repo_name;

                // Create CFS layer
                let cfs_layer = Layer::new(
                    clone_url,
                    None, // TODO: replace with real source value
                    Some(shasta_commitid_details["sha"].as_str().unwrap().to_string()),
                    format!(
                        "{}-{}",
                        repo_name.substring(0, repo_name.len()),
                        chrono::offset::Local::now()
                            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
                    ),
                    String::from("site.yml"),
                    None,
                );

                CfsConfigurationResponse::add_layer(&mut cfs_configuration, cfs_layer);
            }

            cfs_configuration
        } */
    }
}