242 lines
		
	
	
		
			5.7 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			242 lines
		
	
	
		
			5.7 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
package main
 | 
						|
 | 
						|
import (
 | 
						|
	"bufio"
 | 
						|
	gocontext "context"
 | 
						|
	"crypto/tls"
 | 
						|
	"encoding/csv"
 | 
						|
	"fmt"
 | 
						|
	"net"
 | 
						|
	"net/http"
 | 
						|
	"os"
 | 
						|
	"os/signal"
 | 
						|
	"strconv"
 | 
						|
	"strings"
 | 
						|
	"syscall"
 | 
						|
	"time"
 | 
						|
 | 
						|
	"github.com/containerd/console"
 | 
						|
	"github.com/containerd/containerd"
 | 
						|
	"github.com/containerd/containerd/namespaces"
 | 
						|
	"github.com/containerd/containerd/remotes"
 | 
						|
	"github.com/containerd/containerd/remotes/docker"
 | 
						|
	specs "github.com/opencontainers/runtime-spec/specs-go"
 | 
						|
	"github.com/pkg/errors"
 | 
						|
	"github.com/sirupsen/logrus"
 | 
						|
	"github.com/urfave/cli"
 | 
						|
)
 | 
						|
 | 
						|
// appContext returns the context for a command. Should only be called once per
 | 
						|
// command, near the start.
 | 
						|
//
 | 
						|
// This will ensure the namespace is picked up and set the timeout, if one is
 | 
						|
// defined.
 | 
						|
func appContext(clicontext *cli.Context) (gocontext.Context, gocontext.CancelFunc) {
 | 
						|
	var (
 | 
						|
		ctx       = gocontext.Background()
 | 
						|
		timeout   = clicontext.GlobalDuration("timeout")
 | 
						|
		namespace = clicontext.GlobalString("namespace")
 | 
						|
		cancel    gocontext.CancelFunc
 | 
						|
	)
 | 
						|
 | 
						|
	ctx = namespaces.WithNamespace(ctx, namespace)
 | 
						|
 | 
						|
	if timeout > 0 {
 | 
						|
		ctx, cancel = gocontext.WithTimeout(ctx, timeout)
 | 
						|
	} else {
 | 
						|
		ctx, cancel = gocontext.WithCancel(ctx)
 | 
						|
	}
 | 
						|
 | 
						|
	return ctx, cancel
 | 
						|
}
 | 
						|
 | 
						|
func newClient(context *cli.Context) (*containerd.Client, gocontext.Context, gocontext.CancelFunc, error) {
 | 
						|
	client, err := containerd.New(context.GlobalString("address"))
 | 
						|
	if err != nil {
 | 
						|
		return nil, nil, nil, err
 | 
						|
	}
 | 
						|
	ctx, cancel := appContext(context)
 | 
						|
	return client, ctx, cancel, nil
 | 
						|
}
 | 
						|
 | 
						|
func passwordPrompt() (string, error) {
 | 
						|
	c := console.Current()
 | 
						|
	defer c.Reset()
 | 
						|
 | 
						|
	if err := c.DisableEcho(); err != nil {
 | 
						|
		return "", errors.Wrap(err, "failed to disable echo")
 | 
						|
	}
 | 
						|
 | 
						|
	line, _, err := bufio.NewReader(c).ReadLine()
 | 
						|
	if err != nil {
 | 
						|
		return "", errors.Wrap(err, "failed to read line")
 | 
						|
	}
 | 
						|
	return string(line), nil
 | 
						|
}
 | 
						|
 | 
						|
// getResolver prepares the resolver from the environment and options.
 | 
						|
func getResolver(ctx gocontext.Context, clicontext *cli.Context) (remotes.Resolver, error) {
 | 
						|
	username := clicontext.String("user")
 | 
						|
	var secret string
 | 
						|
	if i := strings.IndexByte(username, ':'); i > 0 {
 | 
						|
		secret = username[i+1:]
 | 
						|
		username = username[0:i]
 | 
						|
	}
 | 
						|
	options := docker.ResolverOptions{
 | 
						|
		PlainHTTP: clicontext.Bool("plain-http"),
 | 
						|
		Tracker:   pushTracker,
 | 
						|
	}
 | 
						|
	if username != "" {
 | 
						|
		if secret == "" {
 | 
						|
			fmt.Printf("Password: ")
 | 
						|
 | 
						|
			var err error
 | 
						|
			secret, err = passwordPrompt()
 | 
						|
			if err != nil {
 | 
						|
				return nil, err
 | 
						|
			}
 | 
						|
 | 
						|
			fmt.Print("\n")
 | 
						|
		}
 | 
						|
	} else if rt := clicontext.String("refresh"); rt != "" {
 | 
						|
		secret = rt
 | 
						|
	}
 | 
						|
 | 
						|
	options.Credentials = func(host string) (string, string, error) {
 | 
						|
		// Only one host
 | 
						|
		return username, secret, nil
 | 
						|
	}
 | 
						|
 | 
						|
	tr := &http.Transport{
 | 
						|
		Proxy: http.ProxyFromEnvironment,
 | 
						|
		DialContext: (&net.Dialer{
 | 
						|
			Timeout:   30 * time.Second,
 | 
						|
			KeepAlive: 30 * time.Second,
 | 
						|
			DualStack: true,
 | 
						|
		}).DialContext,
 | 
						|
		MaxIdleConns:        10,
 | 
						|
		IdleConnTimeout:     30 * time.Second,
 | 
						|
		TLSHandshakeTimeout: 10 * time.Second,
 | 
						|
		TLSClientConfig: &tls.Config{
 | 
						|
			InsecureSkipVerify: clicontext.Bool("insecure"),
 | 
						|
		},
 | 
						|
		ExpectContinueTimeout: 5 * time.Second,
 | 
						|
	}
 | 
						|
 | 
						|
	options.Client = &http.Client{
 | 
						|
		Transport: tr,
 | 
						|
	}
 | 
						|
 | 
						|
	return docker.NewResolver(options), nil
 | 
						|
}
 | 
						|
 | 
						|
func forwardAllSignals(ctx gocontext.Context, task killer) chan os.Signal {
 | 
						|
	sigc := make(chan os.Signal, 128)
 | 
						|
	signal.Notify(sigc)
 | 
						|
	go func() {
 | 
						|
		for s := range sigc {
 | 
						|
			logrus.Debug("forwarding signal ", s)
 | 
						|
			if err := task.Kill(ctx, s.(syscall.Signal)); err != nil {
 | 
						|
				logrus.WithError(err).Errorf("forward signal %s", s)
 | 
						|
			}
 | 
						|
		}
 | 
						|
	}()
 | 
						|
	return sigc
 | 
						|
}
 | 
						|
 | 
						|
func parseSignal(rawSignal string) (syscall.Signal, error) {
 | 
						|
	s, err := strconv.Atoi(rawSignal)
 | 
						|
	if err == nil {
 | 
						|
		sig := syscall.Signal(s)
 | 
						|
		for _, msig := range signalMap {
 | 
						|
			if sig == msig {
 | 
						|
				return sig, nil
 | 
						|
			}
 | 
						|
		}
 | 
						|
		return -1, fmt.Errorf("unknown signal %q", rawSignal)
 | 
						|
	}
 | 
						|
	signal, ok := signalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")]
 | 
						|
	if !ok {
 | 
						|
		return -1, fmt.Errorf("unknown signal %q", rawSignal)
 | 
						|
	}
 | 
						|
	return signal, nil
 | 
						|
}
 | 
						|
 | 
						|
func stopCatch(sigc chan os.Signal) {
 | 
						|
	signal.Stop(sigc)
 | 
						|
	close(sigc)
 | 
						|
}
 | 
						|
 | 
						|
// parseMountFlag parses a mount string in the form "type=foo,source=/path,destination=/target,options=rbind:rw"
 | 
						|
func parseMountFlag(m string) (specs.Mount, error) {
 | 
						|
	mount := specs.Mount{}
 | 
						|
	r := csv.NewReader(strings.NewReader(m))
 | 
						|
 | 
						|
	fields, err := r.Read()
 | 
						|
	if err != nil {
 | 
						|
		return mount, err
 | 
						|
	}
 | 
						|
 | 
						|
	for _, field := range fields {
 | 
						|
		v := strings.Split(field, "=")
 | 
						|
		if len(v) != 2 {
 | 
						|
			return mount, fmt.Errorf("invalid mount specification: expected key=val")
 | 
						|
		}
 | 
						|
 | 
						|
		key := v[0]
 | 
						|
		val := v[1]
 | 
						|
		switch key {
 | 
						|
		case "type":
 | 
						|
			mount.Type = val
 | 
						|
		case "source", "src":
 | 
						|
			mount.Source = val
 | 
						|
		case "destination", "dst":
 | 
						|
			mount.Destination = val
 | 
						|
		case "options":
 | 
						|
			mount.Options = strings.Split(val, ":")
 | 
						|
		default:
 | 
						|
			return mount, fmt.Errorf("mount option %q not supported", key)
 | 
						|
		}
 | 
						|
	}
 | 
						|
 | 
						|
	return mount, nil
 | 
						|
}
 | 
						|
 | 
						|
// replaceOrAppendEnvValues returns the defaults with the overrides either
 | 
						|
// replaced by env key or appended to the list
 | 
						|
func replaceOrAppendEnvValues(defaults, overrides []string) []string {
 | 
						|
	cache := make(map[string]int, len(defaults))
 | 
						|
	for i, e := range defaults {
 | 
						|
		parts := strings.SplitN(e, "=", 2)
 | 
						|
		cache[parts[0]] = i
 | 
						|
	}
 | 
						|
 | 
						|
	for _, value := range overrides {
 | 
						|
		// Values w/o = means they want this env to be removed/unset.
 | 
						|
		if !strings.Contains(value, "=") {
 | 
						|
			if i, exists := cache[value]; exists {
 | 
						|
				defaults[i] = "" // Used to indicate it should be removed
 | 
						|
			}
 | 
						|
			continue
 | 
						|
		}
 | 
						|
 | 
						|
		// Just do a normal set/update
 | 
						|
		parts := strings.SplitN(value, "=", 2)
 | 
						|
		if i, exists := cache[parts[0]]; exists {
 | 
						|
			defaults[i] = value
 | 
						|
		} else {
 | 
						|
			defaults = append(defaults, value)
 | 
						|
		}
 | 
						|
	}
 | 
						|
 | 
						|
	// Now remove all entries that we want to "unset"
 | 
						|
	for i := 0; i < len(defaults); i++ {
 | 
						|
		if defaults[i] == "" {
 | 
						|
			defaults = append(defaults[:i], defaults[i+1:]...)
 | 
						|
			i--
 | 
						|
		}
 | 
						|
	}
 | 
						|
 | 
						|
	return defaults
 | 
						|
}
 |