✨ 添加新特性。 支付收单模块

This commit is contained in:
pigxcloud committed 2019-06-03 07:41:34 +08:00
1 parent 2ee8021b5e
commit 075c31a508
139 files changed
+4703 -4864

No files matched your search

@@ -1,191 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import io.seata.core.exception.TransactionException;
import io.seata.core.exception.TransactionExceptionCode;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.GlobalStatus;
import io.seata.server.store.SessionStorable;
import io.seata.server.store.TransactionStoreManager;
import io.seata.server.store.TransactionStoreManager.LogOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* The type Abstract session manager.
*
* @author sharajava
*/
public abstract class AbstractSessionManager implements SessionManager, SessionLifecycleListener {
/**
* The constant LOGGER.
*/
protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractSessionManager.class);
/**
* The Session map.
*/
protected Map<Long, GlobalSession> sessionMap = new ConcurrentHashMap<>();
/**
* The Transaction store manager.
*/
protected TransactionStoreManager transactionStoreManager;
/**
* The Name.
*/
protected String name;
/**
* Instantiates a new Abstract session manager.
*
* @param name the name
*/
public AbstractSessionManager(String name) {
this.name = name;
}
@Override
public void addGlobalSession(GlobalSession session) throws TransactionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("MANAGER[" + name + "] SESSION[" + session + "] " + LogOperation.GLOBAL_ADD);
}
writeSession(LogOperation.GLOBAL_ADD, session);
sessionMap.put(session.getTransactionId(), session);
}
@Override
public GlobalSession findGlobalSession(Long transactionId) {
return sessionMap.get(transactionId);
}
@Override
public void updateGlobalSessionStatus(GlobalSession session, GlobalStatus status) throws TransactionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("MANAGER[" + name + "] SESSION[" + session + "] " + LogOperation.GLOBAL_UPDATE);
}
writeSession(LogOperation.GLOBAL_UPDATE, session);
}
@Override
public void removeGlobalSession(GlobalSession session) throws TransactionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("MANAGER[" + name + "] SESSION[" + session + "] " + LogOperation.GLOBAL_REMOVE);
}
writeSession(LogOperation.GLOBAL_REMOVE, session);
sessionMap.remove(session.getTransactionId());
}
@Override
public void addBranchSession(GlobalSession session, BranchSession branchSession) throws TransactionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("MANAGER[" + name + "] SESSION[" + branchSession + "] " + LogOperation.BRANCH_ADD);
}
writeSession(LogOperation.BRANCH_ADD, branchSession);
}
@Override
public void updateBranchSessionStatus(BranchSession branchSession, BranchStatus status)
throws TransactionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("MANAGER[" + name + "] SESSION[" + branchSession + "] " + LogOperation.GLOBAL_ADD);
}
writeSession(LogOperation.BRANCH_UPDATE, branchSession);
}
@Override
public void removeBranchSession(GlobalSession globalSession, BranchSession branchSession)
throws TransactionException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("MANAGER[" + name + "] SESSION[" + branchSession + "] " + LogOperation.GLOBAL_ADD);
}
writeSession(LogOperation.BRANCH_REMOVE, branchSession);
}
@Override
public Collection<GlobalSession> allSessions() {
return sessionMap.values();
}
@Override
public List<GlobalSession> findGlobalSessions(SessionCondition condition) {
List<GlobalSession> found = new ArrayList<>();
for (GlobalSession globalSession : sessionMap.values()) {
if (System.currentTimeMillis() - globalSession.getBeginTime() > condition.getOverTimeAliveMills()) {
found.add(globalSession);
}
}
return found;
}
@Override
public void onBegin(GlobalSession globalSession) throws TransactionException {
addGlobalSession(globalSession);
}
@Override
public void onStatusChange(GlobalSession globalSession, GlobalStatus status) throws TransactionException {
updateGlobalSessionStatus(globalSession, status);
}
@Override
public void onBranchStatusChange(GlobalSession globalSession, BranchSession branchSession, BranchStatus status)
throws TransactionException {
updateBranchSessionStatus(branchSession, status);
}
@Override
public void onAddBranch(GlobalSession globalSession, BranchSession branchSession) throws TransactionException {
addBranchSession(globalSession, branchSession);
}
@Override
public void onRemoveBranch(GlobalSession globalSession, BranchSession branchSession) throws TransactionException {
removeBranchSession(globalSession, branchSession);
}
@Override
public void onClose(GlobalSession globalSession) throws TransactionException {
globalSession.setActive(false);
}
@Override
public void onEnd(GlobalSession globalSession) throws TransactionException {
removeGlobalSession(globalSession);
}
private void writeSession(LogOperation logOperation, SessionStorable sessionStorable) throws TransactionException{
if (!transactionStoreManager.writeSession(logOperation, sessionStorable)) {
throw new TransactionException(TransactionExceptionCode.FailedWriteSession);
}
}
}
@@ -1,395 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import io.seata.common.util.CompressUtil;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.BranchType;
import io.seata.server.lock.LockManagerFactory;
import io.seata.server.store.SessionStorable;
import io.seata.server.store.StoreConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The type Branch session.
*
* @author sharajava
*/
public class BranchSession implements Lockable, Comparable<BranchSession>, SessionStorable {
private static final Logger LOGGER = LoggerFactory.getLogger(BranchSession.class);
private static final int MAX_BRANCH_SESSION_SIZE = StoreConfig.getMaxBranchSessionSize();
private static ThreadLocal<ByteBuffer> byteBufferThreadLocal = ThreadLocal.withInitial(() -> ByteBuffer.allocate(
MAX_BRANCH_SESSION_SIZE));
private long transactionId;
private long branchId;
private String resourceGroupId;
private String resourceId;
private String lockKey;
private BranchType branchType;
private BranchStatus status = BranchStatus.Unknown;
private String clientId;
private String applicationData;
private ConcurrentHashMap<Map<String, Long>, Set<String>> lockHolder
= new ConcurrentHashMap<Map<String, Long>, Set<String>>();
/**
* Gets application data.
*
* @return the application data
*/
public String getApplicationData() {
return applicationData;
}
/**
* Sets application data.
*
* @param applicationData the application data
*/
public void setApplicationData(String applicationData) {
this.applicationData = applicationData;
}
/**
* Gets resource group id.
*
* @return the resource group id
*/
public String getResourceGroupId() {
return resourceGroupId;
}
/**
* Sets resource group id.
*
* @param resourceGroupId the resource group id
*/
public void setResourceGroupId(String resourceGroupId) {
this.resourceGroupId = resourceGroupId;
}
/**
* Gets client id.
*
* @return the client id
*/
public String getClientId() {
return clientId;
}
/**
* Sets client id.
*
* @param clientId the client id
*/
public void setClientId(String clientId) {
this.clientId = clientId;
}
/**
* Gets resource id.
*
* @return the resource id
*/
public String getResourceId() {
return resourceId;
}
/**
* Sets resource id.
*
* @param resourceId the resource id
*/
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
/**
* Gets lock key.
*
* @return the lock key
*/
public String getLockKey() {
return lockKey;
}
/**
* Sets lock key.
*
* @param lockKey the lock key
*/
public void setLockKey(String lockKey) {
this.lockKey = lockKey;
}
/**
* Gets branch type.
*
* @return the branch type
*/
public BranchType getBranchType() {
return branchType;
}
/**
* Sets branch type.
*
* @param branchType the branch type
*/
public void setBranchType(BranchType branchType) {
this.branchType = branchType;
}
/**
* Gets status.
*
* @return the status
*/
public BranchStatus getStatus() {
return status;
}
/**
* Sets status.
*
* @param status the status
*/
void setStatus(BranchStatus status) {
this.status = status;
}
/**
* Gets transaction id.
*
* @return the transaction id
*/
public long getTransactionId() {
return transactionId;
}
/**
* Sets transaction id.
*
* @param transactionId the transaction id
*/
public void setTransactionId(long transactionId) {
this.transactionId = transactionId;
}
/**
* Gets branch id.
*
* @return the branch id
*/
public long getBranchId() {
return branchId;
}
/**
* Sets branch id.
*
* @param branchId the branch id
*/
public void setBranchId(long branchId) {
this.branchId = branchId;
}
@Override
public String toString() {
return "BR:" + branchId + "/" + transactionId;
}
@Override
public int compareTo(BranchSession o) {
return this.branchId < o.branchId ? -1 : (this.branchId > o.branchId ? 1 : 0);
}
/**
* Gets lock holder.
*
* @return the lock holder
*/
public ConcurrentHashMap<Map<String, Long>, Set<String>> getLockHolder() {
return lockHolder;
}
@Override
public boolean lock() throws TransactionException {
return LockManagerFactory.get().acquireLock(this);
}
@Override
public boolean unlock() throws TransactionException {
return LockManagerFactory.get().releaseLock(this);
}
@Override
public byte[] encode() {
byte[] resourceIdBytes = resourceId != null ? resourceId.getBytes() : null;
byte[] lockKeyBytes = lockKey != null ? lockKey.getBytes() : null;
byte[] clientIdBytes = clientId != null ? clientId.getBytes() : null;
byte[] applicationDataBytes = applicationData != null ? applicationData.getBytes() : null;
int size = calBranchSessionSize(resourceIdBytes, lockKeyBytes, clientIdBytes, applicationDataBytes);
if (size > MAX_BRANCH_SESSION_SIZE) {
if (lockKeyBytes == null) {
throw new RuntimeException("branch session size exceeded, size : " + size + " maxBranchSessionSize : "
+ MAX_BRANCH_SESSION_SIZE);
}
// try compress lockkey
try {
size -= lockKeyBytes.length;
lockKeyBytes = CompressUtil.compress(lockKeyBytes);
} catch (IOException e) {
LOGGER.error("compress lockKey error", e);
} finally {
size += lockKeyBytes.length;
}
if (size > MAX_BRANCH_SESSION_SIZE) {
throw new RuntimeException(
"compress branch session size exceeded, compressSize : " + size + " maxBranchSessionSize : "
+ MAX_BRANCH_SESSION_SIZE);
}
}
ByteBuffer byteBuffer = byteBufferThreadLocal.get();
//recycle
byteBuffer.clear();
byteBuffer.putLong(transactionId);
byteBuffer.putLong(branchId);
if (null != resourceIdBytes) {
byteBuffer.putInt(resourceIdBytes.length);
byteBuffer.put(resourceIdBytes);
} else {
byteBuffer.putInt(0);
}
if (null != lockKeyBytes) {
byteBuffer.putInt(lockKeyBytes.length);
byteBuffer.put(lockKeyBytes);
} else {
byteBuffer.putInt(0);
}
if (null != clientIdBytes) {
byteBuffer.putShort((short)clientIdBytes.length);
byteBuffer.put(clientIdBytes);
} else {
byteBuffer.putShort((short)0);
}
if (null != applicationDataBytes) {
byteBuffer.putInt(applicationDataBytes.length);
byteBuffer.put(applicationDataBytes);
} else {
byteBuffer.putInt(0);
}
byteBuffer.put((byte)status.getCode());
byteBuffer.flip();
byte[] result = new byte[byteBuffer.limit()];
byteBuffer.get(result);
return result;
}
private int calBranchSessionSize(byte[] resourceIdBytes, byte[] lockKeyBytes, byte[] clientIdBytes,
byte[] applicationDataBytes) {
final int size = 8 // trascationId
+ 8 // branchId
+ 4 // resourceIdBytes.length
+ 4 // lockKeyBytes.length
+ 2 // clientIdBytes.length
+ 4 // applicationDataBytes.length
+ 1 // statusCode
+ (resourceIdBytes == null ? 0 : resourceIdBytes.length)
+ (lockKeyBytes == null ? 0 : lockKeyBytes.length)
+ (clientIdBytes == null ? 0 : clientIdBytes.length)
+ (applicationDataBytes == null ? 0 : applicationDataBytes.length);
return size;
}
@Override
public void decode(byte[] a) {
ByteBuffer byteBuffer = ByteBuffer.wrap(a);
this.transactionId = byteBuffer.getLong();
this.branchId = byteBuffer.getLong();
int resourceLen = byteBuffer.getInt();
if (resourceLen > 0) {
byte[] byResource = new byte[resourceLen];
byteBuffer.get(byResource);
this.resourceId = new String(byResource);
}
int lockKeyLen = byteBuffer.getInt();
if (lockKeyLen > 0) {
byte[] byLockKey = new byte[lockKeyLen];
byteBuffer.get(byLockKey);
if (CompressUtil.isCompressData(byLockKey)) {
try {
this.lockKey = new String(CompressUtil.uncompress(byLockKey));
} catch (IOException e) {
throw new RuntimeException("uncompress lockKey error", e);
}
} else {
this.lockKey = new String(byLockKey);
}
}
short clientIdLen = byteBuffer.getShort();
if (clientIdLen > 0) {
byte[] byClientId = new byte[clientIdLen];
byteBuffer.get(byClientId);
this.clientId = new String(byClientId);
}
int applicationDataLen = byteBuffer.getInt();
if (applicationDataLen > 0) {
byte[] byApplicationData = new byte[applicationDataLen];
byteBuffer.get(byApplicationData);
this.applicationData = new String(byApplicationData);
}
this.status = BranchStatus.get(byteBuffer.get());
}
}
@@ -1,65 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import java.util.List;
import io.seata.server.store.SessionStorable;
import io.seata.server.store.TransactionStoreManager;
import io.seata.server.store.TransactionWriteStore;
/**
* The type Default session manager.
*
* @author sharajava
*/
public class DefaultSessionManager extends AbstractSessionManager {
/**
* Instantiates a new Default session manager.
*
* @param name the name
*/
public DefaultSessionManager(String name) {
super(name);
transactionStoreManager = new TransactionStoreManager() {
@Override
public boolean writeSession(LogOperation logOperation, SessionStorable session) {
return true;
}
@Override
public void shutdown() {
}
@Override
public List<TransactionWriteStore> readWriteStoreFromFile(int readSize, boolean isHistory) {
return null;
}
@Override
public boolean hasRemaining(boolean isHistory) {
return false;
}
};
}
@Override
public void destroy() {
transactionStoreManager.shutdown();
}
}
@@ -1,232 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import io.seata.common.exception.ShouldNeverHappenException;
import io.seata.config.ConfigurationFactory;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.model.GlobalStatus;
import io.seata.server.UUIDGenerator;
import io.seata.server.store.FileTransactionStoreManager;
import io.seata.server.store.SessionStorable;
import io.seata.server.store.TransactionStoreManager;
import io.seata.server.store.TransactionWriteStore;
/**
* The type File based session manager.
*
* @author jimin.jm @alibaba-inc.com
*/
public class FileBasedSessionManager extends AbstractSessionManager implements Reloadable {
private static final int READ_SIZE = ConfigurationFactory.getInstance().getInt(
ConfigurationKeys.SERVICE_SESSION_RELOAD_READ_SIZE, 100);
/**
* Instantiates a new File based session manager.
*
* @param name the name
* @param sessionStoreFilePath the session store file path
* @throws IOException the io exception
*/
public FileBasedSessionManager(String name, String sessionStoreFilePath) throws IOException {
super(name);
transactionStoreManager = new FileTransactionStoreManager(sessionStoreFilePath + File.separator + name, this);
}
@Override
public void reload() {
restoreSessions();
washSessions();
}
private void restoreSessions() {
Map<Long, BranchSession> unhandledBranchBuffer = new HashMap<>();
restoreSessions(true, unhandledBranchBuffer);
restoreSessions(false, unhandledBranchBuffer);
if (!unhandledBranchBuffer.isEmpty()) {
unhandledBranchBuffer.values().forEach(branchSession -> {
long tid = branchSession.getTransactionId();
long bid = branchSession.getBranchId();
GlobalSession found = sessionMap.get(tid);
if (found == null) {
// Ignore
if (LOGGER.isInfoEnabled()) {
LOGGER.info("GlobalSession Does Not Exists For BranchSession [" + bid + "/" + tid + "]");
}
} else {
BranchSession existingBranch = found.getBranch(branchSession.getBranchId());
if (existingBranch == null) {
found.add(branchSession);
} else {
existingBranch.setStatus(branchSession.getStatus());
}
}
});
}
}
private void washSessions() {
if (sessionMap.size() > 0) {
Iterator<Map.Entry<Long, GlobalSession>> iterator = sessionMap.entrySet().iterator();
while (iterator.hasNext()) {
GlobalSession globalSession = iterator.next().getValue();
GlobalStatus globalStatus = globalSession.getStatus();
switch (globalStatus) {
case UnKnown:
case Committed:
case CommitFailed:
case Rollbacked:
case RollbackFailed:
case TimeoutRollbacked:
case TimeoutRollbackFailed:
case Finished:
// Remove all sessions finished
iterator.remove();
break;
default:
break;
}
}
}
}
private void restoreSessions(boolean isHistory, Map<Long, BranchSession> unhandledBranchBuffer) {
while (transactionStoreManager.hasRemaining(isHistory)) {
List<TransactionWriteStore> stores = transactionStoreManager.readWriteStoreFromFile(READ_SIZE, isHistory);
restore(stores, unhandledBranchBuffer);
}
}
private void restore(List<TransactionWriteStore> stores, Map<Long, BranchSession> unhandledBranchSessions) {
long maxRecoverId = UUIDGenerator.getCurrentUUID();
for (TransactionWriteStore store : stores) {
TransactionStoreManager.LogOperation logOperation = store.getOperate();
SessionStorable sessionStorable = store.getSessionRequest();
maxRecoverId = getMaxId(maxRecoverId, sessionStorable);
switch (logOperation) {
case GLOBAL_ADD:
case GLOBAL_UPDATE: {
GlobalSession globalSession = (GlobalSession)sessionStorable;
long tid = globalSession.getTransactionId();
GlobalSession foundGlobalSession = sessionMap.get(tid);
if (foundGlobalSession == null) {
sessionMap.put(globalSession.getTransactionId(), globalSession);
} else {
foundGlobalSession.setStatus(globalSession.getStatus());
}
break;
}
case GLOBAL_REMOVE: {
GlobalSession globalSession = (GlobalSession)sessionStorable;
long tid = globalSession.getTransactionId();
if (sessionMap.remove(tid) == null) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("GlobalSession To Be Removed Does Not Exists [" + tid + "]");
}
}
break;
}
case BRANCH_ADD:
case BRANCH_UPDATE: {
BranchSession branchSession = (BranchSession)sessionStorable;
long tid = branchSession.getTransactionId();
GlobalSession foundGlobalSession = sessionMap.get(tid);
if (foundGlobalSession == null) {
unhandledBranchSessions.put(branchSession.getBranchId(), branchSession);
} else {
BranchSession existingBranch = foundGlobalSession.getBranch(branchSession.getBranchId());
if (existingBranch == null) {
foundGlobalSession.add(branchSession);
} else {
existingBranch.setStatus(branchSession.getStatus());
}
}
break;
}
case BRANCH_REMOVE: {
BranchSession branchSession = (BranchSession)sessionStorable;
long tid = branchSession.getTransactionId();
long bid = branchSession.getBranchId();
GlobalSession found = sessionMap.get(tid);
if (found == null) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info(
"GlobalSession To Be Updated (Remove Branch) Does Not Exists [" + bid + "/" + tid
+ "]");
}
} else {
BranchSession theBranch = found.getBranch(bid);
if (theBranch == null) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("BranchSession To Be Updated Does Not Exists [" + bid + "/" + tid + "]");
}
} else {
found.remove(theBranch);
}
}
break;
}
default:
throw new ShouldNeverHappenException("Unknown Operation: " + logOperation);
}
}
setMaxId(maxRecoverId);
}
private long getMaxId(long maxRecoverId, SessionStorable sessionStorable) {
long currentId = 0;
if (sessionStorable instanceof GlobalSession) {
currentId = ((GlobalSession)sessionStorable).getTransactionId();
} else if (sessionStorable instanceof BranchSession) {
currentId = ((BranchSession)sessionStorable).getBranchId();
}
return maxRecoverId > currentId ? maxRecoverId : currentId;
}
private void setMaxId(long maxRecoverId) {
long currentId;
// will be recover multi-thread later
while ((currentId = UUIDGenerator.getCurrentUUID()) < maxRecoverId) {
if (UUIDGenerator.setUUID(currentId, maxRecoverId)) {
break;
}
}
}
private void restore(TransactionWriteStore store) {
}
@Override
public void destroy() {
transactionStoreManager.shutdown();
}
}
@@ -1,541 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import io.seata.core.exception.TransactionException;
import io.seata.core.exception.TransactionExceptionCode;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.BranchType;
import io.seata.core.model.GlobalStatus;
import io.seata.server.UUIDGenerator;
import io.seata.server.store.SessionStorable;
import io.seata.server.store.StoreConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* The type Global session.
*
* @author sharajava
*/
public class GlobalSession implements SessionLifecycle, SessionStorable {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalSession.class);
private static final int MAX_GLOBAL_SESSION_SIZE = StoreConfig.getMaxGlobalSessionSize();
private static ThreadLocal<ByteBuffer> byteBufferThreadLocal = ThreadLocal.withInitial(() -> ByteBuffer.allocate(
MAX_GLOBAL_SESSION_SIZE));
private long transactionId;
private volatile GlobalStatus status;
private String applicationId;
private String transactionServiceGroup;
private String transactionName;
private int timeout;
private long beginTime;
private boolean active;
private ArrayList<BranchSession> branchSessions = new ArrayList<>();
private GlobalSessionLock globalSessionLock = new GlobalSessionLock();
/**
* Add boolean.
*
* @param branchSession the branch session
* @return the boolean
*/
public boolean add(BranchSession branchSession) {
return branchSessions.add(branchSession);
}
/**
* Remove boolean.
*
* @param branchSession the branch session
* @return the boolean
*/
public boolean remove(BranchSession branchSession) {
return branchSessions.remove(branchSession);
}
private ArrayList<SessionLifecycleListener> lifecycleListeners = new ArrayList<>();
/**
* Can be committed async boolean.
*
* @return the boolean
*/
public boolean canBeCommittedAsync() {
for (BranchSession branchSession : branchSessions) {
if (branchSession.getBranchType() == BranchType.TCC) {
return false;
}
}
return true;
}
/**
* Is timeout boolean.
*
* @return the boolean
*/
public boolean isTimeout() {
return (System.currentTimeMillis() - beginTime) > timeout;
}
@Override
public void begin() throws TransactionException {
this.status = GlobalStatus.Begin;
this.beginTime = System.currentTimeMillis();
this.active = true;
for (SessionLifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onBegin(this);
}
}
@Override
public void changeStatus(GlobalStatus status) throws TransactionException {
this.status = status;
for (SessionLifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onStatusChange(this, status);
}
}
@Override
public void changeBranchStatus(BranchSession branchSession, BranchStatus status)
throws TransactionException {
branchSession.setStatus(status);
for (SessionLifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onBranchStatusChange(this, branchSession, status);
}
}
@Override
public boolean isActive() {
return active;
}
@Override
public void close() throws TransactionException {
if (active) {
for (SessionLifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onClose(this);
}
}
}
@Override
public void end() throws TransactionException {
// Clean locks first
clean();
for (SessionLifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onEnd(this);
}
}
private void clean() throws TransactionException {
for (BranchSession branchSession : branchSessions) {
branchSession.unlock();
}
}
/**
* Close and clean.
*
* @throws TransactionException the transaction exception
*/
public void closeAndClean() throws TransactionException {
close();
clean();
}
/**
* Add session lifecycle listener.
*
* @param sessionLifecycleListener the session lifecycle listener
*/
public void addSessionLifecycleListener(SessionLifecycleListener sessionLifecycleListener) {
lifecycleListeners.add(sessionLifecycleListener);
}
/**
* Remove session lifecycle listener.
*
* @param sessionLifecycleListener the session lifecycle listener
*/
public void removeSessionLifecycleListener(SessionLifecycleListener sessionLifecycleListener) {
lifecycleListeners.remove(sessionLifecycleListener);
}
@Override
public void addBranch(BranchSession branchSession) throws TransactionException {
for (SessionLifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onAddBranch(this, branchSession);
}
branchSession.setStatus(BranchStatus.Registered);
add(branchSession);
}
@Override
public void removeBranch(BranchSession branchSession) throws TransactionException {
for (SessionLifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onRemoveBranch(this, branchSession);
}
branchSession.unlock();
remove(branchSession);
}
/**
* Gets branch.
*
* @param branchId the branch id
* @return the branch
*/
public BranchSession getBranch(long branchId) {
synchronized (branchSessions) {
for (BranchSession branchSession : branchSessions) {
if (branchSession.getBranchId() == branchId) {
return branchSession;
}
}
return null;
}
}
/**
* Gets sorted branches.
*
* @return the sorted branches
*/
public ArrayList<BranchSession> getSortedBranches() {
ArrayList<BranchSession> sorted = new ArrayList();
sorted.addAll(branchSessions);
return sorted;
}
/**
* Gets reverse sorted branches.
*
* @return the reverse sorted branches
*/
public ArrayList<BranchSession> getReverseSortedBranches() {
ArrayList<BranchSession> reversed = new ArrayList();
reversed.addAll(branchSessions);
Collections.reverse(reversed);
return reversed;
}
/**
* Instantiates a new Global session.
*/
public GlobalSession() {}
/**
* Instantiates a new Global session.
*
* @param applicationId the application id
* @param transactionServiceGroup the transaction service group
* @param transactionName the transaction name
* @param timeout the timeout
*/
public GlobalSession(String applicationId, String transactionServiceGroup, String transactionName, int timeout) {
this.transactionId = UUIDGenerator.generateUUID();
this.status = GlobalStatus.Begin;
this.applicationId = applicationId;
this.transactionServiceGroup = transactionServiceGroup;
this.transactionName = transactionName;
this.timeout = timeout;
}
/**
* Gets transaction id.
*
* @return the transaction id
*/
public long getTransactionId() {
return transactionId;
}
/**
* Gets status.
*
* @return the status
*/
public GlobalStatus getStatus() {
return status;
}
/**
* Sets status.
*
* @param status the status
*/
void setStatus(GlobalStatus status) {
this.status = status;
}
/**
* Gets application id.
*
* @return the application id
*/
public String getApplicationId() {
return applicationId;
}
/**
* Gets transaction service group.
*
* @return the transaction service group
*/
public String getTransactionServiceGroup() {
return transactionServiceGroup;
}
/**
* Gets transaction name.
*
* @return the transaction name
*/
public String getTransactionName() {
return transactionName;
}
/**
* Gets timeout.
*
* @return the timeout
*/
public int getTimeout() {
return timeout;
}
/**
* Gets begin time.
*
* @return the begin time
*/
public long getBeginTime() {
return beginTime;
}
/**
* Create global session global session.
*
* @param applicationId the application id
* @param txServiceGroup the tx service group
* @param txName the tx name
* @param timeout the timeout
* @return the global session
*/
public static GlobalSession createGlobalSession(String applicationId, String txServiceGroup, String txName,
int timeout) {
GlobalSession session = new GlobalSession(applicationId, txServiceGroup, txName, timeout);
return session;
}
/**
* Sets active.
*
* @param active the active
*/
public void setActive(boolean active) {
this.active = active;
}
@Override
public byte[] encode() {
byte[] byApplicationIdBytes = applicationId != null ? applicationId.getBytes() : null;
byte[] byServiceGroupBytes = transactionServiceGroup != null ? transactionServiceGroup.getBytes() : null;
byte[] byTxNameBytes = transactionName != null ? transactionName.getBytes() : null;
int size = calGlobalSessionSize(byApplicationIdBytes, byServiceGroupBytes, byTxNameBytes);
if (size > MAX_GLOBAL_SESSION_SIZE) {
throw new RuntimeException("global session size exceeded, size : " + size + " maxBranchSessionSize : " +
MAX_GLOBAL_SESSION_SIZE);
}
ByteBuffer byteBuffer = byteBufferThreadLocal.get();
//recycle
byteBuffer.clear();
byteBuffer.putLong(transactionId);
byteBuffer.putInt(timeout);
if (null != byApplicationIdBytes) {
byteBuffer.putShort((short)byApplicationIdBytes.length);
byteBuffer.put(byApplicationIdBytes);
} else {
byteBuffer.putShort((short)0);
}
if (null != byServiceGroupBytes) {
byteBuffer.putShort((short)byServiceGroupBytes.length);
byteBuffer.put(byServiceGroupBytes);
} else {
byteBuffer.putShort((short)0);
}
if (null != byTxNameBytes) {
byteBuffer.putShort((short)byTxNameBytes.length);
byteBuffer.put(byTxNameBytes);
} else {
byteBuffer.putShort((short)0);
}
byteBuffer.putLong(beginTime);
byteBuffer.put((byte)status.getCode());
byteBuffer.flip();
byte[] result = new byte[byteBuffer.limit()];
byteBuffer.get(result);
return result;
}
private int calGlobalSessionSize(byte[] byApplicationIdBytes, byte[] byServiceGroupBytes, byte[] byTxNameBytes) {
final int size = 8 // trascationId
+ 4 // timeout
+ 2 // byApplicationIdBytes.length
+ 2 // byServiceGroupBytes.length
+ 2 // byTxNameBytes.length
+ 8 // beginTime
+ 1 // statusCode
+ (byApplicationIdBytes == null ? 0 : byApplicationIdBytes.length)
+ (byServiceGroupBytes == null ? 0 : byServiceGroupBytes.length)
+ (byTxNameBytes == null ? 0 : byTxNameBytes.length);
return size;
}
@Override
public void decode(byte[] a) {
ByteBuffer byteBuffer = ByteBuffer.wrap(a);
this.transactionId = byteBuffer.getLong();
this.timeout = byteBuffer.getInt();
short applicationIdLen = byteBuffer.getShort();
if (applicationIdLen > 0) {
byte[] byApplicationId = new byte[applicationIdLen];
byteBuffer.get(byApplicationId);
this.applicationId = new String(byApplicationId);
}
short serviceGroupLen = byteBuffer.getShort();
if (serviceGroupLen > 0) {
byte[] byServiceGroup = new byte[serviceGroupLen];
byteBuffer.get(byServiceGroup);
this.transactionServiceGroup = new String(byServiceGroup);
}
short txNameLen = byteBuffer.getShort();
if (txNameLen > 0) {
byte[] byTxName = new byte[txNameLen];
byteBuffer.get(byTxName);
this.transactionName = new String(byTxName);
}
this.beginTime = byteBuffer.getLong();
this.status = GlobalStatus.get(byteBuffer.get());
}
/**
* Has branch boolean.
*
* @return the boolean
*/
public boolean hasBranch() {
return branchSessions.size() > 0;
}
public void lock() throws TransactionException {
globalSessionLock.lock();
}
public void unlock(){
globalSessionLock.unlock();
}
public void lockAndExcute(LockRunnable excuteRunnable) throws TransactionException{
this.lock();
try {
excuteRunnable.run();
}finally {
this.unlock();
}
}
public <T> T lockAndExcute(LockCallable<T> lockCallable) throws TransactionException{
this.lock();
try {
return lockCallable.call();
}finally {
this.unlock();
}
}
private class GlobalSessionLock {
private Lock globalSessionLock = new ReentrantLock();
private static final int GLOBAL_SESSOION_LOCK_TIME_OUT_MILLS = 2 * 1000;
public void lock() throws TransactionException {
try {
if (globalSessionLock.tryLock(GLOBAL_SESSOION_LOCK_TIME_OUT_MILLS, TimeUnit.MILLISECONDS)){
return;
}
} catch (InterruptedException e) {
LOGGER.error("Interrupted error", e);
}
throw new TransactionException(TransactionExceptionCode.FailedLockGlobalTranscation);
}
public void unlock() {
globalSessionLock.unlock();
}
}
@FunctionalInterface
public interface LockRunnable {
void run() throws TransactionException;
}
@FunctionalInterface
public interface LockCallable<V> {
V call() throws TransactionException;
}
}
@@ -1,42 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import io.seata.core.exception.TransactionException;
/**
* The interface Lockable.
*
* @author sharajava
*/
public interface Lockable {
/**
* Lock boolean.
*
* @return the boolean
* @throws TransactionException the transaction exception
*/
boolean lock() throws TransactionException;
/**
* Unlock boolean.
*
* @return the boolean
* @throws TransactionException the transaction exception
*/
boolean unlock() throws TransactionException;
}
@@ -1,29 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
/**
* Service contains states which can be reloaded.
*
* @author sharajava
*/
public interface Reloadable {
/**
* Reload states.
*/
void reload();
}
@@ -1,55 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
/**
* The type Session condition.
*
* @author jimin.jm @alibaba-inc.com
* @date 2018 /12/13
*/
public class SessionCondition {
private long overTimeAliveMills;
/**
* Instantiates a new Session condition.
*
* @param overTimeAliveMills the over time alive mills
*/
public SessionCondition( long overTimeAliveMills) {
this.overTimeAliveMills = overTimeAliveMills;
}
/**
* Gets over time alive mills.
*
* @return the over time alive mills
*/
public long getOverTimeAliveMills() {
return overTimeAliveMills;
}
/**
* Sets over time alive mills.
*
* @param overTimeAliveMills the over time alive mills
*/
public void setOverTimeAliveMills(long overTimeAliveMills) {
this.overTimeAliveMills = overTimeAliveMills;
}
}
@@ -1,121 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.BranchType;
import io.seata.core.model.GlobalStatus;
import io.seata.server.UUIDGenerator;
/**
* The type Session helper.
*
* @author sharajava
*/
public class SessionHelper {
private SessionHelper() {}
public static BranchSession newBranchByGlobal(GlobalSession globalSession, BranchType branchType, String resourceId, String lockKeys, String clientId) {
return newBranchByGlobal(globalSession, branchType, resourceId, null, lockKeys, clientId);
}
/**
* New branch by global branch session.
*
* @param globalSession the global session
* @param branchType the branch type
* @param resourceId the resource id
* @param lockKeys the lock keys
* @param clientId the client id
* @return the branch session
*/
public static BranchSession newBranchByGlobal(GlobalSession globalSession, BranchType branchType, String resourceId,
String applicationData, String lockKeys, String clientId) {
BranchSession branchSession = new BranchSession();
branchSession.setTransactionId(globalSession.getTransactionId());
branchSession.setBranchId(UUIDGenerator.generateUUID());
branchSession.setBranchType(branchType);
branchSession.setResourceId(resourceId);
branchSession.setLockKey(lockKeys);
branchSession.setClientId(clientId);
branchSession.setApplicationData(applicationData);
return branchSession;
}
/**
* End committed.
*
* @param globalSession the global session
* @throws TransactionException the transaction exception
*/
public static void endCommitted(GlobalSession globalSession) throws TransactionException {
globalSession.changeStatus(GlobalStatus.Committed);
globalSession.end();
}
/**
* End commit failed.
*
* @param globalSession the global session
* @throws TransactionException the transaction exception
*/
public static void endCommitFailed(GlobalSession globalSession) throws TransactionException {
globalSession.changeStatus(GlobalStatus.CommitFailed);
globalSession.end();
}
/**
* End rollbacked.
*
* @param globalSession the global session
* @throws TransactionException the transaction exception
*/
public static void endRollbacked(GlobalSession globalSession) throws TransactionException {
GlobalStatus currentStatus = globalSession.getStatus();
if (isTimeoutGlobalStatus(currentStatus)) {
globalSession.changeStatus(GlobalStatus.TimeoutRollbacked);
} else {
globalSession.changeStatus(GlobalStatus.Rollbacked);
}
globalSession.end();
}
/**
* End rollback failed.
*
* @param globalSession the global session
* @throws TransactionException the transaction exception
*/
public static void endRollbackFailed(GlobalSession globalSession) throws TransactionException {
GlobalStatus currentStatus = globalSession.getStatus();
if (isTimeoutGlobalStatus(currentStatus)) {
globalSession.changeStatus(GlobalStatus.TimeoutRollbackFailed);
} else {
globalSession.changeStatus(GlobalStatus.RollbackFailed);
}
globalSession.end();
}
public static boolean isTimeoutGlobalStatus(GlobalStatus status) {
return status == GlobalStatus.TimeoutRollbacked
|| status == GlobalStatus.TimeoutRollbackFailed
|| status == GlobalStatus.TimeoutRollbacking
|| status == GlobalStatus.TimeoutRollbackRetrying;
}
}
@@ -1,242 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import io.seata.common.exception.ShouldNeverHappenException;
import io.seata.common.exception.StoreException;
import io.seata.common.util.StringUtils;
import io.seata.config.Configuration;
import io.seata.config.ConfigurationFactory;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.GlobalStatus;
import io.seata.core.store.StoreMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
* The type Session holder.
*
* @author sharajava
*/
public class SessionHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionHolder.class);
/**
* The constant CONFIG.
*/
protected static final Configuration CONFIG = ConfigurationFactory.getInstance();
/**
* The constant ROOT_SESSION_MANAGER_NAME.
*/
public static final String ROOT_SESSION_MANAGER_NAME = "root.data";
/**
* The constant ASYNC_COMMITTING_SESSION_MANAGER_NAME.
*/
public static final String ASYNC_COMMITTING_SESSION_MANAGER_NAME = "async.commit.data";
/**
* The constant RETRY_COMMITTING_SESSION_MANAGER_NAME.
*/
public static final String RETRY_COMMITTING_SESSION_MANAGER_NAME = "retry.commit.data";
/**
* The constant RETRY_ROLLBACKING_SESSION_MANAGER_NAME.
*/
public static final String RETRY_ROLLBACKING_SESSION_MANAGER_NAME = "retry.rollback.data";
private static SessionManager ROOT_SESSION_MANAGER;
private static SessionManager ASYNC_COMMITTING_SESSION_MANAGER;
private static SessionManager RETRY_COMMITTING_SESSION_MANAGER;
private static SessionManager RETRY_ROLLBACKING_SESSION_MANAGER;
/**
* Init.
*
* @param mode the store mode: file、db
* @throws IOException the io exception
*/
public static void init(String mode) throws IOException {
if (StringUtils.isBlank(mode)) {
//use default
mode = CONFIG.getConfig(ConfigurationKeys.STORE_MODE);
}
//the store mode
StoreMode storeMode = StoreMode.valueof(mode);
if (StoreMode.DB.equals(storeMode)) {
//TODO database store
} else if (StoreMode.FILE.equals(storeMode)) {
//file store
String sessionStorePath = CONFIG.getConfig(ConfigurationKeys.STORE_FILE_DIR);
if (sessionStorePath == null) {
throw new StoreException("the {store.file.dir} is empty.");
}
ROOT_SESSION_MANAGER = new FileBasedSessionManager(ROOT_SESSION_MANAGER_NAME, sessionStorePath);
ASYNC_COMMITTING_SESSION_MANAGER = new DefaultSessionManager(ASYNC_COMMITTING_SESSION_MANAGER_NAME);
RETRY_COMMITTING_SESSION_MANAGER = new DefaultSessionManager(RETRY_COMMITTING_SESSION_MANAGER_NAME);
RETRY_ROLLBACKING_SESSION_MANAGER = new DefaultSessionManager(RETRY_ROLLBACKING_SESSION_MANAGER_NAME);
} else {
//unknown store
throw new IllegalArgumentException("unknown store mode:" + mode);
}
if (ROOT_SESSION_MANAGER instanceof Reloadable) {
((Reloadable) ROOT_SESSION_MANAGER).reload();
Collection<GlobalSession> reloadedSessions = ROOT_SESSION_MANAGER.allSessions();
if (reloadedSessions != null && !reloadedSessions.isEmpty()) {
reloadedSessions.forEach(globalSession -> {
GlobalStatus globalStatus = globalSession.getStatus();
switch (globalStatus) {
case UnKnown:
case Committed:
case CommitFailed:
case Rollbacked:
case RollbackFailed:
case TimeoutRollbacked:
case TimeoutRollbackFailed:
case Finished:
throw new ShouldNeverHappenException("Reloaded Session should NOT be " + globalStatus);
case AsyncCommitting:
try {
globalSession.addSessionLifecycleListener(getAsyncCommittingSessionManager());
getAsyncCommittingSessionManager().addGlobalSession(globalSession);
} catch (TransactionException e) {
throw new ShouldNeverHappenException(e);
}
break;
default: {
ArrayList<BranchSession> branchSessions = globalSession.getSortedBranches();
// Lock
branchSessions.forEach(branchSession -> {
try {
branchSession.lock();
} catch (TransactionException e) {
throw new ShouldNeverHappenException(e);
}
});
switch (globalStatus) {
case Committing:
case CommitRetrying:
try {
globalSession.addSessionLifecycleListener(
getRetryCommittingSessionManager());
getRetryCommittingSessionManager().addGlobalSession(globalSession);
} catch (TransactionException e) {
throw new ShouldNeverHappenException(e);
}
break;
case Rollbacking:
case RollbackRetrying:
case TimeoutRollbacking:
case TimeoutRollbackRetrying:
try {
globalSession.addSessionLifecycleListener(
getRetryRollbackingSessionManager());
getRetryRollbackingSessionManager().addGlobalSession(globalSession);
} catch (TransactionException e) {
throw new ShouldNeverHappenException(e);
}
break;
case Begin:
globalSession.setActive(true);
break;
default:
throw new ShouldNeverHappenException("NOT properly handled " + globalStatus);
}
break;
}
}
});
}
}
}
/**
* Gets root session manager.
*
* @return the root session manager
*/
public static final SessionManager getRootSessionManager() {
if (ROOT_SESSION_MANAGER == null) {
throw new ShouldNeverHappenException("SessionManager is NOT init!");
}
return ROOT_SESSION_MANAGER;
}
/**
* Gets async committing session manager.
*
* @return the async committing session manager
*/
public static final SessionManager getAsyncCommittingSessionManager() {
if (ASYNC_COMMITTING_SESSION_MANAGER == null) {
throw new ShouldNeverHappenException("SessionManager is NOT init!");
}
return ASYNC_COMMITTING_SESSION_MANAGER;
}
/**
* Gets retry committing session manager.
*
* @return the retry committing session manager
*/
public static final SessionManager getRetryCommittingSessionManager() {
if (RETRY_COMMITTING_SESSION_MANAGER == null) {
throw new ShouldNeverHappenException("SessionManager is NOT init!");
}
return RETRY_COMMITTING_SESSION_MANAGER;
}
/**
* Gets retry rollbacking session manager.
*
* @return the retry rollbacking session manager
*/
public static final SessionManager getRetryRollbackingSessionManager() {
if (RETRY_ROLLBACKING_SESSION_MANAGER == null) {
throw new ShouldNeverHappenException("SessionManager is NOT init!");
}
return RETRY_ROLLBACKING_SESSION_MANAGER;
}
/**
* Find global session.
*
* @param transactionId the transaction id
* @return the global session
*/
public static GlobalSession findGlobalSession(Long transactionId) {
return getRootSessionManager().findGlobalSession(transactionId);
}
public static void destory() {
ROOT_SESSION_MANAGER.destroy();
ASYNC_COMMITTING_SESSION_MANAGER.destroy();
RETRY_COMMITTING_SESSION_MANAGER.destroy();
RETRY_ROLLBACKING_SESSION_MANAGER.destroy();
}
}
@@ -1,89 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.GlobalStatus;
/**
* The interface Session lifecycle.
*
* @author sharajava
*/
public interface SessionLifecycle {
/**
* Begin.
*
* @throws TransactionException the transaction exception
*/
void begin() throws TransactionException;
/**
* Change status.
*
* @param status the status
* @throws TransactionException the transaction exception
*/
void changeStatus(GlobalStatus status) throws TransactionException;
/**
* Change branch status.
*
* @param branchSession the branch session
* @param status the status
* @throws TransactionException the transaction exception
*/
void changeBranchStatus(BranchSession branchSession, BranchStatus status) throws TransactionException;
/**
* Add branch.
*
* @param branchSession the branch session
* @throws TransactionException the transaction exception
*/
void addBranch(BranchSession branchSession) throws TransactionException;
/**
* Remove branch.
*
* @param branchSession the branch session
* @throws TransactionException the transaction exception
*/
void removeBranch(BranchSession branchSession) throws TransactionException;
/**
* Is active boolean.
*
* @return the boolean
*/
boolean isActive();
/**
* Close.
*
* @throws TransactionException the transaction exception
*/
void close() throws TransactionException;
/**
* End.
*
* @throws TransactionException the transaction exception
*/
void end() throws TransactionException;
}
@@ -1,90 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.GlobalStatus;
/**
* The interface Session lifecycle listener.
*
* @author sharajava
*/
public interface SessionLifecycleListener {
/**
* On begin.
*
* @param globalSession the global session
* @throws TransactionException the transaction exception
*/
void onBegin(GlobalSession globalSession) throws TransactionException;
/**
* On status change.
*
* @param globalSession the global session
* @param status the status
* @throws TransactionException the transaction exception
*/
void onStatusChange(GlobalSession globalSession, GlobalStatus status) throws TransactionException;
/**
* On branch status change.
*
* @param globalSession the global session
* @param branchSession the branch session
* @param status the status
* @throws TransactionException the transaction exception
*/
void onBranchStatusChange(GlobalSession globalSession, BranchSession branchSession, BranchStatus status)
throws TransactionException;
/**
* On add branch.
*
* @param globalSession the global session
* @param branchSession the branch session
* @throws TransactionException the transaction exception
*/
void onAddBranch(GlobalSession globalSession, BranchSession branchSession) throws TransactionException;
/**
* On remove branch.
*
* @param globalSession the global session
* @param branchSession the branch session
* @throws TransactionException the transaction exception
*/
void onRemoveBranch(GlobalSession globalSession, BranchSession branchSession) throws TransactionException;
/**
* On close.
*
* @param globalSession the global session
* @throws TransactionException the transaction exception
*/
void onClose(GlobalSession globalSession) throws TransactionException;
/**
* On end.
*
* @param globalSession the global session
* @throws TransactionException the transaction exception
*/
void onEnd(GlobalSession globalSession) throws TransactionException;
}
@@ -1,109 +0,0 @@
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.server.session;
import java.util.Collection;
import java.util.List;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.GlobalStatus;
import io.seata.core.rpc.Disposable;
/**
* The interface Session manager.
*
* @author sharajava
*/
public interface SessionManager extends SessionLifecycleListener, Disposable {
/**
* Add global session.
*
* @param session the session
* @throws TransactionException the transaction exception
*/
void addGlobalSession(GlobalSession session) throws TransactionException;
/**
* Find global session global session.
*
* @param transactionId the transaction id
* @return the global session
* @throws TransactionException the transaction exception
*/
GlobalSession findGlobalSession(Long transactionId);
/**
* Update global session status.
*
* @param session the session
* @param status the status
* @throws TransactionException the transaction exception
*/
void updateGlobalSessionStatus(GlobalSession session, GlobalStatus status) throws TransactionException;
/**
* Remove global session.
*
* @param session the session
* @throws TransactionException the transaction exception
*/
void removeGlobalSession(GlobalSession session) throws TransactionException;
/**
* Add branch session.
*
* @param globalSession the global session
* @param session the session
* @throws TransactionException the transaction exception
*/
void addBranchSession(GlobalSession globalSession, BranchSession session) throws TransactionException;
/**
* Update branch session status.
*
* @param session the session
* @param status the status
* @throws TransactionException the transaction exception
*/
void updateBranchSessionStatus(BranchSession session, BranchStatus status) throws TransactionException;
/**
* Remove branch session.
*
* @param globalSession the global session
* @param session the session
* @throws TransactionException the transaction exception
*/
void removeBranchSession(GlobalSession globalSession, BranchSession session) throws TransactionException;
/**
* All sessions collection.
*
* @return the collection
*/
Collection<GlobalSession> allSessions();
/**
* Find global sessions list.
*
* @param condition the condition
* @return the list
*/
List<GlobalSession> findGlobalSessions(SessionCondition condition);
}