Skip to content
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
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)

## [Unreleased 2.x](https://github.com/opensearch-project/flow-framework/compare/2.18...2.x)
### Features
- Add synchronous execution option to workflow provisioning ([#990](https://github.com/opensearch-project/flow-framework/pull/990))

### Enhancements
### Bug Fixes
- Remove useCase and defaultParams field in WorkflowRequest ([#758](https://github.com/opensearch-project/flow-framework/pull/758))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
*/
package org.opensearch.flowframework.common;

import org.opensearch.common.unit.TimeValue;

/**
* Representation of common values that are used across project
*/
Expand Down Expand Up @@ -55,6 +57,8 @@ private CommonValue() {}
/** The last provisioned time field */
public static final String LAST_PROVISIONED_TIME_FIELD = "last_provisioned_time";

public static final TimeValue DEFAULT_WAIT_FOR_COMPLETION_TIMEOUT = TimeValue.timeValueSeconds(1);

/*
* Constants associated with Rest or Transport actions
*/
Expand All @@ -74,6 +78,8 @@ private CommonValue() {}
public static final String PROVISION_WORKFLOW = "provision";
/** The param name for update workflow field in create API */
public static final String UPDATE_WORKFLOW_FIELDS = "update_fields";
/** The param name for specifying the timeout duration in seconds to wait for workflow completion */
public static final String WAIT_FOR_COMPLETION_TIMEOUT = "wait_for_completion_timeout";
/** The field name for workflow steps. This field represents the name of the workflow steps to be fetched. */
public static final String WORKFLOW_STEP = "workflow_step";
/** The param name for default use case, used by the create workflow API */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.apache.logging.log4j.Logger;
import org.opensearch.ExceptionsHelper;
import org.opensearch.client.node.NodeClient;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContent;
Expand Down Expand Up @@ -43,6 +44,7 @@
import static org.opensearch.flowframework.common.CommonValue.UPDATE_WORKFLOW_FIELDS;
import static org.opensearch.flowframework.common.CommonValue.USE_CASE;
import static org.opensearch.flowframework.common.CommonValue.VALIDATION;
import static org.opensearch.flowframework.common.CommonValue.WAIT_FOR_COMPLETION_TIMEOUT;
import static org.opensearch.flowframework.common.CommonValue.WORKFLOW_ID;
import static org.opensearch.flowframework.common.CommonValue.WORKFLOW_URI;
import static org.opensearch.flowframework.common.FlowFrameworkSettings.FLOW_FRAMEWORK_ENABLED;
Expand Down Expand Up @@ -87,6 +89,7 @@ protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient cli
boolean provision = request.paramAsBoolean(PROVISION_WORKFLOW, false);
boolean reprovision = request.paramAsBoolean(REPROVISION_WORKFLOW, false);
boolean updateFields = request.paramAsBoolean(UPDATE_WORKFLOW_FIELDS, false);
TimeValue waitForCompletionTimeout = request.paramAsTime(WAIT_FOR_COMPLETION_TIMEOUT, null);
Copy link
Member

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.

Copy link
Member

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?

String useCase = request.param(USE_CASE);

// If provisioning, consume all other params and pass to provision transport action
Expand Down Expand Up @@ -226,7 +229,8 @@ protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient cli
validation,
provision || updateFields,
params,
reprovision
reprovision,
waitForCompletionTimeout
);

return channel -> client.execute(CreateWorkflowAction.INSTANCE, workflowRequest, ActionListener.wrap(response -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.apache.logging.log4j.Logger;
import org.opensearch.ExceptionsHelper;
import org.opensearch.client.node.NodeClient;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContent;
Expand All @@ -33,6 +34,7 @@
import java.util.stream.Collectors;

import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.opensearch.flowframework.common.CommonValue.WAIT_FOR_COMPLETION_TIMEOUT;
import static org.opensearch.flowframework.common.CommonValue.WORKFLOW_ID;
import static org.opensearch.flowframework.common.CommonValue.WORKFLOW_URI;
import static org.opensearch.flowframework.common.FlowFrameworkSettings.FLOW_FRAMEWORK_ENABLED;
Expand Down Expand Up @@ -73,6 +75,7 @@ public List<Route> routes() {
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String workflowId = request.param(WORKFLOW_ID);
TimeValue waitForCompletionTimeout = request.paramAsTime(WAIT_FOR_COMPLETION_TIMEOUT, null);
try {
Map<String, String> params = parseParamsAndContent(request);
if (!flowFrameworkFeatureEnabledSetting.isFlowFrameworkEnabled()) {
Expand All @@ -86,7 +89,7 @@ protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient cli
throw new FlowFrameworkException("workflow_id cannot be null", RestStatus.BAD_REQUEST);
}
// Create request and provision
WorkflowRequest workflowRequest = new WorkflowRequest(workflowId, null, params);
WorkflowRequest workflowRequest = new WorkflowRequest(workflowId, null, params, waitForCompletionTimeout);
return channel -> client.execute(ProvisionWorkflowAction.INSTANCE, workflowRequest, ActionListener.wrap(response -> {
XContentBuilder builder = response.toXContent(channel.newBuilder(), ToXContent.EMPTY_PARAMS);
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,8 @@ private void createExecute(WorkflowRequest request, User user, ActionListener<Wo
WorkflowRequest workflowRequest = new WorkflowRequest(
globalContextResponse.getId(),
null,
request.getParams()
request.getParams(),
request.getWaitForCompletionTimeout()
);
logger.info(
"Provisioning parameter is set, continuing to provision workflow {}",
Expand All @@ -261,7 +262,14 @@ private void createExecute(WorkflowRequest request, User user, ActionListener<Wo
ProvisionWorkflowAction.INSTANCE,
workflowRequest,
ActionListener.wrap(provisionResponse -> {
listener.onResponse(new WorkflowResponse(provisionResponse.getWorkflowId()));
listener.onResponse(
request.getWaitForCompletionTimeout() != null
? new WorkflowResponse(
provisionResponse.getWorkflowId(),
provisionResponse.getWorkflowState()
)
: new WorkflowResponse(provisionResponse.getWorkflowId())
);
}, exception -> {
String errorMessage = "Provisioning failed.";
logger.error(errorMessage, exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {}",
Expand Down Expand Up @@ -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);
Copy link
Member

@dbwiddis dbwiddis Jan 9, 2025

Choose a reason for hiding this comment

The 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 TimeoutRunnableListener<Response> to execute a block of code when the timeout expires. We should probably follow that pattern.

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<>();
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading