github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/client/docker/utils.go (about)

     1  // Copyright © 2021 Alibaba Group Holding Ltd.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package docker
    16  
    17  import (
    18  	"encoding/base64"
    19  	"encoding/json"
    20  
    21  	"github.com/docker/distribution/reference"
    22  	"github.com/docker/docker/api/types"
    23  	dockerregistry "github.com/docker/docker/registry"
    24  	"github.com/sirupsen/logrus"
    25  
    26  	"github.com/sealerio/sealer/pkg/client/docker/auth"
    27  	normalreference "github.com/sealerio/sealer/pkg/image/reference"
    28  )
    29  
    30  func GetCanonicalImageName(rawImageName string) (reference.Named, error) {
    31  	var named reference.Named
    32  	named, err := reference.ParseNormalizedNamed(rawImageName)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	return named, nil
    37  }
    38  
    39  func GetCanonicalImagePullOptions(canonicalImageName string) types.ImagePullOptions {
    40  	var (
    41  		err         error
    42  		authConfig  types.AuthConfig
    43  		encodedJSON []byte
    44  		authStr     string
    45  		opts        types.ImagePullOptions
    46  	)
    47  
    48  	named, err := normalreference.ParseToNamed(canonicalImageName)
    49  	if err != nil {
    50  		logrus.Warnf("failed to parse canonical ImageName: %v", err)
    51  		return opts
    52  	}
    53  
    54  	//convert default docker.io to its default index server endpoint
    55  	registryAddr := named.Domain()
    56  	if registryAddr == dockerregistry.IndexName {
    57  		registryAddr = dockerregistry.IndexServer
    58  	}
    59  	svc, err := auth.NewDockerAuthService()
    60  	if err != nil {
    61  		return opts
    62  	}
    63  
    64  	authConfig, err = svc.GetAuthByDomain(registryAddr)
    65  	if err == nil {
    66  		encodedJSON, err = json.Marshal(authConfig)
    67  		if err != nil {
    68  			logrus.Warnf("failed to authConfig encodedJSON: %v", err)
    69  		} else {
    70  			authStr = base64.URLEncoding.EncodeToString(encodedJSON)
    71  		}
    72  	}
    73  	return types.ImagePullOptions{RegistryAuth: authStr}
    74  }