github.com/containerd/Containerd@v1.4.13/cmd/ctr/commands/client.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package commands
    18  
    19  import (
    20  	gocontext "context"
    21  
    22  	"github.com/containerd/containerd"
    23  	"github.com/containerd/containerd/namespaces"
    24  	"github.com/urfave/cli"
    25  )
    26  
    27  // AppContext returns the context for a command. Should only be called once per
    28  // command, near the start.
    29  //
    30  // This will ensure the namespace is picked up and set the timeout, if one is
    31  // defined.
    32  func AppContext(context *cli.Context) (gocontext.Context, gocontext.CancelFunc) {
    33  	var (
    34  		ctx       = gocontext.Background()
    35  		timeout   = context.GlobalDuration("timeout")
    36  		namespace = context.GlobalString("namespace")
    37  		cancel    gocontext.CancelFunc
    38  	)
    39  	ctx = namespaces.WithNamespace(ctx, namespace)
    40  	if timeout > 0 {
    41  		ctx, cancel = gocontext.WithTimeout(ctx, timeout)
    42  	} else {
    43  		ctx, cancel = gocontext.WithCancel(ctx)
    44  	}
    45  	return ctx, cancel
    46  }
    47  
    48  // NewClient returns a new containerd client
    49  func NewClient(context *cli.Context, opts ...containerd.ClientOpt) (*containerd.Client, gocontext.Context, gocontext.CancelFunc, error) {
    50  	timeoutOpt := containerd.WithTimeout(context.GlobalDuration("connect-timeout"))
    51  	opts = append(opts, timeoutOpt)
    52  	client, err := containerd.New(context.GlobalString("address"), opts...)
    53  	if err != nil {
    54  		return nil, nil, nil, err
    55  	}
    56  	ctx, cancel := AppContext(context)
    57  	return client, ctx, cancel, nil
    58  }