| 1 |
package dockerclient |
| 2 |
|
| 3 |
import ( |
| 4 |
"archive/tar" |
| 5 |
"context" |
| 6 |
"io" |
| 7 |
|
| 8 |
docker "github.com/fsouza/go-dockerclient" |
| 9 |
"k8s.io/klog" |
| 10 |
) |
| 11 |
|
| 12 |
type DirectoryCheck interface { |
| 13 |
IsDirectory(path string) (bool, error) |
| 14 |
} |
| 15 |
|
| 16 |
type directoryCheck struct { |
| 17 |
containerID string |
| 18 |
client *docker.Client |
| 19 |
} |
| 20 |
|
| 21 |
func newDirectoryCheck(client *docker.Client, containerID string) *directoryCheck { |
| 22 |
return &directoryCheck{ |
| 23 |
containerID: containerID, |
| 24 |
client: client, |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
func (c *directoryCheck) IsDirectory(path string) (bool, error) { |
| 29 |
if path == "/" || path == "." || path == "./" { |
| 30 |
return true, nil |
| 31 |
} |
| 32 |
|
| 33 |
dir, err := isContainerPathDirectory(c.client, c.containerID, path) |
| 34 |
if err != nil { |
| 35 |
return false, err |
| 36 |
} |
| 37 |
|
| 38 |
return dir, nil |
| 39 |
} |
| 40 |
|
| 41 |
func isContainerPathDirectory(client *docker.Client, containerID, path string) (bool, error) { |
| 42 |
pr, pw := io.Pipe() |
| 43 |
defer pw.Close() |
| 44 |
ctx, cancel := context.WithCancel(context.TODO()) |
| 45 |
go func() { |
| 46 |
err := client.DownloadFromContainer(containerID, docker.DownloadFromContainerOptions{ |
| 47 |
OutputStream: pw, |
| 48 |
Path: path, |
| 49 |
Context: ctx, |
| 50 |
}) |
| 51 |
if err != nil { |
| 52 |
if apiErr, ok := err.(*docker.Error); ok && apiErr.Status == 404 { |
| 53 |
klog.V(4).Infof("path %s did not exist in container %s: %v", path, containerID, err) |
| 54 |
err = nil |
| 55 |
} |
| 56 |
if err != nil && err != context.Canceled { |
| 57 |
klog.V(6).Infof("error while checking directory contents for container %s at path %s: %v", containerID, path, err) |
| 58 |
} |
| 59 |
} |
| 60 |
pw.CloseWithError(err) |
| 61 |
}() |
| 62 |
|
| 63 |
tr := tar.NewReader(pr) |
| 64 |
|
| 65 |
h, err := tr.Next() |
| 66 |
if err != nil { |
| 67 |
if err == io.EOF { |
| 68 |
err = nil |
| 69 |
} |
| 70 |
cancel() |
| 71 |
return false, err |
| 72 |
} |
| 73 |
|
| 74 |
klog.V(4).Infof("Retrieved first header from container %s at path %s: %#v", containerID, path, h) |
| 75 |
|
| 76 |
// take the remainder of the input and discard it |
| 77 |
go func() { |
| 78 |
cancel() |
| 79 |
n, err := io.Copy(io.Discard, pr) |
| 80 |
if n > 0 || err != nil { |
| 81 |
klog.V(6).Infof("Discarded %d bytes from end of container directory check, and got error: %v", n, err) |
| 82 |
} |
| 83 |
}() |
| 84 |
|
| 85 |
return h.FileInfo().IsDir(), nil |
| 86 |
} |