podman/libpod/common_test.go
Paul Holzinger 0136a66a83
libpod: deduplicate ports in db
The OCICNI port format has one big problem: It does not support ranges.
So if a users forwards a range of 1k ports with podman run -p 1001-2000
we have to store each of the thousand ports individually as array element.
This bloats the db and makes the JSON encoding and decoding much slower.
In many places we already use a better port struct type which supports
ranges, e.g. `pkg/specgen` or the new network interface.

Because of this we have to do many runtime conversions between the two
port formats. If everything uses the new format we can skip the runtime
conversions.

This commit adds logic to replace all occurrences of the old format
with the new one. The database will automatically migrate the ports
to new format when the container config is read for the first time
after the update.

The `ParsePortMapping` function is `pkg/specgen/generate` has been
reworked to better work with the new format. The new logic is able
to deduplicate the given ports. This is necessary the ensure we
store them efficiently in the DB. The new code should also be more
performant than the old one.

To prove that the code is fast enough I added go benchmarks. Parsing
1 million ports took less than 0.5 seconds on my laptop.

Benchmark normalize PortMappings in specgen:
Please note that the 1 million ports are actually 20x 50k ranges
because we cannot have bigger ranges than 65535 ports.
```
$ go test -bench=. -benchmem  ./pkg/specgen/generate/
goos: linux
goarch: amd64
pkg: github.com/containers/podman/v3/pkg/specgen/generate
cpu: Intel(R) Core(TM) i7-10850H CPU @ 2.70GHz
BenchmarkParsePortMappingNoPorts-12             480821532                2.230 ns/op           0 B/op          0 allocs/op
BenchmarkParsePortMapping1-12                      38972             30183 ns/op          131584 B/op          9 allocs/op
BenchmarkParsePortMapping100-12                    18752             60688 ns/op          141088 B/op        315 allocs/op
BenchmarkParsePortMapping1k-12                      3104            331719 ns/op          223840 B/op       3018 allocs/op
BenchmarkParsePortMapping10k-12                      376           3122930 ns/op         1223650 B/op      30027 allocs/op
BenchmarkParsePortMapping1m-12                         3         390869926 ns/op        124593840 B/op   4000624 allocs/op
BenchmarkParsePortMappingReverse100-12             18940             63414 ns/op          141088 B/op        315 allocs/op
BenchmarkParsePortMappingReverse1k-12               3015            362500 ns/op          223841 B/op       3018 allocs/op
BenchmarkParsePortMappingReverse10k-12               343           3318135 ns/op         1223650 B/op      30027 allocs/op
BenchmarkParsePortMappingReverse1m-12                  3         403392469 ns/op        124593840 B/op   4000624 allocs/op
BenchmarkParsePortMappingRange1-12                 37635             28756 ns/op          131584 B/op          9 allocs/op
BenchmarkParsePortMappingRange100-12               39604             28935 ns/op          131584 B/op          9 allocs/op
BenchmarkParsePortMappingRange1k-12                38384             29921 ns/op          131584 B/op          9 allocs/op
BenchmarkParsePortMappingRange10k-12               29479             40381 ns/op          131584 B/op          9 allocs/op
BenchmarkParsePortMappingRange1m-12                  927           1279369 ns/op          143022 B/op        164 allocs/op
PASS
ok      github.com/containers/podman/v3/pkg/specgen/generate    25.492s
```

Benchmark convert old port format to new one:
```
go test -bench=. -benchmem  ./libpod/
goos: linux
goarch: amd64
pkg: github.com/containers/podman/v3/libpod
cpu: Intel(R) Core(TM) i7-10850H CPU @ 2.70GHz
Benchmark_ocicniPortsToNetTypesPortsNoPorts-12          663526126                1.663 ns/op           0 B/op          0 allocs/op
Benchmark_ocicniPortsToNetTypesPorts1-12                 7858082               141.9 ns/op            72 B/op          2 allocs/op
Benchmark_ocicniPortsToNetTypesPorts10-12                2065347               571.0 ns/op           536 B/op          4 allocs/op
Benchmark_ocicniPortsToNetTypesPorts100-12                138478              8641 ns/op            4216 B/op          4 allocs/op
Benchmark_ocicniPortsToNetTypesPorts1k-12                   9414            120964 ns/op           41080 B/op          4 allocs/op
Benchmark_ocicniPortsToNetTypesPorts10k-12                   781           1490526 ns/op          401528 B/op          4 allocs/op
Benchmark_ocicniPortsToNetTypesPorts1m-12                      4         250579010 ns/op        40001656 B/op          4 allocs/op
PASS
ok      github.com/containers/podman/v3/libpod  11.727s
```

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
2021-10-27 18:59:56 +02:00

248 lines
6 KiB
Go

package libpod
import (
"net"
"reflect"
"strings"
"testing"
"time"
"github.com/containers/common/pkg/config"
"github.com/containers/podman/v3/libpod/define"
"github.com/containers/podman/v3/libpod/lock"
"github.com/containers/podman/v3/libpod/network/types"
"github.com/opencontainers/runtime-tools/generate"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func getTestContainer(id, name string, manager lock.Manager) (*Container, error) {
ctr := &Container{
config: &ContainerConfig{
ID: id,
Name: name,
ContainerRootFSConfig: ContainerRootFSConfig{
RootfsImageID: id,
RootfsImageName: "testimg",
StaticDir: "/does/not/exist/",
Mounts: []string{"/does/not/exist"},
},
ContainerMiscConfig: ContainerMiscConfig{
LogPath: "/does/not/exist/",
Stdin: true,
Labels: map[string]string{"a": "b", "c": "d"},
StopSignal: 0,
StopTimeout: 0,
CreatedTime: time.Now(),
},
ContainerSecurityConfig: ContainerSecurityConfig{
Privileged: true,
},
ContainerNetworkConfig: ContainerNetworkConfig{
DNSServer: []net.IP{net.ParseIP("192.168.1.1"), net.ParseIP("192.168.2.2")},
DNSSearch: []string{"example.com", "example.example.com"},
PortMappings: []types.PortMapping{
{
HostPort: 80,
ContainerPort: 90,
Protocol: "tcp",
HostIP: "192.168.3.3",
Range: 1,
},
{
HostPort: 100,
ContainerPort: 110,
Protocol: "udp",
HostIP: "192.168.4.4",
Range: 1,
},
},
},
},
state: &ContainerState{
State: define.ContainerStateRunning,
ConfigPath: "/does/not/exist/specs/" + id,
RunDir: "/does/not/exist/tmp/",
Mounted: true,
Mountpoint: "/does/not/exist/tmp/" + id,
PID: 1234,
ExecSessions: map[string]*ExecSession{
"abcd": {
Id: "1",
PID: 9876,
},
"ef01": {
Id: "5",
PID: 46765,
},
},
BindMounts: map[string]string{
"/1/2/3": "/4/5/6",
"/test/file.test": "/test2/file2.test",
},
},
runtime: &Runtime{
config: &config.Config{
Engine: config.EngineConfig{
VolumePath: "/does/not/exist/tmp/volumes",
},
},
},
valid: true,
}
g, err := generate.New("linux")
if err != nil {
return nil, err
}
ctr.config.Spec = g.Config
ctr.config.Labels["test"] = "testing"
// Allocate a containerLock for the container
containerLock, err := manager.AllocateLock()
if err != nil {
return nil, err
}
ctr.lock = containerLock
ctr.config.LockID = containerLock.ID()
return ctr, nil
}
func getTestPod(id, name string, manager lock.Manager) (*Pod, error) {
pod := &Pod{
config: &PodConfig{
ID: id,
Name: name,
Labels: map[string]string{"a": "b", "c": "d"},
CgroupParent: "/hello/world/cgroup/parent",
},
state: &podState{
CgroupPath: "/path/to/cgroups/hello/",
},
valid: true,
}
// Allocate a podLock for the pod
podLock, err := manager.AllocateLock()
if err != nil {
return nil, err
}
pod.lock = podLock
pod.config.LockID = podLock.ID()
return pod, nil
}
func getTestCtrN(n string, manager lock.Manager) (*Container, error) {
return getTestContainer(strings.Repeat(n, 32), "test"+n, manager)
}
func getTestCtr1(manager lock.Manager) (*Container, error) {
return getTestCtrN("1", manager)
}
func getTestCtr2(manager lock.Manager) (*Container, error) {
return getTestCtrN("2", manager)
}
func getTestPodN(n string, manager lock.Manager) (*Pod, error) {
return getTestPod(strings.Repeat(n, 32), "test"+n, manager)
}
func getTestPod1(manager lock.Manager) (*Pod, error) {
return getTestPodN("1", manager)
}
func getTestPod2(manager lock.Manager) (*Pod, error) {
return getTestPodN("2", manager)
}
// This horrible hack tests if containers are equal in a way that should handle
// empty arrays being dropped to nil pointers in the spec JSON
// For some operations (container retrieval from the database) state is allowed
// to be empty. This is controlled by the allowedEmpty bool.
func testContainersEqual(t *testing.T, a, b *Container, allowedEmpty bool) {
if a == nil && b == nil {
return
}
require.NotNil(t, a)
require.NotNil(t, b)
require.NotNil(t, a.config)
require.NotNil(t, b.config)
require.NotNil(t, a.state)
require.NotNil(t, b.state)
aConfig := new(ContainerConfig)
bConfig := new(ContainerConfig)
aState := new(ContainerState)
bState := new(ContainerState)
blankState := new(ContainerState)
assert.Equal(t, a.valid, b.valid)
assert.Equal(t, a.lock.ID(), b.lock.ID())
aConfigJSON, err := json.Marshal(a.config)
assert.NoError(t, err)
err = json.Unmarshal(aConfigJSON, aConfig)
assert.NoError(t, err)
bConfigJSON, err := json.Marshal(b.config)
assert.NoError(t, err)
err = json.Unmarshal(bConfigJSON, bConfig)
assert.NoError(t, err)
assert.EqualValues(t, aConfig, bConfig)
aStateJSON, err := json.Marshal(a.state)
assert.NoError(t, err)
err = json.Unmarshal(aStateJSON, aState)
assert.NoError(t, err)
bStateJSON, err := json.Marshal(b.state)
assert.NoError(t, err)
err = json.Unmarshal(bStateJSON, bState)
assert.NoError(t, err)
if allowedEmpty {
assert.True(t, reflect.DeepEqual(aState, bState) || reflect.DeepEqual(aState, blankState))
} else {
assert.EqualValues(t, aState, bState)
}
}
// Test if pods are equal.
// For some operations (pod retrieval from the database) state is allowed to be
// empty. This is controlled by the allowedEmpty bool.
func testPodsEqual(t *testing.T, a, b *Pod, allowedEmpty bool) {
if a == nil && b == nil {
return
}
blankState := new(podState)
require.NotNil(t, a)
require.NotNil(t, b)
require.NotNil(t, a.config)
require.NotNil(t, b.config)
require.NotNil(t, a.state)
require.NotNil(t, b.state)
assert.Equal(t, a.valid, b.valid)
assert.Equal(t, a.lock.ID(), b.lock.ID())
assert.EqualValues(t, a.config, b.config)
if allowedEmpty {
assert.True(t, reflect.DeepEqual(a.state, b.state) || reflect.DeepEqual(a.state, blankState))
} else {
assert.EqualValues(t, a.state, b.state)
}
}