+public class Shard extends RaftActor {
+
+ private static final ConfigParams configParams = new ShardConfigParams();
+
+ public static final String DEFAULT_NAME = "default";
+
+ // The state of this Shard
+ private final InMemoryDOMDataStore store;
+
+ private final Map<Object, DOMStoreThreePhaseCommitCohort>
+ modificationToCohort = new HashMap<>();
+
+ private final LoggingAdapter LOG =
+ Logging.getLogger(getContext().system(), this);
+
+ // By default persistent will be true and can be turned off using the system
+ // property shard.persistent
+ private final boolean persistent;
+
+ /// The name of this shard
+ private final ShardIdentifier name;
+
+ private final ShardStats shardMBean;
+
+ private final List<ActorSelection> dataChangeListeners = new ArrayList<>();
+
+ private final DatastoreContext datastoreContext;
+
+ private SchemaContext schemaContext;
+
+ private ActorRef createSnapshotTransaction;
+
+ private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
+
+ private Shard(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
+ DatastoreContext datastoreContext, SchemaContext schemaContext) {
+ super(name.toString(), mapPeerAddresses(peerAddresses), Optional.of(configParams));
+
+ this.name = name;
+ this.datastoreContext = datastoreContext;
+ this.schemaContext = schemaContext;
+
+ String setting = System.getProperty("shard.persistent");
+
+ this.persistent = !"false".equals(setting);
+
+ LOG.info("Shard created : {} persistent : {}", name, persistent);
+
+ store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
+ datastoreContext.getDataStoreProperties());
+
+ if(schemaContext != null) {
+ store.onGlobalContextUpdated(schemaContext);
+ }
+
+ shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
+ datastoreContext.getDataStoreMXBeanType());
+ shardMBean.setDataStoreExecutor(store.getDomStoreExecutor());
+ shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
+
+ if (isMetricsCaptureEnabled()) {
+ getContext().become(new MeteringBehavior(this));
+ }
+ }
+
+ private static Map<String, String> mapPeerAddresses(
+ Map<ShardIdentifier, String> peerAddresses) {
+ Map<String, String> map = new HashMap<>();
+
+ for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
+ .entrySet()) {
+ map.put(entry.getKey().toString(), entry.getValue());
+ }
+
+ return map;
+ }
+
+ public static Props props(final ShardIdentifier name,
+ final Map<ShardIdentifier, String> peerAddresses,
+ DatastoreContext datastoreContext, SchemaContext schemaContext) {
+ Preconditions.checkNotNull(name, "name should not be null");
+ Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
+ Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
+ Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
+
+ return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
+ }
+
+ @Override public void onReceiveRecover(Object message) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("onReceiveRecover: Received message {} from {}",
+ message.getClass().toString(),
+ getSender());
+ }
+
+ if (message instanceof RecoveryFailure){
+ LOG.error(((RecoveryFailure) message).cause(), "Recovery failed because of this cause");
+ } else {
+ super.onReceiveRecover(message);
+ }
+ }
+
+ @Override public void onReceiveCommand(Object message) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("onReceiveCommand: Received message {} from {}",
+ message.getClass().toString(),
+ getSender());
+ }
+
+ if(message.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) {
+ // This must be for install snapshot. Don't want to open this up and trigger
+ // deSerialization
+ self()
+ .tell(new CaptureSnapshotReply(ReadDataReply.getNormalizedNodeByteString(message)),
+ self());
+
+ createSnapshotTransaction = null;
+ // Send a PoisonPill instead of sending close transaction because we do not really need
+ // a response
+ getSender().tell(PoisonPill.getInstance(), self());
+
+ } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)){
+ closeTransactionChain(CloseTransactionChain.fromSerializable(message));
+ } else if (message instanceof RegisterChangeListener) {
+ registerChangeListener((RegisterChangeListener) message);
+ } else if (message instanceof UpdateSchemaContext) {
+ updateSchemaContext((UpdateSchemaContext) message);
+ } else if (message instanceof ForwardedCommitTransaction) {
+ handleForwardedCommit((ForwardedCommitTransaction) message);
+ } else if (message.getClass()
+ .equals(CreateTransaction.SERIALIZABLE_CLASS)) {
+ if (isLeader()) {
+ createTransaction(CreateTransaction.fromSerializable(message));
+ } else if (getLeader() != null) {
+ getLeader().forward(message, getContext());
+ } else {
+ getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(
+ "Could not find leader so transaction cannot be created")), getSelf());
+ }
+ } else if (message instanceof PeerAddressResolved) {
+ PeerAddressResolved resolved = (PeerAddressResolved) message;
+ setPeerAddress(resolved.getPeerId().toString(),
+ resolved.getPeerAddress());
+ } else {
+ super.onReceiveCommand(message);
+ }
+ }
+
+ private void closeTransactionChain(CloseTransactionChain closeTransactionChain) {
+ DOMStoreTransactionChain chain =
+ transactionChains.remove(closeTransactionChain.getTransactionChainId());
+
+ if(chain != null) {
+ chain.close();
+ }
+ }
+
+ private ActorRef createTypedTransactionActor(
+ int transactionType,
+ ShardTransactionIdentifier transactionId,
+ String transactionChainId ) {
+
+ DOMStoreTransactionFactory factory = store;
+
+ if(!transactionChainId.isEmpty()) {
+ factory = transactionChains.get(transactionChainId);
+ if(factory == null){
+ DOMStoreTransactionChain transactionChain = store.createTransactionChain();
+ transactionChains.put(transactionChainId, transactionChain);
+ factory = transactionChain;
+ }
+ }
+
+ if(this.schemaContext == null){
+ throw new NullPointerException("schemaContext should not be null");
+ }
+
+ if (transactionType
+ == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
+
+ shardMBean.incrementReadOnlyTransactionCount();
+
+ return getContext().actorOf(
+ ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
+ schemaContext,datastoreContext, shardMBean), transactionId.toString());
+
+ } else if (transactionType
+ == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
+
+ shardMBean.incrementReadWriteTransactionCount();
+
+ return getContext().actorOf(
+ ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
+ schemaContext, datastoreContext, shardMBean), transactionId.toString());
+
+
+ } else if (transactionType
+ == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
+
+ shardMBean.incrementWriteOnlyTransactionCount();
+
+ return getContext().actorOf(
+ ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
+ schemaContext, datastoreContext, shardMBean), transactionId.toString());
+ } else {
+ throw new IllegalArgumentException(
+ "Shard="+name + ":CreateTransaction message has unidentified transaction type="
+ + transactionType);
+ }
+ }
+
+ private void createTransaction(CreateTransaction createTransaction) {
+ createTransaction(createTransaction.getTransactionType(),
+ createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
+ }
+
+ private ActorRef createTransaction(int transactionType, String remoteTransactionId, String transactionChainId) {
+
+ ShardTransactionIdentifier transactionId =
+ ShardTransactionIdentifier.builder()
+ .remoteTransactionId(remoteTransactionId)
+ .build();
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("Creating transaction : {} ", transactionId);
+ }
+ ActorRef transactionActor =
+ createTypedTransactionActor(transactionType, transactionId, transactionChainId);
+
+ getSender()
+ .tell(new CreateTransactionReply(
+ Serialization.serializedActorPath(transactionActor),
+ remoteTransactionId).toSerializable(),
+ getSelf());
+
+ return transactionActor;
+ }
+
+ private void syncCommitTransaction(DOMStoreWriteTransaction transaction)
+ throws ExecutionException, InterruptedException {
+ DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
+ commitCohort.preCommit().get();
+ commitCohort.commit().get();
+ }
+
+
+ private void commit(final ActorRef sender, Object serialized) {
+ Modification modification = MutableCompositeModification
+ .fromSerializable(serialized, schemaContext);
+ DOMStoreThreePhaseCommitCohort cohort =
+ modificationToCohort.remove(serialized);
+ if (cohort == null) {
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug(
+ "Could not find cohort for modification : {}. Writing modification using a new transaction",
+ modification);
+ }
+
+ DOMStoreWriteTransaction transaction =
+ store.newWriteOnlyTransaction();
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("Created new transaction {}", transaction.getIdentifier().toString());
+ }