...

Source file src/github.com/docker/distribution/context/context.go

Documentation: github.com/docker/distribution/context

     1  package context
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  
     7  	"github.com/docker/distribution/uuid"
     8  )
     9  
    10  // instanceContext is a context that provides only an instance id. It is
    11  // provided as the main background context.
    12  type instanceContext struct {
    13  	context.Context
    14  	id   string    // id of context, logged as "instance.id"
    15  	once sync.Once // once protect generation of the id
    16  }
    17  
    18  func (ic *instanceContext) Value(key interface{}) interface{} {
    19  	if key == "instance.id" {
    20  		ic.once.Do(func() {
    21  			// We want to lazy initialize the UUID such that we don't
    22  			// call a random generator from the package initialization
    23  			// code. For various reasons random could not be available
    24  			// https://github.com/docker/distribution/issues/782
    25  			ic.id = uuid.Generate().String()
    26  		})
    27  		return ic.id
    28  	}
    29  
    30  	return ic.Context.Value(key)
    31  }
    32  
    33  var background = &instanceContext{
    34  	Context: context.Background(),
    35  }
    36  
    37  // Background returns a non-nil, empty Context. The background context
    38  // provides a single key, "instance.id" that is globally unique to the
    39  // process.
    40  func Background() context.Context {
    41  	return background
    42  }
    43  
    44  // stringMapContext is a simple context implementation that checks a map for a
    45  // key, falling back to a parent if not present.
    46  type stringMapContext struct {
    47  	context.Context
    48  	m map[string]interface{}
    49  }
    50  
    51  // WithValues returns a context that proxies lookups through a map. Only
    52  // supports string keys.
    53  func WithValues(ctx context.Context, m map[string]interface{}) context.Context {
    54  	mo := make(map[string]interface{}, len(m)) // make our own copy.
    55  	for k, v := range m {
    56  		mo[k] = v
    57  	}
    58  
    59  	return stringMapContext{
    60  		Context: ctx,
    61  		m:       mo,
    62  	}
    63  }
    64  
    65  func (smc stringMapContext) Value(key interface{}) interface{} {
    66  	if ks, ok := key.(string); ok {
    67  		if v, ok := smc.m[ks]; ok {
    68  			return v
    69  		}
    70  	}
    71  
    72  	return smc.Context.Value(key)
    73  }
    74  

View as plain text