github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/pkg/authorization/plugin.go (about)

     1  package authorization
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/docker/docker/pkg/plugins"
     7  )
     8  
     9  // Plugin allows third party plugins to authorize requests and responses
    10  // in the context of docker API
    11  type Plugin interface {
    12  	// Name returns the registered plugin name
    13  	Name() string
    14  
    15  	// AuthZRequest authorizes the request from the client to the daemon
    16  	AuthZRequest(*Request) (*Response, error)
    17  
    18  	// AuthZResponse authorizes the response from the daemon to the client
    19  	AuthZResponse(*Request) (*Response, error)
    20  }
    21  
    22  // newPlugins constructs and initializes the authorization plugins based on plugin names
    23  func newPlugins(names []string) []Plugin {
    24  	plugins := []Plugin{}
    25  	pluginsMap := make(map[string]struct{})
    26  	for _, name := range names {
    27  		if _, ok := pluginsMap[name]; ok {
    28  			continue
    29  		}
    30  		pluginsMap[name] = struct{}{}
    31  		plugins = append(plugins, newAuthorizationPlugin(name))
    32  	}
    33  	return plugins
    34  }
    35  
    36  // authorizationPlugin is an internal adapter to docker plugin system
    37  type authorizationPlugin struct {
    38  	plugin *plugins.Client
    39  	name   string
    40  	once   sync.Once
    41  }
    42  
    43  func newAuthorizationPlugin(name string) Plugin {
    44  	return &authorizationPlugin{name: name}
    45  }
    46  
    47  func (a *authorizationPlugin) Name() string {
    48  	return a.name
    49  }
    50  
    51  func (a *authorizationPlugin) AuthZRequest(authReq *Request) (*Response, error) {
    52  	if err := a.initPlugin(); err != nil {
    53  		return nil, err
    54  	}
    55  
    56  	authRes := &Response{}
    57  	if err := a.plugin.Call(AuthZApiRequest, authReq, authRes); err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	return authRes, nil
    62  }
    63  
    64  func (a *authorizationPlugin) AuthZResponse(authReq *Request) (*Response, error) {
    65  	if err := a.initPlugin(); err != nil {
    66  		return nil, err
    67  	}
    68  
    69  	authRes := &Response{}
    70  	if err := a.plugin.Call(AuthZApiResponse, authReq, authRes); err != nil {
    71  		return nil, err
    72  	}
    73  
    74  	return authRes, nil
    75  }
    76  
    77  // initPlugin initializes the authorization plugin if needed
    78  func (a *authorizationPlugin) initPlugin() error {
    79  	// Lazy loading of plugins
    80  	var err error
    81  	a.once.Do(func() {
    82  		if a.plugin == nil {
    83  			plugin, e := plugins.Get(a.name, AuthZApiImplements)
    84  			if e != nil {
    85  				err = e
    86  				return
    87  			}
    88  			a.plugin = plugin.Client()
    89  		}
    90  	})
    91  	return err
    92  }