mirror of
https://github.com/containers/podman.git
synced 2025-12-02 02:58:03 +08:00
Vendor crc CopySparse
Added the module github.com/crc-org/crc/ as a dependency. Updated `decompress.go` and `copy_test.go` in compression so that `CopySparse` from crc-org/crc/v2/pkg/os is used instead of the local version in `copy.go`. Deleted `copy.go` that is not used anymore. Signed-off-by: Mario Loriedo <mario.loriedo@gmail.com>
This commit is contained in:
191
vendor/github.com/crc-org/crc/v2/LICENSE
generated
vendored
Normal file
191
vendor/github.com/crc-org/crc/v2/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,191 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright 2019 Red Hat, Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
44
vendor/github.com/crc-org/crc/v2/pkg/crc/logging/inmemory.go
generated
vendored
Normal file
44
vendor/github.com/crc-org/crc/v2/pkg/crc/logging/inmemory.go
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"container/ring"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// This hook keeps in memory n messages from error to info level
|
||||
type inMemoryHook struct {
|
||||
messages *ring.Ring
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func newInMemoryHook(size int) *inMemoryHook {
|
||||
return &inMemoryHook{
|
||||
messages: ring.New(size),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *inMemoryHook) Levels() []logrus.Level {
|
||||
return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel}
|
||||
}
|
||||
|
||||
func (h *inMemoryHook) Fire(entry *logrus.Entry) error {
|
||||
h.lock.Lock()
|
||||
defer h.lock.Unlock()
|
||||
h.messages.Value = entry.Message
|
||||
h.messages = h.messages.Next()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *inMemoryHook) Messages() []string {
|
||||
h.lock.RLock()
|
||||
defer h.lock.RUnlock()
|
||||
var ret []string
|
||||
h.messages.Do(func(elem interface{}) {
|
||||
if str, ok := elem.(string); ok {
|
||||
ret = append(ret, str)
|
||||
}
|
||||
})
|
||||
return ret
|
||||
}
|
||||
126
vendor/github.com/crc-org/crc/v2/pkg/crc/logging/logging.go
generated
vendored
Normal file
126
vendor/github.com/crc-org/crc/v2/pkg/crc/logging/logging.go
generated
vendored
Normal file
@@ -0,0 +1,126 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/pflag"
|
||||
terminal "golang.org/x/term"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
lumberjackLogger *lumberjack.Logger
|
||||
logLevel = defaultLogLevel()
|
||||
Memory = newInMemoryHook(100)
|
||||
)
|
||||
|
||||
func CloseLogging() {
|
||||
if lumberjackLogger != nil {
|
||||
_ = lumberjackLogger.Close()
|
||||
}
|
||||
logrus.StandardLogger().ReplaceHooks(make(logrus.LevelHooks))
|
||||
}
|
||||
|
||||
func BackupLogFile() {
|
||||
if lumberjackLogger == nil {
|
||||
return
|
||||
}
|
||||
_ = lumberjackLogger.Rotate()
|
||||
}
|
||||
|
||||
func InitLogrus(logFilePath string) {
|
||||
if lumberjackLogger != nil {
|
||||
return
|
||||
}
|
||||
|
||||
lumberjackLogger = &lumberjack.Logger{
|
||||
Filename: logFilePath,
|
||||
MaxSize: 5, // 5MB
|
||||
MaxBackups: 2,
|
||||
}
|
||||
// send logs to file
|
||||
logrus.SetOutput(lumberjackLogger)
|
||||
|
||||
logrus.SetLevel(logrus.TraceLevel)
|
||||
|
||||
level, err := logrus.ParseLevel(logLevel)
|
||||
if err != nil {
|
||||
level = logrus.InfoLevel
|
||||
}
|
||||
|
||||
logrus.AddHook(Memory)
|
||||
|
||||
// Add hook to send error/fatal to stderr
|
||||
logrus.AddHook(newstdErrHook(level, &logrus.TextFormatter{
|
||||
ForceColors: terminal.IsTerminal(int(os.Stderr.Fd())),
|
||||
DisableTimestamp: true,
|
||||
DisableLevelTruncation: false,
|
||||
}))
|
||||
}
|
||||
|
||||
func DefaultLogLevel() logrus.Level {
|
||||
level, err := logrus.ParseLevel(logLevel)
|
||||
if err != nil {
|
||||
level = logrus.InfoLevel
|
||||
}
|
||||
return level
|
||||
}
|
||||
|
||||
func defaultLogLevel() string {
|
||||
defaultLevel := "info"
|
||||
envLogLevel := os.Getenv("CRC_LOG_LEVEL")
|
||||
if envLogLevel != "" {
|
||||
defaultLevel = envLogLevel
|
||||
}
|
||||
|
||||
return defaultLevel
|
||||
}
|
||||
|
||||
func AddLogLevelFlag(flagset *pflag.FlagSet) {
|
||||
flagset.StringVar(&logLevel, "log-level", defaultLogLevel(), "log level (e.g. \"debug | info | warn | error\")")
|
||||
}
|
||||
|
||||
func IsDebug() bool {
|
||||
return logLevel == "debug"
|
||||
}
|
||||
|
||||
func Info(args ...interface{}) {
|
||||
logrus.Info(args...)
|
||||
}
|
||||
|
||||
func Infof(s string, args ...interface{}) {
|
||||
logrus.Infof(s, args...)
|
||||
}
|
||||
|
||||
func Warn(args ...interface{}) {
|
||||
logrus.Warn(args...)
|
||||
}
|
||||
|
||||
func Warnf(s string, args ...interface{}) {
|
||||
logrus.Warnf(s, args...)
|
||||
}
|
||||
|
||||
func Fatal(args ...interface{}) {
|
||||
logrus.Fatal(args...)
|
||||
}
|
||||
|
||||
func Fatalf(s string, args ...interface{}) {
|
||||
logrus.Fatalf(s, args...)
|
||||
}
|
||||
|
||||
func Error(args ...interface{}) {
|
||||
logrus.Error(args...)
|
||||
}
|
||||
|
||||
func Errorf(s string, args ...interface{}) {
|
||||
logrus.Errorf(s, args...)
|
||||
}
|
||||
|
||||
func Debug(args ...interface{}) {
|
||||
logrus.Debug(args...)
|
||||
}
|
||||
|
||||
func Debugf(s string, args ...interface{}) {
|
||||
logrus.Debugf(s, args...)
|
||||
}
|
||||
53
vendor/github.com/crc-org/crc/v2/pkg/crc/logging/stderr_hook.go
generated
vendored
Normal file
53
vendor/github.com/crc-org/crc/v2/pkg/crc/logging/stderr_hook.go
generated
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"github.com/mattn/go-colorable"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// This is stdErrHook to send error to the stdErr.
|
||||
type stdErrHook struct {
|
||||
stderr io.Writer
|
||||
formatter logrus.Formatter
|
||||
level logrus.Level
|
||||
}
|
||||
|
||||
func newstdErrHook(level logrus.Level, formatter logrus.Formatter) *stdErrHook {
|
||||
// For windows to display colors we need to use the go-colorable writer
|
||||
if runtime.GOOS == "windows" {
|
||||
return &stdErrHook{
|
||||
stderr: colorable.NewColorableStderr(),
|
||||
formatter: formatter,
|
||||
level: level,
|
||||
}
|
||||
}
|
||||
return &stdErrHook{
|
||||
stderr: os.Stderr,
|
||||
formatter: formatter,
|
||||
level: level,
|
||||
}
|
||||
}
|
||||
|
||||
func (h stdErrHook) Levels() []logrus.Level {
|
||||
var levels []logrus.Level
|
||||
for _, level := range logrus.AllLevels {
|
||||
if level <= h.level {
|
||||
levels = append(levels, level)
|
||||
}
|
||||
}
|
||||
return levels
|
||||
}
|
||||
|
||||
func (h *stdErrHook) Fire(entry *logrus.Entry) error {
|
||||
line, err := h.formatter.Format(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = h.stderr.Write(line)
|
||||
return err
|
||||
}
|
||||
111
vendor/github.com/crc-org/crc/v2/pkg/os/copy.go
generated
vendored
Normal file
111
vendor/github.com/crc-org/crc/v2/pkg/os/copy.go
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
package os
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func copyFile(src, dst string, sparse bool) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer in.Close()
|
||||
|
||||
out, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer out.Close()
|
||||
|
||||
if sparse {
|
||||
if _, err = CopySparse(out, in); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err = io.Copy(out, in); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
fi, err := os.Stat(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = os.Chmod(dst, fi.Mode()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return out.Close()
|
||||
}
|
||||
|
||||
func CopyFile(src, dst string) error {
|
||||
return copyFile(src, dst, false)
|
||||
}
|
||||
|
||||
func CopyFileSparse(src, dst string) error {
|
||||
return copyFile(src, dst, true)
|
||||
}
|
||||
|
||||
func CopySparse(dst io.WriteSeeker, src io.Reader) (int64, error) {
|
||||
copyBuf := make([]byte, copyChunkSize)
|
||||
sparseWriter := newSparseWriter(dst)
|
||||
|
||||
bytesWritten, err := io.CopyBuffer(sparseWriter, src, copyBuf)
|
||||
if err != nil {
|
||||
return bytesWritten, err
|
||||
}
|
||||
err = sparseWriter.Close()
|
||||
return bytesWritten, err
|
||||
}
|
||||
|
||||
type sparseWriter struct {
|
||||
writer io.WriteSeeker
|
||||
lastChunkSparse bool
|
||||
}
|
||||
|
||||
func newSparseWriter(writer io.WriteSeeker) *sparseWriter {
|
||||
return &sparseWriter{writer: writer}
|
||||
}
|
||||
|
||||
const copyChunkSize = 4096
|
||||
|
||||
var emptyChunk = make([]byte, copyChunkSize)
|
||||
|
||||
func isEmptyChunk(p []byte) bool {
|
||||
// HasPrefix instead of bytes.Equal in order to handle the last chunk
|
||||
// of the file, which may be shorter than len(emptyChunk), and would
|
||||
// fail bytes.Equal()
|
||||
return bytes.HasPrefix(emptyChunk, p)
|
||||
}
|
||||
|
||||
func (w *sparseWriter) Write(p []byte) (n int, err error) {
|
||||
if isEmptyChunk(p) {
|
||||
offset, err := w.writer.Seek(int64(len(p)), io.SeekCurrent)
|
||||
if err != nil {
|
||||
w.lastChunkSparse = false
|
||||
return 0, err
|
||||
}
|
||||
_ = offset
|
||||
w.lastChunkSparse = true
|
||||
return len(p), nil
|
||||
}
|
||||
w.lastChunkSparse = false
|
||||
return w.writer.Write(p)
|
||||
}
|
||||
|
||||
func (w *sparseWriter) Close() error {
|
||||
if w.lastChunkSparse {
|
||||
if _, err := w.writer.Seek(-1, io.SeekCurrent); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.writer.Write([]byte{0}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
86
vendor/github.com/crc-org/crc/v2/pkg/os/exec.go
generated
vendored
Normal file
86
vendor/github.com/crc-org/crc/v2/pkg/os/exec.go
generated
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
package os
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/crc-org/crc/v2/pkg/crc/logging"
|
||||
)
|
||||
|
||||
func runCmd(command string, args []string, env map[string]string) (string, string, error) {
|
||||
cmd := exec.Command(command, args...) // #nosec G204
|
||||
if len(env) != 0 {
|
||||
cmd.Env = os.Environ()
|
||||
for key, value := range env {
|
||||
cmd.Env = ReplaceOrAddEnv(cmd.Env, key, value)
|
||||
}
|
||||
}
|
||||
stdOut := new(bytes.Buffer)
|
||||
stdErr := new(bytes.Buffer)
|
||||
cmd.Stdout = stdOut
|
||||
cmd.Stderr = stdErr
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
logging.Debugf("Command failed: %v", err)
|
||||
logging.Debugf("stdout: %s", stdOut.String())
|
||||
logging.Debugf("stderr: %s", stdErr.String())
|
||||
}
|
||||
return stdOut.String(), stdErr.String(), err
|
||||
}
|
||||
|
||||
func run(command string, args []string, env map[string]string) (string, string, error) {
|
||||
logging.Debugf("Running '%s %s'", command, strings.Join(args, " "))
|
||||
return runCmd(command, args, env)
|
||||
}
|
||||
|
||||
func runPrivate(command string, args []string, env map[string]string) (string, string, error) {
|
||||
logging.Debugf("Running '%s <hidden arguments>'", command)
|
||||
return runCmd(command, args, env)
|
||||
}
|
||||
|
||||
// RunPrivileged executes a command using sudo
|
||||
// provide a reason why root is needed as the first argument
|
||||
func RunPrivileged(reason string, cmdAndArgs ...string) (string, string, error) {
|
||||
sudo, err := exec.LookPath("sudo")
|
||||
if err != nil {
|
||||
return "", "", errors.New("sudo executable not found")
|
||||
}
|
||||
logging.Infof("Using root access: %s", reason)
|
||||
return run(sudo, cmdAndArgs, map[string]string{})
|
||||
}
|
||||
|
||||
var defaultLocaleEnv = map[string]string{"LC_ALL": "C", "LANG": "C"}
|
||||
|
||||
func RunWithDefaultLocale(command string, args ...string) (string, string, error) {
|
||||
return run(command, args, defaultLocaleEnv)
|
||||
}
|
||||
|
||||
func RunWithDefaultLocalePrivate(command string, args ...string) (string, string, error) {
|
||||
return runPrivate(command, args, defaultLocaleEnv)
|
||||
}
|
||||
|
||||
type CommandRunner interface {
|
||||
Run(command string, args ...string) (string, string, error)
|
||||
RunPrivate(command string, args ...string) (string, string, error)
|
||||
RunPrivileged(reason string, cmdAndArgs ...string) (string, string, error)
|
||||
}
|
||||
type localRunner struct{}
|
||||
|
||||
func (r *localRunner) Run(command string, args ...string) (string, string, error) {
|
||||
return RunWithDefaultLocale(command, args...)
|
||||
}
|
||||
|
||||
func (r *localRunner) RunPrivate(command string, args ...string) (string, string, error) {
|
||||
return RunWithDefaultLocalePrivate(command, args...)
|
||||
}
|
||||
|
||||
func (r *localRunner) RunPrivileged(reason string, cmdAndArgs ...string) (string, string, error) {
|
||||
return RunPrivileged(reason, cmdAndArgs...)
|
||||
}
|
||||
|
||||
func NewLocalCommandRunner() CommandRunner {
|
||||
return &localRunner{}
|
||||
}
|
||||
57
vendor/github.com/crc-org/crc/v2/pkg/os/execerror.go
generated
vendored
Normal file
57
vendor/github.com/crc-org/crc/v2/pkg/os/execerror.go
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package os
|
||||
|
||||
// ExitError is an interface that presents an API similar to os.ProcessState, which is
|
||||
// what ExitError from os/exec is. This is designed to make testing a bit easier and
|
||||
// probably loses some of the cross-platform properties of the underlying library.
|
||||
type ExitError interface {
|
||||
String() string
|
||||
Error() string
|
||||
Exited() bool
|
||||
ExitStatus() int
|
||||
Unwrap() error
|
||||
}
|
||||
|
||||
// CodeExitError is an implementation of ExitError consisting of an error object
|
||||
// and an exit code (the upper bits of os.exec.ExitStatus).
|
||||
type CodeExitError struct {
|
||||
Err error
|
||||
Code int
|
||||
}
|
||||
|
||||
var _ ExitError = CodeExitError{}
|
||||
|
||||
func (e CodeExitError) Error() string {
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e CodeExitError) String() string {
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e CodeExitError) Exited() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (e CodeExitError) ExitStatus() int {
|
||||
return e.Code
|
||||
}
|
||||
|
||||
func (e CodeExitError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
129
vendor/github.com/crc-org/crc/v2/pkg/os/util.go
generated
vendored
Normal file
129
vendor/github.com/crc-org/crc/v2/pkg/os/util.go
generated
vendored
Normal file
@@ -0,0 +1,129 @@
|
||||
package os
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/crc-org/crc/v2/pkg/crc/logging"
|
||||
)
|
||||
|
||||
// ReplaceOrAddEnv changes the value of an environment variable if it exists otherwise add the new variable
|
||||
// It drops the existing value and appends the new value in-place
|
||||
func ReplaceOrAddEnv(variables []string, varName string, value string) []string {
|
||||
var result []string
|
||||
|
||||
found := false
|
||||
for _, e := range variables {
|
||||
pair := strings.Split(e, "=")
|
||||
if pair[0] != varName {
|
||||
result = append(result, e)
|
||||
} else {
|
||||
found = true
|
||||
result = append(result, fmt.Sprintf("%s=%s", varName, value))
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
result = append(result, fmt.Sprintf("%s=%s", varName, value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func CopyFileContents(src string, dst string, permission os.FileMode) error {
|
||||
logging.Debugf("Copying '%s' to '%s'", src, dst)
|
||||
srcFile, err := os.Open(filepath.Clean(src))
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%v] Cannot open src file '%s'", err, src)
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
destFile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE, permission)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%v] Cannot create dst file '%s'", err, dst)
|
||||
}
|
||||
defer destFile.Close()
|
||||
|
||||
_, err = io.Copy(destFile, srcFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%v] Cannot copy '%s' to '%s'", err, src, dst)
|
||||
}
|
||||
|
||||
err = destFile.Sync()
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%v] Cannot sync '%s' to '%s'", err, src, dst)
|
||||
}
|
||||
|
||||
return destFile.Close()
|
||||
}
|
||||
|
||||
func FileContentMatches(path string, expectedContent []byte) error {
|
||||
_, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("File not found: %s: %s", path, err.Error())
|
||||
}
|
||||
content, err := os.ReadFile(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error opening file: %s: %s", path, err.Error())
|
||||
}
|
||||
if !bytes.Equal(content, expectedContent) {
|
||||
return fmt.Errorf("File has unexpected content: %s", path)
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func WriteFileIfContentChanged(path string, newContent []byte, perm os.FileMode) (bool, error) {
|
||||
err := FileContentMatches(path, newContent)
|
||||
if err == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
/* Intentionally ignore errors, just try to write the file if we can't read it */
|
||||
err = os.WriteFile(path, newContent, perm)
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// FileExists returns true if the file at path exists.
|
||||
// It returns false if it does not exist, or if there was an error when checking for its existence.
|
||||
// This means there can be false negatives if Lstat fails because of permission issues (file exists,
|
||||
// but is not reachable by the current user)
|
||||
func FileExists(path string) bool {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return !info.IsDir()
|
||||
}
|
||||
|
||||
func RemoveFileIfExists(path string) error {
|
||||
if FileExists(path) {
|
||||
return os.Remove(path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RunningUsingSSH() bool {
|
||||
return os.Getenv("SSH_TTY") != ""
|
||||
}
|
||||
|
||||
// RemoveFileGlob takes a glob pattern as string to remove the files and directories that matches
|
||||
func RemoveFileGlob(glob string) error {
|
||||
matchedFiles, err := filepath.Glob(glob)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to find matches: %w", err)
|
||||
}
|
||||
for _, file := range matchedFiles {
|
||||
if err = os.RemoveAll(file); err != nil {
|
||||
return fmt.Errorf("Failed to delete file: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
48
vendor/github.com/crc-org/crc/v2/pkg/os/util_unix.go
generated
vendored
Normal file
48
vendor/github.com/crc-org/crc/v2/pkg/os/util_unix.go
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package os
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/crc-org/crc/v2/pkg/crc/logging"
|
||||
)
|
||||
|
||||
func WriteToFileAsRoot(reason, content, filepath string, mode os.FileMode) error {
|
||||
logging.Infof("Using root access: %s", reason)
|
||||
cmd := exec.Command("sudo", "tee", filepath) // #nosec G204
|
||||
cmd.Stdin = strings.NewReader(content)
|
||||
buf := new(bytes.Buffer)
|
||||
cmd.Stderr = buf
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("Failed writing to file as root: %s: %s: %v", filepath, buf.String(), err)
|
||||
}
|
||||
if _, _, err := RunPrivileged(fmt.Sprintf("Changing permissions for %s to %o ", filepath, mode),
|
||||
"chmod", strconv.FormatUint(uint64(mode), 8), filepath); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RemoveFileAsRoot(reason, filepath string) error {
|
||||
if !FileExists(filepath) {
|
||||
return nil
|
||||
}
|
||||
_, _, err := RunPrivileged(reason, "rm", "-fr", filepath)
|
||||
return err
|
||||
}
|
||||
|
||||
func GetCurrentUsername() (string, error) {
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return u.Username, nil
|
||||
}
|
||||
46
vendor/github.com/crc-org/crc/v2/pkg/os/util_windows.go
generated
vendored
Normal file
46
vendor/github.com/crc-org/crc/v2/pkg/os/util_windows.go
generated
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
package os
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/user"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/text/encoding/unicode"
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
// ReadFileUTF16LE reads a UTF-16LE file and returns in a []byte
|
||||
// ini/inf files in windows are of this format, reading a UTF-16
|
||||
// file directly without this would result in malformed texts
|
||||
func ReadFileUTF16LE(filename string) ([]byte, error) {
|
||||
// Read the file into a []byte
|
||||
raw, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Make an tranformer that converts MS-Win default to UTF8
|
||||
win16le := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
|
||||
// Make a transformer that is like win16le, but abides by BOM
|
||||
utf16bom := unicode.BOMOverride(win16le.NewDecoder())
|
||||
|
||||
// Make a Reader that uses utf16bom
|
||||
unicodeReader := transform.NewReader(bytes.NewReader(raw), utf16bom)
|
||||
decoded, err := io.ReadAll(unicodeReader)
|
||||
return decoded, err
|
||||
}
|
||||
|
||||
func GetCurrentUsername() (string, error) {
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
userAndDomain := strings.Split(u.Username, "\\")
|
||||
if len(userAndDomain) > 1 {
|
||||
return userAndDomain[1], nil
|
||||
}
|
||||
return "", errors.New("unable to find the username of current user")
|
||||
}
|
||||
Reference in New Issue
Block a user