File: cloudinit_test.go

package info (click to toggle)
snapd 2.71-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 79,536 kB
  • sloc: ansic: 16,114; sh: 16,105; python: 9,941; makefile: 1,890; exp: 190; awk: 40; xml: 22
file content (1488 lines) | stat: -rw-r--r-- 45,867 bytes parent folder | download | duplicates (2)
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
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2020, 2024 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package sysconfig_test

import (
	"fmt"
	"os"
	"path/filepath"
	"testing"

	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/osutil/kcmdline"
	"github.com/snapcore/snapd/sysconfig"
	"github.com/snapcore/snapd/testutil"
)

// Hook up check.v1 into the "go test" runner
func Test(t *testing.T) { TestingT(t) }

type sysconfigSuite struct {
	testutil.BaseTest

	tmpdir string
}

var _ = Suite(&sysconfigSuite{})

func (s *sysconfigSuite) SetUpTest(c *C) {
	s.BaseTest.SetUpTest(c)

	s.tmpdir = c.MkDir()
	dirs.SetRootDir(s.tmpdir)
	s.AddCleanup(func() { dirs.SetRootDir("/") })

	oldTmpdir := os.Getenv("TMPDIR")
	os.Setenv("TMPDIR", s.tmpdir)
	s.AddCleanup(func() { os.Unsetenv(oldTmpdir) })
	err := os.MkdirAll(filepath.Join(s.tmpdir, "proc"), 0755)
	c.Assert(err, IsNil)
	restore := kcmdline.MockProcCmdline(filepath.Join(s.tmpdir, "proc/cmdline"))
	s.AddCleanup(restore)

}

func (s *sysconfigSuite) makeCloudCfgSrcDirFiles(c *C, cfgs ...string) (string, []string) {
	cloudCfgSrcDir := c.MkDir()
	names := make([]string, 0, len(cfgs))
	for i, mockCfg := range cfgs {
		configFileName := fmt.Sprintf("seed-config-%d.cfg", i)
		err := os.WriteFile(filepath.Join(cloudCfgSrcDir, configFileName), []byte(mockCfg), 0644)
		c.Assert(err, IsNil)
		names = append(names, configFileName)
	}
	return cloudCfgSrcDir, names
}

func (s *sysconfigSuite) makeGadgetCloudConfFile(c *C, content string) string {
	gadgetDir := c.MkDir()
	gadgetCloudConf := filepath.Join(gadgetDir, "cloud.conf")
	if content == "" {
		content = "#cloud-config some gadget cloud config"
	}
	err := os.WriteFile(gadgetCloudConf, []byte(content), 0644)
	c.Assert(err, IsNil)

	return gadgetDir
}

func (s *sysconfigSuite) TestHasGadgetCloudConf(c *C) {
	// no cloud.conf is false
	c.Assert(sysconfig.HasGadgetCloudConf("non-existent-dir-place"), Equals, false)

	// the dir is not enough
	gadgetDir := c.MkDir()
	c.Assert(sysconfig.HasGadgetCloudConf(gadgetDir), Equals, false)

	// creating one now is true
	gadgetCloudConf := filepath.Join(gadgetDir, "cloud.conf")
	err := os.WriteFile(gadgetCloudConf, []byte("gadget cloud config"), 0644)
	c.Assert(err, IsNil)

	c.Assert(sysconfig.HasGadgetCloudConf(gadgetDir), Equals, true)
}

// this test is for initramfs calls that disable cloud-init for the ephemeral
// writable partition that is used while running during install or recover mode
func (s *sysconfigSuite) TestEphemeralModeInitramfsCloudInitDisables(c *C) {
	writableDefaultsDir := sysconfig.WritableDefaultsDir(filepath.Join(dirs.GlobalRootDir, "/run/mnt/data/system-data"))
	err := sysconfig.DisableCloudInit(writableDefaultsDir)
	c.Assert(err, IsNil)

	ubuntuDataCloudDisabled := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/data/system-data"), "_writable_defaults/etc/cloud/cloud-init.disabled")
	c.Check(ubuntuDataCloudDisabled, testutil.FilePresent)
}

func (s *sysconfigSuite) TestInstallModeCloudInitDisablesByDefaultRunMode(c *C) {
	err := sysconfig.ConfigureTargetSystem(fake20Model("signed"), &sysconfig.Options{
		TargetRootDir: filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"),
	})
	c.Assert(err, IsNil)

	ubuntuDataCloudDisabled := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud-init.disabled")
	c.Check(ubuntuDataCloudDisabled, testutil.FilePresent)
}

func (s *sysconfigSuite) TestInstallModeCloudInitDisallowedIgnoresOtherOptions(c *C) {
	cloudCfgSrcDir, _ := s.makeCloudCfgSrcDirFiles(c)
	gadgetDir := s.makeGadgetCloudConfFile(c, "")

	err := sysconfig.ConfigureTargetSystem(fake20Model("signed"), &sysconfig.Options{
		AllowCloudInit:  false,
		CloudInitSrcDir: cloudCfgSrcDir,
		GadgetDir:       gadgetDir,
		TargetRootDir:   filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"),
	})
	c.Assert(err, IsNil)

	ubuntuDataCloudDisabled := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud-init.disabled")
	c.Check(ubuntuDataCloudDisabled, testutil.FilePresent)

	// did not copy ubuntu-seed src files
	ubuntuDataCloudCfg := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud.cfg.d/")
	c.Check(filepath.Join(ubuntuDataCloudCfg, "foo.cfg"), testutil.FileAbsent)
	c.Check(filepath.Join(ubuntuDataCloudCfg, "bar.cfg"), testutil.FileAbsent)

	// also did not copy gadget cloud.conf
	c.Check(filepath.Join(ubuntuDataCloudCfg, "80_device_gadget.cfg"), testutil.FileAbsent)
}

func (s *sysconfigSuite) TestInstallModeCloudInitAllowedPermutations(c *C) {

	// common inputs in the test cases below
	defaultMAASCfgs := []string{
		maasCfg1, // MAAS specific config
		maasCfg2, // MAAS specific config - this sets the datasource_list
		maasCfg3, // generic config that's filtered out
		maasCfg4, // generic config that passes filtering
		maasCfg5, // MAAS specific config
	}
	defaultMAASHappyInstalled := []bool{
		true,
		true,
		false,
		true,
		true,
	}
	defaultMAASNoneInstalled := []bool{false, false, false, false, false}

	explicitNonSupportedDatasource := `datasource_list: [GCE]`
	explicitSupportedDatasource := maasCfg2
	explicitNoDatasourceAllowed := `datasource_list: []`
	explicitSupportedAndNonSupportedDatasources := `datasource_list: [GCE, MAAS]`

	implictMentionNonSupportedDatasource := `#cloud-config
datasource:
  gce:
    metadata_url: foo
`
	implicitMentionSupportedDatasource := maasCfg1

	restrictDatasourceMAASFile := `datasource_list: [MAAS]
`
	// restrictDatasourceNoneFile := `datasource_list: []
	// `

	tt := []struct {
		grade     string
		gadgetCfg string
		// use lists here to install the files in the order that the file
		// content appears
		seedCfgs []string
		// whether each file in seedCfgs gets installed
		resultCfgCopied           []bool
		expDsRestrictFileContents string
		comment                   string
	}{
		{
			comment: "no config anywhere, but cloud-init not disabled",
		},
		{
			grade:   "dangerous",
			comment: "grade dangerous, no config anywhere, but cloud-init not disabled",
		},
		{
			comment:                   "no gadget config but MAAS allowed",
			seedCfgs:                  defaultMAASCfgs,
			resultCfgCopied:           defaultMAASHappyInstalled,
			expDsRestrictFileContents: restrictDatasourceMAASFile,
		},
		{
			comment: "grade signed NoCloud not allowed",
			seedCfgs: []string{
				`#cloud-config
datasource:
  NoCloud:
    something-no-cloudy: foo
`,
			},
			resultCfgCopied: []bool{false},
		},

		{
			comment:                   "MAAS in seed and gadget explicit gets installed",
			seedCfgs:                  defaultMAASCfgs,
			resultCfgCopied:           defaultMAASHappyInstalled,
			gadgetCfg:                 explicitSupportedDatasource,
			expDsRestrictFileContents: restrictDatasourceMAASFile,
		},
		{
			comment:                   "MAAS in seed and gadget implicit gets installed",
			seedCfgs:                  defaultMAASCfgs,
			resultCfgCopied:           defaultMAASHappyInstalled,
			gadgetCfg:                 implicitMentionSupportedDatasource,
			expDsRestrictFileContents: restrictDatasourceMAASFile,
		},
		{
			comment:         "MAAS in seed not installed due to implicit unsupported datasource in gadget",
			seedCfgs:        defaultMAASCfgs,
			resultCfgCopied: defaultMAASNoneInstalled,
			gadgetCfg:       implictMentionNonSupportedDatasource,
		},
		{
			comment:         "MAAS in seed not installed due to gadget disallowing any datasource",
			seedCfgs:        defaultMAASCfgs,
			resultCfgCopied: defaultMAASNoneInstalled,
			gadgetCfg:       explicitNoDatasourceAllowed,
		},
		{
			comment:         "MAAS in seed not installed due to gadget explicitly allowing other datasource",
			seedCfgs:        defaultMAASCfgs,
			resultCfgCopied: defaultMAASNoneInstalled,
			gadgetCfg:       explicitNonSupportedDatasource,
		},
		{
			comment: "MAAS in seed not installed due to seed config disallowing itself with gadget",
			seedCfgs: []string{
				maasCfg1,                    // MAAS specific config
				maasCfg2,                    // MAAS specific config - this sets the datasource_list
				maasCfg3,                    // generic config that's filtered out
				maasCfg4,                    // generic config that passes filtering
				maasCfg5,                    // MAAS specific config
				explicitNoDatasourceAllowed, // extra that disables all datasources
			},
			resultCfgCopied: []bool{false, false, false, false, false, false},
			gadgetCfg:       explicitNonSupportedDatasource,
		},
		{
			comment: "MAAS in seed not installed due to seed config disallowing itself without gadget",
			seedCfgs: []string{
				maasCfg1,                    // MAAS specific config
				maasCfg2,                    // MAAS specific config - this sets the datasource_list
				maasCfg3,                    // generic config that's filtered out
				maasCfg4,                    // generic config that passes filtering
				maasCfg5,                    // MAAS specific config
				explicitNoDatasourceAllowed, // extra that disables all datasources
			},
			resultCfgCopied: []bool{false, false, false, false, false, false},
		},
		{
			comment: "implictly mentioned datasource in seed not installed because it's unsupported",
			seedCfgs: []string{
				maasCfg1,                             // MAAS specific config
				maasCfg2,                             // MAAS specific config - this sets the datasource_list
				maasCfg4,                             // generic config that passes filtering
				maasCfg5,                             // MAAS specific config
				implictMentionNonSupportedDatasource, // extra that implicitly mentions GCE
			},
			resultCfgCopied: []bool{
				true,
				true,
				true,
				true,
				false, // the implicit GCE one
			},
			expDsRestrictFileContents: restrictDatasourceMAASFile,
		},
		{
			comment: "implictly mentioned datasource in seed not installed because it's unsupported + gadget with explicit supported",
			seedCfgs: []string{
				maasCfg1,                             // MAAS specific config
				maasCfg2,                             // MAAS specific config - this sets the datasource_list
				maasCfg4,                             // generic config that passes filtering
				maasCfg5,                             // MAAS specific config
				implictMentionNonSupportedDatasource, // extra that implicitly mentions GCE
			},
			resultCfgCopied: []bool{
				true,
				true,
				true,
				true,
				false, // the implicit GCE one
			},
			gadgetCfg:                 explicitSupportedDatasource,
			expDsRestrictFileContents: restrictDatasourceMAASFile,
		},
		{
			comment: "implicit mentioned datasource in seed not installed because it's unsupported + gadget with explicit supported and non-supported",
			seedCfgs: []string{
				maasCfg1,                             // MAAS specific config
				maasCfg2,                             // MAAS specific config - this sets the datasource_list
				maasCfg4,                             // generic config that passes filtering
				maasCfg5,                             // MAAS specific config
				implictMentionNonSupportedDatasource, // extra that implicitly mentions GCE
			},

			resultCfgCopied: []bool{
				true,
				true,
				true,
				true,
				false, // the implicit GCE one
			},
			gadgetCfg:                 explicitSupportedAndNonSupportedDatasources,
			expDsRestrictFileContents: restrictDatasourceMAASFile,
		},
		{
			comment: "implicit mentioned datasource and supported datasource in seed all not installed because no supported datasource in intersection with gadget with implicit non-supported",
			seedCfgs: []string{
				maasCfg1,                             // MAAS specific config
				maasCfg2,                             // MAAS specific config - this sets the datasource_list
				maasCfg4,                             // generic config that passes filtering
				maasCfg5,                             // MAAS specific config
				implictMentionNonSupportedDatasource, // extra that implicitly mentions GCE
			},

			resultCfgCopied: []bool{
				false,
				false,
				false,
				false,
				false, // the implicit GCE one
			},
			gadgetCfg: implictMentionNonSupportedDatasource,
		},
		{
			comment: "implicit mentioned datasource and supported datasource in seed all not installed because no supported datasource in intersection with gadget with explicit non-supported",
			seedCfgs: []string{
				maasCfg1,                             // MAAS specific config
				maasCfg2,                             // MAAS specific config - this sets the datasource_list
				maasCfg4,                             // generic config that passes filtering
				maasCfg5,                             // MAAS specific config
				implictMentionNonSupportedDatasource, // extra that implicitly mentions GCE
			},

			resultCfgCopied: []bool{
				false,
				false,
				false,
				false,
				false, // the implicit GCE one
			},
			gadgetCfg: explicitNonSupportedDatasource,
		},
		{
			comment: "implicit mentioned datasource and supported datasource in seed all not installed because no supported datasource in intersection with gadget with implicit non-supported",
			seedCfgs: []string{
				maasCfg1,                             // MAAS specific config
				maasCfg4,                             // generic config that passes filtering
				maasCfg5,                             // MAAS specific config
				implictMentionNonSupportedDatasource, // extra that implicitly mentions GCE
			},

			resultCfgCopied: []bool{
				false,
				false,
				false, // the implicit GCE one
				false,
			},
			gadgetCfg: implictMentionNonSupportedDatasource,
		},
		{
			comment: "implicit mentioned datasource in seed not installed and supported datasource in seed installed due to intersection with gadget with implicit supported",
			seedCfgs: []string{
				maasCfg1,                             // MAAS specific config
				maasCfg4,                             // generic config that passes filtering
				maasCfg5,                             // MAAS specific config
				implictMentionNonSupportedDatasource, // extra that implicitly mentions GCE
			},
			resultCfgCopied: []bool{
				true,
				true,
				true,
				false, // the implicit GCE one
			},
			gadgetCfg:                 explicitSupportedAndNonSupportedDatasources,
			expDsRestrictFileContents: restrictDatasourceMAASFile,
		},
		{
			comment:         "entirely filtered out seed config not installed",
			seedCfgs:        []string{maasCfg3},
			resultCfgCopied: []bool{false},
		},
		{
			comment:         "entirely filtered out seed config not installed + gadget with explicit supported datasource",
			seedCfgs:        []string{maasCfg3},
			resultCfgCopied: []bool{false},
			gadgetCfg:       explicitSupportedDatasource,
		},
		{
			comment: "implicitly mentioned supported datasource in gadget + explicit no datasource in seed",
			seedCfgs: []string{
				explicitNoDatasourceAllowed,
			},
			resultCfgCopied: []bool{false},
			gadgetCfg:       implicitMentionSupportedDatasource,
		},
		{
			comment: "MAAS and GCE in seed gets installed in dangerous",
			grade:   "dangerous",
			seedCfgs: []string{
				maasCfg1,
				maasCfg2,
				maasCfg3,
				maasCfg4,
				maasCfg5,
				implictMentionNonSupportedDatasource,
			},
			resultCfgCopied: []bool{true, true, true, true, true, true},
		},
		{
			comment: "MAAS and GCE in seed gets installed in dangerous with gadget MAAS",
			grade:   "dangerous",
			seedCfgs: []string{
				maasCfg1,
				maasCfg2,
				maasCfg3,
				maasCfg4,
				maasCfg5,
				implictMentionNonSupportedDatasource,
			},
			gadgetCfg:       implicitMentionSupportedDatasource,
			resultCfgCopied: []bool{true, true, true, true, true, true},
		},
	}

	for _, t := range tt {
		comment := Commentf(t.comment)
		var seedSrcNames []string
		var cloudCfgSrcDir string
		c.Assert(t.seedCfgs, HasLen, len(t.resultCfgCopied), comment)
		if len(t.seedCfgs) != 0 {
			cloudCfgSrcDir, seedSrcNames = s.makeCloudCfgSrcDirFiles(c, t.seedCfgs...)
		}

		var gadgetDir string
		if t.gadgetCfg != "" {
			gadgetDir = s.makeGadgetCloudConfFile(c, t.gadgetCfg)
		}

		if t.grade == "" {
			t.grade = "signed"
		}
		err := sysconfig.ConfigureTargetSystem(fake20Model(t.grade), &sysconfig.Options{
			AllowCloudInit:  true,
			TargetRootDir:   filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"),
			CloudInitSrcDir: cloudCfgSrcDir,
			GadgetDir:       gadgetDir,
		})
		c.Assert(err, IsNil, comment)

		ubuntuDataCloudCfg := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud.cfg.d/")
		for i, name := range seedSrcNames {
			if t.resultCfgCopied[i] {
				c.Check(filepath.Join(ubuntuDataCloudCfg, "90_"+name), testutil.FilePresent, comment)
			} else {
				c.Check(filepath.Join(ubuntuDataCloudCfg, "90_"+name), testutil.FileAbsent, comment)
			}
		}

		if t.gadgetCfg != "" {
			ubuntuDataCloudCfg := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud.cfg.d/")
			c.Check(filepath.Join(ubuntuDataCloudCfg, "80_device_gadget.cfg"), testutil.FileEquals, t.gadgetCfg)

		}

		// check the restrict file we should have installed in some cases too
		restrictFile := filepath.Join(ubuntuDataCloudCfg, "99_snapd_datasource.cfg")
		if t.expDsRestrictFileContents != "" {
			c.Check(restrictFile, testutil.FileEquals, t.expDsRestrictFileContents, comment)
		} else {
			c.Check(restrictFile, testutil.FileAbsent, comment)
		}

		// make sure the disabled file is absent
		ubuntuDataCloudDisabled := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud-init.disabled")
		c.Check(ubuntuDataCloudDisabled, testutil.FileAbsent)

		// need to clear this dir each time as it doesn't change for each
		// iteration
		c.Assert(os.RemoveAll(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data")), IsNil)
	}
}

func (s *sysconfigSuite) TestInstallModeCloudInitDisallowedGradeSecuredDoesDisable(c *C) {
	err := sysconfig.ConfigureTargetSystem(fake20Model("secured"), &sysconfig.Options{
		AllowCloudInit: false,
		TargetRootDir:  filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"),
	})
	c.Assert(err, IsNil)

	ubuntuDataCloudDisabled := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud-init.disabled")
	c.Check(ubuntuDataCloudDisabled, testutil.FilePresent)
}

func (s *sysconfigSuite) TestInstallModeCloudInitAllowedGradeSecuredIgnoresSrcButDoesNotDisable(c *C) {
	cloudCfgSrcDir, _ := s.makeCloudCfgSrcDirFiles(c)

	err := sysconfig.ConfigureTargetSystem(fake20Model("secured"), &sysconfig.Options{
		AllowCloudInit:  true,
		CloudInitSrcDir: cloudCfgSrcDir,
		TargetRootDir:   filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"),
	})
	c.Assert(err, IsNil)

	// the disable file is not present
	ubuntuDataCloudDisabled := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud-init.disabled")
	c.Check(ubuntuDataCloudDisabled, testutil.FileAbsent)

	// but we did not copy the config files from ubuntu-seed, even though they
	// are there and cloud-init is not disabled
	ubuntuDataCloudCfg := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud.cfg.d/")
	c.Check(filepath.Join(ubuntuDataCloudCfg, "foo.cfg"), testutil.FileAbsent)
	c.Check(filepath.Join(ubuntuDataCloudCfg, "bar.cfg"), testutil.FileAbsent)
}

// this test is the same as the logic from install mode devicestate, where we
// want to install cloud-init configuration not onto the running, ephemeral
// writable, but rather the host writable partition that will be used upon
// reboot into run mode
func (s *sysconfigSuite) TestInstallModeCloudInitInstallsOntoHostRunMode(c *C) {
	cloudCfgSrcDir, cfgFileNames := s.makeCloudCfgSrcDirFiles(c, "#cloud-config foo", "#cloud-config bar")

	err := sysconfig.ConfigureTargetSystem(fake20Model("dangerous"), &sysconfig.Options{
		AllowCloudInit:  true,
		CloudInitSrcDir: cloudCfgSrcDir,
		TargetRootDir:   filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"),
	})
	c.Assert(err, IsNil)

	// and did copy the cloud-init files
	ubuntuDataCloudCfg := filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data"), "_writable_defaults/etc/cloud/cloud.cfg.d/")
	c.Check(filepath.Join(ubuntuDataCloudCfg, "90_"+cfgFileNames[0]), testutil.FileEquals, "#cloud-config foo")
	c.Check(filepath.Join(ubuntuDataCloudCfg, "90_"+cfgFileNames[1]), testutil.FileEquals, "#cloud-config bar")
}

func (s *sysconfigSuite) TestCloudInitStatusUnhappy(c *C) {
	cmd := testutil.MockCommand(c, "cloud-init", `
echo cloud-init borken
exit 1
`)

	status, err := sysconfig.CloudInitStatus()
	c.Assert(err, ErrorMatches, "cloud-init borken")
	c.Assert(status, Equals, sysconfig.CloudInitErrored)
	c.Assert(cmd.Calls(), DeepEquals, [][]string{
		{"cloud-init", "status"},
	})
}

func (s *sysconfigSuite) TestCloudInitStatus(c *C) {
	tt := []struct {
		comment         string
		cloudInitOutput string
		exitCode        int
		exp             sysconfig.CloudInitState
		restrictedFile  bool
		disabledFile    bool
		disabledKernel  bool
		expError        string
		expectedLog     string
	}{
		{
			comment:         "done",
			cloudInitOutput: "status: done",
			exp:             sysconfig.CloudInitDone,
		},
		{
			comment:         "done",
			cloudInitOutput: "status: done",
			exp:             sysconfig.CloudInitDone,
			exitCode:        2,
			expectedLog:     `.*cloud-init status returned 'recoverable error' status: cloud-init completed but experienced errors\n`,
		},
		{
			comment:         "running",
			cloudInitOutput: "status: running",
			exp:             sysconfig.CloudInitEnabled,
		},
		{
			comment:         "not run",
			cloudInitOutput: "status: not run",
			exp:             sysconfig.CloudInitEnabled,
		},
		{
			comment:         "new unrecognized state",
			cloudInitOutput: "status: newfangledstatus",
			exp:             sysconfig.CloudInitEnabled,
		},
		{
			comment:        "restricted by snapd",
			restrictedFile: true,
			exp:            sysconfig.CloudInitRestrictedBySnapd,
		},
		{
			comment:         "disabled temporarily",
			cloudInitOutput: "status: disabled",
			exp:             sysconfig.CloudInitUntriggered,
		},
		{
			comment:      "disabled permanently via file",
			disabledFile: true,
			exp:          sysconfig.CloudInitDisabledPermanently,
		},
		{
			comment:        "disabled permanently via kernel commandline",
			disabledKernel: true,
			exp:            sysconfig.CloudInitDisabledPermanently,
		},
		{
			comment:         "errored w/ exit code 0",
			cloudInitOutput: "status: error",
			exp:             sysconfig.CloudInitErrored,
			exitCode:        0,
		},
		{
			comment:         "errored w/ exit code 1",
			cloudInitOutput: "status: error",
			exp:             sysconfig.CloudInitErrored,
			exitCode:        1,
		},
		{
			comment:         "broken cloud-init output w/ exit code 0",
			cloudInitOutput: "broken cloud-init output",
			expError:        "invalid cloud-init output: broken cloud-init output",
		},
		{
			comment:         "broken cloud-init output w/ exit code 1",
			cloudInitOutput: "broken cloud-init output",
			exitCode:        1,
			expError:        "broken cloud-init output",
		},
		{
			comment:         "normal cloud-init output w/ exit code 1",
			cloudInitOutput: "status: foobar",
			exitCode:        1,
			expError:        "cloud-init errored: status: foobar",
		},
	}

	for _, t := range tt {
		old := dirs.GlobalRootDir
		dirs.SetRootDir(c.MkDir())
		defer func() { dirs.SetRootDir(old) }()
		cmd := testutil.MockCommand(c, "cloud-init", fmt.Sprintf(`
if [ "$1" = "status" ]; then
	echo '%s'
	exit %d
else 
	echo "unexpected args, $"
	exit 1
fi
		`, t.cloudInitOutput, t.exitCode))

		if t.disabledFile {
			cloudDir := filepath.Join(dirs.GlobalRootDir, "etc/cloud")
			err := os.MkdirAll(cloudDir, 0755)
			c.Assert(err, IsNil)
			err = os.WriteFile(filepath.Join(cloudDir, "cloud-init.disabled"), nil, 0644)
			c.Assert(err, IsNil)
		}

		mockProcCmdline := filepath.Join(s.tmpdir, "proc/cmdline")
		if t.disabledKernel {
			err := os.WriteFile(mockProcCmdline, []byte("BOOT_IMAGE=/vmlinuz-6.1.53- root=UUID=63642d181-ad10-4457-80b0-14289c2183ef ro cloud-init=disabled panic_on_warn"), 0644)
			c.Assert(err, IsNil)
		} else {
			err := os.WriteFile(mockProcCmdline, []byte("BOOT_IMAGE=/vmlinuz-6.1.53- root=UUID=63642d181-ad10-4457-80b0-14289c2183ef ro cloud-init=enabled panic_on_warn"), 0644)
			c.Assert(err, IsNil)
		}

		if t.restrictedFile {
			cloudDir := filepath.Join(dirs.GlobalRootDir, "etc/cloud/cloud.cfg.d")
			err := os.MkdirAll(cloudDir, 0755)
			c.Assert(err, IsNil)
			err = os.WriteFile(filepath.Join(cloudDir, "zzzz_snapd.cfg"), nil, 0644)
			c.Assert(err, IsNil)
		}

		logBuf, restore := logger.MockLogger()
		defer restore()

		status, err := sysconfig.CloudInitStatus()
		if t.expError != "" {
			c.Assert(err, ErrorMatches, t.expError, Commentf(t.comment))
		} else {
			c.Assert(err, IsNil)
			c.Assert(status, Equals, t.exp, Commentf(t.comment))
		}

		// if the restricted file was there we don't call cloud-init status
		var expCalls [][]string
		if !t.restrictedFile && !t.disabledFile && !t.disabledKernel {
			expCalls = [][]string{
				{"cloud-init", "status"},
			}
		}

		c.Assert(cmd.Calls(), DeepEquals, expCalls, Commentf(t.comment))
		cmd.Restore()

		if t.expectedLog != "" {
			c.Check(logBuf.String(), Matches, t.expectedLog)
		}
	}
}

func (s *sysconfigSuite) TestCloudInitNotFoundStatus(c *C) {
	emptyDir := c.MkDir()
	oldPath := os.Getenv("PATH")
	defer func() {
		c.Assert(os.Setenv("PATH", oldPath), IsNil)
	}()
	os.Setenv("PATH", emptyDir)

	status, err := sysconfig.CloudInitStatus()
	c.Assert(err, IsNil)
	c.Check(status, Equals, sysconfig.CloudInitNotFound)
}

var gceCloudInitStatusJSON = `{
	"v1": {
	 "datasource": "DataSourceGCE",
	 "init": {
	  "errors": [],
	  "finished": 1591751113.4536479,
	  "start": 1591751112.130069
	 },
	 "stage": null
	}
}
`

var multipassNoCloudCloudInitStatusJSON = `{
 "v1": {
  "datasource": "DataSourceNoCloud [seed=/dev/sr0][dsmode=net]",
  "init": {
   "errors": [],
   "finished": 1591788514.4656117,
   "start": 1591788514.2607572
  },
  "stage": null
 }
}`

var localNoneCloudInitStatusJSON = `{
 "v1": {
  "datasource": "DataSourceNone",
  "init": {
   "errors": [],
   "finished": 1591788514.4656117,
   "start": 1591788514.2607572
  },
  "stage": null
 }
}`

var lxdNoCloudCloudInitStatusJSON = `{
 "v1": {
  "datasource": "DataSourceNoCloud [seed=/var/lib/cloud/seed/nocloud-net][dsmode=net]",
  "init": {
   "errors": [],
   "finished": 1591788737.3982718,
   "start": 1591788736.9015596
  },
  "stage": null
 }
}`

var restrictNoCloudYaml = `datasource_list: [NoCloud]
datasource:
  NoCloud:
    fs_label: null
manual_cache_clean: true
`

func (s *sysconfigSuite) TestRestrictCloudInit(c *C) {
	tt := []struct {
		comment                string
		state                  sysconfig.CloudInitState
		sysconfOpts            *sysconfig.CloudInitRestrictOptions
		cloudInitStatusJSON    string
		expError               string
		expRestrictYamlWritten string
		expDatasource          string
		expAction              string
		expDisableFile         bool
	}{
		{
			comment:  "already disabled",
			state:    sysconfig.CloudInitDisabledPermanently,
			expError: "cannot restrict cloud-init: already disabled",
		},
		{
			comment:  "already restricted",
			state:    sysconfig.CloudInitRestrictedBySnapd,
			expError: "cannot restrict cloud-init: already restricted",
		},
		{
			comment:  "errored",
			state:    sysconfig.CloudInitErrored,
			expError: "cannot restrict cloud-init in error or enabled state",
		},
		{
			comment:  "enable (not running)",
			state:    sysconfig.CloudInitEnabled,
			expError: "cannot restrict cloud-init in error or enabled state",
		},
		{
			comment: "errored w/ force disable",
			state:   sysconfig.CloudInitErrored,
			sysconfOpts: &sysconfig.CloudInitRestrictOptions{
				ForceDisable: true,
			},
			expAction:      "disable",
			expDisableFile: true,
		},
		{
			comment: "enable (not running) w/ force disable",
			state:   sysconfig.CloudInitEnabled,
			sysconfOpts: &sysconfig.CloudInitRestrictOptions{
				ForceDisable: true,
			},
			expAction:      "disable",
			expDisableFile: true,
		},
		{
			comment:        "untriggered",
			state:          sysconfig.CloudInitUntriggered,
			expAction:      "disable",
			expDisableFile: true,
		},
		{
			comment:        "unknown status",
			state:          -1,
			expAction:      "disable",
			expDisableFile: true,
		},
		{
			comment:             "gce done",
			state:               sysconfig.CloudInitDone,
			cloudInitStatusJSON: gceCloudInitStatusJSON,
			expDatasource:       "GCE",
			expAction:           "restrict",
			expRestrictYamlWritten: `datasource_list: [GCE]
`,
		},
		{
			comment:                "nocloud done",
			state:                  sysconfig.CloudInitDone,
			cloudInitStatusJSON:    multipassNoCloudCloudInitStatusJSON,
			expDatasource:          "NoCloud",
			expAction:              "restrict",
			expRestrictYamlWritten: restrictNoCloudYaml,
		},
		{
			comment:             "nocloud uc20 done",
			state:               sysconfig.CloudInitDone,
			cloudInitStatusJSON: multipassNoCloudCloudInitStatusJSON,
			sysconfOpts: &sysconfig.CloudInitRestrictOptions{
				DisableAfterLocalDatasourcesRun: true,
			},
			expDatasource:  "NoCloud",
			expAction:      "disable",
			expDisableFile: true,
		},
		{
			comment:             "none uc20 done",
			state:               sysconfig.CloudInitDone,
			cloudInitStatusJSON: localNoneCloudInitStatusJSON,
			sysconfOpts: &sysconfig.CloudInitRestrictOptions{
				DisableAfterLocalDatasourcesRun: true,
			},
			expDatasource:  "None",
			expAction:      "disable",
			expDisableFile: true,
		},

		// the two cases for lxd and multipass are effectively the same, but as
		// the largest known users of cloud-init w/ UC, we leave them as
		// separate test cases for their different cloud-init status.json
		// content
		{
			comment:                "nocloud multipass done",
			state:                  sysconfig.CloudInitDone,
			cloudInitStatusJSON:    multipassNoCloudCloudInitStatusJSON,
			expDatasource:          "NoCloud",
			expAction:              "restrict",
			expRestrictYamlWritten: restrictNoCloudYaml,
		},
		{
			comment:                "nocloud seed lxd done",
			state:                  sysconfig.CloudInitDone,
			cloudInitStatusJSON:    lxdNoCloudCloudInitStatusJSON,
			expDatasource:          "NoCloud",
			expAction:              "restrict",
			expRestrictYamlWritten: restrictNoCloudYaml,
		},
		{
			comment:             "nocloud uc20 multipass done",
			state:               sysconfig.CloudInitDone,
			cloudInitStatusJSON: multipassNoCloudCloudInitStatusJSON,
			sysconfOpts: &sysconfig.CloudInitRestrictOptions{
				DisableAfterLocalDatasourcesRun: true,
			},
			expDatasource:  "NoCloud",
			expAction:      "disable",
			expDisableFile: true,
		},
		{
			comment:             "nocloud uc20 seed lxd done",
			state:               sysconfig.CloudInitDone,
			cloudInitStatusJSON: lxdNoCloudCloudInitStatusJSON,
			sysconfOpts: &sysconfig.CloudInitRestrictOptions{
				DisableAfterLocalDatasourcesRun: true,
			},
			expDatasource:  "NoCloud",
			expAction:      "disable",
			expDisableFile: true,
		},
		{
			comment:        "no cloud-init in $PATH",
			state:          sysconfig.CloudInitNotFound,
			expAction:      "disable",
			expDisableFile: true,
		},
	}

	for _, t := range tt {
		comment := Commentf("%s", t.comment)
		// setup status.json
		old := dirs.GlobalRootDir
		dirs.SetRootDir(c.MkDir())
		defer func() { dirs.SetRootDir(old) }()
		statusJSONFile := filepath.Join(dirs.GlobalRootDir, "/run/cloud-init/status.json")
		if t.cloudInitStatusJSON != "" {
			err := os.MkdirAll(filepath.Dir(statusJSONFile), 0755)
			c.Assert(err, IsNil, comment)
			err = os.WriteFile(statusJSONFile, []byte(t.cloudInitStatusJSON), 0644)
			c.Assert(err, IsNil, comment)
		}

		// if we expect snapd to write a yaml config file for cloud-init, ensure
		// the dir exists before hand
		if t.expRestrictYamlWritten != "" {
			err := os.MkdirAll(filepath.Join(dirs.GlobalRootDir, "/etc/cloud/cloud.cfg.d"), 0755)
			c.Assert(err, IsNil, comment)
		}

		res, err := sysconfig.RestrictCloudInit(t.state, t.sysconfOpts)
		if t.expError == "" {
			c.Assert(err, IsNil, comment)
			c.Assert(res.DataSource, Equals, t.expDatasource, comment)
			c.Assert(res.Action, Equals, t.expAction, comment)
			if t.expRestrictYamlWritten != "" {
				// check the snapd restrict yaml file that should have been written
				c.Assert(
					filepath.Join(dirs.GlobalRootDir, "/etc/cloud/cloud.cfg.d/zzzz_snapd.cfg"),
					testutil.FileEquals,
					t.expRestrictYamlWritten,
					comment,
				)
			}

			// if we expect the disable file to be written then check for it
			// otherwise ensure it was not written accidentally
			var fileCheck Checker
			if t.expDisableFile {
				fileCheck = testutil.FilePresent
			} else {
				fileCheck = testutil.FileAbsent
			}

			c.Assert(
				filepath.Join(dirs.GlobalRootDir, "/etc/cloud/cloud-init.disabled"),
				fileCheck,
				comment,
			)

		} else {
			c.Assert(err, ErrorMatches, t.expError, comment)
		}
	}
}

const maasCloudInitImplicitYAML = `
datasource:
  MAAS:
    foo: bar
`

const gceCloudInitImplicitYAML = `
datasource:
  GCE:
    foo: bar
`

const maasGadgetCloudInitImplicitLowerCaseYAML = `
datasource:
  maas:
    foo: bar
`

const explicitlyNoDatasourceYAML = `datasource_list: []`

const explicitlyNoDatasourceButAlsoImplicitlyAnotherYAML = `
datasource_list: []
reporting:
  NoCloud:
    foo: bar
`

const explicitlyMultipleMixedCaseMentioned = `
reporting:
  NoCloud:
    foo: bar
  maas:
    foo: bar
datasource:
  MAAS:
    foo: bar
  NOCLOUD:
    foo: bar
`

func (s *sysconfigSuite) TestCloudDatasourcesInUse(c *C) {
	tt := []struct {
		configFileContent string
		expError          string
		expRes            *sysconfig.CloudDatasourcesInUseResult
		comment           string
	}{
		{
			configFileContent: `datasource_list: [MAAS]`,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"MAAS"},
				Mentioned:         []string{"MAAS"},
			},
			comment: "explicitly allowed via datasource_list in upper case",
		},
		{
			configFileContent: `datasource_list: [maas]`,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"MAAS"},
				Mentioned:         []string{"MAAS"},
			},
			comment: "explicitly allowed via datasource_list in lower case",
		},
		{
			configFileContent: `datasource_list: [mAaS]`,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"MAAS"},
				Mentioned:         []string{"MAAS"},
			},
			comment: "explicitly allowed via datasource_list in random case",
		},
		{
			configFileContent: `datasource_list: [maas, maas]`,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"MAAS"},
				Mentioned:         []string{"MAAS"},
			},
			comment: "duplicated datasource in datasource_list",
		},
		{
			configFileContent: `datasource_list: [maas, MAAS]`,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"MAAS"},
				Mentioned:         []string{"MAAS"},
			},
			comment: "duplicated datasource in datasource_list with different cases",
		},
		{
			configFileContent: `datasource_list: [maas, GCE]`,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"GCE", "MAAS"},
				Mentioned:         []string{"GCE", "MAAS"},
			},
			comment: "multiple datasources in datasource list",
		},
		{
			configFileContent: maasCloudInitImplicitYAML,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				Mentioned: []string{"MAAS"},
			},
			comment: "implicitly mentioned datasource",
		},
		{
			configFileContent: maasGadgetCloudInitImplicitLowerCaseYAML,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				Mentioned: []string{"MAAS"},
			},
			comment: "implicitly mentioned datasource in lower case",
		},
		{
			configFileContent: explicitlyNoDatasourceYAML,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyNoneAllowed: true,
			},
			comment: "no datasources allowed at all",
		},
		{
			configFileContent: explicitlyNoDatasourceButAlsoImplicitlyAnotherYAML,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyNoneAllowed: true,
				Mentioned:             []string{"NOCLOUD"},
			},
			comment: "explicitly no datasources allowed, but still some mentioned",
		},
		{
			configFileContent: explicitlyMultipleMixedCaseMentioned,
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				Mentioned: []string{"MAAS", "NOCLOUD"},
			},
			comment: "multiple of same datasources mentioned in different cases",
		},
		{
			configFileContent: "i'm not yaml",
			expError:          "yaml: unmarshal errors.*\n.*cannot unmarshal.*",
			comment:           "invalid yaml",
		},
	}

	for _, t := range tt {
		comment := Commentf(t.comment)
		configFile := filepath.Join(c.MkDir(), "cloud.conf")
		err := os.WriteFile(configFile, []byte(t.configFileContent), 0644)
		c.Assert(err, IsNil, comment)
		res, err := sysconfig.CloudDatasourcesInUse(configFile)
		if t.expError != "" {
			c.Assert(err, ErrorMatches, t.expError, comment)
			continue
		}

		c.Assert(res, DeepEquals, t.expRes, comment)
	}
}

func (s *sysconfigSuite) TestCloudDatasourcesInUseForDirInUse(c *C) {
	tt := []struct {
		configFilesContents map[string]string
		expError            string
		expRes              *sysconfig.CloudDatasourcesInUseResult
		comment             string
	}{
		{
			configFilesContents: map[string]string{
				"maas.cfg": `datasource_list: [MAAS]`,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"MAAS"},
				Mentioned:         []string{"MAAS"},
			},
			comment: "explicitly allowed via datasource_list",
		},
		{
			configFilesContents: map[string]string{
				"1_maas.cfg": `datasource_list: [MAAS]`,
				"2_none.cfg": `datasource_list: []`,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyNoneAllowed: true,
				Mentioned:             []string{"MAAS"},
			},
			comment: "explicit none overwriting explicit allowing",
		},
		{
			configFilesContents: map[string]string{
				"1_none.cfg": `datasource_list: []`,
				"2_maas.cfg": `datasource_list: [MAAS]`,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyNoneAllowed: false,
				ExplicitlyAllowed:     []string{"MAAS"},
				Mentioned:             []string{"MAAS"},
			},
			comment: "explicit allowing overwriting explicit none",
		},
		{
			configFilesContents: map[string]string{
				"maas.cfg": maasCloudInitImplicitYAML,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				Mentioned: []string{"MAAS"},
			},
			comment: "implicit datasource",
		},
		{
			configFilesContents: map[string]string{
				"1_gce.cfg":  gceCloudInitImplicitYAML,
				"2_maas.cfg": maasCloudInitImplicitYAML,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				Mentioned: []string{"GCE", "MAAS"},
			},
			comment: "multiple implicit datasources",
		},
		{
			configFilesContents: map[string]string{
				"1_maas.cfg": maasCloudInitImplicitYAML,
				"2_gce.cfg":  gceCloudInitImplicitYAML,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				Mentioned: []string{"GCE", "MAAS"},
			},
			comment: "multiple implicit datasources in different lexical order",
		},
		{
			configFilesContents: map[string]string{
				"maas.cfg": `datasource_list: [MAAS]`,
				"gce.cfg":  gceCloudInitImplicitYAML,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed: []string{"MAAS"},
				Mentioned:         []string{"GCE", "MAAS"},
			},
			comment: "implicit datasources and explicit datasource",
		},
		{
			configFilesContents: map[string]string{},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				ExplicitlyAllowed:     nil,
				ExplicitlyNoneAllowed: false,
				Mentioned:             nil,
			},
			comment: "no files means empty result",
		},
		{
			configFilesContents: map[string]string{
				"maas.conf": `datasource_list: [MAAS]`,
			},
			expRes:  &sysconfig.CloudDatasourcesInUseResult{},
			comment: "only .cfg files are allowed",
		},
		{
			configFilesContents: map[string]string{
				"maas":    `datasource_list: [MAAS]`,
				"gce.cfg": gceCloudInitImplicitYAML,
			},
			expRes: &sysconfig.CloudDatasourcesInUseResult{
				Mentioned: []string{"GCE"},
			},
			comment: "with .cfg and non-.cfg files, only .cfg files are allowed",
		},
	}

	for _, t := range tt {
		comment := Commentf(t.comment)

		dir := c.MkDir()
		for basename, content := range t.configFilesContents {
			configFile := filepath.Join(dir, basename)
			err := os.WriteFile(configFile, []byte(content), 0644)
			c.Assert(err, IsNil, comment)
		}

		res, err := sysconfig.CloudDatasourcesInUseForDir(dir)
		if t.expError != "" {
			c.Assert(err, ErrorMatches, t.expError, comment)
			continue
		}

		c.Assert(res, DeepEquals, t.expRes, comment)
	}
}

const maasCfg1 = `#cloud-config
reporting:
  maas:
    type: webhook
    endpoint: http://172-16-99-0--24.maas-internal:5248/MAAS/metadata/status/foo
    consumer_key: foothefoo
    token_key: foothefoothesecond
    token_secret: foothesecretfoo
`

const maasCfg2 = `datasource_list: [ MAAS ]
`

const maasCfg3 = `#cloud-config
snappy:
  email: foo@foothewebsite.com
`

const maasCfg4 = `#cloud-config
network:
  config:
  - id: enp3s0
    mac_address: 52:54:00:b4:9e:25
    mtu: 1500
    name: enp3s0
    subnets:
    - address: 172.16.99.7/24
      dns_nameservers:
      - 172.16.99.1
      dns_search:
      - maas
      type: static
    type: physical
  - address: 172.16.99.1
    search:
    - maas
    type: nameserver
  version: 1
`

const maasCfg5 = `#cloud-config
datasource:
  MAAS:
    consumer_key: foothefoo
    metadata_url: http://172-16-99-0--24.maas-internal:5248/MAAS/metadata/
    token_key: foothefoothesecond
    token_secret: foothesecretfoo
`

func (s *sysconfigSuite) TestFilterCloudCfgFile(c *C) {
	tt := []struct {
		comment string
		inStr   string
		outStr  string
		err     string
	}{
		{
			comment: "maas reporting cloud-init config",
			inStr:   maasCfg1,
			outStr:  maasCfg1,
		},
		{
			comment: "maas datasource list cloud-init config",
			inStr:   maasCfg2,
			outStr: `#cloud-config
datasource_list:
- MAAS
`,
		},
		{
			comment: "maas snappy user cloud-init config",
			inStr:   maasCfg3,
			// we don't support using the snappy key
			outStr: "",
		},
		{
			comment: "maas networking cloud-init config",
			inStr:   maasCfg4,
			outStr:  maasCfg4,
		},
		{
			comment: "maas datasource cloud-init config",
			inStr:   maasCfg5,
			outStr:  maasCfg5,
		},
		{
			comment: "unsupported datasource in datasource section cloud-init config",
			inStr: `#cloud-config
datasource:
  NoCloud:
    consumer_key: fooooooo
`,
			outStr: "",
		},
		{
			comment: "unsupported datasource in reporting section cloud-init config",
			inStr: `#cloud-config
reporting:
  NoCloud:
    consumer_key: fooooooo
`,
			outStr: "",
		},
		{
			comment: "unsupported datasource in datasource_list with supported one",
			inStr: `#cloud-config
datasource_list: [MAAS, NoCloud]
`,
			outStr: `#cloud-config
datasource_list:
- MAAS
`,
		},
		{
			comment: "unsupported datasources in multiple keys with supported ones",
			inStr: `#cloud-config
datasource:
  MAAS:
    consumer_key: fooooooo
  NoCloud:
    consumer_key: fooooooo

reporting:
  MAAS:
    type: webhook
  NoCloud:
    type: webhook

datasource_list: [MAAS, NoCloud]
`,
			outStr: `#cloud-config
datasource:
  MAAS:
    consumer_key: fooooooo
datasource_list:
- MAAS
reporting:
  MAAS:
    type: webhook
`,
		},
		{
			comment: "unrelated keys",
			inStr: `#cloud-config
datasource:
  MAAS:
    consumer_key: fooooooo
    foo: bar

reporting:
  MAAS:
    type: webhook
    new_foo: new_bar

extra_foo: extra_bar
`,
			outStr: `#cloud-config
datasource:
  MAAS:
    consumer_key: fooooooo
reporting:
  MAAS:
    type: webhook
`,
		},
	}

	dir := c.MkDir()
	for i, t := range tt {
		comment := Commentf(t.comment)
		inFile := filepath.Join(dir, fmt.Sprintf("%d.cfg", i))
		err := os.WriteFile(inFile, []byte(t.inStr), 0755)
		c.Assert(err, IsNil, comment)

		out, err := sysconfig.FilterCloudCfgFile(inFile, []string{"MAAS"})
		if t.err != "" {
			c.Assert(err, ErrorMatches, t.err, comment)
			continue
		}
		c.Assert(err, IsNil, comment)

		// no expected output means that everything was filtered out
		if t.outStr == "" {
			c.Assert(out, Equals, "", comment)
			continue
		}

		// otherwise we have expected output in the file
		b, err := os.ReadFile(out)
		c.Assert(err, IsNil, comment)
		c.Assert(string(b), Equals, t.outStr, comment)
	}
}