Request.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. package org.apache.zookeeper.server;
  19. import static java.nio.charset.StandardCharsets.UTF_8;
  20. import java.io.IOException;
  21. import java.nio.ByteBuffer;
  22. import java.util.List;
  23. import java.util.function.Supplier;
  24. import org.apache.jute.Record;
  25. import org.apache.zookeeper.KeeperException;
  26. import org.apache.zookeeper.ZooDefs.OpCode;
  27. import org.apache.zookeeper.common.Time;
  28. import org.apache.zookeeper.data.Id;
  29. import org.apache.zookeeper.metrics.Summary;
  30. import org.apache.zookeeper.metrics.SummarySet;
  31. import org.apache.zookeeper.server.persistence.Util;
  32. import org.apache.zookeeper.server.quorum.LearnerHandler;
  33. import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
  34. import org.apache.zookeeper.server.util.AuthUtil;
  35. import org.apache.zookeeper.txn.TxnDigest;
  36. import org.apache.zookeeper.txn.TxnHeader;
  37. import org.slf4j.Logger;
  38. import org.slf4j.LoggerFactory;
  39. /**
  40. * This is the structure that represents a request moving through a chain of
  41. * RequestProcessors. There are various pieces of information that is tacked
  42. * onto the request as it is processed.
  43. */
  44. public class Request {
  45. private static final Logger LOG = LoggerFactory.getLogger(Request.class);
  46. public static final Request requestOfDeath = new Request(null, 0, 0, 0, null, null);
  47. // Considers a request stale if the request's connection has closed. Enabled
  48. // by default.
  49. private static volatile boolean staleConnectionCheck = Boolean.parseBoolean(System.getProperty("zookeeper.request_stale_connection_check", "true"));
  50. // Considers a request stale if the request latency is higher than its
  51. // associated session timeout. Disabled by default.
  52. private static volatile boolean staleLatencyCheck = Boolean.parseBoolean(System.getProperty("zookeeper.request_stale_latency_check", "false"));
  53. public Request(ServerCnxn cnxn, long sessionId, int xid, int type, RequestRecord request, List<Id> authInfo) {
  54. this.cnxn = cnxn;
  55. this.sessionId = sessionId;
  56. this.cxid = xid;
  57. this.type = type;
  58. this.request = request;
  59. this.authInfo = authInfo;
  60. }
  61. public Request(long sessionId, int xid, int type, TxnHeader hdr, Record txn, long zxid) {
  62. this.sessionId = sessionId;
  63. this.cxid = xid;
  64. this.type = type;
  65. this.hdr = hdr;
  66. this.txn = txn;
  67. this.zxid = zxid;
  68. this.request = null;
  69. this.cnxn = null;
  70. this.authInfo = null;
  71. }
  72. public Request(TxnHeader hdr, Record txn, TxnDigest digest) {
  73. this.sessionId = hdr.getClientId();
  74. this.cxid = hdr.getCxid();
  75. this.type = hdr.getType();
  76. this.hdr = hdr;
  77. this.txn = txn;
  78. this.zxid = hdr.getZxid();
  79. this.request = null;
  80. this.cnxn = null;
  81. this.authInfo = null;
  82. this.txnDigest = digest;
  83. }
  84. public final long sessionId;
  85. public final int cxid;
  86. public final int type;
  87. private final RequestRecord request;
  88. public <T extends Record> T readRequestRecord(Supplier<T> constructor) throws IOException {
  89. if (request != null) {
  90. return request.readRecord(constructor);
  91. }
  92. throw new IOException(new NullPointerException("request"));
  93. }
  94. public <T extends Record> T readRequestRecordNoException(Supplier<T> constructor) {
  95. try {
  96. return readRequestRecord(constructor);
  97. } catch (IOException e) {
  98. return null;
  99. }
  100. }
  101. public byte[] readRequestBytes() {
  102. if (request != null) {
  103. return request.readBytes();
  104. }
  105. return null;
  106. }
  107. public String requestDigest() {
  108. if (request != null) {
  109. final StringBuilder sb = new StringBuilder();
  110. final byte[] payload = request.readBytes();
  111. for (byte b : payload) {
  112. sb.append(String.format("%02x", (0xff & b)));
  113. }
  114. return sb.toString();
  115. }
  116. return "request buffer is null";
  117. }
  118. public final ServerCnxn cnxn;
  119. private TxnHeader hdr;
  120. private Record txn;
  121. public long zxid = -1;
  122. public final List<Id> authInfo;
  123. public final long createTime = Time.currentElapsedTime();
  124. public long prepQueueStartTime = -1;
  125. public long prepStartTime = -1;
  126. public long commitProcQueueStartTime = -1;
  127. public long commitRecvTime = -1;
  128. public long syncQueueStartTime;
  129. public long requestThrottleQueueTime;
  130. private Object owner;
  131. private KeeperException e;
  132. public QuorumVerifier qv = null;
  133. private TxnDigest txnDigest;
  134. private boolean isThrottledFlag = false;
  135. public boolean isThrottled() {
  136. return isThrottledFlag;
  137. }
  138. public void setIsThrottled(boolean val) {
  139. isThrottledFlag = val;
  140. }
  141. public boolean isThrottlable() {
  142. return this.type != OpCode.ping
  143. && this.type != OpCode.closeSession
  144. && this.type != OpCode.createSession;
  145. }
  146. public byte[] getSerializeData() {
  147. if (this.hdr == null) {
  148. return null;
  149. }
  150. try {
  151. return Util.marshallTxnEntry(this.hdr, this.txn, this.txnDigest);
  152. } catch (IOException e) {
  153. LOG.error("This really should be impossible.", e);
  154. return new byte[32];
  155. }
  156. }
  157. /**
  158. * If this is a create or close request for a local-only session.
  159. */
  160. private boolean isLocalSession = false;
  161. private int largeRequestSize = -1;
  162. public boolean isLocalSession() {
  163. return isLocalSession;
  164. }
  165. public void setLocalSession(boolean isLocalSession) {
  166. this.isLocalSession = isLocalSession;
  167. }
  168. public void setLargeRequestSize(int size) {
  169. largeRequestSize = size;
  170. }
  171. public int getLargeRequestSize() {
  172. return largeRequestSize;
  173. }
  174. public Object getOwner() {
  175. return owner;
  176. }
  177. public void setOwner(Object owner) {
  178. this.owner = owner;
  179. }
  180. public TxnHeader getHdr() {
  181. return hdr;
  182. }
  183. public void setHdr(TxnHeader hdr) {
  184. this.hdr = hdr;
  185. }
  186. public Record getTxn() {
  187. return txn;
  188. }
  189. public void setTxn(Record txn) {
  190. this.txn = txn;
  191. }
  192. public ServerCnxn getConnection() {
  193. return cnxn;
  194. }
  195. public static boolean getStaleLatencyCheck() {
  196. return staleLatencyCheck;
  197. }
  198. public static void setStaleLatencyCheck(boolean check) {
  199. staleLatencyCheck = check;
  200. }
  201. public static boolean getStaleConnectionCheck() {
  202. return staleConnectionCheck;
  203. }
  204. public static void setStaleConnectionCheck(boolean check) {
  205. staleConnectionCheck = check;
  206. }
  207. public boolean isStale() {
  208. if (cnxn == null) {
  209. return false;
  210. }
  211. // closeSession requests should be able to outlive the session in order
  212. // to clean-up state.
  213. if (type == OpCode.closeSession) {
  214. return false;
  215. }
  216. if (staleConnectionCheck) {
  217. // If the connection is closed, consider the request stale.
  218. if (cnxn.isStale() || cnxn.isInvalid()) {
  219. return true;
  220. }
  221. }
  222. if (staleLatencyCheck) {
  223. // If the request latency is higher than session timeout, consider
  224. // the request stale.
  225. long currentTime = Time.currentElapsedTime();
  226. return (currentTime - createTime) > cnxn.getSessionTimeout();
  227. }
  228. return false;
  229. }
  230. /**
  231. * A prior request was dropped on this request's connection and
  232. * therefore this request must also be dropped to ensure correct
  233. * ordering semantics.
  234. */
  235. public boolean mustDrop() {
  236. return ((cnxn != null) && cnxn.isInvalid());
  237. }
  238. /**
  239. * is the packet type a valid packet in zookeeper
  240. *
  241. * @param type
  242. * the type of the packet
  243. * @return true if a valid packet, false if not
  244. */
  245. static boolean isValid(int type) {
  246. // make sure this is always synchronized with Zoodefs!!
  247. switch (type) {
  248. case OpCode.notification:
  249. case OpCode.check:
  250. return false;
  251. case OpCode.closeSession:
  252. case OpCode.create:
  253. case OpCode.create2:
  254. case OpCode.createTTL:
  255. case OpCode.createContainer:
  256. case OpCode.createSession:
  257. case OpCode.delete:
  258. case OpCode.deleteContainer:
  259. case OpCode.exists:
  260. case OpCode.getACL:
  261. case OpCode.getChildren:
  262. case OpCode.getAllChildrenNumber:
  263. case OpCode.getChildren2:
  264. case OpCode.getData:
  265. case OpCode.getEphemerals:
  266. case OpCode.multi:
  267. case OpCode.multiRead:
  268. case OpCode.ping:
  269. case OpCode.reconfig:
  270. case OpCode.setACL:
  271. case OpCode.setData:
  272. case OpCode.setWatches:
  273. case OpCode.setWatches2:
  274. case OpCode.sync:
  275. case OpCode.checkWatches:
  276. case OpCode.removeWatches:
  277. case OpCode.addWatch:
  278. case OpCode.whoAmI:
  279. return true;
  280. default:
  281. return false;
  282. }
  283. }
  284. public boolean isQuorum() {
  285. switch (this.type) {
  286. case OpCode.exists:
  287. case OpCode.getACL:
  288. case OpCode.getChildren:
  289. case OpCode.getAllChildrenNumber:
  290. case OpCode.getChildren2:
  291. case OpCode.getData:
  292. case OpCode.getEphemerals:
  293. case OpCode.multiRead:
  294. case OpCode.whoAmI:
  295. return false;
  296. case OpCode.create:
  297. case OpCode.create2:
  298. case OpCode.createTTL:
  299. case OpCode.createContainer:
  300. case OpCode.error:
  301. case OpCode.delete:
  302. case OpCode.deleteContainer:
  303. case OpCode.setACL:
  304. case OpCode.setData:
  305. case OpCode.check:
  306. case OpCode.multi:
  307. case OpCode.reconfig:
  308. return true;
  309. case OpCode.closeSession:
  310. case OpCode.createSession:
  311. return !this.isLocalSession;
  312. default:
  313. return false;
  314. }
  315. }
  316. public static String op2String(int op) {
  317. switch (op) {
  318. case OpCode.notification:
  319. return "notification";
  320. case OpCode.create:
  321. return "create";
  322. case OpCode.delete:
  323. return "delete";
  324. case OpCode.exists:
  325. return "exists";
  326. case OpCode.getData:
  327. return "getData";
  328. case OpCode.setData:
  329. return "setData";
  330. case OpCode.getACL:
  331. return "getACL";
  332. case OpCode.setACL:
  333. return "setACL";
  334. case OpCode.getChildren:
  335. return "getChildren";
  336. case OpCode.sync:
  337. return "sync";
  338. case OpCode.ping:
  339. return "ping";
  340. case OpCode.getChildren2:
  341. return "getChildren2";
  342. case OpCode.check:
  343. return "check";
  344. case OpCode.multi:
  345. return "multi";
  346. case OpCode.create2:
  347. return "create2";
  348. case OpCode.reconfig:
  349. return "reconfig";
  350. case OpCode.checkWatches:
  351. return "checkWatches";
  352. case OpCode.removeWatches:
  353. return "removeWatches";
  354. case OpCode.createContainer:
  355. return "createContainer";
  356. case OpCode.deleteContainer:
  357. return "deleteContainer";
  358. case OpCode.createTTL:
  359. return "createTTL";
  360. case OpCode.multiRead:
  361. return "multiRead";
  362. case OpCode.auth:
  363. return "auth";
  364. case OpCode.setWatches:
  365. return "setWatches";
  366. case OpCode.setWatches2:
  367. return "setWatches2";
  368. case OpCode.addWatch:
  369. return "addWatch";
  370. case OpCode.sasl:
  371. return "sasl";
  372. case OpCode.getEphemerals:
  373. return "getEphemerals";
  374. case OpCode.getAllChildrenNumber:
  375. return "getAllChildrenNumber";
  376. case OpCode.createSession:
  377. return "createSession";
  378. case OpCode.closeSession:
  379. return "closeSession";
  380. case OpCode.error:
  381. return "error";
  382. case OpCode.whoAmI:
  383. return "whoAmI";
  384. default:
  385. return "unknown " + op;
  386. }
  387. }
  388. @Override
  389. public String toString() {
  390. StringBuilder sb = new StringBuilder();
  391. sb.append("sessionid:0x").append(Long.toHexString(sessionId))
  392. .append(" type:").append(op2String(type))
  393. .append(" cxid:0x").append(Long.toHexString(cxid))
  394. .append(" zxid:0x").append(Long.toHexString(hdr == null ? -2 : hdr.getZxid()))
  395. .append(" txntype:").append(hdr == null ? "unknown" : "" + hdr.getType());
  396. // best effort to print the path assoc with this request
  397. String path = "n/a";
  398. if (type != OpCode.createSession
  399. && type != OpCode.setWatches
  400. && type != OpCode.setWatches2
  401. && type != OpCode.closeSession
  402. && request != null) {
  403. try {
  404. // make sure we don't mess with request itself
  405. byte[] bytes = request.readBytes();
  406. if (bytes != null && bytes.length >= 4) {
  407. ByteBuffer buf = ByteBuffer.wrap(bytes);
  408. int pathLen = buf.getInt();
  409. // sanity check
  410. if (pathLen >= 0 && pathLen < 4096 && buf.remaining() >= pathLen) {
  411. byte[] b = new byte[pathLen];
  412. buf.get(b);
  413. path = new String(b, UTF_8);
  414. }
  415. }
  416. } catch (Exception e) {
  417. // ignore - can't find the path, will output "n/a" instead
  418. }
  419. }
  420. sb.append(" reqpath:").append(path);
  421. return sb.toString();
  422. }
  423. public void setException(KeeperException e) {
  424. this.e = e;
  425. }
  426. public KeeperException getException() {
  427. return e;
  428. }
  429. public void logLatency(Summary metric) {
  430. logLatency(metric, Time.currentWallTime());
  431. }
  432. public void logLatency(Summary metric, long currentTime) {
  433. if (hdr != null) {
  434. /* Request header is created by leader. If there is clock drift
  435. * latency might be negative. Headers use wall time, not
  436. * CLOCK_MONOTONIC.
  437. */
  438. long latency = currentTime - hdr.getTime();
  439. if (latency >= 0) {
  440. metric.add(latency);
  441. }
  442. }
  443. }
  444. public void logLatency(SummarySet metric, String key, long currentTime) {
  445. if (hdr != null) {
  446. /* Request header is created by leader. If there is clock drift
  447. * latency might be negative. Headers use wall time, not
  448. * CLOCK_MONOTONIC.
  449. */
  450. long latency = currentTime - hdr.getTime();
  451. if (latency >= 0) {
  452. metric.add(key, latency);
  453. }
  454. }
  455. }
  456. public void logLatency(SummarySet metric, String key) {
  457. logLatency(metric, key, Time.currentWallTime());
  458. }
  459. /**
  460. * Returns a formatted, comma-separated list of the user IDs
  461. * associated with this {@code Request}, or {@code null} if no
  462. * user IDs were found.
  463. *
  464. * The return value is used for audit logging. While it may be
  465. * easy on the eyes, it is underspecified: it does not mention the
  466. * corresponding {@code scheme}, nor are its components escaped.
  467. * This is not a security feature.
  468. *
  469. * @return a comma-separated list of user IDs, or {@code null} if
  470. * no user IDs were found.
  471. */
  472. public String getUsersForAudit() {
  473. return AuthUtil.getUsers(authInfo);
  474. }
  475. public TxnDigest getTxnDigest() {
  476. return txnDigest;
  477. }
  478. public void setTxnDigest(TxnDigest txnDigest) {
  479. this.txnDigest = txnDigest;
  480. }
  481. public boolean isFromLearner() {
  482. return owner instanceof LearnerHandler;
  483. }
  484. }