github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/compilers/utils.go (about) 1 package compilers 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path" 8 "path/filepath" 9 10 "github.com/emc-advanced-dev/pkg/errors" 11 12 unikos "github.com/solo-io/unik/pkg/os" 13 unikutil "github.com/solo-io/unik/pkg/util" 14 ) 15 16 func BuildBootableImage(kernel, cmdline string, usePartitionTables, noCleanup bool) (string, error) { 17 directory, err := ioutil.TempDir("", "bootable-image-directory.") 18 if err != nil { 19 return "", errors.New("creating tmpdir", err) 20 } 21 if !noCleanup { 22 defer os.RemoveAll(directory) 23 } 24 kernelBaseName := "program.bin" 25 26 if err := unikos.CopyDir(filepath.Dir(kernel), directory); err != nil { 27 return "", errors.New("copying dir "+filepath.Dir(kernel)+" to "+directory, err) 28 } 29 30 if err := unikos.CopyFile(kernel, path.Join(directory, kernelBaseName)); err != nil { 31 return "", errors.New("copying kernel "+kernel+" to "+kernelBaseName, err) 32 } 33 34 tmpResultFile, err := ioutil.TempFile(directory, "boot-creator-result.img.") 35 if err != nil { 36 return "", err 37 } 38 tmpResultFile.Close() 39 40 const contextDir = "/opt/vol/" 41 cmds := []string{ 42 "-d", contextDir, 43 "-p", kernelBaseName, 44 "-a", cmdline, 45 "-o", filepath.Base(tmpResultFile.Name()), 46 fmt.Sprintf("-part=%v", usePartitionTables), 47 } 48 binds := map[string]string{directory: contextDir, "/dev/": "/dev/"} 49 50 if err := unikutil.NewContainer("boot-creator").Privileged(true).WithVolumes(binds).Run(cmds...); err != nil { 51 return "", err 52 } 53 54 resultFile, err := ioutil.TempFile("", "boot-creator-result.img.") 55 if err != nil { 56 return "", err 57 } 58 resultFile.Close() 59 60 if err := os.Rename(tmpResultFile.Name(), resultFile.Name()); err != nil { 61 return "", errors.New("renaming "+tmpResultFile.Name()+" to "+resultFile.Name(), err) 62 } 63 return resultFile.Name(), nil 64 }