github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/plugin/defs.go (about)

     1  package plugin // import "github.com/docker/docker/plugin"
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"sync"
     7  
     8  	"github.com/docker/docker/pkg/plugins"
     9  	v2 "github.com/docker/docker/plugin/v2"
    10  	specs "github.com/opencontainers/runtime-spec/specs-go"
    11  )
    12  
    13  // Store manages the plugin inventory in memory and on-disk
    14  type Store struct {
    15  	sync.RWMutex
    16  	plugins  map[string]*v2.Plugin
    17  	specOpts map[string][]SpecOpt
    18  	/* handlers are necessary for transition path of legacy plugins
    19  	 * to the new model. Legacy plugins use Handle() for registering an
    20  	 * activation callback.*/
    21  	handlers map[string][]func(string, *plugins.Client)
    22  }
    23  
    24  // NewStore creates a Store.
    25  func NewStore() *Store {
    26  	return &Store{
    27  		plugins:  make(map[string]*v2.Plugin),
    28  		specOpts: make(map[string][]SpecOpt),
    29  		handlers: make(map[string][]func(string, *plugins.Client)),
    30  	}
    31  }
    32  
    33  // SpecOpt is used for subsystems that need to modify the runtime spec of a plugin
    34  type SpecOpt func(*specs.Spec)
    35  
    36  // CreateOpt is used to configure specific plugin details when created
    37  type CreateOpt func(p *v2.Plugin)
    38  
    39  // WithSwarmService is a CreateOpt that flags the passed in a plugin as a plugin
    40  // managed by swarm
    41  func WithSwarmService(id string) CreateOpt {
    42  	return func(p *v2.Plugin) {
    43  		p.SwarmServiceID = id
    44  	}
    45  }
    46  
    47  // WithEnv is a CreateOpt that passes the user-provided environment variables
    48  // to the plugin container, de-duplicating variables with the same names case
    49  // sensitively and only appends valid key=value pairs
    50  func WithEnv(env []string) CreateOpt {
    51  	return func(p *v2.Plugin) {
    52  		effectiveEnv := make(map[string]string)
    53  		for _, penv := range p.PluginObj.Config.Env {
    54  			if penv.Value != nil {
    55  				effectiveEnv[penv.Name] = *penv.Value
    56  			}
    57  		}
    58  		for _, line := range env {
    59  			if pair := strings.SplitN(line, "=", 2); len(pair) > 1 {
    60  				effectiveEnv[pair[0]] = pair[1]
    61  			}
    62  		}
    63  		p.PluginObj.Settings.Env = make([]string, len(effectiveEnv))
    64  		i := 0
    65  		for key, value := range effectiveEnv {
    66  			p.PluginObj.Settings.Env[i] = fmt.Sprintf("%s=%s", key, value)
    67  			i++
    68  		}
    69  	}
    70  }
    71  
    72  // WithSpecMounts is a SpecOpt which appends the provided mounts to the runtime spec
    73  func WithSpecMounts(mounts []specs.Mount) SpecOpt {
    74  	return func(s *specs.Spec) {
    75  		s.Mounts = append(s.Mounts, mounts...)
    76  	}
    77  }