github.com/containerd/Containerd@v1.4.13/lease.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 containerd
    18  
    19  import (
    20  	"context"
    21  	"time"
    22  
    23  	"github.com/containerd/containerd/leases"
    24  )
    25  
    26  // WithLease attaches a lease on the context
    27  func (c *Client) WithLease(ctx context.Context, opts ...leases.Opt) (context.Context, func(context.Context) error, error) {
    28  	nop := func(context.Context) error { return nil }
    29  
    30  	_, ok := leases.FromContext(ctx)
    31  	if ok {
    32  		return ctx, nop, nil
    33  	}
    34  
    35  	ls := c.LeasesService()
    36  
    37  	if len(opts) == 0 {
    38  		// Use default lease configuration if no options provided
    39  		opts = []leases.Opt{
    40  			leases.WithRandomID(),
    41  			leases.WithExpiration(24 * time.Hour),
    42  		}
    43  	}
    44  
    45  	l, err := ls.Create(ctx, opts...)
    46  	if err != nil {
    47  		return ctx, nop, err
    48  	}
    49  
    50  	ctx = leases.WithLease(ctx, l.ID)
    51  	return ctx, func(ctx context.Context) error {
    52  		return ls.Delete(ctx, l)
    53  	}, nil
    54  }