Merge pull request #556 from vcaputo/expand_container_lifecycle_encompass_uuids

*: refactor container lifecycle to be more granular/comprehensive
This commit is contained in:
Vito Caputo
2015-03-07 18:13:34 -08:00
13 changed files with 1013 additions and 285 deletions
+79 -11
View File
@@ -1,35 +1,103 @@
# Life-cycle of a container in rocket
## Creation
Throughout this document `$var` is used to refer to the directory `/var/lib/rkt/containers`, and `$uuid` refers to a container's UUID e.g. "076292e6-54c4-4cc8-9fa7-679c5f7dcfd3".
`rkt run` instantiates a container UUID and file-system tree rooted at `/var/lib/rkt/containers/$uuid/.`, henceforth referred to as `$cdir`.
Due to rocket's lack of a management daemon process, a combination of advisory file locking and atomically changing (via rename(2)) directory locations is used to represent and transition the basic container states.
A robust mechanism is necessary for reliably determining whether a container is executing so garbage collection may be safely and reliably implemented. In lieu of a daemon process responsible for managing the execution of containers, an advisory lock associated with an open file descriptor in the container's /init process context is used instead. The advisory lock is acquired exclusively on `$cdir` early in the container execution, this lock is automatically released by the kernel when the /init process exits.
At times where a state must be reliably coupled to an executing process, that process is executed with an open file descriptor possessing an exclusive advisory lock on the respective container's directory. Should that process exit for any reason, its open file descriptors will automatically be closed by the kernel, implicitly unlocking the container's directory in the process. By attempting to acquire a shared non-blocking advisory lock on a container directory we're able to poll for these process-bound states, additionally by employing a blocking acquisition mode we may reliably synchronize indirectly with the exit of such processes, effectively providing us with a wake-up event the moment such a state transitions. For more information on advisory locks see the flock(2) man page.
At this time there are four distinct phases of a container's life which involve process-bound states:
* Prepare
* Run
* ExitedGarbage
* Garbage
Each of these phases involves an exclusive lock on a given container's directory. As an exclusive lock by itself cannot express both the phase and process-bound activity within that phase, we combine the lock with the container's directory location to represent the whole picture:
locked unlocked
exclusively
* Prepare: "$var/prepare/$uuid" preparing prepare-failed
* Run: "$var/run/$uuid" running exited
* ExitedGarbage: "$var/exited-garbage/$uuid" exited+deleting exited+gc-marked
* Garbage: "$var/garbage/$uuid" prepare-failed+deleting prepare-failed+gc-marked
To prevent the period between first creating a container's directory and acquiring its lock from appearing as prepare-failed in the Prepare phase, and to provide a phase for prepared containers where they may dwell and the lock may be acquired prior to entering the Run phase, two additional directories are employed where locks have no meaning:
* Embryo: "$var/embryo/$uuid" - -
* Prepare: "$var/prepare/$uuid" preparing prepare-failed
* Prepared: "$var/prepared/$uuid" - -
* Run: "$var/run/$uuid" running exited
* ExitedGarbage: "$var/exited-garbage/$uuid" exited+deleting exited+gc-marked
* Prepare-failed: "$var/garbage/$uuid" prepare-failed+deleting prepare-failed+gc-marked
These phases, their function, and how they proceed through their respective states is explained in more detail below.
## Embryo
`rkt run` and `rkt prepare` instantiate a new container by creating an empty directory at `$var/embryo/$uuid`.
An exclusive lock is immediately acquired on the created directory which is then renamed to `$var/prepare/$uuid`, transitioning to the #Prepare phase.
## Prepare
`rkt run` and `rkt prepare` enter this phase identically; holding an exclusive lock on the container directory `$var/prepare/$uuid`.
After preparation completes, while still holding the exclusive lock (the lock is held for the duration):
`rkt prepare` transitions to #Prepared by renaming `$var/prepare/$uuid` to `$var/prepared/$uuid`.
`rkt run` transitions directly from #Prepare to #Run by renaming `$var/prepare/$uuid` to `$var/run/$uuid`, entirely skipping the #Prepared phase.
Should #Prepare fail or be interrupted, `$var/prepare/$uuid` will be left in an unlocked state. Any directory in `$var/prepare` in an unlocked state is considered a failed prepare. `rkt gc` identifies failed prepares in need of cleanup by trying to acquire a shared lock on all directories in `$var/prepare`, renaming successfully locked directories to `$var/garbage` where they are then deleted.
## Prepared
`rkt prepare` concludes successfully by leaving the container directory at `$var/prepared/$uuid` in an unlocked state before returning $uuid to the user.
`rkt run-prepared` resumes where `rkt prepare` concluded by exclusively locking the container at `$var/prepared/$uuid` before renaming it to `$var/run/$uuid`, specifically acquiring the lock prior to entering the #Run phase.
`rkt run` never enters this phase, skipping directly from #Prepare to #Run with the lock held.
## Run
`rkt run` and `rkt run-prepared` both arrive here with the container at `$var/run/$uuid` while holding the exclusive lock.
The container is then excuted while holding this lock. It is required that the stage 1 `coreos.com/rocket/stage1/run` entrypoint keep the file descriptor representing the exclusive lock open for the lifetime of the container's process. All this requires is that the stage 1 implementation not close the inherited file descriptor. This is facilitated by supplying stage 1 its number in the RKT_LOCK_FD environment variable.
What follows applies equally to `rkt run` and `rkt run-prepared`.
## Death / exit
A container is considered exited if an advisory lock can be acquired on `$cdir`. Upon exit of a container's /init process, the exclusive `$cdir` lock acquired at the beginning of `rkt run` becomes released by the kernel.
A container is considered exited if a shared lock can be acquired on `$var/run/$uuid`. Upon exit of a container's process, the exclusive lock acquired before entering the #Run phase becomes released by the kernel.
## Garbage collection
Exited containers are discarded using a common mark-and-sweep style of garbage collection by invoking the `rkt gc` command. This relatively simple approach lends itself well to a minimal file-system-based implementation utilizing no additional daemons or record-keeping with good efficiency. The process is performed in two distinct passes explained below in detail.
Exited containers are discarded using a common mark-and-sweep style of garbage collection by invoking the `rkt gc` command. This relatively simple approach lends itself well to a minimal file-system based implementation utilizing no additional daemons or record keeping with good efficiency. The process is performed in two distinct passes explained in detail below.
### Pass 1: mark
All directories found in `/var/lib/rkt/containers` are tested for exited status by trying to acquire a shared advisory lock on each directory.
All directories found in `$var/run` are tested for exited status by trying to acquire a shared advisory lock on each directory.
When a directory's lock cannot be acquired, the directory is skipped as it indicates the container is currently executing.
For directories which the lock is successfully acquired, the directory is atomically renamed from `/var/lib/rkt/containers/$uuid` to `/var/lib/rkt/garbage/$uuid`. The renaming effectively implements the "mark" operation. The locks are immediately released, and operations like `rkt status` may occur simultaneous to `rkt gc`.
For directories which the lock is successfully acquired, the directory is renamed from `$var/run/$uuid` to `$var/exited-garbage/$uuid`. The renaming effectively implements the "mark" operation. The locks are immediately released, and operations like `rkt status` may occur simultaneous to `rkt gc`.
Containers dwell in the `/var/lib/rkt/garbage` directory for a grace-period during which their status may continue to be queried by `rkt status`. The rename from `/var/lib/rkt/containers/$uuid` to `/var/lib/rkt/garbage/$uuid` serves to keep exited containers from cluttering the `/var/lib/rkt/containers` directory during their respective dwell periods.
Marked exited containers dwell in the `$var/exited-garbage` directory for a grace period during which their status may continue to be queried by `rkt status`. The rename from `$var/run/$uuid` to `$var/exited-garbage/$uuid` serves in part to keep marked containers from cluttering the `$var/run` directory during their respective dwell periods.
### Pass 2: sweep
A side-effect of the rename operation responsible for moving a container from `/var/lib/rkt/containers` to `/var/lib/rkt/garbage` is an update to the container directory's change time. The sweep operation takes advantage of this in honoring the necessary grace-period before discarding exited containers. This grace period currently defaults to 30 minutes, and may be explicitly specified using the `--grace-period duration` option of `rkt gc`. Note that this grace period begins from the time a container was marked by `rkt gc`, not when the container exited. A container becomes eligible for marking upon exit, but will not be marked until a subsequent `rkt gc` is performed.
A side-effect of the rename operation responsible for moving a container from `$var/run` to `$var/exited-garbage` is an update to the container directory's change time. The sweep operation takes advantage of this in honoring the necessary grace period before discarding exited containers. This grace period currently defaults to 30 minutes, and may be explicitly specified using the `--grace-period duration` flag with `rkt gc`. Note that this grace period begins from the time a container was marked by `rkt gc`, not when the container exited. A container becomes eligible for marking upon exit, but will not become marked until a subsequent `rkt gc` is performed.
The change times of all directories found in `/var/lib/rkt/garbage` are compared against the current time. Directories having sufficiently old change times are locked exclusively and recursively deleted. If a lock acquisition fails, the directory is skipped. Failed exclusive lock acquisitions may occur if the garbage container is currently being accessed via `rkt status`, for example. The skipped containers will be revisited on a subsequent `rkt gc` invocation's sweep pass.
The change times of all directories found in `$var/exited-garbage` are compared against the current time. Directories having sufficiently old change times are locked exclusively and recursively deleted. If a lock acquisition fails, the directory is skipped. Failed exclusive lock acquisitions may occur if the garbage container is currently being accessed via `rkt status`, or deleted by a concurrent `rkt gc`, for example. The skipped containers will be revisited on a subsequent `rkt gc` invocation's sweep pass.
## Pulse
To answer the questions "Has this container exited?" and "Is this container being deleted?" the container's UUID is looked for in `/var/lib/rkt/containers` and `/var/lib/rkt/garbage`. Containers found in the `/var/lib/rkt/garbage` directory must already be exited, and a shared lock acquisition may be used to determine if the garbage container is actively being deleted. Those found in the `/var/lib/rkt/containers` directory may be exited or running, a failed shared lock acquisition indicates a container in `/var/lib/rkt/containers` is alive at the time of the failed acquisition.
To answer the questions "Has this container exited?" and "Is this container being deleted?" the container's UUID is looked for in `$var/run` and `$var/exited-garbage`, respectively. Containers found in the `$var/exited-garbage` directory must already be exited, and a shared lock acquisition may be used to determine if the garbage container is actively being deleted. Those found in the `$var/run` directory may be exited or running, a failed shared lock acquisition indicates a container in `$var/run` is alive at the time of the failed acquisition.
Care must be taken when acting on what is effectively always going to be stale knowledge of container state; though a container's status may be found to be "running" by the mechanisms documented here, this was an instantaneously sampled state that was true at the time sampled (failed lock attempt at $var/run/$uuid), and may cease to be true by the time code execution progressed to acting on that sample. Container exit is totally asynchronous and cannot be prevented, relevant code must take this into consideration (e.g. `rkt enter`) and be tolerant of states progressing.
For example, two `rkt run-prepared` invocations for the same UUID may occur simultaneously. Only one of these will successfully transition the container from #Prepared to #Run due to rename's atomicity, which is exactly what we want. The loser of this race needs to simply inform the user of the inability to transition the container to the run state, perhaps with a check to see if the container transitioned independently and a useful message mentioning it.
Another example would be two `rkt gc` commands finding the same exited containers and attempting to transition them to the #Garbage phase concurrently. They can't both perform the transitions, one will lose the race at each same container. This needs to be considered in the error handling of the transition callers as perfectly normal, simply ignoring ENOENT errors propagated from the loser's rename calls can suffice.
+492 -89
View File
@@ -25,28 +25,68 @@ import (
"syscall"
"time"
"github.com/coreos/rocket/Godeps/_workspace/src/code.google.com/p/go-uuid/uuid"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
"github.com/coreos/rocket/pkg/lock"
)
// see Documentation/container-lifecycle.md for some explanation
type container struct {
*lock.DirLock
uuid string
isExited bool
isGarbage bool
isDeleting bool
createdAt time.Time
garbageAt time.Time
uuid *types.UUID
createdByMe bool // true if we're the creator of this container (only the creator can xToPrepare or xToRun directly from preparing)
isEmbryo bool // directory starts as embryo before entering preparing state, serves as stage for acquiring lock before rename to prepare/.
isPreparing bool // when locked at containers/prepare/$uuid the container is actively being prepared
isAbortedPrepare bool // when unlocked at containers/prepare/$uuid the container never finished preparing
isPrepared bool // when at containers/prepared/$uuid the container is prepared, serves as stage for acquiring lock before rename to run/.
isExited bool // when locked at containers/run/$uuid the container is running, when unlocked it's exited.
isExitedGarbage bool // when unlocked at containers/exited-garbage/$uuid the container is exited and is garbage
isExitedDeleting bool // when locked at containers/exited-garbage/$uuid the container is exited, garbage, and is being actively deleted
isGarbage bool // when unlocked at containers/garbage/$uuid the container is garbage that never ran
isDeleting bool // when locked at containers/garbage/$uuid the container is garbage that never ran, and is being actively deleted
isGone bool // when a container no longer can be located at its uuid anywhere XXX: only set by refreshState()
}
type includeMask byte
const (
includeContainersDir includeMask = 1 << iota
includeEmbryoDir includeMask = 1 << iota
includePrepareDir
includePreparedDir
includeRunDir
includeExitedGarbageDir
includeGarbageDir
includeMostDirs includeMask = (includeRunDir | includeExitedGarbageDir | includePrepareDir | includePreparedDir)
includeAllDirs includeMask = (includeMostDirs | includeEmbryoDir | includeGarbageDir)
)
// walkContainers iterates over the included containers calling function f for every container.
var (
containersInitialized = false
)
// initContainers creates the required global directories
func initContainers() error {
if !containersInitialized {
dirs := []string{embryoDir(), prepareDir(), preparedDir(), runDir(), exitedGarbageDir(), garbageDir()}
for _, d := range dirs {
if err := os.MkdirAll(d, 0700); err != nil {
return fmt.Errorf("error creating directory: %v", err)
}
}
containersInitialized = true
}
return nil
}
// walkContainers iterates over the included directories calling function f for every container found.
func walkContainers(include includeMask, f func(*container)) error {
if err := initContainers(); err != nil {
return err
}
ls, err := listContainers(include)
if err != nil {
return fmt.Errorf("failed to get containers: %v", err)
@@ -60,9 +100,15 @@ func walkContainers(include includeMask, f func(*container)) error {
continue
}
// omit garbage containers if garbage wasn't included
// this is to cover a race between listContainers finding the uuids and `rkt gc` renaming a container
if c.isGarbage && include&includeGarbageDir == 0 {
// omit containers found in unrequested states
// this is to cover a race between listContainers finding the uuids and container states changing
// it's preferable to keep these operations lock-free, for example a `rkt gc` shouldn't block `rkt run`.
if c.isEmbryo && include&includeEmbryoDir == 0 ||
c.isExitedGarbage && include&includeExitedGarbageDir == 0 ||
c.isGarbage && include&includeGarbageDir == 0 ||
c.isPrepared && include&includePreparedDir == 0 ||
((c.isPreparing || c.isAbortedPrepare) && include&includePrepareDir == 0) ||
c.isRunning() && include&includeRunDir == 0 {
c.Close()
continue
}
@@ -70,109 +116,342 @@ func walkContainers(include includeMask, f func(*container)) error {
f(c)
c.Close()
}
return nil
}
// newContainer creates a new container directory in the "preparing" state, allocating a unique uuid for it in the process.
// The returned container is always left in an exclusively locked state (preparing is locked in the prepared directory)
// The container must be closed using container.Close()
func newContainer() (*container, error) {
if err := initContainers(); err != nil {
return nil, err
}
c := &container{
createdByMe: true,
isEmbryo: true, // starts as an embryo, then xToPreparing locks, renames, and sets isPreparing
// rest start false.
}
var err error
c.uuid, err = types.NewUUID(uuid.New())
if err != nil {
return nil, fmt.Errorf("error creating UUID: %v", err)
}
err = os.Mkdir(c.embryoPath(), 0700)
if err != nil {
return nil, err
}
c.DirLock, err = lock.NewLock(c.embryoPath())
if err != nil {
os.Remove(c.embryoPath())
return nil, err
}
err = c.xToPreparing()
if err != nil {
return nil, err
}
// At this point we we have:
// /var/lib/rkt/containers/prepare/$uuid << exclusively locked to indicate "preparing"
return c, nil
}
// getContainer returns a container struct representing the given container.
// The returned lock is always left in an open but unlocked state.
// The container must be closed using container.Close()
func getContainer(uuid string) (*container, error) {
c := &container{
uuid: uuid,
isGarbage: true,
isExited: true,
isDeleting: false,
if err := initContainers(); err != nil {
return nil, err
}
l, err := lock.NewLock(filepath.Join(garbageDir(), uuid))
if err == lock.ErrNotExist {
l, err = lock.NewLock(filepath.Join(containersDir(), uuid))
c.isGarbage = false
c.isExited = false
}
c := &container{}
u, err := types.NewUUID(uuid)
if err != nil {
return nil, err
}
c.uuid = u
// we try open the container in all possible directories, in the same order the states occur
l, err := lock.NewLock(c.embryoPath())
if err == nil {
c.isEmbryo = true
} else if err == lock.ErrNotExist {
l, err = lock.NewLock(c.preparePath())
if err == nil {
// treat as aborted prepare until lock is tested
c.isAbortedPrepare = true
} else if err == lock.ErrNotExist {
l, err = lock.NewLock(c.preparedPath())
if err == nil {
c.isPrepared = true
} else if err == lock.ErrNotExist {
l, err = lock.NewLock(c.runPath())
if err == nil {
// treat as exited until lock is tested
c.isExited = true
} else if err == lock.ErrNotExist {
l, err = lock.NewLock(c.exitedGarbagePath())
if err == lock.ErrNotExist {
l, err = lock.NewLock(c.garbagePath())
if err == nil {
c.isGarbage = true
} else {
return nil, fmt.Errorf("container %q not found", uuid)
}
} else if err == nil {
c.isExitedGarbage = true
c.isExited = true // ExitedGarbage is _always_ implicitly exited
}
}
}
}
}
if err != nil && err != lock.ErrNotExist {
return nil, fmt.Errorf("error opening container %q: %v", uuid, err)
}
if err = l.TrySharedLock(); err != nil {
if err != lock.ErrLocked {
l.Close()
return nil, fmt.Errorf("unexpected lock error: %v", err)
if !c.isPrepared && !c.isEmbryo {
// preparing, run, exitedGarbage, and garbage dirs use exclusive locks to indicate preparing/aborted, running/exited, and deleting/marked
if err = l.TrySharedLock(); err != nil {
if err != lock.ErrLocked {
l.Close()
return nil, fmt.Errorf("unexpected lock error: %v", err)
}
if c.isExitedGarbage {
// locked exitedGarbage is also being deleted
c.isExitedDeleting = true
} else if c.isExited {
// locked exited and !exitedGarbage is not exited (default in the run dir)
c.isExited = false
} else if c.isAbortedPrepare {
// locked in preparing is preparing, not aborted (default in the preparing dir)
c.isAbortedPrepare = false
c.isPreparing = true
} else if c.isGarbage {
// locked in non-exited garbage is deleting
c.isDeleting = true
}
err = nil
} else {
l.Unlock()
}
if c.isGarbage {
c.isDeleting = true
}
} else {
l.Unlock()
c.isExited = true
}
c.DirLock = l
cfd, err := c.Fd()
if err != nil {
c.Close()
return nil, fmt.Errorf("error getting lock fd: %v", err)
}
var st syscall.Stat_t
if err := syscall.Fstat(cfd, &st); err != nil {
return nil, fmt.Errorf("error stating container: %v", err)
}
// The container directory's mtime is approximately the time it was created
c.createdAt = time.Unix(st.Mtim.Unix())
// If the container is garbage, its Ctim reflects when it was marked as such
if c.isGarbage {
c.garbageAt = time.Unix(st.Ctim.Unix())
}
return c, nil
}
// path returns the path to the container where it was opened.
// path returns the path to the container according to the current (cached) state.
func (c *container) path() string {
if c.isGarbage {
if c.isEmbryo {
return c.embryoPath()
} else if c.isPreparing || c.isAbortedPrepare {
return c.preparePath()
} else if c.isPrepared {
return c.preparedPath()
} else if c.isExitedGarbage {
return c.exitedGarbagePath()
} else if c.isGarbage {
return c.garbagePath()
} else if c.isGone {
return "" // TODO(vc): anything better?
}
return c.containersPath()
return c.runPath()
}
// embryoPath returns the path to the container where it would be in the embryoDir in its embryonic state.
func (c *container) embryoPath() string {
return filepath.Join(embryoDir(), c.uuid.String())
}
// preparePath returns the path to the container where it would be in the prepareDir in its preparing state.
func (c *container) preparePath() string {
return filepath.Join(prepareDir(), c.uuid.String())
}
// preparedPath returns the path to the container where it would be in the preparedDir.
func (c *container) preparedPath() string {
return filepath.Join(preparedDir(), c.uuid.String())
}
// runPath returns the path to the container where it would be in the runDir.
func (c *container) runPath() string {
return filepath.Join(runDir(), c.uuid.String())
}
// exitedGarbagePath returns the path to the container where it would be in the exitedGarbageDir.
func (c *container) exitedGarbagePath() string {
return filepath.Join(exitedGarbageDir(), c.uuid.String())
}
// garbagePath returns the path to the container where it would be in the garbageDir.
func (c *container) garbagePath() string {
return filepath.Join(garbageDir(), c.uuid)
return filepath.Join(garbageDir(), c.uuid.String())
}
// containersPath returns the path to the container where it would be in the containersDir.
func (c *container) containersPath() string {
return filepath.Join(containersDir(), c.uuid)
// xToPrepare transitions a container from embryo -> preparing, leaves the container locked in the prepare directory.
// only the creator of the container (via newContainer()) may do this, nobody to race with.
func (c *container) xToPreparing() error {
if !c.createdByMe {
return fmt.Errorf("bug: only containers created by me may transition to preparing")
}
if !c.isEmbryo {
return fmt.Errorf("bug: only embryonic containers can transition to preparing")
}
if err := c.ExclusiveLock(); err != nil {
return err
}
if err := os.Rename(c.embryoPath(), c.preparePath()); err != nil {
return err
}
c.isEmbryo = false
c.isPreparing = true
return nil
}
// xToPrepared transitions a container from preparing -> prepared, leaves the container unlocked in the prepared directory.
// only the creator of the container (via newContainer()) may do this, nobody to race with.
func (c *container) xToPrepared() error {
if !c.createdByMe {
return fmt.Errorf("bug: only containers created by me may transition to prepared")
}
if !c.isPreparing {
return fmt.Errorf("bug: only preparing containers may transition to prepared")
}
if err := os.Rename(c.path(), c.preparedPath()); err != nil {
return err
}
if err := c.Unlock(); err != nil {
return err
}
c.isPreparing = false
c.isPrepared = true
return nil
}
// xToRun transitions a container from prepared -> run, leaves the container locked in the run directory.
// the creator of the container (via newContainer()) may also jump directly from preparing -> run
func (c *container) xToRun() error {
if !c.createdByMe && !c.isPrepared {
return fmt.Errorf("bug: only prepared containers may transition to run")
}
if c.createdByMe && !c.isPrepared && !c.isPreparing {
return fmt.Errorf("bug: only prepared or preparing containers may transition to run")
}
if err := c.ExclusiveLock(); err != nil {
return err
}
if err := os.Rename(c.path(), c.runPath()); err != nil {
// TODO(vc): we could race here with a concurrent xToRun(), let caller deal with the error.
return err
}
c.isPreparing = false
c.isPrepared = false
return nil
}
// xToExitedGarbage transitions a container from run -> exitedGarbage
func (c *container) xToExitedGarbage() error {
if !c.isExited || c.isExitedGarbage {
return fmt.Errorf("bug: only exited non-garbage containers may transition to exited-garbage")
}
if err := os.Rename(c.runPath(), c.exitedGarbagePath()); err != nil {
// TODO(vc): another case where we could race with a concurrent xToExitedGarbage(), let caller deal with the error.
return err
}
c.isExitedGarbage = true
return nil
}
// xToGarbage transitions a container from prepared -> garbage or prepared -> garbage
func (c *container) xToGarbage() error {
if !c.isAbortedPrepare && !c.isPrepared {
return fmt.Errorf("bug: only failed prepare or prepared containers may transition to garbage")
}
if err := os.Rename(c.path(), c.garbagePath()); err != nil {
return err
}
c.isAbortedPrepare = false
c.isPrepared = false
c.isGarbage = true
return nil
}
// isRunning does the annoying tests to infer if a container is in a running state
func (c *container) isRunning() bool {
// when none of these things, running!
return !c.isEmbryo && !c.isAbortedPrepare && !c.isPreparing && !c.isPrepared && !c.isExited && !c.isExitedGarbage && !c.isGarbage && !c.isGone
}
// listContainers returns a list of container uuids in string form.
func listContainers(include includeMask) ([]string, error) {
// uniqued due to the possibility of a container being renamed from containersDir to garbageDir during this operation
// uniqued due to the possibility of a container being renamed from across directories during the list operation
ucs := make(map[string]struct{})
if include&includeContainersDir != 0 {
cs, err := listContainersFromDir(containersDir())
if err != nil {
return nil, err
}
for _, c := range cs {
ucs[c] = struct{}{}
}
dirs := []struct {
kind includeMask
path string
}{
{ // the order here is significant: embryo -> preparing -> prepared -> running -> exitedGarbage
kind: includeEmbryoDir,
path: embryoDir(),
}, {
kind: includePrepareDir,
path: prepareDir(),
}, {
kind: includePreparedDir,
path: preparedDir(),
}, {
kind: includeRunDir,
path: runDir(),
}, {
kind: includeExitedGarbageDir,
path: exitedGarbageDir(),
}, {
kind: includeGarbageDir,
path: garbageDir(),
},
}
if include&includeGarbageDir != 0 {
cs, err := listContainersFromDir(garbageDir())
if err != nil {
return nil, err
}
for _, c := range cs {
ucs[c] = struct{}{}
for _, d := range dirs {
if include&d.kind != 0 {
cs, err := listContainersFromDir(d.path)
if err != nil {
return nil, err
}
for _, c := range cs {
ucs[c] = struct{}{}
}
}
}
@@ -207,18 +486,119 @@ func listContainersFromDir(cdir string) ([]string, error) {
return cs, nil
}
// waitExited waits for a container to exit.
func (c *container) waitExited() error {
if !c.isExited {
if err := c.SharedLock(); err != nil {
return err
// refreshState() updates the cached members of c to reflect current reality
// assumes c.DirLock is currently unlocked, and always returns with it unlocked.
func (c *container) refreshState() error {
// TODO(vc): this overlaps substantially with newContainer(), could probably unify.
c.isEmbryo = false
c.isPreparing = false
c.isAbortedPrepare = false
c.isPrepared = false
c.isExited = false
c.isExitedGarbage = false
c.isExitedDeleting = false
c.isGarbage = false
c.isDeleting = false
c.isGone = false
// we try open the container in all possible directories, in the same order the states occur
_, err := os.Stat(c.embryoPath())
if err == nil {
c.isEmbryo = true
} else if os.IsNotExist(err) {
_, err := os.Stat(c.preparePath())
if err == nil {
// treat as aborted prepare until lock is tested
c.isAbortedPrepare = true
} else if os.IsNotExist(err) {
_, err := os.Stat(c.preparedPath())
if err == nil {
c.isPrepared = true
} else if os.IsNotExist(err) {
_, err := os.Stat(c.runPath())
if err == nil {
// treat as exited until lock is tested
c.isExited = true
} else if os.IsNotExist(err) {
_, err := os.Stat(c.exitedGarbagePath())
if os.IsNotExist(err) {
_, err := os.Stat(c.garbagePath())
if os.IsNotExist(err) {
// XXX: note this is unique to refreshState(), getContainer() errors when it can't find a uuid.
c.isGone = true
} else if err == nil {
c.isGarbage = true
}
} else if err == nil {
c.isExitedGarbage = true
c.isExited = true // exitedGarbage is _always_ implicitly exited
}
}
}
}
c.isExited = true
}
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("error refreshing state of container %q: %v", c.uuid.String(), err)
}
if !c.isPrepared && !c.isEmbryo && !c.isGone {
// preparing, run, and exitedGarbage dirs use exclusive locks to indicate preparing/aborted, running/exited, and deleting/marked
if err = c.TrySharedLock(); err != nil {
if err != lock.ErrLocked {
c.Close()
return fmt.Errorf("unexpected lock error: %v", err)
}
if c.isExitedGarbage {
// locked exitedGarbage is also being deleted
c.isExitedDeleting = true
} else if c.isExited {
// locked exited and !exitedGarbage is not exited (default in the run dir)
c.isExited = false
} else if c.isAbortedPrepare {
// locked in preparing is preparing, not aborted (default in the preparing dir)
c.isAbortedPrepare = false
c.isPreparing = true
} else if c.isGarbage {
// locked in non-exited garbage is deleting
c.isDeleting = true
}
err = nil
} else {
c.Unlock()
}
}
return nil
}
// readFile reads an entire file from a container's directory
// waitExited waits for a container to (run and) exit.
func (c *container) waitExited() error {
for !c.isExited && !c.isAbortedPrepare && !c.isGarbage && !c.isGone {
if err := c.SharedLock(); err != nil {
return err
}
if err := c.Unlock(); err != nil {
return err
}
if err := c.refreshState(); err != nil {
return err
}
// if we're in the gap between preparing and running in a split prepare/run-prepared usage, take a nap
if c.isPrepared {
time.Sleep(time.Second)
}
}
// TODO(vc): return error or let caller detect the !c.isExited possibilities?
return nil
}
// readFile reads an entire file from a container's directory.
func (c *container) readFile(path string) ([]byte, error) {
f, err := c.openFile(path, syscall.O_RDONLY)
if err != nil {
@@ -229,7 +609,7 @@ func (c *container) readFile(path string) ([]byte, error) {
return ioutil.ReadAll(f)
}
// readIntFromFile reads an int from a file in a container's directory
// readIntFromFile reads an int from a file in a container's directory.
func (c *container) readIntFromFile(path string) (i int, err error) {
b, err := c.readFile(path)
if err != nil {
@@ -239,7 +619,7 @@ func (c *container) readIntFromFile(path string) (i int, err error) {
return
}
// openFile opens a file from a container's directory returning a file descriptor
// openFile opens a file from a container's directory returning a file descriptor.
func (c *container) openFile(path string, flags int) (*os.File, error) {
cdirfd, err := c.Fd()
if err != nil {
@@ -248,19 +628,42 @@ func (c *container) openFile(path string, flags int) (*os.File, error) {
fd, err := syscall.Openat(cdirfd, path, flags, 0)
if err != nil {
return nil, fmt.Errorf("unable to open status directory: %v", err)
return nil, fmt.Errorf("unable to open file: %v", err)
}
return os.NewFile(uintptr(fd), path), nil
}
// getPID returns the pid of the container
// getState returns the current state of the container
func (c *container) getState() string {
state := "running"
if c.isEmbryo {
state = "embryo"
} else if c.isPreparing {
state = "preparing"
} else if c.isAbortedPrepare {
state = "aborted prepare"
} else if c.isPrepared {
state = "prepared"
} else if c.isExitedDeleting || c.isDeleting {
state = "deleting"
} else if c.isExited { // this covers c.isExitedGarbage
state = "exited"
} else if c.isGarbage {
state = "garbage"
}
return state
}
// getPID returns the pid of the container.
func (c *container) getPID() (int, error) {
return c.readIntFromFile("pid")
}
// getStatuses returns a map of the statuses of the container
func (c *container) getStatuses() (map[string]int, error) {
// getExitStatuses returns a map of the statuses of the container.
func (c *container) getExitStatuses() (map[string]int, error) {
sdir, err := c.openFile(statusDir, syscall.O_RDONLY|syscall.O_DIRECTORY)
if err != nil {
return nil, fmt.Errorf("unable to open status directory: %v", err)
+10 -30
View File
@@ -94,24 +94,7 @@ func TestWalkContainers(t *testing.T) {
expected: true,
},
},
{ // faked rename race, same uuid as both garbage and non-garbage, only expect the garbage
{ // exited
uuid: "f2f2f2f2-f2f2-f2f2-f2f2-f2f2f2f2f2f2",
exited: true,
garbage: false,
deleting: false,
expected: false,
},
{ // garbage
uuid: "f2f2f2f2-f2f2-f2f2-f2f2-f2f2f2f2f2f2",
exited: true,
garbage: true,
deleting: false,
expected: true,
},
},
// TODO(vc): update to test new prepared/prepare-failed/non-exited-garbage states..
}
for _, tt := range tests {
@@ -123,11 +106,8 @@ func TestWalkContainers(t *testing.T) {
defer os.RemoveAll(d)
globalFlags.Dir = d
if err := os.MkdirAll(containersDir(), 0700); err != nil {
t.Fatalf("error creating container directory: %v", err)
}
if err := os.MkdirAll(garbageDir(), 0700); err != nil {
t.Fatalf("error creating garbage directory: %v", err)
if err := initContainers(); err != nil {
t.Fatalf("error initializing containers: %v", err)
}
var (
@@ -141,11 +121,11 @@ func TestWalkContainers(t *testing.T) {
for _, ct := range tt {
var cp string
if ct.garbage {
cp = filepath.Join(garbageDir(), ct.uuid)
included |= includeGarbageDir
cp = filepath.Join(exitedGarbageDir(), ct.uuid)
included |= includeExitedGarbageDir
} else {
cp = filepath.Join(containersDir(), ct.uuid)
included |= includeContainersDir
cp = filepath.Join(runDir(), ct.uuid)
included |= includeRunDir
}
if err := os.MkdirAll(cp, 0700); err != nil {
@@ -169,10 +149,10 @@ func TestWalkContainers(t *testing.T) {
if err := walkContainers(included, func(ch *container) {
n_walked++
for _, ct := range tt {
if ch.uuid == ct.uuid &&
ch.isGarbage == ct.garbage &&
if ch.uuid.String() == ct.uuid &&
ch.isExitedGarbage == ct.garbage &&
ch.isExited == ct.exited &&
ch.isDeleting == ct.deleting {
ch.isExitedDeleting == ct.deleting {
ct.n_matched++
if ct.n_matched > 1 {
+2 -2
View File
@@ -70,8 +70,8 @@ func runEnter(args []string) (exit int) {
}
defer c.Close()
if c.isExited {
stderr("Cannot enter exited container")
if !c.isRunning() {
stderr("Container %q isn't currently running", cid)
return 1
}
+51 -13
View File
@@ -42,18 +42,24 @@ func init() {
}
func runGC(args []string) (exit int) {
if err := os.MkdirAll(garbageDir(), 0755); err != nil {
stderr("Unable to create garbage dir: %v", err)
return 1
}
if err := renameExited(); err != nil {
stderr("Failed to rename exited containers: %v", err)
return 1
}
// clean up anything old in the garbage dir
if err := emptyGarbage(flagGracePeriod); err != nil {
if err := renameAborted(); err != nil {
stderr("Failed to rename aborted containers: %v", err)
return 1
}
// TODO(vc): rename abandoned successfully prepared containers to garbageDir() after a grace period
if err := emptyExitedGarbage(flagGracePeriod); err != nil {
stderr("Failed to empty exitedGarbage: %v", err)
return 1
}
if err := emptyGarbage(); err != nil {
stderr("Failed to empty garbage: %v", err)
return 1
}
@@ -61,12 +67,12 @@ func runGC(args []string) (exit int) {
return
}
// renameExited renames exited containers to the garbage directory
// renameExited renames exited containers to the exitedGarbage directory
func renameExited() error {
if err := walkContainers(includeContainersDir, func(c *container) {
if err := walkContainers(includeRunDir, func(c *container) {
if c.isExited {
stdout("Moving container %q to garbage", c.uuid)
if err := os.Rename(c.containersPath(), c.garbagePath()); err != nil && err != os.ErrNotExist {
if err := c.xToExitedGarbage(); err != nil && err != os.ErrNotExist {
stderr("Rename error: %v", err)
}
}
@@ -77,9 +83,9 @@ func renameExited() error {
return nil
}
// emptyGarbage discards sufficiently aged containers from garbageDir()
func emptyGarbage(gracePeriod time.Duration) error {
if err := walkContainers(includeGarbageDir, func(c *container) {
// emptyExitedGarbage discards sufficiently aged containers from exitedGarbageDir()
func emptyExitedGarbage(gracePeriod time.Duration) error {
if err := walkContainers(includeExitedGarbageDir, func(c *container) {
gp := c.path()
st := &syscall.Stat_t{}
if err := syscall.Lstat(gp, st); err != nil {
@@ -104,3 +110,35 @@ func emptyGarbage(gracePeriod time.Duration) error {
return nil
}
// renameAborted renames failed prepares to the garbage directory
func renameAborted() error {
if err := walkContainers(includePrepareDir, func(c *container) {
if c.isAbortedPrepare {
stdout("Moving failed prepare %q to garbage", c.uuid)
if err := c.xToGarbage(); err != nil && err != os.ErrNotExist {
stderr("Rename error: %v", err)
}
}
}); err != nil {
return err
}
return nil
}
// emptyGarbage discards everything from garbageDir()
func emptyGarbage() error {
if err := walkContainers(includeGarbageDir, func(c *container) {
if err := c.ExclusiveLock(); err != nil {
return
}
stdout("Garbage collecting container %q", c.uuid)
if err := os.RemoveAll(c.path()); err != nil {
stderr("Unable to remove container %q: %v", c.uuid, err)
}
}); err != nil {
return err
}
return nil
}
+23 -24
View File
@@ -43,33 +43,32 @@ func runList(args []string) (exit int) {
fmt.Fprintf(tabOut, "UUID\tACI\tSTATE\n")
}
if err := walkContainers(includeContainersDir|includeGarbageDir, func(c *container) {
manifFile, err := c.readFile(common.ContainerManifestPath(""))
if err != nil {
stderr("Unable to read manifest: %v", err)
return
}
if err := walkContainers(includeMostDirs, func(c *container) {
m := schema.ContainerRuntimeManifest{}
err = m.UnmarshalJSON(manifFile)
if err != nil {
stderr("Unable to load manifest: %v", err)
return
app_zero := ""
if !c.isPreparing && !c.isAbortedPrepare && !c.isExitedDeleting {
// TODO(vc): we should really hold a shared lock here to prevent gc of the container
manifFile, err := c.readFile(common.ContainerManifestPath(""))
if err != nil {
stderr("Unable to read manifest: %v", err)
return
}
err = m.UnmarshalJSON(manifFile)
if err != nil {
stderr("Unable to load manifest: %v", err)
return
}
if len(m.Apps) == 0 {
stderr("Container contains zero apps")
return
}
app_zero = m.Apps[0].Name.String()
}
if len(m.Apps) == 0 {
stderr("Container contains zero apps")
return
}
state := "active"
if c.isDeleting {
state = "deleting"
} else if c.isExited {
state = "inactive"
}
fmt.Fprintf(tabOut, "%s\t%s\t%s\n", c.uuid, m.Apps[0].Name.String(), state)
fmt.Fprintf(tabOut, "%s\t%s\t%s\n", c.uuid, app_zero, c.getState())
for i := 1; i < len(m.Apps); i++ {
fmt.Fprintf(tabOut, "\t%s\n", m.Apps[i].Name.String())
}
+119
View File
@@ -0,0 +1,119 @@
// Copyright 2015 CoreOS, Inc.
//
// 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.
//+build linux
package main
import (
"io/ioutil"
"log"
"os"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
"github.com/coreos/rocket/cas"
"github.com/coreos/rocket/stage0"
)
var (
cmdPrepare = &Command{
Name: "prepare",
Summary: "Prepare to run image(s) in an application container in rocket",
Usage: "[--volume name,type=host...] [--quiet] IMAGE...",
Description: `Image should be a string referencing an image; either a hash, local file on disk, or URL.
They will be checked in that order and the first match will be used.`,
Run: runPrepare,
}
flagQuiet bool
)
func init() {
commands = append(commands, cmdPrepare)
cmdPrepare.Flags.StringVar(&flagStage1Image, "stage1-image", defaultStage1Image, `image to use as stage1. Local paths and http/https URLs are supported. If empty, Rocket will look for a file called "stage1.aci" in the same directory as rkt itself`)
cmdPrepare.Flags.Var(&flagVolumes, "volume", "volumes to mount into the shared container environment")
cmdPrepare.Flags.BoolVar(&flagQuiet, "quiet", false, "suppress superfluous output on stdout, print only the UUID on success")
}
func runPrepare(args []string) (exit int) {
var err error
origStdout := os.Stdout
if flagQuiet {
if os.Stdout, err = os.Open("/dev/null"); err != nil {
stderr("prepare: unable to open /dev/null")
return 1
}
}
if len(args) < 1 {
stderr("prepare: Must provide at least one image")
return 1
}
if globalFlags.Dir == "" {
log.Printf("dir unset - using temporary directory")
globalFlags.Dir, err = ioutil.TempDir("", "rkt")
if err != nil {
stderr("prepare: error creating temporary directory: %v", err)
return 1
}
}
ds, err := cas.NewStore(globalFlags.Dir)
if err != nil {
stderr("prepare: cannot open store: %v")
return 1
}
ks := getKeystore()
s1img, err := findImage(flagStage1Image, ds, ks, false)
if err != nil {
stderr("prepare: finding stage1 image %q: %v", flagStage1Image, err)
return 1
}
imgs, err := findImages(args, ds, ks)
if err != nil {
stderr("%v", err)
return 1
}
c, err := newContainer()
if err != nil {
stderr("prepare: error creating new container: %v", err)
return 1
}
pcfg := stage0.PrepareConfig{
CommonConfig: stage0.CommonConfig{
Store: ds,
Debug: globalFlags.Debug,
},
Stage1Image: *s1img,
Images: imgs,
Volumes: []types.Volume(flagVolumes),
}
if err = stage0.Prepare(pcfg, c.path(), c.uuid); err != nil {
stderr("prepare: error setting up stage0: %v", err)
return 1
}
if err := c.xToPrepared(); err != nil {
stderr("prepare: error transitioning to prepared: %v", err)
return 1
}
os.Stdout = origStdout // restore output in case of --quiet
stdout("%s", c.uuid.String())
return 1
}
+25 -3
View File
@@ -125,12 +125,34 @@ func getFlags(flagset *flag.FlagSet) (flags []*flag.Flag) {
return
}
func containersDir() string {
return filepath.Join(globalFlags.Dir, "containers")
// where container directories are created and locked before moving to prepared
func embryoDir() string {
return filepath.Join(globalFlags.Dir, "containers", "embryo")
}
// where container trees reside during (locked) and after failing to complete preparation (unlocked)
func prepareDir() string {
return filepath.Join(globalFlags.Dir, "containers", "prepare")
}
// where container trees reside upon successful preparation
func preparedDir() string {
return filepath.Join(globalFlags.Dir, "containers", "prepared")
}
// where container trees reside once run
func runDir() string {
return filepath.Join(globalFlags.Dir, "containers", "run")
}
// where container trees reside once exited & marked as garbage by a gc pass
func exitedGarbageDir() string {
return filepath.Join(globalFlags.Dir, "containers", "exited-garbage")
}
// where never-executed container trees reside once marked as garbage by a gc pass (failed prepares, expired prepareds)
func garbageDir() string {
return filepath.Join(globalFlags.Dir, "garbage")
return filepath.Join(globalFlags.Dir, "containers", "garbage")
}
func getKeystore() *keystore.Keystore {
+109
View File
@@ -0,0 +1,109 @@
// Copyright 2015 CoreOS, Inc.
//
// 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.
//+build linux
package main
import (
"io/ioutil"
"log"
//"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
"github.com/coreos/rocket/cas"
"github.com/coreos/rocket/stage0"
)
const (
cmdRunPreparedName = "run-prepared"
)
var (
cmdRunPrepared = &Command{
Name: cmdRunPreparedName,
Summary: "Run a prepared application container in rocket",
Usage: "UUID",
Description: "UUID must have been acquired via `rkt prepare`",
Run: runRunPrepared,
}
)
func init() {
commands = append(commands, cmdRunPrepared)
cmdRunPrepared.Flags.BoolVar(&flagPrivateNet, "private-net", false, "give container a private network")
cmdRunPrepared.Flags.BoolVar(&flagSpawnMetadataSvc, "spawn-metadata-svc", false, "launch metadata svc if not running")
}
func runRunPrepared(args []string) (exit int) {
if len(args) != 1 {
printCommandUsageByName(cmdRunPreparedName)
return 1
}
containerUUID, err := resolveUUID(args[0])
if err != nil {
stderr("Unable to resolve UUID: %v", err)
return 1
}
if globalFlags.Dir == "" {
log.Printf("dir unset - using temporary directory")
var err error
globalFlags.Dir, err = ioutil.TempDir("", "rkt")
if err != nil {
stderr("error creating temporary directory: %v", err)
return 1
}
}
ds, err := cas.NewStore(globalFlags.Dir)
if err != nil {
stderr("prepared-run: cannot open store: %v", err)
return 1
}
c, err := getContainer(containerUUID.String())
if err != nil {
stderr("prepared-run: cannot get container: %v", err)
return 1
}
if !c.isPrepared {
stderr("prepared-run: container %q is not prepared", containerUUID.String())
return 1
}
if err := c.xToRun(); err != nil {
stderr("prepared-run: cannot transition to run: %v", err)
return 1
}
lfd, err := c.Fd()
if err != nil {
stderr("prepared-run: unable to get lock fd: %v", err)
return 1
}
rcfg := stage0.RunConfig{
CommonConfig: stage0.CommonConfig{
Store: ds,
Debug: globalFlags.Debug,
},
PrivateNet: flagPrivateNet,
SpawnMetadataSvc: flagSpawnMetadataSvc,
LockFd: lfd,
}
stage0.Run(rcfg, c.path()) // execs, never returns
return 1
}
+40 -12
View File
@@ -144,7 +144,7 @@ func runRun(args []string) (exit int) {
ds, err := cas.NewStore(globalFlags.Dir)
if err != nil {
fmt.Fprintf(os.Stderr, "run: cannot open store: %v\n", err)
stderr("run: cannot open store: %v")
return 1
}
ks := getKeystore()
@@ -161,22 +161,50 @@ func runRun(args []string) (exit int) {
return 1
}
cfg := stage0.Config{
Store: ds,
ContainersDir: containersDir(),
Debug: globalFlags.Debug,
Stage1Image: *s1img,
Images: imgs,
Volumes: []types.Volume(flagVolumes),
PrivateNet: flagPrivateNet,
SpawnMetadataSvc: flagSpawnMetadataSvc,
c, err := newContainer()
if err != nil {
stderr("Error creating new container: %v", err)
return 1
}
cdir, err := stage0.Setup(cfg)
cfg := stage0.CommonConfig{
Store: ds,
Debug: globalFlags.Debug,
}
pcfg := stage0.PrepareConfig{
CommonConfig: cfg,
Stage1Image: *s1img,
Images: imgs,
Volumes: []types.Volume(flagVolumes),
}
err = stage0.Prepare(pcfg, c.path(), c.uuid)
if err != nil {
stderr("run: error setting up stage0: %v", err)
return 1
}
stage0.Run(cfg, cdir) // execs, never returns
// get the lock fd for run
lfd, err := c.Fd()
if err != nil {
stderr("Error getting container lock fd: %v", err)
return 1
}
// skip prepared by jumping directly to run, we own this container
if err := c.xToRun(); err != nil {
stderr("run: unable to transition to run: %v", err)
return 1
}
rcfg := stage0.RunConfig{
CommonConfig: cfg,
PrivateNet: flagPrivateNet,
SpawnMetadataSvc: flagSpawnMetadataSvc,
LockFd: lfd,
}
stage0.Run(rcfg, c.path()) // execs, never returns
return 1
}
+22 -18
View File
@@ -33,7 +33,7 @@ const (
func init() {
commands = append(commands, cmdStatus)
cmdStatus.Flags.BoolVar(&flagWait, "wait", false, "toggle waiting for the container to exit if running")
cmdStatus.Flags.BoolVar(&flagWait, "wait", false, "toggle waiting for the container to exit")
}
func runStatus(args []string) (exit int) {
@@ -48,21 +48,21 @@ func runStatus(args []string) (exit int) {
return 1
}
ch, err := getContainer(containerUUID.String())
c, err := getContainer(containerUUID.String())
if err != nil {
stderr("Unable to get container handle: %v", err)
stderr("Unable to get container: %v", err)
return 1
}
defer ch.Close()
defer c.Close()
if flagWait {
if err := ch.waitExited(); err != nil {
if err := c.waitExited(); err != nil {
stderr("Unable to wait for container: %v", err)
return 1
}
}
if err = printStatus(ch); err != nil {
if err = printStatus(c); err != nil {
stderr("Unable to print status: %v", err)
return 1
}
@@ -71,20 +71,24 @@ func runStatus(args []string) (exit int) {
}
// printStatus prints the container's pid and per-app status codes
func printStatus(ch *container) error {
pid, err := ch.getPID()
if err != nil {
return err
}
func printStatus(c *container) error {
stdout("state=%s", c.getState())
stats, err := ch.getStatuses()
if err != nil {
return err
}
if !c.isEmbryo && !c.isPreparing && !c.isPrepared && !c.isAbortedPrepare && !c.isGarbage && !c.isGone {
pid, err := c.getPID()
if err != nil {
return err
}
stdout("pid=%d\nexited=%t", pid, ch.isExited)
for app, stat := range stats {
stdout("%s=%d", app, stat)
stats, err := c.getExitStatuses()
if err != nil {
return err
}
stdout("pid=%d\nexited=%t", pid, c.isExited)
for app, stat := range stats {
stdout("%s=%d", app, stat)
}
}
return nil
}
+2 -1
View File
@@ -26,7 +26,8 @@ import (
// matchUUID attempts to match the uuid specified as uuid against all containers present.
// An array of matches is returned, which may be empty when nothing matches.
func matchUUID(uuid string) ([]string, error) {
ls, err := listContainers(includeContainersDir | includeGarbageDir)
// TODO(vc): maybe switch this to use the uuidsDir instead (include embryos?)
ls, err := listContainers(includePreparedDir | includeRunDir | includeExitedGarbageDir)
if err != nil {
return nil, err
}
+39 -82
View File
@@ -37,12 +37,10 @@ import (
"path/filepath"
"syscall"
"github.com/coreos/rocket/Godeps/_workspace/src/code.google.com/p/go-uuid/uuid"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
"github.com/coreos/rocket/cas"
"github.com/coreos/rocket/common"
"github.com/coreos/rocket/pkg/lock"
ptar "github.com/coreos/rocket/pkg/tar"
"github.com/coreos/rocket/version"
)
@@ -51,72 +49,68 @@ const (
envLockFd = "RKT_LOCK_FD"
)
type Config struct {
// configuration parameters required by Prepare
type PrepareConfig struct {
CommonConfig
Stage1Image types.Hash // stage1 image containing usable /init and /enter entrypoints
Images []types.Hash // application images
Volumes []types.Volume // list of volumes that rocket can provide to applications
}
// configuration parameters needed by Run
type RunConfig struct {
CommonConfig
// TODO(jonboulle): These images are partially-populated hashes, this should be clarified.
PrivateNet bool // container should have its own network stack
SpawnMetadataSvc bool // launch metadata service
LockFd int // lock file descriptor
}
// configuration shared by both Run and Prepare
type CommonConfig struct {
Store *cas.Store // store containing all of the configured application images
ContainersDir string // root directory for rocket containers
Stage1Image types.Hash // stage1 image containing usable /init and /enter entrypoints
Debug bool
// TODO(jonboulle): These images are partially-populated hashes, this should be clarified.
Images []types.Hash // application images
Volumes []types.Volume // list of volumes that rocket can provide to applications
PrivateNet bool // container should have its own network stack
SpawnMetadataSvc bool // launch metadata service
}
func init() {
log.SetOutput(ioutil.Discard)
}
// Setup sets up a filesystem for a container based on the given config.
// The directory containing the filesystem is returned, and any error encountered.
func Setup(cfg Config) (string, error) {
// Prepare sets up a filesystem for a container based on the given config.
func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error {
if cfg.Debug {
log.SetOutput(os.Stderr)
}
if err := os.MkdirAll(cfg.ContainersDir, 0700); err != nil {
return "", fmt.Errorf("error creating containers directory: %v", err)
}
// Create a unique directory for this container
cuuid, dir, err := makeUniqueContainer(cfg.ContainersDir)
if err != nil {
return "", fmt.Errorf("error creating directory: %v", err)
}
// Set up the container lock
if err := lockDir(dir); err != nil {
return "", err
}
log.Printf("Preparing stage1")
if err := setupStage1Image(cfg, cfg.Stage1Image, dir); err != nil {
return "", fmt.Errorf("error preparing stage1: %v", err)
return fmt.Errorf("error preparing stage1: %v", err)
}
log.Printf("Wrote filesystem to %s\n", dir)
cm := schema.ContainerRuntimeManifest{
ACKind: "ContainerRuntimeManifest",
UUID: *cuuid,
UUID: *uuid, // TODO(vc): later appc spec omits uuid from the crm, this is a temp hack.
Apps: make(schema.AppList, 0),
}
v, err := types.NewSemVer(version.Version)
if err != nil {
return "", fmt.Errorf("error creating version: %v", err)
return fmt.Errorf("error creating version: %v", err)
}
cm.ACVersion = *v
for _, img := range cfg.Images {
am, err := setupAppImage(cfg, img, dir)
if err != nil {
return "", fmt.Errorf("error setting up image %s: %v", img, err)
return fmt.Errorf("error setting up image %s: %v", img, err)
}
if cm.Apps.Get(am.Name) != nil {
return "", fmt.Errorf("error: multiple apps with name %s", am.Name)
return fmt.Errorf("error: multiple apps with name %s", am.Name)
}
if am.App == nil {
return "", fmt.Errorf("error: image %s has no app section", img)
return fmt.Errorf("error: image %s has no app section", img)
}
a := schema.RuntimeApp{
Name: am.Name,
@@ -133,20 +127,24 @@ func Setup(cfg Config) (string, error) {
cdoc, err := json.Marshal(cm)
if err != nil {
return "", fmt.Errorf("error marshalling container manifest: %v", err)
return fmt.Errorf("error marshalling container manifest: %v", err)
}
log.Printf("Writing container manifest")
fn := common.ContainerManifestPath(dir)
if err := ioutil.WriteFile(fn, cdoc, 0700); err != nil {
return "", fmt.Errorf("error writing container manifest: %v", err)
return fmt.Errorf("error writing container manifest: %v", err)
}
return dir, nil
return nil
}
// Run actually runs the container by exec()ing the stage1 init inside
// Run actually runs the prepared container by exec()ing the stage1 init inside
// the container filesystem.
func Run(cfg Config, dir string) {
func Run(cfg RunConfig, dir string) {
if err := os.Setenv(envLockFd, fmt.Sprintf("%v", cfg.LockFd)); err != nil {
log.Fatalf("setting lock fd environment: %v", err)
}
if cfg.SpawnMetadataSvc {
log.Print("Launching metadata svc")
if err := launchMetadataSvc(cfg.Debug); err != nil {
@@ -177,53 +175,12 @@ func Run(cfg Config, dir string) {
}
}
// makeUniqueContainer creates a subdirectory (representing a container)
// within the given parent directory. On success, it returns a UUID
// representing the created container and the full path to the new directory.
// The UUID is guaranteed to be unique within the parent directory.
// The parent directory MUST exist and be writeable.
func makeUniqueContainer(pdir string) (*types.UUID, string, error) {
// Arbitrary limit so we don't spin forever
for i := 0; i <= 100; i++ {
cuuid, err := types.NewUUID(uuid.New())
if err != nil {
// Should never happen
return nil, "", fmt.Errorf("error creating UUID: %v", err)
}
dir := filepath.Join(pdir, cuuid.String())
err = os.Mkdir(dir, 0700)
switch {
case err == nil:
return cuuid, dir, nil
case os.IsExist(err):
continue
case err != nil:
return nil, "", err
}
}
return nil, "", fmt.Errorf("couldn't find unique directory!")
}
func lockDir(dir string) error {
l, err := lock.TryExclusiveLock(dir)
if err != nil {
return fmt.Errorf("error acquiring lock on dir %q: %v", dir, err)
}
// We need the fd number for stage1 and leave the file open / lock held til process exit
fd, err := l.Fd()
if err != nil {
panic(err)
}
return os.Setenv(envLockFd, fmt.Sprintf("%v", fd))
}
// setupAppImage attempts to load the app image by the given hash from the store,
// verifies that the image matches the hash, and extracts the image into a
// directory in the given dir.
// It returns the ImageManifest that the image contains.
// TODO(jonboulle): tighten up the Hash type here; currently it is partially-populated (i.e. half-length sha512)
func setupAppImage(cfg Config, img types.Hash, cdir string) (*schema.ImageManifest, error) {
func setupAppImage(cfg PrepareConfig, img types.Hash, cdir string) (*schema.ImageManifest, error) {
log.Println("Loading image", img.String())
ad := common.AppImagePath(cdir, img)
@@ -254,7 +211,7 @@ func setupAppImage(cfg Config, img types.Hash, cdir string) (*schema.ImageManife
}
// setupStage1Image attempts to expand the image by the given hash as the stage1
func setupStage1Image(cfg Config, img types.Hash, cdir string) error {
func setupStage1Image(cfg PrepareConfig, img types.Hash, cdir string) error {
s1 := common.Stage1ImagePath(cdir)
if err := os.MkdirAll(s1, 0755); err != nil {
return fmt.Errorf("error creating stage1 directory: %v", err)
@@ -267,7 +224,7 @@ func setupStage1Image(cfg Config, img types.Hash, cdir string) error {
// expandImage attempts to load the image by the given hash from the store,
// verifies that the image matches the hash, and extracts the image at the specified destination.
func expandImage(cfg Config, img types.Hash, dest string) error {
func expandImage(cfg PrepareConfig, img types.Hash, dest string) error {
rs, err := cfg.Store.ReadStream(img.String())
if err != nil {
return fmt.Errorf("error reading stream: %v", err)