Commit aa307da5 authored by Janet Kuo's avatar Janet Kuo

Merge pull request #15124 from timstclair/container-id

Use strong type for container ID
parents 4b8f91fd 551eff63
...@@ -28,32 +28,31 @@ import ( ...@@ -28,32 +28,31 @@ import (
// for the caller. // for the caller.
type RefManager struct { type RefManager struct {
sync.RWMutex sync.RWMutex
// TODO(yifan): To use strong type. containerIDToRef map[ContainerID]*api.ObjectReference
containerIDToRef map[string]*api.ObjectReference
} }
// NewRefManager creates and returns a container reference manager // NewRefManager creates and returns a container reference manager
// with empty contents. // with empty contents.
func NewRefManager() *RefManager { func NewRefManager() *RefManager {
return &RefManager{containerIDToRef: make(map[string]*api.ObjectReference)} return &RefManager{containerIDToRef: make(map[ContainerID]*api.ObjectReference)}
} }
// SetRef stores a reference to a pod's container, associating it with the given container ID. // SetRef stores a reference to a pod's container, associating it with the given container ID.
func (c *RefManager) SetRef(id string, ref *api.ObjectReference) { func (c *RefManager) SetRef(id ContainerID, ref *api.ObjectReference) {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
c.containerIDToRef[id] = ref c.containerIDToRef[id] = ref
} }
// ClearRef forgets the given container id and its associated container reference. // ClearRef forgets the given container id and its associated container reference.
func (c *RefManager) ClearRef(id string) { func (c *RefManager) ClearRef(id ContainerID) {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
delete(c.containerIDToRef, id) delete(c.containerIDToRef, id)
} }
// GetRef returns the container reference of the given ID, or (nil, false) if none is stored. // GetRef returns the container reference of the given ID, or (nil, false) if none is stored.
func (c *RefManager) GetRef(id string) (ref *api.ObjectReference, ok bool) { func (c *RefManager) GetRef(id ContainerID) (ref *api.ObjectReference, ok bool) {
c.RLock() c.RLock()
defer c.RUnlock() defer c.RUnlock()
ref, ok = c.containerIDToRef[id] ref, ok = c.containerIDToRef[id]
......
...@@ -217,7 +217,7 @@ func (f *FakeRuntime) GetPodStatus(*api.Pod) (*api.PodStatus, error) { ...@@ -217,7 +217,7 @@ func (f *FakeRuntime) GetPodStatus(*api.Pod) (*api.PodStatus, error) {
return &status, f.Err return &status, f.Err
} }
func (f *FakeRuntime) ExecInContainer(containerID string, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { func (f *FakeRuntime) ExecInContainer(containerID ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
...@@ -225,7 +225,7 @@ func (f *FakeRuntime) ExecInContainer(containerID string, cmd []string, stdin io ...@@ -225,7 +225,7 @@ func (f *FakeRuntime) ExecInContainer(containerID string, cmd []string, stdin io
return f.Err return f.Err
} }
func (f *FakeRuntime) AttachContainer(containerID string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { func (f *FakeRuntime) AttachContainer(containerID ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
...@@ -233,7 +233,7 @@ func (f *FakeRuntime) AttachContainer(containerID string, stdin io.Reader, stdou ...@@ -233,7 +233,7 @@ func (f *FakeRuntime) AttachContainer(containerID string, stdin io.Reader, stdou
return f.Err return f.Err
} }
func (f *FakeRuntime) RunInContainer(containerID string, cmd []string) ([]byte, error) { func (f *FakeRuntime) RunInContainer(containerID ContainerID, cmd []string) ([]byte, error) {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
...@@ -241,7 +241,7 @@ func (f *FakeRuntime) RunInContainer(containerID string, cmd []string) ([]byte, ...@@ -241,7 +241,7 @@ func (f *FakeRuntime) RunInContainer(containerID string, cmd []string) ([]byte,
return []byte{}, f.Err return []byte{}, f.Err
} }
func (f *FakeRuntime) GetContainerLogs(pod *api.Pod, containerID string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) { func (f *FakeRuntime) GetContainerLogs(pod *api.Pod, containerID ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
......
...@@ -18,7 +18,6 @@ package container ...@@ -18,7 +18,6 @@ package container
import ( import (
"hash/adler32" "hash/adler32"
"strings"
"k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util"
...@@ -29,7 +28,7 @@ import ( ...@@ -29,7 +28,7 @@ import (
// HandlerRunner runs a lifecycle handler for a container. // HandlerRunner runs a lifecycle handler for a container.
type HandlerRunner interface { type HandlerRunner interface {
Run(containerID string, pod *api.Pod, container *api.Container, handler *api.Handler) error Run(containerID ContainerID, pod *api.Pod, container *api.Container, handler *api.Handler) error
} }
// RunContainerOptionsGenerator generates the options that necessary for // RunContainerOptionsGenerator generates the options that necessary for
...@@ -38,17 +37,6 @@ type RunContainerOptionsGenerator interface { ...@@ -38,17 +37,6 @@ type RunContainerOptionsGenerator interface {
GenerateRunContainerOptions(pod *api.Pod, container *api.Container) (*RunContainerOptions, error) GenerateRunContainerOptions(pod *api.Pod, container *api.Container) (*RunContainerOptions, error)
} }
// Trims runtime prefix from ID or image name (e.g.: docker://busybox -> busybox).
func TrimRuntimePrefix(fullString string) string {
const prefixSeparator = "://"
idx := strings.Index(fullString, prefixSeparator)
if idx < 0 {
return fullString
}
return fullString[idx+len(prefixSeparator):]
}
// ShouldContainerBeRestarted checks whether a container needs to be restarted. // ShouldContainerBeRestarted checks whether a container needs to be restarted.
// TODO(yifan): Think about how to refactor this. // TODO(yifan): Think about how to refactor this.
func ShouldContainerBeRestarted(container *api.Container, pod *api.Pod, podStatus *api.PodStatus) bool { func ShouldContainerBeRestarted(container *api.Container, pod *api.Pod, podStatus *api.PodStatus) bool {
......
...@@ -23,6 +23,7 @@ import ( ...@@ -23,6 +23,7 @@ import (
"reflect" "reflect"
"strings" "strings"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util"
...@@ -79,7 +80,7 @@ type Runtime interface { ...@@ -79,7 +80,7 @@ type Runtime interface {
// default, it returns a snapshot of the container log. Set 'follow' to true to // default, it returns a snapshot of the container log. Set 'follow' to true to
// stream the log. Set 'follow' to false and specify the number of lines (e.g. // stream the log. Set 'follow' to false and specify the number of lines (e.g.
// "100" or "all") to tail the log. // "100" or "all") to tail the log.
GetContainerLogs(pod *api.Pod, containerID string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) GetContainerLogs(pod *api.Pod, containerID ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error)
// ContainerCommandRunner encapsulates the command runner interfaces for testability. // ContainerCommandRunner encapsulates the command runner interfaces for testability.
ContainerCommandRunner ContainerCommandRunner
// ContainerAttach encapsulates the attaching to containers for testability // ContainerAttach encapsulates the attaching to containers for testability
...@@ -87,20 +88,18 @@ type Runtime interface { ...@@ -87,20 +88,18 @@ type Runtime interface {
} }
type ContainerAttacher interface { type ContainerAttacher interface {
AttachContainer(id string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) (err error) AttachContainer(id ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) (err error)
} }
// CommandRunner encapsulates the command runner interfaces for testability. // CommandRunner encapsulates the command runner interfaces for testability.
type ContainerCommandRunner interface { type ContainerCommandRunner interface {
// TODO(vmarmol): Merge RunInContainer and ExecInContainer. // TODO(vmarmol): Merge RunInContainer and ExecInContainer.
// Runs the command in the container of the specified pod using nsinit. // Runs the command in the container of the specified pod using nsinit.
// TODO(yifan): Use strong type for containerID. RunInContainer(containerID ContainerID, cmd []string) ([]byte, error)
RunInContainer(containerID string, cmd []string) ([]byte, error)
// Runs the command in the container of the specified pod using nsenter. // Runs the command in the container of the specified pod using nsenter.
// Attaches the processes stdin, stdout, and stderr. Optionally uses a // Attaches the processes stdin, stdout, and stderr. Optionally uses a
// tty. // tty.
// TODO(yifan): Use strong type for containerID. ExecInContainer(containerID ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error
ExecInContainer(containerID string, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error
// Forward the specified port from the specified pod to the stream. // Forward the specified port from the specified pod to the stream.
PortForward(pod *Pod, port uint16, stream io.ReadWriteCloser) error PortForward(pod *Pod, port uint16, stream io.ReadWriteCloser) error
} }
...@@ -139,6 +138,15 @@ func BuildContainerID(typ, ID string) ContainerID { ...@@ -139,6 +138,15 @@ func BuildContainerID(typ, ID string) ContainerID {
return ContainerID{Type: typ, ID: ID} return ContainerID{Type: typ, ID: ID}
} }
// Convenience method for creating a ContainerID from an ID string.
func ParseContainerID(containerID string) ContainerID {
var id ContainerID
if err := id.ParseString(containerID); err != nil {
glog.Error(err)
}
return id
}
func (c *ContainerID) ParseString(data string) error { func (c *ContainerID) ParseString(data string) error {
// Trim the quotes and split the type and ID. // Trim the quotes and split the type and ID.
parts := strings.Split(strings.Trim(data, "\""), "://") parts := strings.Split(strings.Trim(data, "\""), "://")
...@@ -153,6 +161,10 @@ func (c *ContainerID) String() string { ...@@ -153,6 +161,10 @@ func (c *ContainerID) String() string {
return fmt.Sprintf("%s://%s", c.Type, c.ID) return fmt.Sprintf("%s://%s", c.Type, c.ID)
} }
func (c *ContainerID) IsEmpty() bool {
return *c == ContainerID{}
}
func (c *ContainerID) MarshalJSON() ([]byte, error) { func (c *ContainerID) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", c.String())), nil return []byte(fmt.Sprintf("%q", c.String())), nil
} }
...@@ -166,7 +178,7 @@ func (c *ContainerID) UnmarshalJSON(data []byte) error { ...@@ -166,7 +178,7 @@ func (c *ContainerID) UnmarshalJSON(data []byte) error {
type Container struct { type Container struct {
// The ID of the container, used by the container runtime to identify // The ID of the container, used by the container runtime to identify
// a container. // a container.
ID types.UID ID ContainerID
// The name of the container, which should be the same as specified by // The name of the container, which should be the same as specified by
// api.Container. // api.Container.
Name string Name string
......
...@@ -21,7 +21,7 @@ import ( ...@@ -21,7 +21,7 @@ import (
docker "github.com/fsouza/go-dockerclient" docker "github.com/fsouza/go-dockerclient"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/types" kubeletTypes "k8s.io/kubernetes/pkg/kubelet/types"
) )
// This file contains helper functions to convert docker API types to runtime // This file contains helper functions to convert docker API types to runtime
...@@ -38,7 +38,7 @@ func toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, erro ...@@ -38,7 +38,7 @@ func toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, erro
return nil, err return nil, err
} }
return &kubecontainer.Container{ return &kubecontainer.Container{
ID: types.UID(c.ID), ID: kubeletTypes.DockerID(c.ID).ContainerID(),
Name: dockerName.ContainerName, Name: dockerName.ContainerName,
Image: c.Image, Image: c.Image,
Hash: hash, Hash: hash,
......
...@@ -22,7 +22,6 @@ import ( ...@@ -22,7 +22,6 @@ import (
docker "github.com/fsouza/go-dockerclient" docker "github.com/fsouza/go-dockerclient"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/types"
) )
func TestToRuntimeContainer(t *testing.T) { func TestToRuntimeContainer(t *testing.T) {
...@@ -33,7 +32,7 @@ func TestToRuntimeContainer(t *testing.T) { ...@@ -33,7 +32,7 @@ func TestToRuntimeContainer(t *testing.T) {
Names: []string{"/k8s_bar.5678_foo_ns_1234_42"}, Names: []string{"/k8s_bar.5678_foo_ns_1234_42"},
} }
expected := &kubecontainer.Container{ expected := &kubecontainer.Container{
ID: types.UID("ab2cdf"), ID: kubecontainer.ContainerID{"docker", "ab2cdf"},
Name: "bar", Name: "bar",
Image: "bar_image", Image: "bar_image",
Hash: 0x5678, Hash: 0x5678,
......
...@@ -34,6 +34,7 @@ import ( ...@@ -34,6 +34,7 @@ import (
"k8s.io/kubernetes/pkg/credentialprovider" "k8s.io/kubernetes/pkg/credentialprovider"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/kubelet/network" "k8s.io/kubernetes/pkg/kubelet/network"
kubeletTypes "k8s.io/kubernetes/pkg/kubelet/types"
"k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util"
) )
...@@ -171,10 +172,10 @@ func TestExecSupportNotExists(t *testing.T) { ...@@ -171,10 +172,10 @@ func TestExecSupportNotExists(t *testing.T) {
func TestDockerContainerCommand(t *testing.T) { func TestDockerContainerCommand(t *testing.T) {
runner := &DockerManager{} runner := &DockerManager{}
containerID := "1234" containerID := kubeletTypes.DockerID("1234").ContainerID()
command := []string{"ls"} command := []string{"ls"}
cmd, _ := runner.getRunInContainerCommand(containerID, command) cmd, _ := runner.getRunInContainerCommand(containerID, command)
if cmd.Dir != "/var/lib/docker/execdriver/native/"+containerID { if cmd.Dir != "/var/lib/docker/execdriver/native/"+containerID.ID {
t.Errorf("unexpected command CWD: %s", cmd.Dir) t.Errorf("unexpected command CWD: %s", cmd.Dir)
} }
if !reflect.DeepEqual(cmd.Args, []string{"/usr/sbin/nsinit", "exec", "ls"}) { if !reflect.DeepEqual(cmd.Args, []string{"/usr/sbin/nsinit", "exec", "ls"}) {
...@@ -517,7 +518,7 @@ type containersByID []*kubecontainer.Container ...@@ -517,7 +518,7 @@ type containersByID []*kubecontainer.Container
func (b containersByID) Len() int { return len(b) } func (b containersByID) Len() int { return len(b) }
func (b containersByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b containersByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b containersByID) Less(i, j int) bool { return b[i].ID < b[j].ID } func (b containersByID) Less(i, j int) bool { return b[i].ID.ID < b[j].ID.ID }
func TestFindContainersByPod(t *testing.T) { func TestFindContainersByPod(t *testing.T) {
tests := []struct { tests := []struct {
...@@ -560,12 +561,12 @@ func TestFindContainersByPod(t *testing.T) { ...@@ -560,12 +561,12 @@ func TestFindContainersByPod(t *testing.T) {
Namespace: "ns", Namespace: "ns",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
ID: "foobar", ID: kubeletTypes.DockerID("foobar").ContainerID(),
Name: "foobar", Name: "foobar",
Hash: 0x1234, Hash: 0x1234,
}, },
{ {
ID: "baz", ID: kubeletTypes.DockerID("baz").ContainerID(),
Name: "baz", Name: "baz",
Hash: 0x1234, Hash: 0x1234,
}, },
...@@ -577,7 +578,7 @@ func TestFindContainersByPod(t *testing.T) { ...@@ -577,7 +578,7 @@ func TestFindContainersByPod(t *testing.T) {
Namespace: "ns", Namespace: "ns",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
ID: "barbar", ID: kubeletTypes.DockerID("barbar").ContainerID(),
Name: "barbar", Name: "barbar",
Hash: 0x1234, Hash: 0x1234,
}, },
...@@ -618,17 +619,17 @@ func TestFindContainersByPod(t *testing.T) { ...@@ -618,17 +619,17 @@ func TestFindContainersByPod(t *testing.T) {
Namespace: "ns", Namespace: "ns",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
ID: "foobar", ID: kubeletTypes.DockerID("foobar").ContainerID(),
Name: "foobar", Name: "foobar",
Hash: 0x1234, Hash: 0x1234,
}, },
{ {
ID: "barfoo", ID: kubeletTypes.DockerID("barfoo").ContainerID(),
Name: "barfoo", Name: "barfoo",
Hash: 0x1234, Hash: 0x1234,
}, },
{ {
ID: "baz", ID: kubeletTypes.DockerID("baz").ContainerID(),
Name: "baz", Name: "baz",
Hash: 0x1234, Hash: 0x1234,
}, },
...@@ -640,7 +641,7 @@ func TestFindContainersByPod(t *testing.T) { ...@@ -640,7 +641,7 @@ func TestFindContainersByPod(t *testing.T) {
Namespace: "ns", Namespace: "ns",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
ID: "barbar", ID: kubeletTypes.DockerID("barbar").ContainerID(),
Name: "barbar", Name: "barbar",
Hash: 0x1234, Hash: 0x1234,
}, },
...@@ -652,7 +653,7 @@ func TestFindContainersByPod(t *testing.T) { ...@@ -652,7 +653,7 @@ func TestFindContainersByPod(t *testing.T) {
Namespace: "ns", Namespace: "ns",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
ID: "bazbaz", ID: kubeletTypes.DockerID("bazbaz").ContainerID(),
Name: "bazbaz", Name: "bazbaz",
Hash: 0x1234, Hash: 0x1234,
}, },
......
...@@ -346,7 +346,7 @@ func apiContainerToContainer(c docker.APIContainers) kubecontainer.Container { ...@@ -346,7 +346,7 @@ func apiContainerToContainer(c docker.APIContainers) kubecontainer.Container {
return kubecontainer.Container{} return kubecontainer.Container{}
} }
return kubecontainer.Container{ return kubecontainer.Container{
ID: types.UID(c.ID), ID: kubecontainer.ContainerID{"docker", c.ID},
Name: dockerName.ContainerName, Name: dockerName.ContainerName,
Hash: hash, Hash: hash,
} }
...@@ -360,7 +360,7 @@ func dockerContainersToPod(containers DockerContainers) kubecontainer.Pod { ...@@ -360,7 +360,7 @@ func dockerContainersToPod(containers DockerContainers) kubecontainer.Pod {
continue continue
} }
pod.Containers = append(pod.Containers, &kubecontainer.Container{ pod.Containers = append(pod.Containers, &kubecontainer.Container{
ID: types.UID(c.ID), ID: kubecontainer.ContainerID{"docker", c.ID},
Name: dockerName.ContainerName, Name: dockerName.ContainerName,
Hash: hash, Hash: hash,
Image: c.Image, Image: c.Image,
...@@ -399,7 +399,7 @@ func TestKillContainerInPod(t *testing.T) { ...@@ -399,7 +399,7 @@ func TestKillContainerInPod(t *testing.T) {
containerToSpare := &containers[1] containerToSpare := &containers[1]
fakeDocker.ContainerList = containers fakeDocker.ContainerList = containers
if err := manager.KillContainerInPod("", &pod.Spec.Containers[0], pod); err != nil { if err := manager.KillContainerInPod(kubecontainer.ContainerID{}, &pod.Spec.Containers[0], pod); err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }
// Assert the container has been stopped. // Assert the container has been stopped.
...@@ -464,7 +464,7 @@ func TestKillContainerInPodWithPreStop(t *testing.T) { ...@@ -464,7 +464,7 @@ func TestKillContainerInPodWithPreStop(t *testing.T) {
}, },
} }
if err := manager.KillContainerInPod("", &pod.Spec.Containers[0], pod); err != nil { if err := manager.KillContainerInPod(kubecontainer.ContainerID{}, &pod.Spec.Containers[0], pod); err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }
// Assert the container has been stopped. // Assert the container has been stopped.
...@@ -501,7 +501,7 @@ func TestKillContainerInPodWithError(t *testing.T) { ...@@ -501,7 +501,7 @@ func TestKillContainerInPodWithError(t *testing.T) {
fakeDocker.ContainerList = containers fakeDocker.ContainerList = containers
fakeDocker.Errors["stop"] = fmt.Errorf("sample error") fakeDocker.Errors["stop"] = fmt.Errorf("sample error")
if err := manager.KillContainerInPod("", &pod.Spec.Containers[0], pod); err == nil { if err := manager.KillContainerInPod(kubecontainer.ContainerID{}, &pod.Spec.Containers[0], pod); err == nil {
t.Errorf("expected error, found nil") t.Errorf("expected error, found nil")
} }
} }
......
...@@ -27,7 +27,6 @@ import ( ...@@ -27,7 +27,6 @@ import (
"k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/record"
"k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/kubelet/cadvisor"
"k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/types"
) )
var zero time.Time var zero time.Time
...@@ -74,7 +73,7 @@ func makeImage(id int, size int64) container.Image { ...@@ -74,7 +73,7 @@ func makeImage(id int, size int64) container.Image {
// Make a container with the specified ID. It will use the image with the same ID. // Make a container with the specified ID. It will use the image with the same ID.
func makeContainer(id int) *container.Container { func makeContainer(id int) *container.Container {
return &container.Container{ return &container.Container{
ID: types.UID(fmt.Sprintf("container-%d", id)), ID: container.ContainerID{"test", fmt.Sprintf("container-%d", id)},
Image: imageName(id), Image: imageName(id),
} }
} }
...@@ -322,7 +321,7 @@ func TestFreeSpaceImagesAlsoDoesLookupByRepoTags(t *testing.T) { ...@@ -322,7 +321,7 @@ func TestFreeSpaceImagesAlsoDoesLookupByRepoTags(t *testing.T) {
{ {
Containers: []*container.Container{ Containers: []*container.Container{
{ {
ID: "c5678", ID: container.ContainerID{"test", "c5678"},
Image: "salad", Image: "salad",
}, },
}, },
......
...@@ -2073,25 +2073,25 @@ func (kl *Kubelet) validatePodPhase(podStatus *api.PodStatus) error { ...@@ -2073,25 +2073,25 @@ func (kl *Kubelet) validatePodPhase(podStatus *api.PodStatus) error {
return fmt.Errorf("pod is not in 'Running', 'Succeeded' or 'Failed' state - State: %q", podStatus.Phase) return fmt.Errorf("pod is not in 'Running', 'Succeeded' or 'Failed' state - State: %q", podStatus.Phase)
} }
func (kl *Kubelet) validateContainerStatus(podStatus *api.PodStatus, containerName string, previous bool) (containerID string, err error) { func (kl *Kubelet) validateContainerStatus(podStatus *api.PodStatus, containerName string, previous bool) (containerID kubecontainer.ContainerID, err error) {
var cID string var cID string
cStatus, found := api.GetContainerStatus(podStatus.ContainerStatuses, containerName) cStatus, found := api.GetContainerStatus(podStatus.ContainerStatuses, containerName)
if !found { if !found {
return "", fmt.Errorf("container %q not found", containerName) return kubecontainer.ContainerID{}, fmt.Errorf("container %q not found", containerName)
} }
if previous { if previous {
if cStatus.LastTerminationState.Terminated == nil { if cStatus.LastTerminationState.Terminated == nil {
return "", fmt.Errorf("previous terminated container %q not found", containerName) return kubecontainer.ContainerID{}, fmt.Errorf("previous terminated container %q not found", containerName)
} }
cID = cStatus.LastTerminationState.Terminated.ContainerID cID = cStatus.LastTerminationState.Terminated.ContainerID
} else { } else {
if cStatus.State.Waiting != nil { if cStatus.State.Waiting != nil {
return "", fmt.Errorf("container %q is in waiting state.", containerName) return kubecontainer.ContainerID{}, fmt.Errorf("container %q is in waiting state.", containerName)
} }
cID = cStatus.ContainerID cID = cStatus.ContainerID
} }
return kubecontainer.TrimRuntimePrefix(cID), nil return kubecontainer.ParseContainerID(cID), nil
} }
// GetKubeletContainerLogs returns logs from the container // GetKubeletContainerLogs returns logs from the container
...@@ -2673,7 +2673,7 @@ func (kl *Kubelet) RunInContainer(podFullName string, podUID types.UID, containe ...@@ -2673,7 +2673,7 @@ func (kl *Kubelet) RunInContainer(podFullName string, podUID types.UID, containe
if container == nil { if container == nil {
return nil, fmt.Errorf("container not found (%q)", containerName) return nil, fmt.Errorf("container not found (%q)", containerName)
} }
return kl.runner.RunInContainer(string(container.ID), cmd) return kl.runner.RunInContainer(container.ID, cmd)
} }
// ExecInContainer executes a command in a container, connecting the supplied // ExecInContainer executes a command in a container, connecting the supplied
...@@ -2688,7 +2688,7 @@ func (kl *Kubelet) ExecInContainer(podFullName string, podUID types.UID, contain ...@@ -2688,7 +2688,7 @@ func (kl *Kubelet) ExecInContainer(podFullName string, podUID types.UID, contain
if container == nil { if container == nil {
return fmt.Errorf("container not found (%q)", containerName) return fmt.Errorf("container not found (%q)", containerName)
} }
return kl.runner.ExecInContainer(string(container.ID), cmd, stdin, stdout, stderr, tty) return kl.runner.ExecInContainer(container.ID, cmd, stdin, stdout, stderr, tty)
} }
func (kl *Kubelet) AttachContainer(podFullName string, podUID types.UID, containerName string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { func (kl *Kubelet) AttachContainer(podFullName string, podUID types.UID, containerName string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error {
...@@ -2701,7 +2701,7 @@ func (kl *Kubelet) AttachContainer(podFullName string, podUID types.UID, contain ...@@ -2701,7 +2701,7 @@ func (kl *Kubelet) AttachContainer(podFullName string, podUID types.UID, contain
if container == nil { if container == nil {
return fmt.Errorf("container not found (%q)", containerName) return fmt.Errorf("container not found (%q)", containerName)
} }
return kl.containerRuntime.AttachContainer(string(container.ID), stdin, stdout, stderr, tty) return kl.containerRuntime.AttachContainer(container.ID, stdin, stdout, stderr, tty)
} }
// PortForward connects to the pod's port and copies data between the port // PortForward connects to the pod's port and copies data between the port
...@@ -2749,7 +2749,7 @@ func (kl *Kubelet) GetContainerInfo(podFullName string, podUID types.UID, contai ...@@ -2749,7 +2749,7 @@ func (kl *Kubelet) GetContainerInfo(podFullName string, podUID types.UID, contai
return nil, ErrContainerNotFound return nil, ErrContainerNotFound
} }
ci, err := kl.cadvisor.DockerContainer(string(container.ID), req) ci, err := kl.cadvisor.DockerContainer(container.ID.ID, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -2800,10 +2800,10 @@ func (kl *Kubelet) GetRuntime() kubecontainer.Runtime { ...@@ -2800,10 +2800,10 @@ func (kl *Kubelet) GetRuntime() kubecontainer.Runtime {
// Proxy prober calls through the Kubelet to break the circular dependency between the runtime & // Proxy prober calls through the Kubelet to break the circular dependency between the runtime &
// prober. // prober.
// TODO: Remove this hack once the runtime no longer depends on the prober. // TODO: Remove this hack once the runtime no longer depends on the prober.
func (kl *Kubelet) ProbeLiveness(pod *api.Pod, status api.PodStatus, container api.Container, containerID string, createdAt int64) (probe.Result, error) { func (kl *Kubelet) ProbeLiveness(pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID, createdAt int64) (probe.Result, error) {
return kl.prober.ProbeLiveness(pod, status, container, containerID, createdAt) return kl.prober.ProbeLiveness(pod, status, container, containerID, createdAt)
} }
func (kl *Kubelet) ProbeReadiness(pod *api.Pod, status api.PodStatus, container api.Container, containerID string) (probe.Result, error) { func (kl *Kubelet) ProbeReadiness(pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID) (probe.Result, error) {
return kl.prober.ProbeReadiness(pod, status, container, containerID) return kl.prober.ProbeReadiness(pod, status, container, containerID)
} }
......
...@@ -586,7 +586,7 @@ func TestGetContainerInfo(t *testing.T) { ...@@ -586,7 +586,7 @@ func TestGetContainerInfo(t *testing.T) {
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
Name: "foo", Name: "foo",
ID: types.UID(containerID), ID: kubecontainer.ContainerID{"test", containerID},
}, },
}, },
}, },
...@@ -668,7 +668,7 @@ func TestGetContainerInfoWhenCadvisorFailed(t *testing.T) { ...@@ -668,7 +668,7 @@ func TestGetContainerInfoWhenCadvisorFailed(t *testing.T) {
Namespace: "ns", Namespace: "ns",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{Name: "foo", {Name: "foo",
ID: types.UID(containerID), ID: kubecontainer.ContainerID{"test", containerID},
}, },
}, },
}, },
...@@ -752,7 +752,7 @@ func TestGetContainerInfoWithNoMatchingContainers(t *testing.T) { ...@@ -752,7 +752,7 @@ func TestGetContainerInfoWithNoMatchingContainers(t *testing.T) {
Namespace: "ns", Namespace: "ns",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{Name: "bar", {Name: "bar",
ID: types.UID("fakeID"), ID: kubecontainer.ContainerID{"test", "fakeID"},
}, },
}}, }},
} }
...@@ -772,7 +772,7 @@ func TestGetContainerInfoWithNoMatchingContainers(t *testing.T) { ...@@ -772,7 +772,7 @@ func TestGetContainerInfoWithNoMatchingContainers(t *testing.T) {
type fakeContainerCommandRunner struct { type fakeContainerCommandRunner struct {
Cmd []string Cmd []string
ID string ID kubecontainer.ContainerID
PodID types.UID PodID types.UID
E error E error
Stdin io.Reader Stdin io.Reader
...@@ -783,13 +783,13 @@ type fakeContainerCommandRunner struct { ...@@ -783,13 +783,13 @@ type fakeContainerCommandRunner struct {
Stream io.ReadWriteCloser Stream io.ReadWriteCloser
} }
func (f *fakeContainerCommandRunner) RunInContainer(id string, cmd []string) ([]byte, error) { func (f *fakeContainerCommandRunner) RunInContainer(id kubecontainer.ContainerID, cmd []string) ([]byte, error) {
f.Cmd = cmd f.Cmd = cmd
f.ID = id f.ID = id
return []byte{}, f.E return []byte{}, f.E
} }
func (f *fakeContainerCommandRunner) ExecInContainer(id string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error { func (f *fakeContainerCommandRunner) ExecInContainer(id kubecontainer.ContainerID, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error {
f.Cmd = cmd f.Cmd = cmd
f.ID = id f.ID = id
f.Stdin = in f.Stdin = in
...@@ -835,7 +835,7 @@ func TestRunInContainer(t *testing.T) { ...@@ -835,7 +835,7 @@ func TestRunInContainer(t *testing.T) {
fakeCommandRunner := fakeContainerCommandRunner{} fakeCommandRunner := fakeContainerCommandRunner{}
kubelet.runner = &fakeCommandRunner kubelet.runner = &fakeCommandRunner
containerID := "abc1234" containerID := kubecontainer.ContainerID{"test", "abc1234"}
fakeRuntime.PodList = []*kubecontainer.Pod{ fakeRuntime.PodList = []*kubecontainer.Pod{
{ {
ID: "12345678", ID: "12345678",
...@@ -843,7 +843,7 @@ func TestRunInContainer(t *testing.T) { ...@@ -843,7 +843,7 @@ func TestRunInContainer(t *testing.T) {
Namespace: "nsFoo", Namespace: "nsFoo",
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{Name: "containerFoo", {Name: "containerFoo",
ID: types.UID(containerID), ID: containerID,
}, },
}, },
}, },
...@@ -1865,7 +1865,7 @@ func TestExecInContainerNoSuchPod(t *testing.T) { ...@@ -1865,7 +1865,7 @@ func TestExecInContainerNoSuchPod(t *testing.T) {
if err == nil { if err == nil {
t.Fatal("unexpected non-error") t.Fatal("unexpected non-error")
} }
if fakeCommandRunner.ID != "" { if !fakeCommandRunner.ID.IsEmpty() {
t.Fatal("unexpected invocation of runner.ExecInContainer") t.Fatal("unexpected invocation of runner.ExecInContainer")
} }
} }
...@@ -1887,7 +1887,7 @@ func TestExecInContainerNoSuchContainer(t *testing.T) { ...@@ -1887,7 +1887,7 @@ func TestExecInContainerNoSuchContainer(t *testing.T) {
Namespace: podNamespace, Namespace: podNamespace,
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{Name: "bar", {Name: "bar",
ID: "barID"}, ID: kubecontainer.ContainerID{"test", "barID"}},
}, },
}, },
} }
...@@ -1909,7 +1909,7 @@ func TestExecInContainerNoSuchContainer(t *testing.T) { ...@@ -1909,7 +1909,7 @@ func TestExecInContainerNoSuchContainer(t *testing.T) {
if err == nil { if err == nil {
t.Fatal("unexpected non-error") t.Fatal("unexpected non-error")
} }
if fakeCommandRunner.ID != "" { if !fakeCommandRunner.ID.IsEmpty() {
t.Fatal("unexpected invocation of runner.ExecInContainer") t.Fatal("unexpected invocation of runner.ExecInContainer")
} }
} }
...@@ -1950,7 +1950,7 @@ func TestExecInContainer(t *testing.T) { ...@@ -1950,7 +1950,7 @@ func TestExecInContainer(t *testing.T) {
Namespace: podNamespace, Namespace: podNamespace,
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{Name: containerID, {Name: containerID,
ID: types.UID(containerID), ID: kubecontainer.ContainerID{"test", containerID},
}, },
}, },
}, },
...@@ -1973,7 +1973,7 @@ func TestExecInContainer(t *testing.T) { ...@@ -1973,7 +1973,7 @@ func TestExecInContainer(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("unexpected error: %s", err) t.Fatalf("unexpected error: %s", err)
} }
if e, a := containerID, fakeCommandRunner.ID; e != a { if e, a := containerID, fakeCommandRunner.ID.ID; e != a {
t.Fatalf("container name: expected %q, got %q", e, a) t.Fatalf("container name: expected %q, got %q", e, a)
} }
if e, a := command, fakeCommandRunner.Cmd; !reflect.DeepEqual(e, a) { if e, a := command, fakeCommandRunner.Cmd; !reflect.DeepEqual(e, a) {
...@@ -2014,7 +2014,7 @@ func TestPortForwardNoSuchPod(t *testing.T) { ...@@ -2014,7 +2014,7 @@ func TestPortForwardNoSuchPod(t *testing.T) {
if err == nil { if err == nil {
t.Fatal("unexpected non-error") t.Fatal("unexpected non-error")
} }
if fakeCommandRunner.ID != "" { if !fakeCommandRunner.ID.IsEmpty() {
t.Fatal("unexpected invocation of runner.PortForward") t.Fatal("unexpected invocation of runner.PortForward")
} }
} }
...@@ -2035,7 +2035,7 @@ func TestPortForward(t *testing.T) { ...@@ -2035,7 +2035,7 @@ func TestPortForward(t *testing.T) {
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
Name: "foo", Name: "foo",
ID: "containerFoo", ID: kubecontainer.ContainerID{"test", "containerFoo"},
}, },
}, },
}, },
...@@ -2847,7 +2847,7 @@ func TestGetContainerInfoForMirrorPods(t *testing.T) { ...@@ -2847,7 +2847,7 @@ func TestGetContainerInfoForMirrorPods(t *testing.T) {
Containers: []*kubecontainer.Container{ Containers: []*kubecontainer.Container{
{ {
Name: "foo", Name: "foo",
ID: types.UID(containerID), ID: kubecontainer.ContainerID{"test", containerID},
}, },
}, },
}, },
......
...@@ -46,8 +46,7 @@ func NewHandlerRunner(httpGetter kubeletTypes.HttpGetter, commandRunner kubecont ...@@ -46,8 +46,7 @@ func NewHandlerRunner(httpGetter kubeletTypes.HttpGetter, commandRunner kubecont
} }
} }
// TODO(yifan): Use a strong type for containerID. func (hr *HandlerRunner) Run(containerID kubecontainer.ContainerID, pod *api.Pod, container *api.Container, handler *api.Handler) error {
func (hr *HandlerRunner) Run(containerID string, pod *api.Pod, container *api.Container, handler *api.Handler) error {
switch { switch {
case handler.Exec != nil: case handler.Exec != nil:
_, err := hr.commandRunner.RunInContainer(containerID, handler.Exec.Command) _, err := hr.commandRunner.RunInContainer(containerID, handler.Exec.Command)
......
...@@ -74,16 +74,16 @@ func TestResolvePortStringUnknown(t *testing.T) { ...@@ -74,16 +74,16 @@ func TestResolvePortStringUnknown(t *testing.T) {
type fakeContainerCommandRunner struct { type fakeContainerCommandRunner struct {
Cmd []string Cmd []string
ID string ID kubecontainer.ContainerID
} }
func (f *fakeContainerCommandRunner) RunInContainer(id string, cmd []string) ([]byte, error) { func (f *fakeContainerCommandRunner) RunInContainer(id kubecontainer.ContainerID, cmd []string) ([]byte, error) {
f.Cmd = cmd f.Cmd = cmd
f.ID = id f.ID = id
return []byte{}, nil return []byte{}, nil
} }
func (f *fakeContainerCommandRunner) ExecInContainer(id string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error { func (f *fakeContainerCommandRunner) ExecInContainer(id kubecontainer.ContainerID, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error {
return nil return nil
} }
...@@ -95,7 +95,7 @@ func TestRunHandlerExec(t *testing.T) { ...@@ -95,7 +95,7 @@ func TestRunHandlerExec(t *testing.T) {
fakeCommandRunner := fakeContainerCommandRunner{} fakeCommandRunner := fakeContainerCommandRunner{}
handlerRunner := NewHandlerRunner(&fakeHTTP{}, &fakeCommandRunner, nil) handlerRunner := NewHandlerRunner(&fakeHTTP{}, &fakeCommandRunner, nil)
containerID := "abc1234" containerID := kubecontainer.ContainerID{"test", "abc1234"}
containerName := "containerFoo" containerName := "containerFoo"
container := api.Container{ container := api.Container{
...@@ -137,7 +137,7 @@ func TestRunHandlerHttp(t *testing.T) { ...@@ -137,7 +137,7 @@ func TestRunHandlerHttp(t *testing.T) {
fakeHttp := fakeHTTP{} fakeHttp := fakeHTTP{}
handlerRunner := NewHandlerRunner(&fakeHttp, &fakeContainerCommandRunner{}, nil) handlerRunner := NewHandlerRunner(&fakeHttp, &fakeContainerCommandRunner{}, nil)
containerID := "abc1234" containerID := kubecontainer.ContainerID{"test", "abc1234"}
containerName := "containerFoo" containerName := "containerFoo"
container := api.Container{ container := api.Container{
...@@ -168,7 +168,7 @@ func TestRunHandlerHttp(t *testing.T) { ...@@ -168,7 +168,7 @@ func TestRunHandlerHttp(t *testing.T) {
func TestRunHandlerNil(t *testing.T) { func TestRunHandlerNil(t *testing.T) {
handlerRunner := NewHandlerRunner(&fakeHTTP{}, &fakeContainerCommandRunner{}, nil) handlerRunner := NewHandlerRunner(&fakeHTTP{}, &fakeContainerCommandRunner{}, nil)
containerID := "abc1234" containerID := kubecontainer.ContainerID{"test", "abc1234"}
podName := "podFoo" podName := "podFoo"
podNamespace := "nsFoo" podNamespace := "nsFoo"
containerName := "containerFoo" containerName := "containerFoo"
......
...@@ -18,15 +18,17 @@ package cni ...@@ -18,15 +18,17 @@ package cni
import ( import (
"fmt" "fmt"
"net"
"sort"
"strings"
"github.com/appc/cni/libcni" "github.com/appc/cni/libcni"
cniTypes "github.com/appc/cni/pkg/types" cniTypes "github.com/appc/cni/pkg/types"
"github.com/golang/glog" "github.com/golang/glog"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/kubelet/dockertools" "k8s.io/kubernetes/pkg/kubelet/dockertools"
"k8s.io/kubernetes/pkg/kubelet/network" "k8s.io/kubernetes/pkg/kubelet/network"
kubeletTypes "k8s.io/kubernetes/pkg/kubelet/types" kubeletTypes "k8s.io/kubernetes/pkg/kubelet/types"
"net"
"sort"
"strings"
) )
const ( const (
...@@ -105,12 +107,12 @@ func (plugin *cniNetworkPlugin) SetUpPod(namespace string, name string, id kubel ...@@ -105,12 +107,12 @@ func (plugin *cniNetworkPlugin) SetUpPod(namespace string, name string, id kubel
if !ok { if !ok {
return fmt.Errorf("CNI execution called on non-docker runtime") return fmt.Errorf("CNI execution called on non-docker runtime")
} }
netns, err := runtime.GetNetNs(string(id)) netns, err := runtime.GetNetNs(id.ContainerID())
if err != nil { if err != nil {
return err return err
} }
_, err = plugin.defaultNetwork.addToNetwork(name, namespace, string(id), netns) _, err = plugin.defaultNetwork.addToNetwork(name, namespace, id.ContainerID(), netns)
if err != nil { if err != nil {
glog.Errorf("Error while adding to cni network: %s", err) glog.Errorf("Error while adding to cni network: %s", err)
return err return err
...@@ -124,12 +126,12 @@ func (plugin *cniNetworkPlugin) TearDownPod(namespace string, name string, id ku ...@@ -124,12 +126,12 @@ func (plugin *cniNetworkPlugin) TearDownPod(namespace string, name string, id ku
if !ok { if !ok {
return fmt.Errorf("CNI execution called on non-docker runtime") return fmt.Errorf("CNI execution called on non-docker runtime")
} }
netns, err := runtime.GetNetNs(string(id)) netns, err := runtime.GetNetNs(id.ContainerID())
if err != nil { if err != nil {
return err return err
} }
return plugin.defaultNetwork.deleteFromNetwork(name, namespace, string(id), netns) return plugin.defaultNetwork.deleteFromNetwork(name, namespace, id.ContainerID(), netns)
} }
// TODO: Use the addToNetwork function to obtain the IP of the Pod. That will assume idempotent ADD call to the plugin. // TODO: Use the addToNetwork function to obtain the IP of the Pod. That will assume idempotent ADD call to the plugin.
...@@ -150,7 +152,7 @@ func (plugin *cniNetworkPlugin) Status(namespace string, name string, id kubelet ...@@ -150,7 +152,7 @@ func (plugin *cniNetworkPlugin) Status(namespace string, name string, id kubelet
return &network.PodNetworkStatus{IP: ip}, nil return &network.PodNetworkStatus{IP: ip}, nil
} }
func (network *cniNetwork) addToNetwork(podName string, podNamespace string, podInfraContainerID string, podNetnsPath string) (*cniTypes.Result, error) { func (network *cniNetwork) addToNetwork(podName string, podNamespace string, podInfraContainerID kubecontainer.ContainerID, podNetnsPath string) (*cniTypes.Result, error) {
rt, err := buildCNIRuntimeConf(podName, podNamespace, podInfraContainerID, podNetnsPath) rt, err := buildCNIRuntimeConf(podName, podNamespace, podInfraContainerID, podNetnsPath)
if err != nil { if err != nil {
glog.Errorf("Error adding network: %v", err) glog.Errorf("Error adding network: %v", err)
...@@ -168,7 +170,7 @@ func (network *cniNetwork) addToNetwork(podName string, podNamespace string, pod ...@@ -168,7 +170,7 @@ func (network *cniNetwork) addToNetwork(podName string, podNamespace string, pod
return res, nil return res, nil
} }
func (network *cniNetwork) deleteFromNetwork(podName string, podNamespace string, podInfraContainerID string, podNetnsPath string) error { func (network *cniNetwork) deleteFromNetwork(podName string, podNamespace string, podInfraContainerID kubecontainer.ContainerID, podNetnsPath string) error {
rt, err := buildCNIRuntimeConf(podName, podNamespace, podInfraContainerID, podNetnsPath) rt, err := buildCNIRuntimeConf(podName, podNamespace, podInfraContainerID, podNetnsPath)
if err != nil { if err != nil {
glog.Errorf("Error deleting network: %v", err) glog.Errorf("Error deleting network: %v", err)
...@@ -185,18 +187,18 @@ func (network *cniNetwork) deleteFromNetwork(podName string, podNamespace string ...@@ -185,18 +187,18 @@ func (network *cniNetwork) deleteFromNetwork(podName string, podNamespace string
return nil return nil
} }
func buildCNIRuntimeConf(podName string, podNs string, podInfraContainerID string, podNetnsPath string) (*libcni.RuntimeConf, error) { func buildCNIRuntimeConf(podName string, podNs string, podInfraContainerID kubecontainer.ContainerID, podNetnsPath string) (*libcni.RuntimeConf, error) {
glog.V(4).Infof("Got netns path %v", podNetnsPath) glog.V(4).Infof("Got netns path %v", podNetnsPath)
glog.V(4).Infof("Using netns path %v", podNs) glog.V(4).Infof("Using netns path %v", podNs)
rt := &libcni.RuntimeConf{ rt := &libcni.RuntimeConf{
ContainerID: podInfraContainerID, ContainerID: podInfraContainerID.ID,
NetNS: podNetnsPath, NetNS: podNetnsPath,
IfName: DefaultInterfaceName, IfName: DefaultInterfaceName,
Args: [][2]string{ Args: [][2]string{
{"K8S_POD_NAMESPACE", podNs}, {"K8S_POD_NAMESPACE", podNs},
{"K8S_POD_NAME", podName}, {"K8S_POD_NAME", podName},
{"K8S_POD_INFRA_CONTAINER_ID", podInfraContainerID}, {"K8S_POD_INFRA_CONTAINER_ID", podInfraContainerID.ID},
}, },
} }
......
...@@ -18,6 +18,7 @@ package prober ...@@ -18,6 +18,7 @@ package prober
import ( import (
"k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/probe" "k8s.io/kubernetes/pkg/probe"
) )
...@@ -29,14 +30,14 @@ type FakeProber struct { ...@@ -29,14 +30,14 @@ type FakeProber struct {
Error error Error error
} }
func (f FakeProber) ProbeLiveness(_ *api.Pod, _ api.PodStatus, c api.Container, _ string, _ int64) (probe.Result, error) { func (f FakeProber) ProbeLiveness(_ *api.Pod, _ api.PodStatus, c api.Container, _ kubecontainer.ContainerID, _ int64) (probe.Result, error) {
if c.LivenessProbe == nil { if c.LivenessProbe == nil {
return probe.Success, nil return probe.Success, nil
} }
return f.Liveness, f.Error return f.Liveness, f.Error
} }
func (f FakeProber) ProbeReadiness(_ *api.Pod, _ api.PodStatus, c api.Container, _ string) (probe.Result, error) { func (f FakeProber) ProbeReadiness(_ *api.Pod, _ api.PodStatus, c api.Container, _ kubecontainer.ContainerID) (probe.Result, error) {
if c.ReadinessProbe == nil { if c.ReadinessProbe == nil {
return probe.Success, nil return probe.Success, nil
} }
......
...@@ -141,7 +141,8 @@ func (m *manager) UpdatePodStatus(podUID types.UID, podStatus *api.PodStatus) { ...@@ -141,7 +141,8 @@ func (m *manager) UpdatePodStatus(podUID types.UID, podStatus *api.PodStatus) {
var ready bool var ready bool
if c.State.Running == nil { if c.State.Running == nil {
ready = false ready = false
} else if result, ok := m.readinessCache.getReadiness(kubecontainer.TrimRuntimePrefix(c.ContainerID)); ok { } else if result, ok := m.readinessCache.getReadiness(
kubecontainer.ParseContainerID(c.ContainerID)); ok {
ready = result ready = result
} else { } else {
// The check whether there is a probe which hasn't run yet. // The check whether there is a probe which hasn't run yet.
......
...@@ -24,6 +24,7 @@ import ( ...@@ -24,6 +24,7 @@ import (
"github.com/golang/glog" "github.com/golang/glog"
"k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/unversioned/testclient" "k8s.io/kubernetes/pkg/client/unversioned/testclient"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/kubelet/status" "k8s.io/kubernetes/pkg/kubelet/status"
"k8s.io/kubernetes/pkg/probe" "k8s.io/kubernetes/pkg/probe"
"k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/util/wait"
...@@ -151,35 +152,35 @@ func TestUpdatePodStatus(t *testing.T) { ...@@ -151,35 +152,35 @@ func TestUpdatePodStatus(t *testing.T) {
const podUID = "pod_uid" const podUID = "pod_uid"
unprobed := api.ContainerStatus{ unprobed := api.ContainerStatus{
Name: "unprobed_container", Name: "unprobed_container",
ContainerID: "unprobed_container_id", ContainerID: "test://unprobed_container_id",
State: api.ContainerState{ State: api.ContainerState{
Running: &api.ContainerStateRunning{}, Running: &api.ContainerStateRunning{},
}, },
} }
probedReady := api.ContainerStatus{ probedReady := api.ContainerStatus{
Name: "probed_container_ready", Name: "probed_container_ready",
ContainerID: "probed_container_ready_id", ContainerID: "test://probed_container_ready_id",
State: api.ContainerState{ State: api.ContainerState{
Running: &api.ContainerStateRunning{}, Running: &api.ContainerStateRunning{},
}, },
} }
probedPending := api.ContainerStatus{ probedPending := api.ContainerStatus{
Name: "probed_container_pending", Name: "probed_container_pending",
ContainerID: "probed_container_pending_id", ContainerID: "test://probed_container_pending_id",
State: api.ContainerState{ State: api.ContainerState{
Running: &api.ContainerStateRunning{}, Running: &api.ContainerStateRunning{},
}, },
} }
probedUnready := api.ContainerStatus{ probedUnready := api.ContainerStatus{
Name: "probed_container_unready", Name: "probed_container_unready",
ContainerID: "probed_container_unready_id", ContainerID: "test://probed_container_unready_id",
State: api.ContainerState{ State: api.ContainerState{
Running: &api.ContainerStateRunning{}, Running: &api.ContainerStateRunning{},
}, },
} }
terminated := api.ContainerStatus{ terminated := api.ContainerStatus{
Name: "terminated_container", Name: "terminated_container",
ContainerID: "terminated_container_id", ContainerID: "test://terminated_container_id",
State: api.ContainerState{ State: api.ContainerState{
Terminated: &api.ContainerStateTerminated{}, Terminated: &api.ContainerStateTerminated{},
}, },
...@@ -199,9 +200,10 @@ func TestUpdatePodStatus(t *testing.T) { ...@@ -199,9 +200,10 @@ func TestUpdatePodStatus(t *testing.T) {
containerPath{podUID, probedUnready.Name}: {}, containerPath{podUID, probedUnready.Name}: {},
containerPath{podUID, terminated.Name}: {}, containerPath{podUID, terminated.Name}: {},
} }
m.readinessCache.setReadiness(probedReady.ContainerID, true)
m.readinessCache.setReadiness(probedUnready.ContainerID, false) m.readinessCache.setReadiness(kubecontainer.ParseContainerID(probedReady.ContainerID), true)
m.readinessCache.setReadiness(terminated.ContainerID, true) m.readinessCache.setReadiness(kubecontainer.ParseContainerID(probedUnready.ContainerID), false)
m.readinessCache.setReadiness(kubecontainer.ParseContainerID(terminated.ContainerID), true)
m.UpdatePodStatus(podUID, &podStatus) m.UpdatePodStatus(podUID, &podStatus)
......
...@@ -41,8 +41,8 @@ const maxProbeRetries = 3 ...@@ -41,8 +41,8 @@ const maxProbeRetries = 3
// Prober checks the healthiness of a container. // Prober checks the healthiness of a container.
type Prober interface { type Prober interface {
ProbeLiveness(pod *api.Pod, status api.PodStatus, container api.Container, containerID string, createdAt int64) (probe.Result, error) ProbeLiveness(pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID, createdAt int64) (probe.Result, error)
ProbeReadiness(pod *api.Pod, status api.PodStatus, container api.Container, containerID string) (probe.Result, error) ProbeReadiness(pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID) (probe.Result, error)
} }
// Prober helps to check the liveness/readiness of a container. // Prober helps to check the liveness/readiness of a container.
...@@ -75,7 +75,7 @@ func New( ...@@ -75,7 +75,7 @@ func New(
// ProbeLiveness probes the liveness of a container. // ProbeLiveness probes the liveness of a container.
// If the initalDelay since container creation on liveness probe has not passed the probe will return probe.Success. // If the initalDelay since container creation on liveness probe has not passed the probe will return probe.Success.
func (pb *prober) ProbeLiveness(pod *api.Pod, status api.PodStatus, container api.Container, containerID string, createdAt int64) (probe.Result, error) { func (pb *prober) ProbeLiveness(pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID, createdAt int64) (probe.Result, error) {
var live probe.Result var live probe.Result
var output string var output string
var err error var err error
...@@ -114,7 +114,7 @@ func (pb *prober) ProbeLiveness(pod *api.Pod, status api.PodStatus, container ap ...@@ -114,7 +114,7 @@ func (pb *prober) ProbeLiveness(pod *api.Pod, status api.PodStatus, container ap
} }
// ProbeReadiness probes and sets the readiness of a container. // ProbeReadiness probes and sets the readiness of a container.
func (pb *prober) ProbeReadiness(pod *api.Pod, status api.PodStatus, container api.Container, containerID string) (probe.Result, error) { func (pb *prober) ProbeReadiness(pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID) (probe.Result, error) {
var ready probe.Result var ready probe.Result
var output string var output string
var err error var err error
...@@ -151,7 +151,7 @@ func (pb *prober) ProbeReadiness(pod *api.Pod, status api.PodStatus, container a ...@@ -151,7 +151,7 @@ func (pb *prober) ProbeReadiness(pod *api.Pod, status api.PodStatus, container a
// runProbeWithRetries tries to probe the container in a finite loop, it returns the last result // runProbeWithRetries tries to probe the container in a finite loop, it returns the last result
// if it never succeeds. // if it never succeeds.
func (pb *prober) runProbeWithRetries(p *api.Probe, pod *api.Pod, status api.PodStatus, container api.Container, containerID string, retries int) (probe.Result, string, error) { func (pb *prober) runProbeWithRetries(p *api.Probe, pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID, retries int) (probe.Result, string, error) {
var err error var err error
var result probe.Result var result probe.Result
var output string var output string
...@@ -164,7 +164,7 @@ func (pb *prober) runProbeWithRetries(p *api.Probe, pod *api.Pod, status api.Pod ...@@ -164,7 +164,7 @@ func (pb *prober) runProbeWithRetries(p *api.Probe, pod *api.Pod, status api.Pod
return result, output, err return result, output, err
} }
func (pb *prober) runProbe(p *api.Probe, pod *api.Pod, status api.PodStatus, container api.Container, containerID string) (probe.Result, string, error) { func (pb *prober) runProbe(p *api.Probe, pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID) (probe.Result, string, error) {
timeout := time.Duration(p.TimeoutSeconds) * time.Second timeout := time.Duration(p.TimeoutSeconds) * time.Second
if p.Exec != nil { if p.Exec != nil {
glog.V(4).Infof("Exec-Probe Pod: %v, Container: %v, Command: %v", pod, container, p.Exec.Command) glog.V(4).Infof("Exec-Probe Pod: %v, Container: %v, Command: %v", pod, container, p.Exec.Command)
...@@ -242,7 +242,7 @@ type execInContainer struct { ...@@ -242,7 +242,7 @@ type execInContainer struct {
run func() ([]byte, error) run func() ([]byte, error)
} }
func (p *prober) newExecInContainer(pod *api.Pod, container api.Container, containerID string, cmd []string) exec.Cmd { func (p *prober) newExecInContainer(pod *api.Pod, container api.Container, containerID kubecontainer.ContainerID, cmd []string) exec.Cmd {
return execInContainer{func() ([]byte, error) { return execInContainer{func() ([]byte, error) {
return p.runner.RunInContainer(containerID, cmd) return p.runner.RunInContainer(containerID, cmd)
}} }}
......
...@@ -183,7 +183,7 @@ func TestProbeContainer(t *testing.T) { ...@@ -183,7 +183,7 @@ func TestProbeContainer(t *testing.T) {
refManager: kubecontainer.NewRefManager(), refManager: kubecontainer.NewRefManager(),
recorder: &record.FakeRecorder{}, recorder: &record.FakeRecorder{},
} }
containerID := "foobar" containerID := kubecontainer.ContainerID{"test", "foobar"}
createdAt := time.Now().Unix() createdAt := time.Now().Unix()
tests := []struct { tests := []struct {
......
...@@ -16,7 +16,11 @@ limitations under the License. ...@@ -16,7 +16,11 @@ limitations under the License.
package prober package prober
import "sync" import (
"sync"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
)
// readinessManager maintains the readiness information(probe results) of // readinessManager maintains the readiness information(probe results) of
// containers over time to allow for implementation of health thresholds. // containers over time to allow for implementation of health thresholds.
...@@ -24,20 +28,19 @@ import "sync" ...@@ -24,20 +28,19 @@ import "sync"
type readinessManager struct { type readinessManager struct {
// guards states // guards states
sync.RWMutex sync.RWMutex
// TODO(yifan): To use strong type. states map[kubecontainer.ContainerID]bool
states map[string]bool
} }
// newReadinessManager creates ane returns a readiness manager with empty // newReadinessManager creates ane returns a readiness manager with empty
// contents. // contents.
func newReadinessManager() *readinessManager { func newReadinessManager() *readinessManager {
return &readinessManager{states: make(map[string]bool)} return &readinessManager{states: make(map[kubecontainer.ContainerID]bool)}
} }
// getReadiness returns the readiness value for the container with the given ID. // getReadiness returns the readiness value for the container with the given ID.
// If the readiness value is found, returns it. // If the readiness value is found, returns it.
// If the readiness is not found, returns false. // If the readiness is not found, returns false.
func (r *readinessManager) getReadiness(id string) (ready bool, found bool) { func (r *readinessManager) getReadiness(id kubecontainer.ContainerID) (ready bool, found bool) {
r.RLock() r.RLock()
defer r.RUnlock() defer r.RUnlock()
state, found := r.states[id] state, found := r.states[id]
...@@ -45,14 +48,14 @@ func (r *readinessManager) getReadiness(id string) (ready bool, found bool) { ...@@ -45,14 +48,14 @@ func (r *readinessManager) getReadiness(id string) (ready bool, found bool) {
} }
// setReadiness sets the readiness value for the container with the given ID. // setReadiness sets the readiness value for the container with the given ID.
func (r *readinessManager) setReadiness(id string, value bool) { func (r *readinessManager) setReadiness(id kubecontainer.ContainerID, value bool) {
r.Lock() r.Lock()
defer r.Unlock() defer r.Unlock()
r.states[id] = value r.states[id] = value
} }
// removeReadiness clears the readiness value for the container with the given ID. // removeReadiness clears the readiness value for the container with the given ID.
func (r *readinessManager) removeReadiness(id string) { func (r *readinessManager) removeReadiness(id kubecontainer.ContainerID) {
r.Lock() r.Lock()
defer r.Unlock() defer r.Unlock()
delete(r.states, id) delete(r.states, id)
......
...@@ -24,7 +24,6 @@ import ( ...@@ -24,7 +24,6 @@ import (
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
kubeutil "k8s.io/kubernetes/pkg/kubelet/util" kubeutil "k8s.io/kubernetes/pkg/kubelet/util"
"k8s.io/kubernetes/pkg/probe" "k8s.io/kubernetes/pkg/probe"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util"
) )
...@@ -47,7 +46,7 @@ type worker struct { ...@@ -47,7 +46,7 @@ type worker struct {
spec *api.Probe spec *api.Probe
// The last known container ID for this worker. // The last known container ID for this worker.
containerID types.UID containerID kubecontainer.ContainerID
} }
// Creates and starts a new probe worker. // Creates and starts a new probe worker.
...@@ -75,8 +74,8 @@ func run(m *manager, w *worker) { ...@@ -75,8 +74,8 @@ func run(m *manager, w *worker) {
defer func() { defer func() {
// Clean up. // Clean up.
probeTicker.Stop() probeTicker.Stop()
if w.containerID != "" { if !w.containerID.IsEmpty() {
m.readinessCache.removeReadiness(string(w.containerID)) m.readinessCache.removeReadiness(w.containerID)
} }
m.removeReadinessProbe(w.pod.UID, w.container.Name) m.removeReadinessProbe(w.pod.UID, w.container.Name)
...@@ -121,17 +120,17 @@ func doProbe(m *manager, w *worker) (keepGoing bool) { ...@@ -121,17 +120,17 @@ func doProbe(m *manager, w *worker) (keepGoing bool) {
return true // Wait for more information. return true // Wait for more information.
} }
if w.containerID != types.UID(c.ContainerID) { if w.containerID.String() != c.ContainerID {
if w.containerID != "" { if !w.containerID.IsEmpty() {
m.readinessCache.removeReadiness(string(w.containerID)) m.readinessCache.removeReadiness(w.containerID)
} }
w.containerID = types.UID(kubecontainer.TrimRuntimePrefix(c.ContainerID)) w.containerID = kubecontainer.ParseContainerID(c.ContainerID)
} }
if c.State.Running == nil { if c.State.Running == nil {
glog.V(3).Infof("Non-running container probed: %v - %v", glog.V(3).Infof("Non-running container probed: %v - %v",
kubeutil.FormatPodName(w.pod), w.container.Name) kubeutil.FormatPodName(w.pod), w.container.Name)
m.readinessCache.setReadiness(string(w.containerID), false) m.readinessCache.setReadiness(w.containerID, false)
// Abort if the container will not be restarted. // Abort if the container will not be restarted.
return c.State.Terminated == nil || return c.State.Terminated == nil ||
w.pod.Spec.RestartPolicy != api.RestartPolicyNever w.pod.Spec.RestartPolicy != api.RestartPolicyNever
...@@ -139,14 +138,14 @@ func doProbe(m *manager, w *worker) (keepGoing bool) { ...@@ -139,14 +138,14 @@ func doProbe(m *manager, w *worker) (keepGoing bool) {
if int64(time.Since(c.State.Running.StartedAt.Time).Seconds()) < w.spec.InitialDelaySeconds { if int64(time.Since(c.State.Running.StartedAt.Time).Seconds()) < w.spec.InitialDelaySeconds {
// Readiness defaults to false during the initial delay. // Readiness defaults to false during the initial delay.
m.readinessCache.setReadiness(string(w.containerID), false) m.readinessCache.setReadiness(w.containerID, false)
return true return true
} }
// TODO: Move error handling out of prober. // TODO: Move error handling out of prober.
result, _ := m.prober.ProbeReadiness(w.pod, status, w.container, string(w.containerID)) result, _ := m.prober.ProbeReadiness(w.pod, status, w.container, w.containerID)
if result != probe.Unknown { if result != probe.Unknown {
m.readinessCache.setReadiness(string(w.containerID), result != probe.Failure) m.readinessCache.setReadiness(w.containerID, result != probe.Failure)
} }
return true return true
......
...@@ -22,15 +22,17 @@ import ( ...@@ -22,15 +22,17 @@ import (
"k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/unversioned"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/probe" "k8s.io/kubernetes/pkg/probe"
) )
const ( const (
containerID = "cOnTaInEr_Id"
containerName = "cOnTaInEr_NaMe" containerName = "cOnTaInEr_NaMe"
podUID = "pOd_UiD" podUID = "pOd_UiD"
) )
var containerID = kubecontainer.ContainerID{"test", "cOnTaInEr_Id"}
func TestDoProbe(t *testing.T) { func TestDoProbe(t *testing.T) {
m := newTestManager() m := newTestManager()
...@@ -204,7 +206,7 @@ func newTestWorker(probeSpec api.Probe) *worker { ...@@ -204,7 +206,7 @@ func newTestWorker(probeSpec api.Probe) *worker {
func getRunningStatus() api.PodStatus { func getRunningStatus() api.PodStatus {
containerStatus := api.ContainerStatus{ containerStatus := api.ContainerStatus{
Name: containerName, Name: containerName,
ContainerID: containerID, ContainerID: containerID.String(),
} }
containerStatus.State.Running = &api.ContainerStateRunning{unversioned.Now()} containerStatus.State.Running = &api.ContainerStateRunning{unversioned.Now()}
podStatus := api.PodStatus{ podStatus := api.PodStatus{
...@@ -231,10 +233,10 @@ func getTestPod(probeSpec api.Probe) api.Pod { ...@@ -231,10 +233,10 @@ func getTestPod(probeSpec api.Probe) api.Pod {
type CrashingProber struct{} type CrashingProber struct{}
func (f CrashingProber) ProbeLiveness(_ *api.Pod, _ api.PodStatus, c api.Container, _ string, _ int64) (probe.Result, error) { func (f CrashingProber) ProbeLiveness(_ *api.Pod, _ api.PodStatus, c api.Container, _ kubecontainer.ContainerID, _ int64) (probe.Result, error) {
panic("Intentional ProbeLiveness crash.") panic("Intentional ProbeLiveness crash.")
} }
func (f CrashingProber) ProbeReadiness(_ *api.Pod, _ api.PodStatus, c api.Container, _ string) (probe.Result, error) { func (f CrashingProber) ProbeReadiness(_ *api.Pod, _ api.PodStatus, c api.Container, _ kubecontainer.ContainerID) (probe.Result, error) {
panic("Intentional ProbeReadiness crash.") panic("Intentional ProbeReadiness crash.")
} }
...@@ -19,6 +19,8 @@ package rkt ...@@ -19,6 +19,8 @@ package rkt
import ( import (
"fmt" "fmt"
"strings" "strings"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
) )
// containerID defines the ID of rkt containers, it will // containerID defines the ID of rkt containers, it will
...@@ -29,17 +31,22 @@ type containerID struct { ...@@ -29,17 +31,22 @@ type containerID struct {
appName string // Name of the app in that pod. appName string // Name of the app in that pod.
} }
const RktType = "rkt"
// buildContainerID constructs the containers's ID using containerID, // buildContainerID constructs the containers's ID using containerID,
// which consists of the pod uuid and the container name. // which consists of the pod uuid and the container name.
// The result can be used to uniquely identify a container. // The result can be used to uniquely identify a container.
func buildContainerID(c *containerID) string { func buildContainerID(c *containerID) kubecontainer.ContainerID {
return fmt.Sprintf("%s:%s", c.uuid, c.appName) return kubecontainer.ContainerID{
Type: RktType,
ID: fmt.Sprintf("%s:%s", c.uuid, c.appName),
}
} }
// parseContainerID parses the containerID into pod uuid and the container name. The // parseContainerID parses the containerID into pod uuid and the container name. The
// results can be used to get more information of the container. // results can be used to get more information of the container.
func parseContainerID(id string) (*containerID, error) { func parseContainerID(id kubecontainer.ContainerID) (*containerID, error) {
tuples := strings.Split(id, ":") tuples := strings.Split(id.ID, ":")
if len(tuples) != 2 { if len(tuples) != 2 {
return nil, fmt.Errorf("rkt: cannot parse container ID for: %v", id) return nil, fmt.Errorf("rkt: cannot parse container ID for: %v", id)
} }
......
...@@ -143,7 +143,7 @@ func makeContainerStatus(container *kubecontainer.Container, podInfo *podInfo) a ...@@ -143,7 +143,7 @@ func makeContainerStatus(container *kubecontainer.Container, podInfo *podInfo) a
var status api.ContainerStatus var status api.ContainerStatus
status.Name = container.Name status.Name = container.Name
status.Image = container.Image status.Image = container.Image
status.ContainerID = string(container.ID) status.ContainerID = container.ID.String()
// TODO(yifan): Add image ID info. // TODO(yifan): Add image ID info.
switch podInfo.state { switch podInfo.state {
......
...@@ -513,7 +513,7 @@ func apiPodToruntimePod(uuid string, pod *api.Pod) *kubecontainer.Pod { ...@@ -513,7 +513,7 @@ func apiPodToruntimePod(uuid string, pod *api.Pod) *kubecontainer.Pod {
for i := range pod.Spec.Containers { for i := range pod.Spec.Containers {
c := &pod.Spec.Containers[i] c := &pod.Spec.Containers[i]
p.Containers = append(p.Containers, &kubecontainer.Container{ p.Containers = append(p.Containers, &kubecontainer.Container{
ID: types.UID(buildContainerID(&containerID{uuid, c.Name})), ID: buildContainerID(&containerID{uuid, c.Name}),
Name: c.Name, Name: c.Name,
Image: c.Image, Image: c.Image,
Hash: kubecontainer.HashContainer(c), Hash: kubecontainer.HashContainer(c),
...@@ -646,7 +646,7 @@ func (r *Runtime) preparePod(pod *api.Pod, pullSecrets []api.Secret) (string, *k ...@@ -646,7 +646,7 @@ func (r *Runtime) preparePod(pod *api.Pod, pullSecrets []api.Secret) (string, *k
func (r *Runtime) generateEvents(runtimePod *kubecontainer.Pod, reason string, failure error) { func (r *Runtime) generateEvents(runtimePod *kubecontainer.Pod, reason string, failure error) {
// Set up container references. // Set up container references.
for _, c := range runtimePod.Containers { for _, c := range runtimePod.Containers {
containerID := string(c.ID) containerID := c.ID
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { if err != nil {
glog.Warningf("Invalid container ID %q", containerID) glog.Warningf("Invalid container ID %q", containerID)
...@@ -697,7 +697,7 @@ func (r *Runtime) RunPod(pod *api.Pod, pullSecrets []api.Secret) error { ...@@ -697,7 +697,7 @@ func (r *Runtime) RunPod(pod *api.Pod, pullSecrets []api.Secret) error {
r.recorder.Eventf(ref, "Failed", "Failed to create rkt container with error: %v", prepareErr) r.recorder.Eventf(ref, "Failed", "Failed to create rkt container with error: %v", prepareErr)
continue continue
} }
containerID := string(runtimePod.Containers[i].ID) containerID := runtimePod.Containers[i].ID
r.containerRefManager.SetRef(containerID, ref) r.containerRefManager.SetRef(containerID, ref)
} }
...@@ -802,8 +802,7 @@ func (r *Runtime) KillPod(pod *api.Pod, runningPod kubecontainer.Pod) error { ...@@ -802,8 +802,7 @@ func (r *Runtime) KillPod(pod *api.Pod, runningPod kubecontainer.Pod) error {
serviceName := makePodServiceFileName(runningPod.ID) serviceName := makePodServiceFileName(runningPod.ID)
r.generateEvents(&runningPod, "Killing", nil) r.generateEvents(&runningPod, "Killing", nil)
for _, c := range runningPod.Containers { for _, c := range runningPod.Containers {
id := string(c.ID) r.containerRefManager.ClearRef(c.ID)
r.containerRefManager.ClearRef(id)
} }
// Since all service file have 'KillMode=mixed', the processes in // Since all service file have 'KillMode=mixed', the processes in
...@@ -989,7 +988,7 @@ func (r *Runtime) SyncPod(pod *api.Pod, runningPod kubecontainer.Pod, podStatus ...@@ -989,7 +988,7 @@ func (r *Runtime) SyncPod(pod *api.Pod, runningPod kubecontainer.Pod, podStatus
podFullName := kubeletUtil.FormatPodName(pod) podFullName := kubeletUtil.FormatPodName(pod)
// Add references to all containers. // Add references to all containers.
unidentifiedContainers := make(map[types.UID]*kubecontainer.Container) unidentifiedContainers := make(map[kubecontainer.ContainerID]*kubecontainer.Container)
for _, c := range runningPod.Containers { for _, c := range runningPod.Containers {
unidentifiedContainers[c.ID] = c unidentifiedContainers[c.ID] = c
} }
...@@ -1020,7 +1019,7 @@ func (r *Runtime) SyncPod(pod *api.Pod, runningPod kubecontainer.Pod, podStatus ...@@ -1020,7 +1019,7 @@ func (r *Runtime) SyncPod(pod *api.Pod, runningPod kubecontainer.Pod, podStatus
break break
} }
result, err := r.prober.ProbeLiveness(pod, podStatus, container, string(c.ID), c.Created) result, err := r.prober.ProbeLiveness(pod, podStatus, container, c.ID, c.Created)
// TODO(vmarmol): examine this logic. // TODO(vmarmol): examine this logic.
if err == nil && result != probe.Success { if err == nil && result != probe.Success {
glog.Infof("Pod %q container %q is unhealthy (probe result: %v), it will be killed and re-created.", podFullName, container.Name, result) glog.Infof("Pod %q container %q is unhealthy (probe result: %v), it will be killed and re-created.", podFullName, container.Name, result)
...@@ -1062,7 +1061,7 @@ func (r *Runtime) SyncPod(pod *api.Pod, runningPod kubecontainer.Pod, podStatus ...@@ -1062,7 +1061,7 @@ func (r *Runtime) SyncPod(pod *api.Pod, runningPod kubecontainer.Pod, podStatus
// See https://github.com/coreos/rkt/blob/master/Documentation/commands.md#logging for more details. // See https://github.com/coreos/rkt/blob/master/Documentation/commands.md#logging for more details.
// //
// TODO(yifan): If the rkt is using lkvm as the stage1 image, then this function will fail. // TODO(yifan): If the rkt is using lkvm as the stage1 image, then this function will fail.
func (r *Runtime) GetContainerLogs(pod *api.Pod, containerID string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error { func (r *Runtime) GetContainerLogs(pod *api.Pod, containerID kubecontainer.ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error {
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { if err != nil {
return err return err
...@@ -1098,7 +1097,7 @@ func (r *Runtime) GarbageCollect() error { ...@@ -1098,7 +1097,7 @@ func (r *Runtime) GarbageCollect() error {
// Note: In rkt, the container ID is in the form of "UUID:appName", where // Note: In rkt, the container ID is in the form of "UUID:appName", where
// appName is the container name. // appName is the container name.
// TODO(yifan): If the rkt is using lkvm as the stage1 image, then this function will fail. // TODO(yifan): If the rkt is using lkvm as the stage1 image, then this function will fail.
func (r *Runtime) RunInContainer(containerID string, cmd []string) ([]byte, error) { func (r *Runtime) RunInContainer(containerID kubecontainer.ContainerID, cmd []string) ([]byte, error) {
glog.V(4).Infof("Rkt running in container.") glog.V(4).Infof("Rkt running in container.")
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
...@@ -1112,14 +1111,14 @@ func (r *Runtime) RunInContainer(containerID string, cmd []string) ([]byte, erro ...@@ -1112,14 +1111,14 @@ func (r *Runtime) RunInContainer(containerID string, cmd []string) ([]byte, erro
return []byte(strings.Join(result, "\n")), err return []byte(strings.Join(result, "\n")), err
} }
func (r *Runtime) AttachContainer(containerID string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { func (r *Runtime) AttachContainer(containerID kubecontainer.ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error {
return fmt.Errorf("unimplemented") return fmt.Errorf("unimplemented")
} }
// Note: In rkt, the container ID is in the form of "UUID:appName", where UUID is // Note: In rkt, the container ID is in the form of "UUID:appName", where UUID is
// the rkt UUID, and appName is the container name. // the rkt UUID, and appName is the container name.
// TODO(yifan): If the rkt is using lkvm as the stage1 image, then this function will fail. // TODO(yifan): If the rkt is using lkvm as the stage1 image, then this function will fail.
func (r *Runtime) ExecInContainer(containerID string, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { func (r *Runtime) ExecInContainer(containerID kubecontainer.ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error {
glog.V(4).Infof("Rkt execing in container.") glog.V(4).Infof("Rkt execing in container.")
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
......
...@@ -21,6 +21,7 @@ import ( ...@@ -21,6 +21,7 @@ import (
"time" "time"
"k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
) )
// TODO: Reconcile custom types in kubelet/types and this subpackage // TODO: Reconcile custom types in kubelet/types and this subpackage
...@@ -28,6 +29,13 @@ import ( ...@@ -28,6 +29,13 @@ import (
// DockerID is an ID of docker container. It is a type to make it clear when we're working with docker container Ids // DockerID is an ID of docker container. It is a type to make it clear when we're working with docker container Ids
type DockerID string type DockerID string
func (id DockerID) ContainerID() kubecontainer.ContainerID {
return kubecontainer.ContainerID{
Type: "docker",
ID: string(id),
}
}
type HttpGetter interface { type HttpGetter interface {
Get(url string) (*http.Response, error) Get(url string) (*http.Response, error)
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment