-
Notifications
You must be signed in to change notification settings - Fork 516
/
FrontendSession.java
738 lines (666 loc) · 23.6 KB
/
FrontendSession.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.lealone.engine;
import java.io.IOException;
import java.net.Socket;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Random;
import org.lealone.api.ErrorCode;
import org.lealone.command.CommandInterface;
import org.lealone.command.FrontendBatchCommand;
import org.lealone.command.FrontendCommand;
import org.lealone.fs.FileUtils;
import org.lealone.message.DbException;
import org.lealone.message.JdbcSQLException;
import org.lealone.message.Trace;
import org.lealone.message.TraceSystem;
import org.lealone.storage.FileStore;
import org.lealone.storage.FrontendLobStorage;
import org.lealone.storage.LobStorage;
import org.lealone.transaction.Transaction;
import org.lealone.util.MathUtils;
import org.lealone.util.NetUtils;
import org.lealone.util.SmallLRUCache;
import org.lealone.util.StringUtils;
import org.lealone.util.TempFileDeleter;
import org.lealone.value.Transfer;
import org.lealone.value.Value;
/**
* The client side part of a session when using the server mode. This object
* communicates with a Session on the server side.
*/
public class FrontendSession extends SessionWithState implements DataHandler {
public static final int SESSION_PREPARE = 0;
public static final int SESSION_CLOSE = 1;
public static final int COMMAND_EXECUTE_QUERY = 2;
public static final int COMMAND_EXECUTE_UPDATE = 3;
public static final int COMMAND_CLOSE = 4;
public static final int RESULT_FETCH_ROWS = 5;
public static final int RESULT_RESET = 6;
public static final int RESULT_CLOSE = 7;
//public static final int COMMAND_COMMIT = 8; //不再使用
public static final int CHANGE_ID = 9;
public static final int COMMAND_GET_META_DATA = 10;
public static final int SESSION_PREPARE_READ_PARAMS = 11;
public static final int SESSION_SET_ID = 12;
public static final int SESSION_CANCEL_STATEMENT = 13;
public static final int SESSION_CHECK_KEY = 14;
public static final int SESSION_SET_AUTOCOMMIT = 15;
public static final int SESSION_UNDO_LOG_POS = 16;
public static final int LOB_READ = 17;
public static final int COMMAND_EXECUTE_DISTRIBUTED_QUERY = 100;
public static final int COMMAND_EXECUTE_DISTRIBUTED_UPDATE = 101;
public static final int COMMAND_EXECUTE_DISTRIBUTED_COMMIT = 102;
public static final int COMMAND_EXECUTE_DISTRIBUTED_ROLLBACK = 103;
public static final int COMMAND_EXECUTE_DISTRIBUTED_SAVEPOINT_ADD = 104;
public static final int COMMAND_EXECUTE_DISTRIBUTED_SAVEPOINT_ROLLBACK = 105;
public static final int COMMAND_EXECUTE_TRANSACTION_VALIDATE = 106;
public static final int COMMAND_EXECUTE_BATCH_UPDATE_STATEMENT = 120;
public static final int COMMAND_EXECUTE_BATCH_UPDATE_PREPAREDSTATEMENT = 121;
public static final int STATUS_ERROR = 0;
public static final int STATUS_OK = 1;
public static final int STATUS_CLOSED = 2;
public static final int STATUS_OK_STATE_CHANGED = 3;
private static final Random random = new Random(System.currentTimeMillis());
private SessionFactory sessionFactory;
private TraceSystem traceSystem;
private Trace trace;
private Transfer transfer;
private int nextId;
private boolean autoCommit = true;
private final ConnectionInfo connectionInfo;
private String databaseName;
private String cipher;
private byte[] fileEncryptionKey;
private final Object lobSyncObject = new Object();
private String sessionId;
private int clientVersion;
//private boolean autoReconnect;
private int lastReconnect;
private SessionInterface embedded;
//private DatabaseEventListener eventListener;
private LobStorage lobStorage;
private Transaction transaction;
public FrontendSession(ConnectionInfo ci) {
this.connectionInfo = ci;
}
private Transfer initTransfer(ConnectionInfo ci, String db, String server) throws IOException {
Socket socket = NetUtils.createSocket(server, Constants.DEFAULT_TCP_PORT, ci.isSSL());
Transfer trans = new Transfer(this, socket);
trans.setSSL(ci.isSSL());
trans.init();
trans.writeInt(Constants.TCP_PROTOCOL_VERSION_1);
trans.writeInt(Constants.TCP_PROTOCOL_VERSION_1);
trans.writeString(db);
trans.writeString(ci.getURL());
trans.writeString(ci.getUserName());
trans.writeBytes(ci.getUserPasswordHash());
trans.writeBytes(ci.getFilePasswordHash());
trans.writeBytes(ci.getFileEncryptionKey());
String[] keys = ci.getKeys();
trans.writeInt(keys.length);
for (String key : keys) {
trans.writeString(key).writeString(ci.getProperty(key));
}
try {
done(trans);
clientVersion = trans.readInt();
trans.setVersion(clientVersion);
trans.writeInt(FrontendSession.SESSION_SET_ID);
trans.writeString(sessionId);
done(trans);
} catch (DbException e) {
trans.close();
throw e;
}
autoCommit = true;
return trans;
}
@Override
public int getUndoLogPos() {
try {
traceOperation("SESSION_UNDO_LOG_POS", 0);
transfer.writeInt(FrontendSession.SESSION_UNDO_LOG_POS);
done(transfer);
return transfer.readInt();
} catch (IOException e) {
handleException(e);
}
return 1;
}
@Override
public void cancel() {
// this method is called when closing the connection
// the statement that is currently running is not canceled in this case
// however Statement.cancel is supported
}
/**
* Cancel the statement with the given id.
*
* @param id the statement id
*/
public void cancelStatement(int id) {
try {
Transfer trans = transfer.openNewConnection();
trans.init();
trans.writeInt(clientVersion);
trans.writeInt(clientVersion);
trans.writeString(null);
trans.writeString(null);
trans.writeString(sessionId);
trans.writeInt(FrontendSession.SESSION_CANCEL_STATEMENT);
trans.writeInt(id);
trans.close();
} catch (IOException e) {
trace.debug(e, "could not cancel statement");
}
}
@Override
public boolean isAutoCommit() {
return autoCommit;
}
@Override
public void setAutoCommit(boolean autoCommit) {
setAutoCommitSend(autoCommit);
this.autoCommit = autoCommit;
}
public void setAutoCommitFromServer(boolean autoCommit) {
this.autoCommit = autoCommit;
}
private void setAutoCommitSend(boolean autoCommit) {
try {
traceOperation("SESSION_SET_AUTOCOMMIT", autoCommit ? 1 : 0);
transfer.writeInt(FrontendSession.SESSION_SET_AUTOCOMMIT).writeBoolean(autoCommit);
done(transfer);
} catch (IOException e) {
handleException(e);
}
}
private String getFilePrefix(String dir) {
StringBuilder buff = new StringBuilder(dir);
buff.append('/');
for (int i = 0; i < databaseName.length(); i++) {
char ch = databaseName.charAt(i);
if (Character.isLetterOrDigit(ch)) {
buff.append(ch);
} else {
buff.append('_');
}
}
return buff.toString();
}
@Override
public int getPowerOffCount() {
return 0;
}
@Override
public void setPowerOffCount(int count) {
throw DbException.getUnsupportedException("remote");
}
/**
* Open a new (remote or embedded) session.
*
* @param openNew whether to open a new session in any case
* @return the session
*/
public SessionInterface connectEmbeddedOrServer(boolean openNew) {
ConnectionInfo ci = connectionInfo;
if (ci.isRemote()) {
connectServer(ci);
return this;
}
// create the session using reflection,
// so that the JDBC layer can be compiled without it
try {
if (openNew) {
ci.setProperty("OPEN_NEW", "true");
}
if (sessionFactory == null) {
sessionFactory = ci.getSessionFactory();
}
return sessionFactory.createSession(ci);
} catch (Exception e) {
throw DbException.convert(e);
}
}
private void connectServer(ConnectionInfo ci) {
String name = ci.getDatabaseName();
if (name.startsWith("//")) {
name = name.substring("//".length());
}
int idx = name.indexOf('/');
if (idx < 0) {
throw ci.getFormatException();
}
databaseName = name.substring(idx + 1);
String server = name.substring(0, idx);
traceSystem = new TraceSystem(null);
String traceLevelFile = ci.getProperty(SetTypes.TRACE_LEVEL_FILE, null);
if (traceLevelFile != null) {
int level = Integer.parseInt(traceLevelFile);
String prefix = getFilePrefix(SysProperties.CLIENT_TRACE_DIRECTORY);
try {
traceSystem.setLevelFile(level);
if (level > 0) {
String file = FileUtils.createTempFile(prefix, Constants.SUFFIX_TRACE_FILE, false, false);
traceSystem.setFileName(file);
}
} catch (IOException e) {
throw DbException.convertIOException(e, prefix);
}
}
String traceLevelSystemOut = ci.getProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT, null);
if (traceLevelSystemOut != null) {
int level = Integer.parseInt(traceLevelSystemOut);
traceSystem.setLevelSystemOut(level);
}
trace = traceSystem.getTrace(Trace.JDBC);
//autoReconnect = Boolean.valueOf(ci.getProperty("AUTO_RECONNECT", "false")).booleanValue();
// if (autoReconnect) {
// String className = ci.getProperty("DATABASE_EVENT_LISTENER");
// if (className != null) {
// className = StringUtils.trim(className, true, true, "'");
// try {
// eventListener = (DatabaseEventListener) Utils.loadUserClass(className).newInstance();
// } catch (Throwable e) {
// throw DbException.convert(e);
// }
// }
// }
cipher = ci.getProperty("CIPHER");
if (cipher != null) {
fileEncryptionKey = MathUtils.secureRandomBytes(32);
}
String[] servers = StringUtils.arraySplit(server, ',', true);
int len = servers.length;
transfer = null;
sessionId = StringUtils.convertBytesToHex(MathUtils.secureRandomBytes(32));
try {
for (int i = 0; i < len; i++) {
String s = servers[random.nextInt(len)];
try {
transfer = initTransfer(ci, databaseName, s);
break;
} catch (IOException e) {
if (i == len - 1) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, e, e + ": " + s);
}
int index = 0;
String[] newServers = new String[len - 1];
for (int j = 0; j < len; j++) {
if (j != i)
newServers[index++] = servers[j];
}
servers = newServers;
len--;
i = -1;
}
}
checkClosed();
} catch (DbException e) {
traceSystem.close();
throw e;
}
}
//TODO
public void handleException(Exception e) {
checkClosed();
}
@Override
public synchronized CommandInterface prepareCommand(String sql, int fetchSize) {
checkClosed();
return new FrontendCommand(this, transfer, sql, fetchSize);
}
//TODO
/**
* Automatically re-connect if necessary and if configured to do so.
*
* @param count the retry count index
* @return true if reconnected
*/
// private boolean autoReconnect(int count) {
// if (!isClosed()) {
// return false;
// }
// if (!autoReconnect) {
// return false;
// }
// if (!cluster && !autoCommit) {
// return false;
// }
// if (count > SysProperties.MAX_RECONNECT) {
// return false;
// }
// lastReconnect++;
// while (true) {
// try {
// embedded = connectEmbeddedOrServer(false);
// break;
// } catch (DbException e) {
// if (e.getErrorCode() != ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE) {
// throw e;
// }
// // exclusive mode: re-try endlessly
// try {
// Thread.sleep(500);
// } catch (Exception e2) {
// // ignore
// }
// }
// }
// if (embedded == this) {
// // connected to a server somewhere else
// embedded = null;
// } else {
// // opened an embedded connection now -
// // must connect to this database in server mode
// // unfortunately
// connectEmbeddedOrServer(true);
// }
// recreateSessionState();
// if (eventListener != null) {
// eventListener.setProgress(DatabaseEventListener.STATE_RECONNECTED, databaseName, count, SysProperties.MAX_RECONNECT);
// }
// return true;
// }
/**
* Check if this session is closed and throws an exception if so.
*
* @throws DbException if the session is closed
*/
public void checkClosed() {
if (isClosed()) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "session closed");
}
}
@Override
public void close() {
RuntimeException closeError = null;
if (transfer != null) {
synchronized (this) {
try {
traceOperation("SESSION_CLOSE", 0);
transfer.writeInt(FrontendSession.SESSION_CLOSE);
done(transfer);
transfer.close();
} catch (RuntimeException e) {
trace.error(e, "close");
closeError = e;
} catch (Exception e) {
trace.error(e, "close");
}
}
transfer = null;
}
traceSystem.close();
if (embedded != null) {
embedded.close();
embedded = null;
}
if (closeError != null) {
throw closeError;
}
}
@Override
public Trace getTrace() {
return traceSystem.getTrace(Trace.JDBC);
}
public int getNextId() {
return nextId++;
}
public int getCurrentId() {
return nextId;
}
/**
* Called to flush the output after data has been sent to the server and
* just before receiving data. This method also reads the status code from
* the server and throws any exception the server sent.
*
* @param transfer the transfer object
* @throws DbException if the server sent an exception
* @throws IOException if there is a communication problem between client
* and server
*/
public void done(Transfer transfer) throws IOException {
//正常来讲不会出现这种情况,如果出现了,说明存在bug,找出为什么transfer的输入流没正常读完的原因
if (transfer.available() > 0) {
throw DbException.throwInternalError("before transfer flush, the available bytes was "
+ transfer.available());
}
transfer.flush();
int status = transfer.readInt();
if (status == STATUS_ERROR) {
parseError(transfer);
} else if (status == STATUS_CLOSED) {
transfer = null;
} else if (status == STATUS_OK_STATE_CHANGED) {
sessionStateChanged = true;
} else if (status == STATUS_OK) {
// ok
} else {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "unexpected status " + status);
}
}
public void parseError(Transfer transfer) throws IOException {
String sqlstate = transfer.readString();
String message = transfer.readString();
String sql = transfer.readString();
int errorCode = transfer.readInt();
String stackTrace = transfer.readString();
JdbcSQLException s = new JdbcSQLException(message, sql, sqlstate, errorCode, null, stackTrace);
if (errorCode == ErrorCode.CONNECTION_BROKEN_1) {
// allow re-connect
IOException e = new IOException(s.toString());
e.initCause(s);
throw e;
}
throw DbException.convert(s);
}
@Override
public boolean isClosed() {
return transfer == null;
}
/**
* Write the operation to the trace system if debug trace is enabled.
*
* @param operation the operation performed
* @param id the id of the operation
*/
public void traceOperation(String operation, int id) {
if (trace.isDebugEnabled()) {
trace.debug("{0} {1}", operation, id);
}
}
@Override
public void checkPowerOff() {
// ok
}
@Override
public void checkWritingAllowed() {
// ok
}
@Override
public String getDatabasePath() {
return "";
}
@Override
public String getLobCompressionAlgorithm(int type) {
return null;
}
@Override
public int getMaxLengthInplaceLob() {
return SysProperties.LOB_CLIENT_MAX_SIZE_MEMORY;
}
@Override
public FileStore openFile(String name, String mode, boolean mustExist) {
if (mustExist && !FileUtils.exists(name)) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name);
}
FileStore store;
if (cipher == null) {
store = FileStore.open(this, name, mode);
} else {
store = FileStore.open(this, name, mode, cipher, fileEncryptionKey, 0);
}
store.setCheckedWriting(false);
try {
store.init();
} catch (DbException e) {
store.closeSilently();
throw e;
}
return store;
}
@Override
public DataHandler getDataHandler() {
return this;
}
@Override
public Object getLobSyncObject() {
return lobSyncObject;
}
@Override
public SmallLRUCache<String, String[]> getLobFileListCache() {
return null;
}
public int getLastReconnect() {
return lastReconnect;
}
@Override
public TempFileDeleter getTempFileDeleter() {
return TempFileDeleter.getInstance();
}
@Override
public boolean isReconnectNeeded(boolean write) {
return false;
}
@Override
public SessionInterface reconnect(boolean write) {
return this;
}
@Override
public void afterWriting() {
// nothing to do
}
@Override
public LobStorage getLobStorage() {
if (lobStorage == null) {
lobStorage = new FrontendLobStorage(this);
}
return lobStorage;
}
@Override
public Connection getLobConnection() {
return null;
}
@Override
public synchronized int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length) {
try {
traceOperation("LOB_READ", (int) lobId);
transfer.writeInt(FrontendSession.LOB_READ);
transfer.writeLong(lobId);
transfer.writeBytes(hmac);
transfer.writeLong(offset);
transfer.writeInt(length);
done(transfer);
length = transfer.readInt();
if (length <= 0) {
return length;
}
transfer.readBytes(buff, off, length);
return length;
} catch (IOException e) {
handleException(e);
}
return 1;
}
public synchronized void commitTransaction(String allLocalTransactionNames) {
checkClosed();
try {
transfer.writeInt(FrontendSession.COMMAND_EXECUTE_DISTRIBUTED_COMMIT).writeString(allLocalTransactionNames);
done(transfer);
} catch (IOException e) {
handleException(e);
}
}
public synchronized void rollbackTransaction() {
checkClosed();
try {
transfer.writeInt(FrontendSession.COMMAND_EXECUTE_DISTRIBUTED_ROLLBACK);
done(transfer);
} catch (IOException e) {
handleException(e);
}
}
public synchronized void addSavepoint(String name) {
checkClosed();
try {
transfer.writeInt(FrontendSession.COMMAND_EXECUTE_DISTRIBUTED_SAVEPOINT_ADD).writeString(name);
done(transfer);
} catch (IOException e) {
handleException(e);
}
}
public synchronized void rollbackToSavepoint(String name) {
checkClosed();
try {
transfer.writeInt(FrontendSession.COMMAND_EXECUTE_DISTRIBUTED_SAVEPOINT_ROLLBACK).writeString(name);
done(transfer);
} catch (IOException e) {
handleException(e);
}
}
public synchronized boolean validateTransaction(String localTransactionName) {
checkClosed();
try {
transfer.writeInt(FrontendSession.COMMAND_EXECUTE_TRANSACTION_VALIDATE).writeString(localTransactionName);
done(transfer);
return transfer.readBoolean();
} catch (Exception e) {
handleException(e);
return false;
}
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
public Transaction getTransaction() {
return transaction;
}
public synchronized FrontendBatchCommand getFrontendBatchCommand(ArrayList<String> batchCommands) {
checkClosed();
return new FrontendBatchCommand(this, transfer, batchCommands);
}
public synchronized FrontendBatchCommand getFrontendBatchCommand(CommandInterface preparedCommand,
ArrayList<Value[]> batchParameters) {
checkClosed();
return new FrontendBatchCommand(this, transfer, preparedCommand, batchParameters);
}
public String getURL() {
return connectionInfo.getURL();
}
public synchronized void checkTransfers() {
if (transfer != null) {
try {
if (transfer.available() > 0)
throw DbException.throwInternalError("the transfer available bytes was " + transfer.available());
} catch (IOException e) {
throw DbException.convert(e);
}
}
}
// private boolean distributed;
//
// public void setDistributed(boolean distributed) {
// this.distributed = distributed;
// }
//
// public boolean isDistributed() {
// return distributed;
// }
}