Formatted Alfresco-style

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@22322 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Derek Hulley
2010-09-08 10:39:51 +00:00
parent 808ff739a3
commit 7f4402ac58

View File

@@ -26,7 +26,6 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import org.alfresco.repo.cache.EhCacheAdapter;
import org.alfresco.repo.cache.SimpleCache; import org.alfresco.repo.cache.SimpleCache;
import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
@@ -51,462 +50,461 @@ import org.apache.commons.logging.LogFactory;
*/ */
public class ActionTrackingServiceImpl implements ActionTrackingService public class ActionTrackingServiceImpl implements ActionTrackingService
{ {
/** /**
* The logger * The logger
*/ */
private static Log logger = LogFactory.getLog(ActionTrackingServiceImpl.class); private static Log logger = LogFactory.getLog(ActionTrackingServiceImpl.class);
private SimpleCache<String, ExecutionDetails> executingActionsCache; private SimpleCache<String, ExecutionDetails> executingActionsCache;
private TransactionService transactionService;
private RuntimeActionService runtimeActionService;
private TransactionService transactionService; /**
private RuntimeActionService runtimeActionService; * Doesn't need to be cluster unique, is just used to try to reduce the
* chance of clashes in the quickest and easiest way.
*/
private short nextExecutionId = 1;
private short wrapExecutionIdAfter = Short.MAX_VALUE / 2;
/** How we separate bits of the cache key */
private static final char cacheKeyPartSeparator = '=';
/** /**
* Doesn't need to be cluster unique, is just used * Set the transaction service
* to try to reduce the chance of clashes in the *
* quickest and easiest way. * @param transactionService the transaction service
*/ */
private short nextExecutionId = 1; public void setTransactionService(TransactionService transactionService)
private short wrapExecutionIdAfter = Short.MAX_VALUE/2; {
this.transactionService = transactionService;
}
/** How we separate bits of the cache key */ /**
private static final char cacheKeyPartSeparator = '='; * Set the runtime action service
*
* @param runtimeActionService the runtime action service
*/
public void setRuntimeActionService(RuntimeActionService runtimeActionService)
{
this.runtimeActionService = runtimeActionService;
}
/** /**
* Set the transaction service * Sets the cache used to store details of currently executing actions,
* * cluster wide.
* @param transactionService the transaction service */
*/ public void setExecutingActionsCache(SimpleCache<String, ExecutionDetails> executingActionsCache)
public void setTransactionService(TransactionService transactionService) {
{ this.executingActionsCache = executingActionsCache;
this.transactionService = transactionService; }
}
/** /** Used by unit tests only */
* Set the runtime action service protected void resetNextExecutionId()
* {
* @param runtimeActionService the runtime action service this.nextExecutionId = 1;
*/ }
public void setRuntimeActionService(RuntimeActionService runtimeActionService)
{
this.runtimeActionService = runtimeActionService;
}
/** public void recordActionPending(Action action)
* Sets the cache used to store details of {
* currently executing actions, cluster wide. recordActionPending((ActionImpl) action);
*/ }
public void setExecutingActionsCache(SimpleCache<String, ExecutionDetails> executingActionsCache)
{
this.executingActionsCache = executingActionsCache;
}
public void recordActionPending(ActionImpl action)
{
// Set the status
action.setExecutionStatus(ActionStatus.Pending);
/** Used by unit tests only */ // Mark it as not having started quite yet
protected void resetNextExecutionId() { action.setExecutionStartDate(null);
this.nextExecutionId = 1;
}
// Have it put into the cache, so we can tell it
// is waiting to be run
placeActionInCache(action);
}
public void recordActionPending(Action action) public void recordActionComplete(Action action)
{ {
recordActionPending((ActionImpl)action); recordActionComplete((ActionImpl) action);
} }
public void recordActionPending(ActionImpl action)
{
// Set the status
action.setExecutionStatus(ActionStatus.Pending);
// Mark it as not having started quite yet private void recordActionComplete(ActionImpl action)
action.setExecutionStartDate(null); {
if (logger.isDebugEnabled() == true)
{
logger.debug("Action " + action + " has completed execution");
}
// Have it put into the cache, so we can tell it // Mark it as having worked
// is waiting to be run action.setExecutionEndDate(new Date());
placeActionInCache(action); action.setExecutionStatus(ActionStatus.Completed);
} action.setExecutionFailureMessage(null);
if (action.getNodeRef() != null)
{
runtimeActionService.saveActionImpl(action.getNodeRef(), action);
}
public void recordActionComplete(Action action) // Remove it from the cache, as it's finished
{ String key = generateCacheKey(action);
recordActionComplete((ActionImpl)action); executingActionsCache.remove(key);
} }
private void recordActionComplete(ActionImpl action)
{
if (logger.isDebugEnabled() == true)
{
logger.debug("Action " + action + " has completed execution");
}
// Mark it as having worked public void recordActionExecuting(Action action)
action.setExecutionEndDate(new Date()); {
action.setExecutionStatus(ActionStatus.Completed); recordActionExecuting((ActionImpl) action);
action.setExecutionFailureMessage(null); }
if(action.getNodeRef() != null)
{
runtimeActionService.saveActionImpl(action.getNodeRef(), action);
}
// Remove it from the cache, as it's finished private void recordActionExecuting(ActionImpl action)
String key = generateCacheKey(action); {
executingActionsCache.remove(key); if (logger.isDebugEnabled() == true)
} {
logger.debug("Action " + action + " with provisional key " + generateCacheKey(action)
+ " has begun exection");
}
public void recordActionExecuting(Action action) // Grab what status it was before
{ ActionStatus previousStatus = action.getExecutionStatus();
recordActionExecuting((ActionImpl)action);
}
private void recordActionExecuting(ActionImpl action)
{
if (logger.isDebugEnabled() == true)
{
logger.debug("Action " + action + " with provisional key " + generateCacheKey(action) + " has begun exection");
}
// Grab what status it was before // Mark the action as starting
ActionStatus previousStatus = action.getExecutionStatus(); action.setExecutionStartDate(new Date());
action.setExecutionStatus(ActionStatus.Running);
// Mark the action as starting // If it's a synchronous execution, put it into the cache
action.setExecutionStartDate(new Date()); if (previousStatus != ActionStatus.Pending)
action.setExecutionStatus(ActionStatus.Running); {
placeActionInCache(action);
}
else
{
// If it's async, update the existing cache entry
String key = generateCacheKey(action);
ExecutionDetails details = executingActionsCache.get(key);
// If it's a synchronous execution, put it into the cache // Check it's really there, warn + fix if not
if(previousStatus != ActionStatus.Pending) if (details == null)
{ {
placeActionInCache(action); logger.warn("Went to mark the start of execution of " + action + " with key " + key
} + " but it wasn't in the running actions cache! "
else + "Your running actions cache is probably too small");
{
// If it's async, update the existing cache entry
String key = generateCacheKey(action);
ExecutionDetails details = executingActionsCache.get(key);
// Check it's really there, warn + fix if not
if(details == null) {
logger.warn(
"Went to mark the start of execution of " +
action + " with key " + key +
" but it wasn't in the running actions cache! " +
"Your running actions cache is probably too small"
);
}
// Update and save into the cache
details = buildExecutionDetails(action);
executingActionsCache.put(key, details);
}
}
/**
* For an action that needs to go into the cache
* (async action that is pending, or sync action
* that is running), assign an execution instance
* and put into the cache
*/
private void placeActionInCache(ActionImpl action)
{
// Assign it a (unique) execution ID
// (Keep checking to see if the key is used as we
// increase nextExecutionId until it isn't)
String key = null;
boolean assigned = false;
while(!assigned) {
// Try
action.setExecutionInstance(nextExecutionId++);
key = generateCacheKey(action);
// Is it ok?
if(executingActionsCache.get(key) == null) {
assigned = true;
}
// Do we need to wrap?
// (Wrap before absolutely needed, makes things simpler)
if(nextExecutionId > wrapExecutionIdAfter) {
synchronized (this) {
while(nextExecutionId > wrapExecutionIdAfter) {
nextExecutionId -= wrapExecutionIdAfter;
}
} }
}
}
// Put it into the cache // Update and save into the cache
ExecutionDetails details = buildExecutionDetails(action); details = buildExecutionDetails(action);
executingActionsCache.put(key, details); executingActionsCache.put(key, details);
}
}
if (logger.isDebugEnabled() == true) /**
{ * For an action that needs to go into the cache (async action that is
logger.debug("Action " + action + " with key " + key + " placed into execution cache"); * pending, or sync action that is running), assign an execution instance
} * and put into the cache
} */
private void placeActionInCache(ActionImpl action)
{
// Assign it a (unique) execution ID
// (Keep checking to see if the key is used as we
// increase nextExecutionId until it isn't)
String key = null;
boolean assigned = false;
while (!assigned)
{
// Try
action.setExecutionInstance(nextExecutionId++);
key = generateCacheKey(action);
/** // Is it ok?
* Schedule the recording of the action failure to occur if (executingActionsCache.get(key) == null)
* in another transaction {
*/ assigned = true;
public void recordActionFailure(Action action, Throwable exception)
{
if (logger.isDebugEnabled() == true)
{
if(exception instanceof ActionCancelledException)
{
logger.debug("Will shortly record completed cancellation of action " + action);
}
else
{
logger.debug("Will shortly record failure of action " + action + " due to " + exception.getMessage());
}
}
// Record when it finished
((ActionImpl)action).setExecutionEndDate(new Date());
// Record it as Failed or Cancelled, depending on the exception
if(exception instanceof ActionCancelledException)
{
((ActionImpl)action).setExecutionStatus(ActionStatus.Cancelled);
((ActionImpl)action).setExecutionFailureMessage(null);
}
else
{
((ActionImpl)action).setExecutionStatus(ActionStatus.Failed);
((ActionImpl)action).setExecutionFailureMessage(exception.getMessage());
}
// Remove it from the cache, as it's no longer running
String key = generateCacheKey(action);
executingActionsCache.remove(key);
// Do we need to update the persisted details?
if(action.getNodeRef() != null)
{
// Take a local copy of the details
// (That way, if someone has a reference to the
// action and plays with it, we still save the
// correct information)
final String actionId = action.getId();
final Date startedAt = action.getExecutionStartDate();
final Date endedAt = action.getExecutionEndDate();
final String message = action.getExecutionFailureMessage();
final NodeRef actionNode = action.getNodeRef();
// Have the details updated on the action as soon
// as the transaction has finished rolling back
AlfrescoTransactionSupport.bindListener(
new TransactionListenerAdapter() {
public void afterRollback()
{
transactionService.getRetryingTransactionHelper().doInTransaction(
new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
// Update the action as the system user
return AuthenticationUtil.runAs(new RunAsWork<Action>() {
public Action doWork() throws Exception
{
// Grab the latest version of the action
ActionImpl action = (ActionImpl)
runtimeActionService.createAction(actionNode);
// Update it
action.setExecutionStartDate(startedAt);
action.setExecutionEndDate(endedAt);
action.setExecutionStatus(ActionStatus.Failed);
action.setExecutionFailureMessage(message);
runtimeActionService.saveActionImpl(actionNode, action);
if (logger.isDebugEnabled() == true)
{
logger.debug("Recorded failure of action " + actionId + ", node " + actionNode + " due to " + message);
}
// All done
return action;
}
}, AuthenticationUtil.SYSTEM_USER_NAME);
}
}, false, true
);
}
} }
);
}
}
public boolean isCancellationRequested(CancellableAction action) // Do we need to wrap?
{ // (Wrap before absolutely needed, makes things simpler)
// If the action isn't in the cache, but is of if (nextExecutionId > wrapExecutionIdAfter)
// status executing, then put it back into the {
// cache and warn synchronized (this)
// (Probably means the cache is too small) {
String key = generateCacheKey(action); while (nextExecutionId > wrapExecutionIdAfter)
ExecutionDetails details = getExecutionDetails(buildExecutionSummary(key)); {
if(details == null) { nextExecutionId -= wrapExecutionIdAfter;
Exception e = new Exception("Cancellation status missing from cache"); }
e.fillInStackTrace(); }
}
}
logger.warn( // Put it into the cache
"Unable to check cancellation status for running action " + ExecutionDetails details = buildExecutionDetails(action);
action + " with execution key " + key + executingActionsCache.put(key, details);
" as it wasn't in the running actions cache! " +
"Your running actions cache is probably too small",
e
);
// Re-generate if (logger.isDebugEnabled() == true)
details = buildExecutionDetails(action); {
logger.debug("Action " + action + " with key " + key + " placed into execution cache");
}
}
// Re-save into the cache, so it's there for /**
// next time * Schedule the recording of the action failure to occur in another
executingActionsCache.put(key, details); * transaction
} */
public void recordActionFailure(Action action, Throwable exception)
{
if (logger.isDebugEnabled() == true)
{
if (exception instanceof ActionCancelledException)
{
logger.debug("Will shortly record completed cancellation of action " + action);
}
else
{
logger.debug("Will shortly record failure of action " + action + " due to "
+ exception.getMessage());
}
}
// Check the cached details, and see if cancellation // Record when it finished
// has been requested ((ActionImpl) action).setExecutionEndDate(new Date());
return details.isCancelRequested();
}
public void requestActionCancellation(CancellableAction action) // Record it as Failed or Cancelled, depending on the exception
{ if (exception instanceof ActionCancelledException)
requestActionCancellation( {
generateCacheKey(action) ((ActionImpl) action).setExecutionStatus(ActionStatus.Cancelled);
); ((ActionImpl) action).setExecutionFailureMessage(null);
} }
else
{
((ActionImpl) action).setExecutionStatus(ActionStatus.Failed);
((ActionImpl) action).setExecutionFailureMessage(exception.getMessage());
}
public void requestActionCancellation(ExecutionSummary executionSummary) // Remove it from the cache, as it's no longer running
{ String key = generateCacheKey(action);
requestActionCancellation( executingActionsCache.remove(key);
generateCacheKey(executionSummary)
);
}
private void requestActionCancellation(String actionKey) // Do we need to update the persisted details?
{ if (action.getNodeRef() != null)
// See if the action is in the cache {
ExecutionDetails details = executingActionsCache.get(actionKey); // Take a local copy of the details
// (That way, if someone has a reference to the
// action and plays with it, we still save the
// correct information)
final String actionId = action.getId();
final Date startedAt = action.getExecutionStartDate();
final Date endedAt = action.getExecutionEndDate();
final String message = action.getExecutionFailureMessage();
final NodeRef actionNode = action.getNodeRef();
if(details == null) { // Have the details updated on the action as soon
// It isn't in the cache, so nothing to do // as the transaction has finished rolling back
return; AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter()
} {
public void afterRollback()
{
transactionService.getRetryingTransactionHelper().doInTransaction(
new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
// Update the action as the system user
return AuthenticationUtil.runAs(new RunAsWork<Action>()
{
public Action doWork() throws Exception
{
// Grab the latest version of the
// action
ActionImpl action = (ActionImpl) runtimeActionService
.createAction(actionNode);
// Since it is, update the cancelled flag on it // Update it
details.requestCancel(); action.setExecutionStartDate(startedAt);
action.setExecutionEndDate(endedAt);
action.setExecutionStatus(ActionStatus.Failed);
action.setExecutionFailureMessage(message);
runtimeActionService.saveActionImpl(actionNode, action);
// Save the flag to the cache if (logger.isDebugEnabled() == true)
executingActionsCache.put(actionKey, details); {
} logger.debug("Recorded failure of action "
+ actionId + ", node " + actionNode
+ " due to " + message);
}
// All done
return action;
}
}, AuthenticationUtil.SYSTEM_USER_NAME);
}
}, false, true);
}
});
}
}
public List<ExecutionSummary> getAllExecutingActions() { public boolean isCancellationRequested(CancellableAction action)
Collection<String> actions = executingActionsCache.getKeys(); {
List<ExecutionSummary> details = new ArrayList<ExecutionSummary>(actions.size()); // If the action isn't in the cache, but is of
for(String key : actions) { // status executing, then put it back into the
details.add( buildExecutionSummary(key) ); // cache and warn
} // (Probably means the cache is too small)
return details; String key = generateCacheKey(action);
} ExecutionDetails details = getExecutionDetails(buildExecutionSummary(key));
if (details == null)
{
Exception e = new Exception("Cancellation status missing from cache");
e.fillInStackTrace();
public List<ExecutionSummary> getExecutingActions(Action action) { logger.warn("Unable to check cancellation status for running action " + action
Collection<String> actions = executingActionsCache.getKeys(); + " with execution key " + key + " as it wasn't in the running actions cache! "
List<ExecutionSummary> details = new ArrayList<ExecutionSummary>(); + "Your running actions cache is probably too small", e);
String match = action.getActionDefinitionName() + cacheKeyPartSeparator +
action.getId() + cacheKeyPartSeparator;
for(String key : actions) {
if(key.startsWith(match)) {
details.add( buildExecutionSummary(key) );
}
}
return details;
}
public List<ExecutionSummary> getExecutingActions(String type) { // Re-generate
Collection<String> actions = executingActionsCache.getKeys(); details = buildExecutionDetails(action);
List<ExecutionSummary> details = new ArrayList<ExecutionSummary>();
String match = type + cacheKeyPartSeparator;
for(String key : actions) {
if(key.startsWith(match)) {
details.add( buildExecutionSummary(key) );
}
}
return details;
}
public ExecutionDetails getExecutionDetails(ExecutionSummary executionSummary) { // Re-save into the cache, so it's there for
ExecutionDetails details = executingActionsCache.get( // next time
generateCacheKey(executionSummary) executingActionsCache.put(key, details);
); }
if(details != null) {
details.setExecutionSummary(executionSummary);
}
return details;
}
/** // Check the cached details, and see if cancellation
* Generates the cache key for the specified action. // has been requested
*/ return details.isCancelRequested();
protected static String generateCacheKey(Action action) }
{
return
action.getActionDefinitionName() + cacheKeyPartSeparator +
action.getId() + cacheKeyPartSeparator +
((ActionImpl)action).getExecutionInstance()
;
}
protected static String generateCacheKey(ExecutionSummary summary)
{
return
summary.getActionType() + cacheKeyPartSeparator +
summary.getActionId() + cacheKeyPartSeparator +
summary.getExecutionInstance()
;
}
/** public void requestActionCancellation(CancellableAction action)
* Builds up the details to be stored in a cache {
* for a specific action requestActionCancellation(generateCacheKey(action));
*/ }
protected static ExecutionDetails buildExecutionDetails(Action action)
{
// Where are we running?
if(machineName == null) {
try {
InetAddress localhost = InetAddress.getLocalHost();
machineName = localhost.getHostAddress() + " : " +
localhost.getHostName();
} catch(UnknownHostException e) {
machineName = "(machine details unavailable - server IP not known)";
}
}
// Generate public void requestActionCancellation(ExecutionSummary executionSummary)
return new ExecutionDetails( {
buildExecutionSummary(action), requestActionCancellation(generateCacheKey(executionSummary));
action.getNodeRef(), machineName, }
action.getExecutionStartDate(), false
);
}
private static String machineName = null;
/** private void requestActionCancellation(String actionKey)
* Turns a cache key back into its constituent {
* parts, for easier access. // See if the action is in the cache
*/ ExecutionDetails details = executingActionsCache.get(actionKey);
protected static ExecutionSummary buildExecutionSummary(String key)
{
StringTokenizer st = new StringTokenizer(key, new String(new char[]{cacheKeyPartSeparator}));
String actionType = st.nextToken();
String actionId = st.nextToken();
int executionInstance = Integer.parseInt(st.nextToken());
return new ExecutionSummary(actionType, actionId, executionInstance); if (details == null)
} {
protected static ExecutionSummary buildExecutionSummary(Action action) // It isn't in the cache, so nothing to do
{ return;
return new ExecutionSummary( }
action.getActionDefinitionName(),
action.getId(), // Since it is, update the cancelled flag on it
((ActionImpl)action).getExecutionInstance() details.requestCancel();
);
} // Save the flag to the cache
executingActionsCache.put(actionKey, details);
}
public List<ExecutionSummary> getAllExecutingActions()
{
Collection<String> actions = executingActionsCache.getKeys();
List<ExecutionSummary> details = new ArrayList<ExecutionSummary>(actions.size());
for (String key : actions)
{
details.add(buildExecutionSummary(key));
}
return details;
}
public List<ExecutionSummary> getExecutingActions(Action action)
{
Collection<String> actions = executingActionsCache.getKeys();
List<ExecutionSummary> details = new ArrayList<ExecutionSummary>();
String match = action.getActionDefinitionName() + cacheKeyPartSeparator + action.getId()
+ cacheKeyPartSeparator;
for (String key : actions)
{
if (key.startsWith(match))
{
details.add(buildExecutionSummary(key));
}
}
return details;
}
public List<ExecutionSummary> getExecutingActions(String type)
{
Collection<String> actions = executingActionsCache.getKeys();
List<ExecutionSummary> details = new ArrayList<ExecutionSummary>();
String match = type + cacheKeyPartSeparator;
for (String key : actions)
{
if (key.startsWith(match))
{
details.add(buildExecutionSummary(key));
}
}
return details;
}
public ExecutionDetails getExecutionDetails(ExecutionSummary executionSummary)
{
ExecutionDetails details = executingActionsCache.get(generateCacheKey(executionSummary));
if (details != null)
{
details.setExecutionSummary(executionSummary);
}
return details;
}
/**
* Generates the cache key for the specified action.
*/
protected static String generateCacheKey(Action action)
{
return action.getActionDefinitionName() + cacheKeyPartSeparator + action.getId()
+ cacheKeyPartSeparator + ((ActionImpl) action).getExecutionInstance();
}
protected static String generateCacheKey(ExecutionSummary summary)
{
return summary.getActionType() + cacheKeyPartSeparator + summary.getActionId()
+ cacheKeyPartSeparator + summary.getExecutionInstance();
}
/**
* Builds up the details to be stored in a cache for a specific action
*/
protected static ExecutionDetails buildExecutionDetails(Action action)
{
// Where are we running?
if (machineName == null)
{
try
{
InetAddress localhost = InetAddress.getLocalHost();
machineName = localhost.getHostAddress() + " : " + localhost.getHostName();
}
catch (UnknownHostException e)
{
machineName = "(machine details unavailable - server IP not known)";
}
}
// Generate
return new ExecutionDetails(buildExecutionSummary(action), action.getNodeRef(),
machineName, action.getExecutionStartDate(), false);
}
private static String machineName = null;
/**
* Turns a cache key back into its constituent parts, for easier access.
*/
protected static ExecutionSummary buildExecutionSummary(String key)
{
StringTokenizer st = new StringTokenizer(key, new String(
new char[] { cacheKeyPartSeparator }));
String actionType = st.nextToken();
String actionId = st.nextToken();
int executionInstance = Integer.parseInt(st.nextToken());
return new ExecutionSummary(actionType, actionId, executionInstance);
}
protected static ExecutionSummary buildExecutionSummary(Action action)
{
return new ExecutionSummary(action.getActionDefinitionName(), action.getId(),
((ActionImpl) action).getExecutionInstance());
}
} }