quota.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2016 The etcd Authors
  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. package v3rpc
  15. import (
  16. "context"
  17. "go.etcd.io/etcd/etcdserver"
  18. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  19. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  20. "go.etcd.io/etcd/pkg/types"
  21. )
  22. type quotaKVServer struct {
  23. pb.KVServer
  24. qa quotaAlarmer
  25. }
  26. type quotaAlarmer struct {
  27. q etcdserver.Quota
  28. a Alarmer
  29. id types.ID
  30. }
  31. // check whether request satisfies the quota. If there is not enough space,
  32. // ignore request and raise the free space alarm.
  33. func (qa *quotaAlarmer) check(ctx context.Context, r interface{}) error {
  34. if qa.q.Available(r) {
  35. return nil
  36. }
  37. req := &pb.AlarmRequest{
  38. MemberID: uint64(qa.id),
  39. Action: pb.AlarmRequest_ACTIVATE,
  40. Alarm: pb.AlarmType_NOSPACE,
  41. }
  42. qa.a.Alarm(ctx, req)
  43. return rpctypes.ErrGRPCNoSpace
  44. }
  45. func NewQuotaKVServer(s *etcdserver.EtcdServer) pb.KVServer {
  46. return &quotaKVServer{
  47. NewKVServer(s),
  48. quotaAlarmer{etcdserver.NewBackendQuota(s, "kv"), s, s.ID()},
  49. }
  50. }
  51. func (s *quotaKVServer) Put(ctx context.Context, r *pb.PutRequest) (*pb.PutResponse, error) {
  52. if err := s.qa.check(ctx, r); err != nil {
  53. return nil, err
  54. }
  55. return s.KVServer.Put(ctx, r)
  56. }
  57. func (s *quotaKVServer) Txn(ctx context.Context, r *pb.TxnRequest) (*pb.TxnResponse, error) {
  58. if err := s.qa.check(ctx, r); err != nil {
  59. return nil, err
  60. }
  61. return s.KVServer.Txn(ctx, r)
  62. }
  63. type quotaLeaseServer struct {
  64. pb.LeaseServer
  65. qa quotaAlarmer
  66. }
  67. func (s *quotaLeaseServer) LeaseGrant(ctx context.Context, cr *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error) {
  68. if err := s.qa.check(ctx, cr); err != nil {
  69. return nil, err
  70. }
  71. return s.LeaseServer.LeaseGrant(ctx, cr)
  72. }
  73. func NewQuotaLeaseServer(s *etcdserver.EtcdServer) pb.LeaseServer {
  74. return &quotaLeaseServer{
  75. NewLeaseServer(s),
  76. quotaAlarmer{etcdserver.NewBackendQuota(s, "lease"), s, s.ID()},
  77. }
  78. }