-
Notifications
You must be signed in to change notification settings - Fork 57
/
classic_states.go
1412 lines (1191 loc) · 46.4 KB
/
classic_states.go
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
package statemachine
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"github.com/snapcore/snapd/image"
"github.com/snapcore/snapd/image/preseed"
"github.com/snapcore/snapd/interfaces/builtin"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/seed/seedwriter"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/store"
"github.com/canonical/ubuntu-image/internal/helper"
"github.com/canonical/ubuntu-image/internal/imagedefinition"
"github.com/canonical/ubuntu-image/internal/ppa"
)
var (
seedVersionRegex = regexp.MustCompile(`^[a-z0-9].*`)
localePresentRegex = regexp.MustCompile(`(?m)^LANG=|LC_[A-Z_]+=`)
)
var buildGadgetTreeState = stateFunc{"build_gadget_tree", (*StateMachine).buildGadgetTree}
// Build the gadget tree
func (stateMachine *StateMachine) buildGadgetTree() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
// make the gadget directory under scratch
gadgetDir := filepath.Join(stateMachine.tempDirs.scratch, "gadget")
err := classicStateMachine.prepareGadgetDir(gadgetDir)
if err != nil {
return err
}
makeCmd := execCommand("make")
// if a make target was specified then add it to the command
if classicStateMachine.ImageDef.Gadget.GadgetTarget != "" {
makeCmd.Args = append(makeCmd.Args, classicStateMachine.ImageDef.Gadget.GadgetTarget)
}
// add ARCH and SERIES environment variables for making the gadget tree
makeCmd.Env = append(makeCmd.Env, []string{
fmt.Sprintf("ARCH=%s", classicStateMachine.ImageDef.Architecture),
fmt.Sprintf("SERIES=%s", classicStateMachine.ImageDef.Series),
}...)
// add the current ENV to the command
makeCmd.Env = append(makeCmd.Env, os.Environ()...)
makeCmd.Dir = gadgetDir
makeOutput := helper.SetCommandOutput(makeCmd, classicStateMachine.commonFlags.Debug)
if err := makeCmd.Run(); err != nil {
return fmt.Errorf("Error running \"make\" in gadget source. "+
"Error is \"%s\". Full output below:\n%s",
err.Error(), makeOutput.String())
}
return nil
}
// prepareGadgetDir prepares the gadget directory prior to running the make command
func (classicStateMachine *ClassicStateMachine) prepareGadgetDir(gadgetDir string) error {
err := osMkdir(gadgetDir, 0755)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("Error creating scratch/gadget directory: %s", err.Error())
}
switch classicStateMachine.ImageDef.Gadget.GadgetType {
case "git":
err := cloneGitRepo(classicStateMachine.ImageDef, gadgetDir)
if err != nil {
return fmt.Errorf("Error cloning gadget repository: \"%s\"", err.Error())
}
case "directory":
gadgetTreePath := strings.TrimPrefix(classicStateMachine.ImageDef.Gadget.GadgetURL, "file://")
if !filepath.IsAbs(gadgetTreePath) {
gadgetTreePath = filepath.Join(classicStateMachine.ConfDefPath, gadgetTreePath)
}
// copy the source tree to the workdir
files, err := osReadDir(gadgetTreePath)
if err != nil {
return fmt.Errorf("Error reading gadget tree: %s", err.Error())
}
for _, gadgetFile := range files {
srcFile := filepath.Join(gadgetTreePath, gadgetFile.Name())
if err := osutilCopySpecialFile(srcFile, gadgetDir); err != nil {
return fmt.Errorf("Error copying gadget source: %s", err.Error())
}
}
}
return nil
}
var prepareGadgetTreeState = stateFunc{"prepare_gadget_tree", (*StateMachine).prepareGadgetTree}
// Prepare the gadget tree
func (stateMachine *StateMachine) prepareGadgetTree() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
gadgetDir := filepath.Join(classicStateMachine.tempDirs.unpack, "gadget")
err := osMkdirAll(gadgetDir, 0755)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("Error creating unpack directory: %s", err.Error())
}
// recursively copy the gadget tree to unpack/gadget
var gadgetTree string
if classicStateMachine.ImageDef.Gadget.GadgetType == "prebuilt" {
gadgetTree = strings.TrimPrefix(classicStateMachine.ImageDef.Gadget.GadgetURL, "file://")
if !filepath.IsAbs(gadgetTree) {
gadgetTree, err = filepath.Abs(gadgetTree)
if err != nil {
return fmt.Errorf("Error finding the absolute path of the gadget tree: %s", err.Error())
}
}
} else {
gadgetTree = filepath.Join(classicStateMachine.tempDirs.scratch, "gadget", "install")
}
entries, err := osReadDir(gadgetTree)
if err != nil {
return fmt.Errorf("Error reading gadget tree: %s", err.Error())
}
for _, gadgetEntry := range entries {
srcFile := filepath.Join(gadgetTree, gadgetEntry.Name())
if err := osutilCopySpecialFile(srcFile, gadgetDir); err != nil {
return fmt.Errorf("Error copying gadget tree entry: %s", err.Error())
}
}
classicStateMachine.YamlFilePath = filepath.Join(gadgetDir, gadgetYamlPathInTree)
return nil
}
// fixHostname set fresh hostname since debootstrap copies /etc/hostname from build environment
func (stateMachine *StateMachine) fixHostname() error {
hostname := filepath.Join(stateMachine.tempDirs.chroot, "etc", "hostname")
hostnameFile, err := osOpenFile(hostname, os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("unable to open hostname file: %w", err)
}
defer hostnameFile.Close()
_, err = hostnameFile.WriteString("ubuntu\n")
if err != nil {
return fmt.Errorf("unable to write hostname: %w", err)
}
return nil
}
var createChrootState = stateFunc{"create_chroot", (*StateMachine).createChroot}
// Bootstrap a chroot environment to install packages in. It will eventually
// become the rootfs of the image
func (stateMachine *StateMachine) createChroot() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
if err := osMkdir(stateMachine.tempDirs.chroot, 0755); err != nil {
return fmt.Errorf("Failed to create chroot directory %s : %s", stateMachine.tempDirs.chroot, err.Error())
}
debootstrapCmd := generateDebootstrapCmd(classicStateMachine.ImageDef,
stateMachine.tempDirs.chroot,
)
debootstrapOutput := helper.SetCommandOutput(debootstrapCmd, classicStateMachine.commonFlags.Debug)
if err := debootstrapCmd.Run(); err != nil {
return fmt.Errorf("Error running debootstrap command \"%s\". Error is \"%s\". Output is: \n%s",
debootstrapCmd.String(), err.Error(), debootstrapOutput.String())
}
err := stateMachine.fixHostname()
if err != nil {
return err
}
// debootstrap also copies /etc/resolv.conf from build environment; truncate it
// as to not leak the host files into the built image
resolvConf := filepath.Join(stateMachine.tempDirs.chroot, "etc", "resolv.conf")
if err = osTruncate(resolvConf, 0); err != nil {
return fmt.Errorf("Error truncating resolv.conf: %s", err.Error())
}
if *classicStateMachine.ImageDef.Rootfs.SourcesListDeb822 {
err := stateMachine.setDeb822SourcesList(classicStateMachine.ImageDef.Deb822BuildSourcesList())
if err != nil {
return err
}
return stateMachine.setLegacySourcesList(imagedefinition.LegacySourcesListComment)
}
return stateMachine.setLegacySourcesList(classicStateMachine.ImageDef.LegacyBuildSourcesList())
}
var addExtraPPAsState = stateFunc{"add_extra_ppas", (*StateMachine).addExtraPPAs}
// addExtraPPAs adds PPAs to the /etc/apt/sources.list.d directory
func (stateMachine *StateMachine) addExtraPPAs() (err error) {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
for _, extraPPA := range classicStateMachine.ImageDef.Customization.ExtraPPAs {
p := ppa.New(extraPPA, *classicStateMachine.ImageDef.Rootfs.SourcesListDeb822, classicStateMachine.ImageDef.Series)
err := p.Add(classicStateMachine.tempDirs.chroot, classicStateMachine.commonFlags.Debug)
if err != nil {
return err
}
}
return nil
}
var cleanExtraPPAsState = stateFunc{"clean_extra_ppas", (*StateMachine).cleanExtraPPAs}
// cleanExtraPPAs cleans previously added PPA to the source list
func (stateMachine *StateMachine) cleanExtraPPAs() (err error) {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
for _, extraPPA := range classicStateMachine.ImageDef.Customization.ExtraPPAs {
p := ppa.New(extraPPA, *classicStateMachine.ImageDef.Rootfs.SourcesListDeb822, classicStateMachine.ImageDef.Series)
err := p.Remove(stateMachine.tempDirs.chroot)
if err != nil {
return err
}
}
return nil
}
var installPackagesState = stateFunc{"install_packages", (*StateMachine).installPackages}
// Install packages in the chroot environment
func (stateMachine *StateMachine) installPackages() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
err := helperBackupAndCopyResolvConf(classicStateMachine.tempDirs.chroot)
if err != nil {
return fmt.Errorf("Error setting up /etc/resolv.conf in the chroot: \"%s\"", err.Error())
}
stateMachine.gatherPackages(&classicStateMachine.ImageDef)
// setupCmds should be filled as a FIFO list
var setupCmds []*exec.Cmd
// teardownCmds should be filled as a LIFO list
var teardownCmds []*exec.Cmd
mountPoints := []*mountPoint{}
// Make sure we left the system as clean as possible if something has gone wrong
defer func() {
err = teardownMount(stateMachine.tempDirs.chroot, mountPoints, teardownCmds, err, stateMachine.commonFlags.Debug)
}()
// mount some necessary partitions in the chroot
mountPoints = append(mountPoints,
&mountPoint{
src: "devtmpfs-build",
basePath: stateMachine.tempDirs.chroot,
relpath: "/dev",
typ: "devtmpfs",
},
&mountPoint{
src: "devpts-build",
basePath: stateMachine.tempDirs.chroot,
relpath: "/dev/pts",
typ: "devpts",
opts: []string{"nodev", "nosuid"},
},
&mountPoint{
src: "proc-build",
basePath: stateMachine.tempDirs.chroot,
relpath: "/proc",
typ: "proc",
},
&mountPoint{
src: "sysfs-build",
basePath: stateMachine.tempDirs.chroot,
relpath: "/sys",
typ: "sysfs",
},
&mountPoint{
basePath: stateMachine.tempDirs.chroot,
relpath: "/run",
bind: true,
},
)
mountCmds, umountCmds, err := generateMountPointCmds(mountPoints, stateMachine.tempDirs.scratch)
if err != nil {
return err
}
setupCmds = append(setupCmds, mountCmds...)
teardownCmds = append(umountCmds, teardownCmds...)
teardownCmds = append([]*exec.Cmd{
execCommand("udevadm", "settle"),
}, teardownCmds...)
policyRcDPath := filepath.Join(classicStateMachine.tempDirs.chroot, "usr", "sbin", "policy-rc.d")
if osutil.FileExists(policyRcDPath) {
divertCmd, undivertCmd := divertPolicyRcD(stateMachine.tempDirs.chroot)
setupCmds = append(setupCmds, divertCmd)
teardownCmds = append([]*exec.Cmd{undivertCmd}, teardownCmds...)
}
err = helper.RunCmds(setupCmds, classicStateMachine.commonFlags.Debug)
if err != nil {
return err
}
unsetDenyingPolicyRcD, err := setDenyingPolicyRcD(policyRcDPath)
if err != nil {
return err
}
defer func() {
err = unsetDenyingPolicyRcD(err)
}()
restoreStartStopDaemon, err := backupReplaceStartStopDaemon(classicStateMachine.tempDirs.chroot)
if err != nil {
return err
}
defer func() {
err = restoreStartStopDaemon(err)
}()
initctlPath := filepath.Join(classicStateMachine.tempDirs.chroot, "sbin", "initctl")
if osutil.FileExists(initctlPath) {
restoreInitctl, err := backupReplaceInitctl(classicStateMachine.tempDirs.chroot)
if err != nil {
return err
}
defer func() {
err = restoreInitctl(err)
}()
}
installPackagesCmds := generateAptCmds(stateMachine.tempDirs.chroot, classicStateMachine.Packages)
err = helper.RunCmds(installPackagesCmds, classicStateMachine.commonFlags.Debug)
if err != nil {
return err
}
return nil
}
func (stateMachine *StateMachine) gatherPackages(imageDef *imagedefinition.ImageDefinition) {
if imageDef.Customization != nil {
for _, packageInfo := range imageDef.Customization.ExtraPackages {
stateMachine.Packages = append(stateMachine.Packages,
packageInfo.PackageName)
}
}
// Make sure to install the extra kernel if it is specified
if imageDef.Kernel != "" {
stateMachine.Packages = append(stateMachine.Packages,
imageDef.Kernel)
}
}
// generateMountPointCmds generate lists of mount/umount commands for a list of mountpoints
func generateMountPointCmds(mountPoints []*mountPoint, scratchDir string) (allMountCmds []*exec.Cmd, allUmountCmds []*exec.Cmd, err error) {
for _, mp := range mountPoints {
var mountCmds, umountCmds []*exec.Cmd
var err error
if mp.bind {
mp.src, err = osMkdirTemp(scratchDir, strings.Trim(mp.relpath, "/"))
if err != nil {
return nil, nil, fmt.Errorf("Error making temporary directory for mountpoint \"%s\": \"%s\"",
mp.relpath,
err.Error(),
)
}
}
mountCmds, umountCmds, err = mp.getMountCmd()
if err != nil {
return nil, nil, fmt.Errorf("Error preparing mountpoint \"%s\": \"%s\"",
mp.relpath,
err.Error(),
)
}
allMountCmds = append(allMountCmds, mountCmds...)
allUmountCmds = append(umountCmds, allUmountCmds...)
}
return allMountCmds, allUmountCmds, err
}
var verifyArtifactNamesState = stateFunc{"verify_artifact_names", (*StateMachine).verifyArtifactNames}
// Verify artifact names have volumes listed for multi-volume gadgets and set
// the volume names in the struct
func (stateMachine *StateMachine) verifyArtifactNames() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
if classicStateMachine.ImageDef.Artifacts == nil {
return nil
}
stateMachine.VolumeNames = make(map[string]string)
if len(stateMachine.GadgetInfo.Volumes) > 1 {
err := stateMachine.prepareImgArtifactsMultipleVolumes(classicStateMachine.ImageDef.Artifacts)
if err != nil {
return err
}
err = stateMachine.prepareQcow2ArtifactsMultipleVolumes(classicStateMachine.ImageDef.Artifacts)
if err != nil {
return err
}
} else {
stateMachine.prepareImgArtifactOneVolume(classicStateMachine.ImageDef.Artifacts)
stateMachine.prepareQcow2ArtifactOneVolume(classicStateMachine.ImageDef.Artifacts)
}
return nil
}
func (stateMachine *StateMachine) prepareImgArtifactsMultipleVolumes(artifacts *imagedefinition.Artifact) error {
if artifacts.Img == nil {
return nil
}
for _, img := range *artifacts.Img {
if img.ImgVolume == "" {
return fmt.Errorf("Volume names must be specified for each image when using a gadget with more than one volume")
}
stateMachine.VolumeNames[img.ImgVolume] = img.ImgName
}
return nil
}
// qcow2 img logic is complicated. If .img artifacts are already specified
// in the image definition for corresponding volumes, we will re-use those and
// convert them to a qcow2 image. Otherwise, we will create a raw .img file to
// use as an input file for the conversion.
// The names of these images are placed in the VolumeNames map, which is used
// as an input file for an eventual `qemu-convert` operation.
func (stateMachine *StateMachine) prepareQcow2ArtifactsMultipleVolumes(artifacts *imagedefinition.Artifact) error {
if artifacts.Qcow2 != nil {
for _, qcow2 := range *artifacts.Qcow2 {
if qcow2.Qcow2Volume == "" {
return fmt.Errorf("Volume names must be specified for each image when using a gadget with more than one volume")
}
// We can save a whole lot of disk I/O here if the volume is
// already specified as a .img file
if artifacts.Img != nil {
found := false
for _, img := range *artifacts.Img {
if img.ImgVolume == qcow2.Qcow2Volume {
found = true
}
}
if !found {
// if a .img artifact for this volume isn't explicitly stated in
// the image definition, then create one
stateMachine.VolumeNames[qcow2.Qcow2Volume] = fmt.Sprintf("%s.img", qcow2.Qcow2Name)
}
} else {
// no .img artifacts exist in the image definition,
// but we still need to create one to convert to qcow2
stateMachine.VolumeNames[qcow2.Qcow2Volume] = fmt.Sprintf("%s.img", qcow2.Qcow2Name)
}
}
}
return nil
}
func (stateMachine *StateMachine) prepareImgArtifactOneVolume(artifacts *imagedefinition.Artifact) {
if artifacts.Img == nil {
return
}
img := (*artifacts.Img)[0]
if img.ImgVolume == "" {
// there is only one volume, so get it from the map
volName := reflect.ValueOf(stateMachine.GadgetInfo.Volumes).MapKeys()[0].String()
stateMachine.VolumeNames[volName] = img.ImgName
} else {
stateMachine.VolumeNames[img.ImgVolume] = img.ImgName
}
}
// qcow2 img logic is complicated. If .img artifacts are already specified
// in the image definition for corresponding volumes, we will re-use those and
// convert them to a qcow2 image. Otherwise, we will create a raw .img file to
// use as an input file for the conversion.
// The names of these images are placed in the VolumeNames map, which is used
// as an input file for an eventual `qemu-convert` operation.
func (stateMachine *StateMachine) prepareQcow2ArtifactOneVolume(artifacts *imagedefinition.Artifact) {
if artifacts.Qcow2 == nil {
return
}
qcow2 := (*artifacts.Qcow2)[0]
if qcow2.Qcow2Volume == "" {
volName := reflect.ValueOf(stateMachine.GadgetInfo.Volumes).MapKeys()[0].String()
if artifacts.Img != nil {
qcow2.Qcow2Volume = volName
(*artifacts.Qcow2)[0] = qcow2
return // We will re-use the .img file in this case
}
// there is only one volume, so get it from the map
stateMachine.VolumeNames[volName] = fmt.Sprintf("%s.img", qcow2.Qcow2Name)
qcow2.Qcow2Volume = volName
(*artifacts.Qcow2)[0] = qcow2
} else {
if artifacts.Img != nil {
return // We will re-use the .img file in this case
}
stateMachine.VolumeNames[qcow2.Qcow2Volume] = fmt.Sprintf("%s.img", qcow2.Qcow2Name)
}
}
var buildRootfsFromTasksState = stateFunc{"build_rootfs_from_tasks", (*StateMachine).buildRootfsFromTasks}
// Build a rootfs from a list of archive tasks
func (stateMachine *StateMachine) buildRootfsFromTasks() error {
// currently a no-op pending implementation of the classic image redesign
return nil
}
var extractRootfsTarState = stateFunc{"extract_rootfs_tar", (*StateMachine).extractRootfsTar}
// Extract the rootfs from a tar archive
func (stateMachine *StateMachine) extractRootfsTar() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
// make the chroot directory to which we will extract the tar
if err := osMkdir(stateMachine.tempDirs.chroot, 0755); err != nil {
return fmt.Errorf("Failed to create chroot directory: %s", err.Error())
}
// convert the URL to a file path
// no need to check error here as the validity of the URL
// has been confirmed by the schema validation
tarPath := strings.TrimPrefix(classicStateMachine.ImageDef.Rootfs.Tarball.TarballURL, "file://")
if !filepath.IsAbs(tarPath) {
tarPath = filepath.Join(stateMachine.ConfDefPath, tarPath)
}
// if the sha256 sum of the tarball is provided, make sure it matches
if classicStateMachine.ImageDef.Rootfs.Tarball.SHA256sum != "" {
tarSHA256, err := helper.CalculateSHA256(tarPath)
if err != nil {
return err
}
if tarSHA256 != classicStateMachine.ImageDef.Rootfs.Tarball.SHA256sum {
return fmt.Errorf("Calculated SHA256 sum of rootfs tarball \"%s\" does not match "+
"the expected value specified in the image definition: \"%s\"",
tarSHA256, classicStateMachine.ImageDef.Rootfs.Tarball.SHA256sum)
}
}
// now extract the archive
return helper.ExtractTarArchive(tarPath, stateMachine.tempDirs.chroot,
stateMachine.commonFlags.Verbose, stateMachine.commonFlags.Debug)
}
var germinateState = stateFunc{"germinate", (*StateMachine).germinate}
// germinate runs the germinate binary and parses the output to create
// a list of packages from the seed section of the image definition
func (stateMachine *StateMachine) germinate() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
// create a scratch directory to run germinate in
germinateDir := filepath.Join(classicStateMachine.stateMachineFlags.WorkDir, "germinate")
err := osMkdir(germinateDir, 0755)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("Error creating germinate directory: \"%s\"", err.Error())
}
germinateCmd := generateGerminateCmd(classicStateMachine.ImageDef)
germinateCmd.Dir = germinateDir
germinateOutput := helper.SetCommandOutput(germinateCmd, classicStateMachine.commonFlags.Debug)
if err := germinateCmd.Run(); err != nil {
return fmt.Errorf("Error running germinate command \"%s\". Error is \"%s\". Output is: \n%s",
germinateCmd.String(), err.Error(), germinateOutput.String())
}
packageMap := make(map[string]*[]string)
packageMap[".seed"] = &classicStateMachine.Packages
packageMap[".snaps"] = &classicStateMachine.Snaps
for fileExtension, packageList := range packageMap {
for _, fileName := range classicStateMachine.ImageDef.Rootfs.Seed.Names {
seedFilePath := filepath.Join(germinateDir, fileName+fileExtension)
seedFile, err := osOpen(seedFilePath)
if err != nil {
return fmt.Errorf("Error opening seed file %s: \"%s\"", seedFilePath, err.Error())
}
defer seedFile.Close()
seedScanner := bufio.NewScanner(seedFile)
for seedScanner.Scan() {
seedLine := seedScanner.Bytes()
if seedVersionRegex.Match(seedLine) {
packageName := strings.Split(string(seedLine), " ")[0]
*packageList = append(*packageList, packageName)
}
}
}
}
return nil
}
// customizeCloudInitFile customizes a cloud-init data file with the given content
func customizeCloudInitFile(customData string, seedPath string, fileName string, requireHeader bool) error {
if customData == "" {
return nil
}
f, err := osCreate(path.Join(seedPath, fileName))
if err != nil {
return err
}
defer f.Close()
if requireHeader && !strings.HasPrefix(customData, "#cloud-config\n") {
return fmt.Errorf("provided cloud-init customization for %s is missing proper header", fileName)
}
_, err = f.WriteString(customData)
if err != nil {
return err
}
return nil
}
var customizeCloudInitState = stateFunc{"customize_cloud_init", (*StateMachine).customizeCloudInit}
// Customize Cloud init with the values in the image definition YAML
func (stateMachine *StateMachine) customizeCloudInit() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
cloudInitCustomization := classicStateMachine.ImageDef.Customization.CloudInit
seedPath := path.Join(classicStateMachine.tempDirs.chroot, "var/lib/cloud/seed/nocloud")
err := osMkdirAll(seedPath, 0755)
if err != nil {
return err
}
err = customizeCloudInitFile(cloudInitCustomization.MetaData, seedPath, "meta-data", false)
if err != nil {
return err
}
err = customizeCloudInitFile(cloudInitCustomization.UserData, seedPath, "user-data", true)
if err != nil {
return err
}
err = customizeCloudInitFile(cloudInitCustomization.NetworkConfig, seedPath, "network-config", false)
if err != nil {
return err
}
datasourceConfig := "# to update this file, run dpkg-reconfigure cloud-init\ndatasource_list: [ NoCloud ]\n"
dpkgConfigPath := path.Join(classicStateMachine.tempDirs.chroot, "etc/cloud/cloud.cfg.d/90_dpkg.cfg")
dpkgConfigFile, err := osCreate(dpkgConfigPath)
if err != nil {
return err
}
defer dpkgConfigFile.Close()
_, err = dpkgConfigFile.WriteString(datasourceConfig)
return err
}
var customizeFstabState = stateFunc{"customize_fstab", (*StateMachine).customizeFstab}
// Customize /etc/fstab based on values in the image definition
func (stateMachine *StateMachine) customizeFstab() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
fstabPath := filepath.Join(stateMachine.tempDirs.chroot, "etc", "fstab")
fstabIO, err := osOpenFile(fstabPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("Error opening fstab: %s", err.Error())
}
defer fstabIO.Close()
var fstabEntries []string
for _, fstab := range classicStateMachine.ImageDef.Customization.Fstab {
var dumpString string
if fstab.Dump {
dumpString = "1"
} else {
dumpString = "0"
}
fstabEntry := fmt.Sprintf("LABEL=%s\t%s\t%s\t%s\t%s\t%d",
fstab.Label,
fstab.Mountpoint,
fstab.FSType,
fstab.MountOptions,
dumpString,
fstab.FsckOrder,
)
fstabEntries = append(fstabEntries, fstabEntry)
}
_, err = fstabIO.Write([]byte(strings.Join(fstabEntries, "\n") + "\n"))
return err
}
var manualCustomizationState = stateFunc{"perform_manual_customization", (*StateMachine).manualCustomization}
// Handle any manual customizations specified in the image definition
func (stateMachine *StateMachine) manualCustomization() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
// copy /etc/resolv.conf from the host system into the chroot if it hasn't already been done
err := helperBackupAndCopyResolvConf(classicStateMachine.tempDirs.chroot)
if err != nil {
return fmt.Errorf("Error setting up /etc/resolv.conf in the chroot: \"%s\"", err.Error())
}
err = manualMakeDirs(classicStateMachine.ImageDef.Customization.Manual.MakeDirs, stateMachine.tempDirs.chroot, stateMachine.commonFlags.Debug)
if err != nil {
return err
}
err = manualCopyFile(classicStateMachine.ImageDef.Customization.Manual.CopyFile, classicStateMachine.ConfDefPath, stateMachine.tempDirs.chroot, stateMachine.commonFlags.Debug)
if err != nil {
return err
}
err = manualExecute(classicStateMachine.ImageDef.Customization.Manual.Execute, stateMachine.tempDirs.chroot, stateMachine.commonFlags.Debug)
if err != nil {
return err
}
err = manualTouchFile(classicStateMachine.ImageDef.Customization.Manual.TouchFile, stateMachine.tempDirs.chroot, stateMachine.commonFlags.Debug)
if err != nil {
return err
}
err = manualAddGroup(classicStateMachine.ImageDef.Customization.Manual.AddGroup, stateMachine.tempDirs.chroot, stateMachine.commonFlags.Debug)
if err != nil {
return err
}
err = manualAddUser(classicStateMachine.ImageDef.Customization.Manual.AddUser, stateMachine.tempDirs.chroot, stateMachine.commonFlags.Debug)
if err != nil {
return err
}
return nil
}
var prepareClassicImageState = stateFunc{"prepare_image", (*StateMachine).prepareClassicImage}
// prepareClassicImage calls image.Prepare to stage snaps in classic images
func (stateMachine *StateMachine) prepareClassicImage() error {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
imageOpts := &image.Options{}
var err error
imageOpts.Snaps, imageOpts.SnapChannels, err = parseSnapsAndChannels(classicStateMachine.Snaps)
if err != nil {
return err
}
if stateMachine.commonFlags.Channel != "" {
imageOpts.Channel = stateMachine.commonFlags.Channel
}
// plug/slot sanitization needed by provider handling
snap.SanitizePlugsSlots = builtin.SanitizePlugsSlots
err = resetPreseeding(imageOpts, classicStateMachine.tempDirs.chroot, stateMachine.commonFlags.Debug, stateMachine.commonFlags.Verbose)
if err != nil {
return err
}
err = ensureSnapBasesInstalled(imageOpts)
if err != nil {
return err
}
err = addExtraSnaps(imageOpts, &classicStateMachine.ImageDef)
if err != nil {
return err
}
setModelFile(imageOpts, classicStateMachine.ImageDef.ModelAssertion, stateMachine.ConfDefPath)
imageOpts.Classic = true
imageOpts.Architecture = classicStateMachine.ImageDef.Architecture
imageOpts.PrepareDir = classicStateMachine.tempDirs.chroot
imageOpts.Customizations = *new(image.Customizations)
imageOpts.Customizations.Validation = stateMachine.commonFlags.Validation
// image.Prepare automatically has some output that we only want for
// verbose or greater logging
if !stateMachine.commonFlags.Debug && !stateMachine.commonFlags.Verbose {
oldImageStdout := image.Stdout
image.Stdout = io.Discard
defer func() {
image.Stdout = oldImageStdout
}()
}
if err := imagePrepare(imageOpts); err != nil {
return fmt.Errorf("Error preparing image: %s", err.Error())
}
return nil
}
// resetPreseeding checks if the rootfs is already preseeded and reset if necessary.
// This can happen when building from a rootfs tarball
func resetPreseeding(imageOpts *image.Options, chroot string, debug, verbose bool) error {
if !osutil.FileExists(filepath.Join(chroot, "var", "lib", "snapd", "state.json")) {
return nil
}
// first get a list of all preseeded snaps
// seededSnaps maps the snap name and channel that was seeded
preseededSnaps, err := getPreseededSnaps(chroot)
if err != nil {
return fmt.Errorf("Error getting list of preseeded snaps from existing rootfs: %s",
err.Error())
}
for snap, channel := range preseededSnaps {
// if a channel is specified on the command line for a snap that was already
// preseeded, use the channel from the command line instead of the channel
// that was originally used for the preseeding
if !helper.SliceHasElement(imageOpts.Snaps, snap) {
imageOpts.Snaps = append(imageOpts.Snaps, snap)
imageOpts.SnapChannels[snap] = channel
}
}
// preseed.ClassicReset automatically has some output that we only want for
// verbose or greater logging
if !debug && !verbose {
oldPreseedStdout := preseed.Stdout
preseed.Stdout = io.Discard
defer func() {
preseed.Stdout = oldPreseedStdout
}()
}
// We need to use the snap-preseed binary for the reset as well, as using
// preseed.ClassicReset() might leave us in a chroot jail
cmd := execCommand("/usr/lib/snapd/snap-preseed", "--reset", chroot)
err = cmd.Run()
if err != nil {
return fmt.Errorf("Error resetting preseeding in the chroot. Error is \"%s\"", err.Error())
}
return nil
}
// ensureSnapBasesInstalled iterates through the list of snaps and ensure that all
// of their bases are also set to be installed. Note we only do this for snaps that
// are seeded. Users are expected to specify all base and content provider snaps
// in the image definition.
func ensureSnapBasesInstalled(imageOpts *image.Options) error {
snapStore := store.New(nil, nil)
snapContext := context.Background()
for _, seededSnap := range imageOpts.Snaps {
snapSpec := store.SnapSpec{Name: seededSnap}
snapInfo, err := snapStore.SnapInfo(snapContext, snapSpec, nil)
if err != nil {
return fmt.Errorf("Error getting info for snap %s: \"%s\"",
seededSnap, err.Error())
}
if snapInfo.Base != "" && !helper.SliceHasElement(imageOpts.Snaps, snapInfo.Base) {
imageOpts.Snaps = append(imageOpts.Snaps, snapInfo.Base)
}
}
return nil
}
// addExtraSnaps adds any extra snaps from the image definition to the list
// This should be done last to ensure the correct channels are being used
func addExtraSnaps(imageOpts *image.Options, imageDefinition *imagedefinition.ImageDefinition) error {
if imageDefinition.Customization == nil || len(imageDefinition.Customization.ExtraSnaps) == 0 {
return nil
}
imageOpts.SeedManifest = seedwriter.NewManifest()
for _, extraSnap := range imageDefinition.Customization.ExtraSnaps {
if !helper.SliceHasElement(imageOpts.Snaps, extraSnap.SnapName) {
imageOpts.Snaps = append(imageOpts.Snaps, extraSnap.SnapName)
}
if extraSnap.Channel != "" {
imageOpts.SnapChannels[extraSnap.SnapName] = extraSnap.Channel
}
if extraSnap.SnapRevision != 0 {
fmt.Printf("WARNING: revision %d for snap %s may not be the latest available version!\n",
extraSnap.SnapRevision,
extraSnap.SnapName,
)
err := imageOpts.SeedManifest.SetAllowedSnapRevision(extraSnap.SnapName, snap.R(extraSnap.SnapRevision))
if err != nil {
return fmt.Errorf("error dealing with the extra snap %s: %w", extraSnap.SnapName, err)
}
}
}
return nil
}
// setModelFile sets the ModelFile based on the given ModelAssertion
func setModelFile(imageOpts *image.Options, modelAssertion string, confDefPath string) {
modelAssertionPath := strings.TrimPrefix(modelAssertion, "file://")
// if no explicit model assertion was given, keep empty ModelFile to let snapd fallback to default
// model assertion
if len(modelAssertionPath) != 0 {
if !filepath.IsAbs(modelAssertionPath) {
imageOpts.ModelFile = filepath.Join(confDefPath, modelAssertionPath)
} else {
imageOpts.ModelFile = modelAssertionPath
}
}
}
var preseedClassicImageState = stateFunc{"preseed_image", (*StateMachine).preseedClassicImage}
// preseedClassicImage preseeds the snaps that have already been staged in the chroot
func (stateMachine *StateMachine) preseedClassicImage() (err error) {
classicStateMachine := stateMachine.parent.(*ClassicStateMachine)
// preseedCmds should be filled as a FIFO list
var preseedCmds []*exec.Cmd
// teardownCmds should be filled as a LIFO list to unmount first what was mounted last
var teardownCmds []*exec.Cmd
// set up the mount commands
mountPoints := []*mountPoint{
{
src: "devtmpfs-build",
basePath: stateMachine.tempDirs.chroot,
relpath: "/dev",
typ: "devtmpfs",
},
{
src: "devpts-build",
basePath: stateMachine.tempDirs.chroot,
relpath: "/dev/pts",
typ: "devpts",
opts: []string{"nodev", "nosuid"},
},
{
src: "proc-build",
basePath: stateMachine.tempDirs.chroot,
relpath: "/proc",
typ: "proc",
},
{
src: "none",
basePath: stateMachine.tempDirs.chroot,
relpath: "/sys/kernel/security",
typ: "securityfs",
},
{
src: "none",
basePath: stateMachine.tempDirs.chroot,
relpath: "/sys/fs/cgroup",
typ: "cgroup2",
},
}
// Make sure we left the system as clean as possible if something has gone wrong
defer func() {
err = teardownMount(stateMachine.tempDirs.chroot, mountPoints, teardownCmds, err, stateMachine.commonFlags.Debug)
}()
for _, mp := range mountPoints {
mountCmds, umountCmds, err := mp.getMountCmd()
if err != nil {
return fmt.Errorf("Error preparing mountpoint \"%s\": \"%s\"",
mp.relpath,
err.Error(),
)