/
step_create_cdrom.go
321 lines (284 loc) · 7.92 KB
/
step_create_cdrom.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
package commonsteps
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
"github.com/hashicorp/packer-plugin-sdk/shell-local/localexec"
"github.com/hashicorp/packer-plugin-sdk/tmp"
)
// StepCreateCD will create a CD disk with the given files.
type StepCreateCD struct {
// Files can be either files or directories. Any files provided here will
// be written to the root of the CD. Directories will be written to the
// root of the CD as well, but will retain their subdirectory structure.
Files []string
Content map[string]string
Label string
CDPath string
rootFolder string
}
func (s *StepCreateCD) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
if len(s.Files) == 0 && len(s.Content) == 0 {
log.Println("No CD files specified. CD disk will not be made.")
return multistep.ActionContinue
}
ui := state.Get("ui").(packersdk.Ui)
ui.Say("Creating CD disk...")
if s.Label == "" {
s.Label = "packer"
} else {
log.Printf("CD label is set to %s", s.Label)
}
// Create a temporary file to be our CD drive
CDF, err := tmp.File("packer*.iso")
// Set the path so we can remove it later
CDPath := CDF.Name()
CDF.Close()
os.Remove(CDPath)
if err != nil {
state.Put("error",
fmt.Errorf("Error creating temporary file for CD: %s", err))
return multistep.ActionHalt
}
log.Printf("CD path: %s", CDPath)
s.CDPath = CDPath
// Consolidate all files provided into a single directory to become our
// "root" directory.
rootFolder, err := tmp.Dir("packer_to_cdrom")
if err != nil {
state.Put("error",
fmt.Errorf("Error creating temporary file for CD: %s", err))
return multistep.ActionHalt
}
s.rootFolder = rootFolder
for _, toAdd := range s.Files {
err = s.AddFile(rootFolder, toAdd)
if err != nil {
state.Put("error",
fmt.Errorf("Error creating temporary file for CD: %s", err))
return multistep.ActionHalt
}
}
for path, content := range s.Content {
err = s.AddContent(rootFolder, path, content)
if err != nil {
state.Put("error",
fmt.Errorf("Error creating temporary file for CD: %s", err))
return multistep.ActionHalt
}
}
cmd, err := retrieveCDISOCreationCommand(s.Label, rootFolder, CDPath)
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
err = localexec.RunAndStream(cmd, ui, []string{})
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
ui.Message("Done copying paths from CD_dirs")
// Set the path to the CD so it can be used later
state.Put("cd_path", CDPath)
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
return multistep.ActionContinue
}
func (s *StepCreateCD) Cleanup(multistep.StateBag) {
if s.rootFolder != "" {
os.RemoveAll(s.rootFolder)
}
if s.CDPath != "" {
log.Printf("Deleting CD disk: %s", s.CDPath)
os.Remove(s.CDPath)
}
}
type cdISOCreationCommand struct {
Name string
Command func(path string, label string, source string, dest string) *exec.Cmd
}
var supportedCDISOCreationCommands []cdISOCreationCommand = []cdISOCreationCommand{
{
"xorriso", func(path string, label string, source string, dest string) *exec.Cmd {
return exec.Command(
path,
"-as", "genisoimage",
"-rock",
"-joliet",
"-volid", label,
"-output", dest,
source)
},
},
{
"mkisofs", func(path string, label string, source string, dest string) *exec.Cmd {
return exec.Command(
path,
"-joliet",
"-volid", label,
"-o", dest,
source)
},
},
{
"hdiutil", func(path string, label string, source string, dest string) *exec.Cmd {
return exec.Command(
path,
"makehybrid",
"-o", dest,
"-hfs",
"-joliet",
"-iso",
"-default-volume-name", label,
source)
},
},
{
"oscdimg", func(path string, label string, source string, dest string) *exec.Cmd {
return exec.Command(
path,
"-j1",
"-o",
"-m",
"-l"+label,
source,
dest)
},
},
}
func isCygwinExecutable(path string) bool {
return runtime.GOOS == "windows" && strings.Contains(path, "\\usr\\bin\\")
}
func toCygwinPath(path string) (string, error) {
c := exec.Command("cygpath", path)
cygwinPath, err := c.Output()
return strings.TrimSpace(string(cygwinPath)), err
}
func retrieveCDISOCreationCommand(label string, source string, dest string) (*exec.Cmd, error) {
for _, c := range supportedCDISOCreationCommands {
path, err := exec.LookPath(c.Name)
if err != nil {
continue
}
// if we are running a cygwin/msys2 executable we must convert the
// native win32 path to a cygwin/msys2/unix style path.
if isCygwinExecutable(path) {
source, err = toCygwinPath(source)
if err != nil {
return nil, err
}
dest, err = toCygwinPath(dest)
if err != nil {
return nil, err
}
}
return c.Command(path, label, source, dest), nil
}
var commands = make([]string, 0, len(supportedCDISOCreationCommands))
for _, c := range supportedCDISOCreationCommands {
commands = append(commands, c.Name)
}
return nil, fmt.Errorf(
"could not find a supported CD ISO creation command (the supported commands are: %s)",
strings.Join(commands, ", "))
}
func (s *StepCreateCD) AddFile(dst, src string) error {
finfo, err := os.Stat(src)
if err != nil {
return fmt.Errorf("Error adding path to CD: %s", err)
}
// add a file
if !finfo.IsDir() {
inputF, err := os.Open(src)
if err != nil {
return err
}
defer inputF.Close()
// Create a new file in the root directory
dest, err := os.Create(filepath.Join(dst, finfo.Name()))
if err != nil {
return fmt.Errorf("Error opening file for copy %s to CD root", src)
}
defer dest.Close()
nBytes, err := io.Copy(dest, inputF)
if err != nil {
return fmt.Errorf("Error copying %s to CD root", src)
}
log.Printf("Wrote %d bytes to %s", nBytes, finfo.Name())
return err
}
// file is a directory, so we need to parse the filename into a path to
// discard and a basename
discardPath, _ := filepath.Split(src)
// Add a directory and its subdirectories
visit := func(pathname string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
// Clean up pathing so that we preserve the base directory provided by
// the user but not the local pathing to that directory.
allDirs, base := filepath.Split(pathname)
allDirsSlashSafe := filepath.ToSlash(allDirs)
discardPathSlashSafe := filepath.ToSlash(discardPath)
intermediaryDirs := strings.Replace(allDirsSlashSafe, discardPathSlashSafe, "", 1)
dstPath := filepath.Join(dst, base)
if intermediaryDirs != "" {
dstPath = filepath.Join(dst, intermediaryDirs, base)
}
// add a file
if !fi.IsDir() {
inputF, err := os.Open(pathname)
if err != nil {
return err
}
defer inputF.Close()
fileDst, err := os.Create(dstPath)
if err != nil {
return fmt.Errorf("Error opening file %s on CD: %s", dstPath, err)
}
defer fileDst.Close()
nBytes, err := io.Copy(fileDst, inputF)
if err != nil {
return fmt.Errorf("Error copying %s to CD: %s", dstPath, err)
}
log.Printf("Wrote %d bytes to %s", nBytes, dstPath)
return err
}
if fi.Mode().IsDir() {
// create the directory on the CD, continue walk.
err := os.MkdirAll(dstPath, fi.Mode())
if err != nil {
err = fmt.Errorf("error creating new directory %s: %s",
dstPath, err)
}
return err
}
return err
}
return filepath.Walk(src, visit)
}
func (s *StepCreateCD) AddContent(dst, path, content string) error {
// Join Cleans the path so we can join it without path traversal issues.
dstPath := filepath.Join(dst, path)
dstDir := filepath.Dir(dstPath)
err := os.MkdirAll(dstDir, 0777)
if err != nil {
return fmt.Errorf("error creating new directory %s: %s", dstDir, err)
}
err = ioutil.WriteFile(dstPath, []byte(content), 0666)
if err != nil {
return fmt.Errorf("Error writing file %s on CD: %s", path, err)
}
return nil
}