Allow finding docker containers by short name

Allow docker containers to be found by a short prefix name to match
the behavior of the docker daemon. This change now matches the
examples on the API docs.

Return an error if the given short name of a container is not unique.
This commit is contained in:
Chris Bui 2017-05-18 08:17:15 -05:00 committed by Chris Bui
parent fdb6e418c2
commit cdf78981fb
2 changed files with 33 additions and 3 deletions

View File

@ -566,9 +566,24 @@ func (self *manager) getDockerContainer(containerName string) (*containerData, e
Namespace: docker.DockerNamespace, Namespace: docker.DockerNamespace,
Name: containerName, Name: containerName,
}] }]
// Look for container by short prefix name if no exact match found.
if !ok { if !ok {
return nil, fmt.Errorf("unable to find Docker container %q", containerName) for contName, c := range self.containers {
if contName.Namespace == docker.DockerNamespace && strings.HasPrefix(contName.Name, containerName) {
if cont == nil {
cont = c
} else {
return nil, fmt.Errorf("unable to find container. Container %q is not unique", containerName)
}
}
}
if cont == nil {
return nil, fmt.Errorf("unable to find Docker container %q", containerName)
}
} }
return cont, nil return cont, nil
} }

View File

@ -280,7 +280,8 @@ func TestSubcontainersInfo(t *testing.T) {
func TestDockerContainersInfo(t *testing.T) { func TestDockerContainersInfo(t *testing.T) {
containers := []string{ containers := []string{
"/docker/c1", "/docker/c1a",
"/docker/c2a",
} }
query := &info.ContainerInfoRequest{ query := &info.ContainerInfoRequest{
@ -289,13 +290,27 @@ func TestDockerContainersInfo(t *testing.T) {
m, _, _ := expectManagerWithContainers(containers, query, t) m, _, _ := expectManagerWithContainers(containers, query, t)
result, err := m.DockerContainer("c1", query) result, err := m.DockerContainer("c1a", query)
if err != nil { if err != nil {
t.Fatalf("expected to succeed: %s", err) t.Fatalf("expected to succeed: %s", err)
} }
if result.Name != containers[0] { if result.Name != containers[0] {
t.Errorf("Unexpected container %q in result. Expected container %q", result.Name, containers[0]) t.Errorf("Unexpected container %q in result. Expected container %q", result.Name, containers[0])
} }
result, err = m.DockerContainer("c2", query)
if err != nil {
t.Fatalf("expected to succeed: %s", err)
}
if result.Name != containers[1] {
t.Errorf("Unexpected container %q in result. Expected container %q", result.Name, containers[1])
}
result, err = m.DockerContainer("c", query)
expectedError := "unable to find container. Container \"c\" is not unique"
if err == nil {
t.Errorf("expected error %q but received %q", expectedError, err)
}
} }
func TestNewNilManager(t *testing.T) { func TestNewNilManager(t *testing.T) {