1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

Merge pull request #4538 from crosbymichael/move-runtime

Move runtime into sub package
This commit is contained in:
unclejack 2014-03-10 22:52:32 +02:00
commit 52c258c5cf
25 changed files with 463 additions and 362 deletions

View file

@ -10,6 +10,7 @@ import (
"github.com/dotcloud/docker/auth" "github.com/dotcloud/docker/auth"
"github.com/dotcloud/docker/registry" "github.com/dotcloud/docker/registry"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/runtime"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io" "io"
"io/ioutil" "io/ioutil"
@ -34,7 +35,7 @@ type BuildFile interface {
} }
type buildFile struct { type buildFile struct {
runtime *Runtime runtime *runtime.Runtime
srv *Server srv *Server
image string image string
@ -74,9 +75,9 @@ func (b *buildFile) clearTmp(containers map[string]struct{}) {
} }
func (b *buildFile) CmdFrom(name string) error { func (b *buildFile) CmdFrom(name string) error {
image, err := b.runtime.repositories.LookupImage(name) image, err := b.runtime.Repositories().LookupImage(name)
if err != nil { if err != nil {
if b.runtime.graph.IsNotExist(err) { if b.runtime.Graph().IsNotExist(err) {
remote, tag := utils.ParseRepositoryTag(name) remote, tag := utils.ParseRepositoryTag(name)
pullRegistryAuth := b.authConfig pullRegistryAuth := b.authConfig
if len(b.configFile.Configs) > 0 { if len(b.configFile.Configs) > 0 {
@ -96,7 +97,7 @@ func (b *buildFile) CmdFrom(name string) error {
if err := job.Run(); err != nil { if err := job.Run(); err != nil {
return err return err
} }
image, err = b.runtime.repositories.LookupImage(name) image, err = b.runtime.Repositories().LookupImage(name)
if err != nil { if err != nil {
return err return err
} }
@ -110,7 +111,7 @@ func (b *buildFile) CmdFrom(name string) error {
b.config = image.Config b.config = image.Config
} }
if b.config.Env == nil || len(b.config.Env) == 0 { if b.config.Env == nil || len(b.config.Env) == 0 {
b.config.Env = append(b.config.Env, "HOME=/", "PATH="+defaultPathEnv) b.config.Env = append(b.config.Env, "HOME=/", "PATH="+runtime.DefaultPathEnv)
} }
// Process ONBUILD triggers if they exist // Process ONBUILD triggers if they exist
if nTriggers := len(b.config.OnBuild); nTriggers != 0 { if nTriggers := len(b.config.OnBuild); nTriggers != 0 {
@ -371,7 +372,7 @@ func (b *buildFile) checkPathForAddition(orig string) error {
return nil return nil
} }
func (b *buildFile) addContext(container *Container, orig, dest string, remote bool) error { func (b *buildFile) addContext(container *runtime.Container, orig, dest string, remote bool) error {
var ( var (
origPath = path.Join(b.contextPath, orig) origPath = path.Join(b.contextPath, orig)
destPath = path.Join(container.BasefsPath(), dest) destPath = path.Join(container.BasefsPath(), dest)
@ -604,7 +605,7 @@ func (sf *StderrFormater) Write(buf []byte) (int, error) {
return len(buf), err return len(buf), err
} }
func (b *buildFile) create() (*Container, error) { func (b *buildFile) create() (*runtime.Container, error) {
if b.image == "" { if b.image == "" {
return nil, fmt.Errorf("Please provide a source image with `from` prior to run") return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
} }
@ -625,7 +626,7 @@ func (b *buildFile) create() (*Container, error) {
return c, nil return c, nil
} }
func (b *buildFile) run(c *Container) error { func (b *buildFile) run(c *runtime.Container) error {
var errCh chan error var errCh chan error
if b.verbose { if b.verbose {

View file

@ -1,4 +1,4 @@
package docker package daemonconfig
import ( import (
"net" "net"
@ -13,7 +13,7 @@ const (
) )
// FIXME: separate runtime configuration from http api configuration // FIXME: separate runtime configuration from http api configuration
type DaemonConfig struct { type Config struct {
Pidfile string Pidfile string
Root string Root string
AutoRestart bool AutoRestart bool
@ -32,8 +32,8 @@ type DaemonConfig struct {
// ConfigFromJob creates and returns a new DaemonConfig object // ConfigFromJob creates and returns a new DaemonConfig object
// by parsing the contents of a job's environment. // by parsing the contents of a job's environment.
func DaemonConfigFromJob(job *engine.Job) *DaemonConfig { func ConfigFromJob(job *engine.Job) *Config {
config := &DaemonConfig{ config := &Config{
Pidfile: job.Getenv("Pidfile"), Pidfile: job.Getenv("Pidfile"),
Root: job.Getenv("Root"), Root: job.Getenv("Root"),
AutoRestart: job.GetenvBool("AutoRestart"), AutoRestart: job.GetenvBool("AutoRestart"),

View file

@ -1,10 +1,11 @@
package docker package graph
import ( import (
"fmt" "fmt"
"github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/dockerversion" "github.com/dotcloud/docker/dockerversion"
"github.com/dotcloud/docker/graphdriver" "github.com/dotcloud/docker/graphdriver"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io" "io"
@ -79,20 +80,20 @@ func (graph *Graph) Exists(id string) bool {
} }
// Get returns the image with the given id, or an error if the image doesn't exist. // Get returns the image with the given id, or an error if the image doesn't exist.
func (graph *Graph) Get(name string) (*Image, error) { func (graph *Graph) Get(name string) (*image.Image, error) {
id, err := graph.idIndex.Get(name) id, err := graph.idIndex.Get(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// FIXME: return nil when the image doesn't exist, instead of an error // FIXME: return nil when the image doesn't exist, instead of an error
img, err := LoadImage(graph.imageRoot(id)) img, err := image.LoadImage(graph.ImageRoot(id))
if err != nil { if err != nil {
return nil, err return nil, err
} }
if img.ID != id { if img.ID != id {
return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.ID) return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.ID)
} }
img.graph = graph img.SetGraph(graph)
if img.Size < 0 { if img.Size < 0 {
rootfs, err := graph.driver.Get(img.ID) rootfs, err := graph.driver.Get(img.ID)
@ -119,7 +120,7 @@ func (graph *Graph) Get(name string) (*Image, error) {
} }
img.Size = size img.Size = size
if err := img.SaveSize(graph.imageRoot(id)); err != nil { if err := img.SaveSize(graph.ImageRoot(id)); err != nil {
return nil, err return nil, err
} }
} }
@ -127,9 +128,9 @@ func (graph *Graph) Get(name string) (*Image, error) {
} }
// Create creates a new image and registers it in the graph. // Create creates a new image and registers it in the graph.
func (graph *Graph) Create(layerData archive.ArchiveReader, container *Container, comment, author string, config *runconfig.Config) (*Image, error) { func (graph *Graph) Create(layerData archive.ArchiveReader, containerID, containerImage, comment, author string, containerConfig, config *runconfig.Config) (*image.Image, error) {
img := &Image{ img := &image.Image{
ID: GenerateID(), ID: utils.GenerateRandomID(),
Comment: comment, Comment: comment,
Created: time.Now().UTC(), Created: time.Now().UTC(),
DockerVersion: dockerversion.VERSION, DockerVersion: dockerversion.VERSION,
@ -138,10 +139,10 @@ func (graph *Graph) Create(layerData archive.ArchiveReader, container *Container
Architecture: runtime.GOARCH, Architecture: runtime.GOARCH,
OS: runtime.GOOS, OS: runtime.GOOS,
} }
if container != nil { if containerID != "" {
img.Parent = container.Image img.Parent = containerImage
img.Container = container.ID img.Container = containerID
img.ContainerConfig = *container.Config img.ContainerConfig = *containerConfig
} }
if err := graph.Register(nil, layerData, img); err != nil { if err := graph.Register(nil, layerData, img); err != nil {
return nil, err return nil, err
@ -151,7 +152,7 @@ func (graph *Graph) Create(layerData archive.ArchiveReader, container *Container
// Register imports a pre-existing image into the graph. // Register imports a pre-existing image into the graph.
// FIXME: pass img as first argument // FIXME: pass img as first argument
func (graph *Graph) Register(jsonData []byte, layerData archive.ArchiveReader, img *Image) (err error) { func (graph *Graph) Register(jsonData []byte, layerData archive.ArchiveReader, img *image.Image) (err error) {
defer func() { defer func() {
// If any error occurs, remove the new dir from the driver. // If any error occurs, remove the new dir from the driver.
// Don't check for errors since the dir might not have been created. // Don't check for errors since the dir might not have been created.
@ -160,7 +161,7 @@ func (graph *Graph) Register(jsonData []byte, layerData archive.ArchiveReader, i
graph.driver.Remove(img.ID) graph.driver.Remove(img.ID)
} }
}() }()
if err := ValidateID(img.ID); err != nil { if err := utils.ValidateID(img.ID); err != nil {
return err return err
} }
// (This is a convenience to save time. Race conditions are taken care of by os.Rename) // (This is a convenience to save time. Race conditions are taken care of by os.Rename)
@ -171,7 +172,7 @@ func (graph *Graph) Register(jsonData []byte, layerData archive.ArchiveReader, i
// Ensure that the image root does not exist on the filesystem // Ensure that the image root does not exist on the filesystem
// when it is not registered in the graph. // when it is not registered in the graph.
// This is common when you switch from one graph driver to another // This is common when you switch from one graph driver to another
if err := os.RemoveAll(graph.imageRoot(img.ID)); err != nil && !os.IsNotExist(err) { if err := os.RemoveAll(graph.ImageRoot(img.ID)); err != nil && !os.IsNotExist(err) {
return err return err
} }
@ -197,12 +198,12 @@ func (graph *Graph) Register(jsonData []byte, layerData archive.ArchiveReader, i
return fmt.Errorf("Driver %s failed to get image rootfs %s: %s", graph.driver, img.ID, err) return fmt.Errorf("Driver %s failed to get image rootfs %s: %s", graph.driver, img.ID, err)
} }
defer graph.driver.Put(img.ID) defer graph.driver.Put(img.ID)
img.graph = graph img.SetGraph(graph)
if err := StoreImage(img, jsonData, layerData, tmp, rootfs); err != nil { if err := image.StoreImage(img, jsonData, layerData, tmp, rootfs); err != nil {
return err return err
} }
// Commit // Commit
if err := os.Rename(tmp, graph.imageRoot(img.ID)); err != nil { if err := os.Rename(tmp, graph.ImageRoot(img.ID)); err != nil {
return err return err
} }
graph.idIndex.Add(img.ID) graph.idIndex.Add(img.ID)
@ -233,7 +234,7 @@ func (graph *Graph) TempLayerArchive(id string, compression archive.Compression,
// Mktemp creates a temporary sub-directory inside the graph's filesystem. // Mktemp creates a temporary sub-directory inside the graph's filesystem.
func (graph *Graph) Mktemp(id string) (string, error) { func (graph *Graph) Mktemp(id string) (string, error) {
dir := path.Join(graph.Root, "_tmp", GenerateID()) dir := path.Join(graph.Root, "_tmp", utils.GenerateRandomID())
if err := os.MkdirAll(dir, 0700); err != nil { if err := os.MkdirAll(dir, 0700); err != nil {
return "", err return "", err
} }
@ -246,7 +247,7 @@ func (graph *Graph) Mktemp(id string) (string, error) {
// //
// This extra layer is used by all containers as the top-most ro layer. It protects // This extra layer is used by all containers as the top-most ro layer. It protects
// the container from unwanted side-effects on the rw layer. // the container from unwanted side-effects on the rw layer.
func setupInitLayer(initLayer string) error { func SetupInitLayer(initLayer string) error {
for pth, typ := range map[string]string{ for pth, typ := range map[string]string{
"/dev/pts": "dir", "/dev/pts": "dir",
"/dev/shm": "dir", "/dev/shm": "dir",
@ -320,7 +321,7 @@ func (graph *Graph) Delete(name string) error {
return err return err
} }
graph.idIndex.Delete(id) graph.idIndex.Delete(id)
err = os.Rename(graph.imageRoot(id), tmp) err = os.Rename(graph.ImageRoot(id), tmp)
if err != nil { if err != nil {
return err return err
} }
@ -331,9 +332,9 @@ func (graph *Graph) Delete(name string) error {
} }
// Map returns a list of all images in the graph, addressable by ID. // Map returns a list of all images in the graph, addressable by ID.
func (graph *Graph) Map() (map[string]*Image, error) { func (graph *Graph) Map() (map[string]*image.Image, error) {
images := make(map[string]*Image) images := make(map[string]*image.Image)
err := graph.walkAll(func(image *Image) { err := graph.walkAll(func(image *image.Image) {
images[image.ID] = image images[image.ID] = image
}) })
if err != nil { if err != nil {
@ -344,7 +345,7 @@ func (graph *Graph) Map() (map[string]*Image, error) {
// walkAll iterates over each image in the graph, and passes it to a handler. // walkAll iterates over each image in the graph, and passes it to a handler.
// The walking order is undetermined. // The walking order is undetermined.
func (graph *Graph) walkAll(handler func(*Image)) error { func (graph *Graph) walkAll(handler func(*image.Image)) error {
files, err := ioutil.ReadDir(graph.Root) files, err := ioutil.ReadDir(graph.Root)
if err != nil { if err != nil {
return err return err
@ -364,17 +365,17 @@ func (graph *Graph) walkAll(handler func(*Image)) error {
// If an image of id ID has 3 children images, then the value for key ID // If an image of id ID has 3 children images, then the value for key ID
// will be a list of 3 images. // will be a list of 3 images.
// If an image has no children, it will not have an entry in the table. // If an image has no children, it will not have an entry in the table.
func (graph *Graph) ByParent() (map[string][]*Image, error) { func (graph *Graph) ByParent() (map[string][]*image.Image, error) {
byParent := make(map[string][]*Image) byParent := make(map[string][]*image.Image)
err := graph.walkAll(func(image *Image) { err := graph.walkAll(func(img *image.Image) {
parent, err := graph.Get(image.Parent) parent, err := graph.Get(img.Parent)
if err != nil { if err != nil {
return return
} }
if children, exists := byParent[parent.ID]; exists { if children, exists := byParent[parent.ID]; exists {
byParent[parent.ID] = append(children, image) byParent[parent.ID] = append(children, img)
} else { } else {
byParent[parent.ID] = []*Image{image} byParent[parent.ID] = []*image.Image{img}
} }
}) })
return byParent, err return byParent, err
@ -382,13 +383,13 @@ func (graph *Graph) ByParent() (map[string][]*Image, error) {
// Heads returns all heads in the graph, keyed by id. // Heads returns all heads in the graph, keyed by id.
// A head is an image which is not the parent of another image in the graph. // A head is an image which is not the parent of another image in the graph.
func (graph *Graph) Heads() (map[string]*Image, error) { func (graph *Graph) Heads() (map[string]*image.Image, error) {
heads := make(map[string]*Image) heads := make(map[string]*image.Image)
byParent, err := graph.ByParent() byParent, err := graph.ByParent()
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = graph.walkAll(func(image *Image) { err = graph.walkAll(func(image *image.Image) {
// If it's not in the byParent lookup table, then // If it's not in the byParent lookup table, then
// it's not a parent -> so it's a head! // it's not a parent -> so it's a head!
if _, exists := byParent[image.ID]; !exists { if _, exists := byParent[image.ID]; !exists {
@ -398,7 +399,7 @@ func (graph *Graph) Heads() (map[string]*Image, error) {
return heads, err return heads, err
} }
func (graph *Graph) imageRoot(id string) string { func (graph *Graph) ImageRoot(id string) string {
return path.Join(graph.Root, id) return path.Join(graph.Root, id)
} }

View file

@ -1,8 +1,9 @@
package docker package graph
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io/ioutil" "io/ioutil"
"os" "os"
@ -65,7 +66,7 @@ func (store *TagStore) Reload() error {
return nil return nil
} }
func (store *TagStore) LookupImage(name string) (*Image, error) { func (store *TagStore) LookupImage(name string) (*image.Image, error) {
// FIXME: standardize on returning nil when the image doesn't exist, and err for everything else // FIXME: standardize on returning nil when the image doesn't exist, and err for everything else
// (so we can pass all errors here) // (so we can pass all errors here)
repos, tag := utils.ParseRepositoryTag(name) repos, tag := utils.ParseRepositoryTag(name)
@ -195,7 +196,7 @@ func (store *TagStore) Get(repoName string) (Repository, error) {
return nil, nil return nil, nil
} }
func (store *TagStore) GetImage(repoName, tagOrID string) (*Image, error) { func (store *TagStore) GetImage(repoName, tagOrID string) (*image.Image, error) {
repo, err := store.Get(repoName) repo, err := store.Get(repoName)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -1,8 +1,13 @@
package docker package graph
import ( import (
"bytes"
"github.com/dotcloud/docker/graphdriver" "github.com/dotcloud/docker/graphdriver"
_ "github.com/dotcloud/docker/graphdriver/vfs" // import the vfs driver so it is used in the tests
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
"io"
"os" "os"
"path" "path"
"testing" "testing"
@ -13,6 +18,23 @@ const (
testImageID = "foo" testImageID = "foo"
) )
func fakeTar() (io.Reader, error) {
content := []byte("Hello world!\n")
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} {
hdr := new(tar.Header)
hdr.Size = int64(len(content))
hdr.Name = name
if err := tw.WriteHeader(hdr); err != nil {
return nil, err
}
tw.Write([]byte(content))
}
tw.Close()
return buf, nil
}
func mkTestTagStore(root string, t *testing.T) *TagStore { func mkTestTagStore(root string, t *testing.T) *TagStore {
driver, err := graphdriver.New(root) driver, err := graphdriver.New(root)
if err != nil { if err != nil {
@ -30,7 +52,7 @@ func mkTestTagStore(root string, t *testing.T) *TagStore {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
img := &Image{ID: testImageID} img := &image.Image{ID: testImageID}
// FIXME: this fails on Darwin with: // FIXME: this fails on Darwin with:
// tags_unit_test.go:36: mkdir /var/folders/7g/b3ydb5gx4t94ndr_cljffbt80000gq/T/docker-test569b-tRunner-075013689/vfs/dir/foo/etc/postgres: permission denied // tags_unit_test.go:36: mkdir /var/folders/7g/b3ydb5gx4t94ndr_cljffbt80000gq/T/docker-test569b-tRunner-075013689/vfs/dir/foo/etc/postgres: permission denied
if err := graph.Register(nil, archive, img); err != nil { if err := graph.Register(nil, archive, img); err != nil {

11
image/graph.go Normal file
View file

@ -0,0 +1,11 @@
package image
import (
"github.com/dotcloud/docker/graphdriver"
)
type Graph interface {
Get(id string) (*Image, error)
ImageRoot(id string) string
Driver() graphdriver.Driver
}

View file

@ -1,20 +1,16 @@
package docker package image
import ( import (
"crypto/rand"
"encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/graphdriver" "github.com/dotcloud/docker/graphdriver"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io"
"io/ioutil" "io/ioutil"
"os" "os"
"path" "path"
"strconv" "strconv"
"strings"
"time" "time"
) )
@ -30,8 +26,9 @@ type Image struct {
Config *runconfig.Config `json:"config,omitempty"` Config *runconfig.Config `json:"config,omitempty"`
Architecture string `json:"architecture,omitempty"` Architecture string `json:"architecture,omitempty"`
OS string `json:"os,omitempty"` OS string `json:"os,omitempty"`
graph *Graph
Size int64 Size int64
graph Graph
} }
func LoadImage(root string) (*Image, error) { func LoadImage(root string) (*Image, error) {
@ -45,7 +42,7 @@ func LoadImage(root string) (*Image, error) {
if err := json.Unmarshal(jsonData, img); err != nil { if err := json.Unmarshal(jsonData, img); err != nil {
return nil, err return nil, err
} }
if err := ValidateID(img.ID); err != nil { if err := utils.ValidateID(img.ID); err != nil {
return nil, err return nil, err
} }
@ -72,7 +69,7 @@ func StoreImage(img *Image, jsonData []byte, layerData archive.ArchiveReader, ro
var ( var (
size int64 size int64
err error err error
driver = img.graph.driver driver = img.graph.Driver()
) )
if err := os.MkdirAll(layer, 0755); err != nil { if err := os.MkdirAll(layer, 0755); err != nil {
return err return err
@ -136,6 +133,10 @@ func StoreImage(img *Image, jsonData []byte, layerData archive.ArchiveReader, ro
return nil return nil
} }
func (img *Image) SetGraph(graph Graph) {
img.graph = graph
}
// SaveSize stores the current `size` value of `img` in the directory `root`. // SaveSize stores the current `size` value of `img` in the directory `root`.
func (img *Image) SaveSize(root string) error { func (img *Image) SaveSize(root string) error {
if err := ioutil.WriteFile(path.Join(root, "layersize"), []byte(strconv.Itoa(int(img.Size))), 0600); err != nil { if err := ioutil.WriteFile(path.Join(root, "layersize"), []byte(strconv.Itoa(int(img.Size))), 0600); err != nil {
@ -153,7 +154,7 @@ func (img *Image) TarLayer() (arch archive.Archive, err error) {
if img.graph == nil { if img.graph == nil {
return nil, fmt.Errorf("Can't load storage driver for unregistered image %s", img.ID) return nil, fmt.Errorf("Can't load storage driver for unregistered image %s", img.ID)
} }
driver := img.graph.driver driver := img.graph.Driver()
if differ, ok := driver.(graphdriver.Differ); ok { if differ, ok := driver.(graphdriver.Differ); ok {
return differ.Diff(img.ID) return differ.Diff(img.ID)
} }
@ -201,33 +202,6 @@ func (img *Image) TarLayer() (arch archive.Archive, err error) {
}), nil }), nil
} }
func ValidateID(id string) error {
if id == "" {
return fmt.Errorf("Image id can't be empty")
}
if strings.Contains(id, ":") {
return fmt.Errorf("Invalid character in image id: ':'")
}
return nil
}
func GenerateID() string {
for {
id := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, id); err != nil {
panic(err) // This shouldn't happen
}
value := hex.EncodeToString(id)
// if we try to parse the truncated for as an int and we don't have
// an error then the value is all numberic and causes issues when
// used as a hostname. ref #3869
if _, err := strconv.Atoi(utils.TruncateID(value)); err == nil {
continue
}
return value
}
}
// Image includes convenience proxy functions to its graph // Image includes convenience proxy functions to its graph
// These functions will return an error if the image is not registered // These functions will return an error if the image is not registered
// (ie. if image.graph == nil) // (ie. if image.graph == nil)
@ -274,16 +248,16 @@ func (img *Image) root() (string, error) {
if img.graph == nil { if img.graph == nil {
return "", fmt.Errorf("Can't lookup root of unregistered image") return "", fmt.Errorf("Can't lookup root of unregistered image")
} }
return img.graph.imageRoot(img.ID), nil return img.graph.ImageRoot(img.ID), nil
} }
func (img *Image) getParentsSize(size int64) int64 { func (img *Image) GetParentsSize(size int64) int64 {
parentImage, err := img.GetParent() parentImage, err := img.GetParent()
if err != nil || parentImage == nil { if err != nil || parentImage == nil {
return size return size
} }
size += parentImage.Size size += parentImage.Size
return parentImage.getParentsSize(size) return parentImage.GetParentsSize(size)
} }
// Depth returns the number of parents for a // Depth returns the number of parents for a

View file

@ -5,11 +5,12 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/dotcloud/docker"
"github.com/dotcloud/docker/api" "github.com/dotcloud/docker/api"
"github.com/dotcloud/docker/dockerversion" "github.com/dotcloud/docker/dockerversion"
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/runtime"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
"io" "io"
@ -287,7 +288,7 @@ func TestGetImagesByName(t *testing.T) {
} }
assertHttpNotError(r, t) assertHttpNotError(r, t)
img := &docker.Image{} img := &image.Image{}
if err := json.Unmarshal(r.Body.Bytes(), img); err != nil { if err := json.Unmarshal(r.Body.Bytes(), img); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -599,7 +600,7 @@ func TestGetContainersByName(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
assertHttpNotError(r, t) assertHttpNotError(r, t)
outContainer := &docker.Container{} outContainer := &runtime.Container{}
if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil { if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -5,6 +5,7 @@ import (
"github.com/dotcloud/docker" "github.com/dotcloud/docker"
"github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io/ioutil" "io/ioutil"
"net" "net"
@ -350,7 +351,7 @@ func TestBuild(t *testing.T) {
} }
} }
func buildImage(context testContextTemplate, t *testing.T, eng *engine.Engine, useCache bool) (*docker.Image, error) { func buildImage(context testContextTemplate, t *testing.T, eng *engine.Engine, useCache bool) (*image.Image, error) {
if eng == nil { if eng == nil {
eng = NewTestEngine(t) eng = NewTestEngine(t)
runtime := mkRuntimeFromEngine(eng, t) runtime := mkRuntimeFromEngine(eng, t)

View file

@ -3,10 +3,11 @@ package docker
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"github.com/dotcloud/docker"
"github.com/dotcloud/docker/api" "github.com/dotcloud/docker/api"
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/pkg/term" "github.com/dotcloud/docker/pkg/term"
"github.com/dotcloud/docker/runtime"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io" "io"
"io/ioutil" "io/ioutil"
@ -35,7 +36,7 @@ func closeWrap(args ...io.Closer) error {
return nil return nil
} }
func setRaw(t *testing.T, c *docker.Container) *term.State { func setRaw(t *testing.T, c *runtime.Container) *term.State {
pty, err := c.GetPtyMaster() pty, err := c.GetPtyMaster()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -47,7 +48,7 @@ func setRaw(t *testing.T, c *docker.Container) *term.State {
return state return state
} }
func unsetRaw(t *testing.T, c *docker.Container, state *term.State) { func unsetRaw(t *testing.T, c *runtime.Container, state *term.State) {
pty, err := c.GetPtyMaster() pty, err := c.GetPtyMaster()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -55,8 +56,8 @@ func unsetRaw(t *testing.T, c *docker.Container, state *term.State) {
term.RestoreTerminal(pty.Fd(), state) term.RestoreTerminal(pty.Fd(), state)
} }
func waitContainerStart(t *testing.T, timeout time.Duration) *docker.Container { func waitContainerStart(t *testing.T, timeout time.Duration) *runtime.Container {
var container *docker.Container var container *runtime.Container
setTimeout(t, "Waiting for the container to be started timed out", timeout, func() { setTimeout(t, "Waiting for the container to be started timed out", timeout, func() {
for { for {
@ -902,7 +903,7 @@ func TestImagesTree(t *testing.T) {
}) })
} }
func buildTestImages(t *testing.T, eng *engine.Engine) *docker.Image { func buildTestImages(t *testing.T, eng *engine.Engine) *image.Image {
var testBuilder = testContextTemplate{ var testBuilder = testContextTemplate{
` `

View file

@ -2,10 +2,11 @@ package docker
import ( import (
"errors" "errors"
"github.com/dotcloud/docker"
"github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/dockerversion" "github.com/dotcloud/docker/dockerversion"
"github.com/dotcloud/docker/graph"
"github.com/dotcloud/docker/graphdriver" "github.com/dotcloud/docker/graphdriver"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io" "io"
"io/ioutil" "io/ioutil"
@ -24,7 +25,7 @@ func TestMount(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
image, err := graph.Create(archive, nil, "Testing", "", nil) image, err := graph.Create(archive, "", "", "Testing", "", nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -67,8 +68,8 @@ func TestInterruptedRegister(t *testing.T) {
graph, _ := tempGraph(t) graph, _ := tempGraph(t)
defer nukeGraph(graph) defer nukeGraph(graph)
badArchive, w := io.Pipe() // Use a pipe reader as a fake archive which never yields data badArchive, w := io.Pipe() // Use a pipe reader as a fake archive which never yields data
image := &docker.Image{ image := &image.Image{
ID: docker.GenerateID(), ID: utils.GenerateRandomID(),
Comment: "testing", Comment: "testing",
Created: time.Now(), Created: time.Now(),
} }
@ -96,18 +97,18 @@ func TestGraphCreate(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
image, err := graph.Create(archive, nil, "Testing", "", nil) img, err := graph.Create(archive, "", "", "Testing", "", nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := docker.ValidateID(image.ID); err != nil { if err := utils.ValidateID(img.ID); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if image.Comment != "Testing" { if img.Comment != "Testing" {
t.Fatalf("Wrong comment: should be '%s', not '%s'", "Testing", image.Comment) t.Fatalf("Wrong comment: should be '%s', not '%s'", "Testing", img.Comment)
} }
if image.DockerVersion != dockerversion.VERSION { if img.DockerVersion != dockerversion.VERSION {
t.Fatalf("Wrong docker_version: should be '%s', not '%s'", dockerversion.VERSION, image.DockerVersion) t.Fatalf("Wrong docker_version: should be '%s', not '%s'", dockerversion.VERSION, img.DockerVersion)
} }
images, err := graph.Map() images, err := graph.Map()
if err != nil { if err != nil {
@ -115,8 +116,8 @@ func TestGraphCreate(t *testing.T) {
} else if l := len(images); l != 1 { } else if l := len(images); l != 1 {
t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l) t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l)
} }
if images[image.ID] == nil { if images[img.ID] == nil {
t.Fatalf("Could not find image with id %s", image.ID) t.Fatalf("Could not find image with id %s", img.ID)
} }
} }
@ -127,8 +128,8 @@ func TestRegister(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
image := &docker.Image{ image := &image.Image{
ID: docker.GenerateID(), ID: utils.GenerateRandomID(),
Comment: "testing", Comment: "testing",
Created: time.Now(), Created: time.Now(),
} }
@ -164,12 +165,12 @@ func TestDeletePrefix(t *testing.T) {
assertNImages(graph, t, 0) assertNImages(graph, t, 0)
} }
func createTestImage(graph *docker.Graph, t *testing.T) *docker.Image { func createTestImage(graph *graph.Graph, t *testing.T) *image.Image {
archive, err := fakeTar() archive, err := fakeTar()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
img, err := graph.Create(archive, nil, "Test image", "", nil) img, err := graph.Create(archive, "", "", "Test image", "", nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -184,7 +185,7 @@ func TestDelete(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
assertNImages(graph, t, 0) assertNImages(graph, t, 0)
img, err := graph.Create(archive, nil, "Bla bla", "", nil) img, err := graph.Create(archive, "", "", "Bla bla", "", nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -199,7 +200,7 @@ func TestDelete(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// Test 2 create (same name) / 1 delete // Test 2 create (same name) / 1 delete
img1, err := graph.Create(archive, nil, "Testing", "", nil) img1, err := graph.Create(archive, "", "", "Testing", "", nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -207,7 +208,7 @@ func TestDelete(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err = graph.Create(archive, nil, "Testing", "", nil); err != nil { if _, err = graph.Create(archive, "", "", "Testing", "", nil, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
assertNImages(graph, t, 2) assertNImages(graph, t, 2)
@ -243,20 +244,20 @@ func TestByParent(t *testing.T) {
graph, _ := tempGraph(t) graph, _ := tempGraph(t)
defer nukeGraph(graph) defer nukeGraph(graph)
parentImage := &docker.Image{ parentImage := &image.Image{
ID: docker.GenerateID(), ID: utils.GenerateRandomID(),
Comment: "parent", Comment: "parent",
Created: time.Now(), Created: time.Now(),
Parent: "", Parent: "",
} }
childImage1 := &docker.Image{ childImage1 := &image.Image{
ID: docker.GenerateID(), ID: utils.GenerateRandomID(),
Comment: "child1", Comment: "child1",
Created: time.Now(), Created: time.Now(),
Parent: parentImage.ID, Parent: parentImage.ID,
} }
childImage2 := &docker.Image{ childImage2 := &image.Image{
ID: docker.GenerateID(), ID: utils.GenerateRandomID(),
Comment: "child2", Comment: "child2",
Created: time.Now(), Created: time.Now(),
Parent: parentImage.ID, Parent: parentImage.ID,
@ -279,7 +280,7 @@ func TestByParent(t *testing.T) {
* HELPER FUNCTIONS * HELPER FUNCTIONS
*/ */
func assertNImages(graph *docker.Graph, t *testing.T, n int) { func assertNImages(graph *graph.Graph, t *testing.T, n int) {
if images, err := graph.Map(); err != nil { if images, err := graph.Map(); err != nil {
t.Fatal(err) t.Fatal(err)
} else if actualN := len(images); actualN != n { } else if actualN := len(images); actualN != n {
@ -287,7 +288,7 @@ func assertNImages(graph *docker.Graph, t *testing.T, n int) {
} }
} }
func tempGraph(t *testing.T) (*docker.Graph, graphdriver.Driver) { func tempGraph(t *testing.T) (*graph.Graph, graphdriver.Driver) {
tmp, err := ioutil.TempDir("", "docker-graph-") tmp, err := ioutil.TempDir("", "docker-graph-")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -296,14 +297,14 @@ func tempGraph(t *testing.T) (*docker.Graph, graphdriver.Driver) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
graph, err := docker.NewGraph(tmp, driver) graph, err := graph.NewGraph(tmp, driver)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
return graph, driver return graph, driver
} }
func nukeGraph(graph *docker.Graph) { func nukeGraph(graph *graph.Graph) {
graph.Driver().Cleanup() graph.Driver().Cleanup()
os.RemoveAll(graph.Root) os.RemoveAll(graph.Root)
} }

View file

@ -3,10 +3,11 @@ package docker
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/dotcloud/docker"
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/nat" "github.com/dotcloud/docker/nat"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/runtime"
"github.com/dotcloud/docker/sysinit" "github.com/dotcloud/docker/sysinit"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io" "io"
@ -15,7 +16,7 @@ import (
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"runtime" goruntime "runtime"
"strconv" "strconv"
"strings" "strings"
"syscall" "syscall"
@ -35,14 +36,14 @@ const (
var ( var (
// FIXME: globalRuntime is deprecated by globalEngine. All tests should be converted. // FIXME: globalRuntime is deprecated by globalEngine. All tests should be converted.
globalRuntime *docker.Runtime globalRuntime *runtime.Runtime
globalEngine *engine.Engine globalEngine *engine.Engine
startFds int startFds int
startGoroutines int startGoroutines int
) )
// FIXME: nuke() is deprecated by Runtime.Nuke() // FIXME: nuke() is deprecated by Runtime.Nuke()
func nuke(runtime *docker.Runtime) error { func nuke(runtime *runtime.Runtime) error {
return runtime.Nuke() return runtime.Nuke()
} }
@ -119,7 +120,7 @@ func init() {
// Create the "global runtime" with a long-running daemon for integration tests // Create the "global runtime" with a long-running daemon for integration tests
spawnGlobalDaemon() spawnGlobalDaemon()
startFds, startGoroutines = utils.GetTotalUsedFds(), runtime.NumGoroutine() startFds, startGoroutines = utils.GetTotalUsedFds(), goruntime.NumGoroutine()
} }
func setupBaseImage() { func setupBaseImage() {
@ -172,7 +173,7 @@ func spawnGlobalDaemon() {
// FIXME: test that ImagePull(json=true) send correct json output // FIXME: test that ImagePull(json=true) send correct json output
func GetTestImage(runtime *docker.Runtime) *docker.Image { func GetTestImage(runtime *runtime.Runtime) *image.Image {
imgs, err := runtime.Graph().Map() imgs, err := runtime.Graph().Map()
if err != nil { if err != nil {
log.Fatalf("Unable to get the test image: %s", err) log.Fatalf("Unable to get the test image: %s", err)
@ -356,7 +357,7 @@ func TestGet(t *testing.T) {
} }
func startEchoServerContainer(t *testing.T, proto string) (*docker.Runtime, *docker.Container, string) { func startEchoServerContainer(t *testing.T, proto string) (*runtime.Runtime, *runtime.Container, string) {
var ( var (
err error err error
id string id string

View file

@ -18,6 +18,7 @@ import (
"github.com/dotcloud/docker/builtins" "github.com/dotcloud/docker/builtins"
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/runtime"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
) )
@ -27,7 +28,7 @@ import (
// Create a temporary runtime suitable for unit testing. // Create a temporary runtime suitable for unit testing.
// Call t.Fatal() at the first error. // Call t.Fatal() at the first error.
func mkRuntime(f utils.Fataler) *docker.Runtime { func mkRuntime(f utils.Fataler) *runtime.Runtime {
eng := newTestEngine(f, false, "") eng := newTestEngine(f, false, "")
return mkRuntimeFromEngine(eng, f) return mkRuntimeFromEngine(eng, f)
// FIXME: // FIXME:
@ -139,7 +140,7 @@ func assertHttpError(r *httptest.ResponseRecorder, t utils.Fataler) {
} }
} }
func getContainer(eng *engine.Engine, id string, t utils.Fataler) *docker.Container { func getContainer(eng *engine.Engine, id string, t utils.Fataler) *runtime.Container {
runtime := mkRuntimeFromEngine(eng, t) runtime := mkRuntimeFromEngine(eng, t)
c := runtime.Get(id) c := runtime.Get(id)
if c == nil { if c == nil {
@ -160,14 +161,14 @@ func mkServerFromEngine(eng *engine.Engine, t utils.Fataler) *docker.Server {
return srv return srv
} }
func mkRuntimeFromEngine(eng *engine.Engine, t utils.Fataler) *docker.Runtime { func mkRuntimeFromEngine(eng *engine.Engine, t utils.Fataler) *runtime.Runtime {
iRuntime := eng.Hack_GetGlobalVar("httpapi.runtime") iRuntime := eng.Hack_GetGlobalVar("httpapi.runtime")
if iRuntime == nil { if iRuntime == nil {
panic("Legacy runtime field not set in engine") panic("Legacy runtime field not set in engine")
} }
runtime, ok := iRuntime.(*docker.Runtime) runtime, ok := iRuntime.(*runtime.Runtime)
if !ok { if !ok {
panic("Legacy runtime field in engine does not cast to *docker.Runtime") panic("Legacy runtime field in engine does not cast to *runtime.Runtime")
} }
return runtime return runtime
} }
@ -249,7 +250,7 @@ func readFile(src string, t *testing.T) (content string) {
// dynamically replaced by the current test image. // dynamically replaced by the current test image.
// The caller is responsible for destroying the container. // The caller is responsible for destroying the container.
// Call t.Fatal() at the first error. // Call t.Fatal() at the first error.
func mkContainer(r *docker.Runtime, args []string, t *testing.T) (*docker.Container, *runconfig.HostConfig, error) { func mkContainer(r *runtime.Runtime, args []string, t *testing.T) (*runtime.Container, *runconfig.HostConfig, error) {
config, hc, _, err := runconfig.Parse(args, nil) config, hc, _, err := runconfig.Parse(args, nil)
defer func() { defer func() {
if err != nil && t != nil { if err != nil && t != nil {
@ -280,7 +281,7 @@ func mkContainer(r *docker.Runtime, args []string, t *testing.T) (*docker.Contai
// and return its standard output as a string. // and return its standard output as a string.
// The image name (eg. the XXX in []string{"-i", "-t", "XXX", "bash"}, is dynamically replaced by the current test image. // The image name (eg. the XXX in []string{"-i", "-t", "XXX", "bash"}, is dynamically replaced by the current test image.
// If t is not nil, call t.Fatal() at the first error. Otherwise return errors normally. // If t is not nil, call t.Fatal() at the first error. Otherwise return errors normally.
func runContainer(eng *engine.Engine, r *docker.Runtime, args []string, t *testing.T) (output string, err error) { func runContainer(eng *engine.Engine, r *runtime.Runtime, args []string, t *testing.T) (output string, err error) {
defer func() { defer func() {
if err != nil && t != nil { if err != nil && t != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -1,4 +1,4 @@
package docker package runtime
import ( import (
"encoding/json" "encoding/json"
@ -8,6 +8,7 @@ import (
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/execdriver" "github.com/dotcloud/docker/execdriver"
"github.com/dotcloud/docker/graphdriver" "github.com/dotcloud/docker/graphdriver"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/links" "github.com/dotcloud/docker/links"
"github.com/dotcloud/docker/nat" "github.com/dotcloud/docker/nat"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
@ -23,7 +24,7 @@ import (
"time" "time"
) )
const defaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
var ( var (
ErrNotATTY = errors.New("The PTY is not a file") ErrNotATTY = errors.New("The PTY is not a file")
@ -173,7 +174,7 @@ func (container *Container) ToDisk() (err error) {
if err != nil { if err != nil {
return return
} }
return container.writeHostConfig() return container.WriteHostConfig()
} }
func (container *Container) readHostConfig() error { func (container *Container) readHostConfig() error {
@ -192,7 +193,7 @@ func (container *Container) readHostConfig() error {
return json.Unmarshal(data, container.hostConfig) return json.Unmarshal(data, container.hostConfig)
} }
func (container *Container) writeHostConfig() (err error) { func (container *Container) WriteHostConfig() (err error) {
data, err := json.Marshal(container.hostConfig) data, err := json.Marshal(container.hostConfig)
if err != nil { if err != nil {
return return
@ -450,7 +451,7 @@ func (container *Container) Start() (err error) {
// Setup environment // Setup environment
env := []string{ env := []string{
"HOME=/", "HOME=/",
"PATH=" + defaultPathEnv, "PATH=" + DefaultPathEnv,
"HOSTNAME=" + container.Config.Hostname, "HOSTNAME=" + container.Config.Hostname,
} }
@ -692,7 +693,7 @@ func (container *Container) allocateNetwork() error {
return err return err
} }
container.Config.PortSpecs = nil container.Config.PortSpecs = nil
if err := container.writeHostConfig(); err != nil { if err := container.WriteHostConfig(); err != nil {
return err return err
} }
} }
@ -750,7 +751,7 @@ func (container *Container) allocateNetwork() error {
} }
bindings[port] = binding bindings[port] = binding
} }
container.writeHostConfig() container.WriteHostConfig()
container.NetworkSettings.Ports = bindings container.NetworkSettings.Ports = bindings
@ -849,7 +850,7 @@ func (container *Container) cleanup() {
} }
} }
func (container *Container) kill(sig int) error { func (container *Container) KillSig(sig int) error {
container.Lock() container.Lock()
defer container.Unlock() defer container.Unlock()
@ -865,7 +866,7 @@ func (container *Container) Kill() error {
} }
// 1. Send SIGKILL // 1. Send SIGKILL
if err := container.kill(9); err != nil { if err := container.KillSig(9); err != nil {
return err return err
} }
@ -890,10 +891,10 @@ func (container *Container) Stop(seconds int) error {
} }
// 1. Send a SIGTERM // 1. Send a SIGTERM
if err := container.kill(15); err != nil { if err := container.KillSig(15); err != nil {
utils.Debugf("Error sending kill SIGTERM: %s", err) utils.Debugf("Error sending kill SIGTERM: %s", err)
log.Print("Failed to send SIGTERM to the process, force killing") log.Print("Failed to send SIGTERM to the process, force killing")
if err := container.kill(9); err != nil { if err := container.KillSig(9); err != nil {
return err return err
} }
} }
@ -992,7 +993,7 @@ func (container *Container) Changes() ([]archive.Change, error) {
return container.runtime.Changes(container) return container.runtime.Changes(container)
} }
func (container *Container) GetImage() (*Image, error) { func (container *Container) GetImage() (*image.Image, error) {
if container.runtime == nil { if container.runtime == nil {
return nil, fmt.Errorf("Can't get image of unregistered container") return nil, fmt.Errorf("Can't get image of unregistered container")
} }
@ -1140,3 +1141,21 @@ func (container *Container) GetPtyMaster() (*os.File, error) {
} }
return ttyConsole.Master(), nil return ttyConsole.Master(), nil
} }
func (container *Container) HostConfig() *runconfig.HostConfig {
return container.hostConfig
}
func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) {
container.hostConfig = hostConfig
}
func (container *Container) DisableLink(name string) {
if container.activeLinks != nil {
if link, exists := container.activeLinks[name]; exists {
link.Disable()
} else {
utils.Debugf("Could not find active link for %s", name)
}
}
}

View file

@ -1,4 +1,4 @@
package docker package runtime
import ( import (
"github.com/dotcloud/docker/nat" "github.com/dotcloud/docker/nat"
@ -132,14 +132,14 @@ func TestParseNetworkOptsUdp(t *testing.T) {
} }
func TestGetFullName(t *testing.T) { func TestGetFullName(t *testing.T) {
name, err := getFullName("testing") name, err := GetFullContainerName("testing")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if name != "/testing" { if name != "/testing" {
t.Fatalf("Expected /testing got %s", name) t.Fatalf("Expected /testing got %s", name)
} }
if _, err := getFullName(""); err == nil { if _, err := GetFullContainerName(""); err == nil {
t.Fatal("Error should not be nil") t.Fatal("Error should not be nil")
} }
} }

View file

@ -1,19 +1,22 @@
package docker package runtime
import ( import (
"container/list" "container/list"
"fmt" "fmt"
"github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/daemonconfig"
"github.com/dotcloud/docker/dockerversion" "github.com/dotcloud/docker/dockerversion"
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/execdriver" "github.com/dotcloud/docker/execdriver"
"github.com/dotcloud/docker/execdriver/lxc" "github.com/dotcloud/docker/execdriver/lxc"
"github.com/dotcloud/docker/execdriver/native" "github.com/dotcloud/docker/execdriver/native"
"github.com/dotcloud/docker/graph"
"github.com/dotcloud/docker/graphdriver" "github.com/dotcloud/docker/graphdriver"
"github.com/dotcloud/docker/graphdriver/aufs" "github.com/dotcloud/docker/graphdriver/aufs"
_ "github.com/dotcloud/docker/graphdriver/btrfs" _ "github.com/dotcloud/docker/graphdriver/btrfs"
_ "github.com/dotcloud/docker/graphdriver/devmapper" _ "github.com/dotcloud/docker/graphdriver/devmapper"
_ "github.com/dotcloud/docker/graphdriver/vfs" _ "github.com/dotcloud/docker/graphdriver/vfs"
"github.com/dotcloud/docker/image"
_ "github.com/dotcloud/docker/networkdriver/lxc" _ "github.com/dotcloud/docker/networkdriver/lxc"
"github.com/dotcloud/docker/networkdriver/portallocator" "github.com/dotcloud/docker/networkdriver/portallocator"
"github.com/dotcloud/docker/pkg/graphdb" "github.com/dotcloud/docker/pkg/graphdb"
@ -37,7 +40,7 @@ import (
const MaxImageDepth = 127 const MaxImageDepth = 127
var ( var (
defaultDns = []string{"8.8.8.8", "8.8.4.4"} DefaultDns = []string{"8.8.8.8", "8.8.4.4"}
validContainerNameChars = `[a-zA-Z0-9_.-]` validContainerNameChars = `[a-zA-Z0-9_.-]`
validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`) validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
) )
@ -46,14 +49,14 @@ type Runtime struct {
repository string repository string
sysInitPath string sysInitPath string
containers *list.List containers *list.List
graph *Graph graph *graph.Graph
repositories *TagStore repositories *graph.TagStore
idIndex *utils.TruncIndex idIndex *utils.TruncIndex
sysInfo *sysinfo.SysInfo sysInfo *sysinfo.SysInfo
volumes *Graph volumes *graph.Graph
srv *Server srv Server
eng *engine.Engine eng *engine.Engine
config *DaemonConfig config *daemonconfig.Config
containerGraph *graphdb.Database containerGraph *graphdb.Database
driver graphdriver.Driver driver graphdriver.Driver
execDriver execdriver.Driver execDriver execdriver.Driver
@ -395,7 +398,7 @@ func (runtime *Runtime) Create(config *runconfig.Config, name string) (*Containe
} }
// Generate id // Generate id
id := GenerateID() id := utils.GenerateRandomID()
if name == "" { if name == "" {
name, err = generateRandomName(runtime) name, err = generateRandomName(runtime)
@ -484,7 +487,7 @@ func (runtime *Runtime) Create(config *runconfig.Config, name string) (*Containe
} }
defer runtime.driver.Put(initID) defer runtime.driver.Put(initID)
if err := setupInitLayer(initPath); err != nil { if err := graph.SetupInitLayer(initPath); err != nil {
return nil, nil, err return nil, nil, err
} }
@ -497,8 +500,7 @@ func (runtime *Runtime) Create(config *runconfig.Config, name string) (*Containe
} }
if len(config.Dns) == 0 && len(runtime.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) { if len(config.Dns) == 0 && len(runtime.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) {
//"WARNING: Docker detected local DNS server on resolv.conf. Using default external servers: %v", defaultDns runtime.config.Dns = DefaultDns
runtime.config.Dns = defaultDns
} }
// If custom dns exists, then create a resolv.conf for the container // If custom dns exists, then create a resolv.conf for the container
@ -538,7 +540,7 @@ func (runtime *Runtime) Create(config *runconfig.Config, name string) (*Containe
// Commit creates a new filesystem image from the current state of a container. // Commit creates a new filesystem image from the current state of a container.
// The image can optionally be tagged into a repository // The image can optionally be tagged into a repository
func (runtime *Runtime) Commit(container *Container, repository, tag, comment, author string, config *runconfig.Config) (*Image, error) { func (runtime *Runtime) Commit(container *Container, repository, tag, comment, author string, config *runconfig.Config) (*image.Image, error) {
// FIXME: freeze the container before copying it to avoid data corruption? // FIXME: freeze the container before copying it to avoid data corruption?
// FIXME: this shouldn't be in commands. // FIXME: this shouldn't be in commands.
if err := container.Mount(); err != nil { if err := container.Mount(); err != nil {
@ -553,7 +555,16 @@ func (runtime *Runtime) Commit(container *Container, repository, tag, comment, a
defer rwTar.Close() defer rwTar.Close()
// Create a new image from the container's base layers + a new layer from container changes // Create a new image from the container's base layers + a new layer from container changes
img, err := runtime.graph.Create(rwTar, container, comment, author, config) var (
containerID, containerImage string
containerConfig *runconfig.Config
)
if container != nil {
containerID = container.ID
containerImage = container.Image
containerConfig = container.Config
}
img, err := runtime.graph.Create(rwTar, containerID, containerImage, comment, author, containerConfig, config)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -566,7 +577,7 @@ func (runtime *Runtime) Commit(container *Container, repository, tag, comment, a
return img, nil return img, nil
} }
func getFullName(name string) (string, error) { func GetFullContainerName(name string) (string, error) {
if name == "" { if name == "" {
return "", fmt.Errorf("Container name cannot be empty") return "", fmt.Errorf("Container name cannot be empty")
} }
@ -577,7 +588,7 @@ func getFullName(name string) (string, error) {
} }
func (runtime *Runtime) GetByName(name string) (*Container, error) { func (runtime *Runtime) GetByName(name string) (*Container, error) {
fullName, err := getFullName(name) fullName, err := GetFullContainerName(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -593,7 +604,7 @@ func (runtime *Runtime) GetByName(name string) (*Container, error) {
} }
func (runtime *Runtime) Children(name string) (map[string]*Container, error) { func (runtime *Runtime) Children(name string) (map[string]*Container, error) {
name, err := getFullName(name) name, err := GetFullContainerName(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -624,7 +635,7 @@ func (runtime *Runtime) RegisterLink(parent, child *Container, alias string) err
} }
// FIXME: harmonize with NewGraph() // FIXME: harmonize with NewGraph()
func NewRuntime(config *DaemonConfig, eng *engine.Engine) (*Runtime, error) { func NewRuntime(config *daemonconfig.Config, eng *engine.Engine) (*Runtime, error) {
runtime, err := NewRuntimeFromDirectory(config, eng) runtime, err := NewRuntimeFromDirectory(config, eng)
if err != nil { if err != nil {
return nil, err return nil, err
@ -632,7 +643,7 @@ func NewRuntime(config *DaemonConfig, eng *engine.Engine) (*Runtime, error) {
return runtime, nil return runtime, nil
} }
func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime, error) { func NewRuntimeFromDirectory(config *daemonconfig.Config, eng *engine.Engine) (*Runtime, error) {
// Set the default driver // Set the default driver
graphdriver.DefaultDriver = config.GraphDriver graphdriver.DefaultDriver = config.GraphDriver
@ -652,13 +663,13 @@ func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime
if ad, ok := driver.(*aufs.Driver); ok { if ad, ok := driver.(*aufs.Driver); ok {
utils.Debugf("Migrating existing containers") utils.Debugf("Migrating existing containers")
if err := ad.Migrate(config.Root, setupInitLayer); err != nil { if err := ad.Migrate(config.Root, graph.SetupInitLayer); err != nil {
return nil, err return nil, err
} }
} }
utils.Debugf("Creating images graph") utils.Debugf("Creating images graph")
g, err := NewGraph(path.Join(config.Root, "graph"), driver) g, err := graph.NewGraph(path.Join(config.Root, "graph"), driver)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -670,12 +681,12 @@ func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime
return nil, err return nil, err
} }
utils.Debugf("Creating volumes graph") utils.Debugf("Creating volumes graph")
volumes, err := NewGraph(path.Join(config.Root, "volumes"), volumesDriver) volumes, err := graph.NewGraph(path.Join(config.Root, "volumes"), volumesDriver)
if err != nil { if err != nil {
return nil, err return nil, err
} }
utils.Debugf("Creating repository list") utils.Debugf("Creating repository list")
repositories, err := NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g) repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g)
if err != nil { if err != nil {
return nil, fmt.Errorf("Couldn't create Tag store: %s", err) return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
} }
@ -876,10 +887,46 @@ func (runtime *Runtime) Nuke() error {
// which need direct access to runtime.graph. // which need direct access to runtime.graph.
// Once the tests switch to using engine and jobs, this method // Once the tests switch to using engine and jobs, this method
// can go away. // can go away.
func (runtime *Runtime) Graph() *Graph { func (runtime *Runtime) Graph() *graph.Graph {
return runtime.graph return runtime.graph
} }
func (runtime *Runtime) Repositories() *graph.TagStore {
return runtime.repositories
}
func (runtime *Runtime) Config() *daemonconfig.Config {
return runtime.config
}
func (runtime *Runtime) SystemConfig() *sysinfo.SysInfo {
return runtime.sysInfo
}
func (runtime *Runtime) SystemInitPath() string {
return runtime.sysInitPath
}
func (runtime *Runtime) GraphDriver() graphdriver.Driver {
return runtime.driver
}
func (runtime *Runtime) ExecutionDriver() execdriver.Driver {
return runtime.execDriver
}
func (runtime *Runtime) Volumes() *graph.Graph {
return runtime.volumes
}
func (runtime *Runtime) ContainerGraph() *graphdb.Database {
return runtime.containerGraph
}
func (runtime *Runtime) SetServer(server Server) {
runtime.srv = server
}
// History is a convenience type for storing a list of containers, // History is a convenience type for storing a list of containers,
// ordered by creation date. // ordered by creation date.
type History []*Container type History []*Container

10
runtime/server.go Normal file
View file

@ -0,0 +1,10 @@
package runtime
import (
"github.com/dotcloud/docker/utils"
)
type Server interface {
LogEvent(action, id, from string) *utils.JSONMessage
IsRunning() bool // returns true if the server is currently in operation
}

View file

@ -1,4 +1,4 @@
package docker package runtime
import "sort" import "sort"

View file

@ -1,4 +1,4 @@
package docker package runtime
import ( import (
"fmt" "fmt"

44
runtime/utils.go Normal file
View file

@ -0,0 +1,44 @@
package runtime
import (
"github.com/dotcloud/docker/nat"
"github.com/dotcloud/docker/pkg/namesgenerator"
"github.com/dotcloud/docker/runconfig"
)
func migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error {
if config.PortSpecs != nil {
ports, bindings, err := nat.ParsePortSpecs(config.PortSpecs)
if err != nil {
return err
}
config.PortSpecs = nil
if len(bindings) > 0 {
if hostConfig == nil {
hostConfig = &runconfig.HostConfig{}
}
hostConfig.PortBindings = bindings
}
if config.ExposedPorts == nil {
config.ExposedPorts = make(nat.PortSet, len(ports))
}
for k, v := range ports {
config.ExposedPorts[k] = v
}
}
return nil
}
type checker struct {
runtime *Runtime
}
func (c *checker) Exists(name string) bool {
return c.runtime.containerGraph.Exists("/" + name)
}
// Generate a random and unique name
func generateRandomName(runtime *Runtime) (string, error) {
return namesgenerator.GenerateRandomName(&checker{runtime})
}

View file

@ -1,4 +1,4 @@
package docker package runtime
import ( import (
"fmt" "fmt"
@ -216,7 +216,7 @@ func createVolumes(container *Container) error {
return err return err
} }
volumesDriver := container.runtime.volumes.driver volumesDriver := container.runtime.volumes.Driver()
// Create the requested volumes if they don't exist // Create the requested volumes if they don't exist
for volPath := range container.Config.Volumes { for volPath := range container.Config.Volumes {
volPath = filepath.Clean(volPath) volPath = filepath.Clean(volPath)
@ -246,7 +246,7 @@ func createVolumes(container *Container) error {
// Do not pass a container as the parameter for the volume creation. // Do not pass a container as the parameter for the volume creation.
// The graph driver using the container's information ( Image ) to // The graph driver using the container's information ( Image ) to
// create the parent. // create the parent.
c, err := container.runtime.volumes.Create(nil, nil, "", "", nil) c, err := container.runtime.volumes.Create(nil, "", "", "", "", nil, nil)
if err != nil { if err != nil {
return err return err
} }

222
server.go
View file

@ -5,11 +5,15 @@ import (
"fmt" "fmt"
"github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/auth" "github.com/dotcloud/docker/auth"
"github.com/dotcloud/docker/daemonconfig"
"github.com/dotcloud/docker/dockerversion" "github.com/dotcloud/docker/dockerversion"
"github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/graph"
"github.com/dotcloud/docker/image"
"github.com/dotcloud/docker/pkg/graphdb" "github.com/dotcloud/docker/pkg/graphdb"
"github.com/dotcloud/docker/registry" "github.com/dotcloud/docker/registry"
"github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/runtime"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
"io" "io"
"io/ioutil" "io/ioutil"
@ -21,7 +25,7 @@ import (
"os/signal" "os/signal"
"path" "path"
"path/filepath" "path/filepath"
"runtime" goruntime "runtime"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -34,13 +38,13 @@ import (
// The signals SIGINT, SIGQUIT and SIGTERM are intercepted for cleanup. // The signals SIGINT, SIGQUIT and SIGTERM are intercepted for cleanup.
func InitServer(job *engine.Job) engine.Status { func InitServer(job *engine.Job) engine.Status {
job.Logf("Creating server") job.Logf("Creating server")
srv, err := NewServer(job.Eng, DaemonConfigFromJob(job)) srv, err := NewServer(job.Eng, daemonconfig.ConfigFromJob(job))
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
if srv.runtime.config.Pidfile != "" { if srv.runtime.Config().Pidfile != "" {
job.Logf("Creating pidfile") job.Logf("Creating pidfile")
if err := utils.CreatePidFile(srv.runtime.config.Pidfile); err != nil { if err := utils.CreatePidFile(srv.runtime.Config().Pidfile); err != nil {
// FIXME: do we need fatal here instead of returning a job error? // FIXME: do we need fatal here instead of returning a job error?
log.Fatal(err) log.Fatal(err)
} }
@ -51,7 +55,7 @@ func InitServer(job *engine.Job) engine.Status {
go func() { go func() {
sig := <-c sig := <-c
log.Printf("Received signal '%v', exiting\n", sig) log.Printf("Received signal '%v', exiting\n", sig)
utils.RemovePidFile(srv.runtime.config.Pidfile) utils.RemovePidFile(srv.runtime.Config().Pidfile)
srv.Close() srv.Close()
os.Exit(0) os.Exit(0)
}() }()
@ -178,10 +182,10 @@ func (srv *Server) ContainerKill(job *engine.Job) engine.Status {
if err := container.Kill(); err != nil { if err := container.Kill(); err != nil {
return job.Errorf("Cannot kill container %s: %s", name, err) return job.Errorf("Cannot kill container %s: %s", name, err)
} }
srv.LogEvent("kill", container.ID, srv.runtime.repositories.ImageName(container.Image)) srv.LogEvent("kill", container.ID, srv.runtime.Repositories().ImageName(container.Image))
} else { } else {
// Otherwise, just send the requested signal // Otherwise, just send the requested signal
if err := container.kill(int(sig)); err != nil { if err := container.KillSig(int(sig)); err != nil {
return job.Errorf("Cannot kill container %s: %s", name, err) return job.Errorf("Cannot kill container %s: %s", name, err)
} }
// FIXME: Add event for signals // FIXME: Add event for signals
@ -290,7 +294,7 @@ func (srv *Server) ContainerExport(job *engine.Job) engine.Status {
return job.Errorf("%s: %s", name, err) return job.Errorf("%s: %s", name, err)
} }
// FIXME: factor job-specific LogEvent to engine.Job.Run() // FIXME: factor job-specific LogEvent to engine.Job.Run()
srv.LogEvent("export", container.ID, srv.runtime.repositories.ImageName(container.Image)) srv.LogEvent("export", container.ID, srv.runtime.Repositories().ImageName(container.Image))
return engine.StatusOK return engine.StatusOK
} }
return job.Errorf("No such container: %s", name) return job.Errorf("No such container: %s", name)
@ -315,7 +319,7 @@ func (srv *Server) ImageExport(job *engine.Job) engine.Status {
utils.Debugf("Serializing %s", name) utils.Debugf("Serializing %s", name)
rootRepo, err := srv.runtime.repositories.Get(name) rootRepo, err := srv.runtime.Repositories().Get(name)
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
@ -332,7 +336,7 @@ func (srv *Server) ImageExport(job *engine.Job) engine.Status {
} }
// write repositories // write repositories
rootRepoMap := map[string]Repository{} rootRepoMap := map[string]graph.Repository{}
rootRepoMap[name] = rootRepo rootRepoMap[name] = rootRepo
rootRepoJson, _ := json.Marshal(rootRepoMap) rootRepoJson, _ := json.Marshal(rootRepoMap)
@ -361,8 +365,8 @@ func (srv *Server) ImageExport(job *engine.Job) engine.Status {
return engine.StatusOK return engine.StatusOK
} }
func (srv *Server) exportImage(image *Image, tempdir string) error { func (srv *Server) exportImage(img *image.Image, tempdir string) error {
for i := image; i != nil; { for i := img; i != nil; {
// temporary directory // temporary directory
tmpImageDir := path.Join(tempdir, i.ID) tmpImageDir := path.Join(tempdir, i.ID)
if err := os.Mkdir(tmpImageDir, os.ModeDir); err != nil { if err := os.Mkdir(tmpImageDir, os.ModeDir); err != nil {
@ -491,7 +495,7 @@ func (srv *Server) Build(job *engine.Job) engine.Status {
return job.Error(err) return job.Error(err)
} }
if repoName != "" { if repoName != "" {
srv.runtime.repositories.Set(repoName, tag, id, false) srv.runtime.Repositories().Set(repoName, tag, id, false)
} }
return engine.StatusOK return engine.StatusOK
} }
@ -545,14 +549,14 @@ func (srv *Server) ImageLoad(job *engine.Job) engine.Status {
repositoriesJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", "repositories")) repositoriesJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", "repositories"))
if err == nil { if err == nil {
repositories := map[string]Repository{} repositories := map[string]graph.Repository{}
if err := json.Unmarshal(repositoriesJson, &repositories); err != nil { if err := json.Unmarshal(repositoriesJson, &repositories); err != nil {
return job.Error(err) return job.Error(err)
} }
for imageName, tagMap := range repositories { for imageName, tagMap := range repositories {
for tag, address := range tagMap { for tag, address := range tagMap {
if err := srv.runtime.repositories.Set(imageName, tag, address, true); err != nil { if err := srv.runtime.Repositories().Set(imageName, tag, address, true); err != nil {
return job.Error(err) return job.Error(err)
} }
} }
@ -579,19 +583,19 @@ func (srv *Server) recursiveLoad(address, tmpImageDir string) error {
utils.Debugf("Error reading embedded tar", err) utils.Debugf("Error reading embedded tar", err)
return err return err
} }
img, err := NewImgJSON(imageJson) img, err := image.NewImgJSON(imageJson)
if err != nil { if err != nil {
utils.Debugf("Error unmarshalling json", err) utils.Debugf("Error unmarshalling json", err)
return err return err
} }
if img.Parent != "" { if img.Parent != "" {
if !srv.runtime.graph.Exists(img.Parent) { if !srv.runtime.Graph().Exists(img.Parent) {
if err := srv.recursiveLoad(img.Parent, tmpImageDir); err != nil { if err := srv.recursiveLoad(img.Parent, tmpImageDir); err != nil {
return err return err
} }
} }
} }
if err := srv.runtime.graph.Register(imageJson, layer, img); err != nil { if err := srv.runtime.Graph().Register(imageJson, layer, img); err != nil {
return err return err
} }
} }
@ -647,7 +651,7 @@ func (srv *Server) ImageInsert(job *engine.Job) engine.Status {
sf := utils.NewStreamFormatter(job.GetenvBool("json")) sf := utils.NewStreamFormatter(job.GetenvBool("json"))
out := utils.NewWriteFlusher(job.Stdout) out := utils.NewWriteFlusher(job.Stdout)
img, err := srv.runtime.repositories.LookupImage(name) img, err := srv.runtime.Repositories().LookupImage(name)
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
@ -658,7 +662,7 @@ func (srv *Server) ImageInsert(job *engine.Job) engine.Status {
} }
defer file.Body.Close() defer file.Body.Close()
config, _, _, err := runconfig.Parse([]string{img.ID, "echo", "insert", url, path}, srv.runtime.sysInfo) config, _, _, err := runconfig.Parse([]string{img.ID, "echo", "insert", url, path}, srv.runtime.SystemConfig())
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
@ -682,14 +686,14 @@ func (srv *Server) ImageInsert(job *engine.Job) engine.Status {
} }
func (srv *Server) ImagesViz(job *engine.Job) engine.Status { func (srv *Server) ImagesViz(job *engine.Job) engine.Status {
images, _ := srv.runtime.graph.Map() images, _ := srv.runtime.Graph().Map()
if images == nil { if images == nil {
return engine.StatusOK return engine.StatusOK
} }
job.Stdout.Write([]byte("digraph docker {\n")) job.Stdout.Write([]byte("digraph docker {\n"))
var ( var (
parentImage *Image parentImage *image.Image
err error err error
) )
for _, image := range images { for _, image := range images {
@ -706,7 +710,7 @@ func (srv *Server) ImagesViz(job *engine.Job) engine.Status {
reporefs := make(map[string][]string) reporefs := make(map[string][]string)
for name, repository := range srv.runtime.repositories.Repositories { for name, repository := range srv.runtime.Repositories().Repositories {
for tag, id := range repository { for tag, id := range repository {
reporefs[utils.TruncateID(id)] = append(reporefs[utils.TruncateID(id)], fmt.Sprintf("%s:%s", name, tag)) reporefs[utils.TruncateID(id)] = append(reporefs[utils.TruncateID(id)], fmt.Sprintf("%s:%s", name, tag))
} }
@ -721,26 +725,26 @@ func (srv *Server) ImagesViz(job *engine.Job) engine.Status {
func (srv *Server) Images(job *engine.Job) engine.Status { func (srv *Server) Images(job *engine.Job) engine.Status {
var ( var (
allImages map[string]*Image allImages map[string]*image.Image
err error err error
) )
if job.GetenvBool("all") { if job.GetenvBool("all") {
allImages, err = srv.runtime.graph.Map() allImages, err = srv.runtime.Graph().Map()
} else { } else {
allImages, err = srv.runtime.graph.Heads() allImages, err = srv.runtime.Graph().Heads()
} }
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
lookup := make(map[string]*engine.Env) lookup := make(map[string]*engine.Env)
for name, repository := range srv.runtime.repositories.Repositories { for name, repository := range srv.runtime.Repositories().Repositories {
if job.Getenv("filter") != "" { if job.Getenv("filter") != "" {
if match, _ := path.Match(job.Getenv("filter"), name); !match { if match, _ := path.Match(job.Getenv("filter"), name); !match {
continue continue
} }
} }
for tag, id := range repository { for tag, id := range repository {
image, err := srv.runtime.graph.Get(id) image, err := srv.runtime.Graph().Get(id)
if err != nil { if err != nil {
log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err) log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
continue continue
@ -756,7 +760,7 @@ func (srv *Server) Images(job *engine.Job) engine.Status {
out.Set("Id", image.ID) out.Set("Id", image.ID)
out.SetInt64("Created", image.Created.Unix()) out.SetInt64("Created", image.Created.Unix())
out.SetInt64("Size", image.Size) out.SetInt64("Size", image.Size)
out.SetInt64("VirtualSize", image.getParentsSize(0)+image.Size) out.SetInt64("VirtualSize", image.GetParentsSize(0)+image.Size)
lookup[id] = out lookup[id] = out
} }
@ -777,7 +781,7 @@ func (srv *Server) Images(job *engine.Job) engine.Status {
out.Set("Id", image.ID) out.Set("Id", image.ID)
out.SetInt64("Created", image.Created.Unix()) out.SetInt64("Created", image.Created.Unix())
out.SetInt64("Size", image.Size) out.SetInt64("Size", image.Size)
out.SetInt64("VirtualSize", image.getParentsSize(0)+image.Size) out.SetInt64("VirtualSize", image.GetParentsSize(0)+image.Size)
outs.Add(out) outs.Add(out)
} }
} }
@ -790,7 +794,7 @@ func (srv *Server) Images(job *engine.Job) engine.Status {
} }
func (srv *Server) DockerInfo(job *engine.Job) engine.Status { func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
images, _ := srv.runtime.graph.Map() images, _ := srv.runtime.Graph().Map()
var imgcount int var imgcount int
if images == nil { if images == nil {
imgcount = 0 imgcount = 0
@ -806,21 +810,21 @@ func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
initPath := utils.DockerInitPath("") initPath := utils.DockerInitPath("")
if initPath == "" { if initPath == "" {
// if that fails, we'll just return the path from the runtime // if that fails, we'll just return the path from the runtime
initPath = srv.runtime.sysInitPath initPath = srv.runtime.SystemInitPath()
} }
v := &engine.Env{} v := &engine.Env{}
v.SetInt("Containers", len(srv.runtime.List())) v.SetInt("Containers", len(srv.runtime.List()))
v.SetInt("Images", imgcount) v.SetInt("Images", imgcount)
v.Set("Driver", srv.runtime.driver.String()) v.Set("Driver", srv.runtime.GraphDriver().String())
v.SetJson("DriverStatus", srv.runtime.driver.Status()) v.SetJson("DriverStatus", srv.runtime.GraphDriver().Status())
v.SetBool("MemoryLimit", srv.runtime.sysInfo.MemoryLimit) v.SetBool("MemoryLimit", srv.runtime.SystemConfig().MemoryLimit)
v.SetBool("SwapLimit", srv.runtime.sysInfo.SwapLimit) v.SetBool("SwapLimit", srv.runtime.SystemConfig().SwapLimit)
v.SetBool("IPv4Forwarding", !srv.runtime.sysInfo.IPv4ForwardingDisabled) v.SetBool("IPv4Forwarding", !srv.runtime.SystemConfig().IPv4ForwardingDisabled)
v.SetBool("Debug", os.Getenv("DEBUG") != "") v.SetBool("Debug", os.Getenv("DEBUG") != "")
v.SetInt("NFd", utils.GetTotalUsedFds()) v.SetInt("NFd", utils.GetTotalUsedFds())
v.SetInt("NGoroutines", runtime.NumGoroutine()) v.SetInt("NGoroutines", goruntime.NumGoroutine())
v.Set("ExecutionDriver", srv.runtime.execDriver.Name()) v.Set("ExecutionDriver", srv.runtime.ExecutionDriver().Name())
v.SetInt("NEventsListener", len(srv.listeners)) v.SetInt("NEventsListener", len(srv.listeners))
v.Set("KernelVersion", kernelVersion) v.Set("KernelVersion", kernelVersion)
v.Set("IndexServerAddress", auth.IndexServerAddress()) v.Set("IndexServerAddress", auth.IndexServerAddress())
@ -837,13 +841,13 @@ func (srv *Server) ImageHistory(job *engine.Job) engine.Status {
return job.Errorf("Usage: %s IMAGE", job.Name) return job.Errorf("Usage: %s IMAGE", job.Name)
} }
name := job.Args[0] name := job.Args[0]
image, err := srv.runtime.repositories.LookupImage(name) foundImage, err := srv.runtime.Repositories().LookupImage(name)
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
lookupMap := make(map[string][]string) lookupMap := make(map[string][]string)
for name, repository := range srv.runtime.repositories.Repositories { for name, repository := range srv.runtime.Repositories().Repositories {
for tag, id := range repository { for tag, id := range repository {
// If the ID already has a reverse lookup, do not update it unless for "latest" // If the ID already has a reverse lookup, do not update it unless for "latest"
if _, exists := lookupMap[id]; !exists { if _, exists := lookupMap[id]; !exists {
@ -854,7 +858,7 @@ func (srv *Server) ImageHistory(job *engine.Job) engine.Status {
} }
outs := engine.NewTable("Created", 0) outs := engine.NewTable("Created", 0)
err = image.WalkHistory(func(img *Image) error { err = foundImage.WalkHistory(func(img *image.Image) error {
out := &engine.Env{} out := &engine.Env{}
out.Set("Id", img.ID) out.Set("Id", img.ID)
out.SetInt64("Created", img.Created.Unix()) out.SetInt64("Created", img.Created.Unix())
@ -888,7 +892,7 @@ func (srv *Server) ContainerTop(job *engine.Job) engine.Status {
if !container.State.IsRunning() { if !container.State.IsRunning() {
return job.Errorf("Container %s is not running", name) return job.Errorf("Container %s is not running", name)
} }
pids, err := srv.runtime.execDriver.GetPidsForContainer(container.ID) pids, err := srv.runtime.ExecutionDriver().GetPidsForContainer(container.ID)
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
@ -981,7 +985,7 @@ func (srv *Server) Containers(job *engine.Job) engine.Status {
outs := engine.NewTable("Created", 0) outs := engine.NewTable("Created", 0)
names := map[string][]string{} names := map[string][]string{}
srv.runtime.containerGraph.Walk("/", func(p string, e *graphdb.Entity) error { srv.runtime.ContainerGraph().Walk("/", func(p string, e *graphdb.Entity) error {
names[e.ID()] = append(names[e.ID()], p) names[e.ID()] = append(names[e.ID()], p)
return nil return nil
}, -1) }, -1)
@ -1006,7 +1010,7 @@ func (srv *Server) Containers(job *engine.Job) engine.Status {
out := &engine.Env{} out := &engine.Env{}
out.Set("Id", container.ID) out.Set("Id", container.ID)
out.SetList("Names", names[container.ID]) out.SetList("Names", names[container.ID])
out.Set("Image", srv.runtime.repositories.ImageName(container.Image)) out.Set("Image", srv.runtime.Repositories().ImageName(container.Image))
if len(container.Args) > 0 { if len(container.Args) > 0 {
out.Set("Command", fmt.Sprintf("\"%s %s\"", container.Path, strings.Join(container.Args, " "))) out.Set("Command", fmt.Sprintf("\"%s %s\"", container.Path, strings.Join(container.Args, " ")))
} else { } else {
@ -1064,7 +1068,7 @@ func (srv *Server) ImageTag(job *engine.Job) engine.Status {
if len(job.Args) == 3 { if len(job.Args) == 3 {
tag = job.Args[2] tag = job.Args[2]
} }
if err := srv.runtime.repositories.Set(job.Args[1], tag, job.Args[0], job.GetenvBool("force")); err != nil { if err := srv.runtime.Repositories().Set(job.Args[1], tag, job.Args[0], job.GetenvBool("force")); err != nil {
return job.Error(err) return job.Error(err)
} }
return engine.StatusOK return engine.StatusOK
@ -1089,7 +1093,7 @@ func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin
} }
defer srv.poolRemove("pull", "layer:"+id) defer srv.poolRemove("pull", "layer:"+id)
if !srv.runtime.graph.Exists(id) { if !srv.runtime.Graph().Exists(id) {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Pulling metadata", nil)) out.Write(sf.FormatProgress(utils.TruncateID(id), "Pulling metadata", nil))
imgJSON, imgSize, err := r.GetRemoteImageJSON(id, endpoint, token) imgJSON, imgSize, err := r.GetRemoteImageJSON(id, endpoint, token)
if err != nil { if err != nil {
@ -1097,7 +1101,7 @@ func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin
// FIXME: Keep going in case of error? // FIXME: Keep going in case of error?
return err return err
} }
img, err := NewImgJSON(imgJSON) img, err := image.NewImgJSON(imgJSON)
if err != nil { if err != nil {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Error pulling dependent layers", nil)) out.Write(sf.FormatProgress(utils.TruncateID(id), "Error pulling dependent layers", nil))
return fmt.Errorf("Failed to parse json: %s", err) return fmt.Errorf("Failed to parse json: %s", err)
@ -1111,7 +1115,7 @@ func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin
return err return err
} }
defer layer.Close() defer layer.Close()
if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf, false, utils.TruncateID(id), "Downloading"), img); err != nil { if err := srv.runtime.Graph().Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf, false, utils.TruncateID(id), "Downloading"), img); err != nil {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Error downloading dependent layers", nil)) out.Write(sf.FormatProgress(utils.TruncateID(id), "Error downloading dependent layers", nil))
return err return err
} }
@ -1246,11 +1250,11 @@ func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, localName
if askedTag != "" && tag != askedTag { if askedTag != "" && tag != askedTag {
continue continue
} }
if err := srv.runtime.repositories.Set(localName, tag, id, true); err != nil { if err := srv.runtime.Repositories().Set(localName, tag, id, true); err != nil {
return err return err
} }
} }
if err := srv.runtime.repositories.Save(); err != nil { if err := srv.runtime.Repositories().Save(); err != nil {
return err return err
} }
@ -1371,7 +1375,7 @@ func (srv *Server) getImageList(localRepo map[string]string) ([]string, map[stri
tagsByImage[id] = append(tagsByImage[id], tag) tagsByImage[id] = append(tagsByImage[id], tag)
for img, err := srv.runtime.graph.Get(id); img != nil; img, err = img.GetParent() { for img, err := srv.runtime.Graph().Get(id); img != nil; img, err = img.GetParent() {
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -1478,7 +1482,7 @@ func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, localName
func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgID, ep string, token []string, sf *utils.StreamFormatter) (checksum string, err error) { func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgID, ep string, token []string, sf *utils.StreamFormatter) (checksum string, err error) {
out = utils.NewWriteFlusher(out) out = utils.NewWriteFlusher(out)
jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.graph.Root, imgID, "json")) jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.Graph().Root, imgID, "json"))
if err != nil { if err != nil {
return "", fmt.Errorf("Cannot retrieve the path for {%s}: %s", imgID, err) return "", fmt.Errorf("Cannot retrieve the path for {%s}: %s", imgID, err)
} }
@ -1497,7 +1501,7 @@ func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgID,
return "", err return "", err
} }
layerData, err := srv.runtime.graph.TempLayerArchive(imgID, archive.Uncompressed, sf, out) layerData, err := srv.runtime.Graph().TempLayerArchive(imgID, archive.Uncompressed, sf, out)
if err != nil { if err != nil {
return "", fmt.Errorf("Failed to generate layer archive: %s", err) return "", fmt.Errorf("Failed to generate layer archive: %s", err)
} }
@ -1549,17 +1553,17 @@ func (srv *Server) ImagePush(job *engine.Job) engine.Status {
return job.Error(err) return job.Error(err)
} }
img, err := srv.runtime.graph.Get(localName) img, err := srv.runtime.Graph().Get(localName)
r, err2 := registry.NewRegistry(authConfig, srv.HTTPRequestFactory(metaHeaders), endpoint) r, err2 := registry.NewRegistry(authConfig, srv.HTTPRequestFactory(metaHeaders), endpoint)
if err2 != nil { if err2 != nil {
return job.Error(err2) return job.Error(err2)
} }
if err != nil { if err != nil {
reposLen := len(srv.runtime.repositories.Repositories[localName]) reposLen := len(srv.runtime.Repositories().Repositories[localName])
job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", localName, reposLen)) job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", localName, reposLen))
// If it fails, try to get the repository // If it fails, try to get the repository
if localRepo, exists := srv.runtime.repositories.Repositories[localName]; exists { if localRepo, exists := srv.runtime.Repositories().Repositories[localName]; exists {
if err := srv.pushRepository(r, job.Stdout, localName, remoteName, localRepo, sf); err != nil { if err := srv.pushRepository(r, job.Stdout, localName, remoteName, localRepo, sf); err != nil {
return job.Error(err) return job.Error(err)
} }
@ -1615,13 +1619,13 @@ func (srv *Server) ImageImport(job *engine.Job) engine.Status {
defer progressReader.Close() defer progressReader.Close()
archive = progressReader archive = progressReader
} }
img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil) img, err := srv.runtime.Graph().Create(archive, "", "", "Imported from "+src, "", nil, nil)
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
// Optionally register the image at REPO/TAG // Optionally register the image at REPO/TAG
if repo != "" { if repo != "" {
if err := srv.runtime.repositories.Set(repo, tag, img.ID, true); err != nil { if err := srv.runtime.Repositories().Set(repo, tag, img.ID, true); err != nil {
return job.Error(err) return job.Error(err)
} }
} }
@ -1640,11 +1644,11 @@ func (srv *Server) ContainerCreate(job *engine.Job) engine.Status {
if config.Memory != 0 && config.Memory < 524288 { if config.Memory != 0 && config.Memory < 524288 {
return job.Errorf("Minimum memory limit allowed is 512k") return job.Errorf("Minimum memory limit allowed is 512k")
} }
if config.Memory > 0 && !srv.runtime.sysInfo.MemoryLimit { if config.Memory > 0 && !srv.runtime.SystemConfig().MemoryLimit {
job.Errorf("Your kernel does not support memory limit capabilities. Limitation discarded.\n") job.Errorf("Your kernel does not support memory limit capabilities. Limitation discarded.\n")
config.Memory = 0 config.Memory = 0
} }
if config.Memory > 0 && !srv.runtime.sysInfo.SwapLimit { if config.Memory > 0 && !srv.runtime.SystemConfig().SwapLimit {
job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n") job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n")
config.MemorySwap = -1 config.MemorySwap = -1
} }
@ -1652,26 +1656,26 @@ func (srv *Server) ContainerCreate(job *engine.Job) engine.Status {
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
if !config.NetworkDisabled && len(config.Dns) == 0 && len(srv.runtime.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) { if !config.NetworkDisabled && len(config.Dns) == 0 && len(srv.runtime.Config().Dns) == 0 && utils.CheckLocalDns(resolvConf) {
job.Errorf("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v\n", defaultDns) job.Errorf("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v\n", runtime.DefaultDns)
config.Dns = defaultDns config.Dns = runtime.DefaultDns
} }
container, buildWarnings, err := srv.runtime.Create(config, name) container, buildWarnings, err := srv.runtime.Create(config, name)
if err != nil { if err != nil {
if srv.runtime.graph.IsNotExist(err) { if srv.runtime.Graph().IsNotExist(err) {
_, tag := utils.ParseRepositoryTag(config.Image) _, tag := utils.ParseRepositoryTag(config.Image)
if tag == "" { if tag == "" {
tag = DEFAULTTAG tag = graph.DEFAULTTAG
} }
return job.Errorf("No such image: %s (tag: %s)", config.Image, tag) return job.Errorf("No such image: %s (tag: %s)", config.Image, tag)
} }
return job.Error(err) return job.Error(err)
} }
if !container.Config.NetworkDisabled && srv.runtime.sysInfo.IPv4ForwardingDisabled { if !container.Config.NetworkDisabled && srv.runtime.SystemConfig().IPv4ForwardingDisabled {
job.Errorf("IPv4 forwarding is disabled.\n") job.Errorf("IPv4 forwarding is disabled.\n")
} }
srv.LogEvent("create", container.ID, srv.runtime.repositories.ImageName(container.Image)) srv.LogEvent("create", container.ID, srv.runtime.Repositories().ImageName(container.Image))
// FIXME: this is necessary because runtime.Create might return a nil container // FIXME: this is necessary because runtime.Create might return a nil container
// with a non-nil error. This should not happen! Once it's fixed we // with a non-nil error. This should not happen! Once it's fixed we
// can remove this workaround. // can remove this workaround.
@ -1699,7 +1703,7 @@ func (srv *Server) ContainerRestart(job *engine.Job) engine.Status {
if err := container.Restart(int(t)); err != nil { if err := container.Restart(int(t)); err != nil {
return job.Errorf("Cannot restart container %s: %s\n", name, err) return job.Errorf("Cannot restart container %s: %s\n", name, err)
} }
srv.LogEvent("restart", container.ID, srv.runtime.repositories.ImageName(container.Image)) srv.LogEvent("restart", container.ID, srv.runtime.Repositories().ImageName(container.Image))
} else { } else {
return job.Errorf("No such container: %s\n", name) return job.Errorf("No such container: %s\n", name)
} }
@ -1721,7 +1725,7 @@ func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
if container == nil { if container == nil {
return job.Errorf("No such link: %s", name) return job.Errorf("No such link: %s", name)
} }
name, err := getFullName(name) name, err := runtime.GetFullContainerName(name)
if err != nil { if err != nil {
job.Error(err) job.Error(err)
} }
@ -1729,21 +1733,17 @@ func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
if parent == "/" { if parent == "/" {
return job.Errorf("Conflict, cannot remove the default name of the container") return job.Errorf("Conflict, cannot remove the default name of the container")
} }
pe := srv.runtime.containerGraph.Get(parent) pe := srv.runtime.ContainerGraph().Get(parent)
if pe == nil { if pe == nil {
return job.Errorf("Cannot get parent %s for name %s", parent, name) return job.Errorf("Cannot get parent %s for name %s", parent, name)
} }
parentContainer := srv.runtime.Get(pe.ID()) parentContainer := srv.runtime.Get(pe.ID())
if parentContainer != nil && parentContainer.activeLinks != nil { if parentContainer != nil {
if link, exists := parentContainer.activeLinks[n]; exists { parentContainer.DisableLink(n)
link.Disable()
} else {
utils.Debugf("Could not find active link for %s", name)
}
} }
if err := srv.runtime.containerGraph.Delete(name); err != nil { if err := srv.runtime.ContainerGraph().Delete(name); err != nil {
return job.Error(err) return job.Error(err)
} }
return engine.StatusOK return engine.StatusOK
@ -1762,13 +1762,13 @@ func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
if err := srv.runtime.Destroy(container); err != nil { if err := srv.runtime.Destroy(container); err != nil {
return job.Errorf("Cannot destroy container %s: %s", name, err) return job.Errorf("Cannot destroy container %s: %s", name, err)
} }
srv.LogEvent("destroy", container.ID, srv.runtime.repositories.ImageName(container.Image)) srv.LogEvent("destroy", container.ID, srv.runtime.Repositories().ImageName(container.Image))
if removeVolume { if removeVolume {
var ( var (
volumes = make(map[string]struct{}) volumes = make(map[string]struct{})
binds = make(map[string]struct{}) binds = make(map[string]struct{})
usedVolumes = make(map[string]*Container) usedVolumes = make(map[string]*runtime.Container)
) )
// the volume id is always the base of the path // the volume id is always the base of the path
@ -1777,7 +1777,7 @@ func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
} }
// populate bind map so that they can be skipped and not removed // populate bind map so that they can be skipped and not removed
for _, bind := range container.hostConfig.Binds { for _, bind := range container.HostConfig().Binds {
source := strings.Split(bind, ":")[0] source := strings.Split(bind, ":")[0]
// TODO: refactor all volume stuff, all of it // TODO: refactor all volume stuff, all of it
// this is very important that we eval the link // this is very important that we eval the link
@ -1816,7 +1816,7 @@ func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
log.Printf("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.ID) log.Printf("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.ID)
continue continue
} }
if err := srv.runtime.volumes.Delete(volumeId); err != nil { if err := srv.runtime.Volumes().Delete(volumeId); err != nil {
return job.Errorf("Error calling volumes.Delete(%q): %v", volumeId, err) return job.Errorf("Error calling volumes.Delete(%q): %v", volumeId, err)
} }
} }
@ -1835,12 +1835,12 @@ func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo
repoName, tag = utils.ParseRepositoryTag(name) repoName, tag = utils.ParseRepositoryTag(name)
if tag == "" { if tag == "" {
tag = DEFAULTTAG tag = graph.DEFAULTTAG
} }
img, err := srv.runtime.repositories.LookupImage(name) img, err := srv.runtime.Repositories().LookupImage(name)
if err != nil { if err != nil {
if r, _ := srv.runtime.repositories.Get(repoName); r != nil { if r, _ := srv.runtime.Repositories().Get(repoName); r != nil {
return fmt.Errorf("No such image: %s:%s", repoName, tag) return fmt.Errorf("No such image: %s:%s", repoName, tag)
} }
return fmt.Errorf("No such image: %s", name) return fmt.Errorf("No such image: %s", name)
@ -1851,14 +1851,14 @@ func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo
tag = "" tag = ""
} }
byParents, err := srv.runtime.graph.ByParent() byParents, err := srv.runtime.Graph().ByParent()
if err != nil { if err != nil {
return err return err
} }
//If delete by id, see if the id belong only to one repository //If delete by id, see if the id belong only to one repository
if repoName == "" { if repoName == "" {
for _, repoAndTag := range srv.runtime.repositories.ByID()[img.ID] { for _, repoAndTag := range srv.runtime.Repositories().ByID()[img.ID] {
parsedRepo, parsedTag := utils.ParseRepositoryTag(repoAndTag) parsedRepo, parsedTag := utils.ParseRepositoryTag(repoAndTag)
if repoName == "" || repoName == parsedRepo { if repoName == "" || repoName == parsedRepo {
repoName = parsedRepo repoName = parsedRepo
@ -1881,7 +1881,7 @@ func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo
//Untag the current image //Untag the current image
for _, tag := range tags { for _, tag := range tags {
tagDeleted, err := srv.runtime.repositories.Delete(repoName, tag) tagDeleted, err := srv.runtime.Repositories().Delete(repoName, tag)
if err != nil { if err != nil {
return err return err
} }
@ -1892,16 +1892,16 @@ func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo
srv.LogEvent("untag", img.ID, "") srv.LogEvent("untag", img.ID, "")
} }
} }
tags = srv.runtime.repositories.ByID()[img.ID] tags = srv.runtime.Repositories().ByID()[img.ID]
if (len(tags) <= 1 && repoName == "") || len(tags) == 0 { if (len(tags) <= 1 && repoName == "") || len(tags) == 0 {
if len(byParents[img.ID]) == 0 { if len(byParents[img.ID]) == 0 {
if err := srv.canDeleteImage(img.ID); err != nil { if err := srv.canDeleteImage(img.ID); err != nil {
return err return err
} }
if err := srv.runtime.repositories.DeleteAll(img.ID); err != nil { if err := srv.runtime.Repositories().DeleteAll(img.ID); err != nil {
return err return err
} }
if err := srv.runtime.graph.Delete(img.ID); err != nil { if err := srv.runtime.Graph().Delete(img.ID); err != nil {
return err return err
} }
out := &engine.Env{} out := &engine.Env{}
@ -1940,12 +1940,12 @@ func (srv *Server) ImageDelete(job *engine.Job) engine.Status {
func (srv *Server) canDeleteImage(imgID string) error { func (srv *Server) canDeleteImage(imgID string) error {
for _, container := range srv.runtime.List() { for _, container := range srv.runtime.List() {
parent, err := srv.runtime.repositories.LookupImage(container.Image) parent, err := srv.runtime.Repositories().LookupImage(container.Image)
if err != nil { if err != nil {
return err return err
} }
if err := parent.WalkHistory(func(p *Image) error { if err := parent.WalkHistory(func(p *image.Image) error {
if imgID == p.ID { if imgID == p.ID {
return fmt.Errorf("Conflict, cannot delete %s because the container %s is using it", utils.TruncateID(imgID), utils.TruncateID(container.ID)) return fmt.Errorf("Conflict, cannot delete %s because the container %s is using it", utils.TruncateID(imgID), utils.TruncateID(container.ID))
} }
@ -1957,10 +1957,10 @@ func (srv *Server) canDeleteImage(imgID string) error {
return nil return nil
} }
func (srv *Server) ImageGetCached(imgID string, config *runconfig.Config) (*Image, error) { func (srv *Server) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) {
// Retrieve all images // Retrieve all images
images, err := srv.runtime.graph.Map() images, err := srv.runtime.Graph().Map()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1975,9 +1975,9 @@ func (srv *Server) ImageGetCached(imgID string, config *runconfig.Config) (*Imag
} }
// Loop on the children of the given image and check the config // Loop on the children of the given image and check the config
var match *Image var match *image.Image
for elem := range imageMap[imgID] { for elem := range imageMap[imgID] {
img, err := srv.runtime.graph.Get(elem) img, err := srv.runtime.Graph().Get(elem)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1990,7 +1990,7 @@ func (srv *Server) ImageGetCached(imgID string, config *runconfig.Config) (*Imag
return match, nil return match, nil
} }
func (srv *Server) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error { func (srv *Server) RegisterLinks(container *runtime.Container, hostConfig *runconfig.HostConfig) error {
runtime := srv.runtime runtime := srv.runtime
if hostConfig != nil && hostConfig.Links != nil { if hostConfig != nil && hostConfig.Links != nil {
@ -2014,7 +2014,7 @@ func (srv *Server) RegisterLinks(container *Container, hostConfig *runconfig.Hos
// After we load all the links into the runtime // After we load all the links into the runtime
// set them to nil on the hostconfig // set them to nil on the hostconfig
hostConfig.Links = nil hostConfig.Links = nil
if err := container.writeHostConfig(); err != nil { if err := container.WriteHostConfig(); err != nil {
return err return err
} }
} }
@ -2062,13 +2062,13 @@ func (srv *Server) ContainerStart(job *engine.Job) engine.Status {
if err := srv.RegisterLinks(container, hostConfig); err != nil { if err := srv.RegisterLinks(container, hostConfig); err != nil {
return job.Error(err) return job.Error(err)
} }
container.hostConfig = hostConfig container.SetHostConfig(hostConfig)
container.ToDisk() container.ToDisk()
} }
if err := container.Start(); err != nil { if err := container.Start(); err != nil {
return job.Errorf("Cannot start container %s: %s", name, err) return job.Errorf("Cannot start container %s: %s", name, err)
} }
srv.LogEvent("start", container.ID, runtime.repositories.ImageName(container.Image)) srv.LogEvent("start", container.ID, runtime.Repositories().ImageName(container.Image))
return engine.StatusOK return engine.StatusOK
} }
@ -2088,7 +2088,7 @@ func (srv *Server) ContainerStop(job *engine.Job) engine.Status {
if err := container.Stop(int(t)); err != nil { if err := container.Stop(int(t)); err != nil {
return job.Errorf("Cannot stop container %s: %s\n", name, err) return job.Errorf("Cannot stop container %s: %s\n", name, err)
} }
srv.LogEvent("stop", container.ID, srv.runtime.repositories.ImageName(container.Image)) srv.LogEvent("stop", container.ID, srv.runtime.Repositories().ImageName(container.Image))
} else { } else {
return job.Errorf("No such container: %s\n", name) return job.Errorf("No such container: %s\n", name)
} }
@ -2234,15 +2234,15 @@ func (srv *Server) ContainerAttach(job *engine.Job) engine.Status {
return engine.StatusOK return engine.StatusOK
} }
func (srv *Server) ContainerInspect(name string) (*Container, error) { func (srv *Server) ContainerInspect(name string) (*runtime.Container, error) {
if container := srv.runtime.Get(name); container != nil { if container := srv.runtime.Get(name); container != nil {
return container, nil return container, nil
} }
return nil, fmt.Errorf("No such container: %s", name) return nil, fmt.Errorf("No such container: %s", name)
} }
func (srv *Server) ImageInspect(name string) (*Image, error) { func (srv *Server) ImageInspect(name string) (*image.Image, error) {
if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil { if image, err := srv.runtime.Repositories().LookupImage(name); err == nil && image != nil {
return image, nil return image, nil
} }
return nil, fmt.Errorf("No such image: %s", name) return nil, fmt.Errorf("No such image: %s", name)
@ -2277,9 +2277,9 @@ func (srv *Server) JobInspect(job *engine.Job) engine.Status {
return job.Error(errContainer) return job.Error(errContainer)
} }
object = &struct { object = &struct {
*Container *runtime.Container
HostConfig *runconfig.HostConfig HostConfig *runconfig.HostConfig
}{container, container.hostConfig} }{container, container.HostConfig()}
default: default:
return job.Errorf("Unknown kind: %s", kind) return job.Errorf("Unknown kind: %s", kind)
} }
@ -2318,8 +2318,8 @@ func (srv *Server) ContainerCopy(job *engine.Job) engine.Status {
return job.Errorf("No such container: %s", name) return job.Errorf("No such container: %s", name)
} }
func NewServer(eng *engine.Engine, config *DaemonConfig) (*Server, error) { func NewServer(eng *engine.Engine, config *daemonconfig.Config) (*Server, error) {
runtime, err := NewRuntime(config, eng) runtime, err := runtime.NewRuntime(config, eng)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -2332,7 +2332,7 @@ func NewServer(eng *engine.Engine, config *DaemonConfig) (*Server, error) {
listeners: make(map[string]chan utils.JSONMessage), listeners: make(map[string]chan utils.JSONMessage),
running: true, running: true,
} }
runtime.srv = srv runtime.SetServer(srv)
return srv, nil return srv, nil
} }
@ -2400,7 +2400,7 @@ func (srv *Server) Close() error {
type Server struct { type Server struct {
sync.RWMutex sync.RWMutex
runtime *Runtime runtime *runtime.Runtime
pullingPool map[string]chan struct{} pullingPool map[string]chan struct{}
pushingPool map[string]chan struct{} pushingPool map[string]chan struct{}
events []utils.JSONMessage events []utils.JSONMessage

View file

@ -2,9 +2,6 @@ package docker
import ( import (
"github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/nat"
"github.com/dotcloud/docker/pkg/namesgenerator"
"github.com/dotcloud/docker/runconfig"
"github.com/dotcloud/docker/utils" "github.com/dotcloud/docker/utils"
) )
@ -12,45 +9,8 @@ type Change struct {
archive.Change archive.Change
} }
func migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error {
if config.PortSpecs != nil {
ports, bindings, err := nat.ParsePortSpecs(config.PortSpecs)
if err != nil {
return err
}
config.PortSpecs = nil
if len(bindings) > 0 {
if hostConfig == nil {
hostConfig = &runconfig.HostConfig{}
}
hostConfig.PortBindings = bindings
}
if config.ExposedPorts == nil {
config.ExposedPorts = make(nat.PortSet, len(ports))
}
for k, v := range ports {
config.ExposedPorts[k] = v
}
}
return nil
}
// Links come in the format of // Links come in the format of
// name:alias // name:alias
func parseLink(rawLink string) (map[string]string, error) { func parseLink(rawLink string) (map[string]string, error) {
return utils.PartParser("name:alias", rawLink) return utils.PartParser("name:alias", rawLink)
} }
type checker struct {
runtime *Runtime
}
func (c *checker) Exists(name string) bool {
return c.runtime.containerGraph.Exists("/" + name)
}
// Generate a random and unique name
func generateRandomName(runtime *Runtime) (string, error) {
return namesgenerator.GenerateRandomName(&checker{runtime})
}

View file

@ -2,6 +2,7 @@ package utils
import ( import (
"bytes" "bytes"
"crypto/rand"
"crypto/sha1" "crypto/sha1"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
@ -493,6 +494,34 @@ func TruncateID(id string) string {
return id[:shortLen] return id[:shortLen]
} }
// GenerateRandomID returns an unique id
func GenerateRandomID() string {
for {
id := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, id); err != nil {
panic(err) // This shouldn't happen
}
value := hex.EncodeToString(id)
// if we try to parse the truncated for as an int and we don't have
// an error then the value is all numberic and causes issues when
// used as a hostname. ref #3869
if _, err := strconv.Atoi(TruncateID(value)); err == nil {
continue
}
return value
}
}
func ValidateID(id string) error {
if id == "" {
return fmt.Errorf("Id can't be empty")
}
if strings.Contains(id, ":") {
return fmt.Errorf("Invalid character in id: ':'")
}
return nil
}
// Code c/c from io.Copy() modified to handle escape sequence // Code c/c from io.Copy() modified to handle escape sequence
func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) { func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
buf := make([]byte, 32*1024) buf := make([]byte, 32*1024)

View file

@ -1,24 +0,0 @@
package docker
import (
"bytes"
"github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
"io"
)
func fakeTar() (io.Reader, error) {
content := []byte("Hello world!\n")
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} {
hdr := new(tar.Header)
hdr.Size = int64(len(content))
hdr.Name = name
if err := tw.WriteHeader(hdr); err != nil {
return nil, err
}
tw.Write([]byte(content))
}
tw.Close()
return buf, nil
}