github.com/zorawar87/trillian@v1.2.1/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) GetTokens(ctx context.Context, numTokens int, specs []quota.Spec) error {
    37  	return m.qs.Get(ctx, configNames(specs), int64(numTokens))
    38  }
    39  
    40  func (m *manager) PeekTokens(ctx context.Context, specs []quota.Spec) (map[quota.Spec]int, error) {
    41  	names := configNames(specs)
    42  	nameToSpec := make(map[string]quota.Spec)
    43  	for i, name := range names {
    44  		nameToSpec[name] = specs[i]
    45  	}
    46  
    47  	nameToTokens, err := m.qs.Peek(ctx, names)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	tokens := make(map[quota.Spec]int)
    53  	for k, v := range nameToTokens {
    54  		tokens[nameToSpec[k]] = int(v)
    55  	}
    56  	return tokens, nil
    57  }
    58  
    59  func (m *manager) PutTokens(ctx context.Context, numTokens int, specs []quota.Spec) error {
    60  	return m.qs.Put(ctx, configNames(specs), int64(numTokens))
    61  }
    62  
    63  func (m *manager) ResetQuota(ctx context.Context, specs []quota.Spec) error {
    64  	return m.qs.Reset(ctx, configNames(specs))
    65  }
    66  
    67  func configNames(specs []quota.Spec) []string {
    68  	names := make([]string, 0, len(specs))
    69  	for _, spec := range specs {
    70  		names = append(names, configName(spec))
    71  	}
    72  	return names
    73  }
    74  
    75  func configName(spec quota.Spec) string {
    76  	return fmt.Sprintf("quotas/%v/config", spec.Name())
    77  }