mirror of
https://github.com/moby/moby.git
synced 2026-01-11 18:51:37 +00:00
The Container.State struct holds the container's state, and most of
its fields are expected to change dynamically. Some o these state-changes
are explicit, for example, setting the container to be "stopped". Other
state changes can be more explicit, for example due to the containers'
process exiting or being "OOM" killed by the kernel.
The distinction between explicit ("desired") state changes and "state"
("actual state") is sometimes vague; for some properties, we clearly
separated them, for example if a user requested the container to be
stopped or restarted, we store state in the Container object itself;
HasBeenManuallyStopped bool // used for unless-stopped restart policy
HasBeenManuallyRestarted bool `json:"-"` // used to distinguish restart caused by restart policy from the manual one
Other properties are more ambiguous. such as "HasBeenStartedBefore" and
"RestartCount", which are stored on the Container (and persisted to
disk), but may be more related to "actual" state, and likely should
not be persisted;
RestartCount int
HasBeenStartedBefore bool
Given that (per the above) concurrency must be taken into account, most
changes to the `container.State` struct should be protected; here's where
things get blurry. While the `State` type provides various accessor methods,
only some of them take concurrency into account; for example, [State.IsRunning]
and [State.GetPID] acquire a lock, whereas [State.ExitCodeValue] does not.
Even the (commonly used) [State.StateString] has no locking at all.
The way to handle this is error-prone; [container.State] contains a mutex,
and it's exported. Given that its embedded in the [container.Container]
struct, it's also exposed as an exported mutex for the container. The
assumption here is that by "merging" the two, the caller to acquire a lock
when either the container _or_ its state must be mutated. However, because
some methods on `container.State` handle their own locking, consumers must
be deeply familiar with the internals; if both changes to the `Container`
AND `Container.State` must be made. This gets amplified more as some
(exported!) methods, such as [container.SetRunning] mutate multiple fields,
but don't acquire a lock (so expect the caller to hold one), but their
(also exported) counterpart (e.g. [State.IsRunning]) do.
It should be clear from the above, that this needs some architectural
changes; a clearer separation between "desired" and "actual" state (opening
the potential to update the container's config without manually touching
its `State`), possibly a method to obtain a read-only copy of the current
state (for those querying state), and reviewing which fields belong where
(and should be persisted to disk, or only remain in memory).
This PR preserves the status quo; it makes no structural changes, other
than exposing where we access the container's state. Where previously the
State fields and methods were referred to as "part of the container"
(e.g. `ctr.IsRunning()` or `ctr.Running`), we now explicitly reference
the embedded `State` (`ctr.State.IsRunning`, `ctr.State.Running`).
The exception (for now) is the mutex, which is still referenced through
the embedded struct (`ctr.Lock()` instead of `ctr.State.Lock()`), as this
is (mostly) by design to protect the container, and what's in it (including
its `State`).
[State.IsRunning]: c4afa77157/daemon/container/state.go (L205-L209)
[State.GetPID]: c4afa77157/daemon/container/state.go (L211-L216)
[State.ExitCodeValue]: c4afa77157/daemon/container/state.go (L218-L228)
[State.StateString]: c4afa77157/daemon/container/state.go (L102-L131)
[container.State]: c4afa77157/daemon/container/state.go (L15-L23)
[container.Container]: c4afa77157/daemon/container/container.go (L67-L75)
[container.SetRunning]: c4afa77157/daemon/container/state.go (L230-L277)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
230 lines
6.5 KiB
Go
230 lines
6.5 KiB
Go
package daemon
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
containertypes "github.com/moby/moby/api/types/container"
|
|
"github.com/moby/moby/api/types/filters"
|
|
"github.com/moby/moby/v2/daemon/container"
|
|
"github.com/moby/moby/v2/daemon/internal/image"
|
|
"github.com/moby/moby/v2/daemon/server/backend"
|
|
"github.com/opencontainers/go-digest"
|
|
"gotest.tools/v3/assert"
|
|
is "gotest.tools/v3/assert/cmp"
|
|
)
|
|
|
|
var root string
|
|
|
|
func TestMain(m *testing.M) {
|
|
var err error
|
|
root, err = os.MkdirTemp("", "docker-container-test-")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
defer os.RemoveAll(root)
|
|
os.Exit(m.Run())
|
|
}
|
|
|
|
// This sets up a container with a name so that name filters
|
|
// work against it. It takes in a pointer to Daemon so that
|
|
// minor operations are not repeated by the caller
|
|
func setupContainerWithName(t *testing.T, name string, daemon *Daemon) *container.Container {
|
|
t.Helper()
|
|
var (
|
|
id = uuid.New().String()
|
|
computedImageID = image.ID(digest.FromString(id))
|
|
cRoot = filepath.Join(root, id)
|
|
)
|
|
if err := os.MkdirAll(cRoot, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
c := container.NewBaseContainer(id, cRoot)
|
|
// these are for passing includeContainerInList
|
|
if name[0] != '/' {
|
|
name = "/" + name
|
|
}
|
|
c.Name = name
|
|
c.State.Running = true
|
|
c.HostConfig = &containertypes.HostConfig{}
|
|
c.Created = time.Now()
|
|
|
|
// these are for passing the refreshImage reducer
|
|
c.ImageID = computedImageID
|
|
c.Config = &containertypes.Config{
|
|
Image: computedImageID.String(),
|
|
}
|
|
|
|
// this is done here to avoid requiring these
|
|
// operations n x number of containers in the
|
|
// calling function
|
|
daemon.containersReplica.Save(c)
|
|
daemon.reserveName(id, name)
|
|
|
|
return c
|
|
}
|
|
|
|
func containerListContainsName(containers []*containertypes.Summary, name string) bool {
|
|
for _, ctr := range containers {
|
|
for _, containerName := range ctr.Names {
|
|
if containerName == name {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func TestContainerList(t *testing.T) {
|
|
db, err := container.NewViewDB()
|
|
assert.NilError(t, err)
|
|
d := &Daemon{
|
|
containersReplica: db,
|
|
}
|
|
|
|
// test list with different number of containers
|
|
for _, num := range []int{0, 1, 2, 4, 8, 16, 32, 64, 100} {
|
|
t.Run(fmt.Sprintf("%d containers", num), func(t *testing.T) {
|
|
db, err := container.NewViewDB() // new DB to ignore prior containers
|
|
assert.NilError(t, err)
|
|
d = &Daemon{
|
|
containersReplica: db,
|
|
}
|
|
|
|
// create the containers
|
|
containers := make([]*container.Container, num)
|
|
for i := range num {
|
|
name := fmt.Sprintf("cont-%d", i)
|
|
containers[i] = setupContainerWithName(t, name, d)
|
|
// ensure container timestamps are separated enough so the
|
|
// sort used by d.Containers() can deterministically sort them.
|
|
if i > 0 {
|
|
containers[i].Created = containers[i-1].Created.Add(time.Millisecond)
|
|
}
|
|
}
|
|
|
|
// list them and verify correctness
|
|
containerList, err := d.Containers(context.Background(), &backend.ContainerListOptions{All: true})
|
|
assert.NilError(t, err)
|
|
assert.Assert(t, is.Len(containerList, num))
|
|
|
|
for i := range num {
|
|
// container list should be ordered in descending creation order
|
|
assert.Assert(t, is.Equal(containerList[i].Names[0], containers[num-1-i].Name))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestContainerList_InvalidFilter(t *testing.T) {
|
|
db, err := container.NewViewDB()
|
|
assert.NilError(t, err)
|
|
d := &Daemon{
|
|
containersReplica: db,
|
|
}
|
|
|
|
_, err = d.Containers(context.Background(), &backend.ContainerListOptions{
|
|
Filters: filters.NewArgs(filters.Arg("invalid", "foo")),
|
|
})
|
|
assert.Assert(t, is.Error(err, "invalid filter 'invalid'"))
|
|
}
|
|
|
|
func TestContainerList_NameFilter(t *testing.T) {
|
|
db, err := container.NewViewDB()
|
|
assert.NilError(t, err)
|
|
d := &Daemon{
|
|
containersReplica: db,
|
|
}
|
|
|
|
var (
|
|
one = setupContainerWithName(t, "a1", d)
|
|
two = setupContainerWithName(t, "a2", d)
|
|
three = setupContainerWithName(t, "b1", d)
|
|
)
|
|
|
|
// moby/moby #37453 - ^ regex not working due to prefix slash
|
|
// not being stripped
|
|
containerList, err := d.Containers(context.Background(), &backend.ContainerListOptions{
|
|
Filters: filters.NewArgs(filters.Arg("name", "^a")),
|
|
})
|
|
assert.NilError(t, err)
|
|
assert.Assert(t, is.Len(containerList, 2))
|
|
assert.Assert(t, containerListContainsName(containerList, one.Name))
|
|
assert.Assert(t, containerListContainsName(containerList, two.Name))
|
|
|
|
// Same as above but with slash prefix should produce the same result
|
|
containerListWithPrefix, err := d.Containers(context.Background(), &backend.ContainerListOptions{
|
|
Filters: filters.NewArgs(filters.Arg("name", "^/a")),
|
|
})
|
|
assert.NilError(t, err)
|
|
assert.Assert(t, is.Len(containerListWithPrefix, 2))
|
|
assert.Assert(t, containerListContainsName(containerListWithPrefix, one.Name))
|
|
assert.Assert(t, containerListContainsName(containerListWithPrefix, two.Name))
|
|
|
|
// Same as above but make sure it works for exact names
|
|
containerList, err = d.Containers(context.Background(), &backend.ContainerListOptions{
|
|
Filters: filters.NewArgs(filters.Arg("name", "b1")),
|
|
})
|
|
assert.NilError(t, err)
|
|
assert.Assert(t, is.Len(containerList, 1))
|
|
assert.Assert(t, containerListContainsName(containerList, three.Name))
|
|
|
|
// Same as above but with slash prefix should produce the same result
|
|
containerListWithPrefix, err = d.Containers(context.Background(), &backend.ContainerListOptions{
|
|
Filters: filters.NewArgs(filters.Arg("name", "/b1")),
|
|
})
|
|
assert.NilError(t, err)
|
|
assert.Assert(t, is.Len(containerListWithPrefix, 1))
|
|
assert.Assert(t, containerListContainsName(containerListWithPrefix, three.Name))
|
|
}
|
|
|
|
func TestContainerList_LimitFilter(t *testing.T) {
|
|
db, err := container.NewViewDB()
|
|
assert.NilError(t, err)
|
|
d := &Daemon{
|
|
containersReplica: db,
|
|
}
|
|
|
|
// start containers
|
|
num := 32
|
|
for i := range num {
|
|
name := fmt.Sprintf("cont-%d", i)
|
|
setupContainerWithName(t, name, d)
|
|
}
|
|
|
|
containers, err := db.Snapshot().All()
|
|
assert.NilError(t, err)
|
|
assert.Assert(t, is.Len(containers, num))
|
|
|
|
tests := []struct {
|
|
limit int
|
|
doc string
|
|
}{
|
|
{limit: 0, doc: "no limit"},
|
|
{limit: -1, doc: "negative limit doesn't limit"},
|
|
{limit: 1, doc: "limit 1 container"},
|
|
{limit: 20, doc: "limit less than num containers"},
|
|
{limit: 32, doc: "limit equal num containers"},
|
|
{limit: 40, doc: "limit greater than num containers"},
|
|
}
|
|
|
|
for _, tc := range tests {
|
|
t.Run(tc.doc, func(t *testing.T) {
|
|
containerList, err := d.Containers(context.Background(), &backend.ContainerListOptions{Limit: tc.limit})
|
|
assert.NilError(t, err)
|
|
expectedListLen := num
|
|
if tc.limit > 0 {
|
|
expectedListLen = min(num, tc.limit)
|
|
}
|
|
assert.Assert(t, is.Len(containerList, expectedListLen))
|
|
})
|
|
}
|
|
}
|