apply.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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 etcdserver
  15. import (
  16. "bytes"
  17. "sort"
  18. "time"
  19. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. "github.com/coreos/etcd/lease"
  21. "github.com/coreos/etcd/mvcc"
  22. "github.com/coreos/etcd/mvcc/mvccpb"
  23. "github.com/coreos/etcd/pkg/types"
  24. "github.com/gogo/protobuf/proto"
  25. "golang.org/x/net/context"
  26. )
  27. const (
  28. warnApplyDuration = 100 * time.Millisecond
  29. )
  30. type applyResult struct {
  31. resp proto.Message
  32. err error
  33. // physc signals the physical effect of the request has completed in addition
  34. // to being logically reflected by the node. Currently only used for
  35. // Compaction requests.
  36. physc <-chan struct{}
  37. }
  38. // applierV3 is the interface for processing V3 raft messages
  39. type applierV3 interface {
  40. Apply(r *pb.InternalRaftRequest) *applyResult
  41. Put(txn mvcc.TxnWrite, p *pb.PutRequest) (*pb.PutResponse, error)
  42. Range(txn mvcc.TxnRead, r *pb.RangeRequest) (*pb.RangeResponse, error)
  43. DeleteRange(txn mvcc.TxnWrite, dr *pb.DeleteRangeRequest) (*pb.DeleteRangeResponse, error)
  44. Txn(rt *pb.TxnRequest) (*pb.TxnResponse, error)
  45. Compaction(compaction *pb.CompactionRequest) (*pb.CompactionResponse, <-chan struct{}, error)
  46. LeaseGrant(lc *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error)
  47. LeaseRevoke(lc *pb.LeaseRevokeRequest) (*pb.LeaseRevokeResponse, error)
  48. Alarm(*pb.AlarmRequest) (*pb.AlarmResponse, error)
  49. Authenticate(r *pb.InternalAuthenticateRequest) (*pb.AuthenticateResponse, error)
  50. AuthEnable() (*pb.AuthEnableResponse, error)
  51. AuthDisable() (*pb.AuthDisableResponse, error)
  52. UserAdd(ua *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  53. UserDelete(ua *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  54. UserChangePassword(ua *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  55. UserGrantRole(ua *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  56. UserGet(ua *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  57. UserRevokeRole(ua *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  58. RoleAdd(ua *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  59. RoleGrantPermission(ua *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  60. RoleGet(ua *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  61. RoleRevokePermission(ua *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  62. RoleDelete(ua *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  63. UserList(ua *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  64. RoleList(ua *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  65. }
  66. type applierV3backend struct {
  67. s *EtcdServer
  68. }
  69. func (s *EtcdServer) newApplierV3() applierV3 {
  70. return newAuthApplierV3(
  71. s.AuthStore(),
  72. newQuotaApplierV3(s, &applierV3backend{s}),
  73. )
  74. }
  75. func (a *applierV3backend) Apply(r *pb.InternalRaftRequest) *applyResult {
  76. ar := &applyResult{}
  77. defer func(start time.Time) {
  78. warnOfExpensiveRequest(start, &pb.InternalRaftStringer{Request: r}, ar.resp, ar.err)
  79. }(time.Now())
  80. // call into a.s.applyV3.F instead of a.F so upper appliers can check individual calls
  81. switch {
  82. case r.Range != nil:
  83. ar.resp, ar.err = a.s.applyV3.Range(nil, r.Range)
  84. case r.Put != nil:
  85. ar.resp, ar.err = a.s.applyV3.Put(nil, r.Put)
  86. case r.DeleteRange != nil:
  87. ar.resp, ar.err = a.s.applyV3.DeleteRange(nil, r.DeleteRange)
  88. case r.Txn != nil:
  89. ar.resp, ar.err = a.s.applyV3.Txn(r.Txn)
  90. case r.Compaction != nil:
  91. ar.resp, ar.physc, ar.err = a.s.applyV3.Compaction(r.Compaction)
  92. case r.LeaseGrant != nil:
  93. ar.resp, ar.err = a.s.applyV3.LeaseGrant(r.LeaseGrant)
  94. case r.LeaseRevoke != nil:
  95. ar.resp, ar.err = a.s.applyV3.LeaseRevoke(r.LeaseRevoke)
  96. case r.Alarm != nil:
  97. ar.resp, ar.err = a.s.applyV3.Alarm(r.Alarm)
  98. case r.Authenticate != nil:
  99. ar.resp, ar.err = a.s.applyV3.Authenticate(r.Authenticate)
  100. case r.AuthEnable != nil:
  101. ar.resp, ar.err = a.s.applyV3.AuthEnable()
  102. case r.AuthDisable != nil:
  103. ar.resp, ar.err = a.s.applyV3.AuthDisable()
  104. case r.AuthUserAdd != nil:
  105. ar.resp, ar.err = a.s.applyV3.UserAdd(r.AuthUserAdd)
  106. case r.AuthUserDelete != nil:
  107. ar.resp, ar.err = a.s.applyV3.UserDelete(r.AuthUserDelete)
  108. case r.AuthUserChangePassword != nil:
  109. ar.resp, ar.err = a.s.applyV3.UserChangePassword(r.AuthUserChangePassword)
  110. case r.AuthUserGrantRole != nil:
  111. ar.resp, ar.err = a.s.applyV3.UserGrantRole(r.AuthUserGrantRole)
  112. case r.AuthUserGet != nil:
  113. ar.resp, ar.err = a.s.applyV3.UserGet(r.AuthUserGet)
  114. case r.AuthUserRevokeRole != nil:
  115. ar.resp, ar.err = a.s.applyV3.UserRevokeRole(r.AuthUserRevokeRole)
  116. case r.AuthRoleAdd != nil:
  117. ar.resp, ar.err = a.s.applyV3.RoleAdd(r.AuthRoleAdd)
  118. case r.AuthRoleGrantPermission != nil:
  119. ar.resp, ar.err = a.s.applyV3.RoleGrantPermission(r.AuthRoleGrantPermission)
  120. case r.AuthRoleGet != nil:
  121. ar.resp, ar.err = a.s.applyV3.RoleGet(r.AuthRoleGet)
  122. case r.AuthRoleRevokePermission != nil:
  123. ar.resp, ar.err = a.s.applyV3.RoleRevokePermission(r.AuthRoleRevokePermission)
  124. case r.AuthRoleDelete != nil:
  125. ar.resp, ar.err = a.s.applyV3.RoleDelete(r.AuthRoleDelete)
  126. case r.AuthUserList != nil:
  127. ar.resp, ar.err = a.s.applyV3.UserList(r.AuthUserList)
  128. case r.AuthRoleList != nil:
  129. ar.resp, ar.err = a.s.applyV3.RoleList(r.AuthRoleList)
  130. default:
  131. panic("not implemented")
  132. }
  133. return ar
  134. }
  135. func (a *applierV3backend) Put(txn mvcc.TxnWrite, p *pb.PutRequest) (resp *pb.PutResponse, err error) {
  136. resp = &pb.PutResponse{}
  137. resp.Header = &pb.ResponseHeader{}
  138. val, leaseID := p.Value, lease.LeaseID(p.Lease)
  139. if txn == nil {
  140. if leaseID != lease.NoLease {
  141. if l := a.s.lessor.Lookup(leaseID); l == nil {
  142. return nil, lease.ErrLeaseNotFound
  143. }
  144. }
  145. txn = a.s.KV().Write()
  146. defer txn.End()
  147. }
  148. var rr *mvcc.RangeResult
  149. if p.IgnoreValue || p.IgnoreLease || p.PrevKv {
  150. rr, err = txn.Range(p.Key, nil, mvcc.RangeOptions{})
  151. if err != nil {
  152. return nil, err
  153. }
  154. }
  155. if p.IgnoreValue || p.IgnoreLease {
  156. if rr == nil || len(rr.KVs) == 0 {
  157. // ignore_{lease,value} flag expects previous key-value pair
  158. return nil, ErrKeyNotFound
  159. }
  160. }
  161. if p.IgnoreValue {
  162. val = rr.KVs[0].Value
  163. }
  164. if p.IgnoreLease {
  165. leaseID = lease.LeaseID(rr.KVs[0].Lease)
  166. }
  167. if p.PrevKv {
  168. if rr != nil && len(rr.KVs) != 0 {
  169. resp.PrevKv = &rr.KVs[0]
  170. }
  171. }
  172. resp.Header.Revision = txn.Put(p.Key, val, leaseID)
  173. return resp, nil
  174. }
  175. func (a *applierV3backend) DeleteRange(txn mvcc.TxnWrite, dr *pb.DeleteRangeRequest) (*pb.DeleteRangeResponse, error) {
  176. resp := &pb.DeleteRangeResponse{}
  177. resp.Header = &pb.ResponseHeader{}
  178. if txn == nil {
  179. txn = a.s.kv.Write()
  180. defer txn.End()
  181. }
  182. if isGteRange(dr.RangeEnd) {
  183. dr.RangeEnd = []byte{}
  184. }
  185. if dr.PrevKv {
  186. rr, err := txn.Range(dr.Key, dr.RangeEnd, mvcc.RangeOptions{})
  187. if err != nil {
  188. return nil, err
  189. }
  190. if rr != nil {
  191. for i := range rr.KVs {
  192. resp.PrevKvs = append(resp.PrevKvs, &rr.KVs[i])
  193. }
  194. }
  195. }
  196. resp.Deleted, resp.Header.Revision = txn.DeleteRange(dr.Key, dr.RangeEnd)
  197. return resp, nil
  198. }
  199. func (a *applierV3backend) Range(txn mvcc.TxnRead, r *pb.RangeRequest) (*pb.RangeResponse, error) {
  200. resp := &pb.RangeResponse{}
  201. resp.Header = &pb.ResponseHeader{}
  202. if txn == nil {
  203. txn = a.s.kv.Read()
  204. defer txn.End()
  205. }
  206. if isGteRange(r.RangeEnd) {
  207. r.RangeEnd = []byte{}
  208. }
  209. limit := r.Limit
  210. if r.SortOrder != pb.RangeRequest_NONE ||
  211. r.MinModRevision != 0 || r.MaxModRevision != 0 ||
  212. r.MinCreateRevision != 0 || r.MaxCreateRevision != 0 {
  213. // fetch everything; sort and truncate afterwards
  214. limit = 0
  215. }
  216. if limit > 0 {
  217. // fetch one extra for 'more' flag
  218. limit = limit + 1
  219. }
  220. ro := mvcc.RangeOptions{
  221. Limit: limit,
  222. Rev: r.Revision,
  223. Count: r.CountOnly,
  224. }
  225. rr, err := txn.Range(r.Key, r.RangeEnd, ro)
  226. if err != nil {
  227. return nil, err
  228. }
  229. if r.MaxModRevision != 0 {
  230. f := func(kv *mvccpb.KeyValue) bool { return kv.ModRevision > r.MaxModRevision }
  231. pruneKVs(rr, f)
  232. }
  233. if r.MinModRevision != 0 {
  234. f := func(kv *mvccpb.KeyValue) bool { return kv.ModRevision < r.MinModRevision }
  235. pruneKVs(rr, f)
  236. }
  237. if r.MaxCreateRevision != 0 {
  238. f := func(kv *mvccpb.KeyValue) bool { return kv.CreateRevision > r.MaxCreateRevision }
  239. pruneKVs(rr, f)
  240. }
  241. if r.MinCreateRevision != 0 {
  242. f := func(kv *mvccpb.KeyValue) bool { return kv.CreateRevision < r.MinCreateRevision }
  243. pruneKVs(rr, f)
  244. }
  245. sortOrder := r.SortOrder
  246. if r.SortTarget != pb.RangeRequest_KEY && sortOrder == pb.RangeRequest_NONE {
  247. // Since current mvcc.Range implementation returns results
  248. // sorted by keys in lexiographically ascending order,
  249. // sort ASCEND by default only when target is not 'KEY'
  250. sortOrder = pb.RangeRequest_ASCEND
  251. }
  252. if sortOrder != pb.RangeRequest_NONE {
  253. var sorter sort.Interface
  254. switch {
  255. case r.SortTarget == pb.RangeRequest_KEY:
  256. sorter = &kvSortByKey{&kvSort{rr.KVs}}
  257. case r.SortTarget == pb.RangeRequest_VERSION:
  258. sorter = &kvSortByVersion{&kvSort{rr.KVs}}
  259. case r.SortTarget == pb.RangeRequest_CREATE:
  260. sorter = &kvSortByCreate{&kvSort{rr.KVs}}
  261. case r.SortTarget == pb.RangeRequest_MOD:
  262. sorter = &kvSortByMod{&kvSort{rr.KVs}}
  263. case r.SortTarget == pb.RangeRequest_VALUE:
  264. sorter = &kvSortByValue{&kvSort{rr.KVs}}
  265. }
  266. switch {
  267. case sortOrder == pb.RangeRequest_ASCEND:
  268. sort.Sort(sorter)
  269. case sortOrder == pb.RangeRequest_DESCEND:
  270. sort.Sort(sort.Reverse(sorter))
  271. }
  272. }
  273. if r.Limit > 0 && len(rr.KVs) > int(r.Limit) {
  274. rr.KVs = rr.KVs[:r.Limit]
  275. resp.More = true
  276. }
  277. resp.Header.Revision = rr.Rev
  278. resp.Count = int64(rr.Count)
  279. for i := range rr.KVs {
  280. if r.KeysOnly {
  281. rr.KVs[i].Value = nil
  282. }
  283. resp.Kvs = append(resp.Kvs, &rr.KVs[i])
  284. }
  285. return resp, nil
  286. }
  287. func (a *applierV3backend) Txn(rt *pb.TxnRequest) (*pb.TxnResponse, error) {
  288. isWrite := !isTxnReadonly(rt)
  289. txn := mvcc.NewReadOnlyTxnWrite(a.s.KV().Read())
  290. reqs, ok := a.compareToOps(txn, rt)
  291. if isWrite {
  292. if err := a.checkRequestPut(txn, reqs); err != nil {
  293. txn.End()
  294. return nil, err
  295. }
  296. }
  297. if err := checkRequestRange(txn, reqs); err != nil {
  298. txn.End()
  299. return nil, err
  300. }
  301. resps := make([]*pb.ResponseOp, len(reqs))
  302. txnResp := &pb.TxnResponse{
  303. Responses: resps,
  304. Succeeded: ok,
  305. Header: &pb.ResponseHeader{},
  306. }
  307. // When executing mutable txn ops, etcd must hold the txn lock so
  308. // readers do not see any intermediate results. Since writes are
  309. // serialized on the raft loop, the revision in the read view will
  310. // be the revision of the write txn.
  311. if isWrite {
  312. txn.End()
  313. txn = a.s.KV().Write()
  314. }
  315. for i := range reqs {
  316. resps[i] = a.applyUnion(txn, reqs[i])
  317. }
  318. rev := txn.Rev()
  319. if len(txn.Changes()) != 0 {
  320. rev++
  321. }
  322. txn.End()
  323. txnResp.Header.Revision = rev
  324. return txnResp, nil
  325. }
  326. func (a *applierV3backend) compareToOps(rv mvcc.ReadView, rt *pb.TxnRequest) ([]*pb.RequestOp, bool) {
  327. for _, c := range rt.Compare {
  328. if !applyCompare(rv, c) {
  329. return rt.Failure, false
  330. }
  331. }
  332. return rt.Success, true
  333. }
  334. // applyCompare applies the compare request.
  335. // If the comparison succeeds, it returns true. Otherwise, returns false.
  336. func applyCompare(rv mvcc.ReadView, c *pb.Compare) bool {
  337. rr, err := rv.Range(c.Key, nil, mvcc.RangeOptions{})
  338. if err != nil {
  339. return false
  340. }
  341. var ckv mvccpb.KeyValue
  342. if len(rr.KVs) != 0 {
  343. ckv = rr.KVs[0]
  344. } else {
  345. // Use the zero value of ckv normally. However...
  346. if c.Target == pb.Compare_VALUE {
  347. // Always fail if we're comparing a value on a key that doesn't exist.
  348. // We can treat non-existence as the empty set explicitly, such that
  349. // even a key with a value of length 0 bytes is still a real key
  350. // that was written that way
  351. return false
  352. }
  353. }
  354. // -1 is less, 0 is equal, 1 is greater
  355. var result int
  356. switch c.Target {
  357. case pb.Compare_VALUE:
  358. tv, _ := c.TargetUnion.(*pb.Compare_Value)
  359. if tv != nil {
  360. result = bytes.Compare(ckv.Value, tv.Value)
  361. }
  362. case pb.Compare_CREATE:
  363. tv, _ := c.TargetUnion.(*pb.Compare_CreateRevision)
  364. if tv != nil {
  365. result = compareInt64(ckv.CreateRevision, tv.CreateRevision)
  366. }
  367. case pb.Compare_MOD:
  368. tv, _ := c.TargetUnion.(*pb.Compare_ModRevision)
  369. if tv != nil {
  370. result = compareInt64(ckv.ModRevision, tv.ModRevision)
  371. }
  372. case pb.Compare_VERSION:
  373. tv, _ := c.TargetUnion.(*pb.Compare_Version)
  374. if tv != nil {
  375. result = compareInt64(ckv.Version, tv.Version)
  376. }
  377. }
  378. switch c.Result {
  379. case pb.Compare_EQUAL:
  380. return result == 0
  381. case pb.Compare_NOT_EQUAL:
  382. return result != 0
  383. case pb.Compare_GREATER:
  384. return result > 0
  385. case pb.Compare_LESS:
  386. return result < 0
  387. }
  388. return true
  389. }
  390. func (a *applierV3backend) applyUnion(txn mvcc.TxnWrite, union *pb.RequestOp) *pb.ResponseOp {
  391. switch tv := union.Request.(type) {
  392. case *pb.RequestOp_RequestRange:
  393. if tv.RequestRange != nil {
  394. resp, err := a.Range(txn, tv.RequestRange)
  395. if err != nil {
  396. plog.Panicf("unexpected error during txn: %v", err)
  397. }
  398. return &pb.ResponseOp{Response: &pb.ResponseOp_ResponseRange{ResponseRange: resp}}
  399. }
  400. case *pb.RequestOp_RequestPut:
  401. if tv.RequestPut != nil {
  402. resp, err := a.Put(txn, tv.RequestPut)
  403. if err != nil {
  404. plog.Panicf("unexpected error during txn: %v", err)
  405. }
  406. return &pb.ResponseOp{Response: &pb.ResponseOp_ResponsePut{ResponsePut: resp}}
  407. }
  408. case *pb.RequestOp_RequestDeleteRange:
  409. if tv.RequestDeleteRange != nil {
  410. resp, err := a.DeleteRange(txn, tv.RequestDeleteRange)
  411. if err != nil {
  412. plog.Panicf("unexpected error during txn: %v", err)
  413. }
  414. return &pb.ResponseOp{Response: &pb.ResponseOp_ResponseDeleteRange{ResponseDeleteRange: resp}}
  415. }
  416. default:
  417. // empty union
  418. return nil
  419. }
  420. return nil
  421. }
  422. func (a *applierV3backend) Compaction(compaction *pb.CompactionRequest) (*pb.CompactionResponse, <-chan struct{}, error) {
  423. resp := &pb.CompactionResponse{}
  424. resp.Header = &pb.ResponseHeader{}
  425. ch, err := a.s.KV().Compact(compaction.Revision)
  426. if err != nil {
  427. return nil, ch, err
  428. }
  429. // get the current revision. which key to get is not important.
  430. rr, _ := a.s.KV().Range([]byte("compaction"), nil, mvcc.RangeOptions{})
  431. resp.Header.Revision = rr.Rev
  432. return resp, ch, err
  433. }
  434. func (a *applierV3backend) LeaseGrant(lc *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error) {
  435. l, err := a.s.lessor.Grant(lease.LeaseID(lc.ID), lc.TTL)
  436. resp := &pb.LeaseGrantResponse{}
  437. if err == nil {
  438. resp.ID = int64(l.ID)
  439. resp.TTL = l.TTL()
  440. resp.Header = newHeader(a.s)
  441. }
  442. return resp, err
  443. }
  444. func (a *applierV3backend) LeaseRevoke(lc *pb.LeaseRevokeRequest) (*pb.LeaseRevokeResponse, error) {
  445. err := a.s.lessor.Revoke(lease.LeaseID(lc.ID))
  446. return &pb.LeaseRevokeResponse{Header: newHeader(a.s)}, err
  447. }
  448. func (a *applierV3backend) Alarm(ar *pb.AlarmRequest) (*pb.AlarmResponse, error) {
  449. resp := &pb.AlarmResponse{}
  450. oldCount := len(a.s.alarmStore.Get(ar.Alarm))
  451. switch ar.Action {
  452. case pb.AlarmRequest_GET:
  453. resp.Alarms = a.s.alarmStore.Get(ar.Alarm)
  454. case pb.AlarmRequest_ACTIVATE:
  455. m := a.s.alarmStore.Activate(types.ID(ar.MemberID), ar.Alarm)
  456. if m == nil {
  457. break
  458. }
  459. resp.Alarms = append(resp.Alarms, m)
  460. activated := oldCount == 0 && len(a.s.alarmStore.Get(m.Alarm)) == 1
  461. if !activated {
  462. break
  463. }
  464. switch m.Alarm {
  465. case pb.AlarmType_NOSPACE:
  466. plog.Warningf("alarm raised %+v", m)
  467. a.s.applyV3 = newApplierV3Capped(a)
  468. default:
  469. plog.Errorf("unimplemented alarm activation (%+v)", m)
  470. }
  471. case pb.AlarmRequest_DEACTIVATE:
  472. m := a.s.alarmStore.Deactivate(types.ID(ar.MemberID), ar.Alarm)
  473. if m == nil {
  474. break
  475. }
  476. resp.Alarms = append(resp.Alarms, m)
  477. deactivated := oldCount > 0 && len(a.s.alarmStore.Get(ar.Alarm)) == 0
  478. if !deactivated {
  479. break
  480. }
  481. switch m.Alarm {
  482. case pb.AlarmType_NOSPACE:
  483. plog.Infof("alarm disarmed %+v", ar)
  484. a.s.applyV3 = a.s.newApplierV3()
  485. default:
  486. plog.Errorf("unimplemented alarm deactivation (%+v)", m)
  487. }
  488. default:
  489. return nil, nil
  490. }
  491. return resp, nil
  492. }
  493. type applierV3Capped struct {
  494. applierV3
  495. q backendQuota
  496. }
  497. // newApplierV3Capped creates an applyV3 that will reject Puts and transactions
  498. // with Puts so that the number of keys in the store is capped.
  499. func newApplierV3Capped(base applierV3) applierV3 { return &applierV3Capped{applierV3: base} }
  500. func (a *applierV3Capped) Put(txn mvcc.TxnWrite, p *pb.PutRequest) (*pb.PutResponse, error) {
  501. return nil, ErrNoSpace
  502. }
  503. func (a *applierV3Capped) Txn(r *pb.TxnRequest) (*pb.TxnResponse, error) {
  504. if a.q.Cost(r) > 0 {
  505. return nil, ErrNoSpace
  506. }
  507. return a.applierV3.Txn(r)
  508. }
  509. func (a *applierV3Capped) LeaseGrant(lc *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error) {
  510. return nil, ErrNoSpace
  511. }
  512. func (a *applierV3backend) AuthEnable() (*pb.AuthEnableResponse, error) {
  513. err := a.s.AuthStore().AuthEnable()
  514. if err != nil {
  515. return nil, err
  516. }
  517. return &pb.AuthEnableResponse{Header: newHeader(a.s)}, nil
  518. }
  519. func (a *applierV3backend) AuthDisable() (*pb.AuthDisableResponse, error) {
  520. a.s.AuthStore().AuthDisable()
  521. return &pb.AuthDisableResponse{Header: newHeader(a.s)}, nil
  522. }
  523. func (a *applierV3backend) Authenticate(r *pb.InternalAuthenticateRequest) (*pb.AuthenticateResponse, error) {
  524. ctx := context.WithValue(context.WithValue(a.s.ctx, "index", a.s.consistIndex.ConsistentIndex()), "simpleToken", r.SimpleToken)
  525. resp, err := a.s.AuthStore().Authenticate(ctx, r.Name, r.Password)
  526. if resp != nil {
  527. resp.Header = newHeader(a.s)
  528. }
  529. return resp, err
  530. }
  531. func (a *applierV3backend) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  532. resp, err := a.s.AuthStore().UserAdd(r)
  533. if resp != nil {
  534. resp.Header = newHeader(a.s)
  535. }
  536. return resp, err
  537. }
  538. func (a *applierV3backend) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  539. resp, err := a.s.AuthStore().UserDelete(r)
  540. if resp != nil {
  541. resp.Header = newHeader(a.s)
  542. }
  543. return resp, err
  544. }
  545. func (a *applierV3backend) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  546. resp, err := a.s.AuthStore().UserChangePassword(r)
  547. if resp != nil {
  548. resp.Header = newHeader(a.s)
  549. }
  550. return resp, err
  551. }
  552. func (a *applierV3backend) UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  553. resp, err := a.s.AuthStore().UserGrantRole(r)
  554. if resp != nil {
  555. resp.Header = newHeader(a.s)
  556. }
  557. return resp, err
  558. }
  559. func (a *applierV3backend) UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  560. resp, err := a.s.AuthStore().UserGet(r)
  561. if resp != nil {
  562. resp.Header = newHeader(a.s)
  563. }
  564. return resp, err
  565. }
  566. func (a *applierV3backend) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  567. resp, err := a.s.AuthStore().UserRevokeRole(r)
  568. if resp != nil {
  569. resp.Header = newHeader(a.s)
  570. }
  571. return resp, err
  572. }
  573. func (a *applierV3backend) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  574. resp, err := a.s.AuthStore().RoleAdd(r)
  575. if resp != nil {
  576. resp.Header = newHeader(a.s)
  577. }
  578. return resp, err
  579. }
  580. func (a *applierV3backend) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  581. resp, err := a.s.AuthStore().RoleGrantPermission(r)
  582. if resp != nil {
  583. resp.Header = newHeader(a.s)
  584. }
  585. return resp, err
  586. }
  587. func (a *applierV3backend) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  588. resp, err := a.s.AuthStore().RoleGet(r)
  589. if resp != nil {
  590. resp.Header = newHeader(a.s)
  591. }
  592. return resp, err
  593. }
  594. func (a *applierV3backend) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  595. resp, err := a.s.AuthStore().RoleRevokePermission(r)
  596. if resp != nil {
  597. resp.Header = newHeader(a.s)
  598. }
  599. return resp, err
  600. }
  601. func (a *applierV3backend) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  602. resp, err := a.s.AuthStore().RoleDelete(r)
  603. if resp != nil {
  604. resp.Header = newHeader(a.s)
  605. }
  606. return resp, err
  607. }
  608. func (a *applierV3backend) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  609. resp, err := a.s.AuthStore().UserList(r)
  610. if resp != nil {
  611. resp.Header = newHeader(a.s)
  612. }
  613. return resp, err
  614. }
  615. func (a *applierV3backend) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  616. resp, err := a.s.AuthStore().RoleList(r)
  617. if resp != nil {
  618. resp.Header = newHeader(a.s)
  619. }
  620. return resp, err
  621. }
  622. type quotaApplierV3 struct {
  623. applierV3
  624. q Quota
  625. }
  626. func newQuotaApplierV3(s *EtcdServer, app applierV3) applierV3 {
  627. return &quotaApplierV3{app, NewBackendQuota(s)}
  628. }
  629. func (a *quotaApplierV3) Put(txn mvcc.TxnWrite, p *pb.PutRequest) (*pb.PutResponse, error) {
  630. ok := a.q.Available(p)
  631. resp, err := a.applierV3.Put(txn, p)
  632. if err == nil && !ok {
  633. err = ErrNoSpace
  634. }
  635. return resp, err
  636. }
  637. func (a *quotaApplierV3) Txn(rt *pb.TxnRequest) (*pb.TxnResponse, error) {
  638. ok := a.q.Available(rt)
  639. resp, err := a.applierV3.Txn(rt)
  640. if err == nil && !ok {
  641. err = ErrNoSpace
  642. }
  643. return resp, err
  644. }
  645. func (a *quotaApplierV3) LeaseGrant(lc *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error) {
  646. ok := a.q.Available(lc)
  647. resp, err := a.applierV3.LeaseGrant(lc)
  648. if err == nil && !ok {
  649. err = ErrNoSpace
  650. }
  651. return resp, err
  652. }
  653. type kvSort struct{ kvs []mvccpb.KeyValue }
  654. func (s *kvSort) Swap(i, j int) {
  655. t := s.kvs[i]
  656. s.kvs[i] = s.kvs[j]
  657. s.kvs[j] = t
  658. }
  659. func (s *kvSort) Len() int { return len(s.kvs) }
  660. type kvSortByKey struct{ *kvSort }
  661. func (s *kvSortByKey) Less(i, j int) bool {
  662. return bytes.Compare(s.kvs[i].Key, s.kvs[j].Key) < 0
  663. }
  664. type kvSortByVersion struct{ *kvSort }
  665. func (s *kvSortByVersion) Less(i, j int) bool {
  666. return (s.kvs[i].Version - s.kvs[j].Version) < 0
  667. }
  668. type kvSortByCreate struct{ *kvSort }
  669. func (s *kvSortByCreate) Less(i, j int) bool {
  670. return (s.kvs[i].CreateRevision - s.kvs[j].CreateRevision) < 0
  671. }
  672. type kvSortByMod struct{ *kvSort }
  673. func (s *kvSortByMod) Less(i, j int) bool {
  674. return (s.kvs[i].ModRevision - s.kvs[j].ModRevision) < 0
  675. }
  676. type kvSortByValue struct{ *kvSort }
  677. func (s *kvSortByValue) Less(i, j int) bool {
  678. return bytes.Compare(s.kvs[i].Value, s.kvs[j].Value) < 0
  679. }
  680. func (a *applierV3backend) checkRequestPut(rv mvcc.ReadView, reqs []*pb.RequestOp) error {
  681. for _, requ := range reqs {
  682. tv, ok := requ.Request.(*pb.RequestOp_RequestPut)
  683. if !ok {
  684. continue
  685. }
  686. preq := tv.RequestPut
  687. if preq == nil {
  688. continue
  689. }
  690. if preq.IgnoreValue || preq.IgnoreLease {
  691. // expects previous key-value, error if not exist
  692. rr, err := rv.Range(preq.Key, nil, mvcc.RangeOptions{})
  693. if err != nil {
  694. return err
  695. }
  696. if rr == nil || len(rr.KVs) == 0 {
  697. return ErrKeyNotFound
  698. }
  699. }
  700. if lease.LeaseID(preq.Lease) == lease.NoLease {
  701. continue
  702. }
  703. if l := a.s.lessor.Lookup(lease.LeaseID(preq.Lease)); l == nil {
  704. return lease.ErrLeaseNotFound
  705. }
  706. }
  707. return nil
  708. }
  709. func checkRequestRange(rv mvcc.ReadView, reqs []*pb.RequestOp) error {
  710. for _, requ := range reqs {
  711. tv, ok := requ.Request.(*pb.RequestOp_RequestRange)
  712. if !ok {
  713. continue
  714. }
  715. greq := tv.RequestRange
  716. if greq == nil || greq.Revision == 0 {
  717. continue
  718. }
  719. if greq.Revision > rv.Rev() {
  720. return mvcc.ErrFutureRev
  721. }
  722. if greq.Revision < rv.FirstRev() {
  723. return mvcc.ErrCompacted
  724. }
  725. }
  726. return nil
  727. }
  728. func compareInt64(a, b int64) int {
  729. switch {
  730. case a < b:
  731. return -1
  732. case a > b:
  733. return 1
  734. default:
  735. return 0
  736. }
  737. }
  738. // isGteRange determines if the range end is a >= range. This works around grpc
  739. // sending empty byte strings as nil; >= is encoded in the range end as '\0'.
  740. func isGteRange(rangeEnd []byte) bool {
  741. return len(rangeEnd) == 1 && rangeEnd[0] == 0
  742. }
  743. func noSideEffect(r *pb.InternalRaftRequest) bool {
  744. return r.Range != nil || r.AuthUserGet != nil || r.AuthRoleGet != nil
  745. }
  746. func removeNeedlessRangeReqs(txn *pb.TxnRequest) {
  747. f := func(ops []*pb.RequestOp) []*pb.RequestOp {
  748. j := 0
  749. for i := 0; i < len(ops); i++ {
  750. if _, ok := ops[i].Request.(*pb.RequestOp_RequestRange); ok {
  751. continue
  752. }
  753. ops[j] = ops[i]
  754. j++
  755. }
  756. return ops[:j]
  757. }
  758. txn.Success = f(txn.Success)
  759. txn.Failure = f(txn.Failure)
  760. }
  761. func pruneKVs(rr *mvcc.RangeResult, isPrunable func(*mvccpb.KeyValue) bool) {
  762. j := 0
  763. for i := range rr.KVs {
  764. rr.KVs[j] = rr.KVs[i]
  765. if !isPrunable(&rr.KVs[i]) {
  766. j++
  767. }
  768. }
  769. rr.KVs = rr.KVs[:j]
  770. }
  771. func newHeader(s *EtcdServer) *pb.ResponseHeader {
  772. return &pb.ResponseHeader{
  773. ClusterId: uint64(s.Cluster().ID()),
  774. MemberId: uint64(s.ID()),
  775. Revision: s.KV().Rev(),
  776. RaftTerm: s.Term(),
  777. }
  778. }