-
Notifications
You must be signed in to change notification settings - Fork 37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add synchronous execution option to workflow provisioning #990
Open
junweid62
wants to merge
3
commits into
opensearch-project:main
Choose a base branch
from
junweid62:provision-syncronosly
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -45,6 +45,8 @@ | |
import java.util.List; | ||
import java.util.Locale; | ||
import java.util.Map; | ||
import java.util.concurrent.CompletableFuture; | ||
import java.util.concurrent.atomic.AtomicBoolean; | ||
import java.util.stream.Collectors; | ||
|
||
import static org.opensearch.flowframework.common.CommonValue.ERROR_FIELD; | ||
|
@@ -210,14 +212,27 @@ private void executeProvisionRequest( | |
), | ||
ActionListener.wrap(updateResponse -> { | ||
logger.info("updated workflow {} state to {}", request.getWorkflowId(), State.PROVISIONING); | ||
executeWorkflowAsync(workflowId, provisionProcessSequence, listener); | ||
if (request.getWaitForCompletionTimeout() != null) { | ||
executeWorkflowSync( | ||
workflowId, | ||
provisionProcessSequence, | ||
listener, | ||
request.getWaitForCompletionTimeout().getMillis() | ||
); | ||
} else { | ||
executeWorkflowAsync(workflowId, provisionProcessSequence, listener); | ||
} | ||
// update last provisioned field in template | ||
Template newTemplate = Template.builder(template).lastProvisionedTime(Instant.now()).build(); | ||
flowFrameworkIndicesHandler.updateTemplateInGlobalContext( | ||
request.getWorkflowId(), | ||
newTemplate, | ||
ActionListener.wrap(templateResponse -> { | ||
listener.onResponse(new WorkflowResponse(request.getWorkflowId())); | ||
if (request.getWaitForCompletionTimeout() != null) { | ||
logger.info("Waiting for workflow completion"); | ||
} else { | ||
listener.onResponse(new WorkflowResponse(request.getWorkflowId())); | ||
} | ||
}, exception -> { | ||
String errorMessage = ParameterizedMessageFactory.INSTANCE.newMessage( | ||
"Failed to update use case template {}", | ||
|
@@ -275,18 +290,138 @@ private void executeProvisionRequest( | |
*/ | ||
private void executeWorkflowAsync(String workflowId, List<ProcessNode> workflowSequence, ActionListener<WorkflowResponse> listener) { | ||
try { | ||
threadPool.executor(PROVISION_WORKFLOW_THREAD_POOL).execute(() -> { executeWorkflow(workflowSequence, workflowId); }); | ||
threadPool.executor(PROVISION_WORKFLOW_THREAD_POOL) | ||
.execute(() -> { executeWorkflow(workflowSequence, workflowId, listener, false); }); | ||
} catch (Exception exception) { | ||
listener.onFailure(new FlowFrameworkException("Failed to execute workflow " + workflowId, ExceptionsHelper.status(exception))); | ||
} | ||
} | ||
|
||
/** | ||
* Retrieves a thread from the provision thread pool to execute a workflow with a timeout mechanism. | ||
* If the execution exceeds the specified timeout, it will return the current status of the workflow. | ||
* | ||
* @param workflowId The id of the workflow | ||
* @param workflowSequence The sorted workflow to execute | ||
* @param listener ActionListener for any failures or responses | ||
* @param timeout The timeout duration in milliseconds | ||
*/ | ||
private void executeWorkflowSync( | ||
String workflowId, | ||
List<ProcessNode> workflowSequence, | ||
ActionListener<WorkflowResponse> listener, | ||
long timeout | ||
) { | ||
PlainActionFuture<WorkflowResponse> workflowFuture = new PlainActionFuture<>(); | ||
AtomicBoolean isResponseSent = new AtomicBoolean(false); | ||
CompletableFuture.runAsync(() -> { | ||
try { | ||
executeWorkflow(workflowSequence, workflowId, new ActionListener<>() { | ||
@Override | ||
public void onResponse(WorkflowResponse workflowResponse) { | ||
if (isResponseSent.get()) { | ||
logger.info("Ignoring onResponse for workflowId: {} as timeout already occurred", workflowId); | ||
return; | ||
} | ||
isResponseSent.set(true); | ||
workflowFuture.onResponse(null); | ||
listener.onResponse(new WorkflowResponse(workflowResponse.getWorkflowId(), workflowResponse.getWorkflowState())); | ||
} | ||
|
||
@Override | ||
public void onFailure(Exception e) { | ||
if (isResponseSent.get()) { | ||
logger.info("Ignoring onFailure for workflowId: {} as timeout already occurred", workflowId); | ||
return; | ||
} | ||
isResponseSent.set(true); | ||
workflowFuture.onFailure( | ||
new FlowFrameworkException("Failed to execute workflow " + workflowId, ExceptionsHelper.status(e)) | ||
); | ||
listener.onFailure( | ||
new FlowFrameworkException("Failed to execute workflow " + workflowId, ExceptionsHelper.status(e)) | ||
); | ||
} | ||
}, true); | ||
} catch (Exception ex) { | ||
if (!isResponseSent.get()) { | ||
isResponseSent.set(true); | ||
workflowFuture.onFailure( | ||
new FlowFrameworkException("Failed to execute workflow " + workflowId, ExceptionsHelper.status(ex)) | ||
); | ||
listener.onFailure(new FlowFrameworkException("Failed to execute workflow " + workflowId, ExceptionsHelper.status(ex))); | ||
} | ||
} | ||
}, threadPool.executor(PROVISION_WORKFLOW_THREAD_POOL)); | ||
|
||
// Schedule timeout handler | ||
scheduleTimeoutHandler(workflowId, listener, timeout, isResponseSent); | ||
} | ||
|
||
/** | ||
* Schedules a timeout handler for workflow execution. | ||
* This method starts a new task in the thread pool to wait for the specified timeout duration. | ||
* If the workflow does not complete within the given timeout, it triggers a follow-up action | ||
* to fetch the workflow's state and notify the listener. | ||
* | ||
* @param workflowId The unique identifier of the workflow being executed. | ||
* @param listener The ActionListener to notify with the workflow's response or failure. | ||
* @param timeout The maximum time (in milliseconds) to wait for the workflow to complete before timing out. | ||
* @param isResponseSent An AtomicBoolean flag to ensure the response is sent only once. | ||
*/ | ||
private void scheduleTimeoutHandler( | ||
String workflowId, | ||
ActionListener<WorkflowResponse> listener, | ||
long timeout, | ||
AtomicBoolean isResponseSent | ||
) { | ||
threadPool.executor(PROVISION_WORKFLOW_THREAD_POOL).execute(() -> { | ||
try { | ||
Thread.sleep(timeout); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are probably better ways to handle timeouts than sleeping threads. Async search uses a |
||
if (isResponseSent.compareAndSet(false, true)) { | ||
logger.warn("Workflow execution timed out for workflowId: {}", workflowId); | ||
fetchWorkflowStateAfterTimeout(workflowId, listener); | ||
} | ||
} catch (InterruptedException e) { | ||
Thread.currentThread().interrupt(); | ||
} | ||
}); | ||
} | ||
|
||
/** | ||
* Fetches the workflow state after a timeout has occurred. | ||
* This method sends a request to retrieve the current state of the workflow | ||
* and notifies the listener with the updated state or an error if the request fails. | ||
* | ||
* @param workflowId The unique identifier of the workflow whose state needs to be fetched. | ||
* @param listener The ActionListener to notify with the workflow's updated state or failure. | ||
*/ | ||
private void fetchWorkflowStateAfterTimeout(String workflowId, ActionListener<WorkflowResponse> listener) { | ||
client.execute( | ||
GetWorkflowStateAction.INSTANCE, | ||
new GetWorkflowStateRequest(workflowId, false), | ||
ActionListener.wrap( | ||
response -> listener.onResponse(new WorkflowResponse(workflowId, response.getWorkflowState())), | ||
exception -> listener.onFailure( | ||
new FlowFrameworkException("Failed to get workflow state after timeout", ExceptionsHelper.status(exception)) | ||
) | ||
) | ||
); | ||
} | ||
|
||
/** | ||
* Executes the given workflow sequence | ||
* @param workflowSequence The topologically sorted workflow to execute | ||
* @param workflowId The workflowId associated with the workflow that is executing | ||
* @param listener The ActionListener to handle the workflow response or failure | ||
* @param isSyncExecution Flag indicating whether the workflow should be executed synchronously (true) or asynchronously (false) | ||
*/ | ||
private void executeWorkflow(List<ProcessNode> workflowSequence, String workflowId) { | ||
private void executeWorkflow( | ||
List<ProcessNode> workflowSequence, | ||
String workflowId, | ||
ActionListener<WorkflowResponse> listener, | ||
boolean isSyncExecution | ||
) { | ||
String currentStepId = ""; | ||
try { | ||
Map<String, PlainActionFuture<?>> workflowFutureMap = new LinkedHashMap<>(); | ||
|
@@ -324,6 +459,23 @@ private void executeWorkflow(List<ProcessNode> workflowSequence, String workflow | |
), | ||
ActionListener.wrap(updateResponse -> { | ||
logger.info("updated workflow {} state to {}", workflowId, State.COMPLETED); | ||
if (isSyncExecution) { | ||
client.execute( | ||
GetWorkflowStateAction.INSTANCE, | ||
new GetWorkflowStateRequest(workflowId, false), | ||
ActionListener.wrap(response -> { | ||
listener.onResponse(new WorkflowResponse(workflowId, response.getWorkflowState())); | ||
}, exception -> { | ||
String errorMessage = "Failed to get workflow state."; | ||
logger.error(errorMessage, exception); | ||
if (exception instanceof FlowFrameworkException) { | ||
listener.onFailure(exception); | ||
} else { | ||
listener.onFailure(new FlowFrameworkException(errorMessage, ExceptionsHelper.status(exception))); | ||
} | ||
}) | ||
); | ||
} | ||
}, exception -> { logger.error("Failed to update workflow state for workflow {}", workflowId, exception); }) | ||
); | ||
} catch (Exception ex) { | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I generally like to avoid
null
whenever possible. It can crop up in unexpected places (toString()
gets called somewhere, for example).There is a special constant
TimeValue.MINUS_ONE
you can use to "disable" the feature. Then later rather than testing!= null
you can just test for this special value.This is a common pattern in OpenSearch when using
TimeValue
settings or parameters, so it is behavior that existing users should expect. See for example cancel_after_time_interval.In fact, since -1 is an allowed timevalue, unless you explicitly test for it to not be negative, you'll allow that particular edge case (which will probably behave similarly to 0, returning immediately?).
No other negative values are allowed in timevalues, so you can reliably use a <0 test for this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That said, I'm not sure we need to parse it here, rather than just passing it along in the
params
map to be handled in the transport action?