From 85cb1bde1c1938a883381c6d09d5e248f3ddcc56 Mon Sep 17 00:00:00 2001 From: Angelo De Caro Date: Wed, 26 Jul 2017 12:09:07 +0800 Subject: [PATCH] [FAB-5880] MSP cache support This change-set does the following: - it introduces an MSP wrapper that intercepts the validation functions and cache their results. LRU caches are used. - adds tests to validate the implementation This change-set is a joint work with Senthil Nathan. Change-Id: I2027d6ab4331b4923bb00e961ef15a38ce4c8e8b Signed-off-by: Angelo De Caro --- common/config/channel/msp/config.go | 8 +- common/config/channel/msp/config_util.go | 8 +- msp/cache/cache.go | 138 ++++++++++ msp/cache/cache_test.go | 238 ++++++++++++++++++ msp/mgmt/mgmt.go | 11 +- msp/mocks/mocks.go | 121 +++++++++ msp/msp_test.go | 1 - vendor/github.com/golang/groupcache/LICENSE | 191 ++++++++++++++ .../github.com/golang/groupcache/lru/lru.go | 133 ++++++++++ vendor/vendor.json | 6 + 10 files changed, 850 insertions(+), 5 deletions(-) create mode 100644 msp/cache/cache.go create mode 100644 msp/cache/cache_test.go create mode 100644 msp/mocks/mocks.go create mode 100644 vendor/github.com/golang/groupcache/LICENSE create mode 100644 vendor/github.com/golang/groupcache/lru/lru.go diff --git a/common/config/channel/msp/config.go b/common/config/channel/msp/config.go index 40fec19ff2f..8e523a5c92a 100644 --- a/common/config/channel/msp/config.go +++ b/common/config/channel/msp/config.go @@ -22,6 +22,7 @@ import ( "sync" "github.com/hyperledger/fabric/msp" + "github.com/hyperledger/fabric/msp/cache" mspprotos "github.com/hyperledger/fabric/protos/msp" ) @@ -96,7 +97,12 @@ func (bh *MSPConfigHandler) ProposeMSP(tx interface{}, mspConfig *mspprotos.MSPC } // create the msp instance - mspInst, err := msp.NewBccspMsp() + bccspMSP, err := msp.NewBccspMsp() + if err != nil { + return nil, fmt.Errorf("Creating the MSP manager failed, err %s", err) + } + + mspInst, err := cache.New(bccspMSP) if err != nil { return nil, fmt.Errorf("Creating the MSP manager failed, err %s", err) } diff --git a/common/config/channel/msp/config_util.go b/common/config/channel/msp/config_util.go index 36cbed01a84..a5242ab8a07 100644 --- a/common/config/channel/msp/config_util.go +++ b/common/config/channel/msp/config_util.go @@ -24,6 +24,7 @@ import ( "github.com/hyperledger/fabric/protos/utils" "github.com/hyperledger/fabric/common/flogging" + "github.com/hyperledger/fabric/msp/cache" ) var logger = flogging.MustGetLogger("configvalues/msp") @@ -51,7 +52,12 @@ func TemplateGroupMSPWithAdminRolePrincipal(configPath []string, mspConfig *mspp } // create the msp instance - mspInst, err := msp.NewBccspMsp() + bccspMSP, err := msp.NewBccspMsp() + if err != nil { + logger.Panicf("Creating the MSP manager failed, err %s", err) + } + + mspInst, err := cache.New(bccspMSP) if err != nil { logger.Panicf("Creating the MSP manager failed, err %s", err) } diff --git a/msp/cache/cache.go b/msp/cache/cache.go new file mode 100644 index 00000000000..b8686a6110b --- /dev/null +++ b/msp/cache/cache.go @@ -0,0 +1,138 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + +package cache + +import ( + "fmt" + + "sync" + + "github.com/golang/groupcache/lru" + "github.com/hyperledger/fabric/common/flogging" + "github.com/hyperledger/fabric/msp" + pmsp "github.com/hyperledger/fabric/protos/msp" +) + +const ( + deserializeIdentityCacheSize = 100 + validateIdentityCacheSize = 100 + satisfiesPrincipalCacheSize = 100 +) + +var mspLogger = flogging.MustGetLogger("msp") + +func New(o msp.MSP) (msp.MSP, error) { + mspLogger.Debugf("Creating Cache-MSP instance") + if o == nil { + return nil, fmt.Errorf("Invalid passed MSP. It must be different from nil.") + } + + theMsp := &cachedMSP{MSP: o} + theMsp.deserializeIdentityCache = lru.New(deserializeIdentityCacheSize) + theMsp.satisfiesPrincipalCache = lru.New(satisfiesPrincipalCacheSize) + theMsp.validateIdentityCache = lru.New(validateIdentityCacheSize) + + return theMsp, nil +} + +type cachedMSP struct { + msp.MSP + + // cache for DeserializeIdentity. + deserializeIdentityCache *lru.Cache + + dicMutex sync.RWMutex // synchronize access to cache + + // cache for validateIdentity + validateIdentityCache *lru.Cache + + vicMutex sync.RWMutex // synchronize access to cache + + // basically a map of principals=>identities=>stringified to booleans + // specifying whether this identity satisfies this principal + satisfiesPrincipalCache *lru.Cache + + spcMutex sync.RWMutex // synchronize access to cache +} + +func (c *cachedMSP) DeserializeIdentity(serializedIdentity []byte) (msp.Identity, error) { + c.dicMutex.RLock() + cached, ok := c.deserializeIdentityCache.Get(string(serializedIdentity)) + c.dicMutex.RUnlock() + if ok { + return cached.(msp.Identity), nil + } + + id, err := c.MSP.DeserializeIdentity(serializedIdentity) + if err == nil { + c.dicMutex.Lock() + defer c.dicMutex.Unlock() + c.deserializeIdentityCache.Add(string(serializedIdentity), id) + } + return id, err +} + +func (c *cachedMSP) Setup(config *pmsp.MSPConfig) error { + c.cleanCash() + + return c.MSP.Setup(config) +} + +func (c *cachedMSP) Validate(id msp.Identity) error { + identifier := id.GetIdentifier() + key := string(identifier.Mspid + ":" + identifier.Id) + + c.vicMutex.RLock() + _, ok := c.validateIdentityCache.Get(key) + c.vicMutex.RUnlock() + if ok { + // cache only stores if the identity is valid. + return nil + } + + err := c.MSP.Validate(id) + if err == nil { + c.vicMutex.Lock() + defer c.vicMutex.Unlock() + c.validateIdentityCache.Add(key, true) + } + + return err +} + +func (c *cachedMSP) SatisfiesPrincipal(id msp.Identity, principal *pmsp.MSPPrincipal) error { + identifier := id.GetIdentifier() + identityKey := string(identifier.Mspid + ":" + identifier.Id) + principalKey := string(principal.PrincipalClassification) + string(principal.Principal) + key := identityKey + principalKey + + c.spcMutex.RLock() + v, ok := c.satisfiesPrincipalCache.Get(key) + c.spcMutex.RUnlock() + if ok { + if v == nil { + return nil + } + + return v.(error) + } + + err := c.MSP.SatisfiesPrincipal(id, principal) + + c.spcMutex.Lock() + defer c.spcMutex.Unlock() + c.satisfiesPrincipalCache.Add(key, err) + return err +} + +func (c *cachedMSP) cleanCash() error { + c.deserializeIdentityCache = lru.New(deserializeIdentityCacheSize) + c.satisfiesPrincipalCache = lru.New(satisfiesPrincipalCacheSize) + c.validateIdentityCache = lru.New(validateIdentityCacheSize) + + return nil +} diff --git a/msp/cache/cache_test.go b/msp/cache/cache_test.go new file mode 100644 index 00000000000..e88b84fa593 --- /dev/null +++ b/msp/cache/cache_test.go @@ -0,0 +1,238 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + +package cache + +import ( + "testing" + + "github.com/hyperledger/fabric/msp" + "github.com/hyperledger/fabric/msp/mocks" + msp2 "github.com/hyperledger/fabric/protos/msp" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" +) + +func TestNewCacheMsp(t *testing.T) { + i, err := New(nil) + assert.Error(t, err) + assert.Nil(t, i) + assert.Contains(t, err.Error(), "Invalid passed MSP. It must be different from nil.") + + i, err = New(&mocks.MockMSP{}) + assert.NoError(t, err) + assert.NotNil(t, i) +} + +func TestSetup(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + mockMSP.On("Setup", (*msp2.MSPConfig)(nil)).Return(nil) + err = i.Setup(nil) + assert.NoError(t, err) + mockMSP.AssertExpectations(t) + assert.Equal(t, 0, i.(*cachedMSP).deserializeIdentityCache.Len()) + assert.Equal(t, 0, i.(*cachedMSP).satisfiesPrincipalCache.Len()) + assert.Equal(t, 0, i.(*cachedMSP).validateIdentityCache.Len()) +} + +func TestGetType(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + mockMSP.On("GetType").Return(msp.FABRIC) + assert.Equal(t, msp.FABRIC, i.GetType()) + mockMSP.AssertExpectations(t) +} + +func TestGetIdentifier(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + mockMSP.On("GetIdentifier").Return("MSP", nil) + id, err := i.GetIdentifier() + assert.NoError(t, err) + assert.Equal(t, "MSP", id) + mockMSP.AssertExpectations(t) +} + +func TestGetSigningIdentity(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + mockIdentity := &mocks.MockSigningIdentity{Mock: mock.Mock{}, MockIdentity: &mocks.MockIdentity{ID: "Alice"}} + identifier := &msp.IdentityIdentifier{Mspid: "MSP", Id: "Alice"} + mockMSP.On("GetSigningIdentity", identifier).Return(mockIdentity, nil) + id, err := i.GetSigningIdentity(identifier) + assert.NoError(t, err) + assert.Equal(t, mockIdentity, id) + mockMSP.AssertExpectations(t) +} + +func TestGetDefaultSigningIdentity(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + mockIdentity := &mocks.MockSigningIdentity{Mock: mock.Mock{}, MockIdentity: &mocks.MockIdentity{ID: "Alice"}} + mockMSP.On("GetDefaultSigningIdentity").Return(mockIdentity, nil) + id, err := i.GetDefaultSigningIdentity() + assert.NoError(t, err) + assert.Equal(t, mockIdentity, id) + mockMSP.AssertExpectations(t) +} + +func TestGetTLSRootCerts(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + expected := [][]byte{{1}, {2}} + mockMSP.On("GetTLSRootCerts").Return(expected) + certs := i.GetTLSRootCerts() + assert.Equal(t, expected, certs) +} + +func TestGetTLSIntermediateCerts(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + expected := [][]byte{{1}, {2}} + mockMSP.On("GetTLSIntermediateCerts").Return(expected) + certs := i.GetTLSIntermediateCerts() + assert.Equal(t, expected, certs) +} + +func TestDeserializeIdentity(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + // Check id is cached + mockIdentity := &mocks.MockIdentity{ID: "Alice"} + serializedIdentity := []byte{1, 2, 3} + mockMSP.On("DeserializeIdentity", serializedIdentity).Return(mockIdentity, nil) + id, err := i.DeserializeIdentity(serializedIdentity) + assert.NoError(t, err) + assert.Equal(t, mockIdentity, id) + mockMSP.AssertExpectations(t) + // Check the cache + _, ok := i.(*cachedMSP).deserializeIdentityCache.Get(string(serializedIdentity)) + assert.True(t, ok) + + // Check the same object is returned + id, err = i.DeserializeIdentity(serializedIdentity) + assert.NoError(t, err) + assert.True(t, mockIdentity == id) + mockMSP.AssertExpectations(t) + + // Check id is not cached + mockIdentity = &mocks.MockIdentity{ID: "Bob"} + serializedIdentity = []byte{1, 2, 3, 4} + mockMSP.On("DeserializeIdentity", serializedIdentity).Return(mockIdentity, errors.New("Invalid identity")) + id, err = i.DeserializeIdentity(serializedIdentity) + assert.Error(t, err) + assert.Contains(t, err.Error(), "Invalid identity") + mockMSP.AssertExpectations(t) + + _, ok = i.(*cachedMSP).deserializeIdentityCache.Get(string(serializedIdentity)) + assert.False(t, ok) +} + +func TestValidate(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + // Check validation is cached + mockIdentity := &mocks.MockIdentity{ID: "Alice"} + mockIdentity.On("GetIdentifier").Return(&msp.IdentityIdentifier{Mspid: "MSP", Id: "Alice"}) + mockMSP.On("Validate", mockIdentity).Return(nil) + err = i.Validate(mockIdentity) + assert.NoError(t, err) + mockIdentity.AssertExpectations(t) + mockMSP.AssertExpectations(t) + // Check the cache + identifier := mockIdentity.GetIdentifier() + key := string(identifier.Mspid + ":" + identifier.Id) + v, ok := i.(*cachedMSP).validateIdentityCache.Get(string(key)) + assert.True(t, ok) + assert.True(t, v.(bool)) + + // Recheck + err = i.Validate(mockIdentity) + assert.NoError(t, err) + + // Check validation is not cached + mockIdentity = &mocks.MockIdentity{ID: "Bob"} + mockIdentity.On("GetIdentifier").Return(&msp.IdentityIdentifier{Mspid: "MSP", Id: "Bob"}) + mockMSP.On("Validate", mockIdentity).Return(errors.New("Invalid identity")) + err = i.Validate(mockIdentity) + assert.Error(t, err) + mockIdentity.AssertExpectations(t) + mockMSP.AssertExpectations(t) + // Check the cache + identifier = mockIdentity.GetIdentifier() + key = string(identifier.Mspid + ":" + identifier.Id) + _, ok = i.(*cachedMSP).validateIdentityCache.Get(string(key)) + assert.False(t, ok) +} + +func TestSatisfiesPrincipal(t *testing.T) { + mockMSP := &mocks.MockMSP{} + i, err := New(mockMSP) + assert.NoError(t, err) + + // Check validation is cached + mockIdentity := &mocks.MockIdentity{ID: "Alice"} + mockIdentity.On("GetIdentifier").Return(&msp.IdentityIdentifier{Mspid: "MSP", Id: "Alice"}) + mockMSPPrincipal := &msp2.MSPPrincipal{PrincipalClassification: msp2.MSPPrincipal_IDENTITY, Principal: []byte{1, 2, 3}} + mockMSP.On("SatisfiesPrincipal", mockIdentity, mockMSPPrincipal).Return(nil) + mockMSP.SatisfiesPrincipal(mockIdentity, mockMSPPrincipal) + err = i.SatisfiesPrincipal(mockIdentity, mockMSPPrincipal) + assert.NoError(t, err) + mockIdentity.AssertExpectations(t) + mockMSP.AssertExpectations(t) + // Check the cache + identifier := mockIdentity.GetIdentifier() + identityKey := string(identifier.Mspid + ":" + identifier.Id) + principalKey := string(mockMSPPrincipal.PrincipalClassification) + string(mockMSPPrincipal.Principal) + key := identityKey + principalKey + v, ok := i.(*cachedMSP).satisfiesPrincipalCache.Get(key) + assert.True(t, ok) + assert.Nil(t, v) + + // Recheck + err = i.SatisfiesPrincipal(mockIdentity, mockMSPPrincipal) + assert.NoError(t, err) + + // Check validation is not cached + mockIdentity = &mocks.MockIdentity{ID: "Bob"} + mockIdentity.On("GetIdentifier").Return(&msp.IdentityIdentifier{Mspid: "MSP", Id: "Bob"}) + mockMSPPrincipal = &msp2.MSPPrincipal{PrincipalClassification: msp2.MSPPrincipal_IDENTITY, Principal: []byte{1, 2, 3, 4}} + mockMSP.On("SatisfiesPrincipal", mockIdentity, mockMSPPrincipal).Return(errors.New("Invalid")) + mockMSP.SatisfiesPrincipal(mockIdentity, mockMSPPrincipal) + err = i.SatisfiesPrincipal(mockIdentity, mockMSPPrincipal) + assert.Error(t, err) + mockIdentity.AssertExpectations(t) + mockMSP.AssertExpectations(t) + // Check the cache + identifier = mockIdentity.GetIdentifier() + identityKey = string(identifier.Mspid + ":" + identifier.Id) + principalKey = string(mockMSPPrincipal.PrincipalClassification) + string(mockMSPPrincipal.Principal) + key = identityKey + principalKey + v, ok = i.(*cachedMSP).satisfiesPrincipalCache.Get(key) + assert.True(t, ok) + assert.NotNil(t, v) + assert.Contains(t, "Invalid", v.(error).Error()) +} diff --git a/msp/mgmt/mgmt.go b/msp/mgmt/mgmt.go index 1cefe7955ed..9455f69586e 100644 --- a/msp/mgmt/mgmt.go +++ b/msp/mgmt/mgmt.go @@ -27,6 +27,7 @@ import ( "github.com/hyperledger/fabric/common/flogging" "github.com/hyperledger/fabric/core/config" "github.com/hyperledger/fabric/msp" + "github.com/hyperledger/fabric/msp/cache" ) // LoadLocalMsp loads the local MSP from the specified directory @@ -135,11 +136,17 @@ func GetLocalMSP() msp.MSP { if lclMsp == nil { var err error created = true - lclMsp, err = msp.NewBccspMsp() + + bccspMSP, err := msp.NewBccspMsp() + if err != nil { + mspLogger.Fatalf("Failed to initialize local MSP, received err %s", err) + } + + lclMsp, err = cache.New(bccspMSP) if err != nil { mspLogger.Fatalf("Failed to initialize local MSP, received err %s", err) } - localMsp = lclMsp + localMsp = bccspMSP } } diff --git a/msp/mocks/mocks.go b/msp/mocks/mocks.go new file mode 100644 index 00000000000..421f225a1fd --- /dev/null +++ b/msp/mocks/mocks.go @@ -0,0 +1,121 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + +package mocks + +import ( + "time" + + "github.com/hyperledger/fabric/msp" + pmsp "github.com/hyperledger/fabric/protos/msp" + "github.com/stretchr/testify/mock" +) + +type MockMSP struct { + mock.Mock +} + +func (m *MockMSP) DeserializeIdentity(serializedIdentity []byte) (msp.Identity, error) { + args := m.Called(serializedIdentity) + return args.Get(0).(msp.Identity), args.Error(1) +} + +func (m *MockMSP) Setup(config *pmsp.MSPConfig) error { + args := m.Called(config) + return args.Error(0) +} + +func (m *MockMSP) GetType() msp.ProviderType { + args := m.Called() + return args.Get(0).(msp.ProviderType) +} + +func (m *MockMSP) GetIdentifier() (string, error) { + args := m.Called() + return args.String(0), args.Error(1) +} + +func (m *MockMSP) GetSigningIdentity(identifier *msp.IdentityIdentifier) (msp.SigningIdentity, error) { + args := m.Called(identifier) + return args.Get(0).(msp.SigningIdentity), args.Error(1) +} + +func (m *MockMSP) GetDefaultSigningIdentity() (msp.SigningIdentity, error) { + args := m.Called() + return args.Get(0).(msp.SigningIdentity), args.Error(1) +} + +func (m *MockMSP) GetTLSRootCerts() [][]byte { + args := m.Called() + return args.Get(0).([][]byte) +} + +func (m *MockMSP) GetTLSIntermediateCerts() [][]byte { + args := m.Called() + return args.Get(0).([][]byte) +} + +func (m *MockMSP) Validate(id msp.Identity) error { + args := m.Called(id) + return args.Error(0) +} + +func (m *MockMSP) SatisfiesPrincipal(id msp.Identity, principal *pmsp.MSPPrincipal) error { + args := m.Called(id, principal) + return args.Error(0) +} + +type MockIdentity struct { + mock.Mock + + ID string +} + +func (m *MockIdentity) ExpiresAt() time.Time { + panic("implement me") +} + +func (m *MockIdentity) GetIdentifier() *msp.IdentityIdentifier { + args := m.Called() + return args.Get(0).(*msp.IdentityIdentifier) +} + +func (*MockIdentity) GetMSPIdentifier() string { + panic("implement me") +} + +func (*MockIdentity) Validate() error { + panic("implement me") +} + +func (*MockIdentity) GetOrganizationalUnits() []*msp.OUIdentifier { + panic("implement me") +} + +func (*MockIdentity) Verify(msg []byte, sig []byte) error { + panic("implement me") +} + +func (*MockIdentity) Serialize() ([]byte, error) { + panic("implement me") +} + +func (*MockIdentity) SatisfiesPrincipal(principal *pmsp.MSPPrincipal) error { + panic("implement me") +} + +type MockSigningIdentity struct { + mock.Mock + *MockIdentity +} + +func (*MockSigningIdentity) Sign(msg []byte) ([]byte, error) { + panic("implement me") +} + +func (*MockSigningIdentity) GetPublicVersion() msp.Identity { + panic("implement me") +} diff --git a/msp/msp_test.go b/msp/msp_test.go index 9594d7e5010..58617f836ec 100644 --- a/msp/msp_test.go +++ b/msp/msp_test.go @@ -788,7 +788,6 @@ func TestMSPOus(t *testing.T) { // Set the OUIdentifiers backup := localMsp.(*bccspmsp).ouIdentifiers defer func() { localMsp.(*bccspmsp).ouIdentifiers = backup }() - id, err := localMsp.GetDefaultSigningIdentity() assert.NoError(t, err) diff --git a/vendor/github.com/golang/groupcache/LICENSE b/vendor/github.com/golang/groupcache/LICENSE new file mode 100644 index 00000000000..37ec93a14fd --- /dev/null +++ b/vendor/github.com/golang/groupcache/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/golang/groupcache/lru/lru.go b/vendor/github.com/golang/groupcache/lru/lru.go new file mode 100644 index 00000000000..532cc45e6dc --- /dev/null +++ b/vendor/github.com/golang/groupcache/lru/lru.go @@ -0,0 +1,133 @@ +/* +Copyright 2013 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package lru implements an LRU cache. +package lru + +import "container/list" + +// Cache is an LRU cache. It is not safe for concurrent access. +type Cache struct { + // MaxEntries is the maximum number of cache entries before + // an item is evicted. Zero means no limit. + MaxEntries int + + // OnEvicted optionally specificies a callback function to be + // executed when an entry is purged from the cache. + OnEvicted func(key Key, value interface{}) + + ll *list.List + cache map[interface{}]*list.Element +} + +// A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators +type Key interface{} + +type entry struct { + key Key + value interface{} +} + +// New creates a new Cache. +// If maxEntries is zero, the cache has no limit and it's assumed +// that eviction is done by the caller. +func New(maxEntries int) *Cache { + return &Cache{ + MaxEntries: maxEntries, + ll: list.New(), + cache: make(map[interface{}]*list.Element), + } +} + +// Add adds a value to the cache. +func (c *Cache) Add(key Key, value interface{}) { + if c.cache == nil { + c.cache = make(map[interface{}]*list.Element) + c.ll = list.New() + } + if ee, ok := c.cache[key]; ok { + c.ll.MoveToFront(ee) + ee.Value.(*entry).value = value + return + } + ele := c.ll.PushFront(&entry{key, value}) + c.cache[key] = ele + if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { + c.RemoveOldest() + } +} + +// Get looks up a key's value from the cache. +func (c *Cache) Get(key Key) (value interface{}, ok bool) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.ll.MoveToFront(ele) + return ele.Value.(*entry).value, true + } + return +} + +// Remove removes the provided key from the cache. +func (c *Cache) Remove(key Key) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.removeElement(ele) + } +} + +// RemoveOldest removes the oldest item from the cache. +func (c *Cache) RemoveOldest() { + if c.cache == nil { + return + } + ele := c.ll.Back() + if ele != nil { + c.removeElement(ele) + } +} + +func (c *Cache) removeElement(e *list.Element) { + c.ll.Remove(e) + kv := e.Value.(*entry) + delete(c.cache, kv.key) + if c.OnEvicted != nil { + c.OnEvicted(kv.key, kv.value) + } +} + +// Len returns the number of items in the cache. +func (c *Cache) Len() int { + if c.cache == nil { + return 0 + } + return c.ll.Len() +} + +// Clear purges all stored items from the cache. +func (c *Cache) Clear() { + if c.OnEvicted != nil { + for _, e := range c.cache { + kv := e.Value.(*entry) + c.OnEvicted(kv.key, kv.value) + } + } + c.ll = nil + c.cache = nil +} diff --git a/vendor/vendor.json b/vendor/vendor.json index a71fe6bc211..006cbd61458 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -216,6 +216,12 @@ "revision": "3fd2ffd35c9233bfe91caa84e9c09d7cf8fae964", "revisionTime": "2015-10-06T12:17:10-04:00" }, + { + "checksumSHA1": "nbCxiVT48CWEg6l8L4SEJ5VfN9c=", + "path": "github.com/golang/groupcache/lru", + "revision": "b710c8433bd175204919eb38776e944233235d03", + "revisionTime": "2017-04-21T00:56:42Z" + }, { "checksumSHA1": "R/3Hs4SWeP0F4pYXnt1VIFJ/S5c=", "path": "github.com/golang/protobuf/jsonpb",