Merge pull request #10369 from thaJeztah/cmd_no_alias

cmd: don't alias context package, and use cliContext for cli.Context
This commit is contained in:
Derek McGowan 2024-06-20 20:42:29 +00:00 committed by GitHub
commit 8b5c218e5a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
65 changed files with 754 additions and 755 deletions

View File

@ -187,13 +187,13 @@ func main() {
Value: "overlayfs",
},
}
app.Before = func(context *cli.Context) error {
if context.Bool("json") {
app.Before = func(cliContext *cli.Context) error {
if cliContext.Bool("json") {
if err := log.SetLevel("warn"); err != nil {
return err
}
}
if context.Bool("debug") {
if cliContext.Bool("debug") {
if err := log.SetLevel("debug"); err != nil {
return err
}
@ -203,18 +203,18 @@ func main() {
app.Commands = []*cli.Command{
densityCommand,
}
app.Action = func(context *cli.Context) error {
app.Action = func(cliContext *cli.Context) error {
config := config{
Address: context.String("address"),
Duration: context.Duration("duration"),
Concurrency: context.Int("concurrent"),
CRI: context.Bool("cri"),
Exec: context.Bool("exec"),
Image: context.String("image"),
JSON: context.Bool("json"),
Metrics: context.String("metrics"),
Runtime: context.String("runtime"),
Snapshotter: context.String("snapshotter"),
Address: cliContext.String("address"),
Duration: cliContext.Duration("duration"),
Concurrency: cliContext.Int("concurrent"),
CRI: cliContext.Bool("cri"),
Exec: cliContext.Bool("exec"),
Image: cliContext.String("image"),
JSON: cliContext.Bool("json"),
Metrics: cliContext.String("metrics"),
Runtime: cliContext.String("runtime"),
Snapshotter: cliContext.String("snapshotter"),
}
if config.Metrics != "" {
return serve(config)

View File

@ -17,7 +17,7 @@
package command
import (
gocontext "context"
"context"
"os"
"path/filepath"
@ -33,7 +33,7 @@ import (
"github.com/urfave/cli/v2"
)
func outputConfig(ctx gocontext.Context, config *srvconfig.Config) error {
func outputConfig(ctx context.Context, config *srvconfig.Config) error {
plugins, err := server.LoadPlugins(ctx, config)
if err != nil {
return err
@ -86,17 +86,17 @@ var configCommand = &cli.Command{
{
Name: "default",
Usage: "See the output of the default config",
Action: func(context *cli.Context) error {
return outputConfig(gocontext.Background(), defaultConfig())
Action: func(cliContext *cli.Context) error {
return outputConfig(context.Background(), defaultConfig())
},
},
{
Name: "dump",
Usage: "See the output of the final main config with imported in subconfig files",
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
config := defaultConfig()
ctx := gocontext.Background()
if err := srvconfig.LoadConfig(ctx, context.String("config"), config); err != nil && !os.IsNotExist(err) {
ctx := context.Background()
if err := srvconfig.LoadConfig(ctx, cliContext.String("config"), config); err != nil && !os.IsNotExist(err) {
return err
}
@ -106,10 +106,10 @@ var configCommand = &cli.Command{
{
Name: "migrate",
Usage: "Migrate the current configuration file to the latest version (does not migrate subconfig files)",
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
config := defaultConfig()
ctx := gocontext.Background()
if err := srvconfig.LoadConfig(ctx, context.String("config"), config); err != nil && !os.IsNotExist(err) {
ctx := context.Background()
if err := srvconfig.LoadConfig(ctx, cliContext.String("config"), config); err != nil && !os.IsNotExist(err) {
return err
}

View File

@ -17,7 +17,7 @@
package command
import (
gocontext "context"
"context"
"fmt"
"io"
"net"
@ -54,8 +54,8 @@ func init() {
// Discard grpc logs so that they don't mess with our stdio
grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard))
cli.VersionPrinter = func(c *cli.Context) {
fmt.Println(c.App.Name, version.Package, c.App.Version, version.Revision)
cli.VersionPrinter = func(cliContext *cli.Context) {
fmt.Println(cliContext.App.Name, version.Package, cliContext.App.Version, version.Revision)
}
cli.VersionFlag = &cli.BoolFlag{
Name: "version",
@ -118,12 +118,12 @@ can be used and modified as necessary as a custom configuration.`
publishCommand,
ociHook,
}
app.Action = func(context *cli.Context) error {
app.Action = func(cliContext *cli.Context) error {
var (
start = time.Now()
signals = make(chan os.Signal, 2048)
serverC = make(chan *server.Server, 1)
ctx, cancel = gocontext.WithCancel(gocontext.Background())
ctx, cancel = context.WithCancel(context.Background())
config = defaultConfig()
)
@ -131,16 +131,16 @@ can be used and modified as necessary as a custom configuration.`
// Only try to load the config if it either exists, or the user explicitly
// told us to load this path.
configPath := context.String("config")
configPath := cliContext.String("config")
_, err := os.Stat(configPath)
if !os.IsNotExist(err) || context.IsSet("config") {
if !os.IsNotExist(err) || cliContext.IsSet("config") {
if err := srvconfig.LoadConfig(ctx, configPath, config); err != nil {
return err
}
}
// Apply flags to the config
if err := applyFlags(context, config); err != nil {
if err := applyFlags(cliContext, config); err != nil {
return err
}
@ -303,7 +303,7 @@ can be used and modified as necessary as a custom configuration.`
return app
}
func serve(ctx gocontext.Context, l net.Listener, serveFunc func(net.Listener) error) {
func serve(ctx context.Context, l net.Listener, serveFunc func(net.Listener) error) {
path := l.Addr().String()
log.G(ctx).WithField("address", path).Info("serving...")
go func() {
@ -314,10 +314,10 @@ func serve(ctx gocontext.Context, l net.Listener, serveFunc func(net.Listener) e
}()
}
func applyFlags(context *cli.Context, config *srvconfig.Config) error {
func applyFlags(cliContext *cli.Context, config *srvconfig.Config) error {
// the order for config vs flag values is that flags will always override
// the config values if they are set
if err := setLogLevel(context, config); err != nil {
if err := setLogLevel(cliContext, config); err != nil {
return err
}
if err := setLogFormat(config); err != nil {
@ -341,7 +341,7 @@ func applyFlags(context *cli.Context, config *srvconfig.Config) error {
d: &config.GRPC.Address,
},
} {
if s := context.String(v.name); s != "" {
if s := cliContext.String(v.name); s != "" {
*v.d = s
if v.name == "root" || v.name == "state" {
absPath, err := filepath.Abs(s)
@ -353,13 +353,13 @@ func applyFlags(context *cli.Context, config *srvconfig.Config) error {
}
}
applyPlatformFlags(context)
applyPlatformFlags(cliContext)
return nil
}
func setLogLevel(context *cli.Context, config *srvconfig.Config) error {
l := context.String("log-level")
func setLogLevel(cliContext *cli.Context, config *srvconfig.Config) error {
l := cliContext.String("log-level")
if l == "" {
l = config.Debug.Level
}

View File

@ -33,7 +33,7 @@ import (
var ociHook = &cli.Command{
Name: "oci-hook",
Usage: "Provides a base for OCI runtime hooks to allow arguments to be injected.",
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
state, err := loadHookState(os.Stdin)
if err != nil {
return err
@ -45,7 +45,7 @@ var ociHook = &cli.Command{
}
var (
ctx = newTemplateContext(state, spec)
args = context.Args().Slice()
args = cliContext.Args().Slice()
env = os.Environ()
)
if err := newList(&args).render(ctx); err != nil {

View File

@ -17,7 +17,7 @@
package command
import (
gocontext "context"
"context"
"fmt"
"io"
"net"
@ -49,9 +49,9 @@ var publishCommand = &cli.Command{
Usage: "Topic of the event",
},
},
Action: func(context *cli.Context) error {
ctx := namespaces.WithNamespace(gocontext.Background(), context.String("namespace"))
topic := context.String("topic")
Action: func(cliContext *cli.Context) error {
ctx := namespaces.WithNamespace(context.Background(), cliContext.String("namespace"))
topic := cliContext.String("topic")
if topic == "" {
return fmt.Errorf("topic required to publish event: %w", errdefs.ErrInvalidArgument)
}
@ -59,7 +59,7 @@ var publishCommand = &cli.Command{
if err != nil {
return err
}
client, err := connectEvents(context.String("address"))
client, err := connectEvents(cliContext.String("address"))
if err != nil {
return err
}
@ -93,7 +93,7 @@ func connectEvents(address string) (eventsapi.EventsClient, error) {
return eventsapi.NewEventsClient(conn), nil
}
func connect(address string, d func(gocontext.Context, string) (net.Conn, error)) (*grpc.ClientConn, error) {
func connect(address string, d func(context.Context, string) (net.Conn, error)) (*grpc.ClientConn, error) {
backoffConfig := backoff.DefaultConfig
backoffConfig.MaxDelay = 3 * time.Second
connParams := grpc.ConnectParams{
@ -106,7 +106,7 @@ func connect(address string, d func(gocontext.Context, string) (net.Conn, error)
grpc.FailOnNonTempDialError(true),
grpc.WithConnectParams(connParams),
}
ctx, cancel := gocontext.WithTimeout(gocontext.Background(), 2*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, dialer.DialAddress(address), gopts...)
if err != nil {

View File

@ -30,7 +30,7 @@ func serviceFlags() []cli.Flag {
}
// applyPlatformFlags applies platform-specific flags.
func applyPlatformFlags(context *cli.Context) {
func applyPlatformFlags(cliContext *cli.Context) {
}
// registerUnregisterService is only relevant on Windows.

View File

@ -79,8 +79,8 @@ func serviceFlags() []cli.Flag {
}
// applyPlatformFlags applies platform-specific flags.
func applyPlatformFlags(context *cli.Context) {
serviceNameFlag = context.String("service-name")
func applyPlatformFlags(cliContext *cli.Context) {
serviceNameFlag = cliContext.String("service-name")
if serviceNameFlag == "" {
serviceNameFlag = defaultServiceName
}
@ -101,9 +101,9 @@ func applyPlatformFlags(context *cli.Context) {
d: &runServiceFlag,
},
} {
*v.d = context.Bool(v.name)
*v.d = cliContext.Bool(v.name)
}
logFileFlag = context.String("log-file")
logFileFlag = cliContext.String("log-file")
}
type handler struct {

View File

@ -52,8 +52,8 @@ func init() {
// Discard grpc logs so that they don't mess with our stdio
grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, io.Discard))
cli.VersionPrinter = func(c *cli.Context) {
fmt.Println(c.App.Name, version.Package, c.App.Version)
cli.VersionPrinter = func(cliContext *cli.Context) {
fmt.Println(cliContext.App.Name, version.Package, cliContext.App.Version)
}
cli.VersionFlag = &cli.BoolFlag{
Name: "version",
@ -135,8 +135,8 @@ containerd CLI
info.Command,
deprecations.Command,
}, extraCmds...)
app.Before = func(context *cli.Context) error {
if context.Bool("debug") {
app.Before = func(cliContext *cli.Context) error {
if cliContext.Bool("debug") {
return log.SetLevel("debug")
}
return nil

View File

@ -17,7 +17,7 @@
package commands
import (
gocontext "context"
"context"
"os"
"strconv"
@ -33,18 +33,18 @@ import (
//
// This will ensure the namespace is picked up and set the timeout, if one is
// defined.
func AppContext(context *cli.Context) (gocontext.Context, gocontext.CancelFunc) {
func AppContext(cliContext *cli.Context) (context.Context, context.CancelFunc) {
var (
ctx = gocontext.Background()
timeout = context.Duration("timeout")
namespace = context.String("namespace")
cancel gocontext.CancelFunc
ctx = context.Background()
timeout = cliContext.Duration("timeout")
namespace = cliContext.String("namespace")
cancel context.CancelFunc
)
ctx = namespaces.WithNamespace(ctx, namespace)
if timeout > 0 {
ctx, cancel = gocontext.WithTimeout(ctx, timeout)
ctx, cancel = context.WithTimeout(ctx, timeout)
} else {
ctx, cancel = gocontext.WithCancel(ctx)
ctx, cancel = context.WithCancel(ctx)
}
if tm, err := epoch.SourceDateEpoch(); err != nil {
log.L.WithError(err).Warn("Failed to read SOURCE_DATE_EPOCH")
@ -56,14 +56,14 @@ func AppContext(context *cli.Context) (gocontext.Context, gocontext.CancelFunc)
}
// NewClient returns a new containerd client
func NewClient(context *cli.Context, opts ...containerd.Opt) (*containerd.Client, gocontext.Context, gocontext.CancelFunc, error) {
timeoutOpt := containerd.WithTimeout(context.Duration("connect-timeout"))
func NewClient(cliContext *cli.Context, opts ...containerd.Opt) (*containerd.Client, context.Context, context.CancelFunc, error) {
timeoutOpt := containerd.WithTimeout(cliContext.Duration("connect-timeout"))
opts = append(opts, timeoutOpt)
client, err := containerd.New(context.String("address"), opts...)
client, err := containerd.New(cliContext.String("address"), opts...)
if err != nil {
return nil, nil, nil, err
}
ctx, cancel := AppContext(context)
ctx, cancel := AppContext(cliContext)
var suppressDeprecationWarnings bool
if s := os.Getenv("CONTAINERD_SUPPRESS_DEPRECATION_WARNINGS"); s != "" {
suppressDeprecationWarnings, err = strconv.ParseBool(s)

View File

@ -232,10 +232,10 @@ var (
)
// ObjectWithLabelArgs returns the first arg and a LabelArgs object
func ObjectWithLabelArgs(clicontext *cli.Context) (string, map[string]string) {
func ObjectWithLabelArgs(cliContext *cli.Context) (string, map[string]string) {
var (
first = clicontext.Args().First()
labelStrings = clicontext.Args().Tail()
first = cliContext.Args().First()
labelStrings = cliContext.Args().Tail()
)
return first, LabelArgs(labelStrings)

View File

@ -59,37 +59,37 @@ func init() {
})
}
func getRuncOptions(context *cli.Context) (*options.Options, error) {
func getRuncOptions(cliContext *cli.Context) (*options.Options, error) {
runtimeOpts := &options.Options{}
if runcBinary := context.String("runc-binary"); runcBinary != "" {
if runcBinary := cliContext.String("runc-binary"); runcBinary != "" {
runtimeOpts.BinaryName = runcBinary
}
if context.Bool("runc-systemd-cgroup") {
if context.String("cgroup") == "" {
if cliContext.Bool("runc-systemd-cgroup") {
if cliContext.String("cgroup") == "" {
// runc maps "machine.slice:foo:deadbeef" to "/machine.slice/foo-deadbeef.scope"
return nil, errors.New("option --runc-systemd-cgroup requires --cgroup to be set, e.g. \"machine.slice:foo:deadbeef\"")
}
runtimeOpts.SystemdCgroup = true
}
if root := context.String("runc-root"); root != "" {
if root := cliContext.String("runc-root"); root != "" {
runtimeOpts.Root = root
}
return runtimeOpts, nil
}
func RuntimeOptions(context *cli.Context) (interface{}, error) {
func RuntimeOptions(cliContext *cli.Context) (interface{}, error) {
// validate first
if (context.String("runc-binary") != "" || context.Bool("runc-systemd-cgroup")) &&
context.String("runtime") != "io.containerd.runc.v2" {
if (cliContext.String("runc-binary") != "" || cliContext.Bool("runc-systemd-cgroup")) &&
cliContext.String("runtime") != "io.containerd.runc.v2" {
return nil, errors.New("specifying runc-binary and runc-systemd-cgroup is only supported for \"io.containerd.runc.v2\" runtime")
}
if context.String("runtime") == "io.containerd.runc.v2" {
return getRuncOptions(context)
if cliContext.String("runtime") == "io.containerd.runc.v2" {
return getRuncOptions(cliContext)
}
if configPath := context.String("runtime-config-path"); configPath != "" {
if configPath := cliContext.String("runtime-config-path"); configPath != "" {
return &runtimeoptions.Options{
ConfigPath: configPath,
}, nil

View File

@ -37,6 +37,6 @@ func init() {
})
}
func RuntimeOptions(context *cli.Context) (interface{}, error) {
func RuntimeOptions(cliContext *cli.Context) (interface{}, error) {
return nil, nil
}

View File

@ -44,16 +44,16 @@ var checkpointCommand = &cli.Command{
Usage: "Checkpoint container task",
},
},
Action: func(context *cli.Context) error {
id := context.Args().First()
Action: func(cliContext *cli.Context) error {
id := cliContext.Args().First()
if id == "" {
return errors.New("container id must be provided")
}
ref := context.Args().Get(1)
ref := cliContext.Args().Get(1)
if ref == "" {
return errors.New("ref must be provided")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -62,13 +62,13 @@ var checkpointCommand = &cli.Command{
containerd.WithCheckpointRuntime,
}
if context.Bool("image") {
if cliContext.Bool("image") {
opts = append(opts, containerd.WithCheckpointImage)
}
if context.Bool("rw") {
if cliContext.Bool("rw") {
opts = append(opts, containerd.WithCheckpointRW)
}
if context.Bool("task") {
if cliContext.Bool("task") {
opts = append(opts, containerd.WithCheckpointTask)
}
container, err := client.LoadContainer(ctx, id)

View File

@ -55,21 +55,21 @@ var createCommand = &cli.Command{
Usage: "Create container",
ArgsUsage: "[flags] Image|RootFS CONTAINER [COMMAND] [ARG...]",
Flags: append(commands.RuntimeFlags, append(append(commands.SnapshotterFlags, []cli.Flag{commands.SnapshotterLabels}...), commands.ContainerFlags...)...),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
id string
ref string
config = context.IsSet("config")
config = cliContext.IsSet("config")
)
if config {
id = context.Args().First()
if context.NArg() > 1 {
id = cliContext.Args().First()
if cliContext.NArg() > 1 {
return fmt.Errorf("with spec config file, only container id should be provided: %w", errdefs.ErrInvalidArgument)
}
} else {
id = context.Args().Get(1)
ref = context.Args().First()
id = cliContext.Args().Get(1)
ref = cliContext.Args().First()
if ref == "" {
return fmt.Errorf("image ref must be provided: %w", errdefs.ErrInvalidArgument)
}
@ -77,12 +77,12 @@ var createCommand = &cli.Command{
if id == "" {
return fmt.Errorf("container id must be provided: %w", errdefs.ErrInvalidArgument)
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
_, err = run.NewContainer(ctx, client, context)
_, err = run.NewContainer(ctx, client, cliContext)
if err != nil {
return err
}
@ -102,12 +102,12 @@ var listCommand = &cli.Command{
Usage: "Print only the container id",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
filters = context.Args().Slice()
quiet = context.Bool("quiet")
filters = cliContext.Args().Slice()
quiet = cliContext.Bool("quiet")
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -156,22 +156,22 @@ var deleteCommand = &cli.Command{
Usage: "Do not clean up snapshot with container",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var exitErr error
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
deleteOpts := []containerd.DeleteOpts{}
if !context.Bool("keep-snapshot") {
if !cliContext.Bool("keep-snapshot") {
deleteOpts = append(deleteOpts, containerd.WithSnapshotCleanup)
}
if context.NArg() == 0 {
if cliContext.NArg() == 0 {
return fmt.Errorf("must specify at least one container to delete: %w", errdefs.ErrInvalidArgument)
}
for _, arg := range context.Args().Slice() {
for _, arg := range cliContext.Args().Slice() {
if err := deleteContainer(ctx, client, arg, deleteOpts...); err != nil {
if exitErr == nil {
exitErr = err
@ -212,12 +212,12 @@ var setLabelsCommand = &cli.Command{
ArgsUsage: "[flags] CONTAINER [<key>=<value>, ...]",
Description: "set and clear labels for a container",
Flags: []cli.Flag{},
Action: func(context *cli.Context) error {
containerID, labels := commands.ObjectWithLabelArgs(context)
Action: func(cliContext *cli.Context) error {
containerID, labels := commands.ObjectWithLabelArgs(cliContext)
if containerID == "" {
return fmt.Errorf("container id must be provided: %w", errdefs.ErrInvalidArgument)
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -254,12 +254,12 @@ var infoCommand = &cli.Command{
Usage: "Only display the spec",
},
},
Action: func(context *cli.Context) error {
id := context.Args().First()
Action: func(cliContext *cli.Context) error {
id := cliContext.Args().First()
if id == "" {
return fmt.Errorf("container id must be provided: %w", errdefs.ErrInvalidArgument)
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -272,7 +272,7 @@ var infoCommand = &cli.Command{
if err != nil {
return err
}
if context.Bool("spec") {
if cliContext.Bool("spec") {
v, err := typeurl.UnmarshalAny(info.Spec)
if err != nil {
return err

View File

@ -43,16 +43,16 @@ var restoreCommand = &cli.Command{
Usage: "Restore the runtime and memory data from the checkpoint",
},
},
Action: func(context *cli.Context) error {
id := context.Args().First()
Action: func(cliContext *cli.Context) error {
id := cliContext.Args().First()
if id == "" {
return errors.New("container id must be provided")
}
ref := context.Args().Get(1)
ref := cliContext.Args().Get(1)
if ref == "" {
return errors.New("ref must be provided")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -76,7 +76,7 @@ var restoreCommand = &cli.Command{
containerd.WithRestoreSpec,
containerd.WithRestoreRuntime,
}
if context.Bool("rw") {
if cliContext.Bool("rw") {
opts = append(opts, containerd.WithRestoreRW)
}
@ -85,7 +85,7 @@ var restoreCommand = &cli.Command{
return err
}
topts := []containerd.NewTaskOpts{}
if context.Bool("live") {
if cliContext.Bool("live") {
topts = append(topts, containerd.WithTaskCheckpoint(checkpoint))
}
spec, err := ctr.Spec(ctx)

View File

@ -64,12 +64,12 @@ var (
Usage: "Get the data for an object",
ArgsUsage: "[<digest>, ...]",
Description: "display the image object",
Action: func(context *cli.Context) error {
dgst, err := digest.Parse(context.Args().First())
Action: func(cliContext *cli.Context) error {
dgst, err := digest.Parse(cliContext.Args().First())
if err != nil {
return err
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -103,11 +103,11 @@ var (
Usage: "Verify content against expected digest",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = context.Args().First()
expectedSize = context.Int64("expected-size")
expectedDigest = digest.Digest(context.String("expected-digest"))
ref = cliContext.Args().First()
expectedSize = cliContext.Int64("expected-size")
expectedDigest = digest.Digest(cliContext.String("expected-digest"))
)
if err := expectedDigest.Validate(); expectedDigest != "" && err != nil {
return err
@ -115,7 +115,7 @@ var (
if ref == "" {
return errors.New("must specify a transaction reference")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -148,9 +148,9 @@ var (
Value: "/tmp/content", // TODO(stevvooe): for now, just use the PWD/.content
},
},
Action: func(context *cli.Context) error {
match := context.Args().First()
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
match := cliContext.Args().First()
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -186,12 +186,12 @@ var (
Usage: "Print only the blob digest",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
quiet = context.Bool("quiet")
args = context.Args().Slice()
quiet = cliContext.Bool("quiet")
args = cliContext.Args().Slice()
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -239,9 +239,9 @@ var (
Usage: "Add labels to content",
ArgsUsage: "<digest> [<label>=<value> ...]",
Description: "labels blobs in the content store",
Action: func(context *cli.Context) error {
object, labels := commands.ObjectWithLabelArgs(context)
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
object, labels := commands.ObjectWithLabelArgs(cliContext)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -304,10 +304,10 @@ var (
EnvVars: []string{"EDITOR"},
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
validate = context.String("validate")
object = context.Args().First()
validate = cliContext.String("validate")
object = cliContext.Args().First()
)
if validate != "" {
@ -321,7 +321,7 @@ var (
if err != nil {
return err
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -333,7 +333,7 @@ var (
}
defer ra.Close()
nrc, err := edit(context, content.NewReader(ra))
nrc, err := edit(cliContext, content.NewReader(ra))
if err != nil {
return err
}
@ -364,12 +364,12 @@ var (
ArgsUsage: "[<digest>, ...]",
Description: `Delete one or more blobs permanently. Successfully deleted
blobs are printed to stdout.`,
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
args = context.Args().Slice()
args = cliContext.Args().Slice()
exitError error
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -412,14 +412,14 @@ var (
ArgsUsage: "[flags] <remote> <object> [<hint>, ...]",
Description: `Fetch objects by identifier from a remote.`,
Flags: commands.RegistryFlags,
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = context.Args().First()
ref = cliContext.Args().First()
)
ctx, cancel := commands.AppContext(context)
ctx, cancel := commands.AppContext(cliContext)
defer cancel()
resolver, err := commands.GetResolver(ctx, context)
resolver, err := commands.GetResolver(ctx, cliContext)
if err != nil {
return err
}
@ -459,18 +459,18 @@ var (
Usage: "Specify target mediatype for request header",
},
}...),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = context.Args().First()
digests = context.Args().Tail()
ref = cliContext.Args().First()
digests = cliContext.Args().Tail()
)
if len(digests) == 0 {
return errors.New("must specify digests")
}
ctx, cancel := commands.AppContext(context)
ctx, cancel := commands.AppContext(cliContext)
defer cancel()
resolver, err := commands.GetResolver(ctx, context)
resolver, err := commands.GetResolver(ctx, cliContext)
if err != nil {
return err
}
@ -493,7 +493,7 @@ var (
if err != nil {
return err
}
rc, desc, err := fetcherByDigest.FetchByDigest(ctx, dgst, remotes.WithMediaType(context.String("media-type")))
rc, desc, err := fetcherByDigest.FetchByDigest(ctx, dgst, remotes.WithMediaType(cliContext.String("media-type")))
if err != nil {
return err
}
@ -514,23 +514,23 @@ var (
ArgsUsage: "[flags] <remote> <object> <type>",
Description: `Push objects by identifier to a remote.`,
Flags: commands.RegistryFlags,
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = context.Args().Get(0)
object = context.Args().Get(1)
media = context.Args().Get(2)
ref = cliContext.Args().Get(0)
object = cliContext.Args().Get(1)
media = cliContext.Args().Get(2)
)
dgst, err := digest.Parse(object)
if err != nil {
return err
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
resolver, err := commands.GetResolver(ctx, context)
resolver, err := commands.GetResolver(ctx, cliContext)
if err != nil {
return err
}
@ -578,8 +578,8 @@ var (
}
)
func edit(context *cli.Context, rd io.Reader) (_ io.ReadCloser, retErr error) {
editor := context.String("editor")
func edit(cliContext *cli.Context, rd io.Reader) (_ io.ReadCloser, retErr error) {
editor := cliContext.String("editor")
if editor == "" {
return nil, errors.New("editor is required")
}

View File

@ -81,16 +81,16 @@ Most of this is experimental and there are few leaps to make this work.`,
Usage: "Pull all metadata including manifests and configs",
},
),
Action: func(clicontext *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = clicontext.Args().First()
ref = cliContext.Args().First()
)
client, ctx, cancel, err := commands.NewClient(clicontext)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
config, err := NewFetchConfig(ctx, clicontext)
config, err := NewFetchConfig(ctx, cliContext)
if err != nil {
return err
}
@ -121,42 +121,42 @@ type FetchConfig struct {
}
// NewFetchConfig returns the default FetchConfig from cli flags
func NewFetchConfig(ctx context.Context, clicontext *cli.Context) (*FetchConfig, error) {
resolver, err := commands.GetResolver(ctx, clicontext)
func NewFetchConfig(ctx context.Context, cliContext *cli.Context) (*FetchConfig, error) {
resolver, err := commands.GetResolver(ctx, cliContext)
if err != nil {
return nil, err
}
config := &FetchConfig{
Resolver: resolver,
Labels: clicontext.StringSlice("label"),
TraceHTTP: clicontext.Bool("http-trace"),
Labels: cliContext.StringSlice("label"),
TraceHTTP: cliContext.Bool("http-trace"),
}
if !clicontext.Bool("debug") {
if !cliContext.Bool("debug") {
config.ProgressOutput = os.Stdout
}
if !clicontext.Bool("all-platforms") {
p := clicontext.StringSlice("platform")
if !cliContext.Bool("all-platforms") {
p := cliContext.StringSlice("platform")
if len(p) == 0 {
p = append(p, platforms.DefaultString())
}
config.Platforms = p
}
if clicontext.Bool("metadata-only") {
if cliContext.Bool("metadata-only") {
config.AllMetadata = true
// Any with an empty set is None
config.PlatformMatcher = platforms.Any()
} else if !clicontext.Bool("skip-metadata") {
} else if !cliContext.Bool("skip-metadata") {
config.AllMetadata = true
}
if clicontext.IsSet("max-concurrent-downloads") {
mcd := clicontext.Int("max-concurrent-downloads")
if cliContext.IsSet("max-concurrent-downloads") {
mcd := cliContext.Int("max-concurrent-downloads")
config.RemoteOpts = append(config.RemoteOpts, containerd.WithMaxConcurrentDownloads(mcd))
}
if clicontext.IsSet("max-concurrent-uploaded-layers") {
mcu := clicontext.Int("max-concurrent-uploaded-layers")
if cliContext.IsSet("max-concurrent-uploaded-layers") {
mcu := cliContext.Int("max-concurrent-uploaded-layers")
config.RemoteOpts = append(config.RemoteOpts, containerd.WithMaxConcurrentUploadedLayers(mcu))
}

View File

@ -56,21 +56,21 @@ var pruneReferencesCommand = &cli.Command{
Name: "references",
Usage: "Prunes preference labels from the content store (layers only by default)",
Flags: pruneFlags,
Action: func(clicontext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(clicontext)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
dryRun := clicontext.Bool("dry")
dryRun := cliContext.Bool("dry")
if dryRun {
log.G(ctx).Logger.SetLevel(log.DebugLevel)
log.G(ctx).Debug("dry run, no changes will be applied")
}
var deleteOpts []leases.DeleteOpt
if !clicontext.Bool("async") {
if !cliContext.Bool("async") {
deleteOpts = append(deleteOpts, leases.SynchronousDelete)
}

View File

@ -45,11 +45,11 @@ var listCommand = &cli.Command{
Usage: "output format to use (Examples: 'default', 'json')",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
// Suppress automatic warnings, since we print the warnings by ourselves.
os.Setenv("CONTAINERD_SUPPRESS_DEPRECATION_WARNINGS", "1")
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -61,7 +61,7 @@ var listCommand = &cli.Command{
}
wrn := warnings(resp)
if len(wrn) > 0 {
switch context.String("format") {
switch cliContext.String("format") {
case "json":
commands.PrintAsJSON(warnings(resp))
return nil

View File

@ -35,14 +35,14 @@ var Command = &cli.Command{
Name: "events",
Aliases: []string{"event"},
Usage: "Display containerd events",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
eventsClient := client.EventService()
eventsCh, errCh := eventsClient.Subscribe(ctx, context.Args().Slice()...)
eventsCh, errCh := eventsClient.Subscribe(ctx, cliContext.Args().Slice()...)
for {
var e *events.Envelope
select {

View File

@ -59,16 +59,16 @@ When '--all-platforms' is given all images in a manifest list must be available.
Usage: "Exports content from all platforms",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var convertOpts []converter.Opt
srcRef := context.Args().Get(0)
targetRef := context.Args().Get(1)
srcRef := cliContext.Args().Get(0)
targetRef := cliContext.Args().Get(1)
if srcRef == "" || targetRef == "" {
return errors.New("src and target image need to be specified")
}
if !context.Bool("all-platforms") {
if pss := context.StringSlice("platform"); len(pss) > 0 {
if !cliContext.Bool("all-platforms") {
if pss := cliContext.StringSlice("platform"); len(pss) > 0 {
all, err := platforms.ParseAll(pss)
if err != nil {
return err
@ -79,15 +79,15 @@ When '--all-platforms' is given all images in a manifest list must be available.
}
}
if context.Bool("uncompress") {
if cliContext.Bool("uncompress") {
convertOpts = append(convertOpts, converter.WithLayerConvertFunc(uncompress.LayerConvertFunc))
}
if context.Bool("oci") {
if cliContext.Bool("oci") {
convertOpts = append(convertOpts, converter.WithDockerToOCI(true))
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -97,7 +97,7 @@ When '--all-platforms' is given all images in a manifest list must be available.
if err != nil {
return err
}
fmt.Fprintln(context.App.Writer, newImg.Target.Digest.String())
fmt.Fprintln(cliContext.App.Writer, newImg.Target.Digest.String())
return nil
},
}

View File

@ -66,17 +66,17 @@ When '--all-platforms' is given all images in a manifest list must be available.
Usage: "Run export locally rather than through transfer API",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
out = context.Args().First()
images = context.Args().Tail()
out = cliContext.Args().First()
images = cliContext.Args().Tail()
exportOpts = []archive.ExportOpt{}
)
if out == "" || len(images) == 0 {
return errors.New("please provide both an output filename and an image reference to export")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -93,12 +93,12 @@ When '--all-platforms' is given all images in a manifest list must be available.
}
defer w.Close()
if !context.Bool("local") {
if !cliContext.Bool("local") {
pf, done := ProgressHandler(ctx, os.Stdout)
defer done()
exportOpts := []tarchive.ExportOpt{}
if pss := context.StringSlice("platform"); len(pss) > 0 {
if pss := cliContext.StringSlice("platform"); len(pss) > 0 {
for _, ps := range pss {
p, err := platforms.Parse(ps)
if err != nil {
@ -107,15 +107,15 @@ When '--all-platforms' is given all images in a manifest list must be available.
exportOpts = append(exportOpts, tarchive.WithPlatform(p))
}
}
if context.Bool("all-platforms") {
if cliContext.Bool("all-platforms") {
exportOpts = append(exportOpts, tarchive.WithAllPlatforms)
}
if context.Bool("skip-manifest-json") {
if cliContext.Bool("skip-manifest-json") {
exportOpts = append(exportOpts, tarchive.WithSkipCompatibilityManifest)
}
if context.Bool("skip-non-distributable") {
if cliContext.Bool("skip-non-distributable") {
exportOpts = append(exportOpts, tarchive.WithSkipNonDistributableBlobs)
}
@ -131,7 +131,7 @@ When '--all-platforms' is given all images in a manifest list must be available.
)
}
if pss := context.StringSlice("platform"); len(pss) > 0 {
if pss := cliContext.StringSlice("platform"); len(pss) > 0 {
all, err := platforms.ParseAll(pss)
if err != nil {
return err
@ -141,15 +141,15 @@ When '--all-platforms' is given all images in a manifest list must be available.
exportOpts = append(exportOpts, archive.WithPlatform(platforms.DefaultStrict()))
}
if context.Bool("all-platforms") {
if cliContext.Bool("all-platforms") {
exportOpts = append(exportOpts, archive.WithAllPlatforms())
}
if context.Bool("skip-manifest-json") {
if cliContext.Bool("skip-manifest-json") {
exportOpts = append(exportOpts, archive.WithSkipDockerManifest())
}
if context.Bool("skip-non-distributable") {
if cliContext.Bool("skip-non-distributable") {
exportOpts = append(exportOpts, archive.WithSkipNonDistributableBlobs())
}

View File

@ -70,12 +70,12 @@ var listCommand = &cli.Command{
Usage: "Print only the image refs",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
filters = context.Args().Slice()
quiet = context.Bool("quiet")
filters = cliContext.Args().Slice()
quiet = cliContext.Bool("quiet")
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -154,12 +154,12 @@ var setLabelsCommand = &cli.Command{
Usage: "Replace all labels",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
replaceAll = context.Bool("replace-all")
name, labels = commands.ObjectWithLabelArgs(context)
replaceAll = cliContext.Bool("replace-all")
name, labels = commands.ObjectWithLabelArgs(cliContext)
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -214,12 +214,12 @@ var checkCommand = &cli.Command{
Usage: "Print only the ready image refs (fully downloaded and unpacked)",
},
}, commands.SnapshotterFlags...),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
exitErr error
quiet = context.Bool("quiet")
quiet = cliContext.Bool("quiet")
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -227,7 +227,7 @@ var checkCommand = &cli.Command{
var contentStore = client.ContentStore()
args := context.Args().Slice()
args := cliContext.Args().Slice()
imageList, err := client.ListImages(ctx, args...)
if err != nil {
return fmt.Errorf("failed listing images: %w", err)
@ -287,7 +287,7 @@ var checkCommand = &cli.Command{
size = "-"
}
unpacked, err := image.IsUnpacked(ctx, context.String("snapshotter"))
unpacked, err := image.IsUnpacked(ctx, cliContext.String("snapshotter"))
if err != nil {
if exitErr == nil {
exitErr = fmt.Errorf("unable to check unpack for %v: %w", image.Name(), err)
@ -328,8 +328,8 @@ var removeCommand = &cli.Command{
Usage: "Synchronously remove image and all associated resources",
},
},
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -338,9 +338,9 @@ var removeCommand = &cli.Command{
exitErr error
imageStore = client.ImageService()
)
for i, target := range context.Args().Slice() {
for i, target := range cliContext.Args().Slice() {
var opts []images.DeleteOpt
if context.Bool("sync") && i == context.NArg()-1 {
if cliContext.Bool("sync") && i == cliContext.NArg()-1 {
opts = append(opts, images.SynchronousDelete())
}
if err := imageStore.Delete(ctx, target, opts...); err != nil {
@ -373,14 +373,14 @@ var pruneCommand = &cli.Command{
},
// adapted from `nerdctl`:
// https://github.com/containerd/nerdctl/blob/272dc9c29fc1434839d3ec63194d7efa24d7c0ef/cmd/nerdctl/image_prune.go#L86
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
all := context.Bool("all")
all := cliContext.Bool("all")
if !all {
log.G(ctx).Warn("No images pruned. `image prune` requires --all to be specified.")
// NOP

View File

@ -101,28 +101,28 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
},
}, append(commands.SnapshotterFlags, commands.LabelFlag)...),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
in = context.Args().First()
in = cliContext.Args().First()
opts []containerd.ImportOpt
platformMatcher platforms.MatchComparer
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
if !context.Bool("local") {
if !cliContext.Bool("local") {
unsupportedFlags := []string{"discard-unpacked-layers"}
for _, s := range unsupportedFlags {
if context.IsSet(s) {
if cliContext.IsSet(s) {
return fmt.Errorf("\"--%s\" requires \"--local\" flag", s)
}
}
var opts []image.StoreOpt
prefix := context.String("base-name")
prefix := cliContext.String("base-name")
var overwrite bool
if prefix == "" {
prefix = fmt.Sprintf("import-%s", time.Now().Format("2006-01-02"))
@ -130,13 +130,13 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
overwrite = true
}
labels := context.StringSlice("label")
labels := cliContext.StringSlice("label")
if len(labels) > 0 {
opts = append(opts, image.WithImageLabels(commands.LabelArgs(labels)))
}
if context.Bool("digests") {
opts = append(opts, image.WithDigestRef(prefix, overwrite, !context.Bool("skip-digest-for-named")))
if cliContext.Bool("digests") {
opts = append(opts, image.WithDigestRef(prefix, overwrite, !cliContext.Bool("skip-digest-for-named")))
} else {
opts = append(opts, image.WithNamedPrefix(prefix, overwrite))
}
@ -144,9 +144,9 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
var platSpec ocispec.Platform
// Only when all-platforms not specified, we will check platform value
// Implicitly if the platforms is empty, it means all-platforms
if !context.Bool("all-platforms") {
if !cliContext.Bool("all-platforms") {
// If platform specified, use that one, if not use default
if platform := context.String("platform"); platform != "" {
if platform := cliContext.String("platform"); platform != "" {
platSpec, err = platforms.Parse(platform)
if err != nil {
return err
@ -157,8 +157,8 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
opts = append(opts, image.WithPlatforms(platSpec))
}
if !context.Bool("no-unpack") {
snapshotter := context.String("snapshotter")
if !cliContext.Bool("no-unpack") {
snapshotter := cliContext.String("snapshotter")
// If OS field is not empty, it means platSpec was updated in the above block
// i.e all-platforms was not specified
if platSpec.OS != "" {
@ -170,11 +170,11 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
}
}
is := image.NewStore(context.String("index-name"), opts...)
is := image.NewStore(cliContext.String("index-name"), opts...)
var iopts []tarchive.ImportOpt
if context.Bool("compress-blobs") {
if cliContext.Bool("compress-blobs") {
iopts = append(iopts, tarchive.WithForceCompression)
}
@ -204,7 +204,7 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
// Local logic
prefix := context.String("base-name")
prefix := cliContext.String("base-name")
if prefix == "" {
prefix = fmt.Sprintf("import-%s", time.Now().Format("2006-01-02"))
opts = append(opts, containerd.WithImageRefTranslator(archive.AddRefPrefix(prefix)))
@ -213,25 +213,25 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
opts = append(opts, containerd.WithImageRefTranslator(archive.FilterRefPrefix(prefix)))
}
if context.Bool("digests") {
if cliContext.Bool("digests") {
opts = append(opts, containerd.WithDigestRef(archive.DigestTranslator(prefix)))
}
if context.Bool("skip-digest-for-named") {
if !context.Bool("digests") {
if cliContext.Bool("skip-digest-for-named") {
if !cliContext.Bool("digests") {
return errors.New("--skip-digest-for-named must be specified with --digests option")
}
opts = append(opts, containerd.WithSkipDigestRef(func(name string) bool { return name != "" }))
}
if idxName := context.String("index-name"); idxName != "" {
if idxName := cliContext.String("index-name"); idxName != "" {
opts = append(opts, containerd.WithIndexName(idxName))
}
if context.Bool("compress-blobs") {
if cliContext.Bool("compress-blobs") {
opts = append(opts, containerd.WithImportCompression())
}
if platform := context.String("platform"); platform != "" {
if platform := cliContext.String("platform"); platform != "" {
platSpec, err := platforms.Parse(platform)
if err != nil {
return err
@ -240,16 +240,16 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
opts = append(opts, containerd.WithImportPlatform(platformMatcher))
}
opts = append(opts, containerd.WithAllPlatforms(context.Bool("all-platforms")))
opts = append(opts, containerd.WithAllPlatforms(cliContext.Bool("all-platforms")))
if context.Bool("discard-unpacked-layers") {
if context.Bool("no-unpack") {
if cliContext.Bool("discard-unpacked-layers") {
if cliContext.Bool("no-unpack") {
return errors.New("--discard-unpacked-layers and --no-unpack are incompatible options")
}
opts = append(opts, containerd.WithDiscardUnpackedLayers())
}
labels := context.StringSlice("label")
labels := cliContext.StringSlice("label")
if len(labels) > 0 {
opts = append(opts, containerd.WithImageLabels(commands.LabelArgs(labels)))
}
@ -279,7 +279,7 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
return closeErr
}
if !context.Bool("no-unpack") {
if !cliContext.Bool("no-unpack") {
log.G(ctx).Debugf("unpacking %d images", len(imgs))
for _, img := range imgs {
@ -290,7 +290,7 @@ If foobar.tar contains an OCI ref named "latest" and anonymous ref "sha256:deadb
// TODO: Show unpack status
fmt.Printf("unpacking %s (%s)...", img.Name, img.Target.Digest)
err = image.Unpack(ctx, context.String("snapshotter"))
err = image.Unpack(ctx, cliContext.String("snapshotter"))
if err != nil {
return err
}

View File

@ -36,14 +36,14 @@ var inspectCommand = &cli.Command{
Usage: "Show JSON content",
},
},
Action: func(clicontext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(clicontext)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
var (
ref = clicontext.Args().First()
ref = cliContext.Args().First()
imageStore = client.ImageService()
cs = client.ContentStore()
)
@ -56,7 +56,7 @@ var inspectCommand = &cli.Command{
opts := []display.PrintOpt{
display.WithWriter(os.Stdout),
}
if clicontext.Bool("content") {
if cliContext.Bool("content") {
opts = append(opts, display.Verbose)
}

View File

@ -51,10 +51,10 @@ When you are done, use the unmount command.
Value: platforms.DefaultString(),
},
),
Action: func(context *cli.Context) (retErr error) {
Action: func(cliContext *cli.Context) (retErr error) {
var (
ref = context.Args().First()
target = context.Args().Get(1)
ref = cliContext.Args().First()
target = cliContext.Args().Get(1)
)
if ref == "" {
return errors.New("please provide an image reference to mount")
@ -63,13 +63,13 @@ When you are done, use the unmount command.
return errors.New("please provide a target path to mount to")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := context.String("snapshotter")
snapshotter := cliContext.String("snapshotter")
if snapshotter == "" {
snapshotter = defaults.DefaultSnapshotter
}
@ -89,7 +89,7 @@ When you are done, use the unmount command.
}
}()
ps := context.String("platform")
ps := cliContext.String("platform")
p, err := platforms.Parse(ps)
if err != nil {
return fmt.Errorf("unable to parse platform %s: %w", ps, err)
@ -115,7 +115,7 @@ When you are done, use the unmount command.
s := client.SnapshotService(snapshotter)
var mounts []mount.Mount
if context.Bool("rw") {
if cliContext.Bool("rw") {
mounts, err = s.Prepare(ctx, target, chainID)
} else {
mounts, err = s.View(ctx, target, chainID)
@ -131,12 +131,12 @@ When you are done, use the unmount command.
if err := mount.All(mounts, target); err != nil {
if err := s.Remove(ctx, target); err != nil && !errdefs.IsNotFound(err) {
fmt.Fprintln(context.App.ErrWriter, "Error cleaning up snapshot after mount error:", err)
fmt.Fprintln(cliContext.App.ErrWriter, "Error cleaning up snapshot after mount error:", err)
}
return err
}
fmt.Fprintln(context.App.Writer, target)
fmt.Fprintln(cliContext.App.Writer, target)
return nil
},
}

View File

@ -85,46 +85,46 @@ command. As part of this process, we do the following:
Usage: "Fetch content from local client rather than using transfer service",
},
),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = context.Args().First()
ref = cliContext.Args().First()
)
if ref == "" {
return errors.New("please provide an image reference to pull")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
if !context.Bool("local") {
if !cliContext.Bool("local") {
unsupportedFlags := []string{"max-concurrent-downloads", "print-chainid",
"skip-verify", "tlscacert", "tlscert", "tlskey", "http-dump", "http-trace", // RegistryFlags
}
for _, s := range unsupportedFlags {
if context.IsSet(s) {
if cliContext.IsSet(s) {
return fmt.Errorf("\"--%s\" requires \"--local\" flag", s)
}
}
ch, err := commands.NewStaticCredentials(ctx, context, ref)
ch, err := commands.NewStaticCredentials(ctx, cliContext, ref)
if err != nil {
return err
}
var sopts []image.StoreOpt
p, err := platforms.ParseAll(context.StringSlice("platform"))
p, err := platforms.ParseAll(cliContext.StringSlice("platform"))
if err != nil {
return err
}
// Set unpack configuration
for _, platform := range p {
sopts = append(sopts, image.WithUnpack(platform, context.String("snapshotter")))
sopts = append(sopts, image.WithUnpack(platform, cliContext.String("snapshotter")))
}
if !context.Bool("all-platforms") {
if !cliContext.Bool("all-platforms") {
if len(p) == 0 {
p = append(p, platforms.DefaultSpec())
}
@ -133,21 +133,21 @@ command. As part of this process, we do the following:
// TODO: Support unpack for all platforms..?
// Pass in a *?
if context.Bool("metadata-only") {
if cliContext.Bool("metadata-only") {
sopts = append(sopts, image.WithAllMetadata)
// Any with an empty set is None
// TODO: Specify way to specify not default platform
// config.PlatformMatcher = platforms.Any()
} else if !context.Bool("skip-metadata") {
} else if !cliContext.Bool("skip-metadata") {
sopts = append(sopts, image.WithAllMetadata)
}
labels := context.StringSlice("label")
labels := cliContext.StringSlice("label")
if len(labels) > 0 {
sopts = append(sopts, image.WithImageLabels(commands.LabelArgs(labels)))
}
opts := []registry.Opt{registry.WithCredentials(ch), registry.WithHostDir(context.String("hosts-dir"))}
if context.Bool("plain-http") {
opts := []registry.Opt{registry.WithCredentials(ch), registry.WithHostDir(cliContext.String("hosts-dir"))}
if cliContext.Bool("plain-http") {
opts = append(opts, registry.WithDefaultScheme("http"))
}
reg, err := registry.NewOCIRegistry(ctx, ref, opts...)
@ -169,7 +169,7 @@ command. As part of this process, we do the following:
defer done(ctx)
// TODO: Handle this locally via transfer config
config, err := content.NewFetchConfig(ctx, context)
config, err := content.NewFetchConfig(ctx, cliContext)
if err != nil {
return err
}
@ -184,13 +184,13 @@ command. As part of this process, we do the following:
// TODO: Show unpack status
var p []ocispec.Platform
if context.Bool("all-platforms") {
if cliContext.Bool("all-platforms") {
p, err = images.Platforms(ctx, client.ContentStore(), img.Target)
if err != nil {
return fmt.Errorf("unable to resolve image platforms: %w", err)
}
} else {
p, err = platforms.ParseAll(context.StringSlice("platform"))
p, err = platforms.ParseAll(cliContext.StringSlice("platform"))
if err != nil {
return err
}
@ -203,11 +203,11 @@ command. As part of this process, we do the following:
for _, platform := range p {
fmt.Printf("unpacking %s %s...\n", platforms.Format(platform), img.Target.Digest)
i := containerd.NewImageWithPlatform(client, img, platforms.Only(platform))
err = i.Unpack(ctx, context.String("snapshotter"))
err = i.Unpack(ctx, cliContext.String("snapshotter"))
if err != nil {
return err
}
if context.Bool("print-chainid") {
if cliContext.Bool("print-chainid") {
diffIDs, err := i.RootFS(ctx)
if err != nil {
return err

View File

@ -17,7 +17,7 @@
package images
import (
gocontext "context"
"context"
"errors"
"fmt"
"net/http/httptrace"
@ -78,35 +78,35 @@ var pushCommand = &cli.Command{
Name: "allow-non-distributable-blobs",
Usage: "Allow pushing blobs that are marked as non-distributable",
}),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = context.Args().First()
local = context.Args().Get(1)
debug = context.Bool("debug")
ref = cliContext.Args().First()
local = cliContext.Args().Get(1)
debug = cliContext.Bool("debug")
desc ocispec.Descriptor
)
if ref == "" {
return errors.New("please provide a remote image reference to push")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
if !context.Bool("local") {
if !cliContext.Bool("local") {
unsupportedFlags := []string{
"manifest", "manifest-type", "max-concurrent-uploaded-layers", "allow-non-distributable-blobs",
"skip-verify", "tlscacert", "tlscert", "tlskey", "http-dump", "http-trace", // RegistryFlags
}
for _, s := range unsupportedFlags {
if context.IsSet(s) {
if cliContext.IsSet(s) {
return fmt.Errorf("\"--%s\" requires \"--local\" flag", s)
}
}
ch, err := commands.NewStaticCredentials(ctx, context, ref)
ch, err := commands.NewStaticCredentials(ctx, cliContext, ref)
if err != nil {
return err
}
@ -114,8 +114,8 @@ var pushCommand = &cli.Command{
if local == "" {
local = ref
}
opts := []registry.Opt{registry.WithCredentials(ch), registry.WithHostDir(context.String("hosts-dir"))}
if context.Bool("plain-http") {
opts := []registry.Opt{registry.WithCredentials(ch), registry.WithHostDir(cliContext.String("hosts-dir"))}
if cliContext.Bool("plain-http") {
opts = append(opts, registry.WithDefaultScheme("http"))
}
reg, err := registry.NewOCIRegistry(ctx, ref, opts...)
@ -123,7 +123,7 @@ var pushCommand = &cli.Command{
return err
}
var p []ocispec.Platform
if pss := context.StringSlice("platform"); len(pss) > 0 {
if pss := cliContext.StringSlice("platform"); len(pss) > 0 {
p, err = platforms.ParseAll(pss)
if err != nil {
return fmt.Errorf("invalid platform %v: %w", pss, err)
@ -137,12 +137,12 @@ var pushCommand = &cli.Command{
return client.Transfer(ctx, is, reg, transfer.WithProgress(pf))
}
if manifest := context.String("manifest"); manifest != "" {
if manifest := cliContext.String("manifest"); manifest != "" {
desc.Digest, err = digest.Parse(manifest)
if err != nil {
return fmt.Errorf("invalid manifest digest: %w", err)
}
desc.MediaType = context.String("manifest-type")
desc.MediaType = cliContext.String("manifest-type")
} else {
if local == "" {
local = ref
@ -153,7 +153,7 @@ var pushCommand = &cli.Command{
}
desc = img.Target
if pss := context.StringSlice("platform"); len(pss) == 1 {
if pss := cliContext.StringSlice("platform"); len(pss) == 1 {
p, err := platforms.Parse(pss[0])
if err != nil {
return fmt.Errorf("invalid platform %q: %w", pss[0], err)
@ -175,10 +175,10 @@ var pushCommand = &cli.Command{
}
}
if context.Bool("http-trace") {
if cliContext.Bool("http-trace") {
ctx = httptrace.WithClientTrace(ctx, commands.NewDebugClientTrace(ctx))
}
resolver, err := commands.GetResolver(ctx, context)
resolver, err := commands.GetResolver(ctx, cliContext)
if err != nil {
return err
}
@ -194,8 +194,8 @@ var pushCommand = &cli.Command{
log.G(ctx).WithField("image", ref).WithField("digest", desc.Digest).Debug("pushing")
jobHandler := images.HandlerFunc(func(ctx gocontext.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
if !context.Bool("allow-non-distributable-blobs") && images.IsNonDistributable(desc.MediaType) {
jobHandler := images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
if !cliContext.Bool("allow-non-distributable-blobs") && images.IsNonDistributable(desc.MediaType) {
return nil, nil
}
ongoing.add(remotes.MakeRefKey(ctx, desc))
@ -203,7 +203,7 @@ var pushCommand = &cli.Command{
})
handler := jobHandler
if !context.Bool("allow-non-distributable-blobs") {
if !cliContext.Bool("allow-non-distributable-blobs") {
handler = remotes.SkipNonDistributableBlobs(handler)
}
@ -212,8 +212,8 @@ var pushCommand = &cli.Command{
containerd.WithImageHandler(handler),
}
if context.IsSet("max-concurrent-uploaded-layers") {
mcu := context.Int("max-concurrent-uploaded-layers")
if cliContext.IsSet("max-concurrent-uploaded-layers") {
mcu := cliContext.Int("max-concurrent-uploaded-layers")
ropts = append(ropts, containerd.WithMaxConcurrentUploadedLayers(mcu))
}

View File

@ -47,26 +47,26 @@ var tagCommand = &cli.Command{
Usage: "Skip the strict check for reference names",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
ref = context.Args().First()
ref = cliContext.Args().First()
)
if ref == "" {
return errors.New("please provide an image reference to tag from")
}
if context.NArg() <= 1 {
if cliContext.NArg() <= 1 {
return errors.New("please provide an image reference to tag to")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
if !context.Bool("local") {
for _, targetRef := range context.Args().Slice()[1:] {
if !context.Bool("skip-reference-check") {
if !cliContext.Bool("local") {
for _, targetRef := range cliContext.Args().Slice()[1:] {
if !cliContext.Bool("skip-reference-check") {
if _, err := reference.ParseAnyReference(targetRef); err != nil {
return fmt.Errorf("error parsing reference: %q is not a valid repository/tag %v", targetRef, err)
}
@ -92,8 +92,8 @@ var tagCommand = &cli.Command{
return err
}
// Support multiple references for one command run
for _, targetRef := range context.Args().Slice()[1:] {
if !context.Bool("skip-reference-check") {
for _, targetRef := range cliContext.Args().Slice()[1:] {
if !cliContext.Bool("skip-reference-check") {
if _, err := reference.ParseAnyReference(targetRef); err != nil {
return fmt.Errorf("error parsing reference: %q is not a valid repository/tag %v", targetRef, err)
}
@ -103,7 +103,7 @@ var tagCommand = &cli.Command{
if _, err = imageService.Create(ctx, image); err != nil {
// If user has specified force and the image already exists then
// delete the original image and attempt to create the new one
if errdefs.IsAlreadyExists(err) && context.Bool("force") {
if errdefs.IsAlreadyExists(err) && cliContext.Bool("force") {
if err = imageService.Delete(ctx, targetRef); err != nil {
return err
}

View File

@ -38,15 +38,15 @@ var unmountCommand = &cli.Command{
Usage: "Remove the snapshot after a successful unmount",
},
),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
target = context.Args().First()
target = cliContext.Args().First()
)
if target == "" {
return errors.New("please provide a target path to unmount from")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -56,8 +56,8 @@ var unmountCommand = &cli.Command{
return err
}
if context.Bool("rm") {
snapshotter := context.String("snapshotter")
if cliContext.Bool("rm") {
snapshotter := cliContext.String("snapshotter")
s := client.SnapshotService(snapshotter)
if err := client.LeasesService().Delete(ctx, leases.Lease{ID: target}); err != nil && !errdefs.IsNotFound(err) {
return fmt.Errorf("error deleting lease: %w", err)
@ -67,7 +67,7 @@ var unmountCommand = &cli.Command{
}
}
fmt.Fprintln(context.App.Writer, target)
fmt.Fprintln(cliContext.App.Writer, target)
return nil
},
}

View File

@ -36,19 +36,19 @@ var usageCommand = &cli.Command{
Usage: "Display usage of snapshots for a given image ref",
ArgsUsage: "[flags] <ref>",
Flags: commands.SnapshotterFlags,
Action: func(context *cli.Context) error {
var ref = context.Args().First()
Action: func(cliContext *cli.Context) error {
var ref = cliContext.Args().First()
if ref == "" {
return errors.New("please provide an image reference to mount")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := context.String("snapshotter")
snapshotter := cliContext.String("snapshotter")
if snapshotter == "" {
snapshotter = defaults.DefaultSnapshotter
}

View File

@ -30,8 +30,8 @@ type Info struct {
var Command = &cli.Command{
Name: "info",
Usage: "Print the server info",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}

View File

@ -44,25 +44,25 @@ var Command = &cli.Command{
Usage: "Set an optional install path other than the managed opt directory",
},
},
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
ref := context.Args().First()
ref := cliContext.Args().First()
image, err := client.GetImage(ctx, ref)
if err != nil {
return err
}
var opts []containerd.InstallOpts
if context.Bool("libs") {
if cliContext.Bool("libs") {
opts = append(opts, containerd.WithInstallLibs)
}
if context.Bool("replace") {
if cliContext.Bool("replace") {
opts = append(opts, containerd.WithInstallReplace)
}
if path := context.String("path"); path != "" {
if path := cliContext.String("path"); path != "" {
opts = append(opts, containerd.WithInstallPath(path))
}
return client.Install(ctx, image, opts...)

View File

@ -54,12 +54,12 @@ var listCommand = &cli.Command{
Usage: "Print only the blob digest",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
filters = context.Args().Slice()
quiet = context.Bool("quiet")
filters = cliContext.Args().Slice()
quiet = cliContext.Bool("quiet")
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -117,9 +117,9 @@ var createCommand = &cli.Command{
Value: 24 * time.Hour,
},
},
Action: func(context *cli.Context) error {
var labelstr = context.Args().Slice()
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
var labelstr = cliContext.Args().Slice()
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -136,10 +136,10 @@ var createCommand = &cli.Command{
opts = append(opts, leases.WithLabels(labels))
}
if id := context.String("id"); id != "" {
if id := cliContext.String("id"); id != "" {
opts = append(opts, leases.WithID(id))
}
if exp := context.Duration("expires"); exp > 0 {
if exp := cliContext.Duration("expires"); exp > 0 {
opts = append(opts, leases.WithExpiration(exp))
}
@ -166,19 +166,19 @@ var deleteCommand = &cli.Command{
Usage: "Synchronously remove leases and all unreferenced resources",
},
},
Action: func(context *cli.Context) error {
var lids = context.Args().Slice()
Action: func(cliContext *cli.Context) error {
var lids = cliContext.Args().Slice()
if len(lids) == 0 {
return cli.ShowSubcommandHelp(context)
return cli.ShowSubcommandHelp(cliContext)
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
ls := client.LeasesService()
sync := context.Bool("sync")
sync := cliContext.Bool("sync")
for i, lid := range lids {
var opts []leases.DeleteOpt
if sync && i == len(lids)-1 {

View File

@ -49,12 +49,12 @@ var createCommand = &cli.Command{
Usage: "Create a new namespace",
ArgsUsage: "<name> [<key>=<value>]",
Description: "create a new namespace. it must be unique",
Action: func(context *cli.Context) error {
namespace, labels := commands.ObjectWithLabelArgs(context)
Action: func(cliContext *cli.Context) error {
namespace, labels := commands.ObjectWithLabelArgs(cliContext)
if namespace == "" {
return errors.New("please specify a namespace")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -69,12 +69,12 @@ var setLabelsCommand = &cli.Command{
Usage: "Set and clear labels for a namespace",
ArgsUsage: "<name> [<key>=<value>, ...]",
Description: "set and clear labels for a namespace. empty value clears the label",
Action: func(context *cli.Context) error {
namespace, labels := commands.ObjectWithLabelArgs(context)
Action: func(cliContext *cli.Context) error {
namespace, labels := commands.ObjectWithLabelArgs(cliContext)
if namespace == "" {
return errors.New("please specify a namespace")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -102,9 +102,9 @@ var listCommand = &cli.Command{
Usage: "Print only the namespace name",
},
},
Action: func(context *cli.Context) error {
quiet := context.Bool("quiet")
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
quiet := cliContext.Bool("quiet")
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -155,17 +155,17 @@ var removeCommand = &cli.Command{
Usage: "Delete the namespace's cgroup",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var exitErr error
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
opts := deleteOpts(context)
opts := deleteOpts(cliContext)
namespaces := client.NamespaceService()
for _, target := range context.Args().Slice() {
for _, target := range cliContext.Args().Slice() {
if err := namespaces.Delete(ctx, target, opts...); err != nil {
if !errdefs.IsNotFound(err) {
if exitErr == nil {

View File

@ -22,9 +22,9 @@ import (
"github.com/urfave/cli/v2"
)
func deleteOpts(context *cli.Context) []namespaces.DeleteOpts {
func deleteOpts(cliContext *cli.Context) []namespaces.DeleteOpts {
var delOpts []namespaces.DeleteOpts
if context.Bool("cgroup") {
if cliContext.Bool("cgroup") {
delOpts = append(delOpts, opts.WithNamespaceCgroupDeletion)
}
return delOpts

View File

@ -23,6 +23,6 @@ import (
"github.com/urfave/cli/v2"
)
func deleteOpts(context *cli.Context) []namespaces.DeleteOpts {
func deleteOpts(cliContext *cli.Context) []namespaces.DeleteOpts {
return nil
}

View File

@ -45,12 +45,12 @@ var defaultSpecCommand = &cli.Command{
Usage: "Platform of the spec to print (Examples: 'linux/arm64', 'windows/amd64')",
},
},
Action: func(context *cli.Context) error {
ctx, cancel := commands.AppContext(context)
Action: func(cliContext *cli.Context) error {
ctx, cancel := commands.AppContext(cliContext)
defer cancel()
platform := platforms.DefaultString()
if plat := context.String("platform"); plat != "" {
if plat := cliContext.String("platform"); plat != "" {
platform = plat
}

View File

@ -60,18 +60,18 @@ var listCommand = &cli.Command{
Usage: "Print detailed information about each plugin",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
quiet = context.Bool("quiet")
detailed = context.Bool("detailed")
quiet = cliContext.Bool("quiet")
detailed = cliContext.Bool("detailed")
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
ps := client.IntrospectionService()
response, err := ps.Plugins(ctx, context.Args().Slice()...)
response, err := ps.Plugins(ctx, cliContext.Args().Slice()...)
if err != nil {
return err
}
@ -172,13 +172,13 @@ var inspectRuntimeCommand = &cli.Command{
Usage: "Display runtime info",
ArgsUsage: "[flags]",
Flags: commands.RuntimeFlags,
Action: func(context *cli.Context) error {
rt := context.String("runtime")
rtOptions, err := commands.RuntimeOptions(context)
Action: func(cliContext *cli.Context) error {
rt := cliContext.String("runtime")
rtOptions, err := commands.RuntimeOptions(cliContext)
if err != nil {
return err
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -191,7 +191,7 @@ var inspectRuntimeCommand = &cli.Command{
if err != nil {
return err
}
_, err = fmt.Fprintln(context.App.Writer, string(j))
_, err = fmt.Fprintln(cliContext.App.Writer, string(j))
return err
},
}

View File

@ -64,10 +64,10 @@ var pprofGoroutinesCommand = &cli.Command{
Value: 2,
},
},
Action: func(context *cli.Context) error {
client := getPProfClient(context)
Action: func(cliContext *cli.Context) error {
client := getPProfClient(cliContext)
debug := context.Uint("debug")
debug := cliContext.Uint("debug")
output, err := httpGetRequest(client, fmt.Sprintf("/debug/pprof/goroutine?debug=%d", debug))
if err != nil {
return err
@ -88,10 +88,10 @@ var pprofHeapCommand = &cli.Command{
Value: 0,
},
},
Action: func(context *cli.Context) error {
client := getPProfClient(context)
Action: func(cliContext *cli.Context) error {
client := getPProfClient(cliContext)
debug := context.Uint("debug")
debug := cliContext.Uint("debug")
output, err := httpGetRequest(client, fmt.Sprintf("/debug/pprof/heap?debug=%d", debug))
if err != nil {
return err
@ -118,11 +118,11 @@ var pprofProfileCommand = &cli.Command{
Value: 0,
},
},
Action: func(context *cli.Context) error {
client := getPProfClient(context)
Action: func(cliContext *cli.Context) error {
client := getPProfClient(cliContext)
seconds := context.Duration("seconds").Seconds()
debug := context.Uint("debug")
seconds := cliContext.Duration("seconds").Seconds()
debug := cliContext.Uint("debug")
output, err := httpGetRequest(client, fmt.Sprintf("/debug/pprof/profile?seconds=%v&debug=%d", seconds, debug))
if err != nil {
return err
@ -149,11 +149,11 @@ var pprofTraceCommand = &cli.Command{
Value: 0,
},
},
Action: func(context *cli.Context) error {
client := getPProfClient(context)
Action: func(cliContext *cli.Context) error {
client := getPProfClient(cliContext)
seconds := context.Duration("seconds").Seconds()
debug := context.Uint("debug")
seconds := cliContext.Duration("seconds").Seconds()
debug := cliContext.Uint("debug")
uri := fmt.Sprintf("/debug/pprof/trace?seconds=%v&debug=%d", seconds, debug)
output, err := httpGetRequest(client, uri)
if err != nil {
@ -175,10 +175,10 @@ var pprofBlockCommand = &cli.Command{
Value: 0,
},
},
Action: func(context *cli.Context) error {
client := getPProfClient(context)
Action: func(cliContext *cli.Context) error {
client := getPProfClient(cliContext)
debug := context.Uint("debug")
debug := cliContext.Uint("debug")
output, err := httpGetRequest(client, fmt.Sprintf("/debug/pprof/block?debug=%d", debug))
if err != nil {
return err
@ -199,10 +199,10 @@ var pprofThreadcreateCommand = &cli.Command{
Value: 0,
},
},
Action: func(context *cli.Context) error {
client := getPProfClient(context)
Action: func(cliContext *cli.Context) error {
client := getPProfClient(cliContext)
debug := context.Uint("debug")
debug := cliContext.Uint("debug")
output, err := httpGetRequest(client, fmt.Sprintf("/debug/pprof/threadcreate?debug=%d", debug))
if err != nil {
return err
@ -213,8 +213,8 @@ var pprofThreadcreateCommand = &cli.Command{
},
}
func getPProfClient(context *cli.Context) *http.Client {
dialer := getPProfDialer(context.String("debug-socket"))
func getPProfClient(cliContext *cli.Context) *http.Client {
dialer := getPProfDialer(cliContext.String("debug-socket"))
tr := &http.Transport{
Dial: dialer.pprofDial,

View File

@ -18,7 +18,7 @@ package commands
import (
"bufio"
gocontext "context"
"context"
"crypto/tls"
"crypto/x509"
"errors"
@ -58,8 +58,8 @@ func passwordPrompt() (string, error) {
}
// GetResolver prepares the resolver from the environment and options
func GetResolver(ctx gocontext.Context, clicontext *cli.Context) (remotes.Resolver, error) {
username := clicontext.String("user")
func GetResolver(ctx context.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:]
@ -80,7 +80,7 @@ func GetResolver(ctx gocontext.Context, clicontext *cli.Context) (remotes.Resolv
fmt.Print("\n")
}
} else if rt := clicontext.String("refresh"); rt != "" {
} else if rt := cliContext.String("refresh"); rt != "" {
secret = rt
}
@ -90,19 +90,19 @@ func GetResolver(ctx gocontext.Context, clicontext *cli.Context) (remotes.Resolv
// Only one host
return username, secret, nil
}
if clicontext.Bool("plain-http") {
if cliContext.Bool("plain-http") {
hostOptions.DefaultScheme = "http"
}
defaultTLS, err := resolverDefaultTLS(clicontext)
defaultTLS, err := resolverDefaultTLS(cliContext)
if err != nil {
return nil, err
}
hostOptions.DefaultTLS = defaultTLS
if hostDir := clicontext.String("hosts-dir"); hostDir != "" {
if hostDir := cliContext.String("hosts-dir"); hostDir != "" {
hostOptions.HostDir = config.HostDirFromRoot(hostDir)
}
if clicontext.Bool("http-dump") {
if cliContext.Bool("http-dump") {
hostOptions.UpdateClient = func(client *http.Client) error {
client.Transport = &DebugTransport{
transport: client.Transport,
@ -117,27 +117,27 @@ func GetResolver(ctx gocontext.Context, clicontext *cli.Context) (remotes.Resolv
return docker.NewResolver(options), nil
}
func resolverDefaultTLS(clicontext *cli.Context) (*tls.Config, error) {
config := &tls.Config{}
func resolverDefaultTLS(cliContext *cli.Context) (*tls.Config, error) {
tlsConfig := &tls.Config{}
if clicontext.Bool("skip-verify") {
config.InsecureSkipVerify = true
if cliContext.Bool("skip-verify") {
tlsConfig.InsecureSkipVerify = true
}
if tlsRootPath := clicontext.String("tlscacert"); tlsRootPath != "" {
if tlsRootPath := cliContext.String("tlscacert"); tlsRootPath != "" {
tlsRootData, err := os.ReadFile(tlsRootPath)
if err != nil {
return nil, fmt.Errorf("failed to read %q: %w", tlsRootPath, err)
}
config.RootCAs = x509.NewCertPool()
if !config.RootCAs.AppendCertsFromPEM(tlsRootData) {
tlsConfig.RootCAs = x509.NewCertPool()
if !tlsConfig.RootCAs.AppendCertsFromPEM(tlsRootData) {
return nil, fmt.Errorf("failed to load TLS CAs from %q: invalid data", tlsRootPath)
}
}
tlsCertPath := clicontext.String("tlscert")
tlsKeyPath := clicontext.String("tlskey")
tlsCertPath := cliContext.String("tlscert")
tlsKeyPath := cliContext.String("tlskey")
if tlsCertPath != "" || tlsKeyPath != "" {
if tlsCertPath == "" || tlsKeyPath == "" {
return nil, errors.New("flags --tlscert and --tlskey must be set together")
@ -146,15 +146,15 @@ func resolverDefaultTLS(clicontext *cli.Context) (*tls.Config, error) {
if err != nil {
return nil, fmt.Errorf("failed to load TLS client credentials (cert=%q, key=%q): %w", tlsCertPath, tlsKeyPath, err)
}
config.Certificates = []tls.Certificate{keyPair}
tlsConfig.Certificates = []tls.Certificate{keyPair}
}
// If nothing was set, return nil rather than empty config
if !config.InsecureSkipVerify && config.RootCAs == nil && config.Certificates == nil {
if !tlsConfig.InsecureSkipVerify && tlsConfig.RootCAs == nil && tlsConfig.Certificates == nil {
return nil, nil
}
return config, nil
return tlsConfig, nil
}
// DebugTransport wraps the underlying http.RoundTripper interface and dumps all requests/responses to the writer.
@ -193,7 +193,7 @@ func (t DebugTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// NewDebugClientTrace returns a Go http trace client predefined to write DNS and connection
// information to the log. This is used via the --http-trace flag on push and pull operations in ctr.
func NewDebugClientTrace(ctx gocontext.Context) *httptrace.ClientTrace {
func NewDebugClientTrace(ctx context.Context) *httptrace.ClientTrace {
return &httptrace.ClientTrace{
DNSStart: func(dnsInfo httptrace.DNSStartInfo) {
log.G(ctx).WithField("host", dnsInfo.Host).Debugf("DNS lookup")
@ -223,8 +223,8 @@ type staticCredentials struct {
}
// NewStaticCredentials gets credentials from passing in cli context
func NewStaticCredentials(ctx gocontext.Context, clicontext *cli.Context, ref string) (registry.CredentialHelper, error) {
username := clicontext.String("user")
func NewStaticCredentials(ctx context.Context, cliContext *cli.Context, ref string) (registry.CredentialHelper, error) {
username := cliContext.String("user")
var secret string
if i := strings.IndexByte(username, ':'); i > 0 {
secret = username[i+1:]
@ -242,7 +242,7 @@ func NewStaticCredentials(ctx gocontext.Context, clicontext *cli.Context, ref st
fmt.Print("\n")
}
} else if rt := clicontext.String("refresh"); rt != "" {
} else if rt := cliContext.String("refresh"); rt != "" {
secret = rt
}
@ -253,7 +253,7 @@ func NewStaticCredentials(ctx gocontext.Context, clicontext *cli.Context, ref st
}, nil
}
func (sc *staticCredentials) GetCredentials(ctx gocontext.Context, ref, host string) (registry.Credentials, error) {
func (sc *staticCredentials) GetCredentials(ctx context.Context, ref, host string) (registry.Credentials, error) {
if ref == sc.ref {
return registry.Credentials{
Username: sc.username,

View File

@ -17,7 +17,7 @@
package run
import (
gocontext "context"
"context"
"encoding/csv"
"errors"
"fmt"
@ -39,11 +39,11 @@ import (
"github.com/containerd/log"
)
func withMounts(context *cli.Context) oci.SpecOpts {
return func(ctx gocontext.Context, client oci.Client, container *containers.Container, s *specs.Spec) error {
func withMounts(cliContext *cli.Context) oci.SpecOpts {
return func(ctx context.Context, client oci.Client, container *containers.Container, s *specs.Spec) error {
mounts := make([]specs.Mount, 0)
dests := make([]string, 0)
for _, mount := range context.StringSlice("mount") {
for _, mount := range cliContext.StringSlice("mount") {
m, err := parseMountFlag(mount)
if err != nil {
return err
@ -131,27 +131,27 @@ var Command = &cli.Command{
append(commands.RuntimeFlags,
append(append(commands.SnapshotterFlags, []cli.Flag{commands.SnapshotterLabels}...),
commands.ContainerFlags...)...)...)...),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
err error
id string
ref string
rm = context.Bool("rm")
tty = context.Bool("tty")
detach = context.Bool("detach")
config = context.IsSet("config")
enableCNI = context.Bool("cni")
rm = cliContext.Bool("rm")
tty = cliContext.Bool("tty")
detach = cliContext.Bool("detach")
config = cliContext.IsSet("config")
enableCNI = cliContext.Bool("cni")
)
if config {
id = context.Args().First()
if context.NArg() > 1 {
id = cliContext.Args().First()
if cliContext.NArg() > 1 {
return errors.New("with spec config file, only container id should be provided")
}
} else {
id = context.Args().Get(1)
ref = context.Args().First()
id = cliContext.Args().Get(1)
ref = cliContext.Args().First()
if ref == "" {
return errors.New("image ref must be provided")
@ -164,13 +164,13 @@ var Command = &cli.Command{
return errors.New("flags --detach and --rm cannot be specified together")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
container, err := NewContainer(ctx, client, context)
container, err := NewContainer(ctx, client, cliContext)
if err != nil {
return err
}
@ -196,9 +196,9 @@ var Command = &cli.Command{
}
}
opts := tasks.GetNewTaskOpts(context)
ioOpts := []cio.Opt{cio.WithFIFODir(context.String("fifo-dir"))}
task, err := tasks.NewTask(ctx, client, container, context.String("checkpoint"), con, context.Bool("null-io"), context.String("log-uri"), ioOpts, opts...)
opts := tasks.GetNewTaskOpts(cliContext)
ioOpts := []cio.Opt{cio.WithFIFODir(cliContext.String("fifo-dir"))}
task, err := tasks.NewTask(ctx, client, container, cliContext.String("checkpoint"), con, cliContext.Bool("null-io"), cliContext.String("log-uri"), ioOpts, opts...)
if err != nil {
return err
}
@ -221,8 +221,8 @@ var Command = &cli.Command{
return err
}
}
if context.IsSet("pid-file") {
if err := commands.WritePidFile(context.String("pid-file"), int(task.Pid())); err != nil {
if cliContext.IsSet("pid-file") {
if err := commands.WritePidFile(cliContext.String("pid-file"), int(task.Pid())); err != nil {
return err
}
}

View File

@ -19,7 +19,7 @@
package run
import (
gocontext "context"
"context"
"errors"
"fmt"
"os"
@ -82,15 +82,15 @@ var platformRunFlags = []cli.Flag{
}
// NewContainer creates a new container
func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli.Context) (containerd.Container, error) {
func NewContainer(ctx context.Context, client *containerd.Client, cliContext *cli.Context) (containerd.Container, error) {
var (
id string
config = context.IsSet("config")
config = cliContext.IsSet("config")
)
if config {
id = context.Args().First()
id = cliContext.Args().First()
} else {
id = context.Args().Get(1)
id = cliContext.Args().Get(1)
}
var (
@ -99,41 +99,41 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
spec containerd.NewContainerOpts
)
if sandbox := context.String("sandbox"); sandbox != "" {
if sandbox := cliContext.String("sandbox"); sandbox != "" {
cOpts = append(cOpts, containerd.WithSandbox(sandbox))
}
if config {
cOpts = append(cOpts, containerd.WithContainerLabels(commands.LabelArgs(context.StringSlice("label"))))
opts = append(opts, oci.WithSpecFromFile(context.String("config")))
cOpts = append(cOpts, containerd.WithContainerLabels(commands.LabelArgs(cliContext.StringSlice("label"))))
opts = append(opts, oci.WithSpecFromFile(cliContext.String("config")))
} else {
var (
ref = context.Args().First()
ref = cliContext.Args().First()
// for container's id is Args[1]
args = context.Args().Slice()[2:]
args = cliContext.Args().Slice()[2:]
)
opts = append(opts, oci.WithDefaultSpec(), oci.WithDefaultUnixDevices)
if ef := context.String("env-file"); ef != "" {
if ef := cliContext.String("env-file"); ef != "" {
opts = append(opts, oci.WithEnvFile(ef))
}
opts = append(opts, oci.WithEnv(context.StringSlice("env")))
opts = append(opts, withMounts(context))
opts = append(opts, oci.WithEnv(cliContext.StringSlice("env")))
opts = append(opts, withMounts(cliContext))
if context.Bool("rootfs") {
if cliContext.Bool("rootfs") {
rootfs, err := filepath.Abs(ref)
if err != nil {
return nil, err
}
opts = append(opts, oci.WithRootFSPath(rootfs))
cOpts = append(cOpts, containerd.WithContainerLabels(commands.LabelArgs(context.StringSlice("label"))))
cOpts = append(cOpts, containerd.WithContainerLabels(commands.LabelArgs(cliContext.StringSlice("label"))))
} else {
snapshotter := context.String("snapshotter")
snapshotter := cliContext.String("snapshotter")
var image containerd.Image
i, err := client.ImageService().Get(ctx, ref)
if err != nil {
return nil, err
}
if ps := context.String("platform"); ps != "" {
if ps := cliContext.String("platform"); ps != "" {
platform, err := platforms.Parse(ps)
if err != nil {
return nil, err
@ -152,14 +152,14 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
return nil, err
}
}
labels := buildLabels(commands.LabelArgs(context.StringSlice("label")), image.Labels())
labels := buildLabels(commands.LabelArgs(cliContext.StringSlice("label")), image.Labels())
opts = append(opts, oci.WithImageConfig(image))
cOpts = append(cOpts,
containerd.WithImage(image),
containerd.WithImageConfigLabels(image),
containerd.WithAdditionalContainerLabels(labels),
containerd.WithSnapshotter(snapshotter))
if uidmap, gidmap := context.String("uidmap"), context.String("gidmap"); uidmap != "" && gidmap != "" {
if uidmap, gidmap := cliContext.String("uidmap"), cliContext.String("gidmap"); uidmap != "" && gidmap != "" {
uidMap, err := parseIDMapping(uidmap)
if err != nil {
return nil, err
@ -174,7 +174,7 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
// currently the snapshotters known to support the labels are:
// fuse-overlayfs - https://github.com/containerd/fuse-overlayfs-snapshotter
// overlay - in case of idmapped mount points are supported by host kernel (Linux kernel 5.19)
if context.Bool("remap-labels") {
if cliContext.Bool("remap-labels") {
cOpts = append(cOpts, containerd.WithNewSnapshot(id, image,
containerd.WithRemapperLabels(0, uidMap.HostID, 0, gidMap.HostID, uidMap.Size)))
} else {
@ -187,28 +187,28 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
// For some snapshotter, such as overlaybd, it can provide 2 kind of writable snapshot(overlayfs dir or block-device)
// by command label values.
cOpts = append(cOpts, containerd.WithNewSnapshot(id, image,
snapshots.WithLabels(commands.LabelArgs(context.StringSlice("snapshotter-label")))))
snapshots.WithLabels(commands.LabelArgs(cliContext.StringSlice("snapshotter-label")))))
}
cOpts = append(cOpts, containerd.WithImageStopSignal(image, "SIGTERM"))
}
if context.Bool("read-only") {
if cliContext.Bool("read-only") {
opts = append(opts, oci.WithRootFSReadonly())
}
if len(args) > 0 {
opts = append(opts, oci.WithProcessArgs(args...))
}
if cwd := context.String("cwd"); cwd != "" {
if cwd := cliContext.String("cwd"); cwd != "" {
opts = append(opts, oci.WithProcessCwd(cwd))
}
if user := context.String("user"); user != "" {
if user := cliContext.String("user"); user != "" {
opts = append(opts, oci.WithUser(user), oci.WithAdditionalGIDs(user))
}
if context.Bool("tty") {
if cliContext.Bool("tty") {
opts = append(opts, oci.WithTTY)
}
privileged := context.Bool("privileged")
privilegedWithoutHostDevices := context.Bool("privileged-without-host-devices")
privileged := cliContext.Bool("privileged")
privilegedWithoutHostDevices := cliContext.Bool("privileged-without-host-devices")
if privilegedWithoutHostDevices && !privileged {
return nil, errors.New("can't use 'privileged-without-host-devices' without 'privileged' specified")
}
@ -220,7 +220,7 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
}
}
if context.Bool("net-host") {
if cliContext.Bool("net-host") {
hostname, err := os.Hostname()
if err != nil {
return nil, fmt.Errorf("get hostname: %w", err)
@ -232,7 +232,7 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
oci.WithEnv([]string{fmt.Sprintf("HOSTNAME=%s", hostname)}),
)
}
if annoStrings := context.StringSlice("annotation"); len(annoStrings) > 0 {
if annoStrings := cliContext.StringSlice("annotation"); len(annoStrings) > 0 {
annos, err := commands.AnnotationArgs(annoStrings)
if err != nil {
return nil, err
@ -240,7 +240,7 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
opts = append(opts, oci.WithAnnotations(annos))
}
if caps := context.StringSlice("cap-add"); len(caps) > 0 {
if caps := cliContext.StringSlice("cap-add"); len(caps) > 0 {
for _, cap := range caps {
if !strings.HasPrefix(cap, "CAP_") {
return nil, errors.New("capabilities must be specified with 'CAP_' prefix")
@ -249,7 +249,7 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
opts = append(opts, oci.WithAddedCapabilities(caps))
}
if caps := context.StringSlice("cap-drop"); len(caps) > 0 {
if caps := cliContext.StringSlice("cap-drop"); len(caps) > 0 {
for _, cap := range caps {
if !strings.HasPrefix(cap, "CAP_") {
return nil, errors.New("capabilities must be specified with 'CAP_' prefix")
@ -258,13 +258,13 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
opts = append(opts, oci.WithDroppedCapabilities(caps))
}
seccompProfile := context.String("seccomp-profile")
seccompProfile := cliContext.String("seccomp-profile")
if !context.Bool("seccomp") && seccompProfile != "" {
if !cliContext.Bool("seccomp") && seccompProfile != "" {
return nil, errors.New("seccomp must be set to true, if using a custom seccomp-profile")
}
if context.Bool("seccomp") {
if cliContext.Bool("seccomp") {
if seccompProfile != "" {
opts = append(opts, seccomp.WithProfile(seccompProfile))
} else {
@ -272,18 +272,18 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
}
}
if s := context.String("apparmor-default-profile"); len(s) > 0 {
if s := cliContext.String("apparmor-default-profile"); len(s) > 0 {
opts = append(opts, apparmor.WithDefaultProfile(s))
}
if s := context.String("apparmor-profile"); len(s) > 0 {
if len(context.String("apparmor-default-profile")) > 0 {
if s := cliContext.String("apparmor-profile"); len(s) > 0 {
if len(cliContext.String("apparmor-default-profile")) > 0 {
return nil, errors.New("apparmor-profile conflicts with apparmor-default-profile")
}
opts = append(opts, apparmor.WithProfile(s))
}
if cpus := context.Float64("cpus"); cpus > 0.0 {
if cpus := cliContext.Float64("cpus"); cpus > 0.0 {
var (
period = uint64(100000)
quota = int64(cpus * 100000.0)
@ -291,32 +291,32 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
opts = append(opts, oci.WithCPUCFS(quota, period))
}
if cpusetCpus := context.String("cpuset-cpus"); len(cpusetCpus) > 0 {
if cpusetCpus := cliContext.String("cpuset-cpus"); len(cpusetCpus) > 0 {
opts = append(opts, oci.WithCPUs(cpusetCpus))
}
if cpusetMems := context.String("cpuset-mems"); len(cpusetMems) > 0 {
if cpusetMems := cliContext.String("cpuset-mems"); len(cpusetMems) > 0 {
opts = append(opts, oci.WithCPUsMems(cpusetMems))
}
if shares := context.Int("cpu-shares"); shares > 0 {
if shares := cliContext.Int("cpu-shares"); shares > 0 {
opts = append(opts, oci.WithCPUShares(uint64(shares)))
}
quota := context.Int64("cpu-quota")
period := context.Uint64("cpu-period")
quota := cliContext.Int64("cpu-quota")
period := cliContext.Uint64("cpu-period")
if quota != -1 || period != 0 {
if cpus := context.Float64("cpus"); cpus > 0.0 {
if cpus := cliContext.Float64("cpus"); cpus > 0.0 {
return nil, errors.New("cpus and quota/period should be used separately")
}
opts = append(opts, oci.WithCPUCFS(quota, period))
}
if burst := context.Uint64("cpu-burst"); burst != 0 {
if burst := cliContext.Uint64("cpu-burst"); burst != 0 {
opts = append(opts, oci.WithCPUBurst(burst))
}
joinNs := context.StringSlice("with-ns")
joinNs := cliContext.StringSlice("with-ns")
for _, ns := range joinNs {
nsType, nsPath, ok := strings.Cut(ns, ":")
if !ok {
@ -330,22 +330,22 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
Path: nsPath,
}))
}
if context.IsSet("gpus") {
opts = append(opts, nvidia.WithGPUs(nvidia.WithDevices(context.IntSlice("gpus")...), nvidia.WithAllCapabilities))
if cliContext.IsSet("gpus") {
opts = append(opts, nvidia.WithGPUs(nvidia.WithDevices(cliContext.IntSlice("gpus")...), nvidia.WithAllCapabilities))
}
if context.IsSet("allow-new-privs") {
if cliContext.IsSet("allow-new-privs") {
opts = append(opts, oci.WithNewPrivileges)
}
if context.IsSet("cgroup") {
if cliContext.IsSet("cgroup") {
// NOTE: can be set to "" explicitly for disabling cgroup.
opts = append(opts, oci.WithCgroup(context.String("cgroup")))
opts = append(opts, oci.WithCgroup(cliContext.String("cgroup")))
}
limit := context.Uint64("memory-limit")
limit := cliContext.Uint64("memory-limit")
if limit != 0 {
opts = append(opts, oci.WithMemoryLimit(limit))
}
var cdiDeviceIDs []string
for _, dev := range context.StringSlice("device") {
for _, dev := range cliContext.StringSlice("device") {
if parser.IsQualifiedName(dev) {
cdiDeviceIDs = append(cdiDeviceIDs, dev)
continue
@ -357,9 +357,9 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
}
opts = append(opts, oci.WithCDIDevices(cdiDeviceIDs...))
rootfsPropagation := context.String("rootfs-propagation")
rootfsPropagation := cliContext.String("rootfs-propagation")
if rootfsPropagation != "" {
opts = append(opts, func(_ gocontext.Context, _ oci.Client, _ *containers.Container, s *oci.Spec) error {
opts = append(opts, func(_ context.Context, _ oci.Client, _ *containers.Container, s *oci.Spec) error {
if s.Linux != nil {
s.Linux.RootfsPropagation = rootfsPropagation
} else {
@ -372,39 +372,39 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
})
}
if c := context.String("blockio-config-file"); c != "" {
if c := cliContext.String("blockio-config-file"); c != "" {
if err := blockio.SetConfigFromFile(c, false); err != nil {
return nil, fmt.Errorf("blockio-config-file error: %w", err)
}
}
if c := context.String("blockio-class"); c != "" {
if c := cliContext.String("blockio-class"); c != "" {
if linuxBlockIO, err := blockio.OciLinuxBlockIO(c); err == nil {
opts = append(opts, oci.WithBlockIO(linuxBlockIO))
} else {
return nil, fmt.Errorf("blockio-class error: %w", err)
}
}
if c := context.String("rdt-class"); c != "" {
if c := cliContext.String("rdt-class"); c != "" {
opts = append(opts, oci.WithRdt(c, "", ""))
}
if hostname := context.String("hostname"); hostname != "" {
if hostname := cliContext.String("hostname"); hostname != "" {
opts = append(opts, oci.WithHostname(hostname))
}
}
if context.Bool("cni") {
if cliContext.Bool("cni") {
cniMeta := &commands.NetworkMetaData{EnableCni: true}
cOpts = append(cOpts, containerd.WithContainerExtension(commands.CtrCniMetadataExtension, cniMeta))
}
runtimeOpts, err := commands.RuntimeOptions(context)
runtimeOpts, err := commands.RuntimeOptions(cliContext)
if err != nil {
return nil, err
}
cOpts = append(cOpts, containerd.WithRuntime(context.String("runtime"), runtimeOpts))
cOpts = append(cOpts, containerd.WithRuntime(cliContext.String("runtime"), runtimeOpts))
opts = append(opts, oci.WithAnnotations(commands.LabelArgs(context.StringSlice("label"))))
opts = append(opts, oci.WithAnnotations(commands.LabelArgs(cliContext.StringSlice("label"))))
var s specs.Spec
spec = containerd.WithSpec(&s, opts...)
@ -456,7 +456,7 @@ func validNamespace(ns string) bool {
}
}
func getNetNSPath(_ gocontext.Context, task containerd.Task) (string, error) {
func getNetNSPath(_ context.Context, task containerd.Task) (string, error) {
return fmt.Sprintf("/proc/%d/ns/net", task.Pid()), nil
}
@ -464,7 +464,7 @@ func getNetNSPath(_ gocontext.Context, task containerd.Task) (string, error) {
// This is used from the `run` command to avoid creating a registry with auto-refresh enabled.
// It also provides a way to override the CDI spec file paths if required.
func withStaticCDIRegistry() oci.SpecOpts {
return func(ctx gocontext.Context, _ oci.Client, _ *containers.Container, s *oci.Spec) error {
return func(ctx context.Context, _ oci.Client, _ *containers.Container, s *oci.Spec) error {
_ = cdi.Configure(cdi.WithAutoRefresh(false))
if err := cdi.Refresh(); err != nil {
// We don't consider registry refresh failure a fatal error.

View File

@ -17,7 +17,7 @@
package run
import (
gocontext "context"
"context"
"errors"
"strings"
@ -41,32 +41,32 @@ var platformRunFlags = []cli.Flag{
}
// NewContainer creates a new container
func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli.Context) (containerd.Container, error) {
func NewContainer(ctx context.Context, client *containerd.Client, cliContext *cli.Context) (containerd.Container, error) {
var (
id string
opts []oci.SpecOpts
cOpts []containerd.NewContainerOpts
spec containerd.NewContainerOpts
config = context.IsSet("config")
config = cliContext.IsSet("config")
)
if sandbox := context.String("sandbox"); sandbox != "" {
if sandbox := cliContext.String("sandbox"); sandbox != "" {
cOpts = append(cOpts, containerd.WithSandbox(sandbox))
}
if config {
id = context.Args().First()
opts = append(opts, oci.WithSpecFromFile(context.String("config")))
cOpts = append(cOpts, containerd.WithContainerLabels(commands.LabelArgs(context.StringSlice("label"))))
id = cliContext.Args().First()
opts = append(opts, oci.WithSpecFromFile(cliContext.String("config")))
cOpts = append(cOpts, containerd.WithContainerLabels(commands.LabelArgs(cliContext.StringSlice("label"))))
} else {
var (
ref = context.Args().First()
args = context.Args().Slice()[2:]
ref = cliContext.Args().First()
args = cliContext.Args().Slice()[2:]
)
id = context.Args().Get(1)
snapshotter := context.String("snapshotter")
id = cliContext.Args().Get(1)
snapshotter := cliContext.String("snapshotter")
if snapshotter == "windows-lcow" {
opts = append(opts, oci.WithDefaultSpecForPlatform("linux/amd64"))
// Clear the rootfs section.
@ -76,11 +76,11 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
opts = append(opts, oci.WithWindowNetworksAllowUnqualifiedDNSQuery())
opts = append(opts, oci.WithWindowsIgnoreFlushesDuringBoot())
}
if ef := context.String("env-file"); ef != "" {
if ef := cliContext.String("env-file"); ef != "" {
opts = append(opts, oci.WithEnvFile(ef))
}
opts = append(opts, oci.WithEnv(context.StringSlice("env")))
opts = append(opts, withMounts(context))
opts = append(opts, oci.WithEnv(cliContext.StringSlice("env")))
opts = append(opts, withMounts(cliContext))
image, err := client.GetImage(ctx, ref)
if err != nil {
@ -96,7 +96,7 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
}
}
opts = append(opts, oci.WithImageConfig(image))
labels := buildLabels(commands.LabelArgs(context.StringSlice("label")), image.Labels())
labels := buildLabels(commands.LabelArgs(cliContext.StringSlice("label")), image.Labels())
cOpts = append(cOpts,
containerd.WithImage(image),
containerd.WithImageConfigLabels(image),
@ -104,19 +104,19 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
containerd.WithNewSnapshot(
id,
image,
snapshots.WithLabels(commands.LabelArgs(context.StringSlice("snapshotter-label")))),
snapshots.WithLabels(commands.LabelArgs(cliContext.StringSlice("snapshotter-label")))),
containerd.WithAdditionalContainerLabels(labels))
if len(args) > 0 {
opts = append(opts, oci.WithProcessArgs(args...))
}
if cwd := context.String("cwd"); cwd != "" {
if cwd := cliContext.String("cwd"); cwd != "" {
opts = append(opts, oci.WithProcessCwd(cwd))
}
if user := context.String("user"); user != "" {
if user := cliContext.String("user"); user != "" {
opts = append(opts, oci.WithUser(user))
}
if context.Bool("tty") {
if cliContext.Bool("tty") {
opts = append(opts, oci.WithTTY)
con := console.Current()
@ -126,36 +126,36 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
}
opts = append(opts, oci.WithTTYSize(int(size.Width), int(size.Height)))
}
if context.Bool("net-host") {
if cliContext.Bool("net-host") {
return nil, errors.New("Cannot use host mode networking with Windows containers")
}
if context.Bool("cni") {
if cliContext.Bool("cni") {
ns, err := netns.NewNetNS("")
if err != nil {
return nil, err
}
opts = append(opts, oci.WithWindowsNetworkNamespace(ns.GetPath()))
}
if context.Bool("isolated") {
if cliContext.Bool("isolated") {
opts = append(opts, oci.WithWindowsHyperV)
}
limit := context.Uint64("memory-limit")
limit := cliContext.Uint64("memory-limit")
if limit != 0 {
opts = append(opts, oci.WithMemoryLimit(limit))
}
ccount := context.Uint64("cpu-count")
ccount := cliContext.Uint64("cpu-count")
if ccount != 0 {
opts = append(opts, oci.WithWindowsCPUCount(ccount))
}
cshares := context.Uint64("cpu-shares")
cshares := cliContext.Uint64("cpu-shares")
if cshares != 0 {
opts = append(opts, oci.WithWindowsCPUShares(uint16(cshares)))
}
cmax := context.Uint64("cpu-max")
cmax := cliContext.Uint64("cpu-max")
if cmax != 0 {
opts = append(opts, oci.WithWindowsCPUMaximum(uint16(cmax)))
}
for _, dev := range context.StringSlice("device") {
for _, dev := range cliContext.StringSlice("device") {
idType, devID, ok := strings.Cut(dev, "://")
if !ok {
return nil, errors.New("devices must be in the format IDType://ID")
@ -167,16 +167,16 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
}
}
if context.Bool("cni") {
if cliContext.Bool("cni") {
cniMeta := &commands.NetworkMetaData{EnableCni: true}
cOpts = append(cOpts, containerd.WithContainerExtension(commands.CtrCniMetadataExtension, cniMeta))
}
runtime := context.String("runtime")
runtime := cliContext.String("runtime")
var runtimeOpts interface{}
if runtime == "io.containerd.runhcs.v1" {
runtimeOpts = &options.Options{
Debug: context.Bool("debug"),
Debug: cliContext.Bool("debug"),
}
}
cOpts = append(cOpts, containerd.WithRuntime(runtime, runtimeOpts))
@ -189,7 +189,7 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
return client.NewContainer(ctx, id, cOpts...)
}
func getNetNSPath(ctx gocontext.Context, t containerd.Task) (string, error) {
func getNetNSPath(ctx context.Context, t containerd.Task) (string, error) {
s, err := t.Spec(ctx)
if err != nil {
return "", err

View File

@ -54,16 +54,16 @@ var runCommand = &cli.Command{
Value: defaults.DefaultRuntime,
},
},
Action: func(context *cli.Context) error {
if context.NArg() != 2 {
return cli.ShowSubcommandHelp(context)
Action: func(cliContext *cli.Context) error {
if cliContext.NArg() != 2 {
return cli.ShowSubcommandHelp(cliContext)
}
var (
id = context.Args().Get(1)
runtime = context.String("runtime")
id = cliContext.Args().Get(1)
runtime = cliContext.String("runtime")
)
spec, err := os.ReadFile(context.Args().First())
spec, err := os.ReadFile(cliContext.Args().First())
if err != nil {
return fmt.Errorf("failed to read sandbox config: %w", err)
}
@ -73,7 +73,7 @@ var runCommand = &cli.Command{
return fmt.Errorf("failed to parse sandbox config: %w", err)
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -107,8 +107,8 @@ var listCommand = &cli.Command{
Usage: "The list of filters to apply when querying sandboxes from the store",
},
},
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -116,7 +116,7 @@ var listCommand = &cli.Command{
var (
writer = tabwriter.NewWriter(os.Stdout, 1, 8, 1, ' ', 0)
filters = context.StringSlice("filters")
filters = cliContext.StringSlice("filters")
)
defer func() {
@ -155,16 +155,16 @@ var removeCommand = &cli.Command{
Usage: "Ignore shutdown errors when removing sandbox",
},
},
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
force := context.Bool("force")
force := cliContext.Bool("force")
for _, id := range context.Args().Slice() {
for _, id := range cliContext.Args().Slice() {
sandbox, err := client.LoadSandbox(ctx, id)
if err != nil {
log.G(ctx).WithError(err).Errorf("failed to load sandbox %s", id)

View File

@ -19,7 +19,7 @@
package shim
import (
gocontext "context"
"context"
"io"
"os"
"sync"
@ -37,7 +37,7 @@ var bufPool = sync.Pool{
func prepareStdio(stdin, stdout, stderr string, console bool) (wg *sync.WaitGroup, err error) {
wg = &sync.WaitGroup{}
ctx := gocontext.Background()
ctx := context.Background()
f, err := fifo.OpenFifo(ctx, stdin, unix.O_WRONLY|unix.O_CREAT|unix.O_NONBLOCK, 0700)
if err != nil {

View File

@ -19,7 +19,7 @@
package shim
import (
gocontext "context"
"context"
"errors"
"fmt"
"net"
@ -81,13 +81,13 @@ var Command = &cli.Command{
var startCommand = &cli.Command{
Name: "start",
Usage: "Start a container with a task",
Action: func(context *cli.Context) error {
service, err := getTaskService(context)
Action: func(cliContext *cli.Context) error {
service, err := getTaskService(cliContext)
if err != nil {
return err
}
_, err = service.Start(gocontext.Background(), &task.StartRequest{
ID: context.Args().First(),
_, err = service.Start(context.Background(), &task.StartRequest{
ID: cliContext.Args().First(),
})
return err
},
@ -96,13 +96,13 @@ var startCommand = &cli.Command{
var deleteCommand = &cli.Command{
Name: "delete",
Usage: "Delete a container with a task",
Action: func(context *cli.Context) error {
service, err := getTaskService(context)
Action: func(cliContext *cli.Context) error {
service, err := getTaskService(cliContext)
if err != nil {
return err
}
r, err := service.Delete(gocontext.Background(), &task.DeleteRequest{
ID: context.Args().First(),
r, err := service.Delete(context.Background(), &task.DeleteRequest{
ID: cliContext.Args().First(),
})
if err != nil {
return err
@ -115,13 +115,13 @@ var deleteCommand = &cli.Command{
var stateCommand = &cli.Command{
Name: "state",
Usage: "Get the state of all the processes of the task",
Action: func(context *cli.Context) error {
service, err := getTaskService(context)
Action: func(cliContext *cli.Context) error {
service, err := getTaskService(cliContext)
if err != nil {
return err
}
r, err := service.State(gocontext.Background(), &task.StateRequest{
ID: context.String("id"),
r, err := service.State(context.Background(), &task.StateRequest{
ID: cliContext.String("id"),
})
if err != nil {
return err
@ -155,28 +155,28 @@ var execCommand = &cli.Command{
Usage: "Runtime spec",
},
),
Action: func(context *cli.Context) error {
service, err := getTaskService(context)
Action: func(cliContext *cli.Context) error {
service, err := getTaskService(cliContext)
if err != nil {
return err
}
var (
id = context.Args().First()
ctx = gocontext.Background()
id = cliContext.Args().First()
ctx = context.Background()
)
if id == "" {
return errors.New("exec id must be provided")
}
tty := context.Bool("tty")
wg, err := prepareStdio(context.String("stdin"), context.String("stdout"), context.String("stderr"), tty)
tty := cliContext.Bool("tty")
wg, err := prepareStdio(cliContext.String("stdin"), cliContext.String("stdout"), cliContext.String("stderr"), tty)
if err != nil {
return err
}
// read spec file and extract Any object
spec, err := os.ReadFile(context.String("spec"))
spec, err := os.ReadFile(cliContext.String("spec"))
if err != nil {
return err
}
@ -191,9 +191,9 @@ var execCommand = &cli.Command{
TypeUrl: url,
Value: spec,
},
Stdin: context.String("stdin"),
Stdout: context.String("stdout"),
Stderr: context.String("stderr"),
Stdin: cliContext.String("stdin"),
Stdout: cliContext.String("stdout"),
Stderr: cliContext.String("stderr"),
Terminal: tty,
}
if _, err := service.Exec(ctx, rq); err != nil {
@ -206,7 +206,7 @@ var execCommand = &cli.Command{
return err
}
fmt.Printf("exec running with pid %d\n", r.Pid)
if context.Bool("attach") {
if cliContext.Bool("attach") {
log.L.Info("attaching")
if tty {
current := console.Current()
@ -232,19 +232,19 @@ var execCommand = &cli.Command{
},
}
func getTaskService(context *cli.Context) (task.TTRPCTaskService, error) {
id := context.String("id")
func getTaskService(cliContext *cli.Context) (task.TTRPCTaskService, error) {
id := cliContext.String("id")
if id == "" {
return nil, fmt.Errorf("container id must be specified")
}
ns := context.String("namespace")
ns := cliContext.String("namespace")
// /containerd-shim/ns/id/shim.sock is the old way to generate shim socket,
// compatible it
s1 := filepath.Join(string(filepath.Separator), "containerd-shim", ns, id, "shim.sock")
// this should not error, ctr always get a default ns
ctx := namespaces.WithNamespace(gocontext.Background(), ns)
s2, _ := shim.SocketAddress(ctx, context.String("address"), id)
ctx := namespaces.WithNamespace(context.Background(), ns)
s2, _ := shim.SocketAddress(ctx, cliContext.String("address"), id)
s2 = strings.TrimPrefix(s2, "unix://")
for _, socket := range []string{s2, "\x00" + s1} {

View File

@ -17,7 +17,7 @@
package commands
import (
gocontext "context"
"context"
"os"
"os/signal"
"syscall"
@ -28,11 +28,11 @@ import (
)
type killer interface {
Kill(gocontext.Context, syscall.Signal, ...containerd.KillOpts) error
Kill(context.Context, syscall.Signal, ...containerd.KillOpts) error
}
// ForwardAllSignals forwards signals
func ForwardAllSignals(ctx gocontext.Context, task killer) chan os.Signal {
func ForwardAllSignals(ctx context.Context, task killer) chan os.Signal {
sigc := make(chan os.Signal, 128)
signal.Notify(sigc)
go func() {

View File

@ -17,7 +17,7 @@
package snapshots
import (
gocontext "context"
"context"
"errors"
"fmt"
"io"
@ -67,18 +67,18 @@ var listCommand = &cli.Command{
Name: "list",
Aliases: []string{"ls"},
Usage: "List snapshots",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
var (
snapshotter = client.SnapshotService(context.String("snapshotter"))
snapshotter = client.SnapshotService(cliContext.String("snapshotter"))
tw = tabwriter.NewWriter(os.Stdout, 1, 8, 1, ' ', 0)
)
fmt.Fprintln(tw, "KEY\tPARENT\tKIND\t")
if err := snapshotter.Walk(ctx, func(ctx gocontext.Context, info snapshots.Info) error {
if err := snapshotter.Walk(ctx, func(ctx context.Context, info snapshots.Info) error {
fmt.Fprintf(tw, "%v\t%v\t%v\t\n",
info.Name,
info.Parent,
@ -111,15 +111,15 @@ var diffCommand = &cli.Command{
Usage: "Keep diff content. up to creator to delete it.",
},
}, commands.LabelFlag),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
idA = context.Args().First()
idB = context.Args().Get(1)
idA = cliContext.Args().First()
idB = cliContext.Args().Get(1)
)
if idA == "" {
return errors.New("snapshot id must be provided")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -132,15 +132,15 @@ var diffCommand = &cli.Command{
defer done(ctx)
var desc ocispec.Descriptor
labels := commands.LabelArgs(context.StringSlice("label"))
snapshotter := client.SnapshotService(context.String("snapshotter"))
labels := commands.LabelArgs(cliContext.StringSlice("label"))
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
if context.Bool("keep") {
if cliContext.Bool("keep") {
labels["containerd.io/gc.root"] = time.Now().UTC().Format(time.RFC3339)
}
opts := []diff.Opt{
diff.WithMediaType(context.String("media-type")),
diff.WithReference(context.String("ref")),
diff.WithMediaType(cliContext.String("media-type")),
diff.WithReference(cliContext.String("ref")),
diff.WithLabels(labels),
}
// SOURCE_DATE_EPOCH is propagated via the ctx, so no need to specify diff.WithSourceDateEpoch here
@ -172,7 +172,7 @@ var diffCommand = &cli.Command{
},
}
func withMounts(ctx gocontext.Context, id string, sn snapshots.Snapshotter, f func(mounts []mount.Mount) (ocispec.Descriptor, error)) (ocispec.Descriptor, error) {
func withMounts(ctx context.Context, id string, sn snapshots.Snapshotter, f func(mounts []mount.Mount) (ocispec.Descriptor, error)) (ocispec.Descriptor, error) {
var mounts []mount.Mount
info, err := sn.Stat(ctx, id)
if err != nil {
@ -204,9 +204,9 @@ var usageCommand = &cli.Command{
Usage: "Display size in bytes",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var displaySize func(int64) string
if context.Bool("b") {
if cliContext.Bool("b") {
displaySize = func(s int64) string {
return strconv.FormatInt(s, 10)
}
@ -215,18 +215,18 @@ var usageCommand = &cli.Command{
return progress.Bytes(s).String()
}
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
var (
snapshotter = client.SnapshotService(context.String("snapshotter"))
snapshotter = client.SnapshotService(cliContext.String("snapshotter"))
tw = tabwriter.NewWriter(os.Stdout, 1, 8, 1, ' ', 0)
)
fmt.Fprintln(tw, "KEY\tSIZE\tINODES\t")
if context.NArg() == 0 {
if err := snapshotter.Walk(ctx, func(ctx gocontext.Context, info snapshots.Info) error {
if cliContext.NArg() == 0 {
if err := snapshotter.Walk(ctx, func(ctx context.Context, info snapshots.Info) error {
usage, err := snapshotter.Usage(ctx, info.Name)
if err != nil {
return err
@ -237,7 +237,7 @@ var usageCommand = &cli.Command{
return err
}
} else {
for _, id := range context.Args().Slice() {
for _, id := range cliContext.Args().Slice() {
usage, err := snapshotter.Usage(ctx, id)
if err != nil {
return err
@ -255,14 +255,14 @@ var removeCommand = &cli.Command{
Aliases: []string{"del", "remove", "rm"},
ArgsUsage: "<key> [<key>, ...]",
Usage: "Remove snapshots",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := client.SnapshotService(context.String("snapshotter"))
for _, key := range context.Args().Slice() {
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
for _, key := range cliContext.Args().Slice() {
err = snapshotter.Remove(ctx, key)
if err != nil {
return fmt.Errorf("failed to remove %q: %w", key, err)
@ -288,22 +288,22 @@ var prepareCommand = &cli.Command{
Usage: "Print out snapshot mounts as JSON",
},
},
Action: func(context *cli.Context) error {
if narg := context.NArg(); narg < 1 || narg > 2 {
return cli.ShowSubcommandHelp(context)
Action: func(cliContext *cli.Context) error {
if narg := cliContext.NArg(); narg < 1 || narg > 2 {
return cli.ShowSubcommandHelp(cliContext)
}
var (
target = context.String("target")
key = context.Args().Get(0)
parent = context.Args().Get(1)
target = cliContext.String("target")
key = cliContext.Args().Get(0)
parent = cliContext.Args().Get(1)
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := client.SnapshotService(context.String("snapshotter"))
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
labels := map[string]string{
"containerd.io/gc.root": time.Now().UTC().Format(time.RFC3339),
}
@ -317,7 +317,7 @@ var prepareCommand = &cli.Command{
printMounts(target, mounts)
}
if context.Bool("mounts") {
if cliContext.Bool("mounts") {
commands.PrintAsJSON(mounts)
}
@ -340,22 +340,22 @@ var viewCommand = &cli.Command{
Usage: "Print out snapshot mounts as JSON",
},
},
Action: func(context *cli.Context) error {
if narg := context.NArg(); narg < 1 || narg > 2 {
return cli.ShowSubcommandHelp(context)
Action: func(cliContext *cli.Context) error {
if narg := cliContext.NArg(); narg < 1 || narg > 2 {
return cli.ShowSubcommandHelp(cliContext)
}
var (
target = context.String("target")
key = context.Args().Get(0)
parent = context.Args().Get(1)
target = cliContext.String("target")
key = cliContext.Args().Get(0)
parent = cliContext.Args().Get(1)
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := client.SnapshotService(context.String("snapshotter"))
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
mounts, err := snapshotter.View(ctx, key, parent)
if err != nil {
return err
@ -365,7 +365,7 @@ var viewCommand = &cli.Command{
printMounts(target, mounts)
}
if context.Bool("mounts") {
if cliContext.Bool("mounts") {
commands.PrintAsJSON(mounts)
}
@ -378,20 +378,20 @@ var mountCommand = &cli.Command{
Aliases: []string{"m", "mount"},
Usage: "Mount gets mount commands for the snapshots",
ArgsUsage: "<target> <key>",
Action: func(context *cli.Context) error {
if context.NArg() != 2 {
return cli.ShowSubcommandHelp(context)
Action: func(cliContext *cli.Context) error {
if cliContext.NArg() != 2 {
return cli.ShowSubcommandHelp(cliContext)
}
var (
target = context.Args().Get(0)
key = context.Args().Get(1)
target = cliContext.Args().Get(0)
key = cliContext.Args().Get(1)
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := client.SnapshotService(context.String("snapshotter"))
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
mounts, err := snapshotter.Mounts(ctx, key)
if err != nil {
return err
@ -407,20 +407,20 @@ var commitCommand = &cli.Command{
Name: "commit",
Usage: "Commit an active snapshot into the provided name",
ArgsUsage: "<key> <active>",
Action: func(context *cli.Context) error {
if context.NArg() != 2 {
return cli.ShowSubcommandHelp(context)
Action: func(cliContext *cli.Context) error {
if cliContext.NArg() != 2 {
return cli.ShowSubcommandHelp(cliContext)
}
var (
key = context.Args().Get(0)
active = context.Args().Get(1)
key = cliContext.Args().Get(0)
active = cliContext.Args().Get(1)
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := client.SnapshotService(context.String("snapshotter"))
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
labels := map[string]string{
"containerd.io/gc.root": time.Now().UTC().Format(time.RFC3339),
}
@ -431,18 +431,18 @@ var commitCommand = &cli.Command{
var treeCommand = &cli.Command{
Name: "tree",
Usage: "Display tree view of snapshot branches",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
var (
snapshotter = client.SnapshotService(context.String("snapshotter"))
snapshotter = client.SnapshotService(cliContext.String("snapshotter"))
tree = newSnapshotTree()
)
if err := snapshotter.Walk(ctx, func(ctx gocontext.Context, info snapshots.Info) error {
if err := snapshotter.Walk(ctx, func(ctx context.Context, info snapshots.Info) error {
// Get or create node and add node details
tree.add(info)
return nil
@ -460,18 +460,18 @@ var infoCommand = &cli.Command{
Name: "info",
Usage: "Get info about a snapshot",
ArgsUsage: "<key>",
Action: func(context *cli.Context) error {
if context.NArg() != 1 {
return cli.ShowSubcommandHelp(context)
Action: func(cliContext *cli.Context) error {
if cliContext.NArg() != 1 {
return cli.ShowSubcommandHelp(cliContext)
}
key := context.Args().Get(0)
client, ctx, cancel, err := commands.NewClient(context)
key := cliContext.Args().Get(0)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := client.SnapshotService(context.String("snapshotter"))
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
info, err := snapshotter.Stat(ctx, key)
if err != nil {
return err
@ -488,15 +488,15 @@ var setLabelCommand = &cli.Command{
Usage: "Add labels to content",
ArgsUsage: "<name> [<label>=<value> ...]",
Description: "labels snapshots in the snapshotter",
Action: func(context *cli.Context) error {
key, labels := commands.ObjectWithLabelArgs(context)
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
key, labels := commands.ObjectWithLabelArgs(cliContext)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
snapshotter := client.SnapshotService(context.String("snapshotter"))
snapshotter := client.SnapshotService(cliContext.String("snapshotter"))
info := snapshots.Info{
Name: key,
@ -537,12 +537,12 @@ var unpackCommand = &cli.Command{
Usage: "Unpack applies layers from a manifest to a snapshot",
ArgsUsage: "[flags] <digest>",
Flags: commands.SnapshotterFlags,
Action: func(context *cli.Context) error {
dgst, err := digest.Parse(context.Args().First())
Action: func(cliContext *cli.Context) error {
dgst, err := digest.Parse(cliContext.Args().First())
if err != nil {
return err
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -557,7 +557,7 @@ var unpackCommand = &cli.Command{
for _, image := range images {
if image.Target().Digest == dgst {
fmt.Printf("unpacking %s (%s)...", dgst, image.Target().MediaType)
if err := image.Unpack(ctx, context.String("snapshotter")); err != nil {
if err := image.Unpack(ctx, cliContext.String("snapshotter")); err != nil {
fmt.Println()
return err
}
@ -570,7 +570,7 @@ var unpackCommand = &cli.Command{
return errors.New("manifest not found")
}
// TODO: Get rootfs from Image
//log.G(ctx).Infof("chain ID: %s", chainID.String())
// log.G(ctx).Infof("chain ID: %s", chainID.String())
return nil
},
}

View File

@ -28,13 +28,13 @@ var attachCommand = &cli.Command{
Name: "attach",
Usage: "Attach to the IO of a running container",
ArgsUsage: "CONTAINER",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
container, err := client.LoadContainer(ctx, context.Args().First())
container, err := client.LoadContainer(ctx, cliContext.Args().First())
if err != nil {
return err
}

View File

@ -44,12 +44,12 @@ var checkpointCommand = &cli.Command{
Usage: "Path to criu work files and logs",
},
},
Action: func(context *cli.Context) error {
id := context.Args().First()
Action: func(cliContext *cli.Context) error {
id := cliContext.Args().First()
if id == "" {
return errors.New("container id must be provided")
}
client, ctx, cancel, err := commands.NewClient(context, containerd.WithDefaultRuntime(context.String("runtime")))
client, ctx, cancel, err := commands.NewClient(cliContext, containerd.WithDefaultRuntime(cliContext.String("runtime")))
if err != nil {
return err
}
@ -66,12 +66,12 @@ var checkpointCommand = &cli.Command{
if err != nil {
return err
}
opts := []containerd.CheckpointTaskOpts{withCheckpointOpts(info.Runtime.Name, context)}
opts := []containerd.CheckpointTaskOpts{withCheckpointOpts(info.Runtime.Name, cliContext)}
checkpoint, err := task.Checkpoint(ctx, opts...)
if err != nil {
return err
}
if context.String("image-path") == "" {
if cliContext.String("image-path") == "" {
fmt.Println(checkpoint.Name())
}
return nil
@ -79,17 +79,17 @@ var checkpointCommand = &cli.Command{
}
// withCheckpointOpts only suitable for runc runtime now
func withCheckpointOpts(rt string, context *cli.Context) containerd.CheckpointTaskOpts {
func withCheckpointOpts(rt string, cliContext *cli.Context) containerd.CheckpointTaskOpts {
return func(r *containerd.CheckpointTaskInfo) error {
imagePath := context.String("image-path")
workPath := context.String("work-path")
imagePath := cliContext.String("image-path")
workPath := cliContext.String("work-path")
if r.Options == nil {
r.Options = &options.CheckpointOptions{}
}
opts, _ := r.Options.(*options.CheckpointOptions)
if context.Bool("exit") {
if cliContext.Bool("exit") {
opts.Exit = true
}
if imagePath != "" {

View File

@ -17,7 +17,7 @@
package tasks
import (
gocontext "context"
"context"
containerd "github.com/containerd/containerd/v2/client"
"github.com/containerd/containerd/v2/cmd/ctr/commands"
@ -42,12 +42,12 @@ var deleteCommand = &cli.Command{
Usage: "Process ID to kill",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
execID = context.String("exec-id")
force = context.Bool("force")
execID = cliContext.String("exec-id")
force = cliContext.Bool("force")
)
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -58,7 +58,7 @@ var deleteCommand = &cli.Command{
}
var exitErr error
if execID != "" {
task, err := loadTask(ctx, client, context.Args().First())
task, err := loadTask(ctx, client, cliContext.Args().First())
if err != nil {
return err
}
@ -74,7 +74,7 @@ var deleteCommand = &cli.Command{
return cli.Exit("", int(ec))
}
} else {
for _, target := range context.Args().Slice() {
for _, target := range cliContext.Args().Slice() {
task, err := loadTask(ctx, client, target)
if err != nil {
if exitErr == nil {
@ -100,7 +100,7 @@ var deleteCommand = &cli.Command{
},
}
func loadTask(ctx gocontext.Context, client *containerd.Client, containerID string) (containerd.Task, error) {
func loadTask(ctx context.Context, client *containerd.Client, containerID string) (containerd.Task, error) {
container, err := client.LoadContainer(ctx, containerID)
if err != nil {
return nil, err

View File

@ -68,17 +68,17 @@ var execCommand = &cli.Command{
Usage: "User id or name",
},
},
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
id = context.Args().First()
args = context.Args().Tail()
tty = context.Bool("tty")
detach = context.Bool("detach")
id = cliContext.Args().First()
args = cliContext.Args().Tail()
tty = cliContext.Bool("tty")
detach = cliContext.Bool("detach")
)
if id == "" {
return errors.New("container id must be provided")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -91,7 +91,7 @@ var execCommand = &cli.Command{
if err != nil {
return err
}
if user := context.String("user"); user != "" {
if user := cliContext.String("user"); user != "" {
c, err := container.Info(ctx)
if err != nil {
return err
@ -105,7 +105,7 @@ var execCommand = &cli.Command{
pspec.Terminal = tty
pspec.Args = args
if cwd := context.String("cwd"); cwd != "" {
if cwd := cliContext.String("cwd"); cwd != "" {
pspec.Cwd = cwd
}
@ -122,8 +122,8 @@ var execCommand = &cli.Command{
con console.Console
)
fifoDir := context.String("fifo-dir")
logURI := context.String("log-uri")
fifoDir := cliContext.String("fifo-dir")
logURI := cliContext.String("log-uri")
ioOpts := []cio.Opt{cio.WithFIFODir(fifoDir)}
switch {
case tty && logURI != "":
@ -150,7 +150,7 @@ var execCommand = &cli.Command{
ioCreator = cio.NewCreator(append([]cio.Opt{cio.WithStreams(stdinC, os.Stdout, os.Stderr)}, ioOpts...)...)
}
process, err := task.Exec(ctx, context.String("exec-id"), pspec, ioCreator)
process, err := task.Exec(ctx, cliContext.String("exec-id"), pspec, ioCreator)
if err != nil {
return err
}

View File

@ -82,8 +82,8 @@ var killCommand = &cli.Command{
Usage: "Send signal to all processes inside the container",
},
},
Action: func(context *cli.Context) error {
id := context.Args().First()
Action: func(cliContext *cli.Context) error {
id := cliContext.Args().First()
if id == "" {
return errors.New("container id must be provided")
}
@ -92,14 +92,14 @@ var killCommand = &cli.Command{
return err
}
var (
all = context.Bool("all")
execID = context.String("exec-id")
all = cliContext.Bool("all")
execID = cliContext.String("exec-id")
opts []containerd.KillOpts
)
if all && execID != "" {
return errors.New("specify an exec-id or all; not both")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -114,8 +114,8 @@ var killCommand = &cli.Command{
if err != nil {
return err
}
if context.String("signal") != "" {
sig, err = signal.ParseSignal(context.String("signal"))
if cliContext.String("signal") != "" {
sig, err = signal.ParseSignal(cliContext.String("signal"))
if err != nil {
return err
}

View File

@ -38,9 +38,9 @@ var listCommand = &cli.Command{
Usage: "Print only the task id",
},
},
Action: func(context *cli.Context) error {
quiet := context.Bool("quiet")
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
quiet := cliContext.Bool("quiet")
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}

View File

@ -49,13 +49,13 @@ var metricsCommand = &cli.Command{
Value: formatTable,
},
},
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
container, err := client.LoadContainer(ctx, context.Args().First())
container, err := client.LoadContainer(ctx, cliContext.Args().First())
if err != nil {
return err
}
@ -83,7 +83,7 @@ var metricsCommand = &cli.Command{
return err
}
switch context.String(formatFlag) {
switch cliContext.String(formatFlag) {
case formatTable:
w := tabwriter.NewWriter(os.Stdout, 1, 8, 4, ' ', 0)
fmt.Fprintf(w, "ID\tTIMESTAMP\t\n")

View File

@ -25,13 +25,13 @@ var pauseCommand = &cli.Command{
Name: "pause",
Usage: "Pause an existing container",
ArgsUsage: "CONTAINER",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
container, err := client.LoadContainer(ctx, context.Args().First())
container, err := client.LoadContainer(ctx, cliContext.Args().First())
if err != nil {
return err
}

View File

@ -31,12 +31,12 @@ var psCommand = &cli.Command{
Name: "ps",
Usage: "List processes for container",
ArgsUsage: "CONTAINER",
Action: func(context *cli.Context) error {
id := context.Args().First()
Action: func(cliContext *cli.Context) error {
id := cliContext.Args().First()
if id == "" {
return errors.New("container id must be provided")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}

View File

@ -25,13 +25,13 @@ var resumeCommand = &cli.Command{
Name: "resume",
Usage: "Resume a paused container",
ArgsUsage: "CONTAINER",
Action: func(context *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(context)
Action: func(cliContext *cli.Context) error {
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
defer cancel()
container, err := client.LoadContainer(ctx, context.Args().First())
container, err := client.LoadContainer(ctx, cliContext.Args().First())
if err != nil {
return err
}

View File

@ -55,16 +55,16 @@ var startCommand = &cli.Command{
Usage: "Detach from the task after it has started execution",
},
}...),
Action: func(context *cli.Context) error {
Action: func(cliContext *cli.Context) error {
var (
err error
id = context.Args().Get(0)
detach = context.Bool("detach")
id = cliContext.Args().Get(0)
detach = cliContext.Bool("detach")
)
if id == "" {
return errors.New("container id must be provided")
}
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}
@ -80,8 +80,8 @@ var startCommand = &cli.Command{
}
var (
tty = spec.Process.Terminal
opts = GetNewTaskOpts(context)
ioOpts = []cio.Opt{cio.WithFIFODir(context.String("fifo-dir"))}
opts = GetNewTaskOpts(cliContext)
ioOpts = []cio.Opt{cio.WithFIFODir(cliContext.String("fifo-dir"))}
)
var con console.Console
if tty {
@ -92,7 +92,7 @@ var startCommand = &cli.Command{
}
}
task, err := NewTask(ctx, client, container, "", con, context.Bool("null-io"), context.String("log-uri"), ioOpts, opts...)
task, err := NewTask(ctx, client, container, "", con, cliContext.Bool("null-io"), cliContext.String("log-uri"), ioOpts, opts...)
if err != nil {
return err
}
@ -108,8 +108,8 @@ var startCommand = &cli.Command{
return err
}
}
if context.IsSet("pid-file") {
if err := commands.WritePidFile(context.String("pid-file"), int(task.Pid())); err != nil {
if cliContext.IsSet("pid-file") {
if err := commands.WritePidFile(cliContext.String("pid-file"), int(task.Pid())); err != nil {
return err
}
}

View File

@ -17,13 +17,13 @@
package tasks
import (
gocontext "context"
"context"
"github.com/urfave/cli/v2"
)
type resizer interface {
Resize(ctx gocontext.Context, w, h uint32) error
Resize(ctx context.Context, w, h uint32) error
}
// Command is the cli command for managing tasks

View File

@ -19,7 +19,7 @@
package tasks
import (
gocontext "context"
"context"
"errors"
"net/url"
"os"
@ -41,7 +41,7 @@ var platformStartFlags = []cli.Flag{
}
// HandleConsoleResize resizes the console
func HandleConsoleResize(ctx gocontext.Context, task resizer, con console.Console) error {
func HandleConsoleResize(ctx context.Context, task resizer, con console.Console) error {
// do an initial resize of the console
size, err := con.Size()
if err != nil {
@ -68,7 +68,7 @@ func HandleConsoleResize(ctx gocontext.Context, task resizer, con console.Consol
}
// NewTask creates a new task
func NewTask(ctx gocontext.Context, client *containerd.Client, container containerd.Container, checkpoint string, con console.Console, nullIO bool, logURI string, ioOpts []cio.Opt, opts ...containerd.NewTaskOpts) (containerd.Task, error) {
func NewTask(ctx context.Context, client *containerd.Client, container containerd.Container, checkpoint string, con console.Console, nullIO bool, logURI string, ioOpts []cio.Opt, opts ...containerd.NewTaskOpts) (containerd.Task, error) {
stdinC := &stdinCloser{
stdin: os.Stdin,
}
@ -121,8 +121,8 @@ func NewTask(ctx gocontext.Context, client *containerd.Client, container contain
}
// GetNewTaskOpts resolves containerd.NewTaskOpts from cli.Context
func GetNewTaskOpts(context *cli.Context) []containerd.NewTaskOpts {
if context.Bool("no-pivot") {
func GetNewTaskOpts(cliContext *cli.Context) []containerd.NewTaskOpts {
if cliContext.Bool("no-pivot") {
return []containerd.NewTaskOpts{containerd.WithNoPivotRoot}
}
return nil

View File

@ -17,7 +17,7 @@
package tasks
import (
gocontext "context"
"context"
"errors"
"net/url"
"time"
@ -32,7 +32,7 @@ import (
var platformStartFlags = []cli.Flag{}
// HandleConsoleResize resizes the console
func HandleConsoleResize(ctx gocontext.Context, task resizer, con console.Console) error {
func HandleConsoleResize(ctx context.Context, task resizer, con console.Console) error {
// do an initial resize of the console
size, err := con.Size()
if err != nil {
@ -61,7 +61,7 @@ func HandleConsoleResize(ctx gocontext.Context, task resizer, con console.Consol
}
// NewTask creates a new task
func NewTask(ctx gocontext.Context, client *containerd.Client, container containerd.Container, _ string, con console.Console, nullIO bool, logURI string, ioOpts []cio.Opt, opts ...containerd.NewTaskOpts) (containerd.Task, error) {
func NewTask(ctx context.Context, client *containerd.Client, container containerd.Container, _ string, con console.Console, nullIO bool, logURI string, ioOpts []cio.Opt, opts ...containerd.NewTaskOpts) (containerd.Task, error) {
var ioCreator cio.Creator
if con != nil {
if nullIO {

View File

@ -29,9 +29,9 @@ import (
var Command = &cli.Command{
Name: "version",
Usage: "Print the client and server versions",
Action: func(context *cli.Context) error {
if context.NArg() != 0 {
return fmt.Errorf("extra arguments: %v", context.Args())
Action: func(cliContext *cli.Context) error {
if cliContext.NArg() != 0 {
return fmt.Errorf("extra arguments: %v", cliContext.Args())
}
fmt.Println("Client:")
@ -39,7 +39,7 @@ var Command = &cli.Command{
fmt.Println(" Revision:", version.Revision)
fmt.Println(" Go version:", version.GoVersion)
fmt.Println("")
client, ctx, cancel, err := commands.NewClient(context)
client, ctx, cancel, err := commands.NewClient(cliContext)
if err != nil {
return err
}

View File

@ -20,7 +20,6 @@ package server
import (
"context"
gocontext "context"
"fmt"
"github.com/containerd/typeurl/v2"
@ -147,7 +146,7 @@ func updateContainerSpec(ctx context.Context, cntr containerd.Container, spec *r
if err != nil {
return fmt.Errorf("failed to marshal spec %+v: %w", spec, err)
}
if err := cntr.Update(ctx, func(ctx gocontext.Context, client *containerd.Client, c *containers.Container) error {
if err := cntr.Update(ctx, func(ctx context.Context, client *containerd.Client, c *containers.Container) error {
c.Spec = s
return nil
}); err != nil {