Commit 0e1a166c authored by Kubernetes Submit Queue's avatar Kubernetes Submit Queue Committed by GitHub

Merge pull request #39158 from feiskyer/cri-proto3

Automatic merge from submit-queue (batch tested with PRs 40168, 40165, 39158, 39966, 40190) CRI: upgrade protobuf to v3 For #38854, this PR upgrades CRI protobuf version to v3, and also updated related packages for confirming to new api. **Release note**: ``` CRI: upgrade protobuf version to v3. ```
parents 98411624 b9625802
...@@ -67,7 +67,6 @@ cluster/saltbase/salt/kubelet/default:{% if grains['feature_gates'] is defined - ...@@ -67,7 +67,6 @@ cluster/saltbase/salt/kubelet/default:{% if grains['feature_gates'] is defined -
cluster/saltbase/salt/kubelet/default:{% if pillar.get('non_masquerade_cidr','') -%} cluster/saltbase/salt/kubelet/default:{% if pillar.get('non_masquerade_cidr','') -%}
cluster/saltbase/salt/opencontrail-networking-master/init.sls: - 'SERVICE_CLUSTER_IP_RANGE': '{{ pillar.get('service_cluster_ip_range') }}' cluster/saltbase/salt/opencontrail-networking-master/init.sls: - 'SERVICE_CLUSTER_IP_RANGE': '{{ pillar.get('service_cluster_ip_range') }}'
cluster/saltbase/salt/opencontrail-networking-minion/init.sls: - 'SERVICE_CLUSTER_IP_RANGE': '{{ pillar.get('service_cluster_ip_range') }}' cluster/saltbase/salt/opencontrail-networking-minion/init.sls: - 'SERVICE_CLUSTER_IP_RANGE': '{{ pillar.get('service_cluster_ip_range') }}'
cluster/saltbase/salt/supervisor/kubelet-checker.sh: {% set kubelet_port = pillar['kubelet_port'] -%}
cluster/saltbase/salt/supervisor/supervisor_watcher.sh:# Apply oom_score_adj: -901 to processes cluster/saltbase/salt/supervisor/supervisor_watcher.sh:# Apply oom_score_adj: -901 to processes
cluster/ubuntu/util.sh: local node_ip=${1} cluster/ubuntu/util.sh: local node_ip=${1}
cluster/vagrant/provision-utils.sh: api_servers: '$(echo "$MASTER_IP" | sed -e "s/'/''/g")' cluster/vagrant/provision-utils.sh: api_servers: '$(echo "$MASTER_IP" | sed -e "s/'/''/g")'
...@@ -105,14 +104,14 @@ hack/test-update-storage-objects.sh: local storage_media_type=${3:-""} ...@@ -105,14 +104,14 @@ hack/test-update-storage-objects.sh: local storage_media_type=${3:-""}
hack/test-update-storage-objects.sh: local storage_versions=${2:-""} hack/test-update-storage-objects.sh: local storage_versions=${2:-""}
hack/test-update-storage-objects.sh: source_file=${test_data[0]} hack/test-update-storage-objects.sh: source_file=${test_data[0]}
hack/test-update-storage-objects.sh:# source_file,resource,namespace,name,old_version,new_version hack/test-update-storage-objects.sh:# source_file,resource,namespace,name,old_version,new_version
pkg/kubelet/api/v1alpha1/runtime/api.pb.go: ContainerPort *int32 `protobuf:"varint,2,opt,name=container_port,json=containerPort" json:"container_port,omitempty"` pkg/kubelet/api/v1alpha1/runtime/api.pb.go: ContainerPort int32 `protobuf:"varint,2,opt,name=container_port,json=containerPort,proto3" json:"container_port,omitempty"`
pkg/kubelet/api/v1alpha1/runtime/api.pb.go: OomScoreAdj *int64 `protobuf:"varint,5,opt,name=oom_score_adj,json=oomScoreAdj" json:"oom_score_adj,omitempty"` pkg/kubelet/api/v1alpha1/runtime/api.pb.go: OomScoreAdj int64 `protobuf:"varint,5,opt,name=oom_score_adj,json=oomScoreAdj,proto3" json:"oom_score_adj,omitempty"`
pkg/kubelet/api/v1alpha1/runtime/api.pb.go: PodCidr *string `protobuf:"bytes,1,opt,name=pod_cidr,json=podCidr" json:"pod_cidr,omitempty"` pkg/kubelet/api/v1alpha1/runtime/api.pb.go: PodCidr string `protobuf:"bytes,1,opt,name=pod_cidr,json=podCidr,proto3" json:"pod_cidr,omitempty"`
pkg/kubelet/api/v1alpha1/runtime/api.pb.go: RuntimeConfig *RuntimeConfig `protobuf:"bytes,1,opt,name=runtime_config,json=runtimeConfig" json:"runtime_config,omitempty"` pkg/kubelet/api/v1alpha1/runtime/api.pb.go: RuntimeConfig *RuntimeConfig `protobuf:"bytes,1,opt,name=runtime_config,json=runtimeConfig" json:"runtime_config,omitempty"`
pkg/kubelet/api/v1alpha1/runtime/api.proto: optional RuntimeConfig runtime_config = 1; pkg/kubelet/api/v1alpha1/runtime/api.proto: RuntimeConfig runtime_config = 1;
pkg/kubelet/api/v1alpha1/runtime/api.proto: optional int32 container_port = 2; pkg/kubelet/api/v1alpha1/runtime/api.proto: int32 container_port = 2;
pkg/kubelet/api/v1alpha1/runtime/api.proto: optional int64 oom_score_adj = 5; pkg/kubelet/api/v1alpha1/runtime/api.proto: int64 oom_score_adj = 5;
pkg/kubelet/api/v1alpha1/runtime/api.proto: optional string pod_cidr = 1; pkg/kubelet/api/v1alpha1/runtime/api.proto: string pod_cidr = 1;
pkg/kubelet/cm/container_manager_linux.go: glog.V(3).Infof("Failed to apply oom_score_adj %d for pid %d: %v", oomScoreAdj, pid, err) pkg/kubelet/cm/container_manager_linux.go: glog.V(3).Infof("Failed to apply oom_score_adj %d for pid %d: %v", oomScoreAdj, pid, err)
pkg/kubelet/cm/container_manager_linux.go: glog.V(5).Infof("attempting to apply oom_score_adj of %d to pid %d", oomScoreAdj, pid) pkg/kubelet/cm/container_manager_linux.go: glog.V(5).Infof("attempting to apply oom_score_adj of %d to pid %d", oomScoreAdj, pid)
pkg/kubelet/network/hairpin/hairpin.go: hairpinModeRelativePath = "hairpin_mode" pkg/kubelet/network/hairpin/hairpin.go: hairpinModeRelativePath = "hairpin_mode"
......
...@@ -57,8 +57,8 @@ func NewFakeImageService() *FakeImageService { ...@@ -57,8 +57,8 @@ func NewFakeImageService() *FakeImageService {
func (r *FakeImageService) makeFakeImage(image string) *runtimeapi.Image { func (r *FakeImageService) makeFakeImage(image string) *runtimeapi.Image {
return &runtimeapi.Image{ return &runtimeapi.Image{
Id: &image, Id: image,
Size_: &r.FakeImageSize, Size_: r.FakeImageSize,
RepoTags: []string{image}, RepoTags: []string{image},
} }
} }
...@@ -72,7 +72,7 @@ func (r *FakeImageService) ListImages(filter *runtimeapi.ImageFilter) ([]*runtim ...@@ -72,7 +72,7 @@ func (r *FakeImageService) ListImages(filter *runtimeapi.ImageFilter) ([]*runtim
images := make([]*runtimeapi.Image, 0) images := make([]*runtimeapi.Image, 0)
for _, img := range r.Images { for _, img := range r.Images {
if filter != nil && filter.Image != nil { if filter != nil && filter.Image != nil {
if !sliceutils.StringInSlice(filter.Image.GetImage(), img.RepoTags) { if !sliceutils.StringInSlice(filter.Image.Image, img.RepoTags) {
continue continue
} }
} }
...@@ -88,7 +88,7 @@ func (r *FakeImageService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimeapi ...@@ -88,7 +88,7 @@ func (r *FakeImageService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimeapi
r.Called = append(r.Called, "ImageStatus") r.Called = append(r.Called, "ImageStatus")
return r.Images[image.GetImage()], nil return r.Images[image.Image], nil
} }
func (r *FakeImageService) PullImage(image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig) (string, error) { func (r *FakeImageService) PullImage(image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig) (string, error) {
...@@ -99,9 +99,9 @@ func (r *FakeImageService) PullImage(image *runtimeapi.ImageSpec, auth *runtimea ...@@ -99,9 +99,9 @@ func (r *FakeImageService) PullImage(image *runtimeapi.ImageSpec, auth *runtimea
// ImageID should be randomized for real container runtime, but here just use // ImageID should be randomized for real container runtime, but here just use
// image's name for easily making fake images. // image's name for easily making fake images.
imageID := image.GetImage() imageID := image.Image
if _, ok := r.Images[imageID]; !ok { if _, ok := r.Images[imageID]; !ok {
r.Images[imageID] = r.makeFakeImage(image.GetImage()) r.Images[imageID] = r.makeFakeImage(image.Image)
} }
return imageID, nil return imageID, nil
...@@ -114,7 +114,7 @@ func (r *FakeImageService) RemoveImage(image *runtimeapi.ImageSpec) error { ...@@ -114,7 +114,7 @@ func (r *FakeImageService) RemoveImage(image *runtimeapi.ImageSpec) error {
r.Called = append(r.Called, "RemoveImage") r.Called = append(r.Called, "RemoveImage")
// Remove the image // Remove the image
delete(r.Images, image.GetImage()) delete(r.Images, image.Image)
return nil return nil
} }
...@@ -61,7 +61,7 @@ func (r *FakeRuntimeService) SetFakeSandboxes(sandboxes []*FakePodSandbox) { ...@@ -61,7 +61,7 @@ func (r *FakeRuntimeService) SetFakeSandboxes(sandboxes []*FakePodSandbox) {
r.Sandboxes = make(map[string]*FakePodSandbox) r.Sandboxes = make(map[string]*FakePodSandbox)
for _, sandbox := range sandboxes { for _, sandbox := range sandboxes {
sandboxID := sandbox.GetId() sandboxID := sandbox.Id
r.Sandboxes[sandboxID] = sandbox r.Sandboxes[sandboxID] = sandbox
} }
} }
...@@ -72,7 +72,7 @@ func (r *FakeRuntimeService) SetFakeContainers(containers []*FakeContainer) { ...@@ -72,7 +72,7 @@ func (r *FakeRuntimeService) SetFakeContainers(containers []*FakeContainer) {
r.Containers = make(map[string]*FakeContainer) r.Containers = make(map[string]*FakeContainer)
for _, c := range containers { for _, c := range containers {
containerID := c.GetId() containerID := c.Id
r.Containers[containerID] = c r.Containers[containerID] = c
} }
...@@ -103,10 +103,10 @@ func (r *FakeRuntimeService) Version(apiVersion string) (*runtimeapi.VersionResp ...@@ -103,10 +103,10 @@ func (r *FakeRuntimeService) Version(apiVersion string) (*runtimeapi.VersionResp
r.Called = append(r.Called, "Version") r.Called = append(r.Called, "Version")
return &runtimeapi.VersionResponse{ return &runtimeapi.VersionResponse{
Version: &version, Version: version,
RuntimeName: &FakeRuntimeName, RuntimeName: FakeRuntimeName,
RuntimeVersion: &version, RuntimeVersion: version,
RuntimeApiVersion: &version, RuntimeApiVersion: version,
}, nil }, nil
} }
...@@ -129,15 +129,14 @@ func (r *FakeRuntimeService) RunPodSandbox(config *runtimeapi.PodSandboxConfig) ...@@ -129,15 +129,14 @@ func (r *FakeRuntimeService) RunPodSandbox(config *runtimeapi.PodSandboxConfig)
// fixed name from BuildSandboxName() for easily making fake sandboxes. // fixed name from BuildSandboxName() for easily making fake sandboxes.
podSandboxID := BuildSandboxName(config.Metadata) podSandboxID := BuildSandboxName(config.Metadata)
createdAt := time.Now().Unix() createdAt := time.Now().Unix()
readyState := runtimeapi.PodSandboxState_SANDBOX_READY
r.Sandboxes[podSandboxID] = &FakePodSandbox{ r.Sandboxes[podSandboxID] = &FakePodSandbox{
PodSandboxStatus: runtimeapi.PodSandboxStatus{ PodSandboxStatus: runtimeapi.PodSandboxStatus{
Id: &podSandboxID, Id: podSandboxID,
Metadata: config.Metadata, Metadata: config.Metadata,
State: &readyState, State: runtimeapi.PodSandboxState_SANDBOX_READY,
CreatedAt: &createdAt, CreatedAt: createdAt,
Network: &runtimeapi.PodSandboxNetworkStatus{ Network: &runtimeapi.PodSandboxNetworkStatus{
Ip: &FakePodSandboxIP, Ip: FakePodSandboxIP,
}, },
Labels: config.Labels, Labels: config.Labels,
Annotations: config.Annotations, Annotations: config.Annotations,
...@@ -153,9 +152,8 @@ func (r *FakeRuntimeService) StopPodSandbox(podSandboxID string) error { ...@@ -153,9 +152,8 @@ func (r *FakeRuntimeService) StopPodSandbox(podSandboxID string) error {
r.Called = append(r.Called, "StopPodSandbox") r.Called = append(r.Called, "StopPodSandbox")
notReadyState := runtimeapi.PodSandboxState_SANDBOX_NOTREADY
if s, ok := r.Sandboxes[podSandboxID]; ok { if s, ok := r.Sandboxes[podSandboxID]; ok {
s.State = &notReadyState s.State = runtimeapi.PodSandboxState_SANDBOX_NOTREADY
} else { } else {
return fmt.Errorf("pod sandbox %s not found", podSandboxID) return fmt.Errorf("pod sandbox %s not found", podSandboxID)
} }
...@@ -199,10 +197,10 @@ func (r *FakeRuntimeService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ...@@ -199,10 +197,10 @@ func (r *FakeRuntimeService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter)
result := make([]*runtimeapi.PodSandbox, 0) result := make([]*runtimeapi.PodSandbox, 0)
for id, s := range r.Sandboxes { for id, s := range r.Sandboxes {
if filter != nil { if filter != nil {
if filter.Id != nil && filter.GetId() != id { if filter.Id != "" && filter.Id != id {
continue continue
} }
if filter.State != nil && filter.GetState() != s.GetState() { if filter.State != nil && filter.GetState().State != s.State {
continue continue
} }
if filter.LabelSelector != nil && !filterInLabels(filter.LabelSelector, s.GetLabels()) { if filter.LabelSelector != nil && !filterInLabels(filter.LabelSelector, s.GetLabels()) {
...@@ -242,15 +240,15 @@ func (r *FakeRuntimeService) CreateContainer(podSandboxID string, config *runtim ...@@ -242,15 +240,15 @@ func (r *FakeRuntimeService) CreateContainer(podSandboxID string, config *runtim
containerID := BuildContainerName(config.Metadata, podSandboxID) containerID := BuildContainerName(config.Metadata, podSandboxID)
createdAt := time.Now().Unix() createdAt := time.Now().Unix()
createdState := runtimeapi.ContainerState_CONTAINER_CREATED createdState := runtimeapi.ContainerState_CONTAINER_CREATED
imageRef := config.Image.GetImage() imageRef := config.Image.Image
r.Containers[containerID] = &FakeContainer{ r.Containers[containerID] = &FakeContainer{
ContainerStatus: runtimeapi.ContainerStatus{ ContainerStatus: runtimeapi.ContainerStatus{
Id: &containerID, Id: containerID,
Metadata: config.Metadata, Metadata: config.Metadata,
Image: config.Image, Image: config.Image,
ImageRef: &imageRef, ImageRef: imageRef,
CreatedAt: &createdAt, CreatedAt: createdAt,
State: &createdState, State: createdState,
Labels: config.Labels, Labels: config.Labels,
Annotations: config.Annotations, Annotations: config.Annotations,
}, },
...@@ -272,10 +270,8 @@ func (r *FakeRuntimeService) StartContainer(containerID string) error { ...@@ -272,10 +270,8 @@ func (r *FakeRuntimeService) StartContainer(containerID string) error {
} }
// Set container to running. // Set container to running.
startedAt := time.Now().Unix() c.State = runtimeapi.ContainerState_CONTAINER_RUNNING
runningState := runtimeapi.ContainerState_CONTAINER_RUNNING c.StartedAt = time.Now().Unix()
c.State = &runningState
c.StartedAt = &startedAt
return nil return nil
} }
...@@ -294,8 +290,8 @@ func (r *FakeRuntimeService) StopContainer(containerID string, timeout int64) er ...@@ -294,8 +290,8 @@ func (r *FakeRuntimeService) StopContainer(containerID string, timeout int64) er
// Set container to exited state. // Set container to exited state.
finishedAt := time.Now().Unix() finishedAt := time.Now().Unix()
exitedState := runtimeapi.ContainerState_CONTAINER_EXITED exitedState := runtimeapi.ContainerState_CONTAINER_EXITED
c.State = &exitedState c.State = exitedState
c.FinishedAt = &finishedAt c.FinishedAt = finishedAt
return nil return nil
} }
...@@ -321,13 +317,13 @@ func (r *FakeRuntimeService) ListContainers(filter *runtimeapi.ContainerFilter) ...@@ -321,13 +317,13 @@ func (r *FakeRuntimeService) ListContainers(filter *runtimeapi.ContainerFilter)
result := make([]*runtimeapi.Container, 0) result := make([]*runtimeapi.Container, 0)
for _, s := range r.Containers { for _, s := range r.Containers {
if filter != nil { if filter != nil {
if filter.Id != nil && filter.GetId() != s.GetId() { if filter.Id != "" && filter.Id != s.Id {
continue continue
} }
if filter.PodSandboxId != nil && filter.GetPodSandboxId() != s.SandboxID { if filter.PodSandboxId != "" && filter.PodSandboxId != s.SandboxID {
continue continue
} }
if filter.State != nil && filter.GetState() != s.GetState() { if filter.State != nil && filter.GetState().State != s.State {
continue continue
} }
if filter.LabelSelector != nil && !filterInLabels(filter.LabelSelector, s.GetLabels()) { if filter.LabelSelector != nil && !filterInLabels(filter.LabelSelector, s.GetLabels()) {
...@@ -338,7 +334,7 @@ func (r *FakeRuntimeService) ListContainers(filter *runtimeapi.ContainerFilter) ...@@ -338,7 +334,7 @@ func (r *FakeRuntimeService) ListContainers(filter *runtimeapi.ContainerFilter)
result = append(result, &runtimeapi.Container{ result = append(result, &runtimeapi.Container{
Id: s.Id, Id: s.Id,
CreatedAt: s.CreatedAt, CreatedAt: s.CreatedAt,
PodSandboxId: &s.SandboxID, PodSandboxId: s.SandboxID,
Metadata: s.Metadata, Metadata: s.Metadata,
State: s.State, State: s.State,
Image: s.Image, Image: s.Image,
......
...@@ -24,11 +24,11 @@ import ( ...@@ -24,11 +24,11 @@ import (
func BuildContainerName(metadata *runtimeapi.ContainerMetadata, sandboxID string) string { func BuildContainerName(metadata *runtimeapi.ContainerMetadata, sandboxID string) string {
// include the sandbox ID to make the container ID unique. // include the sandbox ID to make the container ID unique.
return fmt.Sprintf("%s_%s_%d", sandboxID, metadata.GetName(), metadata.GetAttempt()) return fmt.Sprintf("%s_%s_%d", sandboxID, metadata.Name, metadata.Attempt)
} }
func BuildSandboxName(metadata *runtimeapi.PodSandboxMetadata) string { func BuildSandboxName(metadata *runtimeapi.PodSandboxMetadata) string {
return fmt.Sprintf("%s_%s_%s_%d", metadata.GetName(), metadata.GetNamespace(), metadata.GetUid(), metadata.GetAttempt()) return fmt.Sprintf("%s_%s_%s_%d", metadata.Name, metadata.Namespace, metadata.Uid, metadata.Attempt)
} }
func filterInLabels(filter, labels map[string]string) bool { func filterInLabels(filter, labels map[string]string) bool {
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -197,14 +197,14 @@ func ConvertPodStatusToRunningPod(runtimeName string, podStatus *PodStatus) Pod ...@@ -197,14 +197,14 @@ func ConvertPodStatusToRunningPod(runtimeName string, podStatus *PodStatus) Pod
// Populate sandboxes in kubecontainer.Pod // Populate sandboxes in kubecontainer.Pod
for _, sandbox := range podStatus.SandboxStatuses { for _, sandbox := range podStatus.SandboxStatuses {
runningPod.Sandboxes = append(runningPod.Sandboxes, &Container{ runningPod.Sandboxes = append(runningPod.Sandboxes, &Container{
ID: ContainerID{Type: runtimeName, ID: *sandbox.Id}, ID: ContainerID{Type: runtimeName, ID: sandbox.Id},
State: SandboxToContainerState(*sandbox.State), State: SandboxToContainerState(sandbox.State),
}) })
} }
return runningPod return runningPod
} }
// sandboxToContainerState converts runtimeApi.PodSandboxState to // SandboxToContainerState converts runtimeapi.PodSandboxState to
// kubecontainer.ContainerState. // kubecontainer.ContainerState.
// This is only needed because we need to return sandboxes as if they were // This is only needed because we need to return sandboxes as if they were
// kubecontainer.Containers to avoid substantial changes to PLEG. // kubecontainer.Containers to avoid substantial changes to PLEG.
......
...@@ -49,7 +49,6 @@ go_library( ...@@ -49,7 +49,6 @@ go_library(
"//vendor:github.com/docker/engine-api/types/versions", "//vendor:github.com/docker/engine-api/types/versions",
"//vendor:github.com/docker/go-connections/nat", "//vendor:github.com/docker/go-connections/nat",
"//vendor:github.com/golang/glog", "//vendor:github.com/golang/glog",
"//vendor:github.com/golang/protobuf/proto",
], ],
) )
......
...@@ -43,10 +43,10 @@ func imageToRuntimeAPIImage(image *dockertypes.Image) (*runtimeapi.Image, error) ...@@ -43,10 +43,10 @@ func imageToRuntimeAPIImage(image *dockertypes.Image) (*runtimeapi.Image, error)
size := uint64(image.VirtualSize) size := uint64(image.VirtualSize)
return &runtimeapi.Image{ return &runtimeapi.Image{
Id: &image.ID, Id: image.ID,
RepoTags: image.RepoTags, RepoTags: image.RepoTags,
RepoDigests: image.RepoDigests, RepoDigests: image.RepoDigests,
Size_: &size, Size_: size,
}, nil }, nil
} }
...@@ -57,13 +57,17 @@ func imageInspectToRuntimeAPIImage(image *dockertypes.ImageInspect) (*runtimeapi ...@@ -57,13 +57,17 @@ func imageInspectToRuntimeAPIImage(image *dockertypes.ImageInspect) (*runtimeapi
size := uint64(image.VirtualSize) size := uint64(image.VirtualSize)
runtimeImage := &runtimeapi.Image{ runtimeImage := &runtimeapi.Image{
Id: &image.ID, Id: image.ID,
RepoTags: image.RepoTags, RepoTags: image.RepoTags,
RepoDigests: image.RepoDigests, RepoDigests: image.RepoDigests,
Size_: &size, Size_: size,
} }
runtimeImage.Uid, runtimeImage.Username = getUserFromImageUser(image.Config.User) uid, username := getUserFromImageUser(image.Config.User)
if uid != nil {
runtimeImage.Uid = &runtimeapi.Int64Value{Value: *uid}
}
runtimeImage.Username = username
return runtimeImage, nil return runtimeImage, nil
} }
...@@ -91,13 +95,13 @@ func toRuntimeAPIContainer(c *dockertypes.Container) (*runtimeapi.Container, err ...@@ -91,13 +95,13 @@ func toRuntimeAPIContainer(c *dockertypes.Container) (*runtimeapi.Container, err
// The timestamp in dockertypes.Container is in seconds. // The timestamp in dockertypes.Container is in seconds.
createdAt := c.Created * int64(time.Second) createdAt := c.Created * int64(time.Second)
return &runtimeapi.Container{ return &runtimeapi.Container{
Id: &c.ID, Id: c.ID,
PodSandboxId: &sandboxID, PodSandboxId: sandboxID,
Metadata: metadata, Metadata: metadata,
Image: &runtimeapi.ImageSpec{Image: &c.Image}, Image: &runtimeapi.ImageSpec{Image: c.Image},
ImageRef: &c.ImageID, ImageRef: c.ImageID,
State: &state, State: state,
CreatedAt: &createdAt, CreatedAt: createdAt,
Labels: labels, Labels: labels,
Annotations: annotations, Annotations: annotations,
}, nil }, nil
...@@ -157,10 +161,10 @@ func toRuntimeAPISandbox(c *dockertypes.Container) (*runtimeapi.PodSandbox, erro ...@@ -157,10 +161,10 @@ func toRuntimeAPISandbox(c *dockertypes.Container) (*runtimeapi.PodSandbox, erro
// The timestamp in dockertypes.Container is in seconds. // The timestamp in dockertypes.Container is in seconds.
createdAt := c.Created * int64(time.Second) createdAt := c.Created * int64(time.Second)
return &runtimeapi.PodSandbox{ return &runtimeapi.PodSandbox{
Id: &c.ID, Id: c.ID,
Metadata: metadata, Metadata: metadata,
State: &state, State: state,
CreatedAt: &createdAt, CreatedAt: createdAt,
Labels: labels, Labels: labels,
Annotations: annotations, Annotations: annotations,
}, nil }, nil
......
...@@ -42,14 +42,14 @@ func (ds *dockerService) ListContainers(filter *runtimeapi.ContainerFilter) ([]* ...@@ -42,14 +42,14 @@ func (ds *dockerService) ListContainers(filter *runtimeapi.ContainerFilter) ([]*
f.AddLabel(containerTypeLabelKey, containerTypeLabelContainer) f.AddLabel(containerTypeLabelKey, containerTypeLabelContainer)
if filter != nil { if filter != nil {
if filter.Id != nil { if filter.Id != "" {
f.Add("id", filter.GetId()) f.Add("id", filter.Id)
} }
if filter.State != nil { if filter.State != nil {
f.Add("status", toDockerContainerStatus(filter.GetState())) f.Add("status", toDockerContainerStatus(filter.GetState().State))
} }
if filter.PodSandboxId != nil { if filter.PodSandboxId != "" {
f.AddLabel(sandboxIDLabelKey, *filter.PodSandboxId) f.AddLabel(sandboxIDLabelKey, filter.PodSandboxId)
} }
if filter.LabelSelector != nil { if filter.LabelSelector != nil {
...@@ -87,35 +87,35 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi ...@@ -87,35 +87,35 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi
return "", fmt.Errorf("container config is nil") return "", fmt.Errorf("container config is nil")
} }
if sandboxConfig == nil { if sandboxConfig == nil {
return "", fmt.Errorf("sandbox config is nil for container %q", config.Metadata.GetName()) return "", fmt.Errorf("sandbox config is nil for container %q", config.Metadata.Name)
} }
labels := makeLabels(config.GetLabels(), config.GetAnnotations()) labels := makeLabels(config.GetLabels(), config.GetAnnotations())
// Apply a the container type label. // Apply a the container type label.
labels[containerTypeLabelKey] = containerTypeLabelContainer labels[containerTypeLabelKey] = containerTypeLabelContainer
// Write the container log path in the labels. // Write the container log path in the labels.
labels[containerLogPathLabelKey] = filepath.Join(sandboxConfig.GetLogDirectory(), config.GetLogPath()) labels[containerLogPathLabelKey] = filepath.Join(sandboxConfig.LogDirectory, config.LogPath)
// Write the sandbox ID in the labels. // Write the sandbox ID in the labels.
labels[sandboxIDLabelKey] = podSandboxID labels[sandboxIDLabelKey] = podSandboxID
image := "" image := ""
if iSpec := config.GetImage(); iSpec != nil { if iSpec := config.GetImage(); iSpec != nil {
image = iSpec.GetImage() image = iSpec.Image
} }
createConfig := dockertypes.ContainerCreateConfig{ createConfig := dockertypes.ContainerCreateConfig{
Name: makeContainerName(sandboxConfig, config), Name: makeContainerName(sandboxConfig, config),
Config: &dockercontainer.Config{ Config: &dockercontainer.Config{
// TODO: set User. // TODO: set User.
Entrypoint: dockerstrslice.StrSlice(config.GetCommand()), Entrypoint: dockerstrslice.StrSlice(config.Command),
Cmd: dockerstrslice.StrSlice(config.GetArgs()), Cmd: dockerstrslice.StrSlice(config.Args),
Env: generateEnvList(config.GetEnvs()), Env: generateEnvList(config.GetEnvs()),
Image: image, Image: image,
WorkingDir: config.GetWorkingDir(), WorkingDir: config.WorkingDir,
Labels: labels, Labels: labels,
// Interactive containers: // Interactive containers:
OpenStdin: config.GetStdin(), OpenStdin: config.Stdin,
StdinOnce: config.GetStdinOnce(), StdinOnce: config.StdinOnce,
Tty: config.GetTty(), Tty: config.Tty,
}, },
} }
...@@ -132,13 +132,13 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi ...@@ -132,13 +132,13 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi
rOpts := lc.GetResources() rOpts := lc.GetResources()
if rOpts != nil { if rOpts != nil {
hc.Resources = dockercontainer.Resources{ hc.Resources = dockercontainer.Resources{
Memory: rOpts.GetMemoryLimitInBytes(), Memory: rOpts.MemoryLimitInBytes,
MemorySwap: dockertools.DefaultMemorySwap(), MemorySwap: dockertools.DefaultMemorySwap(),
CPUShares: rOpts.GetCpuShares(), CPUShares: rOpts.CpuShares,
CPUQuota: rOpts.GetCpuQuota(), CPUQuota: rOpts.CpuQuota,
CPUPeriod: rOpts.GetCpuPeriod(), CPUPeriod: rOpts.CpuPeriod,
} }
hc.OomScoreAdj = int(rOpts.GetOomScoreAdj()) hc.OomScoreAdj = int(rOpts.OomScoreAdj)
} }
// Note: ShmSize is handled in kube_docker_client.go // Note: ShmSize is handled in kube_docker_client.go
...@@ -149,9 +149,9 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi ...@@ -149,9 +149,9 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi
// Apply cgroupsParent derived from the sandbox config. // Apply cgroupsParent derived from the sandbox config.
if lc := sandboxConfig.GetLinux(); lc != nil { if lc := sandboxConfig.GetLinux(); lc != nil {
// Apply Cgroup options. // Apply Cgroup options.
cgroupParent, err := ds.GenerateExpectedCgroupParent(lc.GetCgroupParent()) cgroupParent, err := ds.GenerateExpectedCgroupParent(lc.CgroupParent)
if err != nil { if err != nil {
return "", fmt.Errorf("failed to generate cgroup parent in expected syntax for container %q: %v", config.Metadata.GetName(), err) return "", fmt.Errorf("failed to generate cgroup parent in expected syntax for container %q: %v", config.Metadata.Name, err)
} }
hc.CgroupParent = cgroupParent hc.CgroupParent = cgroupParent
} }
...@@ -160,17 +160,17 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi ...@@ -160,17 +160,17 @@ func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeapi
devices := make([]dockercontainer.DeviceMapping, len(config.Devices)) devices := make([]dockercontainer.DeviceMapping, len(config.Devices))
for i, device := range config.Devices { for i, device := range config.Devices {
devices[i] = dockercontainer.DeviceMapping{ devices[i] = dockercontainer.DeviceMapping{
PathOnHost: device.GetHostPath(), PathOnHost: device.HostPath,
PathInContainer: device.GetContainerPath(), PathInContainer: device.ContainerPath,
CgroupPermissions: device.GetPermissions(), CgroupPermissions: device.Permissions,
} }
} }
hc.Resources.Devices = devices hc.Resources.Devices = devices
// Apply appArmor and seccomp options. // Apply appArmor and seccomp options.
securityOpts, err := getContainerSecurityOpts(config.Metadata.GetName(), sandboxConfig, ds.seccompProfileRoot) securityOpts, err := getContainerSecurityOpts(config.Metadata.Name, sandboxConfig, ds.seccompProfileRoot)
if err != nil { if err != nil {
return "", fmt.Errorf("failed to generate container security options for container %q: %v", config.Metadata.GetName(), err) return "", fmt.Errorf("failed to generate container security options for container %q: %v", config.Metadata.Name, err)
} }
hc.SecurityOpt = append(hc.SecurityOpt, securityOpts...) hc.SecurityOpt = append(hc.SecurityOpt, securityOpts...)
...@@ -310,9 +310,9 @@ func (ds *dockerService) ContainerStatus(containerID string) (*runtimeapi.Contai ...@@ -310,9 +310,9 @@ func (ds *dockerService) ContainerStatus(containerID string) (*runtimeapi.Contai
m := r.Mounts[i] m := r.Mounts[i]
readonly := !m.RW readonly := !m.RW
mounts = append(mounts, &runtimeapi.Mount{ mounts = append(mounts, &runtimeapi.Mount{
HostPath: &m.Source, HostPath: m.Source,
ContainerPath: &m.Destination, ContainerPath: m.Destination,
Readonly: &readonly, Readonly: readonly,
// Note: Can't set SeLinuxRelabel // Note: Can't set SeLinuxRelabel
}) })
} }
...@@ -369,18 +369,18 @@ func (ds *dockerService) ContainerStatus(containerID string) (*runtimeapi.Contai ...@@ -369,18 +369,18 @@ func (ds *dockerService) ContainerStatus(containerID string) (*runtimeapi.Contai
imageName = ir.RepoTags[0] imageName = ir.RepoTags[0]
} }
return &runtimeapi.ContainerStatus{ return &runtimeapi.ContainerStatus{
Id: &r.ID, Id: r.ID,
Metadata: metadata, Metadata: metadata,
Image: &runtimeapi.ImageSpec{Image: &imageName}, Image: &runtimeapi.ImageSpec{Image: imageName},
ImageRef: &imageID, ImageRef: imageID,
Mounts: mounts, Mounts: mounts,
ExitCode: &exitCode, ExitCode: exitCode,
State: &state, State: state,
CreatedAt: &ct, CreatedAt: ct,
StartedAt: &st, StartedAt: st,
FinishedAt: &ft, FinishedAt: ft,
Reason: &reason, Reason: reason,
Message: &message, Message: message,
Labels: labels, Labels: labels,
Annotations: annotations, Annotations: annotations,
}, nil }, nil
......
...@@ -32,10 +32,10 @@ import ( ...@@ -32,10 +32,10 @@ import (
func makeContainerConfig(sConfig *runtimeapi.PodSandboxConfig, name, image string, attempt uint32, labels, annotations map[string]string) *runtimeapi.ContainerConfig { func makeContainerConfig(sConfig *runtimeapi.PodSandboxConfig, name, image string, attempt uint32, labels, annotations map[string]string) *runtimeapi.ContainerConfig {
return &runtimeapi.ContainerConfig{ return &runtimeapi.ContainerConfig{
Metadata: &runtimeapi.ContainerMetadata{ Metadata: &runtimeapi.ContainerMetadata{
Name: &name, Name: name,
Attempt: &attempt, Attempt: attempt,
}, },
Image: &runtimeapi.ImageSpec{Image: &image}, Image: &runtimeapi.ImageSpec{Image: image},
Labels: labels, Labels: labels,
Annotations: annotations, Annotations: annotations,
} }
...@@ -77,12 +77,12 @@ func TestListContainers(t *testing.T) { ...@@ -77,12 +77,12 @@ func TestListContainers(t *testing.T) {
// the most recent containers first. // the most recent containers first.
expected = append([]*runtimeapi.Container{{ expected = append([]*runtimeapi.Container{{
Metadata: configs[i].Metadata, Metadata: configs[i].Metadata,
Id: &id, Id: id,
PodSandboxId: &sandboxID, PodSandboxId: sandboxID,
State: &state, State: state,
CreatedAt: &createdAt, CreatedAt: createdAt,
Image: configs[i].Image, Image: configs[i].Image,
ImageRef: &imageRef, ImageRef: imageRef,
Labels: configs[i].Labels, Labels: configs[i].Labels,
Annotations: configs[i].Annotations, Annotations: configs[i].Annotations,
}}, expected...) }}, expected...)
...@@ -112,16 +112,16 @@ func TestContainerStatus(t *testing.T) { ...@@ -112,16 +112,16 @@ func TestContainerStatus(t *testing.T) {
var reason, message string var reason, message string
expected := &runtimeapi.ContainerStatus{ expected := &runtimeapi.ContainerStatus{
State: &state, State: state,
CreatedAt: &ct, CreatedAt: ct,
StartedAt: &st, StartedAt: st,
FinishedAt: &ft, FinishedAt: ft,
Metadata: config.Metadata, Metadata: config.Metadata,
Image: config.Image, Image: config.Image,
ImageRef: &imageRef, ImageRef: imageRef,
ExitCode: &exitCode, ExitCode: exitCode,
Reason: &reason, Reason: reason,
Message: &message, Message: message,
Mounts: []*runtimeapi.Mount{}, Mounts: []*runtimeapi.Mount{},
Labels: config.Labels, Labels: config.Labels,
Annotations: config.Annotations, Annotations: config.Annotations,
...@@ -129,7 +129,7 @@ func TestContainerStatus(t *testing.T) { ...@@ -129,7 +129,7 @@ func TestContainerStatus(t *testing.T) {
// Create the container. // Create the container.
fClock.SetTime(time.Now().Add(-1 * time.Hour)) fClock.SetTime(time.Now().Add(-1 * time.Hour))
*expected.CreatedAt = fClock.Now().UnixNano() expected.CreatedAt = fClock.Now().UnixNano()
const sandboxId = "sandboxid" const sandboxId = "sandboxid"
id, err := ds.CreateContainer(sandboxId, config, sConfig) id, err := ds.CreateContainer(sandboxId, config, sConfig)
...@@ -140,7 +140,7 @@ func TestContainerStatus(t *testing.T) { ...@@ -140,7 +140,7 @@ func TestContainerStatus(t *testing.T) {
assert.Equal(t, c.Config.Labels[sandboxIDLabelKey], sandboxId) assert.Equal(t, c.Config.Labels[sandboxIDLabelKey], sandboxId)
// Set the id manually since we don't know the id until it's created. // Set the id manually since we don't know the id until it's created.
expected.Id = &id expected.Id = id
assert.NoError(t, err) assert.NoError(t, err)
status, err := ds.ContainerStatus(id) status, err := ds.ContainerStatus(id)
assert.NoError(t, err) assert.NoError(t, err)
...@@ -148,8 +148,8 @@ func TestContainerStatus(t *testing.T) { ...@@ -148,8 +148,8 @@ func TestContainerStatus(t *testing.T) {
// Advance the clock and start the container. // Advance the clock and start the container.
fClock.SetTime(time.Now()) fClock.SetTime(time.Now())
*expected.StartedAt = fClock.Now().UnixNano() expected.StartedAt = fClock.Now().UnixNano()
*expected.State = runtimeapi.ContainerState_CONTAINER_RUNNING expected.State = runtimeapi.ContainerState_CONTAINER_RUNNING
err = ds.StartContainer(id) err = ds.StartContainer(id)
assert.NoError(t, err) assert.NoError(t, err)
...@@ -158,9 +158,9 @@ func TestContainerStatus(t *testing.T) { ...@@ -158,9 +158,9 @@ func TestContainerStatus(t *testing.T) {
// Advance the clock and stop the container. // Advance the clock and stop the container.
fClock.SetTime(time.Now().Add(1 * time.Hour)) fClock.SetTime(time.Now().Add(1 * time.Hour))
*expected.FinishedAt = fClock.Now().UnixNano() expected.FinishedAt = fClock.Now().UnixNano()
*expected.State = runtimeapi.ContainerState_CONTAINER_EXITED expected.State = runtimeapi.ContainerState_CONTAINER_EXITED
*expected.Reason = "Completed" expected.Reason = "Completed"
err = ds.StopContainer(id, 0) err = ds.StopContainer(id, 0)
assert.NoError(t, err) assert.NoError(t, err)
...@@ -181,9 +181,9 @@ func TestContainerLogPath(t *testing.T) { ...@@ -181,9 +181,9 @@ func TestContainerLogPath(t *testing.T) {
containerLogPath := "0" containerLogPath := "0"
kubeletContainerLogPath := filepath.Join(podLogPath, containerLogPath) kubeletContainerLogPath := filepath.Join(podLogPath, containerLogPath)
sConfig := makeSandboxConfig("foo", "bar", "1", 0) sConfig := makeSandboxConfig("foo", "bar", "1", 0)
sConfig.LogDirectory = &podLogPath sConfig.LogDirectory = podLogPath
config := makeContainerConfig(sConfig, "pause", "iamimage", 0, nil, nil) config := makeContainerConfig(sConfig, "pause", "iamimage", 0, nil, nil)
config.LogPath = &containerLogPath config.LogPath = containerLogPath
const sandboxId = "sandboxid" const sandboxId = "sandboxid"
id, err := ds.CreateContainer(sandboxId, config, sConfig) id, err := ds.CreateContainer(sandboxId, config, sConfig)
......
...@@ -29,7 +29,7 @@ func (ds *dockerService) ListImages(filter *runtimeapi.ImageFilter) ([]*runtimea ...@@ -29,7 +29,7 @@ func (ds *dockerService) ListImages(filter *runtimeapi.ImageFilter) ([]*runtimea
opts := dockertypes.ImageListOptions{} opts := dockertypes.ImageListOptions{}
if filter != nil { if filter != nil {
if imgSpec := filter.GetImage(); imgSpec != nil { if imgSpec := filter.GetImage(); imgSpec != nil {
opts.MatchName = imgSpec.GetImage() opts.MatchName = imgSpec.Image
} }
} }
...@@ -52,7 +52,7 @@ func (ds *dockerService) ListImages(filter *runtimeapi.ImageFilter) ([]*runtimea ...@@ -52,7 +52,7 @@ func (ds *dockerService) ListImages(filter *runtimeapi.ImageFilter) ([]*runtimea
// ImageStatus returns the status of the image, returns nil if the image doesn't present. // ImageStatus returns the status of the image, returns nil if the image doesn't present.
func (ds *dockerService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimeapi.Image, error) { func (ds *dockerService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimeapi.Image, error) {
imageInspect, err := ds.client.InspectImageByRef(image.GetImage()) imageInspect, err := ds.client.InspectImageByRef(image.Image)
if err != nil { if err != nil {
if dockertools.IsImageNotFoundError(err) { if dockertools.IsImageNotFoundError(err) {
return nil, nil return nil, nil
...@@ -64,21 +64,23 @@ func (ds *dockerService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimeapi.I ...@@ -64,21 +64,23 @@ func (ds *dockerService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimeapi.I
// PullImage pulls an image with authentication config. // PullImage pulls an image with authentication config.
func (ds *dockerService) PullImage(image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig) (string, error) { func (ds *dockerService) PullImage(image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig) (string, error) {
err := ds.client.PullImage(image.GetImage(), authConfig := dockertypes.AuthConfig{}
dockertypes.AuthConfig{ if auth != nil {
Username: auth.GetUsername(), authConfig.Username = auth.Username
Password: auth.GetPassword(), authConfig.Password = auth.Password
ServerAddress: auth.GetServerAddress(), authConfig.ServerAddress = auth.ServerAddress
IdentityToken: auth.GetIdentityToken(), authConfig.IdentityToken = auth.IdentityToken
RegistryToken: auth.GetRegistryToken(), authConfig.RegistryToken = auth.RegistryToken
}, }
err := ds.client.PullImage(image.Image,
authConfig,
dockertypes.ImagePullOptions{}, dockertypes.ImagePullOptions{},
) )
if err != nil { if err != nil {
return "", err return "", err
} }
return dockertools.GetImageRef(ds.client, image.GetImage()) return dockertools.GetImageRef(ds.client, image.Image)
} }
// RemoveImage removes the image. // RemoveImage removes the image.
...@@ -86,7 +88,7 @@ func (ds *dockerService) RemoveImage(image *runtimeapi.ImageSpec) error { ...@@ -86,7 +88,7 @@ func (ds *dockerService) RemoveImage(image *runtimeapi.ImageSpec) error {
// If the image has multiple tags, we need to remove all the tags // If the image has multiple tags, we need to remove all the tags
// TODO: We assume image.Image is image ID here, which is true in the current implementation // TODO: We assume image.Image is image ID here, which is true in the current implementation
// of kubelet, but we should still clarify this in CRI. // of kubelet, but we should still clarify this in CRI.
imageInspect, err := ds.client.InspectImageByID(image.GetImage()) imageInspect, err := ds.client.InspectImageByID(image.Image)
if err == nil && imageInspect != nil && len(imageInspect.RepoTags) > 1 { if err == nil && imageInspect != nil && len(imageInspect.RepoTags) > 1 {
for _, tag := range imageInspect.RepoTags { for _, tag := range imageInspect.RepoTags {
if _, err := ds.client.RemoveImage(tag, dockertypes.ImageRemoveOptions{PruneChildren: true}); err != nil { if _, err := ds.client.RemoveImage(tag, dockertypes.ImageRemoveOptions{PruneChildren: true}); err != nil {
...@@ -96,6 +98,6 @@ func (ds *dockerService) RemoveImage(image *runtimeapi.ImageSpec) error { ...@@ -96,6 +98,6 @@ func (ds *dockerService) RemoveImage(image *runtimeapi.ImageSpec) error {
return nil return nil
} }
_, err = ds.client.RemoveImage(image.GetImage(), dockertypes.ImageRemoveOptions{PruneChildren: true}) _, err = ds.client.RemoveImage(image.Image, dockertypes.ImageRemoveOptions{PruneChildren: true})
return err return err
} }
...@@ -29,7 +29,7 @@ func TestRemoveImage(t *testing.T) { ...@@ -29,7 +29,7 @@ func TestRemoveImage(t *testing.T) {
ds, fakeDocker, _ := newTestDockerService() ds, fakeDocker, _ := newTestDockerService()
id := "1111" id := "1111"
fakeDocker.Image = &dockertypes.ImageInspect{ID: id, RepoTags: []string{"foo"}} fakeDocker.Image = &dockertypes.ImageInspect{ID: id, RepoTags: []string{"foo"}}
ds.RemoveImage(&runtimeapi.ImageSpec{Image: &id}) ds.RemoveImage(&runtimeapi.ImageSpec{Image: id})
fakeDocker.AssertCallDetails(dockertools.NewCalledDetail("inspect_image", nil), fakeDocker.AssertCallDetails(dockertools.NewCalledDetail("inspect_image", nil),
dockertools.NewCalledDetail("remove_image", []interface{}{id, dockertypes.ImageRemoveOptions{PruneChildren: true}})) dockertools.NewCalledDetail("remove_image", []interface{}{id, dockertypes.ImageRemoveOptions{PruneChildren: true}}))
} }
...@@ -38,7 +38,7 @@ func TestRemoveImageWithMultipleTags(t *testing.T) { ...@@ -38,7 +38,7 @@ func TestRemoveImageWithMultipleTags(t *testing.T) {
ds, fakeDocker, _ := newTestDockerService() ds, fakeDocker, _ := newTestDockerService()
id := "1111" id := "1111"
fakeDocker.Image = &dockertypes.ImageInspect{ID: id, RepoTags: []string{"foo", "bar"}} fakeDocker.Image = &dockertypes.ImageInspect{ID: id, RepoTags: []string{"foo", "bar"}}
ds.RemoveImage(&runtimeapi.ImageSpec{Image: &id}) ds.RemoveImage(&runtimeapi.ImageSpec{Image: id})
fakeDocker.AssertCallDetails(dockertools.NewCalledDetail("inspect_image", nil), fakeDocker.AssertCallDetails(dockertools.NewCalledDetail("inspect_image", nil),
dockertools.NewCalledDetail("remove_image", []interface{}{"foo", dockertypes.ImageRemoveOptions{PruneChildren: true}}), dockertools.NewCalledDetail("remove_image", []interface{}{"foo", dockertypes.ImageRemoveOptions{PruneChildren: true}}),
dockertools.NewCalledDetail("remove_image", []interface{}{"bar", dockertypes.ImageRemoveOptions{PruneChildren: true}})) dockertools.NewCalledDetail("remove_image", []interface{}{"bar", dockertypes.ImageRemoveOptions{PruneChildren: true}}))
......
...@@ -66,13 +66,13 @@ func (ds *dockerService) RunPodSandbox(config *runtimeapi.PodSandboxConfig) (str ...@@ -66,13 +66,13 @@ func (ds *dockerService) RunPodSandbox(config *runtimeapi.PodSandboxConfig) (str
// Step 2: Create the sandbox container. // Step 2: Create the sandbox container.
createConfig, err := ds.makeSandboxDockerConfig(config, image) createConfig, err := ds.makeSandboxDockerConfig(config, image)
if err != nil { if err != nil {
return "", fmt.Errorf("failed to make sandbox docker config for pod %q: %v", config.Metadata.GetName(), err) return "", fmt.Errorf("failed to make sandbox docker config for pod %q: %v", config.Metadata.Name, err)
} }
createResp, err := ds.client.CreateContainer(*createConfig) createResp, err := ds.client.CreateContainer(*createConfig)
recoverFromConflictIfNeeded(ds.client, err) recoverFromConflictIfNeeded(ds.client, err)
if err != nil || createResp == nil { if err != nil || createResp == nil {
return "", fmt.Errorf("failed to create a sandbox for pod %q: %v", config.Metadata.GetName(), err) return "", fmt.Errorf("failed to create a sandbox for pod %q: %v", config.Metadata.Name, err)
} }
// Step 3: Start the sandbox container. // Step 3: Start the sandbox container.
...@@ -80,9 +80,9 @@ func (ds *dockerService) RunPodSandbox(config *runtimeapi.PodSandboxConfig) (str ...@@ -80,9 +80,9 @@ func (ds *dockerService) RunPodSandbox(config *runtimeapi.PodSandboxConfig) (str
// startContainer failed. // startContainer failed.
err = ds.client.StartContainer(createResp.ID) err = ds.client.StartContainer(createResp.ID)
if err != nil { if err != nil {
return createResp.ID, fmt.Errorf("failed to start sandbox container for pod %q: %v", config.Metadata.GetName(), err) return createResp.ID, fmt.Errorf("failed to start sandbox container for pod %q: %v", config.Metadata.Name, err)
} }
if config.GetLinux().GetSecurityContext().GetNamespaceOptions().GetHostNetwork() { if nsOptions := config.GetLinux().GetSecurityContext().GetNamespaceOptions(); nsOptions != nil && nsOptions.HostNetwork {
return createResp.ID, nil return createResp.ID, nil
} }
...@@ -94,7 +94,7 @@ func (ds *dockerService) RunPodSandbox(config *runtimeapi.PodSandboxConfig) (str ...@@ -94,7 +94,7 @@ func (ds *dockerService) RunPodSandbox(config *runtimeapi.PodSandboxConfig) (str
// on the host as well, to satisfy parts of the pod spec that aren't // on the host as well, to satisfy parts of the pod spec that aren't
// recognized by the CNI standard yet. // recognized by the CNI standard yet.
cID := kubecontainer.BuildContainerID(runtimeName, createResp.ID) cID := kubecontainer.BuildContainerID(runtimeName, createResp.ID)
err = ds.networkPlugin.SetUpPod(config.GetMetadata().GetNamespace(), config.GetMetadata().GetName(), cID) err = ds.networkPlugin.SetUpPod(config.GetMetadata().Namespace, config.GetMetadata().Name, cID)
// TODO: Do we need to teardown on failure or can we rely on a StopPodSandbox call with the given ID? // TODO: Do we need to teardown on failure or can we rely on a StopPodSandbox call with the given ID?
return createResp.ID, err return createResp.ID, err
} }
...@@ -109,16 +109,16 @@ func (ds *dockerService) StopPodSandbox(podSandboxID string) error { ...@@ -109,16 +109,16 @@ func (ds *dockerService) StopPodSandbox(podSandboxID string) error {
if err != nil { if err != nil {
return fmt.Errorf("Failed to get sandbox status: %v", err) return fmt.Errorf("Failed to get sandbox status: %v", err)
} }
if !status.GetLinux().GetNamespaces().GetOptions().GetHostNetwork() { if nsOpts := status.GetLinux().GetNamespaces().GetOptions(); nsOpts != nil && !nsOpts.HostNetwork {
m := status.GetMetadata() m := status.GetMetadata()
cID := kubecontainer.BuildContainerID(runtimeName, podSandboxID) cID := kubecontainer.BuildContainerID(runtimeName, podSandboxID)
if err := ds.networkPlugin.TearDownPod(m.GetNamespace(), m.GetName(), cID); err != nil { if err := ds.networkPlugin.TearDownPod(m.Namespace, m.Name, cID); err != nil {
// TODO: Figure out a way to retry this error. We can't // TODO: Figure out a way to retry this error. We can't
// right now because the plugin throws errors when it doesn't find // right now because the plugin throws errors when it doesn't find
// eth0, which might not exist for various reasons (setup failed, // eth0, which might not exist for various reasons (setup failed,
// conf changed etc). In theory, it should teardown everything else // conf changed etc). In theory, it should teardown everything else
// so there's no need to retry. // so there's no need to retry.
glog.Errorf("Failed to teardown sandbox %v for pod %v/%v: %v", m.GetNamespace(), m.GetName(), podSandboxID, err) glog.Errorf("Failed to teardown sandbox %v for pod %v/%v: %v", m.Namespace, m.Name, podSandboxID, err)
} }
} }
return ds.client.StopContainer(podSandboxID, defaultSandboxGracePeriod) return ds.client.StopContainer(podSandboxID, defaultSandboxGracePeriod)
...@@ -138,12 +138,12 @@ func (ds *dockerService) getIPFromPlugin(sandbox *dockertypes.ContainerJSON) (st ...@@ -138,12 +138,12 @@ func (ds *dockerService) getIPFromPlugin(sandbox *dockertypes.ContainerJSON) (st
if err != nil { if err != nil {
return "", err return "", err
} }
msg := fmt.Sprintf("Couldn't find network status for %s/%s through plugin", *metadata.Namespace, *metadata.Name) msg := fmt.Sprintf("Couldn't find network status for %s/%s through plugin", metadata.Namespace, metadata.Name)
if sharesHostNetwork(sandbox) { if sharesHostNetwork(sandbox) {
return "", fmt.Errorf("%v: not responsible for host-network sandboxes", msg) return "", fmt.Errorf("%v: not responsible for host-network sandboxes", msg)
} }
cID := kubecontainer.BuildContainerID(runtimeName, sandbox.ID) cID := kubecontainer.BuildContainerID(runtimeName, sandbox.ID)
networkStatus, err := ds.networkPlugin.GetPodNetworkStatus(*metadata.Namespace, *metadata.Name, cID) networkStatus, err := ds.networkPlugin.GetPodNetworkStatus(metadata.Namespace, metadata.Name, cID)
if err != nil { if err != nil {
// This might be a sandbox that somehow ended up without a default // This might be a sandbox that somehow ended up without a default
// interface (eth0). We can't distinguish this from a more serious // interface (eth0). We can't distinguish this from a more serious
...@@ -203,7 +203,7 @@ func (ds *dockerService) PodSandboxStatus(podSandboxID string) (*runtimeapi.PodS ...@@ -203,7 +203,7 @@ func (ds *dockerService) PodSandboxStatus(podSandboxID string) (*runtimeapi.PodS
if err != nil { if err != nil {
return nil, err return nil, err
} }
network := &runtimeapi.PodSandboxNetworkStatus{Ip: &IP} network := &runtimeapi.PodSandboxNetworkStatus{Ip: IP}
netNS := getNetworkNamespace(r) netNS := getNetworkNamespace(r)
metadata, err := parseSandboxName(r.Name) metadata, err := parseSandboxName(r.Name)
...@@ -213,18 +213,18 @@ func (ds *dockerService) PodSandboxStatus(podSandboxID string) (*runtimeapi.PodS ...@@ -213,18 +213,18 @@ func (ds *dockerService) PodSandboxStatus(podSandboxID string) (*runtimeapi.PodS
hostNetwork := sharesHostNetwork(r) hostNetwork := sharesHostNetwork(r)
labels, annotations := extractLabels(r.Config.Labels) labels, annotations := extractLabels(r.Config.Labels)
return &runtimeapi.PodSandboxStatus{ return &runtimeapi.PodSandboxStatus{
Id: &r.ID, Id: r.ID,
State: &state, State: state,
CreatedAt: &ct, CreatedAt: ct,
Metadata: metadata, Metadata: metadata,
Labels: labels, Labels: labels,
Annotations: annotations, Annotations: annotations,
Network: network, Network: network,
Linux: &runtimeapi.LinuxPodSandboxStatus{ Linux: &runtimeapi.LinuxPodSandboxStatus{
Namespaces: &runtimeapi.Namespace{ Namespaces: &runtimeapi.Namespace{
Network: &netNS, Network: netNS,
Options: &runtimeapi.NamespaceOption{ Options: &runtimeapi.NamespaceOption{
HostNetwork: &hostNetwork, HostNetwork: hostNetwork,
}, },
}, },
}, },
...@@ -243,11 +243,11 @@ func (ds *dockerService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ([] ...@@ -243,11 +243,11 @@ func (ds *dockerService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ([]
f.AddLabel(containerTypeLabelKey, containerTypeLabelSandbox) f.AddLabel(containerTypeLabelKey, containerTypeLabelSandbox)
if filter != nil { if filter != nil {
if filter.Id != nil { if filter.Id != "" {
f.Add("id", filter.GetId()) f.Add("id", filter.Id)
} }
if filter.State != nil { if filter.State != nil {
if filter.GetState() == runtimeapi.PodSandboxState_SANDBOX_READY { if filter.GetState().State == runtimeapi.PodSandboxState_SANDBOX_READY {
// Only list running containers. // Only list running containers.
opts.All = false opts.All = false
} else { } else {
...@@ -280,7 +280,7 @@ func (ds *dockerService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ([] ...@@ -280,7 +280,7 @@ func (ds *dockerService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ([]
glog.V(4).Infof("Unable to convert docker to runtime API sandbox: %v", err) glog.V(4).Infof("Unable to convert docker to runtime API sandbox: %v", err)
continue continue
} }
if filterOutReadySandboxes && converted.GetState() == runtimeapi.PodSandboxState_SANDBOX_READY { if filterOutReadySandboxes && converted.State == runtimeapi.PodSandboxState_SANDBOX_READY {
continue continue
} }
...@@ -292,7 +292,7 @@ func (ds *dockerService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ([] ...@@ -292,7 +292,7 @@ func (ds *dockerService) ListPodSandbox(filter *runtimeapi.PodSandboxFilter) ([]
// applySandboxLinuxOptions applies LinuxPodSandboxConfig to dockercontainer.HostConfig and dockercontainer.ContainerCreateConfig. // applySandboxLinuxOptions applies LinuxPodSandboxConfig to dockercontainer.HostConfig and dockercontainer.ContainerCreateConfig.
func (ds *dockerService) applySandboxLinuxOptions(hc *dockercontainer.HostConfig, lc *runtimeapi.LinuxPodSandboxConfig, createConfig *dockertypes.ContainerCreateConfig, image string) error { func (ds *dockerService) applySandboxLinuxOptions(hc *dockercontainer.HostConfig, lc *runtimeapi.LinuxPodSandboxConfig, createConfig *dockertypes.ContainerCreateConfig, image string) error {
// Apply Cgroup options. // Apply Cgroup options.
cgroupParent, err := ds.GenerateExpectedCgroupParent(lc.GetCgroupParent()) cgroupParent, err := ds.GenerateExpectedCgroupParent(lc.CgroupParent)
if err != nil { if err != nil {
return err return err
} }
...@@ -317,7 +317,7 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig, ...@@ -317,7 +317,7 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig,
createConfig := &dockertypes.ContainerCreateConfig{ createConfig := &dockertypes.ContainerCreateConfig{
Name: makeSandboxName(c), Name: makeSandboxName(c),
Config: &dockercontainer.Config{ Config: &dockercontainer.Config{
Hostname: c.GetHostname(), Hostname: c.Hostname,
// TODO: Handle environment variables. // TODO: Handle environment variables.
Image: image, Image: image,
Labels: labels, Labels: labels,
...@@ -328,7 +328,7 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig, ...@@ -328,7 +328,7 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig,
// Set sysctls if requested // Set sysctls if requested
sysctls, err := getSysctlsFromAnnotations(c.Annotations) sysctls, err := getSysctlsFromAnnotations(c.Annotations)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get sysctls from annotations %v for sandbox %q: %v", c.Annotations, c.Metadata.GetName(), err) return nil, fmt.Errorf("failed to get sysctls from annotations %v for sandbox %q: %v", c.Annotations, c.Metadata.Name, err)
} }
hc.Sysctls = sysctls hc.Sysctls = sysctls
...@@ -346,9 +346,9 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig, ...@@ -346,9 +346,9 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig,
// Set DNS options. // Set DNS options.
if dnsConfig := c.GetDnsConfig(); dnsConfig != nil { if dnsConfig := c.GetDnsConfig(); dnsConfig != nil {
hc.DNS = dnsConfig.GetServers() hc.DNS = dnsConfig.Servers
hc.DNSSearch = dnsConfig.GetSearches() hc.DNSSearch = dnsConfig.Searches
hc.DNSOptions = dnsConfig.GetOptions() hc.DNSOptions = dnsConfig.Options
} }
// Apply resource options. // Apply resource options.
...@@ -357,7 +357,7 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig, ...@@ -357,7 +357,7 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig,
// Set security options. // Set security options.
securityOpts, err := getSandboxSecurityOpts(c, ds.seccompProfileRoot) securityOpts, err := getSandboxSecurityOpts(c, ds.seccompProfileRoot)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to generate sandbox security options for sandbox %q: %v", c.Metadata.GetName(), err) return nil, fmt.Errorf("failed to generate sandbox security options for sandbox %q: %v", c.Metadata.Name, err)
} }
hc.SecurityOpt = append(hc.SecurityOpt, securityOpts...) hc.SecurityOpt = append(hc.SecurityOpt, securityOpts...)
return createConfig, nil return createConfig, nil
......
...@@ -37,10 +37,10 @@ func makeSandboxConfig(name, namespace, uid string, attempt uint32) *runtimeapi. ...@@ -37,10 +37,10 @@ func makeSandboxConfig(name, namespace, uid string, attempt uint32) *runtimeapi.
func makeSandboxConfigWithLabelsAndAnnotations(name, namespace, uid string, attempt uint32, labels, annotations map[string]string) *runtimeapi.PodSandboxConfig { func makeSandboxConfigWithLabelsAndAnnotations(name, namespace, uid string, attempt uint32, labels, annotations map[string]string) *runtimeapi.PodSandboxConfig {
return &runtimeapi.PodSandboxConfig{ return &runtimeapi.PodSandboxConfig{
Metadata: &runtimeapi.PodSandboxMetadata{ Metadata: &runtimeapi.PodSandboxMetadata{
Name: &name, Name: name,
Namespace: &namespace, Namespace: namespace,
Uid: &uid, Uid: uid,
Attempt: &attempt, Attempt: attempt,
}, },
Labels: labels, Labels: labels,
Annotations: annotations, Annotations: annotations,
...@@ -72,9 +72,9 @@ func TestListSandboxes(t *testing.T) { ...@@ -72,9 +72,9 @@ func TestListSandboxes(t *testing.T) {
// the most recent sandbox first. // the most recent sandbox first.
expected = append([]*runtimeapi.PodSandbox{{ expected = append([]*runtimeapi.PodSandbox{{
Metadata: configs[i].Metadata, Metadata: configs[i].Metadata,
Id: &id, Id: id,
State: &state, State: state,
CreatedAt: &createdAt, CreatedAt: createdAt,
Labels: configs[i].Labels, Labels: configs[i].Labels,
Annotations: configs[i].Annotations, Annotations: configs[i].Annotations,
}}, expected...) }}, expected...)
...@@ -102,18 +102,18 @@ func TestSandboxStatus(t *testing.T) { ...@@ -102,18 +102,18 @@ func TestSandboxStatus(t *testing.T) {
ct := int64(0) ct := int64(0)
hostNetwork := false hostNetwork := false
expected := &runtimeapi.PodSandboxStatus{ expected := &runtimeapi.PodSandboxStatus{
State: &state, State: state,
CreatedAt: &ct, CreatedAt: ct,
Metadata: config.Metadata, Metadata: config.Metadata,
Network: &runtimeapi.PodSandboxNetworkStatus{Ip: &fakeIP}, Network: &runtimeapi.PodSandboxNetworkStatus{Ip: fakeIP},
Linux: &runtimeapi.LinuxPodSandboxStatus{Namespaces: &runtimeapi.Namespace{Network: &fakeNS, Options: &runtimeapi.NamespaceOption{HostNetwork: &hostNetwork}}}, Linux: &runtimeapi.LinuxPodSandboxStatus{Namespaces: &runtimeapi.Namespace{Network: fakeNS, Options: &runtimeapi.NamespaceOption{HostNetwork: hostNetwork}}},
Labels: labels, Labels: labels,
Annotations: annotations, Annotations: annotations,
} }
// Create the sandbox. // Create the sandbox.
fClock.SetTime(time.Now()) fClock.SetTime(time.Now())
*expected.CreatedAt = fClock.Now().UnixNano() expected.CreatedAt = fClock.Now().UnixNano()
id, err := ds.RunPodSandbox(config) id, err := ds.RunPodSandbox(config)
// Check internal labels // Check internal labels
...@@ -122,13 +122,13 @@ func TestSandboxStatus(t *testing.T) { ...@@ -122,13 +122,13 @@ func TestSandboxStatus(t *testing.T) {
assert.Equal(t, c.Config.Labels[containerTypeLabelKey], containerTypeLabelSandbox) assert.Equal(t, c.Config.Labels[containerTypeLabelKey], containerTypeLabelSandbox)
assert.Equal(t, c.Config.Labels[types.KubernetesContainerNameLabel], sandboxContainerName) assert.Equal(t, c.Config.Labels[types.KubernetesContainerNameLabel], sandboxContainerName)
expected.Id = &id // ID is only known after the creation. expected.Id = id // ID is only known after the creation.
status, err := ds.PodSandboxStatus(id) status, err := ds.PodSandboxStatus(id)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, status) assert.Equal(t, expected, status)
// Stop the sandbox. // Stop the sandbox.
*expected.State = runtimeapi.PodSandboxState_SANDBOX_NOTREADY expected.State = runtimeapi.PodSandboxState_SANDBOX_NOTREADY
err = ds.StopPodSandbox(id) err = ds.StopPodSandbox(id)
assert.NoError(t, err) assert.NoError(t, err)
status, err = ds.PodSandboxStatus(id) status, err = ds.PodSandboxStatus(id)
...@@ -189,7 +189,7 @@ func TestHostNetworkPluginInvocation(t *testing.T) { ...@@ -189,7 +189,7 @@ func TestHostNetworkPluginInvocation(t *testing.T) {
c.Linux = &runtimeapi.LinuxPodSandboxConfig{ c.Linux = &runtimeapi.LinuxPodSandboxConfig{
SecurityContext: &runtimeapi.LinuxSandboxSecurityContext{ SecurityContext: &runtimeapi.LinuxSandboxSecurityContext{
NamespaceOptions: &runtimeapi.NamespaceOption{ NamespaceOptions: &runtimeapi.NamespaceOption{
HostNetwork: &hostNetwork, HostNetwork: hostNetwork,
}, },
}, },
} }
......
...@@ -21,7 +21,6 @@ import ( ...@@ -21,7 +21,6 @@ import (
"net/http" "net/http"
"github.com/golang/glog" "github.com/golang/glog"
"github.com/golang/protobuf/proto"
"k8s.io/kubernetes/pkg/apis/componentconfig" "k8s.io/kubernetes/pkg/apis/componentconfig"
internalapi "k8s.io/kubernetes/pkg/kubelet/api" internalapi "k8s.io/kubernetes/pkg/kubelet/api"
...@@ -191,10 +190,10 @@ func (ds *dockerService) Version(_ string) (*runtimeapi.VersionResponse, error) ...@@ -191,10 +190,10 @@ func (ds *dockerService) Version(_ string) (*runtimeapi.VersionResponse, error)
// suffix to remedy this. // suffix to remedy this.
apiVersion := fmt.Sprintf("%s.0", v.APIVersion) apiVersion := fmt.Sprintf("%s.0", v.APIVersion)
return &runtimeapi.VersionResponse{ return &runtimeapi.VersionResponse{
Version: &runtimeAPIVersion, Version: runtimeAPIVersion,
RuntimeName: &name, RuntimeName: name,
RuntimeVersion: &v.Version, RuntimeVersion: v.Version,
RuntimeApiVersion: &apiVersion, RuntimeApiVersion: apiVersion,
}, nil }, nil
} }
...@@ -204,9 +203,9 @@ func (ds *dockerService) UpdateRuntimeConfig(runtimeConfig *runtimeapi.RuntimeCo ...@@ -204,9 +203,9 @@ func (ds *dockerService) UpdateRuntimeConfig(runtimeConfig *runtimeapi.RuntimeCo
return return
} }
glog.Infof("docker cri received runtime config %+v", runtimeConfig) glog.Infof("docker cri received runtime config %+v", runtimeConfig)
if ds.networkPlugin != nil && runtimeConfig.NetworkConfig.PodCidr != nil { if ds.networkPlugin != nil && runtimeConfig.NetworkConfig.PodCidr != "" {
event := make(map[string]interface{}) event := make(map[string]interface{})
event[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR] = *runtimeConfig.NetworkConfig.PodCidr event[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR] = runtimeConfig.NetworkConfig.PodCidr
ds.networkPlugin.Event(network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE, event) ds.networkPlugin.Event(network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE, event)
} }
return return
...@@ -246,23 +245,23 @@ func (ds *dockerService) Start() error { ...@@ -246,23 +245,23 @@ func (ds *dockerService) Start() error {
// TODO(random-liu): Set network condition accordingly here. // TODO(random-liu): Set network condition accordingly here.
func (ds *dockerService) Status() (*runtimeapi.RuntimeStatus, error) { func (ds *dockerService) Status() (*runtimeapi.RuntimeStatus, error) {
runtimeReady := &runtimeapi.RuntimeCondition{ runtimeReady := &runtimeapi.RuntimeCondition{
Type: proto.String(runtimeapi.RuntimeReady), Type: runtimeapi.RuntimeReady,
Status: proto.Bool(true), Status: true,
} }
networkReady := &runtimeapi.RuntimeCondition{ networkReady := &runtimeapi.RuntimeCondition{
Type: proto.String(runtimeapi.NetworkReady), Type: runtimeapi.NetworkReady,
Status: proto.Bool(true), Status: true,
} }
conditions := []*runtimeapi.RuntimeCondition{runtimeReady, networkReady} conditions := []*runtimeapi.RuntimeCondition{runtimeReady, networkReady}
if _, err := ds.client.Version(); err != nil { if _, err := ds.client.Version(); err != nil {
runtimeReady.Status = proto.Bool(false) runtimeReady.Status = false
runtimeReady.Reason = proto.String("DockerDaemonNotReady") runtimeReady.Reason = "DockerDaemonNotReady"
runtimeReady.Message = proto.String(fmt.Sprintf("docker: failed to get docker version: %v", err)) runtimeReady.Message = fmt.Sprintf("docker: failed to get docker version: %v", err)
} }
if err := ds.networkPlugin.Status(); err != nil { if err := ds.networkPlugin.Status(); err != nil {
networkReady.Status = proto.Bool(false) networkReady.Status = false
networkReady.Reason = proto.String("NetworkPluginNotReady") networkReady.Reason = "NetworkPluginNotReady"
networkReady.Message = proto.String(fmt.Sprintf("docker: network plugin is not ready: %v", err)) networkReady.Message = fmt.Sprintf("docker: network plugin is not ready: %v", err)
} }
return &runtimeapi.RuntimeStatus{Conditions: conditions}, nil return &runtimeapi.RuntimeStatus{Conditions: conditions}, nil
} }
......
...@@ -53,8 +53,8 @@ func TestStatus(t *testing.T) { ...@@ -53,8 +53,8 @@ func TestStatus(t *testing.T) {
assert.Equal(t, len(expected), len(conditions)) assert.Equal(t, len(expected), len(conditions))
for k, v := range expected { for k, v := range expected {
for _, c := range conditions { for _, c := range conditions {
if k == c.GetType() { if k == c.Type {
assert.Equal(t, v, c.GetStatus()) assert.Equal(t, v, c.Status)
} }
} }
} }
......
...@@ -86,7 +86,7 @@ func (ds *dockerService) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResp ...@@ -86,7 +86,7 @@ func (ds *dockerService) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResp
if ds.streamingServer == nil { if ds.streamingServer == nil {
return nil, streaming.ErrorStreamingDisabled("exec") return nil, streaming.ErrorStreamingDisabled("exec")
} }
_, err := checkContainerStatus(ds.client, req.GetContainerId()) _, err := checkContainerStatus(ds.client, req.ContainerId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -98,7 +98,7 @@ func (ds *dockerService) Attach(req *runtimeapi.AttachRequest) (*runtimeapi.Atta ...@@ -98,7 +98,7 @@ func (ds *dockerService) Attach(req *runtimeapi.AttachRequest) (*runtimeapi.Atta
if ds.streamingServer == nil { if ds.streamingServer == nil {
return nil, streaming.ErrorStreamingDisabled("attach") return nil, streaming.ErrorStreamingDisabled("attach")
} }
_, err := checkContainerStatus(ds.client, req.GetContainerId()) _, err := checkContainerStatus(ds.client, req.ContainerId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -110,7 +110,7 @@ func (ds *dockerService) PortForward(req *runtimeapi.PortForwardRequest) (*runti ...@@ -110,7 +110,7 @@ func (ds *dockerService) PortForward(req *runtimeapi.PortForwardRequest) (*runti
if ds.streamingServer == nil { if ds.streamingServer == nil {
return nil, streaming.ErrorStreamingDisabled("port forward") return nil, streaming.ErrorStreamingDisabled("port forward")
} }
_, err := checkContainerStatus(ds.client, req.GetPodSandboxId()) _, err := checkContainerStatus(ds.client, req.PodSandboxId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
......
...@@ -64,7 +64,7 @@ func (v apiVersion) Compare(other string) (int, error) { ...@@ -64,7 +64,7 @@ func (v apiVersion) Compare(other string) (int, error) {
// '<key>=<value>', which can be understood by docker. // '<key>=<value>', which can be understood by docker.
func generateEnvList(envs []*runtimeapi.KeyValue) (result []string) { func generateEnvList(envs []*runtimeapi.KeyValue) (result []string) {
for _, env := range envs { for _, env := range envs {
result = append(result, fmt.Sprintf("%s=%s", env.GetKey(), env.GetValue())) result = append(result, fmt.Sprintf("%s=%s", env.Key, env.Value))
} }
return return
} }
...@@ -129,8 +129,8 @@ func extractLabels(input map[string]string) (map[string]string, map[string]strin ...@@ -129,8 +129,8 @@ func extractLabels(input map[string]string) (map[string]string, map[string]strin
// relabeling and the pod provides an SELinux label // relabeling and the pod provides an SELinux label
func generateMountBindings(mounts []*runtimeapi.Mount) (result []string) { func generateMountBindings(mounts []*runtimeapi.Mount) (result []string) {
for _, m := range mounts { for _, m := range mounts {
bind := fmt.Sprintf("%s:%s", m.GetHostPath(), m.GetContainerPath()) bind := fmt.Sprintf("%s:%s", m.HostPath, m.ContainerPath)
readOnly := m.GetReadonly() readOnly := m.Readonly
if readOnly { if readOnly {
bind += ":ro" bind += ":ro"
} }
...@@ -138,7 +138,7 @@ func generateMountBindings(mounts []*runtimeapi.Mount) (result []string) { ...@@ -138,7 +138,7 @@ func generateMountBindings(mounts []*runtimeapi.Mount) (result []string) {
// does not provide an SELinux context relabeling will label the volume with // does not provide an SELinux context relabeling will label the volume with
// the container's randomly allocated MCS label. This would restrict access // the container's randomly allocated MCS label. This would restrict access
// to the volume to the container which mounts it first. // to the volume to the container which mounts it first.
if m.GetSelinuxRelabel() { if m.SelinuxRelabel {
if readOnly { if readOnly {
bind += ",Z" bind += ",Z"
} else { } else {
...@@ -154,16 +154,16 @@ func makePortsAndBindings(pm []*runtimeapi.PortMapping) (map[dockernat.Port]stru ...@@ -154,16 +154,16 @@ func makePortsAndBindings(pm []*runtimeapi.PortMapping) (map[dockernat.Port]stru
exposedPorts := map[dockernat.Port]struct{}{} exposedPorts := map[dockernat.Port]struct{}{}
portBindings := map[dockernat.Port][]dockernat.PortBinding{} portBindings := map[dockernat.Port][]dockernat.PortBinding{}
for _, port := range pm { for _, port := range pm {
exteriorPort := port.GetHostPort() exteriorPort := port.HostPort
if exteriorPort == 0 { if exteriorPort == 0 {
// No need to do port binding when HostPort is not specified // No need to do port binding when HostPort is not specified
continue continue
} }
interiorPort := port.GetContainerPort() interiorPort := port.ContainerPort
// Some of this port stuff is under-documented voodoo. // Some of this port stuff is under-documented voodoo.
// See http://stackoverflow.com/questions/20428302/binding-a-port-to-a-host-interface-using-the-rest-api // See http://stackoverflow.com/questions/20428302/binding-a-port-to-a-host-interface-using-the-rest-api
var protocol string var protocol string
switch strings.ToUpper(string(port.GetProtocol())) { switch strings.ToUpper(string(port.Protocol)) {
case "UDP": case "UDP":
protocol = "/udp" protocol = "/udp"
case "TCP": case "TCP":
...@@ -178,7 +178,7 @@ func makePortsAndBindings(pm []*runtimeapi.PortMapping) (map[dockernat.Port]stru ...@@ -178,7 +178,7 @@ func makePortsAndBindings(pm []*runtimeapi.PortMapping) (map[dockernat.Port]stru
hostBinding := dockernat.PortBinding{ hostBinding := dockernat.PortBinding{
HostPort: strconv.Itoa(int(exteriorPort)), HostPort: strconv.Itoa(int(exteriorPort)),
HostIP: port.GetHostIp(), HostIP: port.HostIp,
} }
// Allow multiple host ports bind to same docker port // Allow multiple host ports bind to same docker port
...@@ -272,20 +272,20 @@ func (f *dockerFilter) AddLabel(key, value string) { ...@@ -272,20 +272,20 @@ func (f *dockerFilter) AddLabel(key, value string) {
// getUserFromImageUser gets uid or user name of the image user. // getUserFromImageUser gets uid or user name of the image user.
// If user is numeric, it will be treated as uid; or else, it is treated as user name. // If user is numeric, it will be treated as uid; or else, it is treated as user name.
func getUserFromImageUser(imageUser string) (*int64, *string) { func getUserFromImageUser(imageUser string) (*int64, string) {
user := dockertools.GetUserFromImageUser(imageUser) user := dockertools.GetUserFromImageUser(imageUser)
// return both nil if user is not specified in the image. // return both nil if user is not specified in the image.
if user == "" { if user == "" {
return nil, nil return nil, ""
} }
// user could be either uid or user name. Try to interpret as numeric uid. // user could be either uid or user name. Try to interpret as numeric uid.
uid, err := strconv.ParseInt(user, 10, 64) uid, err := strconv.ParseInt(user, 10, 64)
if err != nil { if err != nil {
// If user is non numeric, assume it's user name. // If user is non numeric, assume it's user name.
return nil, &user return nil, user
} }
// If user is a numeric uid. // If user is a numeric uid.
return &uid, nil return &uid, ""
} }
// See #33189. If the previous attempt to create a sandbox container name FOO // See #33189. If the previous attempt to create a sandbox container name FOO
......
...@@ -192,11 +192,10 @@ func TestGetSystclsFromAnnotations(t *testing.T) { ...@@ -192,11 +192,10 @@ func TestGetSystclsFromAnnotations(t *testing.T) {
// TestGetUserFromImageUser tests the logic of getting image uid or user name of image user. // TestGetUserFromImageUser tests the logic of getting image uid or user name of image user.
func TestGetUserFromImageUser(t *testing.T) { func TestGetUserFromImageUser(t *testing.T) {
newI64 := func(i int64) *int64 { return &i } newI64 := func(i int64) *int64 { return &i }
newStr := func(s string) *string { return &s }
for c, test := range map[string]struct { for c, test := range map[string]struct {
user string user string
uid *int64 uid *int64
name *string name string
}{ }{
"no gid": { "no gid": {
user: "0", user: "0",
...@@ -215,11 +214,11 @@ func TestGetUserFromImageUser(t *testing.T) { ...@@ -215,11 +214,11 @@ func TestGetUserFromImageUser(t *testing.T) {
}, },
"root username": { "root username": {
user: "root:root", user: "root:root",
name: newStr("root"), name: "root",
}, },
"username": { "username": {
user: "test:test", user: "test:test",
name: newStr("test"), name: "test",
}, },
} { } {
t.Logf("TestCase - %q", c) t.Logf("TestCase - %q", c)
......
...@@ -57,23 +57,23 @@ const ( ...@@ -57,23 +57,23 @@ const (
func makeSandboxName(s *runtimeapi.PodSandboxConfig) string { func makeSandboxName(s *runtimeapi.PodSandboxConfig) string {
return strings.Join([]string{ return strings.Join([]string{
kubePrefix, // 0 kubePrefix, // 0
sandboxContainerName, // 1 sandboxContainerName, // 1
s.Metadata.GetName(), // 2 s.Metadata.Name, // 2
s.Metadata.GetNamespace(), // 3 s.Metadata.Namespace, // 3
s.Metadata.GetUid(), // 4 s.Metadata.Uid, // 4
fmt.Sprintf("%d", s.Metadata.GetAttempt()), // 5 fmt.Sprintf("%d", s.Metadata.Attempt), // 5
}, nameDelimiter) }, nameDelimiter)
} }
func makeContainerName(s *runtimeapi.PodSandboxConfig, c *runtimeapi.ContainerConfig) string { func makeContainerName(s *runtimeapi.PodSandboxConfig, c *runtimeapi.ContainerConfig) string {
return strings.Join([]string{ return strings.Join([]string{
kubePrefix, // 0 kubePrefix, // 0
c.Metadata.GetName(), // 1: c.Metadata.Name, // 1:
s.Metadata.GetName(), // 2: sandbox name s.Metadata.Name, // 2: sandbox name
s.Metadata.GetNamespace(), // 3: sandbox namesapce s.Metadata.Namespace, // 3: sandbox namesapce
s.Metadata.GetUid(), // 4 sandbox uid s.Metadata.Uid, // 4 sandbox uid
fmt.Sprintf("%d", c.Metadata.GetAttempt()), // 5 fmt.Sprintf("%d", c.Metadata.Attempt), // 5
}, nameDelimiter) }, nameDelimiter)
} }
...@@ -105,10 +105,10 @@ func parseSandboxName(name string) (*runtimeapi.PodSandboxMetadata, error) { ...@@ -105,10 +105,10 @@ func parseSandboxName(name string) (*runtimeapi.PodSandboxMetadata, error) {
} }
return &runtimeapi.PodSandboxMetadata{ return &runtimeapi.PodSandboxMetadata{
Name: &parts[2], Name: parts[2],
Namespace: &parts[3], Namespace: parts[3],
Uid: &parts[4], Uid: parts[4],
Attempt: &attempt, Attempt: attempt,
}, nil }, nil
} }
...@@ -131,7 +131,7 @@ func parseContainerName(name string) (*runtimeapi.ContainerMetadata, error) { ...@@ -131,7 +131,7 @@ func parseContainerName(name string) (*runtimeapi.ContainerMetadata, error) {
} }
return &runtimeapi.ContainerMetadata{ return &runtimeapi.ContainerMetadata{
Name: &parts[1], Name: parts[1],
Attempt: &attempt, Attempt: attempt,
}, nil }, nil
} }
...@@ -55,8 +55,8 @@ func TestContainerNameRoundTrip(t *testing.T) { ...@@ -55,8 +55,8 @@ func TestContainerNameRoundTrip(t *testing.T) {
name, attempt := "pause", uint32(5) name, attempt := "pause", uint32(5)
config := &runtimeapi.ContainerConfig{ config := &runtimeapi.ContainerConfig{
Metadata: &runtimeapi.ContainerMetadata{ Metadata: &runtimeapi.ContainerMetadata{
Name: &name, Name: name,
Attempt: &attempt, Attempt: attempt,
}, },
} }
actualName := makeContainerName(sConfig, config) actualName := makeContainerName(sConfig, config)
......
...@@ -47,7 +47,7 @@ func NewDockerService(s dockershim.DockerService) DockerService { ...@@ -47,7 +47,7 @@ func NewDockerService(s dockershim.DockerService) DockerService {
} }
func (d *dockerService) Version(ctx context.Context, r *runtimeapi.VersionRequest) (*runtimeapi.VersionResponse, error) { func (d *dockerService) Version(ctx context.Context, r *runtimeapi.VersionRequest) (*runtimeapi.VersionResponse, error) {
return d.runtimeService.Version(r.GetVersion()) return d.runtimeService.Version(r.Version)
} }
func (d *dockerService) Status(ctx context.Context, r *runtimeapi.StatusRequest) (*runtimeapi.StatusResponse, error) { func (d *dockerService) Status(ctx context.Context, r *runtimeapi.StatusRequest) (*runtimeapi.StatusResponse, error) {
...@@ -63,11 +63,11 @@ func (d *dockerService) RunPodSandbox(ctx context.Context, r *runtimeapi.RunPodS ...@@ -63,11 +63,11 @@ func (d *dockerService) RunPodSandbox(ctx context.Context, r *runtimeapi.RunPodS
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &runtimeapi.RunPodSandboxResponse{PodSandboxId: &podSandboxId}, nil return &runtimeapi.RunPodSandboxResponse{PodSandboxId: podSandboxId}, nil
} }
func (d *dockerService) StopPodSandbox(ctx context.Context, r *runtimeapi.StopPodSandboxRequest) (*runtimeapi.StopPodSandboxResponse, error) { func (d *dockerService) StopPodSandbox(ctx context.Context, r *runtimeapi.StopPodSandboxRequest) (*runtimeapi.StopPodSandboxResponse, error) {
err := d.runtimeService.StopPodSandbox(r.GetPodSandboxId()) err := d.runtimeService.StopPodSandbox(r.PodSandboxId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -75,7 +75,7 @@ func (d *dockerService) StopPodSandbox(ctx context.Context, r *runtimeapi.StopPo ...@@ -75,7 +75,7 @@ func (d *dockerService) StopPodSandbox(ctx context.Context, r *runtimeapi.StopPo
} }
func (d *dockerService) RemovePodSandbox(ctx context.Context, r *runtimeapi.RemovePodSandboxRequest) (*runtimeapi.RemovePodSandboxResponse, error) { func (d *dockerService) RemovePodSandbox(ctx context.Context, r *runtimeapi.RemovePodSandboxRequest) (*runtimeapi.RemovePodSandboxResponse, error) {
err := d.runtimeService.RemovePodSandbox(r.GetPodSandboxId()) err := d.runtimeService.RemovePodSandbox(r.PodSandboxId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -83,7 +83,7 @@ func (d *dockerService) RemovePodSandbox(ctx context.Context, r *runtimeapi.Remo ...@@ -83,7 +83,7 @@ func (d *dockerService) RemovePodSandbox(ctx context.Context, r *runtimeapi.Remo
} }
func (d *dockerService) PodSandboxStatus(ctx context.Context, r *runtimeapi.PodSandboxStatusRequest) (*runtimeapi.PodSandboxStatusResponse, error) { func (d *dockerService) PodSandboxStatus(ctx context.Context, r *runtimeapi.PodSandboxStatusRequest) (*runtimeapi.PodSandboxStatusResponse, error) {
podSandboxStatus, err := d.runtimeService.PodSandboxStatus(r.GetPodSandboxId()) podSandboxStatus, err := d.runtimeService.PodSandboxStatus(r.PodSandboxId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -99,15 +99,15 @@ func (d *dockerService) ListPodSandbox(ctx context.Context, r *runtimeapi.ListPo ...@@ -99,15 +99,15 @@ func (d *dockerService) ListPodSandbox(ctx context.Context, r *runtimeapi.ListPo
} }
func (d *dockerService) CreateContainer(ctx context.Context, r *runtimeapi.CreateContainerRequest) (*runtimeapi.CreateContainerResponse, error) { func (d *dockerService) CreateContainer(ctx context.Context, r *runtimeapi.CreateContainerRequest) (*runtimeapi.CreateContainerResponse, error) {
containerId, err := d.runtimeService.CreateContainer(r.GetPodSandboxId(), r.GetConfig(), r.GetSandboxConfig()) containerId, err := d.runtimeService.CreateContainer(r.PodSandboxId, r.GetConfig(), r.GetSandboxConfig())
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &runtimeapi.CreateContainerResponse{ContainerId: &containerId}, nil return &runtimeapi.CreateContainerResponse{ContainerId: containerId}, nil
} }
func (d *dockerService) StartContainer(ctx context.Context, r *runtimeapi.StartContainerRequest) (*runtimeapi.StartContainerResponse, error) { func (d *dockerService) StartContainer(ctx context.Context, r *runtimeapi.StartContainerRequest) (*runtimeapi.StartContainerResponse, error) {
err := d.runtimeService.StartContainer(r.GetContainerId()) err := d.runtimeService.StartContainer(r.ContainerId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -115,7 +115,7 @@ func (d *dockerService) StartContainer(ctx context.Context, r *runtimeapi.StartC ...@@ -115,7 +115,7 @@ func (d *dockerService) StartContainer(ctx context.Context, r *runtimeapi.StartC
} }
func (d *dockerService) StopContainer(ctx context.Context, r *runtimeapi.StopContainerRequest) (*runtimeapi.StopContainerResponse, error) { func (d *dockerService) StopContainer(ctx context.Context, r *runtimeapi.StopContainerRequest) (*runtimeapi.StopContainerResponse, error) {
err := d.runtimeService.StopContainer(r.GetContainerId(), r.GetTimeout()) err := d.runtimeService.StopContainer(r.ContainerId, r.Timeout)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -123,7 +123,7 @@ func (d *dockerService) StopContainer(ctx context.Context, r *runtimeapi.StopCon ...@@ -123,7 +123,7 @@ func (d *dockerService) StopContainer(ctx context.Context, r *runtimeapi.StopCon
} }
func (d *dockerService) RemoveContainer(ctx context.Context, r *runtimeapi.RemoveContainerRequest) (*runtimeapi.RemoveContainerResponse, error) { func (d *dockerService) RemoveContainer(ctx context.Context, r *runtimeapi.RemoveContainerRequest) (*runtimeapi.RemoveContainerResponse, error) {
err := d.runtimeService.RemoveContainer(r.GetContainerId()) err := d.runtimeService.RemoveContainer(r.ContainerId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -139,7 +139,7 @@ func (d *dockerService) ListContainers(ctx context.Context, r *runtimeapi.ListCo ...@@ -139,7 +139,7 @@ func (d *dockerService) ListContainers(ctx context.Context, r *runtimeapi.ListCo
} }
func (d *dockerService) ContainerStatus(ctx context.Context, r *runtimeapi.ContainerStatusRequest) (*runtimeapi.ContainerStatusResponse, error) { func (d *dockerService) ContainerStatus(ctx context.Context, r *runtimeapi.ContainerStatusRequest) (*runtimeapi.ContainerStatusResponse, error) {
status, err := d.runtimeService.ContainerStatus(r.GetContainerId()) status, err := d.runtimeService.ContainerStatus(r.ContainerId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -147,7 +147,7 @@ func (d *dockerService) ContainerStatus(ctx context.Context, r *runtimeapi.Conta ...@@ -147,7 +147,7 @@ func (d *dockerService) ContainerStatus(ctx context.Context, r *runtimeapi.Conta
} }
func (d *dockerService) ExecSync(ctx context.Context, r *runtimeapi.ExecSyncRequest) (*runtimeapi.ExecSyncResponse, error) { func (d *dockerService) ExecSync(ctx context.Context, r *runtimeapi.ExecSyncRequest) (*runtimeapi.ExecSyncResponse, error) {
stdout, stderr, err := d.runtimeService.ExecSync(r.GetContainerId(), r.GetCmd(), time.Duration(r.GetTimeout())*time.Second) stdout, stderr, err := d.runtimeService.ExecSync(r.ContainerId, r.Cmd, time.Duration(r.Timeout)*time.Second)
var exitCode int32 var exitCode int32
if err != nil { if err != nil {
exitError, ok := err.(utilexec.ExitError) exitError, ok := err.(utilexec.ExitError)
...@@ -159,7 +159,7 @@ func (d *dockerService) ExecSync(ctx context.Context, r *runtimeapi.ExecSyncRequ ...@@ -159,7 +159,7 @@ func (d *dockerService) ExecSync(ctx context.Context, r *runtimeapi.ExecSyncRequ
return &runtimeapi.ExecSyncResponse{ return &runtimeapi.ExecSyncResponse{
Stdout: stdout, Stdout: stdout,
Stderr: stderr, Stderr: stderr,
ExitCode: &exitCode, ExitCode: exitCode,
}, nil }, nil
} }
...@@ -204,7 +204,7 @@ func (d *dockerService) PullImage(ctx context.Context, r *runtimeapi.PullImageRe ...@@ -204,7 +204,7 @@ func (d *dockerService) PullImage(ctx context.Context, r *runtimeapi.PullImageRe
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &runtimeapi.PullImageResponse{ImageRef: &image}, nil return &runtimeapi.PullImageResponse{ImageRef: image}, nil
} }
func (d *dockerService) RemoveImage(ctx context.Context, r *runtimeapi.RemoveImageRequest) (*runtimeapi.RemoveImageResponse, error) { func (d *dockerService) RemoveImage(ctx context.Context, r *runtimeapi.RemoveImageRequest) (*runtimeapi.RemoveImageResponse, error) {
......
...@@ -69,10 +69,10 @@ func modifyContainerConfig(sc *runtimeapi.LinuxContainerSecurityContext, config ...@@ -69,10 +69,10 @@ func modifyContainerConfig(sc *runtimeapi.LinuxContainerSecurityContext, config
return return
} }
if sc.RunAsUser != nil { if sc.RunAsUser != nil {
config.User = strconv.FormatInt(sc.GetRunAsUser(), 10) config.User = strconv.FormatInt(sc.GetRunAsUser().Value, 10)
} }
if sc.RunAsUsername != nil { if sc.RunAsUsername != "" {
config.User = sc.GetRunAsUsername() config.User = sc.RunAsUsername
} }
} }
...@@ -88,24 +88,20 @@ func modifyHostConfig(sc *runtimeapi.LinuxContainerSecurityContext, hostConfig * ...@@ -88,24 +88,20 @@ func modifyHostConfig(sc *runtimeapi.LinuxContainerSecurityContext, hostConfig *
} }
// Apply security context for the container. // Apply security context for the container.
if sc.Privileged != nil { hostConfig.Privileged = sc.Privileged
hostConfig.Privileged = sc.GetPrivileged() hostConfig.ReadonlyRootfs = sc.ReadonlyRootfs
}
if sc.ReadonlyRootfs != nil {
hostConfig.ReadonlyRootfs = sc.GetReadonlyRootfs()
}
if sc.Capabilities != nil { if sc.Capabilities != nil {
hostConfig.CapAdd = sc.GetCapabilities().GetAddCapabilities() hostConfig.CapAdd = sc.GetCapabilities().AddCapabilities
hostConfig.CapDrop = sc.GetCapabilities().GetDropCapabilities() hostConfig.CapDrop = sc.GetCapabilities().DropCapabilities
} }
if sc.SelinuxOptions != nil { if sc.SelinuxOptions != nil {
hostConfig.SecurityOpt = securitycontext.ModifySecurityOptions( hostConfig.SecurityOpt = securitycontext.ModifySecurityOptions(
hostConfig.SecurityOpt, hostConfig.SecurityOpt,
&v1.SELinuxOptions{ &v1.SELinuxOptions{
User: sc.SelinuxOptions.GetUser(), User: sc.SelinuxOptions.User,
Role: sc.SelinuxOptions.GetRole(), Role: sc.SelinuxOptions.Role,
Type: sc.SelinuxOptions.GetType(), Type: sc.SelinuxOptions.Type,
Level: sc.SelinuxOptions.GetLevel(), Level: sc.SelinuxOptions.Level,
}, },
) )
} }
...@@ -114,22 +110,26 @@ func modifyHostConfig(sc *runtimeapi.LinuxContainerSecurityContext, hostConfig * ...@@ -114,22 +110,26 @@ func modifyHostConfig(sc *runtimeapi.LinuxContainerSecurityContext, hostConfig *
// modifySandboxNamespaceOptions apply namespace options for sandbox // modifySandboxNamespaceOptions apply namespace options for sandbox
func modifySandboxNamespaceOptions(nsOpts *runtimeapi.NamespaceOption, hostConfig *dockercontainer.HostConfig, networkPlugin network.NetworkPlugin) { func modifySandboxNamespaceOptions(nsOpts *runtimeapi.NamespaceOption, hostConfig *dockercontainer.HostConfig, networkPlugin network.NetworkPlugin) {
modifyCommonNamespaceOptions(nsOpts, hostConfig) modifyCommonNamespaceOptions(nsOpts, hostConfig)
modifyHostNetworkOptionForSandbox(nsOpts.GetHostNetwork(), networkPlugin, hostConfig) modifyHostNetworkOptionForSandbox(nsOpts.HostNetwork, networkPlugin, hostConfig)
} }
// modifyContainerNamespaceOptions apply namespace options for container // modifyContainerNamespaceOptions apply namespace options for container
func modifyContainerNamespaceOptions(nsOpts *runtimeapi.NamespaceOption, sandboxID string, hostConfig *dockercontainer.HostConfig) { func modifyContainerNamespaceOptions(nsOpts *runtimeapi.NamespaceOption, sandboxID string, hostConfig *dockercontainer.HostConfig) {
hostNetwork := false
if nsOpts != nil {
hostNetwork = nsOpts.HostNetwork
}
modifyCommonNamespaceOptions(nsOpts, hostConfig) modifyCommonNamespaceOptions(nsOpts, hostConfig)
modifyHostNetworkOptionForContainer(nsOpts.GetHostNetwork(), sandboxID, hostConfig) modifyHostNetworkOptionForContainer(hostNetwork, sandboxID, hostConfig)
} }
// modifyCommonNamespaceOptions apply common namespace options for sandbox and container // modifyCommonNamespaceOptions apply common namespace options for sandbox and container
func modifyCommonNamespaceOptions(nsOpts *runtimeapi.NamespaceOption, hostConfig *dockercontainer.HostConfig) { func modifyCommonNamespaceOptions(nsOpts *runtimeapi.NamespaceOption, hostConfig *dockercontainer.HostConfig) {
if nsOpts != nil { if nsOpts != nil {
if nsOpts.GetHostPid() { if nsOpts.HostPid {
hostConfig.PidMode = namespaceModeHost hostConfig.PidMode = namespaceModeHost
} }
if nsOpts.GetHostIpc() { if nsOpts.HostIpc {
hostConfig.IpcMode = namespaceModeHost hostConfig.IpcMode = namespaceModeHost
} }
} }
......
...@@ -30,7 +30,7 @@ import ( ...@@ -30,7 +30,7 @@ import (
func TestModifyContainerConfig(t *testing.T) { func TestModifyContainerConfig(t *testing.T) {
var uid int64 = 123 var uid int64 = 123
var username string = "testuser" var username = "testuser"
cases := []struct { cases := []struct {
name string name string
...@@ -40,7 +40,7 @@ func TestModifyContainerConfig(t *testing.T) { ...@@ -40,7 +40,7 @@ func TestModifyContainerConfig(t *testing.T) {
{ {
name: "container.SecurityContext.RunAsUser set", name: "container.SecurityContext.RunAsUser set",
sc: &runtimeapi.LinuxContainerSecurityContext{ sc: &runtimeapi.LinuxContainerSecurityContext{
RunAsUser: &uid, RunAsUser: &runtimeapi.Int64Value{Value: uid},
}, },
expected: &dockercontainer.Config{ expected: &dockercontainer.Config{
User: strconv.FormatInt(uid, 10), User: strconv.FormatInt(uid, 10),
...@@ -49,7 +49,7 @@ func TestModifyContainerConfig(t *testing.T) { ...@@ -49,7 +49,7 @@ func TestModifyContainerConfig(t *testing.T) {
{ {
name: "container.SecurityContext.RunAsUsername set", name: "container.SecurityContext.RunAsUsername set",
sc: &runtimeapi.LinuxContainerSecurityContext{ sc: &runtimeapi.LinuxContainerSecurityContext{
RunAsUsername: &username, RunAsUsername: username,
}, },
expected: &dockercontainer.Config{ expected: &dockercontainer.Config{
User: username, User: username,
...@@ -70,10 +70,9 @@ func TestModifyContainerConfig(t *testing.T) { ...@@ -70,10 +70,9 @@ func TestModifyContainerConfig(t *testing.T) {
} }
func TestModifyHostConfig(t *testing.T) { func TestModifyHostConfig(t *testing.T) {
priv := true
setNetworkHC := &dockercontainer.HostConfig{} setNetworkHC := &dockercontainer.HostConfig{}
setPrivSC := &runtimeapi.LinuxContainerSecurityContext{} setPrivSC := &runtimeapi.LinuxContainerSecurityContext{}
setPrivSC.Privileged = &priv setPrivSC.Privileged = true
setPrivHC := &dockercontainer.HostConfig{ setPrivHC := &dockercontainer.HostConfig{
Privileged: true, Privileged: true,
} }
...@@ -168,7 +167,7 @@ func TestModifyHostConfigAndNamespaceOptionsForContainer(t *testing.T) { ...@@ -168,7 +167,7 @@ func TestModifyHostConfigAndNamespaceOptionsForContainer(t *testing.T) {
sandboxID := "sandbox" sandboxID := "sandbox"
sandboxNSMode := fmt.Sprintf("container:%v", sandboxID) sandboxNSMode := fmt.Sprintf("container:%v", sandboxID)
setPrivSC := &runtimeapi.LinuxContainerSecurityContext{} setPrivSC := &runtimeapi.LinuxContainerSecurityContext{}
setPrivSC.Privileged = &priv setPrivSC.Privileged = priv
setPrivHC := &dockercontainer.HostConfig{ setPrivHC := &dockercontainer.HostConfig{
Privileged: true, Privileged: true,
IpcMode: dockercontainer.IpcMode(sandboxNSMode), IpcMode: dockercontainer.IpcMode(sandboxNSMode),
...@@ -235,7 +234,7 @@ func TestModifySandboxNamespaceOptions(t *testing.T) { ...@@ -235,7 +234,7 @@ func TestModifySandboxNamespaceOptions(t *testing.T) {
{ {
name: "NamespaceOption.HostNetwork", name: "NamespaceOption.HostNetwork",
nsOpt: &runtimeapi.NamespaceOption{ nsOpt: &runtimeapi.NamespaceOption{
HostNetwork: &set, HostNetwork: set,
}, },
expected: &dockercontainer.HostConfig{ expected: &dockercontainer.HostConfig{
NetworkMode: namespaceModeHost, NetworkMode: namespaceModeHost,
...@@ -244,7 +243,7 @@ func TestModifySandboxNamespaceOptions(t *testing.T) { ...@@ -244,7 +243,7 @@ func TestModifySandboxNamespaceOptions(t *testing.T) {
{ {
name: "NamespaceOption.HostIpc", name: "NamespaceOption.HostIpc",
nsOpt: &runtimeapi.NamespaceOption{ nsOpt: &runtimeapi.NamespaceOption{
HostIpc: &set, HostIpc: set,
}, },
expected: &dockercontainer.HostConfig{ expected: &dockercontainer.HostConfig{
IpcMode: namespaceModeHost, IpcMode: namespaceModeHost,
...@@ -254,7 +253,7 @@ func TestModifySandboxNamespaceOptions(t *testing.T) { ...@@ -254,7 +253,7 @@ func TestModifySandboxNamespaceOptions(t *testing.T) {
{ {
name: "NamespaceOption.HostPid", name: "NamespaceOption.HostPid",
nsOpt: &runtimeapi.NamespaceOption{ nsOpt: &runtimeapi.NamespaceOption{
HostPid: &set, HostPid: set,
}, },
expected: &dockercontainer.HostConfig{ expected: &dockercontainer.HostConfig{
PidMode: namespaceModeHost, PidMode: namespaceModeHost,
...@@ -281,7 +280,7 @@ func TestModifyContainerNamespaceOptions(t *testing.T) { ...@@ -281,7 +280,7 @@ func TestModifyContainerNamespaceOptions(t *testing.T) {
{ {
name: "NamespaceOption.HostNetwork", name: "NamespaceOption.HostNetwork",
nsOpt: &runtimeapi.NamespaceOption{ nsOpt: &runtimeapi.NamespaceOption{
HostNetwork: &set, HostNetwork: set,
}, },
expected: &dockercontainer.HostConfig{ expected: &dockercontainer.HostConfig{
NetworkMode: dockercontainer.NetworkMode(sandboxNSMode), NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
...@@ -292,7 +291,7 @@ func TestModifyContainerNamespaceOptions(t *testing.T) { ...@@ -292,7 +291,7 @@ func TestModifyContainerNamespaceOptions(t *testing.T) {
{ {
name: "NamespaceOption.HostIpc", name: "NamespaceOption.HostIpc",
nsOpt: &runtimeapi.NamespaceOption{ nsOpt: &runtimeapi.NamespaceOption{
HostIpc: &set, HostIpc: set,
}, },
expected: &dockercontainer.HostConfig{ expected: &dockercontainer.HostConfig{
NetworkMode: dockercontainer.NetworkMode(sandboxNSMode), NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
...@@ -302,7 +301,7 @@ func TestModifyContainerNamespaceOptions(t *testing.T) { ...@@ -302,7 +301,7 @@ func TestModifyContainerNamespaceOptions(t *testing.T) {
{ {
name: "NamespaceOption.HostPid", name: "NamespaceOption.HostPid",
nsOpt: &runtimeapi.NamespaceOption{ nsOpt: &runtimeapi.NamespaceOption{
HostPid: &set, HostPid: set,
}, },
expected: &dockercontainer.HostConfig{ expected: &dockercontainer.HostConfig{
NetworkMode: dockercontainer.NetworkMode(sandboxNSMode), NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
...@@ -318,9 +317,8 @@ func TestModifyContainerNamespaceOptions(t *testing.T) { ...@@ -318,9 +317,8 @@ func TestModifyContainerNamespaceOptions(t *testing.T) {
} }
func fullValidSecurityContext() *runtimeapi.LinuxContainerSecurityContext { func fullValidSecurityContext() *runtimeapi.LinuxContainerSecurityContext {
priv := true
return &runtimeapi.LinuxContainerSecurityContext{ return &runtimeapi.LinuxContainerSecurityContext{
Privileged: &priv, Privileged: true,
Capabilities: inputCapabilities(), Capabilities: inputCapabilities(),
SelinuxOptions: inputSELinuxOptions(), SelinuxOptions: inputSELinuxOptions(),
} }
...@@ -340,10 +338,10 @@ func inputSELinuxOptions() *runtimeapi.SELinuxOption { ...@@ -340,10 +338,10 @@ func inputSELinuxOptions() *runtimeapi.SELinuxOption {
level := "level" level := "level"
return &runtimeapi.SELinuxOption{ return &runtimeapi.SELinuxOption{
User: &user, User: user,
Role: &role, Role: role,
Type: &stype, Type: stype,
Level: &level, Level: level,
} }
} }
......
...@@ -113,7 +113,7 @@ func NewFakeKubeRuntimeManager(runtimeService internalapi.RuntimeService, imageS ...@@ -113,7 +113,7 @@ func NewFakeKubeRuntimeManager(runtimeService internalapi.RuntimeService, imageS
} }
kubeRuntimeManager.containerGC = NewContainerGC(runtimeService, newFakePodGetter(), kubeRuntimeManager) kubeRuntimeManager.containerGC = NewContainerGC(runtimeService, newFakePodGetter(), kubeRuntimeManager)
kubeRuntimeManager.runtimeName = typedVersion.GetRuntimeName() kubeRuntimeManager.runtimeName = typedVersion.RuntimeName
kubeRuntimeManager.imagePuller = images.NewImageManager( kubeRuntimeManager.imagePuller = images.NewImageManager(
kubecontainer.FilterEventRecorder(recorder), kubecontainer.FilterEventRecorder(recorder),
kubeRuntimeManager, kubeRuntimeManager,
......
...@@ -61,7 +61,7 @@ type podSandboxByCreated []*runtimeapi.PodSandbox ...@@ -61,7 +61,7 @@ type podSandboxByCreated []*runtimeapi.PodSandbox
func (p podSandboxByCreated) Len() int { return len(p) } func (p podSandboxByCreated) Len() int { return len(p) }
func (p podSandboxByCreated) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p podSandboxByCreated) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p podSandboxByCreated) Less(i, j int) bool { return p[i].GetCreatedAt() > p[j].GetCreatedAt() } func (p podSandboxByCreated) Less(i, j int) bool { return p[i].CreatedAt > p[j].CreatedAt }
type containerStatusByCreated []*kubecontainer.ContainerStatus type containerStatusByCreated []*kubecontainer.ContainerStatus
...@@ -100,18 +100,18 @@ func toRuntimeProtocol(protocol v1.Protocol) runtimeapi.Protocol { ...@@ -100,18 +100,18 @@ func toRuntimeProtocol(protocol v1.Protocol) runtimeapi.Protocol {
// toKubeContainer converts runtimeapi.Container to kubecontainer.Container. // toKubeContainer converts runtimeapi.Container to kubecontainer.Container.
func (m *kubeGenericRuntimeManager) toKubeContainer(c *runtimeapi.Container) (*kubecontainer.Container, error) { func (m *kubeGenericRuntimeManager) toKubeContainer(c *runtimeapi.Container) (*kubecontainer.Container, error) {
if c == nil || c.Id == nil || c.Image == nil || c.State == nil { if c == nil || c.Id == "" || c.Image == nil {
return nil, fmt.Errorf("unable to convert a nil pointer to a runtime container") return nil, fmt.Errorf("unable to convert a nil pointer to a runtime container")
} }
labeledInfo := getContainerInfoFromLabels(c.Labels) labeledInfo := getContainerInfoFromLabels(c.Labels)
annotatedInfo := getContainerInfoFromAnnotations(c.Annotations) annotatedInfo := getContainerInfoFromAnnotations(c.Annotations)
return &kubecontainer.Container{ return &kubecontainer.Container{
ID: kubecontainer.ContainerID{Type: m.runtimeName, ID: c.GetId()}, ID: kubecontainer.ContainerID{Type: m.runtimeName, ID: c.Id},
Name: labeledInfo.ContainerName, Name: labeledInfo.ContainerName,
Image: c.Image.GetImage(), Image: c.Image.Image,
Hash: annotatedInfo.Hash, Hash: annotatedInfo.Hash,
State: toKubeContainerState(c.GetState()), State: toKubeContainerState(c.State),
}, nil }, nil
} }
...@@ -120,34 +120,36 @@ func (m *kubeGenericRuntimeManager) toKubeContainer(c *runtimeapi.Container) (*k ...@@ -120,34 +120,36 @@ func (m *kubeGenericRuntimeManager) toKubeContainer(c *runtimeapi.Container) (*k
// kubecontainer.Containers to avoid substantial changes to PLEG. // kubecontainer.Containers to avoid substantial changes to PLEG.
// TODO: Remove this once it becomes obsolete. // TODO: Remove this once it becomes obsolete.
func (m *kubeGenericRuntimeManager) sandboxToKubeContainer(s *runtimeapi.PodSandbox) (*kubecontainer.Container, error) { func (m *kubeGenericRuntimeManager) sandboxToKubeContainer(s *runtimeapi.PodSandbox) (*kubecontainer.Container, error) {
if s == nil || s.Id == nil || s.State == nil { if s == nil || s.Id == "" {
return nil, fmt.Errorf("unable to convert a nil pointer to a runtime container") return nil, fmt.Errorf("unable to convert a nil pointer to a runtime container")
} }
return &kubecontainer.Container{ return &kubecontainer.Container{
ID: kubecontainer.ContainerID{Type: m.runtimeName, ID: s.GetId()}, ID: kubecontainer.ContainerID{Type: m.runtimeName, ID: s.Id},
State: kubecontainer.SandboxToContainerState(s.GetState()), State: kubecontainer.SandboxToContainerState(s.State),
}, nil }, nil
} }
// getImageUser gets uid or user name that will run the command(s) from image. The function // getImageUser gets uid or user name that will run the command(s) from image. The function
// guarantees that only one of them is set. // guarantees that only one of them is set.
func (m *kubeGenericRuntimeManager) getImageUser(image string) (*int64, *string, error) { func (m *kubeGenericRuntimeManager) getImageUser(image string) (*int64, string, error) {
imageStatus, err := m.imageService.ImageStatus(&runtimeapi.ImageSpec{Image: &image}) imageStatus, err := m.imageService.ImageStatus(&runtimeapi.ImageSpec{Image: image})
if err != nil { if err != nil {
return nil, nil, err return nil, "", err
} }
if imageStatus != nil && imageStatus.Uid != nil { if imageStatus != nil {
// If uid is set, return uid. if imageStatus.Uid != nil {
return imageStatus.Uid, nil, nil return &imageStatus.GetUid().Value, "", nil
} }
if imageStatus != nil && imageStatus.Username != nil {
// If uid is not set, but user name is set, return user name. if imageStatus.Username != "" {
return nil, imageStatus.Username, nil return nil, imageStatus.Username, nil
}
} }
// If non of them is set, treat it as root. // If non of them is set, treat it as root.
return new(int64), nil, nil return new(int64), "", nil
} }
// isContainerFailed returns true if container has exited and exitcode is not zero. // isContainerFailed returns true if container has exited and exitcode is not zero.
...@@ -226,10 +228,10 @@ func toKubeRuntimeStatus(status *runtimeapi.RuntimeStatus) *kubecontainer.Runtim ...@@ -226,10 +228,10 @@ func toKubeRuntimeStatus(status *runtimeapi.RuntimeStatus) *kubecontainer.Runtim
conditions := []kubecontainer.RuntimeCondition{} conditions := []kubecontainer.RuntimeCondition{}
for _, c := range status.GetConditions() { for _, c := range status.GetConditions() {
conditions = append(conditions, kubecontainer.RuntimeCondition{ conditions = append(conditions, kubecontainer.RuntimeCondition{
Type: kubecontainer.RuntimeConditionType(c.GetType()), Type: kubecontainer.RuntimeConditionType(c.Type),
Status: c.GetStatus(), Status: c.Status,
Reason: c.GetReason(), Reason: c.Reason,
Message: c.GetMessage(), Message: c.Message,
}) })
} }
return &kubecontainer.RuntimeStatus{Conditions: conditions} return &kubecontainer.RuntimeStatus{Conditions: conditions}
......
...@@ -51,7 +51,7 @@ func TestRemoveContainer(t *testing.T) { ...@@ -51,7 +51,7 @@ func TestRemoveContainer(t *testing.T) {
_, fakeContainers := makeAndSetFakePod(t, m, fakeRuntime, pod) _, fakeContainers := makeAndSetFakePod(t, m, fakeRuntime, pod)
assert.Equal(t, len(fakeContainers), 1) assert.Equal(t, len(fakeContainers), 1)
containerId := fakeContainers[0].GetId() containerId := fakeContainers[0].Id
fakeOS := m.osInterface.(*containertest.FakeOS) fakeOS := m.osInterface.(*containertest.FakeOS)
err = m.removeContainer(containerId) err = m.removeContainer(containerId)
assert.NoError(t, err) assert.NoError(t, err)
...@@ -61,7 +61,7 @@ func TestRemoveContainer(t *testing.T) { ...@@ -61,7 +61,7 @@ func TestRemoveContainer(t *testing.T) {
assert.Equal(t, fakeOS.Removes, []string{expectedContainerLogPath, expectedContainerLogSymlink}) assert.Equal(t, fakeOS.Removes, []string{expectedContainerLogPath, expectedContainerLogSymlink})
// Verify container is removed // Verify container is removed
fakeRuntime.AssertCalls([]string{"RemoveContainer"}) fakeRuntime.AssertCalls([]string{"RemoveContainer"})
containers, err := fakeRuntime.ListContainers(&runtimeapi.ContainerFilter{Id: &containerId}) containers, err := fakeRuntime.ListContainers(&runtimeapi.ContainerFilter{Id: containerId})
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, containers) assert.Empty(t, containers)
} }
...@@ -161,21 +161,21 @@ func (cgc *containerGC) evictableContainers(minAge time.Duration) (containersByE ...@@ -161,21 +161,21 @@ func (cgc *containerGC) evictableContainers(minAge time.Duration) (containersByE
newestGCTime := time.Now().Add(-minAge) newestGCTime := time.Now().Add(-minAge)
for _, container := range containers { for _, container := range containers {
// Prune out running containers. // Prune out running containers.
if container.GetState() == runtimeapi.ContainerState_CONTAINER_RUNNING { if container.State == runtimeapi.ContainerState_CONTAINER_RUNNING {
continue continue
} }
createdAt := time.Unix(0, container.GetCreatedAt()) createdAt := time.Unix(0, container.CreatedAt)
if newestGCTime.Before(createdAt) { if newestGCTime.Before(createdAt) {
continue continue
} }
labeledInfo := getContainerInfoFromLabels(container.Labels) labeledInfo := getContainerInfoFromLabels(container.Labels)
containerInfo := containerGCInfo{ containerInfo := containerGCInfo{
id: container.GetId(), id: container.Id,
name: container.Metadata.GetName(), name: container.Metadata.Name,
createTime: createdAt, createTime: createdAt,
sandboxID: container.GetPodSandboxId(), sandboxID: container.PodSandboxId,
} }
key := evictUnit{ key := evictUnit{
uid: labeledInfo.PodUID, uid: labeledInfo.PodUID,
...@@ -256,15 +256,15 @@ func (cgc *containerGC) evictSandboxes(minAge time.Duration) error { ...@@ -256,15 +256,15 @@ func (cgc *containerGC) evictSandboxes(minAge time.Duration) error {
newestGCTime := time.Now().Add(-minAge) newestGCTime := time.Now().Add(-minAge)
for _, sandbox := range sandboxes { for _, sandbox := range sandboxes {
// Prune out ready sandboxes. // Prune out ready sandboxes.
if sandbox.GetState() == runtimeapi.PodSandboxState_SANDBOX_READY { if sandbox.State == runtimeapi.PodSandboxState_SANDBOX_READY {
continue continue
} }
// Prune out sandboxes that still have containers. // Prune out sandboxes that still have containers.
found := false found := false
sandboxID := sandbox.GetId() sandboxID := sandbox.Id
for _, container := range containers { for _, container := range containers {
if container.GetPodSandboxId() == sandboxID { if container.PodSandboxId == sandboxID {
found = true found = true
break break
} }
...@@ -274,7 +274,7 @@ func (cgc *containerGC) evictSandboxes(minAge time.Duration) error { ...@@ -274,7 +274,7 @@ func (cgc *containerGC) evictSandboxes(minAge time.Duration) error {
} }
// Only garbage collect sandboxes older than sandboxMinGCAge. // Only garbage collect sandboxes older than sandboxMinGCAge.
createdAt := time.Unix(0, sandbox.GetCreatedAt()) createdAt := time.Unix(0, sandbox.CreatedAt)
if createdAt.After(newestGCTime) { if createdAt.After(newestGCTime) {
continue continue
} }
......
...@@ -115,7 +115,7 @@ func TestSandboxGC(t *testing.T) { ...@@ -115,7 +115,7 @@ func TestSandboxGC(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, realRemain, len(test.remain)) assert.Len(t, realRemain, len(test.remain))
for _, remain := range test.remain { for _, remain := range test.remain {
status, err := fakeRuntime.PodSandboxStatus(fakeSandboxes[remain].GetId()) status, err := fakeRuntime.PodSandboxStatus(fakeSandboxes[remain].Id)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, &fakeSandboxes[remain].PodSandboxStatus, status) assert.Equal(t, &fakeSandboxes[remain].PodSandboxStatus, status)
} }
...@@ -288,7 +288,7 @@ func TestContainerGC(t *testing.T) { ...@@ -288,7 +288,7 @@ func TestContainerGC(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, realRemain, len(test.remain)) assert.Len(t, realRemain, len(test.remain))
for _, remain := range test.remain { for _, remain := range test.remain {
status, err := fakeRuntime.ContainerStatus(fakeContainers[remain].GetId()) status, err := fakeRuntime.ContainerStatus(fakeContainers[remain].Id)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, &fakeContainers[remain].ContainerStatus, status) assert.Equal(t, &fakeContainers[remain].ContainerStatus, status)
} }
......
...@@ -40,7 +40,7 @@ func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pul ...@@ -40,7 +40,7 @@ func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pul
return "", err return "", err
} }
imgSpec := &runtimeapi.ImageSpec{Image: &img} imgSpec := &runtimeapi.ImageSpec{Image: img}
creds, withCredentials := keyring.Lookup(repoToPull) creds, withCredentials := keyring.Lookup(repoToPull)
if !withCredentials { if !withCredentials {
glog.V(3).Infof("Pulling image %q without credentials", img) glog.V(3).Infof("Pulling image %q without credentials", img)
...@@ -58,12 +58,12 @@ func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pul ...@@ -58,12 +58,12 @@ func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pul
for _, currentCreds := range creds { for _, currentCreds := range creds {
authConfig := credentialprovider.LazyProvide(currentCreds) authConfig := credentialprovider.LazyProvide(currentCreds)
auth := &runtimeapi.AuthConfig{ auth := &runtimeapi.AuthConfig{
Username: &authConfig.Username, Username: authConfig.Username,
Password: &authConfig.Password, Password: authConfig.Password,
Auth: &authConfig.Auth, Auth: authConfig.Auth,
ServerAddress: &authConfig.ServerAddress, ServerAddress: authConfig.ServerAddress,
IdentityToken: &authConfig.IdentityToken, IdentityToken: authConfig.IdentityToken,
RegistryToken: &authConfig.RegistryToken, RegistryToken: authConfig.RegistryToken,
} }
imageRef, err := m.imageService.PullImage(imgSpec, auth) imageRef, err := m.imageService.PullImage(imgSpec, auth)
...@@ -81,7 +81,7 @@ func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pul ...@@ -81,7 +81,7 @@ func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pul
// GetImageRef gets the reference (digest or ID) of the image which has already been in // GetImageRef gets the reference (digest or ID) of the image which has already been in
// the local storage. It returns ("", nil) if the image isn't in the local storage. // the local storage. It returns ("", nil) if the image isn't in the local storage.
func (m *kubeGenericRuntimeManager) GetImageRef(image kubecontainer.ImageSpec) (string, error) { func (m *kubeGenericRuntimeManager) GetImageRef(image kubecontainer.ImageSpec) (string, error) {
status, err := m.imageService.ImageStatus(&runtimeapi.ImageSpec{Image: &image.Image}) status, err := m.imageService.ImageStatus(&runtimeapi.ImageSpec{Image: image.Image})
if err != nil { if err != nil {
glog.Errorf("ImageStatus for image %q failed: %v", image, err) glog.Errorf("ImageStatus for image %q failed: %v", image, err)
return "", err return "", err
...@@ -90,7 +90,7 @@ func (m *kubeGenericRuntimeManager) GetImageRef(image kubecontainer.ImageSpec) ( ...@@ -90,7 +90,7 @@ func (m *kubeGenericRuntimeManager) GetImageRef(image kubecontainer.ImageSpec) (
return "", nil return "", nil
} }
imageRef := status.GetId() imageRef := status.Id
if len(status.RepoDigests) > 0 { if len(status.RepoDigests) > 0 {
imageRef = status.RepoDigests[0] imageRef = status.RepoDigests[0]
} }
...@@ -109,8 +109,8 @@ func (m *kubeGenericRuntimeManager) ListImages() ([]kubecontainer.Image, error) ...@@ -109,8 +109,8 @@ func (m *kubeGenericRuntimeManager) ListImages() ([]kubecontainer.Image, error)
for _, img := range allImages { for _, img := range allImages {
images = append(images, kubecontainer.Image{ images = append(images, kubecontainer.Image{
ID: img.GetId(), ID: img.Id,
Size: int64(img.GetSize_()), Size: int64(img.Size_),
RepoTags: img.RepoTags, RepoTags: img.RepoTags,
RepoDigests: img.RepoDigests, RepoDigests: img.RepoDigests,
}) })
...@@ -121,7 +121,7 @@ func (m *kubeGenericRuntimeManager) ListImages() ([]kubecontainer.Image, error) ...@@ -121,7 +121,7 @@ func (m *kubeGenericRuntimeManager) ListImages() ([]kubecontainer.Image, error)
// RemoveImage removes the specified image. // RemoveImage removes the specified image.
func (m *kubeGenericRuntimeManager) RemoveImage(image kubecontainer.ImageSpec) error { func (m *kubeGenericRuntimeManager) RemoveImage(image kubecontainer.ImageSpec) error {
err := m.imageService.RemoveImage(&runtimeapi.ImageSpec{Image: &image.Image}) err := m.imageService.RemoveImage(&runtimeapi.ImageSpec{Image: image.Image})
if err != nil { if err != nil {
glog.Errorf("Remove image %q failed: %v", image.Image, err) glog.Errorf("Remove image %q failed: %v", image.Image, err)
return err return err
...@@ -142,7 +142,7 @@ func (m *kubeGenericRuntimeManager) ImageStats() (*kubecontainer.ImageStats, err ...@@ -142,7 +142,7 @@ func (m *kubeGenericRuntimeManager) ImageStats() (*kubecontainer.ImageStats, err
} }
stats := &kubecontainer.ImageStats{} stats := &kubecontainer.ImageStats{}
for _, img := range allImages { for _, img := range allImages {
stats.TotalStorageBytes += img.GetSize_() stats.TotalStorageBytes += img.Size_
} }
return stats, nil return stats, nil
} }
...@@ -156,18 +156,18 @@ func NewKubeGenericRuntimeManager( ...@@ -156,18 +156,18 @@ func NewKubeGenericRuntimeManager(
// Only matching kubeRuntimeAPIVersion is supported now // Only matching kubeRuntimeAPIVersion is supported now
// TODO: Runtime API machinery is under discussion at https://github.com/kubernetes/kubernetes/issues/28642 // TODO: Runtime API machinery is under discussion at https://github.com/kubernetes/kubernetes/issues/28642
if typedVersion.GetVersion() != kubeRuntimeAPIVersion { if typedVersion.Version != kubeRuntimeAPIVersion {
glog.Errorf("Runtime api version %s is not supported, only %s is supported now", glog.Errorf("Runtime api version %s is not supported, only %s is supported now",
typedVersion.GetVersion(), typedVersion.Version,
kubeRuntimeAPIVersion) kubeRuntimeAPIVersion)
return nil, ErrVersionNotSupported return nil, ErrVersionNotSupported
} }
kubeRuntimeManager.runtimeName = typedVersion.GetRuntimeName() kubeRuntimeManager.runtimeName = typedVersion.RuntimeName
glog.Infof("Container runtime %s initialized, version: %s, apiVersion: %s", glog.Infof("Container runtime %s initialized, version: %s, apiVersion: %s",
typedVersion.GetRuntimeName(), typedVersion.RuntimeName,
typedVersion.GetRuntimeVersion(), typedVersion.RuntimeVersion,
typedVersion.GetRuntimeApiVersion()) typedVersion.RuntimeApiVersion)
// If the container logs directory does not exist, create it. // If the container logs directory does not exist, create it.
// TODO: create podLogsRootDirectory at kubelet.go when kubelet is refactored to // TODO: create podLogsRootDirectory at kubelet.go when kubelet is refactored to
...@@ -224,7 +224,7 @@ func (m *kubeGenericRuntimeManager) Version() (kubecontainer.Version, error) { ...@@ -224,7 +224,7 @@ func (m *kubeGenericRuntimeManager) Version() (kubecontainer.Version, error) {
return nil, err return nil, err
} }
return newRuntimeVersion(typedVersion.GetVersion()) return newRuntimeVersion(typedVersion.Version)
} }
// APIVersion returns the cached API version information of the container // APIVersion returns the cached API version information of the container
...@@ -237,7 +237,7 @@ func (m *kubeGenericRuntimeManager) APIVersion() (kubecontainer.Version, error) ...@@ -237,7 +237,7 @@ func (m *kubeGenericRuntimeManager) APIVersion() (kubecontainer.Version, error)
} }
typedVersion := versionObject.(*runtimeapi.VersionResponse) typedVersion := versionObject.(*runtimeapi.VersionResponse)
return newRuntimeVersion(typedVersion.GetRuntimeApiVersion()) return newRuntimeVersion(typedVersion.RuntimeApiVersion)
} }
// Status returns the status of the runtime. An error is returned if the Status // Status returns the status of the runtime. An error is returned if the Status
...@@ -265,12 +265,12 @@ func (m *kubeGenericRuntimeManager) GetPods(all bool) ([]*kubecontainer.Pod, err ...@@ -265,12 +265,12 @@ func (m *kubeGenericRuntimeManager) GetPods(all bool) ([]*kubecontainer.Pod, err
glog.V(4).Infof("Sandbox does not have metadata: %+v", s) glog.V(4).Infof("Sandbox does not have metadata: %+v", s)
continue continue
} }
podUID := kubetypes.UID(s.Metadata.GetUid()) podUID := kubetypes.UID(s.Metadata.Uid)
if _, ok := pods[podUID]; !ok { if _, ok := pods[podUID]; !ok {
pods[podUID] = &kubecontainer.Pod{ pods[podUID] = &kubecontainer.Pod{
ID: podUID, ID: podUID,
Name: s.Metadata.GetName(), Name: s.Metadata.Name,
Namespace: s.Metadata.GetNamespace(), Namespace: s.Metadata.Namespace,
} }
} }
p := pods[podUID] p := pods[podUID]
...@@ -372,26 +372,26 @@ func (m *kubeGenericRuntimeManager) podSandboxChanged(pod *v1.Pod, podStatus *ku ...@@ -372,26 +372,26 @@ func (m *kubeGenericRuntimeManager) podSandboxChanged(pod *v1.Pod, podStatus *ku
readySandboxCount := 0 readySandboxCount := 0
for _, s := range podStatus.SandboxStatuses { for _, s := range podStatus.SandboxStatuses {
if s.GetState() == runtimeapi.PodSandboxState_SANDBOX_READY { if s.State == runtimeapi.PodSandboxState_SANDBOX_READY {
readySandboxCount++ readySandboxCount++
} }
} }
// Needs to create a new sandbox when readySandboxCount > 1 or the ready sandbox is not the latest one. // Needs to create a new sandbox when readySandboxCount > 1 or the ready sandbox is not the latest one.
sandboxStatus := podStatus.SandboxStatuses[0] sandboxStatus := podStatus.SandboxStatuses[0]
if readySandboxCount > 1 || sandboxStatus.GetState() != runtimeapi.PodSandboxState_SANDBOX_READY { if readySandboxCount > 1 || sandboxStatus.State != runtimeapi.PodSandboxState_SANDBOX_READY {
glog.V(2).Infof("No ready sandbox for pod %q can be found. Need to start a new one", format.Pod(pod)) glog.V(2).Infof("No ready sandbox for pod %q can be found. Need to start a new one", format.Pod(pod))
return true, sandboxStatus.Metadata.GetAttempt() + 1, sandboxStatus.GetId() return true, sandboxStatus.Metadata.Attempt + 1, sandboxStatus.Id
} }
// Needs to create a new sandbox when network namespace changed. // Needs to create a new sandbox when network namespace changed.
if sandboxStatus.Linux != nil && sandboxStatus.Linux.Namespaces.Options != nil && if sandboxStatus.Linux != nil && sandboxStatus.Linux.Namespaces.Options != nil &&
sandboxStatus.Linux.Namespaces.Options.GetHostNetwork() != kubecontainer.IsHostNetworkPod(pod) { sandboxStatus.Linux.Namespaces.Options.HostNetwork != kubecontainer.IsHostNetworkPod(pod) {
glog.V(2).Infof("Sandbox for pod %q has changed. Need to start a new one", format.Pod(pod)) glog.V(2).Infof("Sandbox for pod %q has changed. Need to start a new one", format.Pod(pod))
return true, sandboxStatus.Metadata.GetAttempt() + 1, "" return true, sandboxStatus.Metadata.Attempt + 1, ""
} }
return false, sandboxStatus.Metadata.GetAttempt(), sandboxStatus.GetId() return false, sandboxStatus.Metadata.Attempt, sandboxStatus.Id
} }
// checkAndKeepInitContainers keeps all successfully completed init containers. If there // checkAndKeepInitContainers keeps all successfully completed init containers. If there
...@@ -794,10 +794,8 @@ func (m *kubeGenericRuntimeManager) isHostNetwork(podSandBoxID string, pod *v1.P ...@@ -794,10 +794,8 @@ func (m *kubeGenericRuntimeManager) isHostNetwork(podSandBoxID string, pod *v1.P
return false, err return false, err
} }
if podStatus.Linux != nil && podStatus.Linux.Namespaces != nil && podStatus.Linux.Namespaces.Options != nil { if nsOpts := podStatus.GetLinux().GetNamespaces().GetOptions(); nsOpts != nil {
if podStatus.Linux.Namespaces.Options.HostNetwork != nil { return nsOpts.HostNetwork, nil
return podStatus.Linux.Namespaces.Options.GetHostNetwork(), nil
}
} }
return false, nil return false, nil
...@@ -844,7 +842,7 @@ func (m *kubeGenericRuntimeManager) GetPodStatus(uid kubetypes.UID, name, namesp ...@@ -844,7 +842,7 @@ func (m *kubeGenericRuntimeManager) GetPodStatus(uid kubetypes.UID, name, namesp
sandboxStatuses[idx] = podSandboxStatus sandboxStatuses[idx] = podSandboxStatus
// Only get pod IP from latest sandbox // Only get pod IP from latest sandbox
if idx == 0 && podSandboxStatus.GetState() == runtimeapi.PodSandboxState_SANDBOX_READY { if idx == 0 && podSandboxStatus.State == runtimeapi.PodSandboxState_SANDBOX_READY {
podIP = m.determinePodSandboxIP(namespace, name, podSandboxStatus) podIP = m.determinePodSandboxIP(namespace, name, podSandboxStatus)
} }
} }
...@@ -900,7 +898,7 @@ func (m *kubeGenericRuntimeManager) UpdatePodCIDR(podCIDR string) error { ...@@ -900,7 +898,7 @@ func (m *kubeGenericRuntimeManager) UpdatePodCIDR(podCIDR string) error {
return m.runtimeService.UpdateRuntimeConfig( return m.runtimeService.UpdateRuntimeConfig(
&runtimeapi.RuntimeConfig{ &runtimeapi.RuntimeConfig{
NetworkConfig: &runtimeapi.NetworkConfig{ NetworkConfig: &runtimeapi.NetworkConfig{
PodCidr: &podCIDR, PodCidr: podCIDR,
}, },
}) })
} }
...@@ -119,12 +119,12 @@ func makeFakePodSandbox(t *testing.T, m *kubeGenericRuntimeManager, template san ...@@ -119,12 +119,12 @@ func makeFakePodSandbox(t *testing.T, m *kubeGenericRuntimeManager, template san
podSandboxID := apitest.BuildSandboxName(config.Metadata) podSandboxID := apitest.BuildSandboxName(config.Metadata)
return &apitest.FakePodSandbox{ return &apitest.FakePodSandbox{
PodSandboxStatus: runtimeapi.PodSandboxStatus{ PodSandboxStatus: runtimeapi.PodSandboxStatus{
Id: &podSandboxID, Id: podSandboxID,
Metadata: config.Metadata, Metadata: config.Metadata,
State: &template.state, State: template.state,
CreatedAt: &template.createdAt, CreatedAt: template.createdAt,
Network: &runtimeapi.PodSandboxNetworkStatus{ Network: &runtimeapi.PodSandboxNetworkStatus{
Ip: &apitest.FakePodSandboxIP, Ip: apitest.FakePodSandboxIP,
}, },
Labels: config.Labels, Labels: config.Labels,
}, },
...@@ -151,15 +151,15 @@ func makeFakeContainer(t *testing.T, m *kubeGenericRuntimeManager, template cont ...@@ -151,15 +151,15 @@ func makeFakeContainer(t *testing.T, m *kubeGenericRuntimeManager, template cont
podSandboxID := apitest.BuildSandboxName(sandboxConfig.Metadata) podSandboxID := apitest.BuildSandboxName(sandboxConfig.Metadata)
containerID := apitest.BuildContainerName(containerConfig.Metadata, podSandboxID) containerID := apitest.BuildContainerName(containerConfig.Metadata, podSandboxID)
imageRef := containerConfig.Image.GetImage() imageRef := containerConfig.Image.Image
return &apitest.FakeContainer{ return &apitest.FakeContainer{
ContainerStatus: runtimeapi.ContainerStatus{ ContainerStatus: runtimeapi.ContainerStatus{
Id: &containerID, Id: containerID,
Metadata: containerConfig.Metadata, Metadata: containerConfig.Metadata,
Image: containerConfig.Image, Image: containerConfig.Image,
ImageRef: &imageRef, ImageRef: imageRef,
CreatedAt: &template.createdAt, CreatedAt: template.createdAt,
State: &template.state, State: template.state,
Labels: containerConfig.Labels, Labels: containerConfig.Labels,
Annotations: containerConfig.Annotations, Annotations: containerConfig.Annotations,
}, },
...@@ -223,7 +223,7 @@ func verifyPods(a, b []*kubecontainer.Pod) bool { ...@@ -223,7 +223,7 @@ func verifyPods(a, b []*kubecontainer.Pod) bool {
func verifyFakeContainerList(fakeRuntime *apitest.FakeRuntimeService, expected []string) ([]string, bool) { func verifyFakeContainerList(fakeRuntime *apitest.FakeRuntimeService, expected []string) ([]string, bool) {
actual := []string{} actual := []string{}
for _, c := range fakeRuntime.Containers { for _, c := range fakeRuntime.Containers {
actual = append(actual, c.GetId()) actual = append(actual, c.Id)
} }
sort.Sort(sort.StringSlice(actual)) sort.Sort(sort.StringSlice(actual))
sort.Sort(sort.StringSlice(expected)) sort.Sort(sort.StringSlice(expected))
...@@ -411,7 +411,7 @@ func TestGetPodContainerID(t *testing.T) { ...@@ -411,7 +411,7 @@ func TestGetPodContainerID(t *testing.T) {
Sandboxes: []*kubecontainer.Container{sandbox}, Sandboxes: []*kubecontainer.Container{sandbox},
} }
actual, err := m.GetPodContainerID(expectedPod) actual, err := m.GetPodContainerID(expectedPod)
assert.Equal(t, fakeSandbox.GetId(), actual.ID) assert.Equal(t, fakeSandbox.Id, actual.ID)
} }
func TestGetNetNS(t *testing.T) { func TestGetNetNS(t *testing.T) {
...@@ -441,7 +441,7 @@ func TestGetNetNS(t *testing.T) { ...@@ -441,7 +441,7 @@ func TestGetNetNS(t *testing.T) {
// Set fake sandbox and fake containers to fakeRuntime. // Set fake sandbox and fake containers to fakeRuntime.
sandbox, _ := makeAndSetFakePod(t, m, fakeRuntime, pod) sandbox, _ := makeAndSetFakePod(t, m, fakeRuntime, pod)
actual, err := m.GetNetNS(kubecontainer.ContainerID{ID: sandbox.GetId()}) actual, err := m.GetNetNS(kubecontainer.ContainerID{ID: sandbox.Id})
assert.Equal(t, "", actual) assert.Equal(t, "", actual)
assert.Equal(t, "not supported", err.Error()) assert.Equal(t, "not supported", err.Error())
} }
...@@ -498,7 +498,7 @@ func TestKillPod(t *testing.T) { ...@@ -498,7 +498,7 @@ func TestKillPod(t *testing.T) {
Sandboxes: []*kubecontainer.Container{ Sandboxes: []*kubecontainer.Container{
{ {
ID: kubecontainer.ContainerID{ ID: kubecontainer.ContainerID{
ID: fakeSandbox.GetId(), ID: fakeSandbox.Id,
Type: apitest.FakeRuntimeName, Type: apitest.FakeRuntimeName,
}, },
}, },
...@@ -510,10 +510,10 @@ func TestKillPod(t *testing.T) { ...@@ -510,10 +510,10 @@ func TestKillPod(t *testing.T) {
assert.Equal(t, 2, len(fakeRuntime.Containers)) assert.Equal(t, 2, len(fakeRuntime.Containers))
assert.Equal(t, 1, len(fakeRuntime.Sandboxes)) assert.Equal(t, 1, len(fakeRuntime.Sandboxes))
for _, sandbox := range fakeRuntime.Sandboxes { for _, sandbox := range fakeRuntime.Sandboxes {
assert.Equal(t, runtimeapi.PodSandboxState_SANDBOX_NOTREADY, sandbox.GetState()) assert.Equal(t, runtimeapi.PodSandboxState_SANDBOX_NOTREADY, sandbox.State)
} }
for _, c := range fakeRuntime.Containers { for _, c := range fakeRuntime.Containers {
assert.Equal(t, runtimeapi.ContainerState_CONTAINER_EXITED, c.GetState()) assert.Equal(t, runtimeapi.ContainerState_CONTAINER_EXITED, c.State)
} }
} }
...@@ -551,10 +551,10 @@ func TestSyncPod(t *testing.T) { ...@@ -551,10 +551,10 @@ func TestSyncPod(t *testing.T) {
assert.Equal(t, 2, len(fakeImage.Images)) assert.Equal(t, 2, len(fakeImage.Images))
assert.Equal(t, 1, len(fakeRuntime.Sandboxes)) assert.Equal(t, 1, len(fakeRuntime.Sandboxes))
for _, sandbox := range fakeRuntime.Sandboxes { for _, sandbox := range fakeRuntime.Sandboxes {
assert.Equal(t, runtimeapi.PodSandboxState_SANDBOX_READY, sandbox.GetState()) assert.Equal(t, runtimeapi.PodSandboxState_SANDBOX_READY, sandbox.State)
} }
for _, c := range fakeRuntime.Containers { for _, c := range fakeRuntime.Containers {
assert.Equal(t, runtimeapi.ContainerState_CONTAINER_RUNNING, c.GetState()) assert.Equal(t, runtimeapi.ContainerState_CONTAINER_RUNNING, c.State)
} }
} }
...@@ -589,7 +589,7 @@ func TestPruneInitContainers(t *testing.T) { ...@@ -589,7 +589,7 @@ func TestPruneInitContainers(t *testing.T) {
keep := map[kubecontainer.ContainerID]int{} keep := map[kubecontainer.ContainerID]int{}
m.pruneInitContainersBeforeStart(pod, podStatus, keep) m.pruneInitContainersBeforeStart(pod, podStatus, keep)
expectedContainers := []string{fakes[0].GetId(), fakes[2].GetId()} expectedContainers := []string{fakes[0].Id, fakes[2].Id}
if actual, ok := verifyFakeContainerList(fakeRuntime, expectedContainers); !ok { if actual, ok := verifyFakeContainerList(fakeRuntime, expectedContainers); !ok {
t.Errorf("expected %q, got %q", expectedContainers, actual) t.Errorf("expected %q, got %q", expectedContainers, actual)
} }
...@@ -635,11 +635,11 @@ func TestSyncPodWithInitContainers(t *testing.T) { ...@@ -635,11 +635,11 @@ func TestSyncPodWithInitContainers(t *testing.T) {
buildContainerID := func(pod *v1.Pod, container v1.Container) string { buildContainerID := func(pod *v1.Pod, container v1.Container) string {
uid := string(pod.UID) uid := string(pod.UID)
sandboxID := apitest.BuildSandboxName(&runtimeapi.PodSandboxMetadata{ sandboxID := apitest.BuildSandboxName(&runtimeapi.PodSandboxMetadata{
Name: &pod.Name, Name: pod.Name,
Uid: &uid, Uid: uid,
Namespace: &pod.Namespace, Namespace: pod.Namespace,
}) })
return apitest.BuildContainerName(&runtimeapi.ContainerMetadata{Name: &container.Name}, sandboxID) return apitest.BuildContainerName(&runtimeapi.ContainerMetadata{Name: container.Name}, sandboxID)
} }
backOff := flowcontrol.NewBackOff(time.Second, time.Minute) backOff := flowcontrol.NewBackOff(time.Second, time.Minute)
......
...@@ -41,7 +41,7 @@ func (m *kubeGenericRuntimeManager) createPodSandbox(pod *v1.Pod, attempt uint32 ...@@ -41,7 +41,7 @@ func (m *kubeGenericRuntimeManager) createPodSandbox(pod *v1.Pod, attempt uint32
} }
// Create pod logs directory // Create pod logs directory
err = m.osInterface.MkdirAll(podSandboxConfig.GetLogDirectory(), 0755) err = m.osInterface.MkdirAll(podSandboxConfig.LogDirectory, 0755)
if err != nil { if err != nil {
message := fmt.Sprintf("Create pod log directory for pod %q failed: %v", format.Pod(pod), err) message := fmt.Sprintf("Create pod log directory for pod %q failed: %v", format.Pod(pod), err)
glog.Errorf(message) glog.Errorf(message)
...@@ -65,10 +65,10 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp ...@@ -65,10 +65,10 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp
podUID := string(pod.UID) podUID := string(pod.UID)
podSandboxConfig := &runtimeapi.PodSandboxConfig{ podSandboxConfig := &runtimeapi.PodSandboxConfig{
Metadata: &runtimeapi.PodSandboxMetadata{ Metadata: &runtimeapi.PodSandboxMetadata{
Name: &pod.Name, Name: pod.Name,
Namespace: &pod.Namespace, Namespace: pod.Namespace,
Uid: &podUID, Uid: podUID,
Attempt: &attempt, Attempt: attempt,
}, },
Labels: newPodLabels(pod), Labels: newPodLabels(pod),
Annotations: newPodAnnotations(pod), Annotations: newPodAnnotations(pod),
...@@ -89,11 +89,11 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp ...@@ -89,11 +89,11 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp
if err != nil { if err != nil {
return nil, err return nil, err
} }
podSandboxConfig.Hostname = &hostname podSandboxConfig.Hostname = hostname
} }
logDir := buildPodLogsDirectory(pod.UID) logDir := buildPodLogsDirectory(pod.UID)
podSandboxConfig.LogDirectory = &logDir podSandboxConfig.LogDirectory = logDir
cgroupParent := "" cgroupParent := ""
portMappings := []*runtimeapi.PortMapping{} portMappings := []*runtimeapi.PortMapping{}
...@@ -110,10 +110,10 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp ...@@ -110,10 +110,10 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp
containerPort := int32(port.ContainerPort) containerPort := int32(port.ContainerPort)
protocol := toRuntimeProtocol(port.Protocol) protocol := toRuntimeProtocol(port.Protocol)
portMappings = append(portMappings, &runtimeapi.PortMapping{ portMappings = append(portMappings, &runtimeapi.PortMapping{
HostIp: &port.HostIP, HostIp: port.HostIP,
HostPort: &hostPort, HostPort: hostPort,
ContainerPort: &containerPort, ContainerPort: containerPort,
Protocol: &protocol, Protocol: protocol,
}) })
} }
...@@ -131,20 +131,21 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp ...@@ -131,20 +131,21 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attemp
// generatePodSandboxLinuxConfig generates LinuxPodSandboxConfig from v1.Pod. // generatePodSandboxLinuxConfig generates LinuxPodSandboxConfig from v1.Pod.
func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod, cgroupParent string) *runtimeapi.LinuxPodSandboxConfig { func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod, cgroupParent string) *runtimeapi.LinuxPodSandboxConfig {
lc := &runtimeapi.LinuxPodSandboxConfig{ lc := &runtimeapi.LinuxPodSandboxConfig{
SecurityContext: &runtimeapi.LinuxSandboxSecurityContext{}, CgroupParent: cgroupParent,
} SecurityContext: &runtimeapi.LinuxSandboxSecurityContext{
Privileged: kubecontainer.HasPrivilegedContainer(pod),
if cgroupParent != "" { },
lc.CgroupParent = &cgroupParent
} }
if pod.Spec.SecurityContext != nil { if pod.Spec.SecurityContext != nil {
sc := pod.Spec.SecurityContext sc := pod.Spec.SecurityContext
lc.SecurityContext.RunAsUser = sc.RunAsUser if sc.RunAsUser != nil {
lc.SecurityContext.RunAsUser = &runtimeapi.Int64Value{Value: *sc.RunAsUser}
}
lc.SecurityContext.NamespaceOptions = &runtimeapi.NamespaceOption{ lc.SecurityContext.NamespaceOptions = &runtimeapi.NamespaceOption{
HostNetwork: &pod.Spec.HostNetwork, HostNetwork: pod.Spec.HostNetwork,
HostIpc: &pod.Spec.HostIPC, HostIpc: pod.Spec.HostIPC,
HostPid: &pod.Spec.HostPID, HostPid: pod.Spec.HostPID,
} }
if sc.FSGroup != nil { if sc.FSGroup != nil {
...@@ -158,19 +159,14 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod, c ...@@ -158,19 +159,14 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod, c
} }
if sc.SELinuxOptions != nil { if sc.SELinuxOptions != nil {
lc.SecurityContext.SelinuxOptions = &runtimeapi.SELinuxOption{ lc.SecurityContext.SelinuxOptions = &runtimeapi.SELinuxOption{
User: &sc.SELinuxOptions.User, User: sc.SELinuxOptions.User,
Role: &sc.SELinuxOptions.Role, Role: sc.SELinuxOptions.Role,
Type: &sc.SELinuxOptions.Type, Type: sc.SELinuxOptions.Type,
Level: &sc.SELinuxOptions.Level, Level: sc.SELinuxOptions.Level,
} }
} }
} }
if kubecontainer.HasPrivilegedContainer(pod) {
privileged := true
lc.SecurityContext.Privileged = &privileged
}
return lc return lc
} }
...@@ -180,7 +176,9 @@ func (m *kubeGenericRuntimeManager) getKubeletSandboxes(all bool) ([]*runtimeapi ...@@ -180,7 +176,9 @@ func (m *kubeGenericRuntimeManager) getKubeletSandboxes(all bool) ([]*runtimeapi
if !all { if !all {
readyState := runtimeapi.PodSandboxState_SANDBOX_READY readyState := runtimeapi.PodSandboxState_SANDBOX_READY
filter = &runtimeapi.PodSandboxFilter{ filter = &runtimeapi.PodSandboxFilter{
State: &readyState, State: &runtimeapi.PodSandboxStateValue{
State: readyState,
},
} }
} }
...@@ -194,7 +192,7 @@ func (m *kubeGenericRuntimeManager) getKubeletSandboxes(all bool) ([]*runtimeapi ...@@ -194,7 +192,7 @@ func (m *kubeGenericRuntimeManager) getKubeletSandboxes(all bool) ([]*runtimeapi
for _, s := range resp { for _, s := range resp {
if !isManagedByKubelet(s.Labels) { if !isManagedByKubelet(s.Labels) {
glog.V(5).Infof("Sandbox %s is not managed by kubelet", kubecontainer.BuildPodFullName( glog.V(5).Infof("Sandbox %s is not managed by kubelet", kubecontainer.BuildPodFullName(
s.Metadata.GetName(), s.Metadata.GetNamespace())) s.Metadata.Name, s.Metadata.Namespace))
continue continue
} }
...@@ -210,7 +208,7 @@ func (m *kubeGenericRuntimeManager) determinePodSandboxIP(podNamespace, podName ...@@ -210,7 +208,7 @@ func (m *kubeGenericRuntimeManager) determinePodSandboxIP(podNamespace, podName
glog.Warningf("Pod Sandbox status doesn't have network information, cannot report IP") glog.Warningf("Pod Sandbox status doesn't have network information, cannot report IP")
return "" return ""
} }
ip := podSandbox.Network.GetIp() ip := podSandbox.Network.Ip
if net.ParseIP(ip) == nil { if net.ParseIP(ip) == nil {
glog.Warningf("Pod Sandbox reported an unparseable IP %v", ip) glog.Warningf("Pod Sandbox reported an unparseable IP %v", ip)
return "" return ""
...@@ -222,9 +220,13 @@ func (m *kubeGenericRuntimeManager) determinePodSandboxIP(podNamespace, podName ...@@ -222,9 +220,13 @@ func (m *kubeGenericRuntimeManager) determinePodSandboxIP(podNamespace, podName
// Param state could be nil in order to get all sandboxes belonging to same pod. // Param state could be nil in order to get all sandboxes belonging to same pod.
func (m *kubeGenericRuntimeManager) getSandboxIDByPodUID(podUID kubetypes.UID, state *runtimeapi.PodSandboxState) ([]string, error) { func (m *kubeGenericRuntimeManager) getSandboxIDByPodUID(podUID kubetypes.UID, state *runtimeapi.PodSandboxState) ([]string, error) {
filter := &runtimeapi.PodSandboxFilter{ filter := &runtimeapi.PodSandboxFilter{
State: state,
LabelSelector: map[string]string{types.KubernetesPodUIDLabel: string(podUID)}, LabelSelector: map[string]string{types.KubernetesPodUIDLabel: string(podUID)},
} }
if state != nil {
filter.State = &runtimeapi.PodSandboxStateValue{
State: *state,
}
}
sandboxes, err := m.runtimeService.ListPodSandbox(filter) sandboxes, err := m.runtimeService.ListPodSandbox(filter)
if err != nil { if err != nil {
glog.Errorf("ListPodSandbox with pod UID %q failed: %v", podUID, err) glog.Errorf("ListPodSandbox with pod UID %q failed: %v", podUID, err)
...@@ -239,7 +241,7 @@ func (m *kubeGenericRuntimeManager) getSandboxIDByPodUID(podUID kubetypes.UID, s ...@@ -239,7 +241,7 @@ func (m *kubeGenericRuntimeManager) getSandboxIDByPodUID(podUID kubetypes.UID, s
sandboxIDs := make([]string, len(sandboxes)) sandboxIDs := make([]string, len(sandboxes))
sort.Sort(podSandboxByCreated(sandboxes)) sort.Sort(podSandboxByCreated(sandboxes))
for i, s := range sandboxes { for i, s := range sandboxes {
sandboxIDs[i] = s.GetId() sandboxIDs[i] = s.Id
} }
return sandboxIDs, nil return sandboxIDs, nil
...@@ -256,11 +258,11 @@ func (m *kubeGenericRuntimeManager) GetPortForward(podName, podNamespace string, ...@@ -256,11 +258,11 @@ func (m *kubeGenericRuntimeManager) GetPortForward(podName, podNamespace string,
} }
// TODO: Port is unused for now, but we may need it in the future. // TODO: Port is unused for now, but we may need it in the future.
req := &runtimeapi.PortForwardRequest{ req := &runtimeapi.PortForwardRequest{
PodSandboxId: &sandboxIDs[0], PodSandboxId: sandboxIDs[0],
} }
resp, err := m.runtimeService.PortForward(req) resp, err := m.runtimeService.PortForward(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return url.Parse(resp.GetUrl()) return url.Parse(resp.Url)
} }
...@@ -58,7 +58,7 @@ func TestCreatePodSandbox(t *testing.T) { ...@@ -58,7 +58,7 @@ func TestCreatePodSandbox(t *testing.T) {
id, _, err := m.createPodSandbox(pod, 1) id, _, err := m.createPodSandbox(pod, 1)
assert.NoError(t, err) assert.NoError(t, err)
fakeRuntime.AssertCalls([]string{"RunPodSandbox"}) fakeRuntime.AssertCalls([]string{"RunPodSandbox"})
sandboxes, err := fakeRuntime.ListPodSandbox(&runtimeapi.PodSandboxFilter{Id: &id}) sandboxes, err := fakeRuntime.ListPodSandbox(&runtimeapi.PodSandboxFilter{Id: id})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, len(sandboxes), 1) assert.Equal(t, len(sandboxes), 1)
// TODO Check pod sandbox configuration // TODO Check pod sandbox configuration
......
...@@ -25,7 +25,7 @@ import ( ...@@ -25,7 +25,7 @@ import (
) )
// determineEffectiveSecurityContext gets container's security context from v1.Pod and v1.Container. // determineEffectiveSecurityContext gets container's security context from v1.Pod and v1.Container.
func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container, uid *int64, username *string) *runtimeapi.LinuxContainerSecurityContext { func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container, uid *int64, username string) *runtimeapi.LinuxContainerSecurityContext {
effectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container) effectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container)
synthesized := convertToRuntimeSecurityContext(effectiveSc) synthesized := convertToRuntimeSecurityContext(effectiveSc)
if synthesized == nil { if synthesized == nil {
...@@ -34,7 +34,9 @@ func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Po ...@@ -34,7 +34,9 @@ func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Po
// set RunAsUser. // set RunAsUser.
if synthesized.RunAsUser == nil { if synthesized.RunAsUser == nil {
synthesized.RunAsUser = uid if uid != nil {
synthesized.RunAsUser = &runtimeapi.Int64Value{Value: *uid}
}
synthesized.RunAsUsername = username synthesized.RunAsUsername = username
} }
...@@ -44,9 +46,9 @@ func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Po ...@@ -44,9 +46,9 @@ func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Po
return synthesized return synthesized
} }
synthesized.NamespaceOptions = &runtimeapi.NamespaceOption{ synthesized.NamespaceOptions = &runtimeapi.NamespaceOption{
HostNetwork: &pod.Spec.HostNetwork, HostNetwork: pod.Spec.HostNetwork,
HostIpc: &pod.Spec.HostIPC, HostIpc: pod.Spec.HostIPC,
HostPid: &pod.Spec.HostPID, HostPid: pod.Spec.HostPID,
} }
if podSc.FSGroup != nil { if podSc.FSGroup != nil {
synthesized.SupplementalGroups = append(synthesized.SupplementalGroups, *podSc.FSGroup) synthesized.SupplementalGroups = append(synthesized.SupplementalGroups, *podSc.FSGroup)
...@@ -88,13 +90,21 @@ func convertToRuntimeSecurityContext(securityContext *v1.SecurityContext) *runti ...@@ -88,13 +90,21 @@ func convertToRuntimeSecurityContext(securityContext *v1.SecurityContext) *runti
return nil return nil
} }
return &runtimeapi.LinuxContainerSecurityContext{ sc := &runtimeapi.LinuxContainerSecurityContext{
RunAsUser: securityContext.RunAsUser,
Privileged: securityContext.Privileged,
ReadonlyRootfs: securityContext.ReadOnlyRootFilesystem,
Capabilities: convertToRuntimeCapabilities(securityContext.Capabilities), Capabilities: convertToRuntimeCapabilities(securityContext.Capabilities),
SelinuxOptions: convertToRuntimeSELinuxOption(securityContext.SELinuxOptions), SelinuxOptions: convertToRuntimeSELinuxOption(securityContext.SELinuxOptions),
} }
if securityContext.RunAsUser != nil {
sc.RunAsUser = &runtimeapi.Int64Value{Value: *securityContext.RunAsUser}
}
if securityContext.Privileged != nil {
sc.Privileged = *securityContext.Privileged
}
if securityContext.ReadOnlyRootFilesystem != nil {
sc.ReadonlyRootfs = *securityContext.ReadOnlyRootFilesystem
}
return sc
} }
// convertToRuntimeSELinuxOption converts v1.SELinuxOptions to runtimeapi.SELinuxOption. // convertToRuntimeSELinuxOption converts v1.SELinuxOptions to runtimeapi.SELinuxOption.
...@@ -104,10 +114,10 @@ func convertToRuntimeSELinuxOption(opts *v1.SELinuxOptions) *runtimeapi.SELinuxO ...@@ -104,10 +114,10 @@ func convertToRuntimeSELinuxOption(opts *v1.SELinuxOptions) *runtimeapi.SELinuxO
} }
return &runtimeapi.SELinuxOption{ return &runtimeapi.SELinuxOption{
User: &opts.User, User: opts.User,
Role: &opts.Role, Role: opts.Role,
Type: &opts.Type, Type: opts.Type,
Level: &opts.Level, Level: opts.Level,
} }
} }
......
...@@ -71,7 +71,7 @@ func (r *RemoteImageService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimea ...@@ -71,7 +71,7 @@ func (r *RemoteImageService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimea
Image: image, Image: image,
}) })
if err != nil { if err != nil {
glog.Errorf("ImageStatus %q from image service failed: %v", image.GetImage(), err) glog.Errorf("ImageStatus %q from image service failed: %v", image.Image, err)
return nil, err return nil, err
} }
...@@ -88,11 +88,11 @@ func (r *RemoteImageService) PullImage(image *runtimeapi.ImageSpec, auth *runtim ...@@ -88,11 +88,11 @@ func (r *RemoteImageService) PullImage(image *runtimeapi.ImageSpec, auth *runtim
Auth: auth, Auth: auth,
}) })
if err != nil { if err != nil {
glog.Errorf("PullImage %q from image service failed: %v", image.GetImage(), err) glog.Errorf("PullImage %q from image service failed: %v", image.Image, err)
return "", err return "", err
} }
return resp.GetImageRef(), nil return resp.ImageRef, nil
} }
// RemoveImage removes the image. // RemoveImage removes the image.
...@@ -104,7 +104,7 @@ func (r *RemoteImageService) RemoveImage(image *runtimeapi.ImageSpec) error { ...@@ -104,7 +104,7 @@ func (r *RemoteImageService) RemoveImage(image *runtimeapi.ImageSpec) error {
Image: image, Image: image,
}) })
if err != nil { if err != nil {
glog.Errorf("RemoveImage %q from image service failed: %v", image.GetImage(), err) glog.Errorf("RemoveImage %q from image service failed: %v", image.Image, err)
return err return err
} }
......
...@@ -55,7 +55,7 @@ func (r *RemoteRuntimeService) Version(apiVersion string) (*runtimeapi.VersionRe ...@@ -55,7 +55,7 @@ func (r *RemoteRuntimeService) Version(apiVersion string) (*runtimeapi.VersionRe
defer cancel() defer cancel()
typedVersion, err := r.runtimeClient.Version(ctx, &runtimeapi.VersionRequest{ typedVersion, err := r.runtimeClient.Version(ctx, &runtimeapi.VersionRequest{
Version: &apiVersion, Version: apiVersion,
}) })
if err != nil { if err != nil {
glog.Errorf("Version from runtime service failed: %v", err) glog.Errorf("Version from runtime service failed: %v", err)
...@@ -79,7 +79,7 @@ func (r *RemoteRuntimeService) RunPodSandbox(config *runtimeapi.PodSandboxConfig ...@@ -79,7 +79,7 @@ func (r *RemoteRuntimeService) RunPodSandbox(config *runtimeapi.PodSandboxConfig
return "", err return "", err
} }
return resp.GetPodSandboxId(), nil return resp.PodSandboxId, nil
} }
// StopPodSandbox stops the sandbox. If there are any running containers in the // StopPodSandbox stops the sandbox. If there are any running containers in the
...@@ -89,7 +89,7 @@ func (r *RemoteRuntimeService) StopPodSandbox(podSandBoxID string) error { ...@@ -89,7 +89,7 @@ func (r *RemoteRuntimeService) StopPodSandbox(podSandBoxID string) error {
defer cancel() defer cancel()
_, err := r.runtimeClient.StopPodSandbox(ctx, &runtimeapi.StopPodSandboxRequest{ _, err := r.runtimeClient.StopPodSandbox(ctx, &runtimeapi.StopPodSandboxRequest{
PodSandboxId: &podSandBoxID, PodSandboxId: podSandBoxID,
}) })
if err != nil { if err != nil {
glog.Errorf("StopPodSandbox %q from runtime service failed: %v", podSandBoxID, err) glog.Errorf("StopPodSandbox %q from runtime service failed: %v", podSandBoxID, err)
...@@ -106,7 +106,7 @@ func (r *RemoteRuntimeService) RemovePodSandbox(podSandBoxID string) error { ...@@ -106,7 +106,7 @@ func (r *RemoteRuntimeService) RemovePodSandbox(podSandBoxID string) error {
defer cancel() defer cancel()
_, err := r.runtimeClient.RemovePodSandbox(ctx, &runtimeapi.RemovePodSandboxRequest{ _, err := r.runtimeClient.RemovePodSandbox(ctx, &runtimeapi.RemovePodSandboxRequest{
PodSandboxId: &podSandBoxID, PodSandboxId: podSandBoxID,
}) })
if err != nil { if err != nil {
glog.Errorf("RemovePodSandbox %q from runtime service failed: %v", podSandBoxID, err) glog.Errorf("RemovePodSandbox %q from runtime service failed: %v", podSandBoxID, err)
...@@ -122,7 +122,7 @@ func (r *RemoteRuntimeService) PodSandboxStatus(podSandBoxID string) (*runtimeap ...@@ -122,7 +122,7 @@ func (r *RemoteRuntimeService) PodSandboxStatus(podSandBoxID string) (*runtimeap
defer cancel() defer cancel()
resp, err := r.runtimeClient.PodSandboxStatus(ctx, &runtimeapi.PodSandboxStatusRequest{ resp, err := r.runtimeClient.PodSandboxStatus(ctx, &runtimeapi.PodSandboxStatusRequest{
PodSandboxId: &podSandBoxID, PodSandboxId: podSandBoxID,
}) })
if err != nil { if err != nil {
glog.Errorf("PodSandboxStatus %q from runtime service failed: %v", podSandBoxID, err) glog.Errorf("PodSandboxStatus %q from runtime service failed: %v", podSandBoxID, err)
...@@ -154,7 +154,7 @@ func (r *RemoteRuntimeService) CreateContainer(podSandBoxID string, config *runt ...@@ -154,7 +154,7 @@ func (r *RemoteRuntimeService) CreateContainer(podSandBoxID string, config *runt
defer cancel() defer cancel()
resp, err := r.runtimeClient.CreateContainer(ctx, &runtimeapi.CreateContainerRequest{ resp, err := r.runtimeClient.CreateContainer(ctx, &runtimeapi.CreateContainerRequest{
PodSandboxId: &podSandBoxID, PodSandboxId: podSandBoxID,
Config: config, Config: config,
SandboxConfig: sandboxConfig, SandboxConfig: sandboxConfig,
}) })
...@@ -163,7 +163,7 @@ func (r *RemoteRuntimeService) CreateContainer(podSandBoxID string, config *runt ...@@ -163,7 +163,7 @@ func (r *RemoteRuntimeService) CreateContainer(podSandBoxID string, config *runt
return "", err return "", err
} }
return resp.GetContainerId(), nil return resp.ContainerId, nil
} }
// StartContainer starts the container. // StartContainer starts the container.
...@@ -172,7 +172,7 @@ func (r *RemoteRuntimeService) StartContainer(containerID string) error { ...@@ -172,7 +172,7 @@ func (r *RemoteRuntimeService) StartContainer(containerID string) error {
defer cancel() defer cancel()
_, err := r.runtimeClient.StartContainer(ctx, &runtimeapi.StartContainerRequest{ _, err := r.runtimeClient.StartContainer(ctx, &runtimeapi.StartContainerRequest{
ContainerId: &containerID, ContainerId: containerID,
}) })
if err != nil { if err != nil {
glog.Errorf("StartContainer %q from runtime service failed: %v", containerID, err) glog.Errorf("StartContainer %q from runtime service failed: %v", containerID, err)
...@@ -188,8 +188,8 @@ func (r *RemoteRuntimeService) StopContainer(containerID string, timeout int64) ...@@ -188,8 +188,8 @@ func (r *RemoteRuntimeService) StopContainer(containerID string, timeout int64)
defer cancel() defer cancel()
_, err := r.runtimeClient.StopContainer(ctx, &runtimeapi.StopContainerRequest{ _, err := r.runtimeClient.StopContainer(ctx, &runtimeapi.StopContainerRequest{
ContainerId: &containerID, ContainerId: containerID,
Timeout: &timeout, Timeout: timeout,
}) })
if err != nil { if err != nil {
glog.Errorf("StopContainer %q from runtime service failed: %v", containerID, err) glog.Errorf("StopContainer %q from runtime service failed: %v", containerID, err)
...@@ -206,7 +206,7 @@ func (r *RemoteRuntimeService) RemoveContainer(containerID string) error { ...@@ -206,7 +206,7 @@ func (r *RemoteRuntimeService) RemoveContainer(containerID string) error {
defer cancel() defer cancel()
_, err := r.runtimeClient.RemoveContainer(ctx, &runtimeapi.RemoveContainerRequest{ _, err := r.runtimeClient.RemoveContainer(ctx, &runtimeapi.RemoveContainerRequest{
ContainerId: &containerID, ContainerId: containerID,
}) })
if err != nil { if err != nil {
glog.Errorf("RemoveContainer %q from runtime service failed: %v", containerID, err) glog.Errorf("RemoveContainer %q from runtime service failed: %v", containerID, err)
...@@ -238,7 +238,7 @@ func (r *RemoteRuntimeService) ContainerStatus(containerID string) (*runtimeapi. ...@@ -238,7 +238,7 @@ func (r *RemoteRuntimeService) ContainerStatus(containerID string) (*runtimeapi.
defer cancel() defer cancel()
resp, err := r.runtimeClient.ContainerStatus(ctx, &runtimeapi.ContainerStatusRequest{ resp, err := r.runtimeClient.ContainerStatus(ctx, &runtimeapi.ContainerStatusRequest{
ContainerId: &containerID, ContainerId: containerID,
}) })
if err != nil { if err != nil {
glog.Errorf("ContainerStatus %q from runtime service failed: %v", containerID, err) glog.Errorf("ContainerStatus %q from runtime service failed: %v", containerID, err)
...@@ -256,9 +256,9 @@ func (r *RemoteRuntimeService) ExecSync(containerID string, cmd []string, timeou ...@@ -256,9 +256,9 @@ func (r *RemoteRuntimeService) ExecSync(containerID string, cmd []string, timeou
timeoutSeconds := int64(timeout.Seconds()) timeoutSeconds := int64(timeout.Seconds())
req := &runtimeapi.ExecSyncRequest{ req := &runtimeapi.ExecSyncRequest{
ContainerId: &containerID, ContainerId: containerID,
Cmd: cmd, Cmd: cmd,
Timeout: &timeoutSeconds, Timeout: timeoutSeconds,
} }
resp, err := r.runtimeClient.ExecSync(ctx, req) resp, err := r.runtimeClient.ExecSync(ctx, req)
if err != nil { if err != nil {
...@@ -267,14 +267,14 @@ func (r *RemoteRuntimeService) ExecSync(containerID string, cmd []string, timeou ...@@ -267,14 +267,14 @@ func (r *RemoteRuntimeService) ExecSync(containerID string, cmd []string, timeou
} }
err = nil err = nil
if resp.GetExitCode() != 0 { if resp.ExitCode != 0 {
err = utilexec.CodeExitError{ err = utilexec.CodeExitError{
Err: fmt.Errorf("command '%s' exited with %d: %s", strings.Join(cmd, " "), resp.GetExitCode(), resp.GetStderr()), Err: fmt.Errorf("command '%s' exited with %d: %s", strings.Join(cmd, " "), resp.ExitCode, resp.Stderr),
Code: int(resp.GetExitCode()), Code: int(resp.ExitCode),
} }
} }
return resp.GetStdout(), resp.GetStderr(), err return resp.Stdout, resp.Stderr, err
} }
// Exec prepares a streaming endpoint to execute a command in the container, and returns the address. // Exec prepares a streaming endpoint to execute a command in the container, and returns the address.
...@@ -284,7 +284,7 @@ func (r *RemoteRuntimeService) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.Ex ...@@ -284,7 +284,7 @@ func (r *RemoteRuntimeService) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.Ex
resp, err := r.runtimeClient.Exec(ctx, req) resp, err := r.runtimeClient.Exec(ctx, req)
if err != nil { if err != nil {
glog.Errorf("Exec %s '%s' from runtime service failed: %v", req.GetContainerId(), strings.Join(req.GetCmd(), " "), err) glog.Errorf("Exec %s '%s' from runtime service failed: %v", req.ContainerId, strings.Join(req.Cmd, " "), err)
return nil, err return nil, err
} }
...@@ -298,7 +298,7 @@ func (r *RemoteRuntimeService) Attach(req *runtimeapi.AttachRequest) (*runtimeap ...@@ -298,7 +298,7 @@ func (r *RemoteRuntimeService) Attach(req *runtimeapi.AttachRequest) (*runtimeap
resp, err := r.runtimeClient.Attach(ctx, req) resp, err := r.runtimeClient.Attach(ctx, req)
if err != nil { if err != nil {
glog.Errorf("Attach %s from runtime service failed: %v", req.GetContainerId(), err) glog.Errorf("Attach %s from runtime service failed: %v", req.ContainerId, err)
return nil, err return nil, err
} }
...@@ -312,7 +312,7 @@ func (r *RemoteRuntimeService) PortForward(req *runtimeapi.PortForwardRequest) ( ...@@ -312,7 +312,7 @@ func (r *RemoteRuntimeService) PortForward(req *runtimeapi.PortForwardRequest) (
resp, err := r.runtimeClient.PortForward(ctx, req) resp, err := r.runtimeClient.PortForward(ctx, req)
if err != nil { if err != nil {
glog.Errorf("PortForward %s from runtime service failed: %v", req.GetPodSandboxId(), err) glog.Errorf("PortForward %s from runtime service failed: %v", req.PodSandboxId, err)
return nil, err return nil, err
} }
......
...@@ -90,16 +90,14 @@ type fakeContainer struct { ...@@ -90,16 +90,14 @@ type fakeContainer struct {
func (c *fakeContainer) Start() { func (c *fakeContainer) Start() {
c.State = runtimeapi.ContainerState_CONTAINER_RUNNING c.State = runtimeapi.ContainerState_CONTAINER_RUNNING
c.Status.State = &c.State c.Status.State = c.State
} }
func (c *fakeContainer) Stop() { func (c *fakeContainer) Stop() {
c.State = runtimeapi.ContainerState_CONTAINER_EXITED c.State = runtimeapi.ContainerState_CONTAINER_EXITED
c.Status.State = &c.State c.Status.State = c.State
c.Status.ExitCode = 0
exitSuccess := int32(0)
c.Status.ExitCode = &exitSuccess
// c.Status.Reason // c.Status.Reason
} }
...@@ -191,7 +189,7 @@ func (r *FakeRuntime) ListContainers(*runtimeapi.ContainerFilter) ([]*runtimeapi ...@@ -191,7 +189,7 @@ func (r *FakeRuntime) ListContainers(*runtimeapi.ContainerFilter) ([]*runtimeapi
Metadata: c.Config.Metadata, Metadata: c.Config.Metadata,
Labels: c.Config.Labels, Labels: c.Config.Labels,
ImageRef: c.Status.ImageRef, ImageRef: c.Status.ImageRef,
State: &c.State, State: c.State,
}) })
} }
...@@ -226,15 +224,15 @@ func (r *FakeRuntime) ExecSync(containerID string, cmd []string, timeout time.Du ...@@ -226,15 +224,15 @@ func (r *FakeRuntime) ExecSync(containerID string, cmd []string, timeout time.Du
} }
func (r *FakeRuntime) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) { func (r *FakeRuntime) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {
url := "http://" + FakeStreamingHost + ":" + FakeStreamingPort + "/exec/" + req.GetContainerId() url := "http://" + FakeStreamingHost + ":" + FakeStreamingPort + "/exec/" + req.ContainerId
return &runtimeapi.ExecResponse{ return &runtimeapi.ExecResponse{
Url: &url, Url: url,
}, nil }, nil
} }
func (r *FakeRuntime) Attach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) { func (r *FakeRuntime) Attach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {
url := "http://" + FakeStreamingHost + ":" + FakeStreamingPort + "/attach/" + req.GetContainerId() url := "http://" + FakeStreamingHost + ":" + FakeStreamingPort + "/attach/" + req.ContainerId
return &runtimeapi.AttachResponse{ return &runtimeapi.AttachResponse{
Url: &url, Url: url,
}, nil }, nil
} }
...@@ -63,19 +63,19 @@ var ( ...@@ -63,19 +63,19 @@ var (
var testImgSpecs = map[string]imageTestCase{ var testImgSpecs = map[string]imageTestCase{
"non-existent-image": { "non-existent-image": {
&runtimeapi.ImageSpec{ &runtimeapi.ImageSpec{
Image: &gibberishStr, Image: gibberishStr,
}, },
nil, nil,
}, },
"busybox": { "busybox": {
&runtimeapi.ImageSpec{ &runtimeapi.ImageSpec{
Image: &busyboxStr, Image: busyboxStr,
}, },
&runtimeapi.Image{ &runtimeapi.Image{
Id: nil, Id: "",
RepoTags: []string{}, RepoTags: []string{},
RepoDigests: []string{}, RepoDigests: []string{},
Size_: nil, Size_: 0,
}, },
}, },
} }
...@@ -201,7 +201,7 @@ func TestListsImages(t *testing.T) { ...@@ -201,7 +201,7 @@ func TestListsImages(t *testing.T) {
} }
for _, img := range imgs { for _, img := range imgs {
expectedImg := *testImgSpecs[*img.Id].ExpectedStatus expectedImg := *testImgSpecs[img.Id].ExpectedStatus
if err := compareContainerImages(img, expectedImg); err != nil { if err := compareContainerImages(img, expectedImg); err != nil {
t.Errorf("rktshim.ImageStore.List() for %q, %v", img.Id, err) t.Errorf("rktshim.ImageStore.List() for %q, %v", img.Id, err)
......
...@@ -146,7 +146,7 @@ type server struct { ...@@ -146,7 +146,7 @@ type server struct {
} }
func (s *server) GetExec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) { func (s *server) GetExec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {
if req.GetContainerId() == "" { if req.ContainerId == "" {
return nil, grpc.Errorf(codes.InvalidArgument, "missing required container_id") return nil, grpc.Errorf(codes.InvalidArgument, "missing required container_id")
} }
token, err := s.cache.Insert(req) token, err := s.cache.Insert(req)
...@@ -159,7 +159,7 @@ func (s *server) GetExec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, ...@@ -159,7 +159,7 @@ func (s *server) GetExec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse,
} }
func (s *server) GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) { func (s *server) GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {
if req.GetContainerId() == "" { if req.ContainerId == "" {
return nil, grpc.Errorf(codes.InvalidArgument, "missing required container_id") return nil, grpc.Errorf(codes.InvalidArgument, "missing required container_id")
} }
token, err := s.cache.Insert(req) token, err := s.cache.Insert(req)
...@@ -172,7 +172,7 @@ func (s *server) GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachRes ...@@ -172,7 +172,7 @@ func (s *server) GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachRes
} }
func (s *server) GetPortForward(req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) { func (s *server) GetPortForward(req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {
if req.GetPodSandboxId() == "" { if req.PodSandboxId == "" {
return nil, grpc.Errorf(codes.InvalidArgument, "missing required pod_sandbox_id") return nil, grpc.Errorf(codes.InvalidArgument, "missing required pod_sandbox_id")
} }
token, err := s.cache.Insert(req) token, err := s.cache.Insert(req)
...@@ -211,11 +211,10 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { ...@@ -211,11 +211,10 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.handler.ServeHTTP(w, r) s.handler.ServeHTTP(w, r)
} }
func (s *server) buildURL(method, token string) *string { func (s *server) buildURL(method, token string) string {
loc := s.config.BaseURL.ResolveReference(&url.URL{ return s.config.BaseURL.ResolveReference(&url.URL{
Path: path.Join(method, token), Path: path.Join(method, token),
}).String() }).String()
return &loc
} }
func (s *server) serveExec(req *restful.Request, resp *restful.Response) { func (s *server) serveExec(req *restful.Request, resp *restful.Response) {
...@@ -232,10 +231,10 @@ func (s *server) serveExec(req *restful.Request, resp *restful.Response) { ...@@ -232,10 +231,10 @@ func (s *server) serveExec(req *restful.Request, resp *restful.Response) {
} }
streamOpts := &remotecommand.Options{ streamOpts := &remotecommand.Options{
Stdin: exec.GetStdin(), Stdin: exec.Stdin,
Stdout: true, Stdout: true,
Stderr: !exec.GetTty(), Stderr: !exec.Tty,
TTY: exec.GetTty(), TTY: exec.Tty,
} }
remotecommand.ServeExec( remotecommand.ServeExec(
...@@ -244,8 +243,8 @@ func (s *server) serveExec(req *restful.Request, resp *restful.Response) { ...@@ -244,8 +243,8 @@ func (s *server) serveExec(req *restful.Request, resp *restful.Response) {
s.runtime, s.runtime,
"", // unused: podName "", // unused: podName
"", // unusued: podUID "", // unusued: podUID
exec.GetContainerId(), exec.ContainerId,
exec.GetCmd(), exec.Cmd,
streamOpts, streamOpts,
s.config.StreamIdleTimeout, s.config.StreamIdleTimeout,
s.config.StreamCreationTimeout, s.config.StreamCreationTimeout,
...@@ -266,10 +265,10 @@ func (s *server) serveAttach(req *restful.Request, resp *restful.Response) { ...@@ -266,10 +265,10 @@ func (s *server) serveAttach(req *restful.Request, resp *restful.Response) {
} }
streamOpts := &remotecommand.Options{ streamOpts := &remotecommand.Options{
Stdin: attach.GetStdin(), Stdin: attach.Stdin,
Stdout: true, Stdout: true,
Stderr: !attach.GetTty(), Stderr: !attach.Tty,
TTY: attach.GetTty(), TTY: attach.Tty,
} }
remotecommand.ServeAttach( remotecommand.ServeAttach(
resp.ResponseWriter, resp.ResponseWriter,
...@@ -277,7 +276,7 @@ func (s *server) serveAttach(req *restful.Request, resp *restful.Response) { ...@@ -277,7 +276,7 @@ func (s *server) serveAttach(req *restful.Request, resp *restful.Response) {
s.runtime, s.runtime,
"", // unused: podName "", // unused: podName
"", // unusued: podUID "", // unusued: podUID
attach.GetContainerId(), attach.ContainerId,
streamOpts, streamOpts,
s.config.StreamIdleTimeout, s.config.StreamIdleTimeout,
s.config.StreamCreationTimeout, s.config.StreamCreationTimeout,
...@@ -301,7 +300,7 @@ func (s *server) servePortForward(req *restful.Request, resp *restful.Response) ...@@ -301,7 +300,7 @@ func (s *server) servePortForward(req *restful.Request, resp *restful.Response)
resp.ResponseWriter, resp.ResponseWriter,
req.Request, req.Request,
s.runtime, s.runtime,
pf.GetPodSandboxId(), pf.PodSandboxId,
"", // unused: podUID "", // unused: podUID
s.config.StreamIdleTimeout, s.config.StreamIdleTimeout,
s.config.StreamCreationTimeout) s.config.StreamCreationTimeout)
......
...@@ -82,25 +82,25 @@ func TestGetExec(t *testing.T) { ...@@ -82,25 +82,25 @@ func TestGetExec(t *testing.T) {
assertRequestToken := func(test testcase, cache *requestCache, token string) { assertRequestToken := func(test testcase, cache *requestCache, token string) {
req, ok := cache.Consume(token) req, ok := cache.Consume(token)
require.True(t, ok, "token %s not found! testcase=%+v", token, test) require.True(t, ok, "token %s not found! testcase=%+v", token, test)
assert.Equal(t, testContainerID, req.(*runtimeapi.ExecRequest).GetContainerId(), "testcase=%+v", test) assert.Equal(t, testContainerID, req.(*runtimeapi.ExecRequest).ContainerId, "testcase=%+v", test)
assert.Equal(t, test.cmd, req.(*runtimeapi.ExecRequest).GetCmd(), "testcase=%+v", test) assert.Equal(t, test.cmd, req.(*runtimeapi.ExecRequest).Cmd, "testcase=%+v", test)
assert.Equal(t, test.tty, req.(*runtimeapi.ExecRequest).GetTty(), "testcase=%+v", test) assert.Equal(t, test.tty, req.(*runtimeapi.ExecRequest).Tty, "testcase=%+v", test)
assert.Equal(t, test.stdin, req.(*runtimeapi.ExecRequest).GetStdin(), "testcase=%+v", test) assert.Equal(t, test.stdin, req.(*runtimeapi.ExecRequest).Stdin, "testcase=%+v", test)
} }
containerID := testContainerID containerID := testContainerID
for _, test := range testcases { for _, test := range testcases {
request := &runtimeapi.ExecRequest{ request := &runtimeapi.ExecRequest{
ContainerId: &containerID, ContainerId: containerID,
Cmd: test.cmd, Cmd: test.cmd,
Tty: &test.tty, Tty: test.tty,
Stdin: &test.stdin, Stdin: test.stdin,
} }
{ // Non-TLS { // Non-TLS
resp, err := serv.GetExec(request) resp, err := serv.GetExec(request)
assert.NoError(t, err, "testcase=%+v", test) assert.NoError(t, err, "testcase=%+v", test)
expectedURL := "http://" + testAddr + "/exec/" expectedURL := "http://" + testAddr + "/exec/"
assert.Contains(t, resp.GetUrl(), expectedURL, "testcase=%+v", test) assert.Contains(t, resp.Url, expectedURL, "testcase=%+v", test)
token := strings.TrimPrefix(resp.GetUrl(), expectedURL) token := strings.TrimPrefix(resp.Url, expectedURL)
assertRequestToken(test, serv.(*server).cache, token) assertRequestToken(test, serv.(*server).cache, token)
} }
...@@ -108,8 +108,8 @@ func TestGetExec(t *testing.T) { ...@@ -108,8 +108,8 @@ func TestGetExec(t *testing.T) {
resp, err := tlsServer.GetExec(request) resp, err := tlsServer.GetExec(request)
assert.NoError(t, err, "testcase=%+v", test) assert.NoError(t, err, "testcase=%+v", test)
expectedURL := "https://" + testAddr + "/exec/" expectedURL := "https://" + testAddr + "/exec/"
assert.Contains(t, resp.GetUrl(), expectedURL, "testcase=%+v", test) assert.Contains(t, resp.Url, expectedURL, "testcase=%+v", test)
token := strings.TrimPrefix(resp.GetUrl(), expectedURL) token := strings.TrimPrefix(resp.Url, expectedURL)
assertRequestToken(test, tlsServer.(*server).cache, token) assertRequestToken(test, tlsServer.(*server).cache, token)
} }
...@@ -117,8 +117,8 @@ func TestGetExec(t *testing.T) { ...@@ -117,8 +117,8 @@ func TestGetExec(t *testing.T) {
resp, err := prefixServer.GetExec(request) resp, err := prefixServer.GetExec(request)
assert.NoError(t, err, "testcase=%+v", test) assert.NoError(t, err, "testcase=%+v", test)
expectedURL := "http://" + testAddr + "/" + pathPrefix + "/exec/" expectedURL := "http://" + testAddr + "/" + pathPrefix + "/exec/"
assert.Contains(t, resp.GetUrl(), expectedURL, "testcase=%+v", test) assert.Contains(t, resp.Url, expectedURL, "testcase=%+v", test)
token := strings.TrimPrefix(resp.GetUrl(), expectedURL) token := strings.TrimPrefix(resp.Url, expectedURL)
assertRequestToken(test, prefixServer.(*server).cache, token) assertRequestToken(test, prefixServer.(*server).cache, token)
} }
} }
...@@ -149,23 +149,23 @@ func TestGetAttach(t *testing.T) { ...@@ -149,23 +149,23 @@ func TestGetAttach(t *testing.T) {
assertRequestToken := func(test testcase, cache *requestCache, token string) { assertRequestToken := func(test testcase, cache *requestCache, token string) {
req, ok := cache.Consume(token) req, ok := cache.Consume(token)
require.True(t, ok, "token %s not found! testcase=%+v", token, test) require.True(t, ok, "token %s not found! testcase=%+v", token, test)
assert.Equal(t, testContainerID, req.(*runtimeapi.AttachRequest).GetContainerId(), "testcase=%+v", test) assert.Equal(t, testContainerID, req.(*runtimeapi.AttachRequest).ContainerId, "testcase=%+v", test)
assert.Equal(t, test.tty, req.(*runtimeapi.AttachRequest).GetTty(), "testcase=%+v", test) assert.Equal(t, test.tty, req.(*runtimeapi.AttachRequest).Tty, "testcase=%+v", test)
assert.Equal(t, test.stdin, req.(*runtimeapi.AttachRequest).GetStdin(), "testcase=%+v", test) assert.Equal(t, test.stdin, req.(*runtimeapi.AttachRequest).Stdin, "testcase=%+v", test)
} }
containerID := testContainerID containerID := testContainerID
for _, test := range testcases { for _, test := range testcases {
request := &runtimeapi.AttachRequest{ request := &runtimeapi.AttachRequest{
ContainerId: &containerID, ContainerId: containerID,
Stdin: &test.stdin, Stdin: test.stdin,
Tty: &test.tty, Tty: test.tty,
} }
{ // Non-TLS { // Non-TLS
resp, err := serv.GetAttach(request) resp, err := serv.GetAttach(request)
assert.NoError(t, err, "testcase=%+v", test) assert.NoError(t, err, "testcase=%+v", test)
expectedURL := "http://" + testAddr + "/attach/" expectedURL := "http://" + testAddr + "/attach/"
assert.Contains(t, resp.GetUrl(), expectedURL, "testcase=%+v", test) assert.Contains(t, resp.Url, expectedURL, "testcase=%+v", test)
token := strings.TrimPrefix(resp.GetUrl(), expectedURL) token := strings.TrimPrefix(resp.Url, expectedURL)
assertRequestToken(test, serv.(*server).cache, token) assertRequestToken(test, serv.(*server).cache, token)
} }
...@@ -173,8 +173,8 @@ func TestGetAttach(t *testing.T) { ...@@ -173,8 +173,8 @@ func TestGetAttach(t *testing.T) {
resp, err := tlsServer.GetAttach(request) resp, err := tlsServer.GetAttach(request)
assert.NoError(t, err, "testcase=%+v", test) assert.NoError(t, err, "testcase=%+v", test)
expectedURL := "https://" + testAddr + "/attach/" expectedURL := "https://" + testAddr + "/attach/"
assert.Contains(t, resp.GetUrl(), expectedURL, "testcase=%+v", test) assert.Contains(t, resp.Url, expectedURL, "testcase=%+v", test)
token := strings.TrimPrefix(resp.GetUrl(), expectedURL) token := strings.TrimPrefix(resp.Url, expectedURL)
assertRequestToken(test, tlsServer.(*server).cache, token) assertRequestToken(test, tlsServer.(*server).cache, token)
} }
} }
...@@ -183,7 +183,7 @@ func TestGetAttach(t *testing.T) { ...@@ -183,7 +183,7 @@ func TestGetAttach(t *testing.T) {
func TestGetPortForward(t *testing.T) { func TestGetPortForward(t *testing.T) {
podSandboxID := testPodSandboxID podSandboxID := testPodSandboxID
request := &runtimeapi.PortForwardRequest{ request := &runtimeapi.PortForwardRequest{
PodSandboxId: &podSandboxID, PodSandboxId: podSandboxID,
Port: []int32{1, 2, 3, 4}, Port: []int32{1, 2, 3, 4},
} }
...@@ -195,11 +195,11 @@ func TestGetPortForward(t *testing.T) { ...@@ -195,11 +195,11 @@ func TestGetPortForward(t *testing.T) {
resp, err := serv.GetPortForward(request) resp, err := serv.GetPortForward(request)
assert.NoError(t, err) assert.NoError(t, err)
expectedURL := "http://" + testAddr + "/portforward/" expectedURL := "http://" + testAddr + "/portforward/"
assert.True(t, strings.HasPrefix(resp.GetUrl(), expectedURL)) assert.True(t, strings.HasPrefix(resp.Url, expectedURL))
token := strings.TrimPrefix(resp.GetUrl(), expectedURL) token := strings.TrimPrefix(resp.Url, expectedURL)
req, ok := serv.(*server).cache.Consume(token) req, ok := serv.(*server).cache.Consume(token)
require.True(t, ok, "token %s not found!", token) require.True(t, ok, "token %s not found!", token)
assert.Equal(t, testPodSandboxID, req.(*runtimeapi.PortForwardRequest).GetPodSandboxId()) assert.Equal(t, testPodSandboxID, req.(*runtimeapi.PortForwardRequest).PodSandboxId)
} }
{ // TLS { // TLS
...@@ -211,11 +211,11 @@ func TestGetPortForward(t *testing.T) { ...@@ -211,11 +211,11 @@ func TestGetPortForward(t *testing.T) {
resp, err := tlsServer.GetPortForward(request) resp, err := tlsServer.GetPortForward(request)
assert.NoError(t, err) assert.NoError(t, err)
expectedURL := "https://" + testAddr + "/portforward/" expectedURL := "https://" + testAddr + "/portforward/"
assert.True(t, strings.HasPrefix(resp.GetUrl(), expectedURL)) assert.True(t, strings.HasPrefix(resp.Url, expectedURL))
token := strings.TrimPrefix(resp.GetUrl(), expectedURL) token := strings.TrimPrefix(resp.Url, expectedURL)
req, ok := tlsServer.(*server).cache.Consume(token) req, ok := tlsServer.(*server).cache.Consume(token)
require.True(t, ok, "token %s not found!", token) require.True(t, ok, "token %s not found!", token)
assert.Equal(t, testPodSandboxID, req.(*runtimeapi.PortForwardRequest).GetPodSandboxId()) assert.Equal(t, testPodSandboxID, req.(*runtimeapi.PortForwardRequest).PodSandboxId)
} }
} }
...@@ -231,12 +231,11 @@ func TestServePortForward(t *testing.T) { ...@@ -231,12 +231,11 @@ func TestServePortForward(t *testing.T) {
s, testServer := startTestServer(t) s, testServer := startTestServer(t)
defer testServer.Close() defer testServer.Close()
podSandboxID := testPodSandboxID
resp, err := s.GetPortForward(&runtimeapi.PortForwardRequest{ resp, err := s.GetPortForward(&runtimeapi.PortForwardRequest{
PodSandboxId: &podSandboxID, PodSandboxId: testPodSandboxID,
}) })
require.NoError(t, err) require.NoError(t, err)
reqURL, err := url.Parse(resp.GetUrl()) reqURL, err := url.Parse(resp.Url)
require.NoError(t, err) require.NoError(t, err)
exec, err := remotecommand.NewExecutor(&restclient.Config{}, "POST", reqURL) exec, err := remotecommand.NewExecutor(&restclient.Config{}, "POST", reqURL)
...@@ -273,20 +272,20 @@ func runRemoteCommandTest(t *testing.T, commandType string) { ...@@ -273,20 +272,20 @@ func runRemoteCommandTest(t *testing.T, commandType string) {
switch commandType { switch commandType {
case "exec": case "exec":
resp, err := s.GetExec(&runtimeapi.ExecRequest{ resp, err := s.GetExec(&runtimeapi.ExecRequest{
ContainerId: &containerID, ContainerId: containerID,
Cmd: []string{"echo"}, Cmd: []string{"echo"},
Stdin: &stdin, Stdin: stdin,
}) })
require.NoError(t, err) require.NoError(t, err)
reqURL, err = url.Parse(resp.GetUrl()) reqURL, err = url.Parse(resp.Url)
require.NoError(t, err) require.NoError(t, err)
case "attach": case "attach":
resp, err := s.GetAttach(&runtimeapi.AttachRequest{ resp, err := s.GetAttach(&runtimeapi.AttachRequest{
ContainerId: &containerID, ContainerId: containerID,
Stdin: &stdin, Stdin: stdin,
}) })
require.NoError(t, err) require.NoError(t, err)
reqURL, err = url.Parse(resp.GetUrl()) reqURL, err = url.Parse(resp.Url)
require.NoError(t, err) require.NoError(t, err)
} }
......
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