package main
import (
"context"
"crypto/tls"
"errors"
"flag"
"fmt"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/daemon"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"net/http"
)
func main() {
var imgName string
flag.StringVar(&imgName, "img", "", "镜像名")
flag.Parse()
err := DownloadImage(imgName)
if err != nil {
fmt.Println(err.Error())
}
}
func rt(ctx context.Context, ref string) (http.RoundTripper, error) {
r, err := name.ParseReference(ref)
if err != nil {
return nil, err
}
repo := r.Context()
auth, err := authn.DefaultKeychain.Resolve(repo)
if err != nil {
return nil, err
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
rt := http.DefaultTransport
rt = transport.NewRetry(rt)
if rt == nil {
fmt.Println("something error")
return nil, errors.New("something error")
}
rt, err = transport.NewWithContext(ctx, repo.Registry, auth, rt, []string{repo.Scope(transport.PullScope)})
if err != nil {
return nil, err
}
return rt, nil
}
func DownloadImage(imageFullName string) (err error) {
ctx := context.Background()
ref, err := name.ParseReference(imageFullName)
if err != nil {
return err
}
rt, err := rt(ctx, imageFullName)
if err != nil {
return err
}
desc, err := remote.Get(ref, remote.WithTransport(rt))
if err != nil {
return err
}
img, err := desc.Image()
if err != nil {
return err
}
dig, err := img.Digest()
if err != nil {
return err
}
fmt.Println(dig.Hex)
tag, _ := name.NewTag(imageFullName) //创建tag对象
str, err := daemon.Write(tag, img) //将镜像导入到docker daemon中,并使用指定的tag命令
if err != nil {
fmt.Println("daemon.Write function failed")
return
} else {
fmt.Println(str)
}
return nil
}
运行:
# ./crane -img testggw.com/library/busybox:0.1
dcdf379c574e1773d703f0c0d56d67594e7a91d6b84d11ff46799f60fb081c52
{"status":"Loading layer","progressDetail":{"current":32768,"total":773257},"progress":"[==\u003e ] 32.77kB/773.3kB","id":"7ad00cd55506"}
{"status":"Loading layer","progressDetail":{"current":229376,"total":773257},"progress":"[==============\u003e ] 229.4kB/773.3kB","id":"7ad00cd55506"}
{"status":"Loading layer","progressDetail":{"current":773257,"total":773257},"progress":"[==================================================\u003e] 773.3kB/773.3kB","id":"7ad00cd55506"}
{"status":"Loading layer","progressDetail":{"current":773257,"total":773257},"progress":"[==================================================\u003e] 773.3kB/773.3kB","id":"7ad00cd55506"}
{"stream":"Loaded image: testggw.com/library/busybox:0.1\n"}
docker images查看
# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
testggw.com/library/busybox 0.1 62aedd01bd85 4 weeks ago 1.24MB