-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathutils.go
533 lines (439 loc) · 13.3 KB
/
utils.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
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: GPL-3.0-only
package utils
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
"unsafe"
"github.com/digitalocean/go-smbios/smbios"
"github.com/leonelquinteros/gotext"
"github.com/clearlinux/clr-installer/errors"
)
// ClearVersion is running version of the OS
var ClearVersion string
// ParseOSClearVersion parses the current version of the Clear Linux OS
func ParseOSClearVersion() error {
var versionBuf []byte
var err error
// in order to avoid issues raised by format bumps between installers image
// version and the latest released we assume the installers host version
// in other words we use the same version swupd is based on
if versionBuf, err = ioutil.ReadFile("/usr/lib/os-release"); err != nil {
return errors.Errorf("Read version file /usr/lib/os-release: %v", err)
}
versionExp := regexp.MustCompile(`VERSION_ID=([0-9][0-9]*)`)
match := versionExp.FindSubmatch(versionBuf)
if len(match) < 2 {
return errors.Errorf("Version not found in /usr/lib/os-release")
}
ClearVersion = string(match[1])
return nil
}
// MkdirAll similar to go's standard os.MkdirAll() this function creates a directory
// named path, along with any necessary parents but also checks if path exists and
// takes no action if that's true.
func MkdirAll(path string, perm os.FileMode) error {
if _, err := os.Stat(path); err == nil {
return nil
}
if err := os.MkdirAll(path, perm); err != nil {
return errors.Errorf("mkdir %s: %v", path, err)
}
return nil
}
// CopyAllFiles copy all of the files in a directory recursively
func CopyAllFiles(srcDir string, destDir string) error {
err := filepath.Walk(srcDir,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return errors.Errorf("failure accessing a path %q: %v", path, err)
}
target := filepath.Join(destDir, path)
if info.IsDir() {
// Create the matching target directory
if err := MkdirAll(target, info.Mode()); err != nil {
return errors.Errorf("Failed to mkdir %q", target)
}
return nil
}
if err := CopyFile(path, target); err != nil {
return errors.Errorf("Failed to copy file %q", target)
}
// Ensure all contents is owned correctly
sys := info.Sys()
stat, ok := sys.(*syscall.Stat_t)
if ok {
if err := os.Chown(target, int(stat.Uid), int(stat.Gid)); err != nil {
return errors.Errorf("Failed to change ownership of %q to UID:%d, GID:%d",
target, stat.Uid, stat.Gid)
}
} else {
return errors.Errorf("Could not stat file %q", path)
}
return nil
})
if err != nil {
return fmt.Errorf("Failed to copy files")
}
return nil
}
// CopyFile copies src file to dest
func CopyFile(src string, dest string) error {
destDir := filepath.Dir(dest)
if _, err := os.Stat(destDir); err != nil {
if os.IsNotExist(err) {
return errors.Errorf("No such dest directory: %s", destDir)
}
return errors.Wrap(err)
}
srcFile, err := os.Open(src)
if err != nil {
if os.IsNotExist(err) {
return errors.Errorf("No such file: %s", src)
}
return errors.Wrap(err)
}
defer srcFile.Close()
srcInfo, err := srcFile.Stat()
if err != nil {
return errors.Wrap(err)
}
destFile, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, srcInfo.Mode()&os.ModePerm)
if err != nil {
return errors.Wrap(err)
}
defer destFile.Close()
_, err = io.Copy(destFile, srcFile)
if err != nil {
return errors.Wrap(err)
}
// Flush cache to disk
if err := destFile.Sync(); err != nil {
return errors.Wrap(err)
}
return nil
}
// FileExists returns true if the file or directory exists
// else it returns false and the associated error
func FileExists(filePath string) (bool, error) {
_, err := os.Stat(filePath)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
// VerifyRootUser returns an error if we're not running as root
func VerifyRootUser() string {
// ProgName is the short name of this executable
progName := path.Base(os.Args[0])
user, err := user.Current()
if err != nil {
return fmt.Sprintf("%s MUST run as 'root' user to install! (user=%s)",
progName, "UNKNOWN")
}
if user.Uid != "0" {
return fmt.Sprintf("%s MUST run as 'root' user to install! (user=%s)",
progName, user.Uid)
}
return ""
}
// IsClearLinux checks if the current OS is Clear by looking for Swupd
// Mostly used in Go Testing
func IsClearLinux() bool {
is := false
if runtime.GOOS == "linux" {
clearFile := "/usr/bin/swupd"
if _, err := os.Stat(clearFile); !os.IsNotExist(err) {
is = true
}
}
return is
}
// IsRoot checks if the current User is root (UID 0)
// Mostly used in Go Testing
func IsRoot() bool {
is := false
user, err := user.Current()
if err == nil {
if user.Uid == "0" {
is = true
}
}
return is
}
// StringSliceContains returns true if sl contains str, returns false otherwise
func StringSliceContains(sl []string, str string) bool {
for _, curr := range sl {
if curr == str {
return true
}
}
return false
}
// IntSliceContains returns true if is contains value, returns false otherwise
func IntSliceContains(is []int, value int) bool {
for _, curr := range is {
if curr == value {
return true
}
}
return false
}
// IsCheckCoverage returns true if CHECK_COVERAGE variable is set
func IsCheckCoverage() bool {
return os.Getenv("CHECK_COVERAGE") != ""
}
// IsStdoutTTY returns true if the stdout is attached to a tty
func IsStdoutTTY() bool {
var termios syscall.Termios
fd := os.Stdout.Fd()
ptr := uintptr(unsafe.Pointer(&termios))
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, syscall.TCGETS, ptr, 0, 0, 0)
return err == 0
}
// ExpandVariables iterates over vars map and replace all the occurrences of ${var} or
// $var in the str string
func ExpandVariables(vars map[string]string, str string) string {
// iterate over available variables
for k, v := range vars {
// tries to replace both ${var} and $var forms
for _, rep := range []string{fmt.Sprintf("$%s", k), fmt.Sprintf("${%s}", k)} {
str = strings.ReplaceAll(str, rep, v)
}
}
return str
}
// IsVirtualBox returns true if the running system is executed
// from within VirtualBox
// Attempt to parse the System Management BIOS (SMBIOS) and
// Desktop Management Interface (DMI) to determine if we are
// executing inside a VirtualBox. Ignoring error conditions and
// assuming we are not VirtualBox.
func IsVirtualBox() bool {
virtualBox := false
// Find SMBIOS data in operating system-specific location.
rc, _, err := smbios.Stream()
if err != nil {
return virtualBox
}
// Be sure to close the stream!
defer func() { _ = rc.Close() }()
// Decode SMBIOS structures from the stream.
// https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.1.1.pdf
d := smbios.NewDecoder(rc)
ss, err := d.Decode()
if err != nil {
return virtualBox
}
for _, s := range ss {
// 7.2 System Information (Type 1)
if s.Header.Type == 1 {
for _, str := range s.Strings {
if strings.Contains(strings.ToLower(str), "virtualbox") {
virtualBox = true
return virtualBox
}
}
}
}
return virtualBox
}
// LookupThemeDir returns the directory to use for reading
// theme files for the UI.
func LookupThemeDir() (string, error) {
return lookupDir("/usr/share/clr-installer/themes", "CLR_INSTALLER_THEME_DIR")
}
// LookupLocaleDir returns the directory to use for reading
// locale files for the UI.
func LookupLocaleDir() (string, error) {
return lookupDir("/usr/share/locale", "CLR_INSTALLER_LOCALE_DIR")
}
// lookupDir returns the full directory path of a directory.
// It will look in the local developers build area first,
// or the ENV variable, and finally the standard
// system install location
func lookupDir(dir, env string) (string, error) {
var result string
fullDir := []string{
os.Getenv(env),
}
src, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return "", err
}
if strings.Contains(src, "/.gopath/bin") {
fullDir = append(fullDir, strings.Replace(src, "bin", "../"+filepath.Base(dir), 1))
}
fullDir = append(fullDir, dir+"/")
for _, curr := range fullDir {
if _, err := os.Stat(curr); os.IsNotExist(err) {
continue
}
result = curr
break
}
if result == "" {
panic(errors.Errorf("Could not find a %s dir", dir))
}
return result, nil
}
// Locale is used to access the localization functions
var Locale *gotext.Locale
// Ensure Locale always has a default
func init() {
SetLocale("en_US.UTF-8")
}
// SetLocale sets the locale of the installer based on the selected language
func SetLocale(language string) {
dir, err := LookupLocaleDir()
if err != nil {
log.Fatal(err)
Locale = nil
} else {
Locale = gotext.NewLocale(dir, language)
Locale.AddDomain("clr-installer")
}
}
// LookupISOTemplateDir returns the directory to use for reading
// template files for ISO creation. It will look in the local developers
// build area first, or the ENV variable, and finally the standard
// system install location
func LookupISOTemplateDir() (string, error) {
var result string
isoTemplateDirs := []string{
os.Getenv("CLR_INSTALLER_ISO_TEMPLATE_DIR"),
}
src, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return "", err
}
if strings.Contains(src, "/.gopath/bin") {
isoTemplateDirs = append(isoTemplateDirs, strings.Replace(src, "bin", "../iso_templates", 1))
}
isoTemplateDirs = append(isoTemplateDirs, "/usr/share/clr-installer/iso_templates/")
for _, curr := range isoTemplateDirs {
if _, err := os.Stat(curr); os.IsNotExist(err) {
continue
}
result = curr
break
}
if result == "" {
panic(errors.Errorf("Could not find a ISO templates dir"))
}
return result, nil
}
// RunDiskPartitionTool creates and executes a script which launches
// the disk partitioning tool and then returns to the installer.
func RunDiskPartitionTool(tmpYaml string, lockFile string, diskUtilCmd string,
remove []string, gui bool) (string, error) {
// We need to save the current state model for the relaunch of clr-installer
tmpBash, err := ioutil.TempFile("", "clr-installer-diskUtil-*.sh")
if err != nil {
return "", errors.Errorf("Could not make BASH tempfile: %v", err)
}
defer func() { _ = tmpBash.Close() }()
var content bytes.Buffer
_, _ = fmt.Fprintf(&content, "#!/bin/bash\n")
// To ensure another instance is not launched, first recreate the
// installer lock file using the PID of the running script
_, _ = fmt.Fprintf(&content, "echo $$ > %s\n", lockFile)
_, _ = fmt.Fprintf(&content, "result=0\n")
args := append(os.Args, "--config", tmpYaml)
if gui {
_, _ = fmt.Fprintf(&content, "if [ -n \"${SUDO_USER}\" ]; then\n")
_, _ = fmt.Fprintf(&content, " sudo --user=${SUDO_USER} xhost +si:localuser:root\n")
_, _ = fmt.Fprintf(&content, " result=$(( ${result} + $? ))\n")
_, _ = fmt.Fprintf(&content, "fi\n")
}
_, _ = fmt.Fprintf(&content, "echo Switching to Disk Partitioning tool\n")
if !gui {
_, _ = fmt.Fprintf(&content, "sleep 2\n")
}
_, _ = fmt.Fprintf(&content, "%s\n", diskUtilCmd)
_, _ = fmt.Fprintf(&content, "result=$(( ${result} + $? ))\n")
if !gui {
_, _ = fmt.Fprintf(&content, "sleep 1\n")
}
_, _ = fmt.Fprintf(&content, "echo Checking partitions with partprobe\n")
_, _ = fmt.Fprintf(&content, "/usr/bin/partprobe\n")
_, _ = fmt.Fprintf(&content, "result=$(( ${result} + $? ))\n")
if !gui {
_, _ = fmt.Fprintf(&content, "sleep 1\n")
}
_, _ = fmt.Fprintf(&content, "echo Restarting Clear Linux OS Installer ...\n")
if gui {
args = append(args, "--gui")
} else {
_, _ = fmt.Fprintf(&content, "sleep 2\n")
args = append(args, "--tui")
}
args = append(args, "--cfPurge")
_, _ = fmt.Fprintf(&content, "if [ ${result} -eq 0 ]; then\n")
_, _ = fmt.Fprintf(&content, " /bin/rm %s\n", tmpBash.Name())
for _, file := range remove {
_, _ = fmt.Fprintf(&content, " /bin/rm -rf %s\n", file)
}
_, _ = fmt.Fprintf(&content, "else\n")
_, _ = fmt.Fprintf(&content, " /bin/cp -a /root/clr-installer.log /root/clr-installer.log.$$\n")
_, _ = fmt.Fprintf(&content, "fi\n")
_, _ = fmt.Fprintf(&content, "/bin/rm %s\n", lockFile)
allArgs := strings.Join(args, " ")
_, err = fmt.Fprintf(&content, "exec %s\n", allArgs)
if err != nil {
return "", errors.Errorf("Could not write BASH buffer: %v", err)
}
if _, err := tmpBash.Write(content.Bytes()); err != nil {
return "", errors.Errorf("Could not write BASH tempfile: %v", err)
}
_ = os.Chmod(tmpBash.Name(), 0700)
return tmpBash.Name(), nil
}
// HostHasEFI check if the running host supports EFI booting
func HostHasEFI() bool {
if _, err := os.Stat("/sys/firmware/efi"); os.IsNotExist(err) {
return false
}
return true
}
// VersionStringUint converts string version to an uint version
func VersionStringUint(versionString string) (uint, error) {
var versionUint uint
if versionString == "" || IsLatestVersion(versionString) {
return 0, nil
}
version, err := strconv.ParseUint(versionString, 10, 32)
if err == nil {
versionUint = uint(version)
}
return versionUint, err
}
// VersionUintString converts an uint version to the string version
func VersionUintString(versionUint uint) string {
var version string
if versionUint == 0 {
version = "latest"
} else {
version = fmt.Sprintf("%d", versionUint)
}
return version
}
func IsLatestVersion(version string) bool {
return strings.EqualFold(version, "latest")
}