Browse Source

Move image into sub pkg
Docker-DCO-1.1-Signed-off-by: Michael Crosby <michael@crosbymichael.com> (github: crosbymichael)

Michael Crosby 11 năm trước cách đây
mục cha
commit
82a5439835

+ 2 - 1
container.go

@@ -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"
@@ -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")
 	}
 	}

+ 30 - 29
graph.go

@@ -5,6 +5,7 @@ import (
 	"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) {
-	img := &Image{
-		ID:            GenerateID(),
+func (graph *Graph) Create(layerData archive.ArchiveReader, container *Container, comment, author string, config *runconfig.Config) (*image.Image, error) {
+	img := &image.Image{
+		ID:            utils.GenerateRandomID(),
 		Comment:       comment,
 		Comment:       comment,
 		Created:       time.Now().UTC(),
 		Created:       time.Now().UTC(),
 		DockerVersion: dockerversion.VERSION,
 		DockerVersion: dockerversion.VERSION,
@@ -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
-	if err := StoreImage(img, jsonData, layerData, tmp, rootfs); err != nil {
+	img.SetGraph(graph)
+	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
 	}
 	}
@@ -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) {
-	images := make(map[string]*Image)
-	err := graph.walkAll(func(image *Image) {
+func (graph *Graph) Map() (map[string]*image.Image, error) {
+	images := make(map[string]*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) {
-	byParent := make(map[string][]*Image)
-	err := graph.walkAll(func(image *Image) {
-		parent, err := graph.Get(image.Parent)
+func (graph *Graph) ByParent() (map[string][]*image.Image, error) {
+	byParent := make(map[string][]*image.Image)
+	err := graph.walkAll(func(img *image.Image) {
+		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) {
-	heads := make(map[string]*Image)
+func (graph *Graph) Heads() (map[string]*image.Image, error) {
+	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)
 }
 }
 
 

+ 11 - 0
image/graph.go

@@ -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
+}

+ 13 - 39
image.go → image/image.go

@@ -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

+ 2 - 1
integration/api_test.go

@@ -9,6 +9,7 @@ import (
 	"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/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"
@@ -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)
 	}
 	}

+ 2 - 1
integration/buildfile_test.go

@@ -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)

+ 2 - 1
integration/commands_test.go

@@ -6,6 +6,7 @@ import (
 	"github.com/dotcloud/docker"
 	"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/utils"
 	"github.com/dotcloud/docker/utils"
 	"io"
 	"io"
@@ -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{
 		`
 		`

+ 20 - 19
integration/graph_test.go

@@ -6,6 +6,7 @@ import (
 	"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/utils"
 	"github.com/dotcloud/docker/utils"
 	"io"
 	"io"
 	"io/ioutil"
 	"io/ioutil"
@@ -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{
-		ID:      docker.GenerateID(),
+	image := &image.Image{
+		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, nil, "Testing", "", 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" {
-		t.Fatalf("Wrong comment: should be '%s', not '%s'", "Testing", image.Comment)
+	if img.Comment != "Testing" {
+		t.Fatalf("Wrong comment: should be '%s', not '%s'", "Testing", img.Comment)
 	}
 	}
-	if image.DockerVersion != dockerversion.VERSION {
-		t.Fatalf("Wrong docker_version: should be '%s', not '%s'", dockerversion.VERSION, image.DockerVersion)
+	if img.DockerVersion != dockerversion.VERSION {
+		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 {
-		t.Fatalf("Could not find image with id %s", image.ID)
+	if images[img.ID] == nil {
+		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{
-		ID:      docker.GenerateID(),
+	image := &image.Image{
+		ID:      utils.GenerateRandomID(),
 		Comment: "testing",
 		Comment: "testing",
 		Created: time.Now(),
 		Created: time.Now(),
 	}
 	}
@@ -164,7 +165,7 @@ 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 *docker.Graph, t *testing.T) *image.Image {
 	archive, err := fakeTar()
 	archive, err := fakeTar()
 	if err != nil {
 	if err != nil {
 		t.Fatal(err)
 		t.Fatal(err)
@@ -243,20 +244,20 @@ func TestByParent(t *testing.T) {
 
 
 	graph, _ := tempGraph(t)
 	graph, _ := tempGraph(t)
 	defer nukeGraph(graph)
 	defer nukeGraph(graph)
-	parentImage := &docker.Image{
-		ID:      docker.GenerateID(),
+	parentImage := &image.Image{
+		ID:      utils.GenerateRandomID(),
 		Comment: "parent",
 		Comment: "parent",
 		Created: time.Now(),
 		Created: time.Now(),
 		Parent:  "",
 		Parent:  "",
 	}
 	}
-	childImage1 := &docker.Image{
-		ID:      docker.GenerateID(),
+	childImage1 := &image.Image{
+		ID:      utils.GenerateRandomID(),
 		Comment: "child1",
 		Comment: "child1",
 		Created: time.Now(),
 		Created: time.Now(),
 		Parent:  parentImage.ID,
 		Parent:  parentImage.ID,
 	}
 	}
-	childImage2 := &docker.Image{
-		ID:      docker.GenerateID(),
+	childImage2 := &image.Image{
+		ID:      utils.GenerateRandomID(),
 		Comment: "child2",
 		Comment: "child2",
 		Created: time.Now(),
 		Created: time.Now(),
 		Parent:  parentImage.ID,
 		Parent:  parentImage.ID,

+ 2 - 1
integration/runtime_test.go

@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"fmt"
 	"github.com/dotcloud/docker"
 	"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/sysinit"
 	"github.com/dotcloud/docker/sysinit"
@@ -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 *docker.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)

+ 3 - 2
runtime.go

@@ -15,6 +15,7 @@ import (
 	_ "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"
@@ -396,7 +397,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)
@@ -539,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 {

+ 15 - 14
server.go

@@ -8,6 +8,7 @@ import (
 	"github.com/dotcloud/docker/daemonconfig"
 	"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/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"
@@ -362,8 +363,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 {
-	for i := image; i != nil; {
+func (srv *Server) exportImage(img *image.Image, tempdir string) error {
+	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 {
@@ -580,7 +581,7 @@ 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
@@ -690,7 +691,7 @@ func (srv *Server) ImagesViz(job *engine.Job) engine.Status {
 	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 {
@@ -722,7 +723,7 @@ 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") {
@@ -757,7 +758,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
 			}
 			}
 
 
@@ -778,7 +779,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)
 		}
 		}
 	}
 	}
@@ -838,7 +839,7 @@ 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)
 	}
 	}
@@ -855,7 +856,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())
@@ -1098,7 +1099,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)
@@ -1946,7 +1947,7 @@ func (srv *Server) canDeleteImage(imgID string) error {
 			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))
 			}
 			}
@@ -1958,7 +1959,7 @@ 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()
@@ -1976,7 +1977,7 @@ 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 {
@@ -2242,7 +2243,7 @@ func (srv *Server) ContainerInspect(name string) (*Container, error) {
 	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
 	}
 	}

+ 3 - 2
tags.go

@@ -3,6 +3,7 @@ package docker
 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

+ 2 - 1
tags_unit_test.go

@@ -2,6 +2,7 @@ package docker
 
 
 import (
 import (
 	"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"
 	"os"
 	"os"
 	"path"
 	"path"
@@ -30,7 +31,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 {

+ 29 - 0
utils/utils.go

@@ -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)