Skip to content
This repository was archived by the owner on Mar 9, 2022. It is now read-only.

Commit bf551b9

Browse files
committed
Add integration test.
Signed-off-by: Lantao Liu <[email protected]>
1 parent 405f57f commit bf551b9

File tree

3 files changed

+186
-30
lines changed

3 files changed

+186
-30
lines changed

integration/container_log_test.go

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/*
2+
Copyright 2018 The containerd Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package integration
18+
19+
import (
20+
"fmt"
21+
"io/ioutil"
22+
"os"
23+
"path/filepath"
24+
"strings"
25+
"testing"
26+
"time"
27+
28+
"github.com/stretchr/testify/assert"
29+
"github.com/stretchr/testify/require"
30+
runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
31+
)
32+
33+
func TestLongContainerLog(t *testing.T) {
34+
testPodLogDir, err := ioutil.TempDir("/tmp", "long-container-log")
35+
require.NoError(t, err)
36+
defer os.RemoveAll(testPodLogDir)
37+
38+
t.Log("Create a sandbox with log directory")
39+
sbConfig := PodSandboxConfig("sandbox", "long-container-log",
40+
WithPodLogDirectory(testPodLogDir),
41+
)
42+
sb, err := runtimeService.RunPodSandbox(sbConfig)
43+
require.NoError(t, err)
44+
defer func() {
45+
assert.NoError(t, runtimeService.StopPodSandbox(sb))
46+
assert.NoError(t, runtimeService.RemovePodSandbox(sb))
47+
}()
48+
49+
const (
50+
testImage = "busybox"
51+
containerName = "test-container"
52+
)
53+
t.Logf("Pull test image %q", testImage)
54+
img, err := imageService.PullImage(&runtime.ImageSpec{Image: testImage}, nil)
55+
require.NoError(t, err)
56+
defer func() {
57+
assert.NoError(t, imageService.RemoveImage(&runtime.ImageSpec{Image: img}))
58+
}()
59+
60+
t.Log("Create a container with log path")
61+
config, err := CRIConfig()
62+
require.NoError(t, err)
63+
maxSize := config.MaxContainerLogLineSize
64+
shortLineCmd := fmt.Sprintf("i=0; while [ $i -lt %d ]; do printf %s; i=$((i+1)); done", maxSize-1, "a")
65+
maxLenLineCmd := fmt.Sprintf("i=0; while [ $i -lt %d ]; do printf %s; i=$((i+1)); done", maxSize, "b")
66+
longLineCmd := fmt.Sprintf("i=0; while [ $i -lt %d ]; do printf %s; i=$((i+1)); done", maxSize+1, "c")
67+
cnConfig := ContainerConfig(
68+
containerName,
69+
"busybox",
70+
WithCommand("sh", "-c",
71+
fmt.Sprintf("%s; echo; %s; echo; %s", shortLineCmd, maxLenLineCmd, longLineCmd)),
72+
WithLogPath(containerName),
73+
)
74+
cn, err := runtimeService.CreateContainer(sb, cnConfig, sbConfig)
75+
require.NoError(t, err)
76+
77+
t.Log("Start the container")
78+
require.NoError(t, runtimeService.StartContainer(cn))
79+
80+
t.Log("Wait for container to finish running")
81+
require.NoError(t, Eventually(func() (bool, error) {
82+
s, err := runtimeService.ContainerStatus(cn)
83+
if err != nil {
84+
return false, err
85+
}
86+
if s.GetState() == runtime.ContainerState_CONTAINER_EXITED {
87+
return true, nil
88+
}
89+
return false, nil
90+
}, time.Second, 30*time.Second))
91+
92+
t.Log("Check container log")
93+
content, err := ioutil.ReadFile(filepath.Join(testPodLogDir, containerName))
94+
assert.NoError(t, err)
95+
checkContainerLog(t, string(content), []string{
96+
fmt.Sprintf("%s %s %s", runtime.Stdout, runtime.LogTagFull, strings.Repeat("a", maxSize-1)),
97+
fmt.Sprintf("%s %s %s", runtime.Stdout, runtime.LogTagFull, strings.Repeat("b", maxSize)),
98+
fmt.Sprintf("%s %s %s", runtime.Stdout, runtime.LogTagPartial, strings.Repeat("c", maxSize)),
99+
fmt.Sprintf("%s %s %s", runtime.Stdout, runtime.LogTagFull, "c"),
100+
})
101+
}
102+
103+
func checkContainerLog(t *testing.T, log string, messages []string) {
104+
lines := strings.Split(strings.TrimSpace(log), "\n")
105+
require.Len(t, lines, len(messages), "log line number should match")
106+
for i, line := range lines {
107+
parts := strings.SplitN(line, " ", 2)
108+
require.Len(t, parts, 2)
109+
_, err := time.Parse(time.RFC3339Nano, parts[0])
110+
assert.NoError(t, err, "timestamp should be in RFC3339Nano format")
111+
assert.Equal(t, messages[i], parts[1], "log content should match")
112+
}
113+
}

integration/container_update_resources_test.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func checkMemoryLimit(t *testing.T, spec *runtimespec.Spec, memLimit int64) {
3737
}
3838

3939
func TestUpdateContainerResources(t *testing.T) {
40-
t.Logf("Create a sandbox")
40+
t.Log("Create a sandbox")
4141
sbConfig := PodSandboxConfig("sandbox", "update-container-resources")
4242
sb, err := runtimeService.RunPodSandbox(sbConfig)
4343
require.NoError(t, err)
@@ -46,7 +46,7 @@ func TestUpdateContainerResources(t *testing.T) {
4646
assert.NoError(t, runtimeService.RemovePodSandbox(sb))
4747
}()
4848

49-
t.Logf("Create a container with memory limit")
49+
t.Log("Create a container with memory limit")
5050
cnConfig := ContainerConfig(
5151
"container",
5252
pauseImage,
@@ -57,48 +57,48 @@ func TestUpdateContainerResources(t *testing.T) {
5757
cn, err := runtimeService.CreateContainer(sb, cnConfig, sbConfig)
5858
require.NoError(t, err)
5959

60-
t.Logf("Check memory limit in container OCI spec")
60+
t.Log("Check memory limit in container OCI spec")
6161
container, err := containerdClient.LoadContainer(context.Background(), cn)
6262
require.NoError(t, err)
6363
spec, err := container.Spec(context.Background())
6464
require.NoError(t, err)
6565
checkMemoryLimit(t, spec, 2*1024*1024)
6666

67-
t.Logf("Update container memory limit after created")
67+
t.Log("Update container memory limit after created")
6868
err = runtimeService.UpdateContainerResources(cn, &runtime.LinuxContainerResources{
6969
MemoryLimitInBytes: 4 * 1024 * 1024,
7070
})
7171
require.NoError(t, err)
7272

73-
t.Logf("Check memory limit in container OCI spec")
73+
t.Log("Check memory limit in container OCI spec")
7474
spec, err = container.Spec(context.Background())
7575
require.NoError(t, err)
7676
checkMemoryLimit(t, spec, 4*1024*1024)
7777

78-
t.Logf("Start the container")
78+
t.Log("Start the container")
7979
require.NoError(t, runtimeService.StartContainer(cn))
8080
task, err := container.Task(context.Background(), nil)
8181
require.NoError(t, err)
8282

83-
t.Logf("Check memory limit in cgroup")
83+
t.Log("Check memory limit in cgroup")
8484
cgroup, err := cgroups.Load(cgroups.V1, cgroups.PidPath(int(task.Pid())))
8585
require.NoError(t, err)
8686
stat, err := cgroup.Stat(cgroups.IgnoreNotExist)
8787
require.NoError(t, err)
8888
assert.Equal(t, uint64(4*1024*1024), stat.Memory.Usage.Limit)
8989

90-
t.Logf("Update container memory limit after started")
90+
t.Log("Update container memory limit after started")
9191
err = runtimeService.UpdateContainerResources(cn, &runtime.LinuxContainerResources{
9292
MemoryLimitInBytes: 8 * 1024 * 1024,
9393
})
9494
require.NoError(t, err)
9595

96-
t.Logf("Check memory limit in container OCI spec")
96+
t.Log("Check memory limit in container OCI spec")
9797
spec, err = container.Spec(context.Background())
9898
require.NoError(t, err)
9999
checkMemoryLimit(t, spec, 8*1024*1024)
100100

101-
t.Logf("Check memory limit in cgroup")
101+
t.Log("Check memory limit in cgroup")
102102
stat, err = cgroup.Stat(cgroups.IgnoreNotExist)
103103
require.NoError(t, err)
104104
assert.Equal(t, uint64(8*1024*1024), stat.Memory.Usage.Limit)

integration/test_utils.go

Lines changed: 63 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package integration
1818

1919
import (
2020
"context"
21+
"encoding/json"
2122
"flag"
2223
"fmt"
2324
"os/exec"
@@ -28,12 +29,15 @@ import (
2829
"github.com/containerd/containerd"
2930
"github.com/pkg/errors"
3031
"github.com/sirupsen/logrus"
32+
"google.golang.org/grpc"
3133
"k8s.io/kubernetes/pkg/kubelet/apis/cri"
3234
runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
3335
"k8s.io/kubernetes/pkg/kubelet/remote"
36+
kubeletutil "k8s.io/kubernetes/pkg/kubelet/util"
3437

3538
api "github.com/containerd/cri/pkg/api/v1"
3639
"github.com/containerd/cri/pkg/client"
40+
criconfig "github.com/containerd/cri/pkg/config"
3741
"github.com/containerd/cri/pkg/constants"
3842
"github.com/containerd/cri/pkg/util"
3943
)
@@ -100,6 +104,7 @@ func ConnectDaemons() error {
100104
// Opts sets specific information in pod sandbox config.
101105
type PodSandboxOpts func(*runtime.PodSandboxConfig)
102106

107+
// Set host network.
103108
func WithHostNetwork(p *runtime.PodSandboxConfig) {
104109
if p.Linux == nil {
105110
p.Linux = &runtime.LinuxPodSandboxConfig{}
@@ -114,6 +119,13 @@ func WithHostNetwork(p *runtime.PodSandboxConfig) {
114119
}
115120
}
116121

122+
// Add pod log directory.
123+
func WithPodLogDirectory(dir string) PodSandboxOpts {
124+
return func(p *runtime.PodSandboxConfig) {
125+
p.LogDirectory = dir
126+
}
127+
}
128+
117129
// PodSandboxConfig generates a pod sandbox config for test.
118130
func PodSandboxConfig(name, ns string, opts ...PodSandboxOpts) *runtime.PodSandboxConfig {
119131
config := &runtime.PodSandboxConfig{
@@ -137,52 +149,59 @@ func PodSandboxConfig(name, ns string, opts ...PodSandboxOpts) *runtime.PodSandb
137149
type ContainerOpts func(*runtime.ContainerConfig)
138150

139151
func WithTestLabels() ContainerOpts {
140-
return func(cf *runtime.ContainerConfig) {
141-
cf.Labels = map[string]string{"key": "value"}
152+
return func(c *runtime.ContainerConfig) {
153+
c.Labels = map[string]string{"key": "value"}
142154
}
143155
}
144156

145157
func WithTestAnnotations() ContainerOpts {
146-
return func(cf *runtime.ContainerConfig) {
147-
cf.Annotations = map[string]string{"a.b.c": "test"}
158+
return func(c *runtime.ContainerConfig) {
159+
c.Annotations = map[string]string{"a.b.c": "test"}
148160
}
149161
}
150162

151163
// Add container resource limits.
152164
func WithResources(r *runtime.LinuxContainerResources) ContainerOpts {
153-
return func(cf *runtime.ContainerConfig) {
154-
if cf.Linux == nil {
155-
cf.Linux = &runtime.LinuxContainerConfig{}
165+
return func(c *runtime.ContainerConfig) {
166+
if c.Linux == nil {
167+
c.Linux = &runtime.LinuxContainerConfig{}
156168
}
157-
cf.Linux.Resources = r
169+
c.Linux.Resources = r
158170
}
159171
}
160172

161173
// Add container command.
162-
func WithCommand(c string, args ...string) ContainerOpts {
163-
return func(cf *runtime.ContainerConfig) {
164-
cf.Command = []string{c}
165-
cf.Args = args
174+
func WithCommand(cmd string, args ...string) ContainerOpts {
175+
return func(c *runtime.ContainerConfig) {
176+
c.Command = []string{cmd}
177+
c.Args = args
166178
}
167179
}
168180

169181
// Add pid namespace mode.
170182
func WithPidNamespace(mode runtime.NamespaceMode) ContainerOpts {
171-
return func(cf *runtime.ContainerConfig) {
172-
if cf.Linux == nil {
173-
cf.Linux = &runtime.LinuxContainerConfig{}
183+
return func(c *runtime.ContainerConfig) {
184+
if c.Linux == nil {
185+
c.Linux = &runtime.LinuxContainerConfig{}
174186
}
175-
if cf.Linux.SecurityContext == nil {
176-
cf.Linux.SecurityContext = &runtime.LinuxContainerSecurityContext{}
187+
if c.Linux.SecurityContext == nil {
188+
c.Linux.SecurityContext = &runtime.LinuxContainerSecurityContext{}
177189
}
178-
if cf.Linux.SecurityContext.NamespaceOptions == nil {
179-
cf.Linux.SecurityContext.NamespaceOptions = &runtime.NamespaceOption{}
190+
if c.Linux.SecurityContext.NamespaceOptions == nil {
191+
c.Linux.SecurityContext.NamespaceOptions = &runtime.NamespaceOption{}
180192
}
181-
cf.Linux.SecurityContext.NamespaceOptions.Pid = mode
193+
c.Linux.SecurityContext.NamespaceOptions.Pid = mode
182194
}
183195

184196
}
185197

198+
// Add container log path.
199+
func WithLogPath(path string) ContainerOpts {
200+
return func(c *runtime.ContainerConfig) {
201+
c.LogPath = path
202+
}
203+
}
204+
186205
// ContainerConfig creates a container config given a name and image name
187206
// and additional container config options
188207
func ContainerConfig(name, image string, opts ...ContainerOpts) *runtime.ContainerConfig {
@@ -247,3 +266,27 @@ func PidOf(name string) (int, error) {
247266
}
248267
return strconv.Atoi(output)
249268
}
269+
270+
// CRIConfig gets current cri config from containerd.
271+
func CRIConfig() (*criconfig.Config, error) {
272+
addr, dialer, err := kubeletutil.GetAddressAndDialer(*criEndpoint)
273+
if err != nil {
274+
return nil, errors.Wrap(err, "failed to get dialer")
275+
}
276+
ctx, cancel := context.WithTimeout(context.Background(), timeout)
277+
defer cancel()
278+
conn, err := grpc.DialContext(ctx, addr, grpc.WithInsecure(), grpc.WithDialer(dialer))
279+
if err != nil {
280+
return nil, errors.Wrap(err, "failed to connect cri endpoint")
281+
}
282+
client := runtime.NewRuntimeServiceClient(conn)
283+
resp, err := client.Status(ctx, &runtime.StatusRequest{Verbose: true})
284+
if err != nil {
285+
return nil, errors.Wrap(err, "failed to get status")
286+
}
287+
config := &criconfig.Config{}
288+
if err := json.Unmarshal([]byte(resp.Info["config"]), config); err != nil {
289+
return nil, errors.Wrap(err, "failed to unmarshal config")
290+
}
291+
return config, nil
292+
}

0 commit comments

Comments
 (0)