github.com/walkingsparrow/docker@v1.4.2-0.20151218153551-b708a2249bfa/pkg/authorization/plugin.go (about)

     1  package authorization
     2  
     3  import (
     4  	"github.com/Sirupsen/logrus"
     5  	"github.com/docker/docker/pkg/plugins"
     6  )
     7  
     8  // Plugin allows third party plugins to authorize requests and responses
     9  // in the context of docker API
    10  type Plugin interface {
    11  	// AuthZRequest authorize the request from the client to the daemon
    12  	AuthZRequest(*Request) (*Response, error)
    13  
    14  	// AuthZResponse authorize the response from the daemon to the client
    15  	AuthZResponse(*Request) (*Response, error)
    16  }
    17  
    18  // NewPlugins constructs and initialize the authorization plugins based on plugin names
    19  func NewPlugins(names []string) []Plugin {
    20  	plugins := make([]Plugin, len(names))
    21  	for i, name := range names {
    22  		plugins[i] = newAuthorizationPlugin(name)
    23  	}
    24  	return plugins
    25  }
    26  
    27  // authorizationPlugin is an internal adapter to docker plugin system
    28  type authorizationPlugin struct {
    29  	plugin *plugins.Plugin
    30  	name   string
    31  }
    32  
    33  func newAuthorizationPlugin(name string) Plugin {
    34  	return &authorizationPlugin{name: name}
    35  }
    36  
    37  func (a *authorizationPlugin) AuthZRequest(authReq *Request) (*Response, error) {
    38  	logrus.Debugf("AuthZ requset using plugins %s", a.name)
    39  
    40  	if err := a.initPlugin(); err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	authRes := &Response{}
    45  	if err := a.plugin.Client.Call(AuthZApiRequest, authReq, authRes); err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	return authRes, nil
    50  }
    51  
    52  func (a *authorizationPlugin) AuthZResponse(authReq *Request) (*Response, error) {
    53  	logrus.Debugf("AuthZ response using plugins %s", a.name)
    54  
    55  	if err := a.initPlugin(); err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	authRes := &Response{}
    60  	if err := a.plugin.Client.Call(AuthZApiResponse, authReq, authRes); err != nil {
    61  		return nil, err
    62  	}
    63  
    64  	return authRes, nil
    65  }
    66  
    67  // initPlugin initialize the authorization plugin if needed
    68  func (a *authorizationPlugin) initPlugin() error {
    69  	// Lazy loading of plugins
    70  	if a.plugin == nil {
    71  		var err error
    72  		a.plugin, err = plugins.Get(a.name, AuthZApiImplements)
    73  		if err != nil {
    74  			return err
    75  		}
    76  	}
    77  	return nil
    78  }