77 lines
1.8 KiB
Go
77 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/google/go-containerregistry/pkg/authn"
|
|
"github.com/google/go-containerregistry/pkg/crane"
|
|
"github.com/google/go-containerregistry/pkg/name"
|
|
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
|
|
)
|
|
|
|
func (util *ImageUtil) pullImage(params *PullImageParams) (*PullImageResult, error) {
|
|
var err error
|
|
|
|
ctx, _ := context.WithTimeout(context.Background(), time.Duration(params.Timeout)*time.Second)
|
|
|
|
res := &PullImageResult{}
|
|
options := make([]crane.Option, 0)
|
|
options = append(options, crane.WithContext(ctx))
|
|
if params.Username != "" && params.Password != "" {
|
|
ref, err := name.ParseReference(params.Imagepath)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
repo := ref.Context()
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
defaultTransport := &roundTripper{}
|
|
|
|
scopes := []string{repo.Scope(transport.PullScope)}
|
|
|
|
regName := repo.RegistryStr()
|
|
reg, err := name.NewRegistry(regName)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
basicAuth := &authn.Basic{
|
|
Username: params.Username,
|
|
Password: params.Password,
|
|
}
|
|
authTransport, err := transport.NewWithContext(ctx, reg, basicAuth, defaultTransport, scopes)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
options = append(options, crane.WithTransport(authTransport))
|
|
} else {
|
|
transport := &roundTripper{}
|
|
options = append(options, crane.WithTransport(transport))
|
|
}
|
|
|
|
image, err := crane.Pull(params.Imagepath, options...)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
dstDir := makeTmpFileName(params.Filepath)
|
|
err = os.MkdirAll(dstDir, 0750)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
err = crane.SaveOCI(image, dstDir)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
err = archiveDir(dstDir, params.Filepath)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
err = os.RemoveAll(dstDir)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
return res, err
|
|
}
|