apply.go 27 KB

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