vendor: remove dep and use vndr

Signed-off-by: Antonio Murdaca <runcom@redhat.com>
This commit is contained in:
Antonio Murdaca 2017-06-06 09:19:04 +02:00
parent 16f44674a4
commit 148e72d81e
No known key found for this signature in database
GPG key ID: B2BEAD150DE936B9
16131 changed files with 73815 additions and 4235138 deletions

View file

@ -1,92 +0,0 @@
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"cache.go",
"container_gc.go",
"container_reference_manager.go",
"helpers.go",
"os.go",
"pty_linux.go",
"ref.go",
"resize.go",
"runtime.go",
"runtime_cache.go",
"runtime_cache_fake.go",
"sync_result.go",
],
tags = ["automanaged"],
deps = [
"//pkg/api/v1:go_default_library",
"//pkg/client/record:go_default_library",
"//pkg/kubelet/api/v1alpha1/runtime:go_default_library",
"//pkg/kubelet/util/format:go_default_library",
"//pkg/kubelet/util/ioutils:go_default_library",
"//pkg/util/hash:go_default_library",
"//pkg/util/term:go_default_library",
"//pkg/volume:go_default_library",
"//third_party/forked/golang/expansion:go_default_library",
"//vendor:github.com/golang/glog",
"//vendor:github.com/kr/pty",
"//vendor:k8s.io/apimachinery/pkg/apis/meta/v1",
"//vendor:k8s.io/apimachinery/pkg/runtime",
"//vendor:k8s.io/apimachinery/pkg/types",
"//vendor:k8s.io/apimachinery/pkg/util/errors",
"//vendor:k8s.io/apimachinery/pkg/util/runtime",
"//vendor:k8s.io/client-go/util/flowcontrol",
],
)
go_test(
name = "go_default_test",
srcs = [
"cache_test.go",
"helpers_test.go",
"ref_test.go",
"sync_result_test.go",
],
library = ":go_default_library",
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/api/v1:go_default_library",
"//vendor:github.com/stretchr/testify/assert",
"//vendor:k8s.io/apimachinery/pkg/apis/meta/v1",
"//vendor:k8s.io/apimachinery/pkg/types",
],
)
go_test(
name = "go_default_xtest",
srcs = ["runtime_cache_test.go"],
tags = ["automanaged"],
deps = [
"//pkg/kubelet/container:go_default_library",
"//pkg/kubelet/container/testing:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//pkg/kubelet/container/testing:all-srcs",
],
tags = ["automanaged"],
)

View file

@ -1,210 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container
import (
"fmt"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/types"
)
func newTestCache() *cache {
c := NewCache()
return c.(*cache)
}
func TestCacheNotInitialized(t *testing.T) {
cache := newTestCache()
// If the global timestamp is not set, always return nil.
d := cache.getIfNewerThan(types.UID("1234"), time.Time{})
assert.True(t, d == nil, "should return nil since cache is not initialized")
}
func getTestPodIDAndStatus(numContainers int) (types.UID, *PodStatus) {
id := types.UID(strconv.FormatInt(time.Now().UnixNano(), 10))
name := fmt.Sprintf("cache-foo-%s", string(id))
namespace := "ns"
var status *PodStatus
if numContainers > 0 {
status = &PodStatus{ID: id, Name: name, Namespace: namespace}
} else {
status = &PodStatus{ID: id}
}
for i := 0; i < numContainers; i++ {
status.ContainerStatuses = append(status.ContainerStatuses, &ContainerStatus{Name: string(i)})
}
return id, status
}
func TestGetIfNewerThanWhenPodExists(t *testing.T) {
cache := newTestCache()
timestamp := time.Now()
cases := []struct {
cacheTime time.Time
modified time.Time
expected bool
}{
{
// Both the global cache timestamp and the modified time are newer
// than the timestamp.
cacheTime: timestamp.Add(time.Second),
modified: timestamp,
expected: true,
},
{
// Global cache timestamp is newer, but the pod entry modified
// time is older than the given timestamp. This means that the
// entry is up-to-date even though it hasn't changed for a while.
cacheTime: timestamp.Add(time.Second),
modified: timestamp.Add(-time.Second * 10),
expected: true,
},
{
// Global cache timestamp is older, but the pod entry modified
// time is newer than the given timestamp. This means that the
// entry is up-to-date but the rest of the cache are still being
// updated.
cacheTime: timestamp.Add(-time.Second),
modified: timestamp.Add(time.Second * 3),
expected: true,
},
{
// Both the global cache timestamp and the modified time are older
// than the given timestamp.
cacheTime: timestamp.Add(-time.Second),
modified: timestamp.Add(-time.Second),
expected: false,
},
}
for i, c := range cases {
podID, status := getTestPodIDAndStatus(2)
cache.UpdateTime(c.cacheTime)
cache.Set(podID, status, nil, c.modified)
d := cache.getIfNewerThan(podID, timestamp)
assert.Equal(t, c.expected, d != nil, "test[%d]", i)
}
}
func TestGetPodNewerThanWhenPodDoesNotExist(t *testing.T) {
cache := newTestCache()
cacheTime := time.Now()
cache.UpdateTime(cacheTime)
podID := types.UID("1234")
cases := []struct {
timestamp time.Time
expected bool
}{
{
timestamp: cacheTime.Add(-time.Second),
expected: true,
},
{
timestamp: cacheTime.Add(time.Second),
expected: false,
},
}
for i, c := range cases {
d := cache.getIfNewerThan(podID, c.timestamp)
assert.Equal(t, c.expected, d != nil, "test[%d]", i)
}
}
func TestCacheSetAndGet(t *testing.T) {
cache := NewCache()
cases := []struct {
numContainers int
error error
}{
{numContainers: 3, error: nil},
{numContainers: 2, error: fmt.Errorf("unable to get status")},
{numContainers: 0, error: nil},
}
for i, c := range cases {
podID, status := getTestPodIDAndStatus(c.numContainers)
cache.Set(podID, status, c.error, time.Time{})
// Read back the status and error stored in cache and make sure they
// match the original ones.
actualStatus, actualErr := cache.Get(podID)
assert.Equal(t, status, actualStatus, "test[%d]", i)
assert.Equal(t, c.error, actualErr, "test[%d]", i)
}
}
func TestCacheGetPodDoesNotExist(t *testing.T) {
cache := NewCache()
podID, status := getTestPodIDAndStatus(0)
// If the pod does not exist in cache, cache should return an status
// object with id filled.
actualStatus, actualErr := cache.Get(podID)
assert.Equal(t, status, actualStatus)
assert.Equal(t, nil, actualErr)
}
func TestDelete(t *testing.T) {
cache := &cache{pods: map[types.UID]*data{}}
// Write a new pod status into the cache.
podID, status := getTestPodIDAndStatus(3)
cache.Set(podID, status, nil, time.Time{})
actualStatus, actualErr := cache.Get(podID)
assert.Equal(t, status, actualStatus)
assert.Equal(t, nil, actualErr)
// Delete the pod from cache, and verify that we get an empty status.
cache.Delete(podID)
expectedStatus := &PodStatus{ID: podID}
actualStatus, actualErr = cache.Get(podID)
assert.Equal(t, expectedStatus, actualStatus)
assert.Equal(t, nil, actualErr)
}
func verifyNotification(t *testing.T, ch chan *data, expectNotification bool) {
if expectNotification {
assert.True(t, len(ch) > 0, "Did not receive notification")
} else {
assert.True(t, len(ch) < 1, "Should not have triggered the notification")
}
// Drain the channel.
for i := 0; i < len(ch); i++ {
<-ch
}
}
func TestRegisterNotification(t *testing.T) {
cache := newTestCache()
cacheTime := time.Now()
cache.UpdateTime(cacheTime)
podID, status := getTestPodIDAndStatus(1)
ch := cache.subscribe(podID, cacheTime.Add(time.Second))
verifyNotification(t, ch, false)
cache.Set(podID, status, nil, cacheTime.Add(time.Second))
// The Set operation should've triggered the notification.
verifyNotification(t, ch, true)
podID, _ = getTestPodIDAndStatus(1)
ch = cache.subscribe(podID, cacheTime.Add(time.Second))
verifyNotification(t, ch, false)
cache.UpdateTime(cacheTime.Add(time.Second * 2))
// The advance of cache timestamp should've triggered the notification.
verifyNotification(t, ch, true)
}

View file

@ -20,6 +20,7 @@ import (
"bytes"
"fmt"
"hash/adler32"
"hash/fnv"
"strings"
"time"
@ -28,9 +29,11 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
clientv1 "k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/tools/record"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/pkg/client/record"
runtimeapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
"k8s.io/kubernetes/pkg/kubelet/events"
"k8s.io/kubernetes/pkg/kubelet/util/format"
"k8s.io/kubernetes/pkg/kubelet/util/ioutils"
hashutil "k8s.io/kubernetes/pkg/util/hash"
@ -45,8 +48,11 @@ type HandlerRunner interface {
// RuntimeHelper wraps kubelet to make container runtime
// able to get necessary informations like the RunContainerOptions, DNS settings.
type RuntimeHelper interface {
GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (*RunContainerOptions, error)
GetClusterDNS(pod *v1.Pod) (dnsServers []string, dnsSearches []string, err error)
GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (contOpts *RunContainerOptions, useClusterFirstPolicy bool, err error)
GetClusterDNS(pod *v1.Pod) (dnsServers []string, dnsSearches []string, useClusterFirstPolicy bool, err error)
// GetPodCgroupParent returns the the CgroupName identifer, and its literal cgroupfs form on the host
// of a pod.
GetPodCgroupParent(pod *v1.Pod) string
GetPodDir(podUID types.UID) string
GeneratePodHostNameAndDomain(pod *v1.Pod) (hostname string, hostDomain string, err error)
// GetExtraSupplementalGroupsForPod returns a list of the extra
@ -69,8 +75,8 @@ func ShouldContainerBeRestarted(container *v1.Container, pod *v1.Pod, podStatus
if status.State == ContainerStateRunning {
return false
}
// Always restart container in unknown state now
if status.State == ContainerStateUnknown {
// Always restart container in the unknown, or in the created state.
if status.State == ContainerStateUnknown || status.State == ContainerStateCreated {
return true
}
// Check RestartPolicy for dead container
@ -91,6 +97,15 @@ func ShouldContainerBeRestarted(container *v1.Container, pod *v1.Pod, podStatus
// HashContainer returns the hash of the container. It is used to compare
// the running container with its desired spec.
func HashContainer(container *v1.Container) uint64 {
hash := fnv.New32a()
hashutil.DeepHashObject(hash, *container)
return uint64(hash.Sum32())
}
// HashContainerLegacy returns the hash of the container. It is used to compare
// the running container with its desired spec.
// TODO: Delete this function after we deprecate dockertools.
func HashContainerLegacy(container *v1.Container) uint64 {
hash := adler32.New()
hashutil.DeepHashObject(hash, *container)
return uint64(hash.Sum32())
@ -103,10 +118,33 @@ func EnvVarsToMap(envs []EnvVar) map[string]string {
for _, env := range envs {
result[env.Name] = env.Value
}
return result
}
// V1EnvVarsToMap constructs a map of environment name to value from a slice
// of env vars.
func V1EnvVarsToMap(envs []v1.EnvVar) map[string]string {
result := map[string]string{}
for _, env := range envs {
result[env.Name] = env.Value
}
return result
}
// ExpandContainerCommandOnlyStatic substitutes only static environment variable values from the
// container environment definitions. This does *not* include valueFrom substitutions.
// TODO: callers should use ExpandContainerCommandAndArgs with a fully resolved list of environment.
func ExpandContainerCommandOnlyStatic(containerCommand []string, envs []v1.EnvVar) (command []string) {
mapping := expansion.MappingFuncFor(V1EnvVarsToMap(envs))
if len(containerCommand) != 0 {
for _, cmd := range containerCommand {
command = append(command, expansion.Expand(cmd, mapping))
}
}
return command
}
func ExpandContainerCommandAndArgs(container *v1.Container, envs []EnvVar) (command []string, args []string) {
mapping := expansion.MappingFuncFor(EnvVarsToMap(envs))
@ -136,15 +174,21 @@ type innerEventRecorder struct {
recorder record.EventRecorder
}
func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*v1.ObjectReference, bool) {
func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*clientv1.ObjectReference, bool) {
if object == nil {
return nil, false
}
if ref, ok := object.(*v1.ObjectReference); ok {
if ref, ok := object.(*clientv1.ObjectReference); ok {
if !strings.HasPrefix(ref.FieldPath, ImplicitContainerPrefix) {
return ref, true
}
}
// just in case we miss a spot, be sure that we still log something
if ref, ok := object.(*v1.ObjectReference); ok {
if !strings.HasPrefix(ref.FieldPath, ImplicitContainerPrefix) {
return events.ToObjectReference(ref), true
}
}
return nil, false
}
@ -273,3 +317,49 @@ func HasPrivilegedContainer(pod *v1.Pod) bool {
}
return false
}
// MakeCapabilities creates string slices from Capability slices
func MakeCapabilities(capAdd []v1.Capability, capDrop []v1.Capability) ([]string, []string) {
var (
addCaps []string
dropCaps []string
)
for _, cap := range capAdd {
addCaps = append(addCaps, string(cap))
}
for _, cap := range capDrop {
dropCaps = append(dropCaps, string(cap))
}
return addCaps, dropCaps
}
// MakePortMappings creates internal port mapping from api port mapping.
func MakePortMappings(container *v1.Container) (ports []PortMapping) {
names := make(map[string]struct{})
for _, p := range container.Ports {
pm := PortMapping{
HostPort: int(p.HostPort),
ContainerPort: int(p.ContainerPort),
Protocol: p.Protocol,
HostIP: p.HostIP,
}
// We need to create some default port name if it's not specified, since
// this is necessary for rkt.
// http://issue.k8s.io/7710
if p.Name == "" {
pm.Name = fmt.Sprintf("%s-%s:%d", container.Name, p.Protocol, p.ContainerPort)
} else {
pm.Name = fmt.Sprintf("%s-%s", container.Name, p.Name)
}
// Protect against exposing the same protocol-port more than once in a container.
if _, ok := names[pm.Name]; ok {
glog.Warningf("Port name conflicted, %q is defined more than once", pm.Name)
continue
}
ports = append(ports, pm)
names[pm.Name] = struct{}{}
}
return
}

View file

@ -1,255 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container
import (
"reflect"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/api/v1"
)
func TestEnvVarsToMap(t *testing.T) {
vars := []EnvVar{
{
Name: "foo",
Value: "bar",
},
{
Name: "zoo",
Value: "baz",
},
}
varMap := EnvVarsToMap(vars)
if e, a := len(vars), len(varMap); e != a {
t.Errorf("Unexpected map length; expected: %d, got %d", e, a)
}
if a := varMap["foo"]; a != "bar" {
t.Errorf("Unexpected value of key 'foo': %v", a)
}
if a := varMap["zoo"]; a != "baz" {
t.Errorf("Unexpected value of key 'zoo': %v", a)
}
}
func TestExpandCommandAndArgs(t *testing.T) {
cases := []struct {
name string
container *v1.Container
envs []EnvVar
expectedCommand []string
expectedArgs []string
}{
{
name: "none",
container: &v1.Container{},
},
{
name: "command expanded",
container: &v1.Container{
Command: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"},
},
envs: []EnvVar{
{
Name: "VAR_TEST",
Value: "zoo",
},
{
Name: "VAR_TEST2",
Value: "boo",
},
},
expectedCommand: []string{"foo", "zoo", "boo"},
},
{
name: "args expanded",
container: &v1.Container{
Args: []string{"zap", "$(VAR_TEST)", "$(VAR_TEST2)"},
},
envs: []EnvVar{
{
Name: "VAR_TEST",
Value: "hap",
},
{
Name: "VAR_TEST2",
Value: "trap",
},
},
expectedArgs: []string{"zap", "hap", "trap"},
},
{
name: "both expanded",
container: &v1.Container{
Command: []string{"$(VAR_TEST2)--$(VAR_TEST)", "foo", "$(VAR_TEST3)"},
Args: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"},
},
envs: []EnvVar{
{
Name: "VAR_TEST",
Value: "zoo",
},
{
Name: "VAR_TEST2",
Value: "boo",
},
{
Name: "VAR_TEST3",
Value: "roo",
},
},
expectedCommand: []string{"boo--zoo", "foo", "roo"},
expectedArgs: []string{"foo", "zoo", "boo"},
},
}
for _, tc := range cases {
actualCommand, actualArgs := ExpandContainerCommandAndArgs(tc.container, tc.envs)
if e, a := tc.expectedCommand, actualCommand; !reflect.DeepEqual(e, a) {
t.Errorf("%v: unexpected command; expected %v, got %v", tc.name, e, a)
}
if e, a := tc.expectedArgs, actualArgs; !reflect.DeepEqual(e, a) {
t.Errorf("%v: unexpected args; expected %v, got %v", tc.name, e, a)
}
}
}
func TestShouldContainerBeRestarted(t *testing.T) {
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
UID: "12345678",
Name: "foo",
Namespace: "new",
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{Name: "no-history"},
{Name: "alive"},
{Name: "succeed"},
{Name: "failed"},
{Name: "unknown"},
},
},
}
podStatus := &PodStatus{
ID: pod.UID,
Name: pod.Name,
Namespace: pod.Namespace,
ContainerStatuses: []*ContainerStatus{
{
Name: "alive",
State: ContainerStateRunning,
},
{
Name: "succeed",
State: ContainerStateExited,
ExitCode: 0,
},
{
Name: "failed",
State: ContainerStateExited,
ExitCode: 1,
},
{
Name: "alive",
State: ContainerStateExited,
ExitCode: 2,
},
{
Name: "unknown",
State: ContainerStateUnknown,
},
{
Name: "failed",
State: ContainerStateExited,
ExitCode: 3,
},
},
}
policies := []v1.RestartPolicy{
v1.RestartPolicyNever,
v1.RestartPolicyOnFailure,
v1.RestartPolicyAlways,
}
expected := map[string][]bool{
"no-history": {true, true, true},
"alive": {false, false, false},
"succeed": {false, false, true},
"failed": {false, true, true},
"unknown": {true, true, true},
}
for _, c := range pod.Spec.Containers {
for i, policy := range policies {
pod.Spec.RestartPolicy = policy
e := expected[c.Name][i]
r := ShouldContainerBeRestarted(&c, pod, podStatus)
if r != e {
t.Errorf("Restart for container %q with restart policy %q expected %t, got %t",
c.Name, policy, e, r)
}
}
}
}
func TestHasPrivilegedContainer(t *testing.T) {
newBoolPtr := func(b bool) *bool {
return &b
}
tests := map[string]struct {
securityContext *v1.SecurityContext
expected bool
}{
"nil security context": {
securityContext: nil,
expected: false,
},
"nil privileged": {
securityContext: &v1.SecurityContext{},
expected: false,
},
"false privileged": {
securityContext: &v1.SecurityContext{Privileged: newBoolPtr(false)},
expected: false,
},
"true privileged": {
securityContext: &v1.SecurityContext{Privileged: newBoolPtr(true)},
expected: true,
},
}
for k, v := range tests {
pod := &v1.Pod{
Spec: v1.PodSpec{
Containers: []v1.Container{
{SecurityContext: v.securityContext},
},
},
}
actual := HasPrivilegedContainer(pod)
if actual != v.expected {
t.Errorf("%s expected %t but got %t", k, v.expected, actual)
}
}
}

View file

@ -19,6 +19,7 @@ package container
import (
"fmt"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
)
@ -37,7 +38,7 @@ func GenerateContainerRef(pod *v1.Pod, container *v1.Container) (*v1.ObjectRefer
// start (like the pod infra container). This is not a good way, ugh.
fieldPath = ImplicitContainerPrefix + container.Name
}
ref, err := v1.GetPartialReference(pod, fieldPath)
ref, err := v1.GetPartialReference(api.Scheme, pod, fieldPath)
if err != nil {
return nil, err
}

View file

@ -1,212 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container
import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
)
func TestFieldPath(t *testing.T) {
pod := &v1.Pod{Spec: v1.PodSpec{Containers: []v1.Container{
{Name: "foo"},
{Name: "bar"},
{Name: ""},
{Name: "baz"},
}}}
table := map[string]struct {
pod *v1.Pod
container *v1.Container
path string
success bool
}{
"basic": {pod, &v1.Container{Name: "foo"}, "spec.containers{foo}", true},
"basic2": {pod, &v1.Container{Name: "baz"}, "spec.containers{baz}", true},
"emptyName": {pod, &v1.Container{Name: ""}, "spec.containers[2]", true},
"basicSamePointer": {pod, &pod.Spec.Containers[0], "spec.containers{foo}", true},
"missing": {pod, &v1.Container{Name: "qux"}, "", false},
}
for name, item := range table {
res, err := fieldPath(item.pod, item.container)
if item.success == false {
if err == nil {
t.Errorf("%v: unexpected non-error", name)
}
continue
}
if err != nil {
t.Errorf("%v: unexpected error: %v", name, err)
continue
}
if e, a := item.path, res; e != a {
t.Errorf("%v: wanted %v, got %v", name, e, a)
}
}
}
func TestGenerateContainerRef(t *testing.T) {
var (
okPod = v1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "ok",
Namespace: "test-ns",
UID: "bar",
ResourceVersion: "42",
SelfLink: "/api/" + api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String() + "/pods/foo",
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "by-name",
},
{},
},
},
}
noSelfLinkPod = okPod
defaultedSelfLinkPod = okPod
)
noSelfLinkPod.Kind = ""
noSelfLinkPod.APIVersion = ""
noSelfLinkPod.ObjectMeta.SelfLink = ""
defaultedSelfLinkPod.ObjectMeta.SelfLink = "/api/" + api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String() + "/pods/ok"
cases := []struct {
name string
pod *v1.Pod
container *v1.Container
expected *v1.ObjectReference
success bool
}{
{
name: "by-name",
pod: &okPod,
container: &v1.Container{
Name: "by-name",
},
expected: &v1.ObjectReference{
Kind: "Pod",
APIVersion: api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(),
Name: "ok",
Namespace: "test-ns",
UID: "bar",
ResourceVersion: "42",
FieldPath: ".spec.containers{by-name}",
},
success: true,
},
{
name: "no-name",
pod: &okPod,
container: &v1.Container{},
expected: &v1.ObjectReference{
Kind: "Pod",
APIVersion: api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(),
Name: "ok",
Namespace: "test-ns",
UID: "bar",
ResourceVersion: "42",
FieldPath: ".spec.containers[1]",
},
success: true,
},
{
name: "no-selflink",
pod: &noSelfLinkPod,
container: &v1.Container{},
expected: nil,
success: false,
},
{
name: "defaulted-selflink",
pod: &defaultedSelfLinkPod,
container: &v1.Container{
Name: "by-name",
},
expected: &v1.ObjectReference{
Kind: "Pod",
APIVersion: api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(),
Name: "ok",
Namespace: "test-ns",
UID: "bar",
ResourceVersion: "42",
FieldPath: ".spec.containers{by-name}",
},
success: true,
},
{
name: "implicitly-required",
pod: &okPod,
container: &v1.Container{
Name: "net",
},
expected: &v1.ObjectReference{
Kind: "Pod",
APIVersion: api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(),
Name: "ok",
Namespace: "test-ns",
UID: "bar",
ResourceVersion: "42",
FieldPath: "implicitly required container net",
},
success: true,
},
}
for _, tc := range cases {
actual, err := GenerateContainerRef(tc.pod, tc.container)
if err != nil {
if tc.success {
t.Errorf("%v: unexpected error: %v", tc.name, err)
}
continue
}
if !tc.success {
t.Errorf("%v: unexpected success", tc.name)
continue
}
if e, a := tc.expected.Kind, actual.Kind; e != a {
t.Errorf("%v: kind: expected %v, got %v", tc.name, e, a)
}
if e, a := tc.expected.APIVersion, actual.APIVersion; e != a {
t.Errorf("%v: apiVersion: expected %v, got %v", tc.name, e, a)
}
if e, a := tc.expected.Name, actual.Name; e != a {
t.Errorf("%v: name: expected %v, got %v", tc.name, e, a)
}
if e, a := tc.expected.Namespace, actual.Namespace; e != a {
t.Errorf("%v: namespace: expected %v, got %v", tc.name, e, a)
}
if e, a := tc.expected.UID, actual.UID; e != a {
t.Errorf("%v: uid: expected %v, got %v", tc.name, e, a)
}
if e, a := tc.expected.ResourceVersion, actual.ResourceVersion; e != a {
t.Errorf("%v: kind: expected %v, got %v", tc.name, e, a)
}
}
}

View file

@ -130,7 +130,7 @@ type DirectStreamingRuntime interface {
// tty.
ExecInContainer(containerID ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size, timeout time.Duration) error
// Forward the specified port from the specified pod to the stream.
PortForward(pod *Pod, port uint16, stream io.ReadWriteCloser) error
PortForward(pod *Pod, port int32, stream io.ReadWriteCloser) error
// ContainerAttach encapsulates the attaching to containers for testability
ContainerAttacher
}
@ -141,7 +141,7 @@ type DirectStreamingRuntime interface {
type IndirectStreamingRuntime interface {
GetExec(id ContainerID, cmd []string, stdin, stdout, stderr, tty bool) (*url.URL, error)
GetAttach(id ContainerID, stdin, stdout, stderr, tty bool) (*url.URL, error)
GetPortForward(podName, podNamespace string, podUID types.UID) (*url.URL, error)
GetPortForward(podName, podNamespace string, podUID types.UID, ports []int32) (*url.URL, error)
}
type ImageService interface {
@ -191,7 +191,7 @@ type Pod struct {
type PodPair struct {
// APIPod is the v1.Pod
APIPod *v1.Pod
// RunningPod is the pod defined defined in pkg/kubelet/container/runtime#Pod
// RunningPod is the pod defined in pkg/kubelet/container/runtime#Pod
RunningPod *Pod
}

View file

@ -1,74 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container_test
import (
"reflect"
"testing"
"time"
. "k8s.io/kubernetes/pkg/kubelet/container"
ctest "k8s.io/kubernetes/pkg/kubelet/container/testing"
)
func comparePods(t *testing.T, expected []*ctest.FakePod, actual []*Pod) {
if len(expected) != len(actual) {
t.Errorf("expected %d pods, got %d instead", len(expected), len(actual))
}
for i := range expected {
if !reflect.DeepEqual(expected[i].Pod, actual[i]) {
t.Errorf("expected %#v, got %#v", expected[i].Pod, actual[i])
}
}
}
func TestGetPods(t *testing.T) {
runtime := &ctest.FakeRuntime{}
expected := []*ctest.FakePod{{Pod: &Pod{ID: "1111"}}, {Pod: &Pod{ID: "2222"}}, {Pod: &Pod{ID: "3333"}}}
runtime.PodList = expected
cache := NewTestRuntimeCache(runtime)
actual, err := cache.GetPods()
if err != nil {
t.Errorf("unexpected error %v", err)
}
comparePods(t, expected, actual)
}
func TestForceUpdateIfOlder(t *testing.T) {
runtime := &ctest.FakeRuntime{}
cache := NewTestRuntimeCache(runtime)
// Cache old pods.
oldpods := []*ctest.FakePod{{Pod: &Pod{ID: "1111"}}}
runtime.PodList = oldpods
cache.UpdateCacheWithLock()
// Update the runtime to new pods.
newpods := []*ctest.FakePod{{Pod: &Pod{ID: "1111"}}, {Pod: &Pod{ID: "2222"}}, {Pod: &Pod{ID: "3333"}}}
runtime.PodList = newpods
// An older timestamp should not force an update.
cache.ForceUpdateIfOlder(time.Now().Add(-20 * time.Minute))
actual := cache.GetCachedPods()
comparePods(t, oldpods, actual)
// A newer timestamp should force an update.
cache.ForceUpdateIfOlder(time.Now().Add(20 * time.Second))
actual = cache.GetCachedPods()
comparePods(t, newpods, actual)
}

View file

@ -1,68 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container
import (
"errors"
"testing"
)
func TestPodSyncResult(t *testing.T) {
okResults := []*SyncResult{
NewSyncResult(StartContainer, "container_0"),
NewSyncResult(SetupNetwork, "pod"),
}
errResults := []*SyncResult{
NewSyncResult(KillContainer, "container_1"),
NewSyncResult(TeardownNetwork, "pod"),
}
errResults[0].Fail(errors.New("error_0"), "message_0")
errResults[1].Fail(errors.New("error_1"), "message_1")
// If the PodSyncResult doesn't contain error result, it should not be error
result := PodSyncResult{}
result.AddSyncResult(okResults...)
if result.Error() != nil {
t.Errorf("PodSyncResult should not be error: %v", result)
}
// If the PodSyncResult contains error result, it should be error
result = PodSyncResult{}
result.AddSyncResult(okResults...)
result.AddSyncResult(errResults...)
if result.Error() == nil {
t.Errorf("PodSyncResult should be error: %q", result)
}
// If the PodSyncResult is failed, it should be error
result = PodSyncResult{}
result.AddSyncResult(okResults...)
result.Fail(errors.New("error"))
if result.Error() == nil {
t.Errorf("PodSyncResult should be error: %q", result)
}
// If the PodSyncResult is added an error PodSyncResult, it should be error
errResult := PodSyncResult{}
errResult.AddSyncResult(errResults...)
result = PodSyncResult{}
result.AddSyncResult(okResults...)
result.AddPodSyncResult(errResult)
if result.Error() == nil {
t.Errorf("PodSyncResult should be error: %q", result)
}
}

View file

@ -1,43 +0,0 @@
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"fake_cache.go",
"fake_runtime.go",
"mockfileinfo.go",
"os.go",
"runtime_mock.go",
],
tags = ["automanaged"],
deps = [
"//pkg/api/v1:go_default_library",
"//pkg/kubelet/container:go_default_library",
"//pkg/util/term:go_default_library",
"//pkg/volume:go_default_library",
"//vendor:github.com/golang/mock/gomock",
"//vendor:github.com/stretchr/testify/mock",
"//vendor:k8s.io/apimachinery/pkg/types",
"//vendor:k8s.io/client-go/util/flowcontrol",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -1,49 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"time"
"k8s.io/apimachinery/pkg/types"
"k8s.io/kubernetes/pkg/kubelet/container"
)
type fakeCache struct {
runtime container.Runtime
}
func NewFakeCache(runtime container.Runtime) container.Cache {
return &fakeCache{runtime: runtime}
}
func (c *fakeCache) Get(id types.UID) (*container.PodStatus, error) {
return c.runtime.GetPodStatus(id, "", "")
}
func (c *fakeCache) GetNewerThan(id types.UID, minTime time.Time) (*container.PodStatus, error) {
return c.Get(id)
}
func (c *fakeCache) Set(id types.UID, status *container.PodStatus, err error, timestamp time.Time) {
}
func (c *fakeCache) Delete(id types.UID) {
}
func (c *fakeCache) UpdateTime(_ time.Time) {
}

View file

@ -1,500 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"fmt"
"io"
"net/url"
"reflect"
"sync"
"time"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/flowcontrol"
"k8s.io/kubernetes/pkg/api/v1"
. "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/util/term"
"k8s.io/kubernetes/pkg/volume"
)
type FakePod struct {
Pod *Pod
NetnsPath string
}
// FakeRuntime is a fake container runtime for testing.
type FakeRuntime struct {
sync.Mutex
CalledFunctions []string
PodList []*FakePod
AllPodList []*FakePod
ImageList []Image
APIPodStatus v1.PodStatus
PodStatus PodStatus
StartedPods []string
KilledPods []string
StartedContainers []string
KilledContainers []string
RuntimeStatus *RuntimeStatus
VersionInfo string
APIVersionInfo string
RuntimeType string
Err error
InspectErr error
StatusErr error
}
type FakeDirectStreamingRuntime struct {
*FakeRuntime
// Arguments to streaming method calls.
Args struct {
// Attach / Exec args
ContainerID ContainerID
Cmd []string
Stdin io.Reader
Stdout io.WriteCloser
Stderr io.WriteCloser
TTY bool
// Port-forward args
Pod *Pod
Port uint16
Stream io.ReadWriteCloser
}
}
var _ DirectStreamingRuntime = &FakeDirectStreamingRuntime{}
const FakeHost = "localhost:12345"
type FakeIndirectStreamingRuntime struct {
*FakeRuntime
}
var _ IndirectStreamingRuntime = &FakeIndirectStreamingRuntime{}
// FakeRuntime should implement Runtime.
var _ Runtime = &FakeRuntime{}
type FakeVersion struct {
Version string
}
func (fv *FakeVersion) String() string {
return fv.Version
}
func (fv *FakeVersion) Compare(other string) (int, error) {
result := 0
if fv.Version > other {
result = 1
} else if fv.Version < other {
result = -1
}
return result, nil
}
type podsGetter interface {
GetPods(bool) ([]*Pod, error)
}
type FakeRuntimeCache struct {
getter podsGetter
}
func NewFakeRuntimeCache(getter podsGetter) RuntimeCache {
return &FakeRuntimeCache{getter}
}
func (f *FakeRuntimeCache) GetPods() ([]*Pod, error) {
return f.getter.GetPods(false)
}
func (f *FakeRuntimeCache) ForceUpdateIfOlder(time.Time) error {
return nil
}
// ClearCalls resets the FakeRuntime to the initial state.
func (f *FakeRuntime) ClearCalls() {
f.Lock()
defer f.Unlock()
f.CalledFunctions = []string{}
f.PodList = []*FakePod{}
f.AllPodList = []*FakePod{}
f.APIPodStatus = v1.PodStatus{}
f.StartedPods = []string{}
f.KilledPods = []string{}
f.StartedContainers = []string{}
f.KilledContainers = []string{}
f.RuntimeStatus = nil
f.VersionInfo = ""
f.RuntimeType = ""
f.Err = nil
f.InspectErr = nil
f.StatusErr = nil
}
// UpdatePodCIDR fulfills the cri interface.
func (f *FakeRuntime) UpdatePodCIDR(c string) error {
return nil
}
func (f *FakeRuntime) assertList(expect []string, test []string) error {
if !reflect.DeepEqual(expect, test) {
return fmt.Errorf("expected %#v, got %#v", expect, test)
}
return nil
}
// AssertCalls test if the invoked functions are as expected.
func (f *FakeRuntime) AssertCalls(calls []string) error {
f.Lock()
defer f.Unlock()
return f.assertList(calls, f.CalledFunctions)
}
func (f *FakeRuntime) AssertStartedPods(pods []string) error {
f.Lock()
defer f.Unlock()
return f.assertList(pods, f.StartedPods)
}
func (f *FakeRuntime) AssertKilledPods(pods []string) error {
f.Lock()
defer f.Unlock()
return f.assertList(pods, f.KilledPods)
}
func (f *FakeRuntime) AssertStartedContainers(containers []string) error {
f.Lock()
defer f.Unlock()
return f.assertList(containers, f.StartedContainers)
}
func (f *FakeRuntime) AssertKilledContainers(containers []string) error {
f.Lock()
defer f.Unlock()
return f.assertList(containers, f.KilledContainers)
}
func (f *FakeRuntime) Type() string {
return f.RuntimeType
}
func (f *FakeRuntime) Version() (Version, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "Version")
return &FakeVersion{Version: f.VersionInfo}, f.Err
}
func (f *FakeRuntime) APIVersion() (Version, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "APIVersion")
return &FakeVersion{Version: f.APIVersionInfo}, f.Err
}
func (f *FakeRuntime) Status() (*RuntimeStatus, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "Status")
return f.RuntimeStatus, f.StatusErr
}
func (f *FakeRuntime) GetPods(all bool) ([]*Pod, error) {
f.Lock()
defer f.Unlock()
var pods []*Pod
f.CalledFunctions = append(f.CalledFunctions, "GetPods")
if all {
for _, fakePod := range f.AllPodList {
pods = append(pods, fakePod.Pod)
}
} else {
for _, fakePod := range f.PodList {
pods = append(pods, fakePod.Pod)
}
}
return pods, f.Err
}
func (f *FakeRuntime) SyncPod(pod *v1.Pod, _ v1.PodStatus, _ *PodStatus, _ []v1.Secret, backOff *flowcontrol.Backoff) (result PodSyncResult) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "SyncPod")
f.StartedPods = append(f.StartedPods, string(pod.UID))
for _, c := range pod.Spec.Containers {
f.StartedContainers = append(f.StartedContainers, c.Name)
}
// TODO(random-liu): Add SyncResult for starting and killing containers
if f.Err != nil {
result.Fail(f.Err)
}
return
}
func (f *FakeRuntime) KillPod(pod *v1.Pod, runningPod Pod, gracePeriodOverride *int64) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "KillPod")
f.KilledPods = append(f.KilledPods, string(runningPod.ID))
for _, c := range runningPod.Containers {
f.KilledContainers = append(f.KilledContainers, c.Name)
}
return f.Err
}
func (f *FakeRuntime) RunContainerInPod(container v1.Container, pod *v1.Pod, volumeMap map[string]volume.VolumePlugin) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "RunContainerInPod")
f.StartedContainers = append(f.StartedContainers, container.Name)
pod.Spec.Containers = append(pod.Spec.Containers, container)
for _, c := range pod.Spec.Containers {
if c.Name == container.Name { // Container already in the pod.
return f.Err
}
}
pod.Spec.Containers = append(pod.Spec.Containers, container)
return f.Err
}
func (f *FakeRuntime) KillContainerInPod(container v1.Container, pod *v1.Pod) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "KillContainerInPod")
f.KilledContainers = append(f.KilledContainers, container.Name)
var containers []v1.Container
for _, c := range pod.Spec.Containers {
if c.Name == container.Name {
continue
}
containers = append(containers, c)
}
return f.Err
}
func (f *FakeRuntime) GetPodStatus(uid types.UID, name, namespace string) (*PodStatus, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetPodStatus")
status := f.PodStatus
return &status, f.Err
}
func (f *FakeDirectStreamingRuntime) ExecInContainer(containerID ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size, timeout time.Duration) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "ExecInContainer")
f.Args.ContainerID = containerID
f.Args.Cmd = cmd
f.Args.Stdin = stdin
f.Args.Stdout = stdout
f.Args.Stderr = stderr
f.Args.TTY = tty
return f.Err
}
func (f *FakeDirectStreamingRuntime) AttachContainer(containerID ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "AttachContainer")
f.Args.ContainerID = containerID
f.Args.Stdin = stdin
f.Args.Stdout = stdout
f.Args.Stderr = stderr
f.Args.TTY = tty
return f.Err
}
func (f *FakeRuntime) GetContainerLogs(pod *v1.Pod, containerID ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetContainerLogs")
return f.Err
}
func (f *FakeRuntime) PullImage(image ImageSpec, pullSecrets []v1.Secret) (string, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "PullImage")
return image.Image, f.Err
}
func (f *FakeRuntime) GetImageRef(image ImageSpec) (string, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetImageRef")
for _, i := range f.ImageList {
if i.ID == image.Image {
return i.ID, nil
}
}
return "", f.InspectErr
}
func (f *FakeRuntime) ListImages() ([]Image, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "ListImages")
return f.ImageList, f.Err
}
func (f *FakeRuntime) RemoveImage(image ImageSpec) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "RemoveImage")
index := 0
for i := range f.ImageList {
if f.ImageList[i].ID == image.Image {
index = i
break
}
}
f.ImageList = append(f.ImageList[:index], f.ImageList[index+1:]...)
return f.Err
}
func (f *FakeDirectStreamingRuntime) PortForward(pod *Pod, port uint16, stream io.ReadWriteCloser) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "PortForward")
f.Args.Pod = pod
f.Args.Port = port
f.Args.Stream = stream
return f.Err
}
func (f *FakeRuntime) GetNetNS(containerID ContainerID) (string, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetNetNS")
for _, fp := range f.AllPodList {
for _, c := range fp.Pod.Containers {
if c.ID == containerID {
return fp.NetnsPath, nil
}
}
}
return "", f.Err
}
func (f *FakeRuntime) GetPodContainerID(pod *Pod) (ContainerID, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetPodContainerID")
return ContainerID{}, f.Err
}
func (f *FakeRuntime) GarbageCollect(gcPolicy ContainerGCPolicy, ready bool) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GarbageCollect")
return f.Err
}
func (f *FakeRuntime) DeleteContainer(containerID ContainerID) error {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "DeleteContainer")
return f.Err
}
func (f *FakeRuntime) ImageStats() (*ImageStats, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "ImageStats")
return nil, f.Err
}
func (f *FakeIndirectStreamingRuntime) GetExec(id ContainerID, cmd []string, stdin, stdout, stderr, tty bool) (*url.URL, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetExec")
return &url.URL{Host: FakeHost}, f.Err
}
func (f *FakeIndirectStreamingRuntime) GetAttach(id ContainerID, stdin, stdout, stderr, tty bool) (*url.URL, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetAttach")
return &url.URL{Host: FakeHost}, f.Err
}
func (f *FakeIndirectStreamingRuntime) GetPortForward(podName, podNamespace string, podUID types.UID) (*url.URL, error) {
f.Lock()
defer f.Unlock()
f.CalledFunctions = append(f.CalledFunctions, "GetPortForward")
return &url.URL{Host: FakeHost}, f.Err
}
type FakeContainerCommandRunner struct {
// what to return
Stdout string
Err error
// actual values when invoked
ContainerID ContainerID
Cmd []string
}
var _ ContainerCommandRunner = &FakeContainerCommandRunner{}
func (f *FakeContainerCommandRunner) RunInContainer(containerID ContainerID, cmd []string, timeout time.Duration) ([]byte, error) {
// record invoked values
f.ContainerID = containerID
f.Cmd = cmd
return []byte(f.Stdout), f.Err
}

View file

@ -1,109 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Generated via: mockgen os FileInfo
// Edited to include required boilerplate
// Source: os (interfaces: FileInfo)
package testing
import (
os "os"
time "time"
gomock "github.com/golang/mock/gomock"
)
// Mock of FileInfo interface
type MockFileInfo struct {
ctrl *gomock.Controller
recorder *_MockFileInfoRecorder
}
// Recorder for MockFileInfo (not exported)
type _MockFileInfoRecorder struct {
mock *MockFileInfo
}
func NewMockFileInfo(ctrl *gomock.Controller) *MockFileInfo {
mock := &MockFileInfo{ctrl: ctrl}
mock.recorder = &_MockFileInfoRecorder{mock}
return mock
}
func (_m *MockFileInfo) EXPECT() *_MockFileInfoRecorder {
return _m.recorder
}
func (_m *MockFileInfo) IsDir() bool {
ret := _m.ctrl.Call(_m, "IsDir")
ret0, _ := ret[0].(bool)
return ret0
}
func (_mr *_MockFileInfoRecorder) IsDir() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "IsDir")
}
func (_m *MockFileInfo) ModTime() time.Time {
ret := _m.ctrl.Call(_m, "ModTime")
ret0, _ := ret[0].(time.Time)
return ret0
}
func (_mr *_MockFileInfoRecorder) ModTime() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "ModTime")
}
func (_m *MockFileInfo) Mode() os.FileMode {
ret := _m.ctrl.Call(_m, "Mode")
ret0, _ := ret[0].(os.FileMode)
return ret0
}
func (_mr *_MockFileInfoRecorder) Mode() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "Mode")
}
func (_m *MockFileInfo) Name() string {
ret := _m.ctrl.Call(_m, "Name")
ret0, _ := ret[0].(string)
return ret0
}
func (_mr *_MockFileInfoRecorder) Name() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "Name")
}
func (_m *MockFileInfo) Size() int64 {
ret := _m.ctrl.Call(_m, "Size")
ret0, _ := ret[0].(int64)
return ret0
}
func (_mr *_MockFileInfoRecorder) Size() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "Size")
}
func (_m *MockFileInfo) Sys() interface{} {
ret := _m.ctrl.Call(_m, "Sys")
ret0, _ := ret[0].(interface{})
return ret0
}
func (_mr *_MockFileInfoRecorder) Sys() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "Sys")
}

View file

@ -1,117 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"errors"
"os"
"time"
)
// FakeOS mocks out certain OS calls to avoid perturbing the filesystem
// If a member of the form `*Fn` is set, that function will be called in place
// of the real call.
type FakeOS struct {
StatFn func(string) (os.FileInfo, error)
ReadDirFn func(string) ([]os.FileInfo, error)
MkdirAllFn func(string, os.FileMode) error
SymlinkFn func(string, string) error
HostName string
Removes []string
Files map[string][]*os.FileInfo
}
func NewFakeOS() *FakeOS {
return &FakeOS{
Removes: []string{},
Files: make(map[string][]*os.FileInfo),
}
}
// Mkdir is a fake call that just returns nil.
func (f *FakeOS) MkdirAll(path string, perm os.FileMode) error {
if f.MkdirAllFn != nil {
return f.MkdirAllFn(path, perm)
}
return nil
}
// Symlink is a fake call that just returns nil.
func (f *FakeOS) Symlink(oldname string, newname string) error {
if f.SymlinkFn != nil {
return f.SymlinkFn(oldname, newname)
}
return nil
}
// Stat is a fake that returns an error
func (f FakeOS) Stat(path string) (os.FileInfo, error) {
if f.StatFn != nil {
return f.StatFn(path)
}
return nil, errors.New("unimplemented testing mock")
}
// Remove is a fake call that returns nil.
func (f *FakeOS) Remove(path string) error {
f.Removes = append(f.Removes, path)
return nil
}
// RemoveAll is a fake call that just returns nil.
func (f *FakeOS) RemoveAll(path string) error {
f.Removes = append(f.Removes, path)
return nil
}
// Create is a fake call that returns nil.
func (FakeOS) Create(path string) (*os.File, error) {
return nil, nil
}
// Chmod is a fake call that returns nil.
func (FakeOS) Chmod(path string, perm os.FileMode) error {
return nil
}
// Hostname is a fake call that returns nil.
func (f *FakeOS) Hostname() (name string, err error) {
return f.HostName, nil
}
// Chtimes is a fake call that returns nil.
func (FakeOS) Chtimes(path string, atime time.Time, mtime time.Time) error {
return nil
}
// Pipe is a fake call that returns nil.
func (FakeOS) Pipe() (r *os.File, w *os.File, err error) {
return nil, nil, nil
}
// ReadDir is a fake call that returns the files under the directory.
func (f *FakeOS) ReadDir(dirname string) ([]os.FileInfo, error) {
if f.ReadDirFn != nil {
return f.ReadDirFn(dirname)
}
return nil, nil
}
// Glob is a fake call that returns nil.
func (f *FakeOS) Glob(pattern string) ([]string, error) {
return nil, nil
}

View file

@ -1,161 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"io"
"time"
"github.com/stretchr/testify/mock"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/flowcontrol"
"k8s.io/kubernetes/pkg/api/v1"
. "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/util/term"
"k8s.io/kubernetes/pkg/volume"
)
type Mock struct {
mock.Mock
}
var _ Runtime = new(Mock)
func (r *Mock) Start() error {
args := r.Called()
return args.Error(0)
}
func (r *Mock) Type() string {
args := r.Called()
return args.Get(0).(string)
}
func (r *Mock) Version() (Version, error) {
args := r.Called()
return args.Get(0).(Version), args.Error(1)
}
func (r *Mock) APIVersion() (Version, error) {
args := r.Called()
return args.Get(0).(Version), args.Error(1)
}
func (r *Mock) Status() (*RuntimeStatus, error) {
args := r.Called()
return args.Get(0).(*RuntimeStatus), args.Error(0)
}
func (r *Mock) GetPods(all bool) ([]*Pod, error) {
args := r.Called(all)
return args.Get(0).([]*Pod), args.Error(1)
}
func (r *Mock) SyncPod(pod *v1.Pod, apiStatus v1.PodStatus, status *PodStatus, secrets []v1.Secret, backOff *flowcontrol.Backoff) PodSyncResult {
args := r.Called(pod, apiStatus, status, secrets, backOff)
return args.Get(0).(PodSyncResult)
}
func (r *Mock) KillPod(pod *v1.Pod, runningPod Pod, gracePeriodOverride *int64) error {
args := r.Called(pod, runningPod, gracePeriodOverride)
return args.Error(0)
}
func (r *Mock) RunContainerInPod(container v1.Container, pod *v1.Pod, volumeMap map[string]volume.VolumePlugin) error {
args := r.Called(pod, pod, volumeMap)
return args.Error(0)
}
func (r *Mock) KillContainerInPod(container v1.Container, pod *v1.Pod) error {
args := r.Called(pod, pod)
return args.Error(0)
}
func (r *Mock) GetPodStatus(uid types.UID, name, namespace string) (*PodStatus, error) {
args := r.Called(uid, name, namespace)
return args.Get(0).(*PodStatus), args.Error(1)
}
func (r *Mock) ExecInContainer(containerID ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size, timeout time.Duration) error {
args := r.Called(containerID, cmd, stdin, stdout, stderr, tty)
return args.Error(0)
}
func (r *Mock) AttachContainer(containerID ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error {
args := r.Called(containerID, stdin, stdout, stderr, tty)
return args.Error(0)
}
func (r *Mock) GetContainerLogs(pod *v1.Pod, containerID ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error) {
args := r.Called(pod, containerID, logOptions, stdout, stderr)
return args.Error(0)
}
func (r *Mock) PullImage(image ImageSpec, pullSecrets []v1.Secret) (string, error) {
args := r.Called(image, pullSecrets)
return image.Image, args.Error(0)
}
func (r *Mock) GetImageRef(image ImageSpec) (string, error) {
args := r.Called(image)
return args.Get(0).(string), args.Error(1)
}
func (r *Mock) ListImages() ([]Image, error) {
args := r.Called()
return args.Get(0).([]Image), args.Error(1)
}
func (r *Mock) RemoveImage(image ImageSpec) error {
args := r.Called(image)
return args.Error(0)
}
func (r *Mock) PortForward(pod *Pod, port uint16, stream io.ReadWriteCloser) error {
args := r.Called(pod, port, stream)
return args.Error(0)
}
func (r *Mock) GetNetNS(containerID ContainerID) (string, error) {
args := r.Called(containerID)
return "", args.Error(0)
}
func (r *Mock) GetPodContainerID(pod *Pod) (ContainerID, error) {
args := r.Called(pod)
return ContainerID{}, args.Error(0)
}
func (r *Mock) GarbageCollect(gcPolicy ContainerGCPolicy, ready bool) error {
args := r.Called(gcPolicy, ready)
return args.Error(0)
}
func (r *Mock) DeleteContainer(containerID ContainerID) error {
args := r.Called(containerID)
return args.Error(0)
}
func (r *Mock) ImageStats() (*ImageStats, error) {
args := r.Called()
return args.Get(0).(*ImageStats), args.Error(1)
}
// UpdatePodCIDR fulfills the cri interface.
func (r *Mock) UpdatePodCIDR(c string) error {
return nil
}