Fresh dep ensure

This commit is contained in:
Mike Cronce
2018-11-26 13:23:56 -05:00
parent 93cb8a04d7
commit 407478ab9a
9016 changed files with 551394 additions and 279685 deletions

50
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/cp/BUILD generated vendored Normal file
View File

@ -0,0 +1,50 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = ["cp.go"],
importpath = "k8s.io/kubernetes/pkg/kubectl/cmd/cp",
visibility = ["//visibility:public"],
deps = [
"//pkg/kubectl/cmd/exec:go_default_library",
"//pkg/kubectl/cmd/util:go_default_library",
"//pkg/kubectl/util/i18n:go_default_library",
"//pkg/kubectl/util/templates:go_default_library",
"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions:go_default_library",
"//staging/src/k8s.io/client-go/kubernetes:go_default_library",
"//staging/src/k8s.io/client-go/rest:go_default_library",
"//vendor/github.com/renstrom/dedent:go_default_library",
"//vendor/github.com/spf13/cobra:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["cp_test.go"],
embed = [":go_default_library"],
deps = [
"//pkg/kubectl/cmd/exec:go_default_library",
"//pkg/kubectl/cmd/testing:go_default_library",
"//pkg/kubectl/scheme:go_default_library",
"//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/api/errors:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions:go_default_library",
"//staging/src/k8s.io/client-go/rest/fake:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

513
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/cp/cp.go generated vendored Normal file
View File

@ -0,0 +1,513 @@
/*
Copyright 2016 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 cp
import (
"archive/tar"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/kubernetes/pkg/kubectl/cmd/exec"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
"k8s.io/kubernetes/pkg/kubectl/util/templates"
"bytes"
"github.com/renstrom/dedent"
"github.com/spf13/cobra"
)
var (
cpExample = templates.Examples(i18n.T(`
# !!!Important Note!!!
# Requires that the 'tar' binary is present in your container
# image. If 'tar' is not present, 'kubectl cp' will fail.
# Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
# Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
# Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar
# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar`))
cpUsageStr = dedent.Dedent(`
expected 'cp <file-spec-src> <file-spec-dest> [-c container]'.
<file-spec> is:
[namespace/]pod-name:/file/path for a remote file
/file/path for a local file`)
)
type CopyOptions struct {
Container string
Namespace string
NoPreserve bool
ClientConfig *restclient.Config
Clientset kubernetes.Interface
genericclioptions.IOStreams
}
func NewCopyOptions(ioStreams genericclioptions.IOStreams) *CopyOptions {
return &CopyOptions{
IOStreams: ioStreams,
}
}
// NewCmdCp creates a new Copy command.
func NewCmdCp(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewCopyOptions(ioStreams)
cmd := &cobra.Command{
Use: "cp <file-spec-src> <file-spec-dest>",
DisableFlagsInUseLine: true,
Short: i18n.T("Copy files and directories to and from containers."),
Long: "Copy files and directories to and from containers.",
Example: cpExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd))
cmdutil.CheckErr(o.Run(args))
},
}
cmd.Flags().StringVarP(&o.Container, "container", "c", o.Container, "Container name. If omitted, the first container in the pod will be chosen")
cmd.Flags().BoolVarP(&o.NoPreserve, "no-preserve", "", false, "The copied file/directory's ownership and permissions will not be preserved in the container")
return cmd
}
type fileSpec struct {
PodNamespace string
PodName string
File string
}
var (
errFileSpecDoesntMatchFormat = errors.New("Filespec must match the canonical format: [[namespace/]pod:]file/path")
errFileCannotBeEmpty = errors.New("Filepath can not be empty")
)
func extractFileSpec(arg string) (fileSpec, error) {
if i := strings.Index(arg, ":"); i == -1 {
return fileSpec{File: arg}, nil
} else if i > 0 {
file := arg[i+1:]
pod := arg[:i]
pieces := strings.Split(pod, "/")
if len(pieces) == 1 {
return fileSpec{
PodName: pieces[0],
File: file,
}, nil
}
if len(pieces) == 2 {
return fileSpec{
PodNamespace: pieces[0],
PodName: pieces[1],
File: file,
}, nil
}
}
return fileSpec{}, errFileSpecDoesntMatchFormat
}
func (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
var err error
o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
o.Clientset, err = f.KubernetesClientSet()
if err != nil {
return err
}
o.ClientConfig, err = f.ToRESTConfig()
if err != nil {
return err
}
return nil
}
func (o *CopyOptions) Validate(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmdutil.UsageErrorf(cmd, cpUsageStr)
}
return nil
}
func (o *CopyOptions) Run(args []string) error {
if len(args) < 2 {
return fmt.Errorf("source and destination are required")
}
srcSpec, err := extractFileSpec(args[0])
if err != nil {
return err
}
destSpec, err := extractFileSpec(args[1])
if err != nil {
return err
}
if len(srcSpec.PodName) != 0 && len(destSpec.PodName) != 0 {
if _, err := os.Stat(args[0]); err == nil {
return o.copyToPod(fileSpec{File: args[0]}, destSpec, &exec.ExecOptions{})
}
return fmt.Errorf("src doesn't exist in local filesystem")
}
if len(srcSpec.PodName) != 0 {
return o.copyFromPod(srcSpec, destSpec)
}
if len(destSpec.PodName) != 0 {
return o.copyToPod(srcSpec, destSpec, &exec.ExecOptions{})
}
return fmt.Errorf("one of src or dest must be a remote file specification")
}
// checkDestinationIsDir receives a destination fileSpec and
// determines if the provided destination path exists on the
// pod. If the destination path does not exist or is _not_ a
// directory, an error is returned with the exit code received.
func (o *CopyOptions) checkDestinationIsDir(dest fileSpec) error {
options := &exec.ExecOptions{
StreamOptions: exec.StreamOptions{
IOStreams: genericclioptions.IOStreams{
Out: bytes.NewBuffer([]byte{}),
ErrOut: bytes.NewBuffer([]byte{}),
},
Namespace: dest.PodNamespace,
PodName: dest.PodName,
},
Command: []string{"test", "-d", dest.File},
Executor: &exec.DefaultRemoteExecutor{},
}
return o.execute(options)
}
func (o *CopyOptions) copyToPod(src, dest fileSpec, options *exec.ExecOptions) error {
if len(src.File) == 0 || len(dest.File) == 0 {
return errFileCannotBeEmpty
}
reader, writer := io.Pipe()
// strip trailing slash (if any)
if dest.File != "/" && strings.HasSuffix(string(dest.File[len(dest.File)-1]), "/") {
dest.File = dest.File[:len(dest.File)-1]
}
if err := o.checkDestinationIsDir(dest); err == nil {
// If no error, dest.File was found to be a directory.
// Copy specified src into it
dest.File = dest.File + "/" + path.Base(src.File)
}
go func() {
defer writer.Close()
err := makeTar(src.File, dest.File, writer)
cmdutil.CheckErr(err)
}()
var cmdArr []string
// TODO: Improve error messages by first testing if 'tar' is present in the container?
if o.NoPreserve {
cmdArr = []string{"tar", "--no-same-permissions", "--no-same-owner", "-xf", "-"}
} else {
cmdArr = []string{"tar", "-xf", "-"}
}
destDir := path.Dir(dest.File)
if len(destDir) > 0 {
cmdArr = append(cmdArr, "-C", destDir)
}
options.StreamOptions = exec.StreamOptions{
IOStreams: genericclioptions.IOStreams{
In: reader,
Out: o.Out,
ErrOut: o.ErrOut,
},
Stdin: true,
Namespace: dest.PodNamespace,
PodName: dest.PodName,
}
options.Command = cmdArr
options.Executor = &exec.DefaultRemoteExecutor{}
return o.execute(options)
}
func (o *CopyOptions) copyFromPod(src, dest fileSpec) error {
if len(src.File) == 0 || len(dest.File) == 0 {
return errFileCannotBeEmpty
}
reader, outStream := io.Pipe()
options := &exec.ExecOptions{
StreamOptions: exec.StreamOptions{
IOStreams: genericclioptions.IOStreams{
In: nil,
Out: outStream,
ErrOut: o.Out,
},
Namespace: src.PodNamespace,
PodName: src.PodName,
},
// TODO: Improve error messages by first testing if 'tar' is present in the container?
Command: []string{"tar", "cf", "-", src.File},
Executor: &exec.DefaultRemoteExecutor{},
}
go func() {
defer outStream.Close()
o.execute(options)
}()
prefix := getPrefix(src.File)
prefix = path.Clean(prefix)
// remove extraneous path shortcuts - these could occur if a path contained extra "../"
// and attempted to navigate beyond "/" in a remote filesystem
prefix = stripPathShortcuts(prefix)
return untarAll(reader, dest.File, prefix)
}
// stripPathShortcuts removes any leading or trailing "../" from a given path
func stripPathShortcuts(p string) string {
newPath := path.Clean(p)
trimmed := strings.TrimPrefix(newPath, "../")
for trimmed != newPath {
newPath = trimmed
trimmed = strings.TrimPrefix(newPath, "../")
}
// trim leftover ".."
if newPath == ".." {
newPath = ""
}
if len(newPath) > 0 && string(newPath[0]) == "/" {
return newPath[1:]
}
return newPath
}
func makeTar(srcPath, destPath string, writer io.Writer) error {
// TODO: use compression here?
tarWriter := tar.NewWriter(writer)
defer tarWriter.Close()
srcPath = path.Clean(srcPath)
destPath = path.Clean(destPath)
return recursiveTar(path.Dir(srcPath), path.Base(srcPath), path.Dir(destPath), path.Base(destPath), tarWriter)
}
func recursiveTar(srcBase, srcFile, destBase, destFile string, tw *tar.Writer) error {
filepath := path.Join(srcBase, srcFile)
stat, err := os.Lstat(filepath)
if err != nil {
return err
}
if stat.IsDir() {
files, err := ioutil.ReadDir(filepath)
if err != nil {
return err
}
if len(files) == 0 {
//case empty directory
hdr, _ := tar.FileInfoHeader(stat, filepath)
hdr.Name = destFile
if err := tw.WriteHeader(hdr); err != nil {
return err
}
}
for _, f := range files {
if err := recursiveTar(srcBase, path.Join(srcFile, f.Name()), destBase, path.Join(destFile, f.Name()), tw); err != nil {
return err
}
}
return nil
} else if stat.Mode()&os.ModeSymlink != 0 {
//case soft link
hdr, _ := tar.FileInfoHeader(stat, filepath)
target, err := os.Readlink(filepath)
if err != nil {
return err
}
hdr.Linkname = target
hdr.Name = destFile
if err := tw.WriteHeader(hdr); err != nil {
return err
}
} else {
//case regular file or other file type like pipe
hdr, err := tar.FileInfoHeader(stat, filepath)
if err != nil {
return err
}
hdr.Name = destFile
if err := tw.WriteHeader(hdr); err != nil {
return err
}
f, err := os.Open(filepath)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(tw, f); err != nil {
return err
}
return f.Close()
}
return nil
}
// clean prevents path traversals by stripping them out.
// This is adapted from https://golang.org/src/net/http/fs.go#L74
func clean(fileName string) string {
return path.Clean(string(os.PathSeparator) + fileName)
}
func untarAll(reader io.Reader, destFile, prefix string) error {
entrySeq := -1
// TODO: use compression here?
tarReader := tar.NewReader(reader)
for {
header, err := tarReader.Next()
if err != nil {
if err != io.EOF {
return err
}
break
}
entrySeq++
mode := header.FileInfo().Mode()
outFileName := path.Join(destFile, clean(header.Name[len(prefix):]))
baseName := path.Dir(outFileName)
if err := os.MkdirAll(baseName, 0755); err != nil {
return err
}
if header.FileInfo().IsDir() {
if err := os.MkdirAll(outFileName, 0755); err != nil {
return err
}
continue
}
// handle coping remote file into local directory
if entrySeq == 0 && !header.FileInfo().IsDir() {
exists, err := dirExists(outFileName)
if err != nil {
return err
}
if exists {
outFileName = filepath.Join(outFileName, path.Base(clean(header.Name)))
}
}
if mode&os.ModeSymlink != 0 {
err := os.Symlink(header.Linkname, outFileName)
if err != nil {
return err
}
} else {
outFile, err := os.Create(outFileName)
if err != nil {
return err
}
defer outFile.Close()
if _, err := io.Copy(outFile, tarReader); err != nil {
return err
}
if err := outFile.Close(); err != nil {
return err
}
}
}
if entrySeq == -1 {
//if no file was copied
errInfo := fmt.Sprintf("error: %s no such file or directory", prefix)
return errors.New(errInfo)
}
return nil
}
func getPrefix(file string) string {
// tar strips the leading '/' if it's there, so we will too
return strings.TrimLeft(file, "/")
}
func (o *CopyOptions) execute(options *exec.ExecOptions) error {
if len(options.Namespace) == 0 {
options.Namespace = o.Namespace
}
if len(o.Container) > 0 {
options.ContainerName = o.Container
}
options.Config = o.ClientConfig
options.PodClient = o.Clientset.Core()
if err := options.Validate(); err != nil {
return err
}
if err := options.Run(); err != nil {
return err
}
return nil
}
// dirExists checks if a path exists and is a directory.
func dirExists(path string) (bool, error) {
fi, err := os.Stat(path)
if err == nil && fi.IsDir() {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}

740
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/cp/cp_test.go generated vendored Normal file
View File

@ -0,0 +1,740 @@
/*
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 cp
import (
"archive/tar"
"bytes"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"strings"
"testing"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/rest/fake"
kexec "k8s.io/kubernetes/pkg/kubectl/cmd/exec"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/kubectl/scheme"
)
type FileType int
const (
RegularFile FileType = 0
SymLink FileType = 1
)
func TestExtractFileSpec(t *testing.T) {
tests := []struct {
spec string
expectedPod string
expectedNamespace string
expectedFile string
expectErr bool
}{
{
spec: "namespace/pod:/some/file",
expectedPod: "pod",
expectedNamespace: "namespace",
expectedFile: "/some/file",
},
{
spec: "pod:/some/file",
expectedPod: "pod",
expectedFile: "/some/file",
},
{
spec: "/some/file",
expectedFile: "/some/file",
},
{
spec: ":file:not:exist:in:local:filesystem",
expectErr: true,
},
{
spec: "namespace/pod/invalid:/some/file",
expectErr: true,
},
{
spec: "pod:/some/filenamewith:in",
expectedPod: "pod",
expectedFile: "/some/filenamewith:in",
},
}
for _, test := range tests {
spec, err := extractFileSpec(test.spec)
if test.expectErr && err == nil {
t.Errorf("unexpected non-error")
continue
}
if err != nil && !test.expectErr {
t.Errorf("unexpected error: %v", err)
continue
}
if spec.PodName != test.expectedPod {
t.Errorf("expected: %s, saw: %s", test.expectedPod, spec.PodName)
}
if spec.PodNamespace != test.expectedNamespace {
t.Errorf("expected: %s, saw: %s", test.expectedNamespace, spec.PodNamespace)
}
if spec.File != test.expectedFile {
t.Errorf("expected: %s, saw: %s", test.expectedFile, spec.File)
}
}
}
func TestGetPrefix(t *testing.T) {
tests := []struct {
input string
expected string
}{
{
input: "/foo/bar",
expected: "foo/bar",
},
{
input: "foo/bar",
expected: "foo/bar",
},
}
for _, test := range tests {
out := getPrefix(test.input)
if out != test.expected {
t.Errorf("expected: %s, saw: %s", test.expected, out)
}
}
}
func TestStripPathShortcuts(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "test single path shortcut prefix",
input: "../foo/bar",
expected: "foo/bar",
},
{
name: "test multiple path shortcuts",
input: "../../foo/bar",
expected: "foo/bar",
},
{
name: "test multiple path shortcuts with absolute path",
input: "/tmp/one/two/../../foo/bar",
expected: "tmp/foo/bar",
},
{
name: "test multiple path shortcuts with no named directory",
input: "../../",
expected: "",
},
{
name: "test multiple path shortcuts with no named directory and no trailing slash",
input: "../..",
expected: "",
},
{
name: "test multiple path shortcuts with absolute path and filename containing leading dots",
input: "/tmp/one/two/../../foo/..bar",
expected: "tmp/foo/..bar",
},
{
name: "test multiple path shortcuts with no named directory and filename containing leading dots",
input: "../...foo",
expected: "...foo",
},
{
name: "test filename containing leading dots",
input: "...foo",
expected: "...foo",
},
}
for _, test := range tests {
out := stripPathShortcuts(test.input)
if out != test.expected {
t.Errorf("expected: %s, saw: %s", test.expected, out)
}
}
}
func TestTarUntar(t *testing.T) {
dir, err := ioutil.TempDir("", "input")
dir2, err2 := ioutil.TempDir("", "output")
if err != nil || err2 != nil {
t.Errorf("unexpected error: %v | %v", err, err2)
t.FailNow()
}
dir = dir + "/"
defer func() {
if err := os.RemoveAll(dir); err != nil {
t.Errorf("Unexpected error cleaning up: %v", err)
}
if err := os.RemoveAll(dir2); err != nil {
t.Errorf("Unexpected error cleaning up: %v", err)
}
}()
files := []struct {
name string
data string
fileType FileType
}{
{
name: "foo",
data: "foobarbaz",
fileType: RegularFile,
},
{
name: "dir/blah",
data: "bazblahfoo",
fileType: RegularFile,
},
{
name: "some/other/directory/",
data: "with more data here",
fileType: RegularFile,
},
{
name: "blah",
data: "same file name different data",
fileType: RegularFile,
},
{
name: "gakki",
data: "/tmp/gakki",
fileType: SymLink,
},
}
for _, file := range files {
filepath := path.Join(dir, file.name)
if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if file.fileType == RegularFile {
f, err := os.Create(filepath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer f.Close()
if _, err := io.Copy(f, bytes.NewBuffer([]byte(file.data))); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
} else if file.fileType == SymLink {
err := os.Symlink(file.data, filepath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
} else {
t.Fatalf("unexpected file type: %v", file)
}
}
writer := &bytes.Buffer{}
if err := makeTar(dir, dir, writer); err != nil {
t.Fatalf("unexpected error: %v", err)
}
reader := bytes.NewBuffer(writer.Bytes())
if err := untarAll(reader, dir2, ""); err != nil {
t.Fatalf("unexpected error: %v", err)
}
for _, file := range files {
absPath := filepath.Join(dir2, strings.TrimPrefix(dir, os.TempDir()))
filePath := filepath.Join(absPath, file.name)
if file.fileType == RegularFile {
f, err := os.Open(filePath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer f.Close()
buff := &bytes.Buffer{}
if _, err := io.Copy(buff, f); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
if file.data != string(buff.Bytes()) {
t.Fatalf("expected: %s, saw: %s", file.data, string(buff.Bytes()))
}
} else if file.fileType == SymLink {
dest, err := os.Readlink(filePath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if file.data != dest {
t.Fatalf("expected: %s, saw: %s", file.data, dest)
}
} else {
t.Fatalf("unexpected file type: %v", file)
}
}
}
// TestCopyToLocalFileOrDir tests untarAll in two cases :
// 1: copy pod file to local file
// 2: copy pod file into local directory
func TestCopyToLocalFileOrDir(t *testing.T) {
dir, err := ioutil.TempDir(os.TempDir(), "input")
dir2, err2 := ioutil.TempDir(os.TempDir(), "output")
if err != nil || err2 != nil {
t.Errorf("unexpected error: %v | %v", err, err2)
t.FailNow()
}
defer func() {
if err := os.RemoveAll(dir); err != nil {
t.Errorf("Unexpected error cleaning up: %v", err)
}
if err := os.RemoveAll(dir2); err != nil {
t.Errorf("Unexpected error cleaning up: %v", err)
}
}()
files := []struct {
name string
data string
dest string
destDirExists bool
}{
{
name: "foo",
data: "foobarbaz",
dest: "path/to/dest",
destDirExists: false,
},
{
name: "dir/blah",
data: "bazblahfoo",
dest: "dest/file/path",
destDirExists: true,
},
}
for _, file := range files {
func() {
// setup
srcFilePath := filepath.Join(dir, file.name)
destPath := filepath.Join(dir2, file.dest)
if err := os.MkdirAll(filepath.Dir(srcFilePath), 0755); err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
srcFile, err := os.Create(srcFilePath)
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
defer srcFile.Close()
if _, err := io.Copy(srcFile, bytes.NewBuffer([]byte(file.data))); err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
if file.destDirExists {
if err := os.MkdirAll(destPath, 0755); err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
}
// start tests
srcTarFilePath := filepath.Join(dir, file.name+".tar")
// here use tar command to create tar file instead of calling makeTar func
// because makeTar func can not generate correct header name
err = exec.Command("tar", "cf", srcTarFilePath, srcFilePath).Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
srcTarFile, err := os.Open(srcTarFilePath)
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
defer srcTarFile.Close()
if err := untarAll(srcTarFile, destPath, getPrefix(srcFilePath)); err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
actualDestFilePath := destPath
if file.destDirExists {
actualDestFilePath = filepath.Join(destPath, filepath.Base(srcFilePath))
}
_, err = os.Stat(actualDestFilePath)
if err != nil && os.IsNotExist(err) {
t.Errorf("expecting %s exists, but actually it's missing", actualDestFilePath)
}
destFile, err := os.Open(actualDestFilePath)
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
defer destFile.Close()
buff := &bytes.Buffer{}
io.Copy(buff, destFile)
if file.data != string(buff.Bytes()) {
t.Errorf("expected: %s, actual: %s", file.data, string(buff.Bytes()))
}
}()
}
}
func TestTarDestinationName(t *testing.T) {
dir, err := ioutil.TempDir(os.TempDir(), "input")
dir2, err2 := ioutil.TempDir(os.TempDir(), "output")
if err != nil || err2 != nil {
t.Errorf("unexpected error: %v | %v", err, err2)
t.FailNow()
}
defer func() {
if err := os.RemoveAll(dir); err != nil {
t.Errorf("Unexpected error cleaning up: %v", err)
}
if err := os.RemoveAll(dir2); err != nil {
t.Errorf("Unexpected error cleaning up: %v", err)
}
}()
files := []struct {
name string
data string
}{
{
name: "foo",
data: "foobarbaz",
},
{
name: "dir/blah",
data: "bazblahfoo",
},
{
name: "some/other/directory",
data: "with more data here",
},
{
name: "blah",
data: "same file name different data",
},
}
// ensure files exist on disk
for _, file := range files {
filepath := path.Join(dir, file.name)
if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
f, err := os.Create(filepath)
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
defer f.Close()
if _, err := io.Copy(f, bytes.NewBuffer([]byte(file.data))); err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
}
reader, writer := io.Pipe()
go func() {
if err := makeTar(dir, dir2, writer); err != nil {
t.Errorf("unexpected error: %v", err)
}
}()
tarReader := tar.NewReader(reader)
for {
hdr, err := tarReader.Next()
if err == io.EOF {
break
} else if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
if !strings.HasPrefix(hdr.Name, path.Base(dir2)) {
t.Errorf("expected %q as destination filename prefix, saw: %q", path.Base(dir2), hdr.Name)
}
}
}
func TestBadTar(t *testing.T) {
dir, err := ioutil.TempDir(os.TempDir(), "dest")
if err != nil {
t.Errorf("unexpected error: %v ", err)
t.FailNow()
}
defer os.RemoveAll(dir)
// More or less cribbed from https://golang.org/pkg/archive/tar/#example__minimal
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
var files = []struct {
name string
body string
}{
{"/prefix/../../../tmp/foo", "Up to temp"},
{"/prefix/foo/bar/../../home/bburns/names.txt", "Down and back"},
}
for _, file := range files {
hdr := &tar.Header{
Name: file.name,
Mode: 0600,
Size: int64(len(file.body)),
}
if err := tw.WriteHeader(hdr); err != nil {
t.Errorf("unexpected error: %v ", err)
t.FailNow()
}
if _, err := tw.Write([]byte(file.body)); err != nil {
t.Errorf("unexpected error: %v ", err)
t.FailNow()
}
}
if err := tw.Close(); err != nil {
t.Errorf("unexpected error: %v ", err)
t.FailNow()
}
if err := untarAll(&buf, dir, "/prefix"); err != nil {
t.Errorf("unexpected error: %v ", err)
t.FailNow()
}
for _, file := range files {
_, err := os.Stat(path.Join(dir, path.Clean(file.name[len("/prefix"):])))
if err != nil {
t.Errorf("Error finding file: %v", err)
}
}
}
func TestClean(t *testing.T) {
tests := []struct {
input string
cleaned string
}{
{
"../../../tmp/foo",
"/tmp/foo",
},
{
"/../../../tmp/foo",
"/tmp/foo",
},
}
for _, test := range tests {
out := clean(test.input)
if out != test.cleaned {
t.Errorf("Expected: %s, saw %s", test.cleaned, out)
}
}
}
func TestCopyToPod(t *testing.T) {
tf := cmdtesting.NewTestFactory().WithNamespace("test")
ns := scheme.Codecs
codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Group: "", Version: "v1"},
NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
responsePod := &v1.Pod{}
return &http.Response{StatusCode: http.StatusNotFound, Header: cmdtesting.DefaultHeader(), Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, responsePod))))}, nil
}),
}
tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
cmd := NewCmdCp(tf, ioStreams)
srcFile, err := ioutil.TempDir("", "test")
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
defer os.RemoveAll(srcFile)
tests := map[string]struct {
dest string
expectedErr bool
}{
"copy to directory": {
dest: "/tmp/",
expectedErr: false,
},
"copy to root": {
dest: "/",
expectedErr: false,
},
"copy to empty file name": {
dest: "",
expectedErr: true,
},
}
for name, test := range tests {
opts := NewCopyOptions(ioStreams)
src := fileSpec{
File: srcFile,
}
dest := fileSpec{
PodNamespace: "pod-ns",
PodName: "pod-name",
File: test.dest,
}
opts.Complete(tf, cmd)
t.Run(name, func(t *testing.T) {
err = opts.copyToPod(src, dest, &kexec.ExecOptions{})
//If error is NotFound error , it indicates that the
//request has been sent correctly.
//Treat this as no error.
if test.expectedErr && errors.IsNotFound(err) {
t.Errorf("expected error but didn't get one")
}
if !test.expectedErr && !errors.IsNotFound(err) {
t.Errorf("unexpected error: %v", err)
}
})
}
}
func TestCopyToPodNoPreserve(t *testing.T) {
tf := cmdtesting.NewTestFactory().WithNamespace("test")
ns := scheme.Codecs
codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Group: "", Version: "v1"},
NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
responsePod := &v1.Pod{}
return &http.Response{StatusCode: http.StatusNotFound, Header: cmdtesting.DefaultHeader(), Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, responsePod))))}, nil
}),
}
tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
cmd := NewCmdCp(tf, ioStreams)
srcFile, err := ioutil.TempDir("", "test")
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
defer os.RemoveAll(srcFile)
tests := map[string]struct {
expectedCmd []string
nopreserve bool
}{
"copy to pod no preserve user and permissions": {
expectedCmd: []string{"tar", "--no-same-permissions", "--no-same-owner", "-xf", "-", "-C", "."},
nopreserve: true,
},
"copy to pod preserve user and permissions": {
expectedCmd: []string{"tar", "-xf", "-", "-C", "."},
nopreserve: false,
},
}
opts := NewCopyOptions(ioStreams)
src := fileSpec{
File: srcFile,
}
dest := fileSpec{
PodNamespace: "pod-ns",
PodName: "pod-name",
File: "foo",
}
opts.Complete(tf, cmd)
for name, test := range tests {
t.Run(name, func(t *testing.T) {
options := &kexec.ExecOptions{}
opts.NoPreserve = test.nopreserve
err = opts.copyToPod(src, dest, options)
if !(reflect.DeepEqual(test.expectedCmd, options.Command)) {
t.Errorf("expected cmd: %v, got: %v", test.expectedCmd, options.Command)
}
})
}
}
func TestValidate(t *testing.T) {
tests := []struct {
name string
args []string
expectedErr bool
}{
{
name: "Validate Succeed",
args: []string{"1", "2"},
expectedErr: false,
},
{
name: "Validate Fail",
args: []string{"1", "2", "3"},
expectedErr: true,
},
}
tf := cmdtesting.NewTestFactory()
ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
opts := NewCopyOptions(ioStreams)
cmd := NewCmdCp(tf, ioStreams)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := opts.Validate(cmd, test.args)
if (err != nil) != test.expectedErr {
t.Errorf("expected error: %v, saw: %v, error: %v", test.expectedErr, err != nil, err)
}
})
}
}