Files
2024-06-07 22:55:26 +08:00

91 lines
2.8 KiB
Go

package pack
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
"github.com/dustin/go-humanize"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"oras.land/oras-go/v2/registry/remote"
"oras.land/oras-go/v2/registry/remote/auth"
"oras.land/oras-go/v2/registry/remote/credentials"
"oras.land/oras-go/v2/registry/remote/retry"
)
// ./bin/vecps fetch --repository epscprelease/maas-models --tag bge-m3-20240607
// NewCmdFetch ...
func NewCmdFetch(ctx context.Context) *cobra.Command {
var registry string
var repository string
var tag string
var username string
var password string
cmd := &cobra.Command{
Use: "fetch",
Short: "fetch files from docker registry",
Example: `vecps fetch`,
RunE: func(_ *cobra.Command, args []string) (err error) {
ctx := context.Background()
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := retry.DefaultClient
client.Transport = customTransport
storeOpts := credentials.StoreOptions{}
credStore, err := credentials.NewStoreFromDocker(storeOpts)
if err != nil {
panic(err)
}
// Note: The below code can be omitted if authentication is not required
repo, err := remote.NewRepository(fmt.Sprintf("%s/%s", registry, repository))
if err != nil {
panic(err)
}
repo.Client = &auth.Client{
Client: client,
Cache: auth.NewCache(),
Credential: credentials.Credential(credStore),
// auth.StaticCredential(reg, auth.Credential{
// Username: "admin",
// Password: "Bytedance@789",
// }),
}
_, reader, err := repo.Manifests().FetchReference(ctx, tag)
if err != nil {
panic(err)
}
data, err := io.ReadAll(reader)
if err != nil {
panic(err)
}
var manifest ocispec.Manifest
err = json.Unmarshal(data, &manifest)
if err != nil {
panic(err)
}
logrus.WithField("anno", manifest.Annotations).Info("get manifest success")
for _, s := range manifest.Layers {
fmt.Printf("%-40s %s\n", s.Annotations["org.opencontainers.image.title"], humanize.BigIBytes(big.NewInt(s.Size)))
// reader, _ := repo.Blobs().Fetch(ctx, s)
// data, _ := io.ReadAll(reader)
// fmt.Println(string(data))
}
return nil
},
}
cmd.PersistentFlags().StringVarP(&registry, "registry", "", "hub.byted.org", "docker registry domain")
cmd.PersistentFlags().StringVarP(&repository, "repository", "", "epscprelease/maas-models", "image repository name")
cmd.PersistentFlags().StringVarP(&tag, "tag", "", "latest", "image tag name")
cmd.PersistentFlags().StringVarP(&username, "username", "u", "", "docker registry username")
cmd.PersistentFlags().StringVarP(&password, "password", "p", "", "docker registry password")
return cmd
}