-
Notifications
You must be signed in to change notification settings - Fork 868
/
OStorageRemote.java
executable file
·1966 lines (1680 loc) · 76.4 KB
/
OStorageRemote.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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.client.remote;
import com.orientechnologies.common.concur.OOfflineNodeException;
import com.orientechnologies.common.concur.lock.OInterruptedException;
import com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.thread.OScheduledThreadPoolExecutorWithLogging;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.orient.client.binary.OChannelBinaryAsynchClient;
import com.orientechnologies.orient.client.remote.message.*;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.command.OCommandRequestAsynch;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterConfiguration;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OLiveQueryMonitor;
import com.orientechnologies.orient.core.db.OrientDBRemote;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentRemote;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTxInternal;
import com.orientechnologies.orient.core.db.document.OLiveQueryMonitorRemote;
import com.orientechnologies.orient.core.db.document.OTransactionOptimisticClient;
import com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OBonsaiCollectionPointer;
import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManager;
import com.orientechnologies.orient.core.exception.*;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.security.OTokenException;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.security.OCredentialInterceptor;
import com.orientechnologies.orient.core.security.OSecurityManager;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory;
import com.orientechnologies.orient.core.sql.query.OLiveQuery;
import com.orientechnologies.orient.core.storage.*;
import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordSerializationContext;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.tx.OTransactionAbstract;
import com.orientechnologies.orient.core.tx.OTransactionOptimistic;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol;
import com.orientechnologies.orient.enterprise.channel.binary.ODistributedRedirectException;
import com.orientechnologies.orient.enterprise.channel.binary.OTokenSecurityException;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This object is bound to each remote ODatabase instances.
*/
public class OStorageRemote extends OStorageAbstract implements OStorageProxy, ORemotePushHandler {
@Deprecated
public static final String PARAM_CONNECTION_STRATEGY = "connectionStrategy";
private static final String DEFAULT_HOST = "localhost";
private static final int DEFAULT_PORT = 2424;
private static final int DEFAULT_SSL_PORT = 2434;
private static final String ADDRESS_SEPARATOR = ";";
public static final String DRIVER_NAME = "OrientDB Java";
private static final String LOCAL_IP = "127.0.0.1";
private static final String LOCALHOST = "localhost";
private static AtomicInteger sessionSerialId = new AtomicInteger(-1);
public enum CONNECTION_STRATEGY {
STICKY, ROUND_ROBIN_CONNECT, ROUND_ROBIN_REQUEST
}
private CONNECTION_STRATEGY connectionStrategy = CONNECTION_STRATEGY.STICKY;
private final OSBTreeCollectionManagerRemote sbTreeCollectionManager = new OSBTreeCollectionManagerRemote(this);
private final List<String> serverURLs = new ArrayList<String>();
private final Map<String, OCluster> clusterMap = new ConcurrentHashMap<String, OCluster>();
private final ExecutorService asynchExecutor;
private final ODocument clusterConfiguration = new ODocument();
private final AtomicInteger users = new AtomicInteger(0);
private OContextConfiguration clientConfiguration;
private int connectionRetry;
private int connectionRetryDelay;
OCluster[] clusters = OCommonConst.EMPTY_CLUSTER_ARRAY;
private int defaultClusterId;
public ORemoteConnectionManager connectionManager;
private final Set<OStorageRemoteSession> sessions = Collections
.newSetFromMap(new ConcurrentHashMap<OStorageRemoteSession, Boolean>());
private final Map<Integer, OLiveQueryClientListener> liveQueryListener = new ConcurrentHashMap<>();
private volatile OStorageRemotePushThread pushThread;
private final OrientDBRemote context;
public OStorageRemote(final String iURL, OrientDBRemote context, final String iMode, ORemoteConnectionManager connectionManager)
throws IOException {
this(iURL, context, iMode, connectionManager, null);
}
public OStorageRemote(final String iURL, OrientDBRemote context, final String iMode, ORemoteConnectionManager connectionManager,
final STATUS status) throws IOException {
super(iURL, iURL, iMode); // NO TIMEOUT @SINCE 1.5
if (status != null)
this.status = status;
configuration = null;
clientConfiguration = new OContextConfiguration();
connectionRetry = clientConfiguration.getValueAsInteger(OGlobalConfiguration.NETWORK_SOCKET_RETRY);
connectionRetryDelay = clientConfiguration.getValueAsInteger(OGlobalConfiguration.NETWORK_SOCKET_RETRY_DELAY);
parseServerURLs();
asynchExecutor = new OScheduledThreadPoolExecutorWithLogging(1);
this.connectionManager = connectionManager;
this.context = context;
}
public <T extends OBinaryResponse> T asyncNetworkOperationNoRetry(final OBinaryAsyncRequest<T> request, int mode,
final ORecordId recordId, final ORecordCallback<T> callback, final String errorMessage) {
return asyncNetworkOperationRetry(request, mode, recordId, callback, errorMessage, 0);
}
public <T extends OBinaryResponse> T asyncNetworkOperationRetry(final OBinaryAsyncRequest<T> request, int mode,
final ORecordId recordId, final ORecordCallback<T> callback, final String errorMessage, int retry) {
final int pMode;
if (mode == 1 && callback == null)
// ASYNCHRONOUS MODE NO ANSWER
pMode = 2;
else
pMode = mode;
request.setMode((byte) pMode);
return baseNetworkOperation((network, session) -> {
// Send The request
try {
network.beginRequest(request.getCommand(), session);
request.write(network, session);
} finally {
network.endRequest();
}
final T response = request.createResponse();
T ret = null;
if (pMode == 0) {
// SYNC
try {
beginResponse(network, session);
response.read(network, session);
} finally {
endResponse(network);
}
ret = response;
connectionManager.release(network);
} else if (pMode == 1) {
// ASYNC
asynchExecutor.submit(() -> {
try {
try {
beginResponse(network, session);
response.read(network, session);
} finally {
endResponse(network);
}
callback.call(recordId, response);
connectionManager.release(network);
} catch (Throwable e) {
connectionManager.remove(network);
OLogManager.instance().error(this, "Exception on async query", e);
}
});
} else {
// NO RESPONSE
connectionManager.release(network);
}
return ret;
}, errorMessage, retry);
}
public <T extends OBinaryResponse> T networkOperationRetryTimeout(final OBinaryRequest<T> request, final String errorMessage,
int retry, int timeout) {
return baseNetworkOperation((network, session) -> {
try {
network.beginRequest(request.getCommand(), session);
request.write(network, session);
} finally {
network.endRequest();
}
int prev = network.getSocketTimeout();
T response = request.createResponse();
try {
if (timeout > 0)
network.setSocketTimeout(timeout);
beginResponse(network, session);
response.read(network, session);
} finally {
endResponse(network);
if (timeout > 0)
network.setSocketTimeout(prev);
}
connectionManager.release(network);
return response;
}, errorMessage, retry);
}
public <T extends OBinaryResponse> T networkOperationNoRetry(final OBinaryRequest<T> request, final String errorMessage) {
return networkOperationRetryTimeout(request, errorMessage, 0, 0);
}
public <T extends OBinaryResponse> T networkOperation(final OBinaryRequest<T> request, final String errorMessage) {
return networkOperationRetryTimeout(request, errorMessage, connectionRetry, 0);
}
public <T> T baseNetworkOperation(final OStorageRemoteOperation<T> operation, final String errorMessage, int retry) {
OStorageRemoteSession session = getCurrentSession();
if (session.commandExecuting)
throw new ODatabaseException(
"Cannot execute the request because an asynchronous operation is in progress. Please use a different connection");
String serverUrl = null;
do {
session.commandExecuting = true;
OChannelBinaryAsynchClient network = null;
if (serverUrl == null)
serverUrl = getNextAvailableServerURL(false, session);
do {
try {
network = getNetwork(serverUrl);
} catch (OException e) {
serverUrl = useNewServerURL(serverUrl);
if (serverUrl == null)
throw e;
}
} while (network == null);
try {
// In case i do not have a token or i'm switching between server i've to execute a open operation.
OStorageRemoteNodeSession nodeSession = session.getServerSession(network.getServerURL());
if (nodeSession == null || !nodeSession.isValid()) {
openRemoteDatabase(network);
if (!network.tryLock())
continue;
}
return operation.execute(network, session);
} catch (ODistributedRedirectException e) {
connectionManager.release(network);
OLogManager.instance()
.debug(this, "Redirecting the request from server '%s' to the server '%s' because %s", e.getFromServer(), e.toString(),
e.getMessage());
// RECONNECT TO THE SERVER SUGGESTED IN THE EXCEPTION
serverUrl = e.getToServerAddress();
} catch (OModificationOperationProhibitedException mope) {
connectionManager.release(network);
handleDBFreeze();
serverUrl = null;
} catch (OTokenException | OTokenSecurityException e) {
connectionManager.release(network);
session.removeServerSession(network.getServerURL());
if (--retry <= 0)
throw OException.wrapException(new OStorageException(errorMessage), e);
serverUrl = null;
} catch (OOfflineNodeException e) {
connectionManager.release(network);
// Remove the current url because the node is offline
synchronized (serverURLs) {
serverURLs.remove(serverUrl);
}
for (OStorageRemoteSession activeSession : sessions) {
// Not thread Safe ...
activeSession.removeServerSession(serverUrl);
}
serverUrl = null;
} catch (IOException | OIOException e) {
connectionManager.release(network);
retry = handleIOException(retry, network, e);
serverUrl = null;
} catch (OException e) {
connectionManager.release(network);
throw e;
} catch (Exception e) {
connectionManager.release(network);
throw OException.wrapException(new OStorageException(errorMessage), e);
} finally {
session.commandExecuting = false;
}
} while (true);
}
private int handleIOException(int retry, final OChannelBinaryAsynchClient network, final Exception e) {
OLogManager.instance()
.info(this, "Caught Network I/O errors on %s, trying an automatic reconnection... (error: %s)", network.getServerURL(),
e.getMessage());
OLogManager.instance().debug(this, "I/O error stack: ", e);
connectionManager.remove(network);
if (--retry <= 0)
throw OException.wrapException(new OIOException(e.getMessage()), e);
else {
try {
Thread.sleep(connectionRetryDelay);
} catch (InterruptedException e1) {
OLogManager.instance().error(this, "Exception was suppressed, original exception is ", e);
throw OException.wrapException(new OInterruptedException(e1.getMessage()), e1);
}
}
return retry;
}
@Override
public boolean isAssigningClusterIds() {
return false;
}
/**
* Supported only in embedded storage. Use <code>SELECT FROM metadata:storage</code> instead.
*/
@Override
public String getCreatedAtVersion() {
throw new UnsupportedOperationException("Supported only in embedded storage. Use 'SELECT FROM metadata:storage' instead.");
}
public int getSessionId() {
OStorageRemoteSession session = getCurrentSession();
return session != null ? session.getSessionId() : -1;
}
public String getServerURL() {
OStorageRemoteSession session = getCurrentSession();
return session != null ? session.getServerUrl() : null;
}
public void open(final String iUserName, final String iUserPassword, final OContextConfiguration conf) {
stateLock.acquireWriteLock();
addUser();
try {
OStorageRemoteSession session = getCurrentSession();
if (status == STATUS.CLOSED || !iUserName.equals(session.connectionUserName) || !iUserPassword
.equals(session.connectionUserPassword) || session.sessions.isEmpty()) {
OCredentialInterceptor ci = OSecurityManager.instance().newCredentialInterceptor();
if (ci != null) {
ci.intercept(getURL(), iUserName, iUserPassword);
session.connectionUserName = ci.getUsername();
session.connectionUserPassword = ci.getPassword();
} else {
// Do Nothing
session.connectionUserName = iUserName;
session.connectionUserPassword = iUserPassword;
}
String strategy = conf.getValueAsString(OGlobalConfiguration.CLIENT_CONNECTION_STRATEGY);
if (strategy != null)
connectionStrategy = CONNECTION_STRATEGY.valueOf(strategy.toUpperCase(Locale.ENGLISH));
openRemoteDatabase();
final OStorageConfiguration storageConfiguration = new OStorageRemoteConfiguration(this,
ORecordSerializerFactory.instance().getDefaultRecordSerializer().toString());
storageConfiguration.load(conf);
updateStorageConfiguration(storageConfiguration);
componentsFactory = new OCurrentStorageComponentsFactory(configuration);
} else {
reopenRemoteDatabase();
}
} catch (Exception e) {
removeUser();
if (e instanceof RuntimeException)
// PASS THROUGH
throw (RuntimeException) e;
else
throw OException.wrapException(new OStorageException("Cannot open the remote storage: " + name), e);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public OSBTreeCollectionManager getSBtreeCollectionManager() {
return sbTreeCollectionManager;
}
public void reload() {
final OStorageConfiguration storageConfiguration = new OStorageRemoteConfiguration(this,
ORecordSerializerFactory.instance().getDefaultRecordSerializer().toString());
storageConfiguration.load(clientConfiguration);
updateStorageConfiguration(storageConfiguration);
}
public void create(OContextConfiguration contextConfiguration) {
throw new UnsupportedOperationException(
"Cannot create a database in a remote server. Please use the console or the OServerAdmin class.");
}
public boolean exists() {
throw new UnsupportedOperationException(
"Cannot check the existence of a database in a remote server. Please use the console or the OServerAdmin class.");
}
public void close(final boolean iForce, boolean onDelete) {
if (status == STATUS.CLOSED)
return;
final OStorageRemoteSession session = getCurrentSession();
if (session != null) {
final Collection<OStorageRemoteNodeSession> nodes = session.getAllServerSessions();
if (!nodes.isEmpty()) {
for (OStorageRemoteNodeSession nodeSession : nodes) {
OChannelBinaryAsynchClient network = null;
try {
network = getNetwork(nodeSession.getServerURL());
OCloseRequest request = new OCloseRequest();
network.beginRequest(request.getCommand(), session);
request.write(network, session);
endRequest(network);
connectionManager.release(network);
} catch (OIOException ex) {
// IGNORING IF THE SERVER IS DOWN OR NOT REACHABLE THE SESSION IS AUTOMATICALLY CLOSED.
OLogManager.instance().debug(this, "Impossible to comunicate to the server for close: %s", ex);
connectionManager.remove(network);
} catch (IOException ex) {
// IGNORING IF THE SERVER IS DOWN OR NOT REACHABLE THE SESSION IS AUTOMATICALLY CLOSED.
OLogManager.instance().debug(this, "Impossible to comunicate to the server for close: %s", ex);
connectionManager.remove(network);
}
}
session.close();
sessions.remove(session);
if (!checkForClose(iForce))
return;
} else {
if (!iForce)
return;
}
}
// FROM HERE FORWARD COMPLETELY CLOSE THE STORAGE
for (Entry<Integer, OLiveQueryClientListener> listener : liveQueryListener.entrySet()) {
listener.getValue().onEnd();
}
liveQueryListener.clear();
// In backward compatible code the context is missing check if is there.
if (context != null) {
context.closeStorage(this);
}
}
public void shutdown() {
stateLock.acquireWriteLock();
try {
if (status == STATUS.CLOSED)
return;
status = STATUS.CLOSING;
super.close(true, false);
if (pushThread != null) {
pushThread.shutdown();
try {
pushThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// CLOSE ALL THE SOCKET POOLS
for (String url : serverURLs) {
connectionManager.closePool(url);
}
sbTreeCollectionManager.close();
status = STATUS.CLOSED;
} finally {
stateLock.releaseWriteLock();
}
}
private boolean checkForClose(final boolean force) {
if (status == STATUS.CLOSED)
return false;
if (status == STATUS.CLOSED)
return false;
final int remainingUsers = getUsers() > 0 ? removeUser() : 0;
return force || remainingUsers == 0;
}
@Override
public int getUsers() {
return users.get();
}
@Override
public int addUser() {
return users.incrementAndGet();
}
@Override
public int removeUser() {
if (users.get() < 1)
throw new IllegalStateException("Cannot remove user of the remote storage '" + toString() + "' because no user is using it");
return users.decrementAndGet();
}
public void delete() {
throw new UnsupportedOperationException(
"Cannot delete a database in a remote server. Please use the console or the OServerAdmin class.");
}
public Set<String> getClusterNames() {
stateLock.acquireReadLock();
try {
return new HashSet<String>(clusterMap.keySet());
} finally {
stateLock.releaseReadLock();
}
}
public OStorageOperationResult<OPhysicalPosition> createRecord(final ORecordId iRid, final byte[] iContent,
final int iRecordVersion, final byte iRecordType, final int iMode, final ORecordCallback<Long> iCallback) {
final OSBTreeCollectionManager collectionManager = ODatabaseRecordThreadLocal.INSTANCE.get().getSbTreeCollectionManager();
ORecordCallback<OCreateRecordResponse> realCallback = null;
if (iCallback != null) {
realCallback = (iRID, response) -> {
iCallback.call(response.getIdentity(), response.getIdentity().getClusterPosition());
updateCollectionsFromChanges(collectionManager, response.getChangedIds());
};
}
// The Upper layer require to return this also if it not really received response from the network
final OPhysicalPosition ppos = new OPhysicalPosition(iRecordType);
final OCreateRecordRequest request = new OCreateRecordRequest(iContent, iRid, iRecordType);
final OCreateRecordResponse response = asyncNetworkOperationNoRetry(request, iMode, iRid, realCallback,
"Error on create record in cluster " + iRid.getClusterId());
if (response != null) {
ppos.clusterPosition = response.getIdentity().getClusterPosition();
ppos.recordVersion = response.getVersion();
// THIS IS A COMPATIBILITY FIX TO AVOID TO FILL THE CLUSTER ID IN CASE OF ASYNC
if (iMode == 0) {
iRid.setClusterId(response.getIdentity().getClusterId());
iRid.setClusterPosition(response.getIdentity().getClusterPosition());
}
updateCollectionsFromChanges(collectionManager, response.getChangedIds());
}
return new OStorageOperationResult<OPhysicalPosition>(ppos);
}
private void updateCollectionsFromChanges(final OSBTreeCollectionManager collectionManager,
final Map<UUID, OBonsaiCollectionPointer> changes) {
if (collectionManager != null) {
for (Entry<UUID, OBonsaiCollectionPointer> coll : changes.entrySet()) {
collectionManager.updateCollectionPointer(coll.getKey(), coll.getValue());
}
if (ORecordSerializationContext.getDepth() <= 1)
collectionManager.clearPendingCollections();
}
}
@Override
public ORecordMetadata getRecordMetadata(final ORID rid) {
OGetRecordMetadataRequest request = new OGetRecordMetadataRequest(rid);
OGetRecordMetadataResponse response = networkOperation(request, "Error on record metadata read " + rid);
return response.getMetadata();
}
@Override
public OStorageOperationResult<ORawBuffer> readRecordIfVersionIsNotLatest(final ORecordId rid, final String fetchPlan,
final boolean ignoreCache, final int recordVersion) throws ORecordNotFoundException {
if (getCurrentSession().commandExecuting)
// PENDING NETWORK OPERATION, CAN'T EXECUTE IT NOW
return new OStorageOperationResult<ORawBuffer>(null);
OReadRecordIfVersionIsNotLatestRequest request = new OReadRecordIfVersionIsNotLatestRequest(rid, recordVersion, fetchPlan,
ignoreCache);
OReadRecordIfVersionIsNotLatestResponse response = networkOperation(request, "Error on read record " + rid);
return new OStorageOperationResult<ORawBuffer>(response.getResult());
}
public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRid, final String iFetchPlan, final boolean iIgnoreCache,
boolean prefetchRecords, final ORecordCallback<ORawBuffer> iCallback) {
if (getCurrentSession().commandExecuting)
// PENDING NETWORK OPERATION, CAN'T EXECUTE IT NOW
return new OStorageOperationResult<ORawBuffer>(null);
OReadRecordRequest request = new OReadRecordRequest(iIgnoreCache, iRid, iFetchPlan, false);
OReadRecordResponse response = networkOperation(request, "Error on read record " + iRid);
return new OStorageOperationResult<ORawBuffer>(response.getResult());
}
@Override
public String incrementalBackup(final String backupDirectory) {
OIncrementalBackupRequest request = new OIncrementalBackupRequest(backupDirectory);
OIncrementalBackupResponse response = networkOperationNoRetry(request, "Error on incremental backup");
return response.getFileName();
}
@Override
public void restoreFromIncrementalBackup(final String filePath) {
throw new UnsupportedOperationException("This operations is part of internal API and is not supported in remote storage");
}
public OStorageOperationResult<Integer> updateRecord(final ORecordId iRid, final boolean updateContent, final byte[] iContent,
final int iVersion, final byte iRecordType, final int iMode, final ORecordCallback<Integer> iCallback) {
final OSBTreeCollectionManager collectionManager = ODatabaseRecordThreadLocal.INSTANCE.get().getSbTreeCollectionManager();
ORecordCallback<OUpdateRecordResponse> realCallback = null;
if (iCallback != null) {
realCallback = (iRID, response) -> {
iCallback.call(iRID, response.getVersion());
updateCollectionsFromChanges(collectionManager, response.getChanges());
};
}
OUpdateRecordRequest request = new OUpdateRecordRequest(iRid, iContent, iVersion, updateContent, iRecordType);
OUpdateRecordResponse response = asyncNetworkOperationNoRetry(request, iMode, iRid, realCallback,
"Error on update record " + iRid);
Integer resVersion = null;
if (response != null) {
// Returning given version in case of no answer from server
resVersion = response.getVersion();
updateCollectionsFromChanges(collectionManager, response.getChanges());
}
return new OStorageOperationResult<Integer>(resVersion);
}
@Override
public OStorageOperationResult<Integer> recyclePosition(ORecordId iRecordId, byte[] iContent, int iVersion, byte recordType) {
throw new UnsupportedOperationException("recyclePosition");
}
public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRid, final int iVersion, final int iMode,
final ORecordCallback<Boolean> iCallback) {
ORecordCallback<ODeleteRecordResponse> realCallback = null;
if (iCallback != null)
realCallback = (iRID, response) -> iCallback.call(iRID, response.getResult());
final ODeleteRecordRequest request = new ODeleteRecordRequest(iRid, iVersion);
final ODeleteRecordResponse response = asyncNetworkOperationNoRetry(request, iMode, iRid, realCallback,
"Error on delete record " + iRid);
Boolean resDelete = null;
if (response != null)
resDelete = response.getResult();
return new OStorageOperationResult<Boolean>(resDelete);
}
@Override
public OStorageOperationResult<Boolean> hideRecord(final ORecordId recordId, final int mode,
final ORecordCallback<Boolean> callback) {
ORecordCallback<OHideRecordResponse> realCallback = null;
if (callback != null)
realCallback = (iRID, response) -> callback.call(iRID, response.getResult());
final OHideRecordRequest request = new OHideRecordRequest(recordId);
final OHideRecordResponse response = asyncNetworkOperationNoRetry(request, mode, recordId, realCallback,
"Error on hide record " + recordId);
Boolean resHide = null;
if (response != null)
resHide = response.getResult();
return new OStorageOperationResult<Boolean>(resHide);
}
@Override
public boolean cleanOutRecord(final ORecordId recordId, final int recordVersion, final int iMode,
final ORecordCallback<Boolean> callback) {
ORecordCallback<OCleanOutRecordResponse> realCallback = null;
if (callback != null)
realCallback = (iRID, response) -> callback.call(iRID, response.getResult());
final OCleanOutRecordRequest request = new OCleanOutRecordRequest(recordVersion, recordId);
final OCleanOutRecordResponse response = asyncNetworkOperationNoRetry(request, iMode, recordId, realCallback,
"Error on delete record " + recordId);
Boolean result = null;
if (response != null)
result = response.getResult();
return result;
}
@Override
public List<String> backup(OutputStream out, Map<String, Object> options, Callable<Object> callable,
final OCommandOutputListener iListener, int compressionLevel, int bufferSize) throws IOException {
throw new UnsupportedOperationException(
"backup is not supported against remote storage. Open the database with plocal or use the incremental backup in the Enterprise Edition");
}
@Override
public void restore(InputStream in, Map<String, Object> options, Callable<Object> callable,
final OCommandOutputListener iListener) throws IOException {
throw new UnsupportedOperationException(
"restore is not supported against remote storage. Open the database with plocal or use Enterprise Edition");
}
public OContextConfiguration getClientConfiguration() {
return clientConfiguration;
}
public long count(final int iClusterId) {
return count(new int[] { iClusterId });
}
@Override
public long count(int iClusterId, boolean countTombstones) {
return count(new int[] { iClusterId }, countTombstones);
}
public long[] getClusterDataRange(final int iClusterId) {
OGetClusterDataRangeRequest request = new OGetClusterDataRangeRequest(iClusterId);
OGetClusterDataRangeResponse response = networkOperation(request,
"Error on getting last entry position count in cluster: " + iClusterId);
return response.getPos();
}
@Override
public OPhysicalPosition[] higherPhysicalPositions(final int iClusterId, final OPhysicalPosition iClusterPosition) {
OHigherPhysicalPositionsRequest request = new OHigherPhysicalPositionsRequest(iClusterId, iClusterPosition);
OHigherPhysicalPositionsResponse response = networkOperation(request,
"Error on retrieving higher positions after " + iClusterPosition.clusterPosition);
return response.getNextPositions();
}
@Override
public OPhysicalPosition[] ceilingPhysicalPositions(final int clusterId, final OPhysicalPosition physicalPosition) {
OCeilingPhysicalPositionsRequest request = new OCeilingPhysicalPositionsRequest(clusterId, physicalPosition);
OCeilingPhysicalPositionsResponse response = networkOperation(request,
"Error on retrieving ceiling positions after " + physicalPosition.clusterPosition);
return response.getPositions();
}
@Override
public OPhysicalPosition[] lowerPhysicalPositions(final int iClusterId, final OPhysicalPosition physicalPosition) {
OLowerPhysicalPositionsRequest request = new OLowerPhysicalPositionsRequest(physicalPosition, iClusterId);
OLowerPhysicalPositionsResponse response = networkOperation(request,
"Error on retrieving lower positions after " + physicalPosition.clusterPosition);
return response.getPreviousPositions();
}
@Override
public OPhysicalPosition[] floorPhysicalPositions(final int clusterId, final OPhysicalPosition physicalPosition) {
OFloorPhysicalPositionsRequest request = new OFloorPhysicalPositionsRequest(physicalPosition, clusterId);
OFloorPhysicalPositionsResponse response = networkOperation(request,
"Error on retrieving floor positions after " + physicalPosition.clusterPosition);
return response.getPositions();
}
public long getSize() {
OGetSizeRequest request = new OGetSizeRequest();
OGetSizeResponse response = networkOperation(request, "Error on read database size");
return response.getSize();
}
@Override
public long countRecords() {
OCountRecordsRequest request = new OCountRecordsRequest();
OCountRecordsResponse response = networkOperation(request, "Error on read database record count");
return response.getCountRecords();
}
public long count(final int[] iClusterIds) {
return count(iClusterIds, false);
}
public long count(final int[] iClusterIds, final boolean countTombstones) {
OCountRequest request = new OCountRequest(iClusterIds, countTombstones);
OCountResponse response = networkOperation(request, "Error on read record count in clusters: " + Arrays.toString(iClusterIds));
return response.getCount();
}
/**
* Execute the command remotely and get the results back.
*/
public Object command(final OCommandRequestText iCommand) {
final boolean live = iCommand instanceof OLiveQuery;
final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal.INSTANCE.get();
final boolean asynch = iCommand instanceof OCommandRequestAsynch && ((OCommandRequestAsynch) iCommand).isAsynchronous();
OCommandRequest request = new OCommandRequest(database, asynch, iCommand, live);
OCommandResponse response = networkOperation(request, "Error on executing command: " + iCommand);
return response.getResult();
}
public ORemoteQueryResult query(ODatabaseDocumentRemote db, String query, Object[] args) {
OQueryRequest request = new OQueryRequest("sql", query, args, OQueryRequest.QUERY, db.getSerializer(), 100);
OQueryResponse response = networkOperation(request, "Error on executing command: " + query);
ORemoteResultSet rs = new ORemoteResultSet(db, response.getQueryId(), response.getResult(), response.getExecutionPlan(),
response.getQueryStats(), response.isHasNextPage());
return new ORemoteQueryResult(rs, response.isTxChanges());
}
public ORemoteQueryResult query(ODatabaseDocumentRemote db, String query, Map args) {
OQueryRequest request = new OQueryRequest("sql", query, args, OQueryRequest.QUERY, db.getSerializer(), 100);
OQueryResponse response = networkOperation(request, "Error on executing command: " + query);
ORemoteResultSet rs = new ORemoteResultSet(db, response.getQueryId(), response.getResult(), response.getExecutionPlan(),
response.getQueryStats(), response.isHasNextPage());
return new ORemoteQueryResult(rs, response.isTxChanges());
}
public ORemoteQueryResult command(ODatabaseDocumentRemote db, String query, Object[] args) {
OQueryRequest request = new OQueryRequest("sql", query, args, OQueryRequest.COMMAND, db.getSerializer(), 100);
OQueryResponse response = networkOperationNoRetry(request, "Error on executing command: " + query);
ORemoteResultSet rs = new ORemoteResultSet(db, response.getQueryId(), response.getResult(), response.getExecutionPlan(),
response.getQueryStats(), response.isHasNextPage());
return new ORemoteQueryResult(rs, response.isTxChanges());
}
public ORemoteQueryResult command(ODatabaseDocumentRemote db, String query, Map args) {
OQueryRequest request = new OQueryRequest("sql", query, args, OQueryRequest.COMMAND, db.getSerializer(), 100);
OQueryResponse response = networkOperationNoRetry(request, "Error on executing command: " + query);
ORemoteResultSet rs = new ORemoteResultSet(db, response.getQueryId(), response.getResult(), response.getExecutionPlan(),
response.getQueryStats(), response.isHasNextPage());
return new ORemoteQueryResult(rs, response.isTxChanges());
}
public ORemoteQueryResult execute(ODatabaseDocumentRemote db, String language, String query, Object[] args) {
OQueryRequest request = new OQueryRequest(language, query, args, OQueryRequest.EXECUTE, db.getSerializer(), 100);
OQueryResponse response = networkOperationNoRetry(request, "Error on executing command: " + query);
ORemoteResultSet rs = new ORemoteResultSet(db, response.getQueryId(), response.getResult(), response.getExecutionPlan(),
response.getQueryStats(), response.isHasNextPage());
return new ORemoteQueryResult(rs, response.isTxChanges());
}
public ORemoteQueryResult execute(ODatabaseDocumentRemote db, String language, String query, Map args) {
OQueryRequest request = new OQueryRequest(language, query, args, OQueryRequest.EXECUTE, db.getSerializer(), 100);
OQueryResponse response = networkOperationNoRetry(request, "Error on executing command: " + query);
ORemoteResultSet rs = new ORemoteResultSet(db, response.getQueryId(), response.getResult(), response.getExecutionPlan(),
response.getQueryStats(), response.isHasNextPage());
return new ORemoteQueryResult(rs, response.isTxChanges());
}
public void closeQuery(ODatabaseDocumentRemote database, String queryId) {
OCloseQueryRequest request = new OCloseQueryRequest(queryId);
OCloseQueryResponse response = networkOperation(request, "Error closing query: " + queryId);
}
public void fetchNextPage(ODatabaseDocumentRemote database, ORemoteResultSet rs) {
OQueryNextPageRequest request = new OQueryNextPageRequest(rs.getQueryId(), 100);
OQueryResponse response = networkOperation(request, "Error on fetching next page for statment: " + rs.getQueryId());
rs.fetched(response.getResult(), response.isHasNextPage(), response.getExecutionPlan(), response.getQueryStats());
}
public List<ORecordOperation> commit(final OTransaction iTx, final Runnable callback) {
OCommit37Request request;
if (((OTransactionOptimistic) iTx).isChanged()) {
request = new OCommit37Request(iTx.getId(), true, iTx.isUsingLog(), (Iterable<ORecordOperation>) iTx.getAllRecordEntries(),
((OTransactionOptimistic) iTx).getIndexEntries());
} else {
request = new OCommit37Request(iTx.getId(), false, iTx.isUsingLog(), null, null);
}
OCommit37Response response = networkOperationNoRetry(request, "Error on commit");
for (OCommit37Response.OCreatedRecordResponse created : response.getCreated()) {
iTx.updateIdentityAfterCommit(created.getCurrentRid(), created.getCreatedRid());
ORecordOperation rop = iTx.getRecordEntry(created.getCurrentRid());
if (rop != null) {
if (created.getVersion() > rop.getRecord().getVersion() + 1)
// IN CASE OF REMOTE CONFLICT STRATEGY FORCE UNLOAD DUE TO INVALID CONTENT
rop.getRecord().unload();
ORecordInternal.setVersion(rop.getRecord(), created.getVersion());
}
}
for (OCommit37Response.OUpdatedRecordResponse updated : response.getUpdated()) {
ORecordOperation rop = iTx.getRecordEntry(updated.getRid());
if (rop != null) {
if (updated.getVersion() > rop.getRecord().getVersion() + 1)
// IN CASE OF REMOTE CONFLICT STRATEGY FORCE UNLOAD DUE TO INVALID CONTENT
rop.getRecord().unload();
ORecordInternal.setVersion(rop.getRecord(), updated.getVersion());
}
}
updateCollectionsFromChanges(((OTransactionOptimistic) iTx).getDatabase().getSbTreeCollectionManager(),
response.getCollectionChanges());
// SET ALL THE RECORDS AS UNDIRTY
for (ORecordOperation txEntry : iTx.getAllRecordEntries())
ORecordInternal.unsetDirty(txEntry.getRecord());
// UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT.
OTransactionAbstract.updateCacheFromEntries(iTx, iTx.getAllRecordEntries(), true);
return null;
}
public void rollback(OTransaction iTx) {
if (((OTransactionOptimistic) iTx).isAlreadyCleared()) {
ORollbackTransactionRequest request = new ORollbackTransactionRequest(iTx.getId());
ORollbackTransactionResponse response = networkOperation(request, "Error on fetching next page for statment: " + request);
}
}
public int getClusterIdByName(final String iClusterName) {
stateLock.acquireReadLock();
try {
if (iClusterName == null)
return -1;
if (Character.isDigit(iClusterName.charAt(0)))
return Integer.parseInt(iClusterName);
final OCluster cluster = clusterMap.get(iClusterName.toLowerCase(Locale.ENGLISH));
if (cluster == null)
return -1;
return cluster.getId();
} finally {
stateLock.releaseReadLock();
}
}
public int getDefaultClusterId() {
return defaultClusterId;
}
public void setDefaultClusterId(int defaultClusterId) {
this.defaultClusterId = defaultClusterId;
}
public int addCluster(final String iClusterName, final Object... iArguments) {
return addCluster(iClusterName, -1, iArguments);
}
public int addCluster(final String iClusterName, final int iRequestedId, final Object... iParameters) {
OAddClusterRequest request = new OAddClusterRequest(iRequestedId, iClusterName);
OAddClusterResponse response = networkOperationNoRetry(request, "Error on add new cluster");
addNewClusterToConfiguration(response.getClusterId(), iClusterName);
return response.getClusterId();
}
public boolean dropCluster(final int iClusterId, final boolean iTruncate) {
ODropClusterRequest request = new ODropClusterRequest(iClusterId);
ODropClusterResponse response = networkOperationNoRetry(request, "Error on removing of cluster");
if (response.getResult())
removeClusterFromConfiguration(iClusterId);
return response.getResult();
}
public void removeClusterFromConfiguration(int iClusterId) {