github.com/containerd/Containerd@v1.4.13/pkg/timeout/timeout.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 timeout
    18  
    19  import (
    20  	"context"
    21  	"sync"
    22  	"time"
    23  )
    24  
    25  var (
    26  	mu       sync.Mutex
    27  	timeouts = make(map[string]time.Duration)
    28  
    29  	// DefaultTimeout of the timeout package
    30  	DefaultTimeout = 1 * time.Second
    31  )
    32  
    33  // Set the timeout for the key
    34  func Set(key string, t time.Duration) {
    35  	mu.Lock()
    36  	timeouts[key] = t
    37  	mu.Unlock()
    38  }
    39  
    40  // Get returns the timeout for the provided key
    41  func Get(key string) time.Duration {
    42  	mu.Lock()
    43  	t, ok := timeouts[key]
    44  	mu.Unlock()
    45  	if !ok {
    46  		t = DefaultTimeout
    47  	}
    48  	return t
    49  }
    50  
    51  // WithContext returns a context with the specified timeout for the provided key
    52  func WithContext(ctx context.Context, key string) (context.Context, func()) {
    53  	t := Get(key)
    54  	return context.WithTimeout(ctx, t)
    55  }
    56  
    57  // All returns all keys and their timeouts
    58  func All() map[string]time.Duration {
    59  	out := make(map[string]time.Duration)
    60  	mu.Lock()
    61  	defer mu.Unlock()
    62  	for k, v := range timeouts {
    63  		out[k] = v
    64  	}
    65  	return out
    66  }