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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
// Copyright 2022 Alibaba Cloud. All rights reserved.
// Copyright 2020 Ant Group. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::fs;
use std::io::{Error, ErrorKind, Result};
use std::path::Path;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use serde::Deserialize;
use serde_json::Value;

/// Configuration file format version 2, based on Toml.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ConfigV2 {
    /// Configuration file format version number, must be 2.
    pub version: u32,
    /// Identifier for the instance.
    #[serde(default)]
    pub id: String,
    /// Configuration information for storage backend.
    pub backend: Option<BackendConfigV2>,
    /// Configuration information for local cache system.
    pub cache: Option<CacheConfigV2>,
    /// Configuration information for RAFS filesystem.
    pub rafs: Option<RafsConfigV2>,
    /// Internal runtime configuration.
    #[serde(skip)]
    pub internal: ConfigV2Internal,
}

impl Default for ConfigV2 {
    fn default() -> Self {
        ConfigV2 {
            version: 2,
            id: String::new(),
            backend: None,
            cache: None,
            rafs: None,
            internal: ConfigV2Internal::default(),
        }
    }
}

impl ConfigV2 {
    /// Create a new instance of `ConfigV2` object.
    pub fn new(id: &str) -> Self {
        ConfigV2 {
            version: 2,
            id: id.to_string(),
            backend: None,
            cache: None,
            rafs: None,
            internal: ConfigV2Internal::default(),
        }
    }

    /// Create a new configuration object for `backend-localfs` and `filecache`.
    pub fn new_localfs(id: &str, dir: &str) -> Result<Self> {
        let content = format!(
            r#"
        version = 2
        id = "{}"
        backend.type = "localfs"
        backend.localfs.dir = "{}"
        cache.type = "filecache"
        cache.compressed = false
        cache.validate = false
        cache.filecache.work_dir = "{}"
        "#,
            id, dir, dir
        );

        Self::from_str(&content)
    }

    /// Read configuration information from a file.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let md = fs::metadata(path.as_ref())?;
        if md.len() > 0x100000 {
            return Err(eother!("configuration file size is too big"));
        }
        let content = fs::read_to_string(path)?;
        Self::from_str(&content)
    }

    /// Validate the configuration object.
    pub fn validate(&self) -> bool {
        if self.version != 2 {
            return false;
        }
        if let Some(backend_cfg) = self.backend.as_ref() {
            if !backend_cfg.validate() {
                return false;
            }
        }
        if let Some(cache_cfg) = self.cache.as_ref() {
            if !cache_cfg.validate() {
                return false;
            }
        }
        if let Some(rafs_cfg) = self.rafs.as_ref() {
            if !rafs_cfg.validate() {
                return false;
            }
        }

        true
    }

    /// Get configuration information for storage backend.
    pub fn get_backend_config(&self) -> Result<&BackendConfigV2> {
        self.backend
            .as_ref()
            .ok_or_else(|| einval!("no configuration information for backend"))
    }

    /// Get configuration information for cache subsystem.
    pub fn get_cache_config(&self) -> Result<&CacheConfigV2> {
        self.cache
            .as_ref()
            .ok_or_else(|| einval!("no configuration information for cache"))
    }

    /// Get cache working directory.
    pub fn get_cache_working_directory(&self) -> Result<String> {
        let cache = self.get_cache_config()?;
        match cache.cache_type.as_str() {
            "blobcache" | "filecache" => {
                if let Some(c) = cache.file_cache.as_ref() {
                    return Ok(c.work_dir.clone());
                }
            }
            "fscache" => {
                if let Some(c) = cache.fs_cache.as_ref() {
                    return Ok(c.work_dir.clone());
                }
            }
            _ => {}
        }

        Err(Error::new(
            ErrorKind::NotFound,
            "no working directory configured",
        ))
    }

    /// Get configuration information for RAFS filesystem.
    pub fn get_rafs_config(&self) -> Result<&RafsConfigV2> {
        self.rafs.as_ref().ok_or_else(|| {
            Error::new(
                ErrorKind::InvalidInput,
                "no configuration information for rafs",
            )
        })
    }

    /// Clone the object with all secrets removed.
    pub fn clone_without_secrets(&self) -> Self {
        let mut cfg = self.clone();

        if let Some(backend_cfg) = cfg.backend.as_mut() {
            if let Some(oss_cfg) = backend_cfg.oss.as_mut() {
                oss_cfg.access_key_id = String::new();
                oss_cfg.access_key_secret = String::new();
            }
            if let Some(registry_cfg) = backend_cfg.registry.as_mut() {
                registry_cfg.auth = None;
                registry_cfg.registry_token = None;
            }
        }

        cfg
    }

    /// Check whether chunk digest validation is enabled or not.
    pub fn is_chunk_validation_enabled(&self) -> bool {
        let mut validation = if let Some(cache) = &self.cache {
            cache.cache_validate
        } else {
            false
        };
        if let Some(rafs) = &self.rafs {
            if rafs.validate {
                validation = true;
            }
        }

        validation
    }

    /// Check whether fscache is enabled or not.
    pub fn is_fs_cache(&self) -> bool {
        if let Some(cache) = self.cache.as_ref() {
            cache.fs_cache.is_some()
        } else {
            false
        }
    }
}

impl FromStr for ConfigV2 {
    type Err = std::io::Error;

    fn from_str(s: &str) -> Result<ConfigV2> {
        if let Ok(v) = serde_json::from_str::<ConfigV2>(s) {
            return if v.validate() {
                Ok(v)
            } else {
                Err(einval!("invalid configuration"))
            };
        }
        if let Ok(v) = toml::from_str::<ConfigV2>(s) {
            return if v.validate() {
                Ok(v)
            } else {
                Err(einval!("invalid configuration"))
            };
        }
        if let Ok(v) = serde_json::from_str::<RafsConfig>(s) {
            if let Ok(v) = ConfigV2::try_from(v) {
                if v.validate() {
                    return Ok(v);
                }
            }
        }
        Err(einval!("failed to parse configuration information"))
    }
}

/// Configuration information for storage backend.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct BackendConfigV2 {
    /// Type of storage backend.
    #[serde(rename = "type")]
    pub backend_type: String,
    /// Configuration for local disk backend.
    pub localdisk: Option<LocalDiskConfig>,
    /// Configuration for local filesystem backend.
    pub localfs: Option<LocalFsConfig>,
    /// Configuration for OSS backend.
    pub oss: Option<OssConfig>,
    /// Configuration for S3 backend.
    pub s3: Option<S3Config>,
    /// Configuration for container registry backend.
    pub registry: Option<RegistryConfig>,
    /// Configuration for local http proxy.
    pub http_proxy: Option<HttpProxyConfig>,
}

impl BackendConfigV2 {
    /// Validate storage backend configuration.
    pub fn validate(&self) -> bool {
        match self.backend_type.as_str() {
            "localdisk" => match self.localdisk.as_ref() {
                Some(v) => {
                    if v.device_path.is_empty() {
                        return false;
                    }
                }
                None => return false,
            },
            "localfs" => match self.localfs.as_ref() {
                Some(v) => {
                    if v.blob_file.is_empty() && v.dir.is_empty() {
                        return false;
                    }
                }
                None => return false,
            },
            "oss" => match self.oss.as_ref() {
                Some(v) => {
                    if v.endpoint.is_empty() || v.bucket_name.is_empty() {
                        return false;
                    }
                }
                None => return false,
            },
            "s3" => match self.s3.as_ref() {
                Some(v) => {
                    if v.region.is_empty() || v.bucket_name.is_empty() {
                        return false;
                    }
                }
                None => return false,
            },
            "registry" => match self.registry.as_ref() {
                Some(v) => {
                    if v.host.is_empty() || v.repo.is_empty() {
                        return false;
                    }
                }
                None => return false,
            },

            "http-proxy" => match self.http_proxy.as_ref() {
                Some(v) => {
                    let is_valid_unix_socket_path = |path: &str| {
                        let path = Path::new(path);
                        path.is_absolute() && path.exists()
                    };
                    if v.addr.is_empty()
                        || !(v.addr.starts_with("http://")
                            || v.addr.starts_with("https://")
                            || is_valid_unix_socket_path(&v.addr))
                    {
                        return false;
                    }

                    // check if v.path is valid url path format
                    if Path::new(&v.path).join("any_blob_id").to_str().is_none() {
                        return false;
                    }
                }
                None => return false,
            },
            _ => return false,
        }

        true
    }

    /// Get configuration information for localdisk
    pub fn get_localdisk_config(&self) -> Result<&LocalDiskConfig> {
        if &self.backend_type != "localdisk" {
            Err(einval!("backend type is not 'localdisk'"))
        } else {
            self.localdisk
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for localdisk"))
        }
    }

    /// Get configuration information for localfs
    pub fn get_localfs_config(&self) -> Result<&LocalFsConfig> {
        if &self.backend_type != "localfs" {
            Err(einval!("backend type is not 'localfs'"))
        } else {
            self.localfs
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for localfs"))
        }
    }

    /// Get configuration information for OSS
    pub fn get_oss_config(&self) -> Result<&OssConfig> {
        if &self.backend_type != "oss" {
            Err(einval!("backend type is not 'oss'"))
        } else {
            self.oss
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for OSS"))
        }
    }

    /// Get configuration information for S3
    pub fn get_s3_config(&self) -> Result<&S3Config> {
        if &self.backend_type != "s3" {
            Err(einval!("backend type is not 's3'"))
        } else {
            self.s3
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for s3"))
        }
    }

    /// Get configuration information for Registry
    pub fn get_registry_config(&self) -> Result<&RegistryConfig> {
        if &self.backend_type != "registry" {
            Err(einval!("backend type is not 'registry'"))
        } else {
            self.registry
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for registry"))
        }
    }

    /// Get configuration information for http proxy
    pub fn get_http_proxy_config(&self) -> Result<&HttpProxyConfig> {
        if &self.backend_type != "http-proxy" {
            Err(einval!("backend type is not 'http-proxy'"))
        } else {
            self.http_proxy
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for http-proxy"))
        }
    }
}

/// Configuration information for localdisk storage backend.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct LocalDiskConfig {
    /// Mounted block device path or original localdisk image file path.
    #[serde(default)]
    pub device_path: String,
}

/// Configuration information for localfs storage backend.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct LocalFsConfig {
    /// Blob file to access.
    #[serde(default)]
    pub blob_file: String,
    /// Dir to hold blob files. Used when 'blob_file' is not specified.
    #[serde(default)]
    pub dir: String,
    /// Alternative dirs to search for blobs.
    #[serde(default)]
    pub alt_dirs: Vec<String>,
}

/// OSS configuration information to access blobs.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct OssConfig {
    /// Oss http scheme, either 'http' or 'https'
    #[serde(default = "default_http_scheme")]
    pub scheme: String,
    /// Oss endpoint
    pub endpoint: String,
    /// Oss bucket name
    pub bucket_name: String,
    /// Prefix object_prefix to OSS object key, for example the simulation of subdirectory:
    /// - object_key: sha256:xxx
    /// - object_prefix: nydus/
    /// - object_key with object_prefix: nydus/sha256:xxx
    #[serde(default)]
    pub object_prefix: String,
    /// Oss access key
    #[serde(default)]
    pub access_key_id: String,
    /// Oss secret
    #[serde(default)]
    pub access_key_secret: String,
    /// Skip SSL certificate validation for HTTPS scheme.
    #[serde(default)]
    pub skip_verify: bool,
    /// Drop the read request once http request timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub timeout: u32,
    /// Drop the read request once http connection timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub connect_timeout: u32,
    /// Retry count when read request failed.
    #[serde(default)]
    pub retry_limit: u8,
    /// Enable HTTP proxy for the read request.
    #[serde(default)]
    pub proxy: ProxyConfig,
    /// Enable mirrors for the read request.
    #[serde(default)]
    pub mirrors: Vec<MirrorConfig>,
}

/// S3 configuration information to access blobs.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct S3Config {
    /// S3 http scheme, either 'http' or 'https'
    #[serde(default = "default_http_scheme")]
    pub scheme: String,
    /// S3 endpoint
    pub endpoint: String,
    /// S3 region
    pub region: String,
    /// S3 bucket name
    pub bucket_name: String,
    /// Prefix object_prefix to S3 object key, for example the simulation of subdirectory:
    /// - object_key: sha256:xxx
    /// - object_prefix: nydus/
    /// - object_key with object_prefix: nydus/sha256:xxx
    #[serde(default)]
    pub object_prefix: String,
    /// S3 access key
    #[serde(default)]
    pub access_key_id: String,
    /// S3 secret
    #[serde(default)]
    pub access_key_secret: String,
    /// Skip SSL certificate validation for HTTPS scheme.
    #[serde(default)]
    pub skip_verify: bool,
    /// Drop the read request once http request timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub timeout: u32,
    /// Drop the read request once http connection timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub connect_timeout: u32,
    /// Retry count when read request failed.
    #[serde(default)]
    pub retry_limit: u8,
    /// Enable HTTP proxy for the read request.
    #[serde(default)]
    pub proxy: ProxyConfig,
    /// Enable mirrors for the read request.
    #[serde(default)]
    pub mirrors: Vec<MirrorConfig>,
}

/// Http proxy configuration information to access blobs.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct HttpProxyConfig {
    /// Address of http proxy server, like `http://xxx.xxx` or `https://xxx.xxx` or `/path/to/unix.sock`.
    pub addr: String,
    /// Path to access the blobs, like `/<_namespace>/<_repo>/blobs`.
    /// If the http proxy server is over unix socket, this field will be ignored.
    #[serde(default)]
    pub path: String,
    /// Skip SSL certificate validation for HTTPS scheme.
    #[serde(default)]
    pub skip_verify: bool,
    /// Drop the read request once http request timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub timeout: u32,
    /// Drop the read request once http connection timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub connect_timeout: u32,
    /// Retry count when read request failed.
    #[serde(default)]
    pub retry_limit: u8,
    /// Enable HTTP proxy for the read request.
    #[serde(default)]
    pub proxy: ProxyConfig,
    /// Enable mirrors for the read request.
    #[serde(default)]
    pub mirrors: Vec<MirrorConfig>,
}

/// Container registry configuration information to access blobs.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct RegistryConfig {
    /// Registry http scheme, either 'http' or 'https'
    #[serde(default = "default_http_scheme")]
    pub scheme: String,
    /// Registry url host
    pub host: String,
    /// Registry image name, like 'library/ubuntu'
    pub repo: String,
    /// Base64_encoded(username:password), the field should be sent to registry auth server to get a bearer token.
    #[serde(default)]
    pub auth: Option<String>,
    /// Skip SSL certificate validation for HTTPS scheme.
    #[serde(default)]
    pub skip_verify: bool,
    /// Drop the read request once http request timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub timeout: u32,
    /// Drop the read request once http connection timeout, in seconds.
    #[serde(default = "default_http_timeout")]
    pub connect_timeout: u32,
    /// Retry count when read request failed.
    #[serde(default)]
    pub retry_limit: u8,
    /// The field is a bearer token to be sent to registry to authorize registry requests.
    #[serde(default)]
    pub registry_token: Option<String>,
    /// The http scheme to access blobs. It is used to workaround some P2P subsystem
    /// that requires a different scheme than the registry.
    #[serde(default)]
    pub blob_url_scheme: String,
    /// Redirect blob access to a different host regardless of the one specified in 'host'.
    #[serde(default)]
    pub blob_redirected_host: String,
    /// Enable HTTP proxy for the read request.
    #[serde(default)]
    pub proxy: ProxyConfig,
    /// Enable mirrors for the read request.
    #[serde(default)]
    pub mirrors: Vec<MirrorConfig>,
}

/// Configuration information for blob cache manager.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct CacheConfigV2 {
    /// Type of blob cache: "blobcache", "fscache" or "dummy"
    #[serde(default, rename = "type")]
    pub cache_type: String,
    /// Whether the data from the cache is compressed, not used anymore.
    #[serde(default, rename = "compressed")]
    pub cache_compressed: bool,
    /// Whether to validate data read from the cache.
    #[serde(default, rename = "validate")]
    pub cache_validate: bool,
    /// Configuration for blob level prefetch.
    #[serde(default)]
    pub prefetch: PrefetchConfigV2,
    /// Configuration information for file cache
    #[serde(rename = "filecache")]
    pub file_cache: Option<FileCacheConfig>,
    #[serde(rename = "fscache")]
    /// Configuration information for fscache
    pub fs_cache: Option<FsCacheConfig>,
}

impl CacheConfigV2 {
    /// Validate cache configuration information.
    pub fn validate(&self) -> bool {
        match self.cache_type.as_str() {
            "blobcache" | "filecache" => {
                if let Some(c) = self.file_cache.as_ref() {
                    if c.work_dir.is_empty() {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            "fscache" => {
                if let Some(c) = self.fs_cache.as_ref() {
                    if c.work_dir.is_empty() {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            "" | "dummycache" => {}
            _ => return false,
        }

        if self.prefetch.enable {
            if self.prefetch.batch_size > 0x10000000 {
                return false;
            }
            if self.prefetch.threads == 0 || self.prefetch.threads > 1024 {
                return false;
            }
        }

        true
    }

    /// Get configuration information for file cache.
    pub fn get_filecache_config(&self) -> Result<&FileCacheConfig> {
        if self.cache_type != "blobcache" && self.cache_type != "filecache" {
            Err(einval!("cache type is not 'filecache'"))
        } else {
            self.file_cache
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for filecache"))
        }
    }

    /// Get configuration information for fscache.
    pub fn get_fscache_config(&self) -> Result<&FsCacheConfig> {
        if self.cache_type != "fscache" {
            Err(einval!("cache type is not 'fscache'"))
        } else {
            self.fs_cache
                .as_ref()
                .ok_or_else(|| einval!("no configuration information for fscache"))
        }
    }
}

/// Configuration information for file cache.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct FileCacheConfig {
    /// Working directory to store state and cached files.
    #[serde(default = "default_work_dir")]
    pub work_dir: String,
    /// Deprecated: disable index mapping, keep it as false when possible.
    #[serde(default)]
    pub disable_indexed_map: bool,
}

impl FileCacheConfig {
    /// Get the working directory.
    pub fn get_work_dir(&self) -> Result<&str> {
        let path = fs::metadata(&self.work_dir)
            .or_else(|_| {
                fs::create_dir_all(&self.work_dir)?;
                fs::metadata(&self.work_dir)
            })
            .map_err(|e| {
                last_error!(format!(
                    "fail to stat filecache work_dir {}: {}",
                    self.work_dir, e
                ))
            })?;

        if path.is_dir() {
            Ok(&self.work_dir)
        } else {
            Err(enoent!(format!(
                "filecache work_dir {} is not a directory",
                self.work_dir
            )))
        }
    }
}

/// Configuration information for fscache.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct FsCacheConfig {
    /// Working directory to store state and cached files.
    #[serde(default = "default_work_dir")]
    pub work_dir: String,
}

impl FsCacheConfig {
    /// Get the working directory.
    pub fn get_work_dir(&self) -> Result<&str> {
        let path = fs::metadata(&self.work_dir)
            .or_else(|_| {
                fs::create_dir_all(&self.work_dir)?;
                fs::metadata(&self.work_dir)
            })
            .map_err(|e| {
                last_error!(format!(
                    "fail to stat fscache work_dir {}: {}",
                    self.work_dir, e
                ))
            })?;

        if path.is_dir() {
            Ok(&self.work_dir)
        } else {
            Err(enoent!(format!(
                "fscache work_dir {} is not a directory",
                self.work_dir
            )))
        }
    }
}

/// Configuration information for RAFS filesystem.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct RafsConfigV2 {
    /// Filesystem metadata cache mode.
    #[serde(default = "default_rafs_mode")]
    pub mode: String,
    /// Batch size to read data from storage cache layer.
    #[serde(default = "default_batch_size")]
    pub batch_size: usize,
    /// Whether to validate data digest.
    #[serde(default)]
    pub validate: bool,
    /// Enable support of extended attributes.
    #[serde(default)]
    pub enable_xattr: bool,
    /// Record file operation metrics for each file.
    ///
    /// Better to keep it off in production environment due to possible resource consumption.
    #[serde(default)]
    pub iostats_files: bool,
    /// Record filesystem access pattern.
    #[serde(default)]
    pub access_pattern: bool,
    /// Record file name if file access trace log.
    #[serde(default)]
    pub latest_read_files: bool,
    /// Filesystem prefetching configuration.
    #[serde(default)]
    pub prefetch: PrefetchConfigV2,
}

impl RafsConfigV2 {
    /// Validate RAFS filesystem configuration information.
    pub fn validate(&self) -> bool {
        if self.mode != "direct" && self.mode != "cached" {
            return false;
        }
        if self.batch_size > 0x10000000 {
            return false;
        }
        if self.prefetch.enable {
            if self.prefetch.batch_size > 0x10000000 {
                return false;
            }
            if self.prefetch.threads == 0 || self.prefetch.threads > 1024 {
                return false;
            }
        }

        true
    }
}

/// Configuration information for blob data prefetching.
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct PrefetchConfigV2 {
    /// Whether to enable blob data prefetching.
    pub enable: bool,
    /// Number of data prefetching working threads.
    #[serde(default = "default_prefetch_threads")]
    pub threads: usize,
    /// The batch size to prefetch data from backend.
    #[serde(default = "default_prefetch_batch_size")]
    pub batch_size: usize,
    /// Network bandwidth rate limit in unit of Bytes and Zero means no limit.
    #[serde(default)]
    pub bandwidth_limit: u32,
    /// Prefetch all data from backend.
    #[serde(default)]
    pub prefetch_all: bool,
}

/// Configuration information for network proxy.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ProxyConfig {
    /// Access remote storage backend via proxy, e.g. Dragonfly dfdaemon server URL.
    #[serde(default)]
    pub url: String,
    /// Proxy health checking endpoint.
    #[serde(default)]
    pub ping_url: String,
    /// Fallback to remote storage backend if proxy ping failed.
    #[serde(default = "default_true")]
    pub fallback: bool,
    /// Interval for proxy health checking, in seconds.
    #[serde(default = "default_check_interval")]
    pub check_interval: u64,
    /// Replace URL to http to request source registry with proxy, and allow fallback to https if the proxy is unhealthy.
    #[serde(default)]
    pub use_http: bool,
}

impl Default for ProxyConfig {
    fn default() -> Self {
        Self {
            url: String::new(),
            ping_url: String::new(),
            fallback: true,
            check_interval: 5,
            use_http: false,
        }
    }
}

/// Configuration for registry mirror.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MirrorConfig {
    /// Mirror server URL, for example http://127.0.0.1:65001.
    pub host: String,
    /// Ping URL to check mirror server health.
    #[serde(default)]
    pub ping_url: String,
    /// HTTP request headers to be passed to mirror server.
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// Whether the authorization process is through mirror, default to false.
    /// true: authorization through mirror, e.g. Using normal registry as mirror.
    /// false: authorization through original registry,
    /// e.g. when using Dragonfly server as mirror, authorization through it may affect performance.
    #[serde(default)]
    pub auth_through: bool,
    /// Interval for mirror health checking, in seconds.
    #[serde(default = "default_check_interval")]
    pub health_check_interval: u64,
    /// Maximum number of failures before marking a mirror as unusable.
    #[serde(default = "default_failure_limit")]
    pub failure_limit: u8,
}

impl Default for MirrorConfig {
    fn default() -> Self {
        Self {
            host: String::new(),
            headers: HashMap::new(),
            auth_through: false,
            health_check_interval: 5,
            failure_limit: 5,
            ping_url: String::new(),
        }
    }
}

/// Configuration information for a cached blob`.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlobCacheEntryConfigV2 {
    /// Configuration file format version number, must be 2.
    pub version: u32,
    /// Identifier for the instance.
    #[serde(default)]
    pub id: String,
    /// Configuration information for storage backend.
    #[serde(default)]
    pub backend: BackendConfigV2,
    /// Configuration information for local cache system.
    #[serde(default)]
    pub cache: CacheConfigV2,
    /// Optional file path for metadata blobs.
    #[serde(default)]
    pub metadata_path: Option<String>,
}

impl From<&BlobCacheEntryConfigV2> for ConfigV2 {
    fn from(c: &BlobCacheEntryConfigV2) -> Self {
        ConfigV2 {
            version: c.version,
            id: c.id.clone(),
            backend: Some(c.backend.clone()),
            cache: Some(c.cache.clone()),
            rafs: None,
            internal: ConfigV2Internal::default(),
        }
    }
}

/// Internal runtime configuration.
#[derive(Clone, Debug)]
pub struct ConfigV2Internal {
    /// It's possible to access the raw or more blob objects.
    pub blob_accessible: Arc<AtomicBool>,
}

impl Default for ConfigV2Internal {
    fn default() -> Self {
        ConfigV2Internal {
            blob_accessible: Arc::new(AtomicBool::new(false)),
        }
    }
}

impl PartialEq for ConfigV2Internal {
    fn eq(&self, other: &Self) -> bool {
        self.blob_accessible() == other.blob_accessible()
    }
}

impl Eq for ConfigV2Internal {}

impl ConfigV2Internal {
    /// Get the auto-probe flag.
    pub fn blob_accessible(&self) -> bool {
        self.blob_accessible.load(Ordering::Relaxed)
    }

    /// Set the auto-probe flag.
    pub fn set_blob_accessible(&self, accessible: bool) {
        self.blob_accessible.store(accessible, Ordering::Relaxed);
    }
}

fn default_true() -> bool {
    true
}

fn default_http_scheme() -> String {
    "https".to_string()
}

fn default_http_timeout() -> u32 {
    5
}

fn default_check_interval() -> u64 {
    5
}

fn default_failure_limit() -> u8 {
    5
}

fn default_work_dir() -> String {
    ".".to_string()
}

pub fn default_batch_size() -> usize {
    128 * 1024
}

fn default_prefetch_batch_size() -> usize {
    1024 * 1024
}

fn default_prefetch_threads() -> usize {
    8
}

fn default_prefetch_all() -> bool {
    true
}

fn default_rafs_mode() -> String {
    "direct".to_string()
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// For backward compatibility
////////////////////////////////////////////////////////////////////////////////////////////////////

/// Configuration information for storage backend.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
struct BackendConfig {
    /// Type of storage backend.
    #[serde(rename = "type")]
    pub backend_type: String,
    /// Configuration for storage backend.
    /// Possible value: `LocalFsConfig`, `RegistryConfig`, `OssConfig`, `LocalDiskConfig`.
    #[serde(rename = "config")]
    pub backend_config: Value,
}

impl TryFrom<&BackendConfig> for BackendConfigV2 {
    type Error = std::io::Error;

    fn try_from(value: &BackendConfig) -> std::result::Result<Self, Self::Error> {
        let mut config = BackendConfigV2 {
            backend_type: value.backend_type.clone(),
            localdisk: None,
            localfs: None,
            oss: None,
            s3: None,
            registry: None,
            http_proxy: None,
        };

        match value.backend_type.as_str() {
            "localdisk" => {
                config.localdisk = Some(serde_json::from_value(value.backend_config.clone())?);
            }
            "localfs" => {
                config.localfs = Some(serde_json::from_value(value.backend_config.clone())?);
            }
            "oss" => {
                config.oss = Some(serde_json::from_value(value.backend_config.clone())?);
            }
            "s3" => {
                config.s3 = Some(serde_json::from_value(value.backend_config.clone())?);
            }
            "registry" => {
                config.registry = Some(serde_json::from_value(value.backend_config.clone())?);
            }
            v => return Err(einval!(format!("unsupported backend type '{}'", v))),
        }

        Ok(config)
    }
}

/// Configuration information for blob cache manager.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
struct CacheConfig {
    /// Type of blob cache: "blobcache", "fscache" or ""
    #[serde(default, rename = "type")]
    pub cache_type: String,
    /// Whether the data from the cache is compressed, not used anymore.
    #[serde(default, rename = "compressed")]
    pub cache_compressed: bool,
    /// Blob cache manager specific configuration: FileCacheConfig, FsCacheConfig.
    #[serde(default, rename = "config")]
    pub cache_config: Value,
    /// Whether to validate data read from the cache.
    #[serde(skip_serializing, skip_deserializing)]
    pub cache_validate: bool,
    /// Configuration for blob data prefetching.
    #[serde(skip_serializing, skip_deserializing)]
    pub prefetch_config: BlobPrefetchConfig,
}

impl TryFrom<&CacheConfig> for CacheConfigV2 {
    type Error = std::io::Error;

    fn try_from(v: &CacheConfig) -> std::result::Result<Self, Self::Error> {
        let mut config = CacheConfigV2 {
            cache_type: v.cache_type.clone(),
            cache_compressed: v.cache_compressed,
            cache_validate: v.cache_validate,
            prefetch: (&v.prefetch_config).into(),
            file_cache: None,
            fs_cache: None,
        };

        match v.cache_type.as_str() {
            "blobcache" | "filecache" => {
                config.file_cache = Some(serde_json::from_value(v.cache_config.clone())?);
            }
            "fscache" => {
                config.fs_cache = Some(serde_json::from_value(v.cache_config.clone())?);
            }
            "" => {}
            t => return Err(einval!(format!("unsupported cache type '{}'", t))),
        }

        Ok(config)
    }
}

/// Configuration information to create blob cache manager.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
struct FactoryConfig {
    /// Id of the factory.
    #[serde(default)]
    pub id: String,
    /// Configuration for storage backend.
    pub backend: BackendConfig,
    /// Configuration for blob cache manager.
    #[serde(default)]
    pub cache: CacheConfig,
}

/// Rafs storage backend configuration information.
#[derive(Clone, Default, Deserialize)]
struct RafsConfig {
    /// Configuration for storage subsystem.
    pub device: FactoryConfig,
    /// Filesystem working mode.
    pub mode: String,
    /// Whether to validate data digest before use.
    #[serde(default)]
    pub digest_validate: bool,
    /// Io statistics.
    #[serde(default)]
    pub iostats_files: bool,
    /// Filesystem prefetching configuration.
    #[serde(default)]
    pub fs_prefetch: FsPrefetchControl,
    /// Enable extended attributes.
    #[serde(default)]
    pub enable_xattr: bool,
    /// Record filesystem access pattern.
    #[serde(default)]
    pub access_pattern: bool,
    /// Record file name if file access trace log.
    #[serde(default)]
    pub latest_read_files: bool,
    // ZERO value means, amplifying user io is not enabled.
    #[serde(default = "default_batch_size")]
    pub amplify_io: usize,
}

impl TryFrom<RafsConfig> for ConfigV2 {
    type Error = std::io::Error;

    fn try_from(v: RafsConfig) -> std::result::Result<Self, Self::Error> {
        let backend: BackendConfigV2 = (&v.device.backend).try_into()?;
        let mut cache: CacheConfigV2 = (&v.device.cache).try_into()?;
        let rafs = RafsConfigV2 {
            mode: v.mode,
            batch_size: v.amplify_io,
            validate: v.digest_validate,
            enable_xattr: v.enable_xattr,
            iostats_files: v.iostats_files,
            access_pattern: v.access_pattern,
            latest_read_files: v.latest_read_files,
            prefetch: v.fs_prefetch.into(),
        };
        if !cache.prefetch.enable && rafs.prefetch.enable {
            cache.prefetch = rafs.prefetch.clone();
        }

        Ok(ConfigV2 {
            version: 2,
            id: v.device.id,
            backend: Some(backend),
            cache: Some(cache),
            rafs: Some(rafs),
            internal: ConfigV2Internal::default(),
        })
    }
}

/// Configuration information for filesystem data prefetch.
#[derive(Clone, Default, Deserialize)]
struct FsPrefetchControl {
    /// Whether the filesystem layer data prefetch is enabled or not.
    #[serde(default)]
    pub enable: bool,

    /// How many working threads to prefetch data.
    #[serde(default = "default_prefetch_threads")]
    pub threads_count: usize,

    /// Window size in unit of bytes to merge request to backend.
    #[serde(default = "default_batch_size")]
    pub merging_size: usize,

    /// Network bandwidth limitation for prefetching.
    ///
    /// In unit of Bytes. It sets a limit to prefetch bandwidth usage in order to
    /// reduce congestion with normal user IO.
    /// bandwidth_rate == 0 -- prefetch bandwidth ratelimit disabled
    /// bandwidth_rate > 0  -- prefetch bandwidth ratelimit enabled.
    ///                        Please note that if the value is less than Rafs chunk size,
    ///                        it will be raised to the chunk size.
    #[serde(default)]
    pub bandwidth_rate: u32,

    /// Whether to prefetch all filesystem data.
    #[serde(default = "default_prefetch_all")]
    pub prefetch_all: bool,
}

impl From<FsPrefetchControl> for PrefetchConfigV2 {
    fn from(v: FsPrefetchControl) -> Self {
        PrefetchConfigV2 {
            enable: v.enable,
            threads: v.threads_count,
            batch_size: v.merging_size,
            bandwidth_limit: v.bandwidth_rate,
            prefetch_all: v.prefetch_all,
        }
    }
}

/// Configuration information for blob data prefetching.
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
struct BlobPrefetchConfig {
    /// Whether to enable blob data prefetching.
    pub enable: bool,
    /// Number of data prefetching working threads.
    pub threads_count: usize,
    /// The maximum size of a merged IO request.
    pub merging_size: usize,
    /// Network bandwidth rate limit in unit of Bytes and Zero means no limit.
    pub bandwidth_rate: u32,
}

impl From<&BlobPrefetchConfig> for PrefetchConfigV2 {
    fn from(v: &BlobPrefetchConfig) -> Self {
        PrefetchConfigV2 {
            enable: v.enable,
            threads: v.threads_count,
            batch_size: v.merging_size,
            bandwidth_limit: v.bandwidth_rate,
            prefetch_all: true,
        }
    }
}

/// Configuration information for a cached blob, corresponding to `FactoryConfig`.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) struct BlobCacheEntryConfig {
    /// Identifier for the blob cache configuration: corresponding to `FactoryConfig::id`.
    #[serde(default)]
    id: String,
    /// Type of storage backend, corresponding to `FactoryConfig::BackendConfig::backend_type`.
    backend_type: String,
    /// Configuration for storage backend, corresponding to `FactoryConfig::BackendConfig::backend_config`.
    ///
    /// Possible value: `LocalFsConfig`, `RegistryConfig`, `OssConfig`, `LocalDiskConfig`.
    backend_config: Value,
    /// Type of blob cache, corresponding to `FactoryConfig::CacheConfig::cache_type`.
    ///
    /// Possible value: "fscache", "filecache".
    cache_type: String,
    /// Configuration for blob cache, corresponding to `FactoryConfig::CacheConfig::cache_config`.
    ///
    /// Possible value: `FileCacheConfig`, `FsCacheConfig`.
    cache_config: Value,
    /// Configuration for data prefetch.
    #[serde(default)]
    prefetch_config: BlobPrefetchConfig,
    /// Optional file path for metadata blobs.
    #[serde(default)]
    metadata_path: Option<String>,
}

impl TryFrom<&BlobCacheEntryConfig> for BlobCacheEntryConfigV2 {
    type Error = std::io::Error;

    fn try_from(v: &BlobCacheEntryConfig) -> std::result::Result<Self, Self::Error> {
        let backend_config = BackendConfig {
            backend_type: v.backend_type.clone(),
            backend_config: v.backend_config.clone(),
        };
        let cache_config = CacheConfig {
            cache_type: v.cache_type.clone(),
            cache_compressed: false,
            cache_config: v.cache_config.clone(),
            cache_validate: false,
            prefetch_config: v.prefetch_config.clone(),
        };
        Ok(BlobCacheEntryConfigV2 {
            version: 2,
            id: v.id.clone(),
            backend: (&backend_config).try_into()?,
            cache: (&cache_config).try_into()?,
            metadata_path: v.metadata_path.clone(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{BlobCacheEntry, BLOB_CACHE_TYPE_META_BLOB};

    #[test]
    fn test_blob_prefetch_config() {
        let config = BlobPrefetchConfig::default();
        assert!(!config.enable);
        assert_eq!(config.threads_count, 0);
        assert_eq!(config.merging_size, 0);
        assert_eq!(config.bandwidth_rate, 0);

        let content = r#"{
            "enable": true,
            "threads_count": 2,
            "merging_size": 4,
            "bandwidth_rate": 5
        }"#;
        let config: BlobPrefetchConfig = serde_json::from_str(content).unwrap();
        assert!(config.enable);
        assert_eq!(config.threads_count, 2);
        assert_eq!(config.merging_size, 4);
        assert_eq!(config.bandwidth_rate, 5);

        let config: PrefetchConfigV2 = (&config).into();
        assert!(config.enable);
        assert_eq!(config.threads, 2);
        assert_eq!(config.batch_size, 4);
        assert_eq!(config.bandwidth_limit, 5);
        assert!(config.prefetch_all);
    }

    #[test]
    fn test_file_cache_config() {
        let config: FileCacheConfig = serde_json::from_str("{}").unwrap();
        assert_eq!(&config.work_dir, ".");
        assert!(!config.disable_indexed_map);

        let config: FileCacheConfig =
            serde_json::from_str("{\"work_dir\":\"/tmp\",\"disable_indexed_map\":true}").unwrap();
        assert_eq!(&config.work_dir, "/tmp");
        assert!(config.get_work_dir().is_ok());
        assert!(config.disable_indexed_map);

        let config: FileCacheConfig =
            serde_json::from_str("{\"work_dir\":\"/proc/mounts\",\"disable_indexed_map\":true}")
                .unwrap();
        assert!(config.get_work_dir().is_err());
    }

    #[test]
    fn test_fs_cache_config() {
        let config: FsCacheConfig = serde_json::from_str("{}").unwrap();
        assert_eq!(&config.work_dir, ".");

        let config: FileCacheConfig = serde_json::from_str("{\"work_dir\":\"/tmp\"}").unwrap();
        assert_eq!(&config.work_dir, "/tmp");
        assert!(config.get_work_dir().is_ok());

        let config: FileCacheConfig =
            serde_json::from_str("{\"work_dir\":\"/proc/mounts\"}").unwrap();
        assert!(config.get_work_dir().is_err());
    }

    #[test]
    fn test_blob_cache_entry() {
        let content = r#"{
            "type": "bootstrap",
            "id": "blob1",
            "config": {
                "id": "cache1",
                "backend_type": "localfs",
                "backend_config": {},
                "cache_type": "fscache",
                "cache_config": {},
                "prefetch_config": {
                    "enable": true,
                    "threads_count": 2,
                    "merging_size": 4,
                    "bandwidth_rate": 5
                },
                "metadata_path": "/tmp/metadata1"
            },
            "domain_id": "domain1"
        }"#;
        let config: BlobCacheEntry = serde_json::from_str(content).unwrap();
        assert_eq!(&config.blob_type, BLOB_CACHE_TYPE_META_BLOB);
        assert_eq!(&config.blob_id, "blob1");
        assert_eq!(&config.domain_id, "domain1");

        let blob_config = config.blob_config_legacy.as_ref().unwrap();
        assert_eq!(blob_config.id, "cache1");
        assert_eq!(blob_config.backend_type, "localfs");
        assert_eq!(blob_config.cache_type, "fscache");
        assert!(blob_config.cache_config.is_object());
        assert!(blob_config.prefetch_config.enable);
        assert_eq!(blob_config.prefetch_config.threads_count, 2);
        assert_eq!(blob_config.prefetch_config.merging_size, 4);
        assert_eq!(
            blob_config.metadata_path.as_ref().unwrap().as_str(),
            "/tmp/metadata1"
        );

        let blob_config: BlobCacheEntryConfigV2 = blob_config.try_into().unwrap();
        assert_eq!(blob_config.id, "cache1");
        assert_eq!(blob_config.backend.backend_type, "localfs");
        assert_eq!(blob_config.cache.cache_type, "fscache");
        assert!(blob_config.cache.fs_cache.is_some());
        assert!(blob_config.cache.prefetch.enable);
        assert_eq!(blob_config.cache.prefetch.threads, 2);
        assert_eq!(blob_config.cache.prefetch.batch_size, 4);
        assert_eq!(
            blob_config.metadata_path.as_ref().unwrap().as_str(),
            "/tmp/metadata1"
        );

        let content = r#"{
            "type": "bootstrap",
            "id": "blob1",
            "config": {
                "id": "cache1",
                "backend_type": "localfs",
                "backend_config": {},
                "cache_type": "fscache",
                "cache_config": {},
                "metadata_path": "/tmp/metadata1"
            },
            "domain_id": "domain1"
        }"#;
        let config: BlobCacheEntry = serde_json::from_str(content).unwrap();
        let blob_config = config.blob_config_legacy.as_ref().unwrap();
        assert!(!blob_config.prefetch_config.enable);
        assert_eq!(blob_config.prefetch_config.threads_count, 0);
        assert_eq!(blob_config.prefetch_config.merging_size, 0);
    }

    #[test]
    fn test_proxy_config() {
        let content = r#"{
            "url": "foo.com",
            "ping_url": "ping.foo.com",
            "fallback": true
        }"#;
        let config: ProxyConfig = serde_json::from_str(content).unwrap();
        assert_eq!(config.url, "foo.com");
        assert_eq!(config.ping_url, "ping.foo.com");
        assert!(config.fallback);
        assert_eq!(config.check_interval, 5);
    }

    #[test]
    fn test_oss_config() {
        let content = r#"{
            "endpoint": "test",
            "access_key_id": "test",
            "access_key_secret": "test",
            "bucket_name": "antsys-nydus",
            "object_prefix":"nydus_v2/"
        }"#;
        let config: OssConfig = serde_json::from_str(content).unwrap();
        assert_eq!(config.scheme, "https");
        assert!(!config.skip_verify);
        assert_eq!(config.timeout, 5);
        assert_eq!(config.connect_timeout, 5);
    }

    #[test]
    fn test_s3_config() {
        let content = r#"{
            "endpoint": "test",
            "region": "us-east-1",
            "access_key_id": "test",
            "access_key_secret": "test",
            "bucket_name": "antsys-nydus",
            "object_prefix":"nydus_v2/"
        }"#;
        let config: OssConfig = serde_json::from_str(content).unwrap();
        assert_eq!(config.scheme, "https");
        assert!(!config.skip_verify);
        assert_eq!(config.timeout, 5);
        assert_eq!(config.connect_timeout, 5);
    }

    #[test]
    fn test_registry_config() {
        let content = r#"{
	    "scheme": "http",
            "skip_verify": true,
	    "host": "my-registry:5000",
	    "repo": "test/repo",
	    "auth": "base64_encoded_auth",
	    "registry_token": "bearer_token",
	    "blob_redirected_host": "blob_redirected_host"
        }"#;
        let config: RegistryConfig = serde_json::from_str(content).unwrap();
        assert_eq!(config.scheme, "http");
        assert!(config.skip_verify);
    }

    #[test]
    fn test_localfs_config() {
        let content = r#"{
            "blob_file": "blob_file",
            "dir": "blob_dir",
            "alt_dirs": ["dir1", "dir2"]
        }"#;
        let config: LocalFsConfig = serde_json::from_str(content).unwrap();
        assert_eq!(config.blob_file, "blob_file");
        assert_eq!(config.dir, "blob_dir");
        assert_eq!(config.alt_dirs, vec!["dir1", "dir2"]);
    }

    #[test]
    fn test_localdisk_config() {
        let content = r#"{
            "device_path": "device_path"
        }"#;
        let config: LocalDiskConfig = serde_json::from_str(content).unwrap();
        assert_eq!(config.device_path, "device_path");
    }

    #[test]
    fn test_backend_config() {
        let config = BackendConfig {
            backend_type: "localfs".to_string(),
            backend_config: Default::default(),
        };
        let str_val = serde_json::to_string(&config).unwrap();
        let config2 = serde_json::from_str(&str_val).unwrap();

        assert_eq!(config, config2);
    }

    #[test]
    fn test_v2_version() {
        let content = "version=2";
        let config: ConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.backend.is_none());
    }

    #[test]
    fn test_v2_backend() {
        let content = r#"version=2
        [backend]
        type = "localfs"
        "#;
        let config: ConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.backend.is_some());
        assert!(config.cache.is_none());

        let backend = config.backend.as_ref().unwrap();
        assert_eq!(&backend.backend_type, "localfs");
        assert!(backend.localfs.is_none());
        assert!(backend.oss.is_none());
        assert!(backend.registry.is_none());
    }

    #[test]
    fn test_v2_backend_localfs() {
        let content = r#"version=2
        [backend]
        type = "localfs"
        [backend.localfs]
        blob_file = "/tmp/nydus.blob.data"
        dir = "/tmp"
        alt_dirs = ["/var/nydus/cache"]
        "#;
        let config: ConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.backend.is_some());

        let backend = config.backend.as_ref().unwrap();
        assert_eq!(&backend.backend_type, "localfs");
        assert!(backend.localfs.is_some());

        let localfs = backend.localfs.as_ref().unwrap();
        assert_eq!(&localfs.blob_file, "/tmp/nydus.blob.data");
        assert_eq!(&localfs.dir, "/tmp");
        assert_eq!(&localfs.alt_dirs[0], "/var/nydus/cache");
    }

    #[test]
    fn test_v2_backend_oss() {
        let content = r#"version=2
        [backend]
        type = "oss"
        [backend.oss]
        endpoint = "my_endpoint"
        bucket_name = "my_bucket_name"
        object_prefix = "my_object_prefix"
        access_key_id = "my_access_key_id"
        access_key_secret = "my_access_key_secret"
        scheme = "http"
        skip_verify = true
        timeout = 10
        connect_timeout = 10
        retry_limit = 5
        [backend.oss.proxy]
        url = "localhost:6789"
        ping_url = "localhost:6789/ping"
        fallback = true
        check_interval = 10
        use_http = true
        [[backend.oss.mirrors]]
        host = "http://127.0.0.1:65001"
        ping_url = "http://127.0.0.1:65001/ping"
        auth_through = true
        health_check_interval = 10
        failure_limit = 10
        "#;
        let config: ConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.backend.is_some());
        assert!(config.rafs.is_none());

        let backend = config.backend.as_ref().unwrap();
        assert_eq!(&backend.backend_type, "oss");
        assert!(backend.oss.is_some());

        let oss = backend.oss.as_ref().unwrap();
        assert_eq!(&oss.endpoint, "my_endpoint");
        assert_eq!(&oss.bucket_name, "my_bucket_name");
        assert_eq!(&oss.object_prefix, "my_object_prefix");
        assert_eq!(&oss.access_key_id, "my_access_key_id");
        assert_eq!(&oss.access_key_secret, "my_access_key_secret");
        assert_eq!(&oss.scheme, "http");
        assert!(oss.skip_verify);
        assert_eq!(oss.timeout, 10);
        assert_eq!(oss.connect_timeout, 10);
        assert_eq!(oss.retry_limit, 5);
        assert_eq!(&oss.proxy.url, "localhost:6789");
        assert_eq!(&oss.proxy.ping_url, "localhost:6789/ping");
        assert_eq!(oss.proxy.check_interval, 10);
        assert!(oss.proxy.fallback);
        assert!(oss.proxy.use_http);

        assert_eq!(oss.mirrors.len(), 1);
        let mirror = &oss.mirrors[0];
        assert_eq!(mirror.host, "http://127.0.0.1:65001");
        assert_eq!(mirror.ping_url, "http://127.0.0.1:65001/ping");
        assert!(mirror.auth_through);
        assert!(mirror.headers.is_empty());
        assert_eq!(mirror.health_check_interval, 10);
        assert_eq!(mirror.failure_limit, 10);
    }

    #[test]
    fn test_v2_backend_registry() {
        let content = r#"version=2
        [backend]
        type = "registry"
        [backend.registry]
        scheme = "http"
        host = "localhost"
        repo = "nydus"
        auth = "auth"
        skip_verify = true
        timeout = 10
        connect_timeout = 10
        retry_limit = 5
        registry_token = "bear_token"
        blob_url_scheme = "https"
        blob_redirected_host = "redirect.registry.com"
        [backend.registry.proxy]
        url = "localhost:6789"
        ping_url = "localhost:6789/ping"
        fallback = true
        check_interval = 10
        use_http = true
        [[backend.registry.mirrors]]
        host = "http://127.0.0.1:65001"
        ping_url = "http://127.0.0.1:65001/ping"
        auth_through = true
        health_check_interval = 10
        failure_limit = 10
        "#;
        let config: ConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.backend.is_some());
        assert!(config.rafs.is_none());

        let backend = config.backend.as_ref().unwrap();
        assert_eq!(&backend.backend_type, "registry");
        assert!(backend.registry.is_some());

        let registry = backend.registry.as_ref().unwrap();
        assert_eq!(&registry.scheme, "http");
        assert_eq!(&registry.host, "localhost");
        assert_eq!(&registry.repo, "nydus");
        assert_eq!(registry.auth.as_ref().unwrap(), "auth");
        assert!(registry.skip_verify);
        assert_eq!(registry.timeout, 10);
        assert_eq!(registry.connect_timeout, 10);
        assert_eq!(registry.retry_limit, 5);
        assert_eq!(registry.registry_token.as_ref().unwrap(), "bear_token");
        assert_eq!(registry.blob_url_scheme, "https");
        assert_eq!(registry.blob_redirected_host, "redirect.registry.com");

        assert_eq!(&registry.proxy.url, "localhost:6789");
        assert_eq!(&registry.proxy.ping_url, "localhost:6789/ping");
        assert_eq!(registry.proxy.check_interval, 10);
        assert!(registry.proxy.fallback);
        assert!(registry.proxy.use_http);

        assert_eq!(registry.mirrors.len(), 1);
        let mirror = &registry.mirrors[0];
        assert_eq!(mirror.host, "http://127.0.0.1:65001");
        assert_eq!(mirror.ping_url, "http://127.0.0.1:65001/ping");
        assert!(mirror.auth_through);
        assert!(mirror.headers.is_empty());
        assert_eq!(mirror.health_check_interval, 10);
        assert_eq!(mirror.failure_limit, 10);
    }

    #[test]
    fn test_v2_cache() {
        let content = r#"version=2
        [cache]
        type = "filecache"
        compressed = true
        validate = true
        [cache.filecache]
        work_dir = "/tmp"
        [cache.fscache]
        work_dir = "./"
        [cache.prefetch]
        enable = true
        threads = 8
        batch_size = 1000000
        bandwidth_limit = 10000000
        "#;
        let config: ConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.backend.is_none());
        assert!(config.rafs.is_none());
        assert!(config.cache.is_some());

        let cache = config.cache.as_ref().unwrap();
        assert_eq!(&cache.cache_type, "filecache");
        assert!(cache.cache_compressed);
        assert!(cache.cache_validate);
        let filecache = cache.file_cache.as_ref().unwrap();
        assert_eq!(&filecache.work_dir, "/tmp");
        let fscache = cache.fs_cache.as_ref().unwrap();
        assert_eq!(&fscache.work_dir, "./");

        let prefetch = &cache.prefetch;
        assert!(prefetch.enable);
        assert_eq!(prefetch.threads, 8);
        assert_eq!(prefetch.batch_size, 1000000);
        assert_eq!(prefetch.bandwidth_limit, 10000000);
    }

    #[test]
    fn test_v2_rafs() {
        let content = r#"version=2
        [rafs]
        mode = "direct"
        batch_size = 1000000
        validate = true
        enable_xattr = true
        iostats_files = true
        access_pattern = true
        latest_read_files = true
        [rafs.prefetch]
        enable = true
        threads = 4
        batch_size = 1000000
        bandwidth_limit = 10000000
        prefetch_all = true
        "#;
        let config: ConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.backend.is_none());
        assert!(config.cache.is_none());
        assert!(config.rafs.is_some());

        let rafs = config.rafs.as_ref().unwrap();
        assert_eq!(&rafs.mode, "direct");
        assert_eq!(rafs.batch_size, 1000000);
        assert!(rafs.validate);
        assert!(rafs.enable_xattr);
        assert!(rafs.iostats_files);
        assert!(rafs.access_pattern);
        assert!(rafs.latest_read_files);
        assert!(rafs.prefetch.enable);
        assert_eq!(rafs.prefetch.threads, 4);
        assert_eq!(rafs.prefetch.batch_size, 1000000);
        assert_eq!(rafs.prefetch.bandwidth_limit, 10000000);
        assert!(rafs.prefetch.prefetch_all)
    }

    #[test]
    fn test_v2_blob_cache_entry() {
        let content = r#"version=2
        id = "my_id"
        metadata_path = "meta_path"
        [backend]
        type = "localfs"
        [backend.localfs]
        blob_file = "/tmp/nydus.blob.data"
        dir = "/tmp"
        alt_dirs = ["/var/nydus/cache"]
        [cache]
        type = "filecache"
        compressed = true
        validate = true
        [cache.filecache]
        work_dir = "/tmp"
        "#;
        let config: BlobCacheEntryConfigV2 = toml::from_str(content).unwrap();
        assert_eq!(config.version, 2);
        assert_eq!(&config.id, "my_id");
        assert_eq!(config.metadata_path.as_ref().unwrap(), "meta_path");

        let backend = &config.backend;
        assert_eq!(&backend.backend_type, "localfs");
        assert!(backend.localfs.is_some());

        let localfs = backend.localfs.as_ref().unwrap();
        assert_eq!(&localfs.blob_file, "/tmp/nydus.blob.data");
        assert_eq!(&localfs.dir, "/tmp");
        assert_eq!(&localfs.alt_dirs[0], "/var/nydus/cache");
    }

    #[test]
    fn test_sample_config_file() {
        let content = r#"{
            "device": {
                "backend": {
                    "type": "localfs",
                    "config": {
                        "dir": "/tmp/AM7TxD/blobs",
                        "readahead": true
                    }
                },
                "cache": {
                    "type": "blobcache",
                    "compressed": true,
                    "config": {
                        "work_dir": "/tmp/AM7TxD/cache"
                    }
                }
            },
            "mode": "cached",
            "digest_validate": true,
            "iostats_files": false
        }
        "#;
        let config = ConfigV2::from_str(content).unwrap();
        assert_eq!(&config.id, "");
    }

    #[test]
    fn test_snapshotter_sample_config() {
        let content = r#"
        {
            "device": {
                "backend": {
                    "type": "registry",
                    "config": {
                        "readahead": false,
                        "host": "localhost",
                        "repo": "vke/golang",
                        "auth": "",
                        "scheme": "https",
                        "proxy": {
                            "fallback": false
                        },
                        "timeout": 5,
                        "connect_timeout": 5,
                        "retry_limit": 2
                    }
                },
                "cache": {
                    "type": "blobcache",
                    "compressed": true,
                    "config": {
                        "work_dir": "/var/lib/containerd-nydus/cache",
                        "disable_indexed_map": false
                    }
                }
            },
            "mode": "direct",
            "digest_validate": false,
            "enable_xattr": true,
            "fs_prefetch": {
                "enable": true,
                "prefetch_all": true,
                "threads_count": 8,
                "merging_size": 1048576,
                "bandwidth_rate": 0
            }
        }
        "#;
        let config = ConfigV2::from_str(content).unwrap();
        assert_eq!(&config.id, "");
    }

    #[test]
    fn test_new_localfs() {
        let config = ConfigV2::new_localfs("id1", "./").unwrap();
        assert_eq!(&config.id, "id1");
        assert_eq!(config.backend.as_ref().unwrap().backend_type, "localfs");
    }
}