1/*
2Copyright 2020 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package proxy
18
19import (
20	"fmt"
21
22	"k8s.io/kubernetes/test/e2e/framework"
23	"k8s.io/kubernetes/test/e2e/storage/drivers/csi-test/mock/service"
24)
25
26type PodDirIO struct {
27	F             *framework.Framework
28	Namespace     string
29	PodName       string
30	ContainerName string
31}
32
33var _ service.DirIO = PodDirIO{}
34
35func (p PodDirIO) DirExists(path string) (bool, error) {
36	stdout, stderr, err := p.execute([]string{
37		"sh",
38		"-c",
39		fmt.Sprintf("if ! [ -e '%s' ]; then echo notexist; elif [ -d '%s' ]; then echo dir; else echo nodir; fi", path, path),
40	})
41	if err != nil {
42		return false, fmt.Errorf("error executing dir test commands: stderr=%q, %v", stderr, err)
43	}
44	switch stdout {
45	case "notexist":
46		return false, nil
47	case "nodir":
48		return false, fmt.Errorf("%s: not a directory", path)
49	case "dir":
50		return true, nil
51	default:
52		return false, fmt.Errorf("unexpected output from dir test commands: %q", stdout)
53	}
54}
55
56func (p PodDirIO) Mkdir(path string) error {
57	_, stderr, err := p.execute([]string{"mkdir", path})
58	if err != nil {
59		return fmt.Errorf("mkdir %q: stderr=%q, %v", path, stderr, err)
60	}
61	return nil
62}
63
64func (p PodDirIO) RemoveAll(path string) error {
65	_, stderr, err := p.execute([]string{"rm", "-rf", path})
66	if err != nil {
67		return fmt.Errorf("rm -rf %q: stderr=%q, %v", path, stderr, err)
68	}
69	return nil
70}
71
72func (p PodDirIO) execute(command []string) (string, string, error) {
73	return p.F.ExecWithOptions(framework.ExecOptions{
74		Command:       command,
75		Namespace:     p.Namespace,
76		PodName:       p.PodName,
77		ContainerName: p.ContainerName,
78		CaptureStdout: true,
79		CaptureStderr: true,
80		Quiet:         true,
81	})
82}
83