docker 会为每一个容器生成一个唯一的容器ID: 3c7b1df8777d 类似这种,我们今天就看一下生成ID的代码,这部分逻辑是很简单的,直接看代码:
// Package stringid provides helper functions for dealing with string identifiers
package stringid // import "github.com/docker/docker/pkg/stringid"
import (
cryptorand "crypto/rand"
"encoding/hex"
"fmt"
"io"
"math"
"math/big"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
)
const shortLen = 12
var (
validShortID = regexp.MustCompile("^[a-f0-9]{12}$")
validHex = regexp.MustCompile(`^[a-f0-9]{64}$`)
)
// IsShortID determines if an arbitrary string *looks like* a short ID.
func IsShortID(id string) bool {
return validShortID.MatchString(id)
}
// TruncateID returns a shorthand version of a string identifier for convenience.
// A collision with other shorthands is very unlikely, but possible.
// In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
// will need to use a longer prefix, or the full-length Id.
func TruncateID(id string) string {
if i := strings.IndexRune(id, ':'); i >= 0 {
id = id[i+1:]
}
if len(id) > shortLen {
id = id[:shortLen]
}
return id
}
func generateID(r io.Reader) string {
b := make([]byte, 32)
for {
if _, err := io.ReadFull(r, b); err != nil {
panic(err) // This shouldn't happen
}
id := hex.EncodeToString(b)
// if we try to parse the truncated for as an int and we don't have
// an error then the value is all numeric and causes issues when
// used as a hostname. ref #3869
if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil {
continue
}
return id
}
}
// GenerateRandomID returns a unique id.
func GenerateRandomID() string {
return generateID(cryptorand.Reader)
}
// GenerateNonCryptoID generates unique id without using cryptographically
// secure sources of random.
// It helps you to save entropy.
func GenerateNonCryptoID() string {
return generateID(readerFunc(rand.Read))
}
// ValidateID checks whether an ID string is a valid image ID.
func ValidateID(id string) error {
if ok := validHex.MatchString(id); !ok {
return fmt.Errorf("image ID %q is invalid", id)
}
return nil
}
func init() {
// safely set the seed globally so we generate random ids. Tries to use a
// crypto seed before falling back to time.
var seed int64
if cryptoseed, err := cryptorand.Int(cryptorand.Reader, big.NewInt(math.MaxInt64)); err != nil {
// This should not happen, but worst-case fallback to time-based seed.
seed = time.Now().UnixNano()
} else {
seed = cryptoseed.Int64()
}
rand.Seed(seed)
}
type readerFunc func(p []byte) (int, error)
func (fn readerFunc) Read(p []byte) (int, error) {
return fn(p)
}
这是 docker 生成 ID 的主要代码,在每次创建一个容器后,都会调用
func GenerateNonCryptoID() string 这个接口,用来生成唯一的ID,整个代码中,最重要的就是 func generateID(r io.Reader) string 这个函数,其中真正生成随机数的代码是
// Read generates len(p) random bytes from the default Source and
// writes them into p. It always returns len(p) and a nil error.
// Read, unlike the Rand.Read method, is safe for concurrent use.
func Read(p []byte) (n int, err error) { return globalRand.Read(p) }
这是go语言自带的部分,在 math/rand/rand.go。并且这个是并发安全的。
这时我们就会得到一个 io.Reader 接口对象,然后我们再将其读出来,放入一个 byte 切片,接下来 docker 将其转成十六进制的字符串,并且进行截取,还有一个就是 docker 判断了 ID 是不能转成 int 类型,根据代码我们可以知道这个是为了避免作为 hostname 是出现的问题。假如生成的 ID 可以转换成 int 类型,那么就会重新在之前的 io.Reader接口对象中继续读取,直到不能够转换成 int 类型。对于没有截取前的 ID 长度为64,截取后就是我们看到的十六进制的长度为12的字符串了。
这部分的逻辑非常简单,之所以写这个文章是觉得如果大家项目中有用到生成唯一ID类的需求,可以借鉴 docker 容器 ID 的生成方式,阅读源码的好处很多,并不止能借鉴其算法或者部分实现,更重要的是要理解其思路,整个项目的思路,所以还是建议大家多看看优秀项目的源码,而且用起来也更加得心应手。感谢阅读。