github.com/letsencrypt/trillian@v1.1.2-0.20180615153820-ae375a99d36a/quota/etcd/etcdqm/etcdqm.go (about) 1 // Copyright 2017 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package etcdqm contains an etcd-based quota.Manager implementation. 16 package etcdqm 17 18 import ( 19 "context" 20 "fmt" 21 22 "github.com/coreos/etcd/clientv3" 23 "github.com/google/trillian/quota" 24 "github.com/google/trillian/quota/etcd/storage" 25 ) 26 27 type manager struct { 28 qs *storage.QuotaStorage 29 } 30 31 // New returns a new etcd-based quota.Manager. 32 func New(client *clientv3.Client) quota.Manager { 33 return &manager{qs: &storage.QuotaStorage{Client: client}} 34 } 35 36 func (m *manager) GetUser(ctx context.Context, req interface{}) string { 37 return "default" // Unused 38 } 39 40 func (m *manager) GetTokens(ctx context.Context, numTokens int, specs []quota.Spec) error { 41 return m.qs.Get(ctx, configNames(specs), int64(numTokens)) 42 } 43 44 func (m *manager) PeekTokens(ctx context.Context, specs []quota.Spec) (map[quota.Spec]int, error) { 45 names := configNames(specs) 46 nameToSpec := make(map[string]quota.Spec) 47 for i, name := range names { 48 nameToSpec[name] = specs[i] 49 } 50 51 nameToTokens, err := m.qs.Peek(ctx, names) 52 if err != nil { 53 return nil, err 54 } 55 56 tokens := make(map[quota.Spec]int) 57 for k, v := range nameToTokens { 58 tokens[nameToSpec[k]] = int(v) 59 } 60 return tokens, nil 61 } 62 63 func (m *manager) PutTokens(ctx context.Context, numTokens int, specs []quota.Spec) error { 64 return m.qs.Put(ctx, configNames(specs), int64(numTokens)) 65 } 66 67 func (m *manager) ResetQuota(ctx context.Context, specs []quota.Spec) error { 68 return m.qs.Reset(ctx, configNames(specs)) 69 } 70 71 func configNames(specs []quota.Spec) []string { 72 names := make([]string, 0, len(specs)) 73 for _, spec := range specs { 74 names = append(names, configName(spec)) 75 } 76 return names 77 } 78 79 func configName(spec quota.Spec) string { 80 return fmt.Sprintf("quotas/%v/config", spec.Name()) 81 }