utils.go 9.3 KB
Newer Older
W
WangFengTu 已提交
1
// Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
2
// iSulad-img licensed under the Mulan PSL v1.
O
overweight 已提交
3 4 5 6 7 8 9 10 11 12 13
// You can use this software according to the terms and conditions of the Mulan PSL v1.
// You may obtain a copy of Mulan PSL v1 at:
//     http://license.coscl.org.cn/MulanPSL
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
// PURPOSE.
// See the Mulan PSL v1 for more details.
// Description: iSulad image kit
// Author: lifeng
// Create: 2019-05-06

W
WangFengTu 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// Since some of this code is derived from skopeo, their copyright
// is retained here....
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// The original version of this file can be found at
// https://github.com/containers/skopeo/blob/master/cmd/skopeo/utils.go

O
overweight 已提交
32 33 34 35 36 37 38 39 40 41 42
package main

import (
	"bufio"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"
D
dogsheng 已提交
43
	"time"
O
overweight 已提交
44 45

	istorage "github.com/containers/image/storage"
D
dogsheng 已提交
46
	"github.com/containers/image/transports/alltransports"
O
overweight 已提交
47 48 49
	"github.com/containers/image/types"
	cstorage "github.com/containers/storage"
	"github.com/docker/docker/pkg/homedir"
D
dogsheng 已提交
50
	v1 "github.com/opencontainers/image-spec/specs-go/v1"
O
overweight 已提交
51 52 53
	"github.com/urfave/cli"
)

D
dogsheng 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
type globalOptions struct {
	RunRoot            string
	GraphRoot          string
	GraphDriverName    string
	GraphDriverOptions []string
	storageOpts        map[string]string
	InsecureRegistries []string
	Registries         []string
	Policy             string
	InsecurePolicy     bool
	CmdTimeout         time.Duration
	TLSVerify          bool

	Daemon bool
}

O
overweight 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
// AuthInfo provide basic information about auth.
type AuthInfo struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Auth     string `json:"auth,omitempty"`
}

const maxJSONFileSize = (10 * 1024 * 1024)

func defaultAuthFilePath() string {
	return filepath.Join(homedir.Get(), ".isulad/auths.json")
}

func tlsVerify(c *cli.Context, flagPrefix string) bool {
	if c.IsSet(flagPrefix + "tls-verify") {
		return c.BoolT(flagPrefix + "tls-verify")
	}

	// If not set, default true.
	return true
}

func contextFromGlobalOptions(c *cli.Context, flagPrefix string) (*types.SystemContext, error) {
	ctx := &types.SystemContext{
		RegistriesDirPath:                 c.GlobalString("registries.d"),
		ArchitectureChoice:                c.GlobalString("override-arch"),
		OSChoice:                          c.GlobalString("override-os"),
		DockerCertPath:                    c.String(flagPrefix + "cert-dir"),
		DockerInsecureSkipTLSVerify:       types.NewOptionalBool(!tlsVerify(c, flagPrefix)),
		OSTreeTmpDirPath:                  c.String(flagPrefix + "ostree-tmp-dir"),
		OCISharedBlobDirPath:              c.String(flagPrefix + "shared-blob-dir"),
		DirForceCompress:                  c.Bool(flagPrefix + "compress"),
		AuthFilePath:                      c.String("authfile"),
		DockerDaemonHost:                  c.String(flagPrefix + "daemon-host"),
		DockerDaemonCertPath:              c.String(flagPrefix + "cert-dir"),
		DockerDaemonInsecureSkipTLSVerify: !c.BoolT(flagPrefix + "tls-verify"),
	}
	if c.IsSet(flagPrefix + "creds") {
		var err error
		ctx.DockerAuthConfig, err = getDockerAuth(c.String(flagPrefix + "creds"))
		if err != nil {
			return nil, err
		}
	}
	if c.IsSet(flagPrefix + "authfile") {
		ctx.AuthFilePath = c.String(flagPrefix + "authfile")
	}
	if ctx.AuthFilePath == "" {
		ctx.AuthFilePath = defaultAuthFilePath()
	}
	return ctx, nil
}

D
dogsheng 已提交
123
func commandTimeoutContextFromGlobalOptions(gopts *globalOptions) (context.Context, context.CancelFunc) {
O
overweight 已提交
124 125
	ctx := context.Background()
	var cancel context.CancelFunc = func() {}
D
dogsheng 已提交
126 127
	if gopts.CmdTimeout > 0 {
		ctx, cancel = context.WithTimeout(ctx, gopts.CmdTimeout)
O
overweight 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
	}
	return ctx, cancel
}

func parseCreds(creds string) (string, string, error) {
	if creds == "" {
		return "", "", errors.New("credentials can't be empty")
	}
	up := strings.SplitN(creds, ":", 2)
	if len(up) == 1 {
		return up[0], "", nil
	}
	if up[0] == "" {
		return "", "", errors.New("username can't be empty")
	}
	return up[0], up[1], nil
}

func getDockerAuth(creds string) (*types.DockerAuthConfig, error) {
	username, password, err := parseCreds(creds)
	if err != nil {
		return nil, err
	}
	return &types.DockerAuthConfig{
		Username: username,
		Password: password,
	}, nil
}

D
dogsheng 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
// parseImage converts image URL-like string to an initialized handler for that image.
// The caller must call .Close() on the returned ImageCloser.
func parseImage(ctx context.Context, c *cli.Context) (types.ImageCloser, error) {
	imgName := c.Args().First()
	ref, err := alltransports.ParseImageName(imgName)
	if err != nil {
		return nil, err
	}
	sys, err := contextFromGlobalOptions(c, "")
	if err != nil {
		return nil, err
	}
	return ref.NewImage(ctx, sys)
}

// parseImageSource converts image URL-like string to an ImageSource.
// The caller must call .Close() on the returned ImageSource.
func parseImageSource(ctx context.Context, c *cli.Context, name string) (types.ImageSource, error) {
	ref, err := alltransports.ParseImageName(name)
	if err != nil {
		return nil, err
	}
	sys, err := contextFromGlobalOptions(c, "")
	if err != nil {
		return nil, err
	}
	return ref.NewImageSource(ctx, sys)
}
O
overweight 已提交
185

D
dogsheng 已提交
186 187
func getMountPoint(gopts *globalOptions, idOrName string) (string, error) {
	store, err := getStorageStore(gopts)
O
overweight 已提交
188 189 190 191 192 193 194 195 196 197 198 199
	if err != nil {
		return "", err
	}

	mountPoint, err := store.Mount(idOrName, "")
	if err != nil {
		return "", fmt.Errorf("Failed to mount container %s: %v", idOrName, err)
	}

	return mountPoint, nil
}

D
dogsheng 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213
func putMountPoint(gopts *globalOptions, idOrName string, force bool) (bool, error) {
	store, err := getStorageStore(gopts)
	if err != nil {
		return false, err
	}

	isMounted, err := store.Unmount(idOrName, force)
	if err != nil {
		return false, fmt.Errorf("Failed to unmount container %s: %v", idOrName, err)
	}

	return isMounted, nil
}

O
overweight 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
func checkJSONFileSize(path string) error {
	fileInfo, err := os.Stat(path)
	if err != nil {
		return err
	}
	fileSize := fileInfo.Size()
	if fileSize > maxJSONFileSize {
		return fmt.Errorf("%s is too large", filepath.Base(path))
	}
	return nil
}

func readAuthFromStdin() (string, string, error) {
	var (
		username string
		password string
		authData AuthInfo
	)

	inputReader := bufio.NewReader(os.Stdin)
	line, _, err := inputReader.ReadLine()
	if err != nil {
		return "", "", fmt.Errorf("error reading authentication: %v", err)
	}

W
WangFengTu 已提交
239 240
	if err2 := json.Unmarshal(line, &authData); err2 != nil {
		return "", "", fmt.Errorf("error unmarshal authentication: %v", err2)
O
overweight 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
	}

	if authData.Username != "" {
		username = authData.Username
	}

	if authData.Password != "" {
		password = authData.Password
	}

	if authData.Auth != "" {
		username, password, err = decodeAuth(authData.Auth)
		if err != nil {
			return "", "", fmt.Errorf("error decoding authentication: %v", err)
		}
	}
	return username, password, nil
}

func getImageCloser(store cstorage.Store, containerImageName string) (types.ImageCloser, error) {
	// Check if we have the specified image.
	ref, err := istorage.Transport.ParseStoreReference(store, containerImageName)
	if err != nil {
		return nil, err
	}
	// Pull out a copy of the image's configuration.
	image, err := ref.NewImage(context.Background(), &types.SystemContext{})
	if err != nil {
		return nil, err
	}

	return image, nil
}

func getImageConf(store cstorage.Store, containerImageName string) (*v1.Image, error) {
	tmpImage, err := getImageCloser(store, containerImageName)
	if err != nil {
		return nil, err
	}
	defer tmpImage.Close()

	return tmpImage.OCIConfig(context.Background())
}

func getHealthcheck(store cstorage.Store, containerImageName string) (*HealthConfig, error) {
	tmpImage, err := getImageCloser(store, containerImageName)
	if err != nil {
		return nil, err
	}
	defer tmpImage.Close()

	cb, err := tmpImage.ConfigBlob(context.Background())
	if err != nil {
		return nil, err
	}
W
WangFengTu 已提交
296 297 298 299 300 301

	// schema1 doesn't have config blob
	if cb == nil {
		return nil, nil
	}

O
overweight 已提交
302 303 304 305 306 307
	config := &ConfigFromJSON{}
	if err := json.Unmarshal(cb, config); err != nil {
		return nil, err
	}
	return config.Config.Healthcheck, nil
}
D
dogsheng 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

func getGlobalOptions(c *cli.Context) (*globalOptions, error) {
	storageOpts, err := getStorageOptions(c)
	if err != nil {
		return nil, err
	}

	return &globalOptions{
		RunRoot:            c.GlobalString("run-root"),
		GraphRoot:          c.GlobalString("graph-root"),
		GraphDriverName:    c.GlobalString("driver-name"),
		GraphDriverOptions: c.GlobalStringSlice("driver-options"),
		storageOpts:        storageOpts,
		InsecureRegistries: c.GlobalStringSlice("insecure-registry"),
		Registries:         c.GlobalStringSlice("registry"),
		Policy:             c.GlobalString("policy"),
		InsecurePolicy:     c.GlobalBool("insecure-policy"),
		CmdTimeout:         c.GlobalDuration("command-timeout"),
		TLSVerify:          tlsVerify(c, ""),
	}, nil
}