v3_server.go 21 KB

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