v3_server.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. // Copyright 2015 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. "encoding/binary"
  18. "time"
  19. "github.com/coreos/etcd/auth"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. "github.com/coreos/etcd/etcdserver/membership"
  22. "github.com/coreos/etcd/lease"
  23. "github.com/coreos/etcd/lease/leasehttp"
  24. "github.com/coreos/etcd/mvcc"
  25. "github.com/coreos/etcd/raft"
  26. "github.com/coreos/go-semver/semver"
  27. "golang.org/x/net/context"
  28. )
  29. const (
  30. // the max request size that raft accepts.
  31. // TODO: make this a flag? But we probably do not want to
  32. // accept large request which might block raft stream. User
  33. // specify a large value might end up with shooting in the foot.
  34. maxRequestBytes = 1.5 * 1024 * 1024
  35. // In the health case, there might be a small gap (10s of entries) between
  36. // the applied index and committed index.
  37. // However, if the committed entries are very heavy to apply, the gap might grow.
  38. // We should stop accepting new proposals if the gap growing to a certain point.
  39. maxGapBetweenApplyAndCommitIndex = 5000
  40. )
  41. var (
  42. newRangeClusterVersion = *semver.Must(semver.NewVersion("3.1.0"))
  43. )
  44. type RaftKV interface {
  45. Range(ctx context.Context, r *pb.RangeRequest) (*pb.RangeResponse, error)
  46. Put(ctx context.Context, r *pb.PutRequest) (*pb.PutResponse, error)
  47. DeleteRange(ctx context.Context, r *pb.DeleteRangeRequest) (*pb.DeleteRangeResponse, error)
  48. Txn(ctx context.Context, r *pb.TxnRequest) (*pb.TxnResponse, error)
  49. Compact(ctx context.Context, r *pb.CompactionRequest) (*pb.CompactionResponse, error)
  50. }
  51. type Lessor interface {
  52. // LeaseGrant sends LeaseGrant request to raft and apply it after committed.
  53. LeaseGrant(ctx context.Context, r *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error)
  54. // LeaseRevoke sends LeaseRevoke request to raft and apply it after committed.
  55. LeaseRevoke(ctx context.Context, r *pb.LeaseRevokeRequest) (*pb.LeaseRevokeResponse, error)
  56. // LeaseRenew renews the lease with given ID. The renewed TTL is returned. Or an error
  57. // is returned.
  58. LeaseRenew(ctx context.Context, id lease.LeaseID) (int64, error)
  59. // LeaseTimeToLive retrieves lease information.
  60. LeaseTimeToLive(ctx context.Context, r *pb.LeaseTimeToLiveRequest) (*pb.LeaseTimeToLiveResponse, error)
  61. }
  62. type Authenticator interface {
  63. AuthEnable(ctx context.Context, r *pb.AuthEnableRequest) (*pb.AuthEnableResponse, error)
  64. AuthDisable(ctx context.Context, r *pb.AuthDisableRequest) (*pb.AuthDisableResponse, error)
  65. Authenticate(ctx context.Context, r *pb.AuthenticateRequest) (*pb.AuthenticateResponse, error)
  66. UserAdd(ctx context.Context, r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  67. UserDelete(ctx context.Context, r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  68. UserChangePassword(ctx context.Context, r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  69. UserGrantRole(ctx context.Context, r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  70. UserGet(ctx context.Context, r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  71. UserRevokeRole(ctx context.Context, r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  72. RoleAdd(ctx context.Context, r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  73. RoleGrantPermission(ctx context.Context, r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  74. RoleGet(ctx context.Context, r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  75. RoleRevokePermission(ctx context.Context, r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  76. RoleDelete(ctx context.Context, r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  77. UserList(ctx context.Context, r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  78. RoleList(ctx context.Context, r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  79. }
  80. func (s *EtcdServer) Range(ctx context.Context, r *pb.RangeRequest) (*pb.RangeResponse, error) {
  81. // TODO: remove this checking when we release etcd 3.2
  82. if s.ClusterVersion() == nil || s.ClusterVersion().LessThan(newRangeClusterVersion) {
  83. return s.legacyRange(ctx, r)
  84. }
  85. var resp *pb.RangeResponse
  86. var err error
  87. defer func(start time.Time) {
  88. warnOfExpensiveReadOnlyRangeRequest(start, r, resp, err)
  89. }(time.Now())
  90. if !r.Serializable {
  91. err = s.linearizableReadNotify(ctx)
  92. if err != nil {
  93. return nil, err
  94. }
  95. }
  96. chk := func(ai *auth.AuthInfo) error {
  97. return s.authStore.IsRangePermitted(ai, r.Key, r.RangeEnd)
  98. }
  99. get := func() { resp, err = s.applyV3Base.Range(noTxn, r) }
  100. if serr := s.doSerialize(ctx, chk, get); serr != nil {
  101. err = serr
  102. return nil, err
  103. }
  104. return resp, err
  105. }
  106. // TODO: remove this func when we release etcd 3.2
  107. func (s *EtcdServer) legacyRange(ctx context.Context, r *pb.RangeRequest) (*pb.RangeResponse, error) {
  108. if r.Serializable {
  109. var resp *pb.RangeResponse
  110. var err error
  111. chk := func(ai *auth.AuthInfo) error {
  112. return s.authStore.IsRangePermitted(ai, r.Key, r.RangeEnd)
  113. }
  114. get := func() { resp, err = s.applyV3Base.Range(noTxn, r) }
  115. if serr := s.doSerialize(ctx, chk, get); serr != nil {
  116. return nil, serr
  117. }
  118. return resp, err
  119. }
  120. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{Range: r})
  121. if err != nil {
  122. return nil, err
  123. }
  124. if result.err != nil {
  125. return nil, result.err
  126. }
  127. return result.resp.(*pb.RangeResponse), nil
  128. }
  129. func (s *EtcdServer) Put(ctx context.Context, r *pb.PutRequest) (*pb.PutResponse, error) {
  130. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{Put: r})
  131. if err != nil {
  132. return nil, err
  133. }
  134. if result.err != nil {
  135. return nil, result.err
  136. }
  137. return result.resp.(*pb.PutResponse), nil
  138. }
  139. func (s *EtcdServer) DeleteRange(ctx context.Context, r *pb.DeleteRangeRequest) (*pb.DeleteRangeResponse, error) {
  140. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{DeleteRange: r})
  141. if err != nil {
  142. return nil, err
  143. }
  144. if result.err != nil {
  145. return nil, result.err
  146. }
  147. return result.resp.(*pb.DeleteRangeResponse), nil
  148. }
  149. func (s *EtcdServer) Txn(ctx context.Context, r *pb.TxnRequest) (*pb.TxnResponse, error) {
  150. // TODO: remove this checking when we release etcd 3.2
  151. if s.ClusterVersion() == nil || s.ClusterVersion().LessThan(newRangeClusterVersion) {
  152. return s.legacyTxn(ctx, r)
  153. }
  154. if isTxnReadonly(r) {
  155. if !isTxnSerializable(r) {
  156. err := s.linearizableReadNotify(ctx)
  157. if err != nil {
  158. return nil, err
  159. }
  160. }
  161. var resp *pb.TxnResponse
  162. var err error
  163. chk := func(ai *auth.AuthInfo) error {
  164. return checkTxnAuth(s.authStore, ai, r)
  165. }
  166. defer func(start time.Time) {
  167. warnOfExpensiveReadOnlyTxnRequest(start, r, resp, err)
  168. }(time.Now())
  169. get := func() { resp, err = s.applyV3Base.Txn(r) }
  170. if serr := s.doSerialize(ctx, chk, get); serr != nil {
  171. return nil, serr
  172. }
  173. return resp, err
  174. }
  175. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{Txn: r})
  176. if err != nil {
  177. return nil, err
  178. }
  179. if result.err != nil {
  180. return nil, result.err
  181. }
  182. return result.resp.(*pb.TxnResponse), nil
  183. }
  184. // TODO: remove this func when we release etcd 3.2
  185. func (s *EtcdServer) legacyTxn(ctx context.Context, r *pb.TxnRequest) (*pb.TxnResponse, error) {
  186. if isTxnSerializable(r) {
  187. var resp *pb.TxnResponse
  188. var err error
  189. chk := func(ai *auth.AuthInfo) error {
  190. return checkTxnAuth(s.authStore, ai, r)
  191. }
  192. get := func() { resp, err = s.applyV3Base.Txn(r) }
  193. if serr := s.doSerialize(ctx, chk, get); serr != nil {
  194. return nil, serr
  195. }
  196. return resp, err
  197. }
  198. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{Txn: r})
  199. if err != nil {
  200. return nil, err
  201. }
  202. if result.err != nil {
  203. return nil, result.err
  204. }
  205. return result.resp.(*pb.TxnResponse), nil
  206. }
  207. func isTxnSerializable(r *pb.TxnRequest) bool {
  208. for _, u := range r.Success {
  209. if r := u.GetRequestRange(); r == nil || !r.Serializable {
  210. return false
  211. }
  212. }
  213. for _, u := range r.Failure {
  214. if r := u.GetRequestRange(); r == nil || !r.Serializable {
  215. return false
  216. }
  217. }
  218. return true
  219. }
  220. func isTxnReadonly(r *pb.TxnRequest) bool {
  221. for _, u := range r.Success {
  222. if r := u.GetRequestRange(); r == nil {
  223. return false
  224. }
  225. }
  226. for _, u := range r.Failure {
  227. if r := u.GetRequestRange(); r == nil {
  228. return false
  229. }
  230. }
  231. return true
  232. }
  233. func (s *EtcdServer) Compact(ctx context.Context, r *pb.CompactionRequest) (*pb.CompactionResponse, error) {
  234. result, err := s.processInternalRaftRequestOnce(ctx, pb.InternalRaftRequest{Compaction: r})
  235. if r.Physical && result != nil && result.physc != nil {
  236. <-result.physc
  237. // The compaction is done deleting keys; the hash is now settled
  238. // but the data is not necessarily committed. If there's a crash,
  239. // the hash may revert to a hash prior to compaction completing
  240. // if the compaction resumes. Force the finished compaction to
  241. // commit so it won't resume following a crash.
  242. s.be.ForceCommit()
  243. }
  244. if err != nil {
  245. return nil, err
  246. }
  247. if result.err != nil {
  248. return nil, result.err
  249. }
  250. resp := result.resp.(*pb.CompactionResponse)
  251. if resp == nil {
  252. resp = &pb.CompactionResponse{}
  253. }
  254. if resp.Header == nil {
  255. resp.Header = &pb.ResponseHeader{}
  256. }
  257. resp.Header.Revision = s.kv.Rev()
  258. return resp, nil
  259. }
  260. func (s *EtcdServer) LeaseGrant(ctx context.Context, r *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error) {
  261. // no id given? choose one
  262. for r.ID == int64(lease.NoLease) {
  263. // only use positive int64 id's
  264. r.ID = int64(s.reqIDGen.Next() & ((1 << 63) - 1))
  265. }
  266. result, err := s.processInternalRaftRequestOnce(ctx, pb.InternalRaftRequest{LeaseGrant: r})
  267. if err != nil {
  268. return nil, err
  269. }
  270. if result.err != nil {
  271. return nil, result.err
  272. }
  273. return result.resp.(*pb.LeaseGrantResponse), nil
  274. }
  275. func (s *EtcdServer) LeaseRevoke(ctx context.Context, r *pb.LeaseRevokeRequest) (*pb.LeaseRevokeResponse, error) {
  276. result, err := s.processInternalRaftRequestOnce(ctx, pb.InternalRaftRequest{LeaseRevoke: r})
  277. if err != nil {
  278. return nil, err
  279. }
  280. if result.err != nil {
  281. return nil, result.err
  282. }
  283. return result.resp.(*pb.LeaseRevokeResponse), nil
  284. }
  285. func (s *EtcdServer) LeaseRenew(ctx context.Context, id lease.LeaseID) (int64, error) {
  286. ttl, err := s.lessor.Renew(id)
  287. if err == nil { // already requested to primary lessor(leader)
  288. return ttl, nil
  289. }
  290. if err != lease.ErrNotPrimary {
  291. return -1, err
  292. }
  293. cctx, cancel := context.WithTimeout(ctx, s.Cfg.ReqTimeout())
  294. defer cancel()
  295. // renewals don't go through raft; forward to leader manually
  296. for cctx.Err() == nil && err != nil {
  297. leader, lerr := s.waitLeader(cctx)
  298. if lerr != nil {
  299. return -1, lerr
  300. }
  301. for _, url := range leader.PeerURLs {
  302. lurl := url + leasehttp.LeasePrefix
  303. ttl, err = leasehttp.RenewHTTP(cctx, id, lurl, s.peerRt)
  304. if err == nil || err == lease.ErrLeaseNotFound {
  305. return ttl, err
  306. }
  307. }
  308. }
  309. return -1, ErrTimeout
  310. }
  311. func (s *EtcdServer) LeaseTimeToLive(ctx context.Context, r *pb.LeaseTimeToLiveRequest) (*pb.LeaseTimeToLiveResponse, error) {
  312. if s.Leader() == s.ID() {
  313. // primary; timetolive directly from leader
  314. le := s.lessor.Lookup(lease.LeaseID(r.ID))
  315. if le == nil {
  316. return nil, lease.ErrLeaseNotFound
  317. }
  318. // TODO: fill out ResponseHeader
  319. resp := &pb.LeaseTimeToLiveResponse{Header: &pb.ResponseHeader{}, ID: r.ID, TTL: int64(le.Remaining().Seconds()), GrantedTTL: le.TTL()}
  320. if r.Keys {
  321. ks := le.Keys()
  322. kbs := make([][]byte, len(ks))
  323. for i := range ks {
  324. kbs[i] = []byte(ks[i])
  325. }
  326. resp.Keys = kbs
  327. }
  328. return resp, nil
  329. }
  330. cctx, cancel := context.WithTimeout(ctx, s.Cfg.ReqTimeout())
  331. defer cancel()
  332. // forward to leader
  333. for cctx.Err() == nil {
  334. leader, err := s.waitLeader(cctx)
  335. if err != nil {
  336. return nil, err
  337. }
  338. for _, url := range leader.PeerURLs {
  339. lurl := url + leasehttp.LeaseInternalPrefix
  340. resp, err := leasehttp.TimeToLiveHTTP(cctx, lease.LeaseID(r.ID), r.Keys, lurl, s.peerRt)
  341. if err == nil {
  342. return resp.LeaseTimeToLiveResponse, nil
  343. }
  344. if err == lease.ErrLeaseNotFound {
  345. return nil, err
  346. }
  347. }
  348. }
  349. return nil, ErrTimeout
  350. }
  351. func (s *EtcdServer) waitLeader(ctx context.Context) (*membership.Member, error) {
  352. leader := s.cluster.Member(s.Leader())
  353. for leader == nil {
  354. // wait an election
  355. dur := time.Duration(s.Cfg.ElectionTicks) * time.Duration(s.Cfg.TickMs) * time.Millisecond
  356. select {
  357. case <-time.After(dur):
  358. leader = s.cluster.Member(s.Leader())
  359. case <-s.stopping:
  360. return nil, ErrStopped
  361. case <-ctx.Done():
  362. return nil, ErrNoLeader
  363. }
  364. }
  365. if leader == nil || len(leader.PeerURLs) == 0 {
  366. return nil, ErrNoLeader
  367. }
  368. return leader, nil
  369. }
  370. func (s *EtcdServer) Alarm(ctx context.Context, r *pb.AlarmRequest) (*pb.AlarmResponse, error) {
  371. result, err := s.processInternalRaftRequestOnce(ctx, pb.InternalRaftRequest{Alarm: r})
  372. if err != nil {
  373. return nil, err
  374. }
  375. if result.err != nil {
  376. return nil, result.err
  377. }
  378. return result.resp.(*pb.AlarmResponse), nil
  379. }
  380. func (s *EtcdServer) AuthEnable(ctx context.Context, r *pb.AuthEnableRequest) (*pb.AuthEnableResponse, error) {
  381. result, err := s.processInternalRaftRequestOnce(ctx, pb.InternalRaftRequest{AuthEnable: r})
  382. if err != nil {
  383. return nil, err
  384. }
  385. if result.err != nil {
  386. return nil, result.err
  387. }
  388. return result.resp.(*pb.AuthEnableResponse), nil
  389. }
  390. func (s *EtcdServer) AuthDisable(ctx context.Context, r *pb.AuthDisableRequest) (*pb.AuthDisableResponse, error) {
  391. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthDisable: r})
  392. if err != nil {
  393. return nil, err
  394. }
  395. if result.err != nil {
  396. return nil, result.err
  397. }
  398. return result.resp.(*pb.AuthDisableResponse), nil
  399. }
  400. func (s *EtcdServer) Authenticate(ctx context.Context, r *pb.AuthenticateRequest) (*pb.AuthenticateResponse, error) {
  401. var result *applyResult
  402. err := s.linearizableReadNotify(ctx)
  403. if err != nil {
  404. return nil, err
  405. }
  406. for {
  407. checkedRevision, err := s.AuthStore().CheckPassword(r.Name, r.Password)
  408. if err != nil {
  409. plog.Errorf("invalid authentication request to user %s was issued", r.Name)
  410. return nil, err
  411. }
  412. st, err := s.AuthStore().GenSimpleToken()
  413. if err != nil {
  414. return nil, err
  415. }
  416. internalReq := &pb.InternalAuthenticateRequest{
  417. Name: r.Name,
  418. Password: r.Password,
  419. SimpleToken: st,
  420. }
  421. result, err = s.processInternalRaftRequestOnce(ctx, pb.InternalRaftRequest{Authenticate: internalReq})
  422. if err != nil {
  423. return nil, err
  424. }
  425. if result.err != nil {
  426. return nil, result.err
  427. }
  428. if checkedRevision != s.AuthStore().Revision() {
  429. plog.Infof("revision when password checked is obsolete, retrying")
  430. continue
  431. }
  432. break
  433. }
  434. return result.resp.(*pb.AuthenticateResponse), nil
  435. }
  436. func (s *EtcdServer) UserAdd(ctx context.Context, r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  437. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthUserAdd: r})
  438. if err != nil {
  439. return nil, err
  440. }
  441. if result.err != nil {
  442. return nil, result.err
  443. }
  444. return result.resp.(*pb.AuthUserAddResponse), nil
  445. }
  446. func (s *EtcdServer) UserDelete(ctx context.Context, r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  447. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthUserDelete: r})
  448. if err != nil {
  449. return nil, err
  450. }
  451. if result.err != nil {
  452. return nil, result.err
  453. }
  454. return result.resp.(*pb.AuthUserDeleteResponse), nil
  455. }
  456. func (s *EtcdServer) UserChangePassword(ctx context.Context, r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  457. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthUserChangePassword: r})
  458. if err != nil {
  459. return nil, err
  460. }
  461. if result.err != nil {
  462. return nil, result.err
  463. }
  464. return result.resp.(*pb.AuthUserChangePasswordResponse), nil
  465. }
  466. func (s *EtcdServer) UserGrantRole(ctx context.Context, r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  467. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthUserGrantRole: r})
  468. if err != nil {
  469. return nil, err
  470. }
  471. if result.err != nil {
  472. return nil, result.err
  473. }
  474. return result.resp.(*pb.AuthUserGrantRoleResponse), nil
  475. }
  476. func (s *EtcdServer) UserGet(ctx context.Context, r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  477. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthUserGet: r})
  478. if err != nil {
  479. return nil, err
  480. }
  481. if result.err != nil {
  482. return nil, result.err
  483. }
  484. return result.resp.(*pb.AuthUserGetResponse), nil
  485. }
  486. func (s *EtcdServer) UserList(ctx context.Context, r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  487. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthUserList: r})
  488. if err != nil {
  489. return nil, err
  490. }
  491. if result.err != nil {
  492. return nil, result.err
  493. }
  494. return result.resp.(*pb.AuthUserListResponse), nil
  495. }
  496. func (s *EtcdServer) UserRevokeRole(ctx context.Context, r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  497. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthUserRevokeRole: r})
  498. if err != nil {
  499. return nil, err
  500. }
  501. if result.err != nil {
  502. return nil, result.err
  503. }
  504. return result.resp.(*pb.AuthUserRevokeRoleResponse), nil
  505. }
  506. func (s *EtcdServer) RoleAdd(ctx context.Context, r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  507. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthRoleAdd: r})
  508. if err != nil {
  509. return nil, err
  510. }
  511. if result.err != nil {
  512. return nil, result.err
  513. }
  514. return result.resp.(*pb.AuthRoleAddResponse), nil
  515. }
  516. func (s *EtcdServer) RoleGrantPermission(ctx context.Context, r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  517. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthRoleGrantPermission: r})
  518. if err != nil {
  519. return nil, err
  520. }
  521. if result.err != nil {
  522. return nil, result.err
  523. }
  524. return result.resp.(*pb.AuthRoleGrantPermissionResponse), nil
  525. }
  526. func (s *EtcdServer) RoleGet(ctx context.Context, r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  527. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthRoleGet: r})
  528. if err != nil {
  529. return nil, err
  530. }
  531. if result.err != nil {
  532. return nil, result.err
  533. }
  534. return result.resp.(*pb.AuthRoleGetResponse), nil
  535. }
  536. func (s *EtcdServer) RoleList(ctx context.Context, r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  537. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthRoleList: r})
  538. if err != nil {
  539. return nil, err
  540. }
  541. if result.err != nil {
  542. return nil, result.err
  543. }
  544. return result.resp.(*pb.AuthRoleListResponse), nil
  545. }
  546. func (s *EtcdServer) RoleRevokePermission(ctx context.Context, r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  547. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthRoleRevokePermission: r})
  548. if err != nil {
  549. return nil, err
  550. }
  551. if result.err != nil {
  552. return nil, result.err
  553. }
  554. return result.resp.(*pb.AuthRoleRevokePermissionResponse), nil
  555. }
  556. func (s *EtcdServer) RoleDelete(ctx context.Context, r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  557. result, err := s.processInternalRaftRequest(ctx, pb.InternalRaftRequest{AuthRoleDelete: r})
  558. if err != nil {
  559. return nil, err
  560. }
  561. if result.err != nil {
  562. return nil, result.err
  563. }
  564. return result.resp.(*pb.AuthRoleDeleteResponse), nil
  565. }
  566. // doSerialize handles the auth logic, with permissions checked by "chk", for a serialized request "get". Returns a non-nil error on authentication failure.
  567. func (s *EtcdServer) doSerialize(ctx context.Context, chk func(*auth.AuthInfo) error, get func()) error {
  568. for {
  569. ai, err := s.AuthStore().AuthInfoFromCtx(ctx)
  570. if err != nil {
  571. return err
  572. }
  573. if ai == nil {
  574. // chk expects non-nil AuthInfo; use empty credentials
  575. ai = &auth.AuthInfo{}
  576. }
  577. if err = chk(ai); err != nil {
  578. if err == auth.ErrAuthOldRevision {
  579. continue
  580. }
  581. return err
  582. }
  583. // fetch response for serialized request
  584. get()
  585. // empty credentials or current auth info means no need to retry
  586. if ai.Revision == 0 || ai.Revision == s.authStore.Revision() {
  587. return nil
  588. }
  589. // avoid TOCTOU error, retry of the request is required.
  590. }
  591. }
  592. func (s *EtcdServer) processInternalRaftRequestOnce(ctx context.Context, r pb.InternalRaftRequest) (*applyResult, error) {
  593. ai := s.getAppliedIndex()
  594. ci := s.getCommittedIndex()
  595. if ci > ai+maxGapBetweenApplyAndCommitIndex {
  596. return nil, ErrTooManyRequests
  597. }
  598. r.Header = &pb.RequestHeader{
  599. ID: s.reqIDGen.Next(),
  600. }
  601. authInfo, err := s.AuthStore().AuthInfoFromCtx(ctx)
  602. if err != nil {
  603. return nil, err
  604. }
  605. if authInfo != nil {
  606. r.Header.Username = authInfo.Username
  607. r.Header.AuthRevision = authInfo.Revision
  608. }
  609. data, err := r.Marshal()
  610. if err != nil {
  611. return nil, err
  612. }
  613. if len(data) > maxRequestBytes {
  614. return nil, ErrRequestTooLarge
  615. }
  616. id := r.ID
  617. if id == 0 {
  618. id = r.Header.ID
  619. }
  620. ch := s.w.Register(id)
  621. cctx, cancel := context.WithTimeout(ctx, s.Cfg.ReqTimeout())
  622. defer cancel()
  623. start := time.Now()
  624. s.r.Propose(cctx, data)
  625. proposalsPending.Inc()
  626. defer proposalsPending.Dec()
  627. select {
  628. case x := <-ch:
  629. return x.(*applyResult), nil
  630. case <-cctx.Done():
  631. proposalsFailed.Inc()
  632. s.w.Trigger(id, nil) // GC wait
  633. return nil, s.parseProposeCtxErr(cctx.Err(), start)
  634. case <-s.done:
  635. return nil, ErrStopped
  636. }
  637. }
  638. func (s *EtcdServer) processInternalRaftRequest(ctx context.Context, r pb.InternalRaftRequest) (*applyResult, error) {
  639. var result *applyResult
  640. var err error
  641. for {
  642. result, err = s.processInternalRaftRequestOnce(ctx, r)
  643. if err != auth.ErrAuthOldRevision {
  644. break
  645. }
  646. }
  647. return result, err
  648. }
  649. // Watchable returns a watchable interface attached to the etcdserver.
  650. func (s *EtcdServer) Watchable() mvcc.WatchableKV { return s.KV() }
  651. func (s *EtcdServer) linearizableReadLoop() {
  652. var rs raft.ReadState
  653. for {
  654. ctxToSend := make([]byte, 8)
  655. id1 := s.reqIDGen.Next()
  656. binary.BigEndian.PutUint64(ctxToSend, id1)
  657. select {
  658. case <-s.readwaitc:
  659. case <-s.stopping:
  660. return
  661. }
  662. nextnr := newNotifier()
  663. s.readMu.Lock()
  664. nr := s.readNotifier
  665. s.readNotifier = nextnr
  666. s.readMu.Unlock()
  667. cctx, cancel := context.WithTimeout(context.Background(), s.Cfg.ReqTimeout())
  668. if err := s.r.ReadIndex(cctx, ctxToSend); err != nil {
  669. cancel()
  670. if err == raft.ErrStopped {
  671. return
  672. }
  673. plog.Errorf("failed to get read index from raft: %v", err)
  674. readIndexFailed.Inc()
  675. nr.notify(err)
  676. continue
  677. }
  678. cancel()
  679. var (
  680. timeout bool
  681. done bool
  682. )
  683. for !timeout && !done {
  684. select {
  685. case rs = <-s.r.readStateC:
  686. done = bytes.Equal(rs.RequestCtx, ctxToSend)
  687. if !done {
  688. // a previous request might time out. now we should ignore the response of it and
  689. // continue waiting for the response of the current requests.
  690. id2 := uint64(0)
  691. if len(rs.RequestCtx) == 8 {
  692. id2 = binary.BigEndian.Uint64(rs.RequestCtx)
  693. }
  694. plog.Warningf("ignored out-of-date read index response; local node read indexes queueing up and waiting to be in sync with leader (request ID want %d, got %d)", id1, id2)
  695. slowReadIndex.Inc()
  696. }
  697. case <-time.After(s.Cfg.ReqTimeout()):
  698. plog.Warningf("timed out waiting for read index response (local node might have slow network)")
  699. nr.notify(ErrTimeout)
  700. timeout = true
  701. slowReadIndex.Inc()
  702. case <-s.stopping:
  703. return
  704. }
  705. }
  706. if !done {
  707. continue
  708. }
  709. if ai := s.getAppliedIndex(); ai < rs.Index {
  710. select {
  711. case <-s.applyWait.Wait(rs.Index):
  712. case <-s.stopping:
  713. return
  714. }
  715. }
  716. // unblock all l-reads requested at indices before rs.Index
  717. nr.notify(nil)
  718. }
  719. }
  720. func (s *EtcdServer) linearizableReadNotify(ctx context.Context) error {
  721. s.readMu.RLock()
  722. nc := s.readNotifier
  723. s.readMu.RUnlock()
  724. // signal linearizable loop for current notify if it hasn't been already
  725. select {
  726. case s.readwaitc <- struct{}{}:
  727. default:
  728. }
  729. // wait for read state notification
  730. select {
  731. case <-nc.c:
  732. return nc.err
  733. case <-ctx.Done():
  734. return ctx.Err()
  735. case <-s.done:
  736. return ErrStopped
  737. }
  738. }