본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

How to: 워크플로 관리하기

원문 보기 위키 갱신

How to: 워크플로 관리하기 (Manage workflows)

애플리케이션에서 워크플로와 그 액티비티를 작성했다면, CLI나 API 호출로 워크플로를 시작·종료·재실행하고 정보를 얻을 수 있어요.

  • CLI
  • Python
  • JavaScript
  • .NET
  • Java
  • Go
  • HTTP

출처: Dapr 문서

본문

Dapr CLI로 워크플로 관리하기 (Managing Workflows with the Dapr CLI)

Dapr CLI는 self-hosted와 Kubernetes 환경 모두에서 워크플로 인스턴스를 관리하는 명령을 제공합니다. 완료된 워크플로의 보존 정책 구성 방법은 Workflow Retention Policy도 참고하세요.

기본 워크플로 연산 (Basic Workflow Operations)

워크플로 시작하기 (Start a Workflow)


dapr workflow run OrderProcessingWorkflow \
--app-id orderprocessing \
--input '{"orderId": "12345", "amount": 100.50}'


dapr workflow run OrderProcessingWorkflow \
--app-id orderprocessing \
--instance-id order-12345 \
--input '{"orderId": "12345"}'

dapr workflow run OrderProcessingWorkflow \
--app-id orderprocessing \
--start-time "2024-12-25T10:00:00Z"

워크플로 인스턴스 나열하기 (List Workflow Instances)


dapr workflow list


dapr workflow list --filter-status RUNNING


dapr workflow list --app-id orderprocessing --filter-name OrderProcessingWorkflow


dapr workflow list --filter-max-age 24h


dapr workflow list -o wide

워크플로 히스토리 보기 (View Workflow History)


dapr workflow history order-12345


dapr workflow history order-12345 --app-id orderprocessing --output json

워크플로 실행 제어하기 (Control Workflow Execution)


dapr workflow suspend order-12345 \
--app-id orderprocessing \
--reason "Waiting for manual approval"


dapr workflow resume order-12345 \
--app-id orderprocessing \
--reason "Approved by manager"


dapr workflow terminate order-12345 \
--app-id orderprocessing \
--output '{"reason": "Cancelled by customer"}'

외부 이벤트 발생시키기 (Raise External Events)


dapr workflow raise-event order-12345/PaymentReceived \
--app-id orderprocessing \
--input '{"paymentId": "pay-67890", "amount": 100.50}'

워크플로 재실행하기 (Re-run Workflows)


dapr workflow rerun order-12345


dapr workflow rerun order-12345 --event-id 5


dapr workflow rerun order-12345 --new-instance-id order-12345-retry

완료된 워크플로 퍼지하기 (Purge Completed Workflows)

CLI에서 워크플로를 퍼지하면 관련된 모든 Scheduler 리마인더도 함께 삭제된다는 점을 유의하세요.

중요 (Important)

<p>It is required that a workflow client is running in the application to perform purge operations.</p>

퍼지 연산을 수행하려면 워크플로 상태 머신의 무결성과 손상 방지를 위해 워크플로 클라이언트 연결이 필요해요. 다음과 같은 오류는 워크플로 클라이언트가 실행 중이지 않다는 뜻입니다.

failed to purge orchestration state: rpc error: code = FailedPrecondition desc = failed to purge orchestration state: failed to lookup actor: api error: code = FailedPrecondition desc = did not find address for actor

--force 플래그를 사용하면 워크플로 애플리케이션이 실행 중이지 않아도 워크플로를 퍼지할 수 있습니다. 하지만 현재 실행 중인 워크플로 인스턴스가 없다고 확신할 때만 사용해야 합니다. 그렇지 않으면 워크플로 상태 머신을 손상시킬 수 있어요.


dapr workflow purge order-12345


dapr workflow purge --all-older-than 720h


dapr workflow purge --all-older-than 720h --all-filter-status FAILED


dapr workflow purge --app-id orderprocessing --all


dapr workflow purge order-12345 --force

Kubernetes 연산 (Kubernetes Operations)

모든 명령은 Kubernetes 배포를 위해 -k 플래그를 지원합니다.


dapr workflow list \
--kubernetes \
--namespace production \
--app-id orderprocessing


dapr workflow suspend order-12345 \
--kubernetes \
--namespace production \
--app-id orderprocessing \
--reason "Maintenance window"

워크플로 나열하기 (Listing Workflows)

self-hosted 모드에서는 단순히 실행하세요.

dapr workflow list

Kubernetes 모드에서는 네임스페이스와 앱 ID와 함께 --kubernetes/-k 플래그를 지정하세요.

dapr workflow list -k

워크플로 관리 모범 사례 (Workflow Management Best Practices)

  • 실행 중인 워크플로 모니터링: 필터링된 목록을 사용해 장기 실행 인스턴스를 추적하세요.
dapr workflow list --app-id orderprocessing --filter-status RUNNING --filter-max-age 24h
  • 인스턴스 ID 사용: 더 쉬운 추적을 위해 의미 있는 인스턴스 ID를 할당하세요.
dapr workflow run OrderWorkflow --app-id orderprocessing --instance-id "order-$(date +%s)"
  • 분석용으로 내보내기: 분석을 위해 워크플로 데이터를 내보내세요.
dapr workflow list --app-id orderprocessing --output json > workflows.json

Dapr Dev Dashboard로 워크플로 관리하기 (Managing Workflows with the Dapr Dev Dashboard)

로컬 개발에서는 dapr workflow list와 dapr workflow history 명령의 시각적 대안으로 Dapr Dev Dashboard를 사용할 수 있어요. 대시보드는 실행 중인 앱의 워크플로 인스턴스를 상태와 함께 나열하고, 각 인스턴스의 전체 이벤트 히스토리(액티비티 입력·출력, 타이머, 외부 이벤트 포함)를 보여줍니다. Dev Dashboard는 로컬 개발용이며 Kubernetes 안에서는 실행되지 않습니다.

Dapr CLI로 워크플로 리마인더 관리하기 (Managing Workflow Reminders with the Dapr CLI)

워크플로 리마인더는 Scheduler에 저장되며 dapr scheduler CLI로 관리할 수 있습니다.

워크플로 리마인더 나열하기 (List workflow reminders)

dapr scheduler list --filter workflow
NAME BEGIN COUNT LAST TRIGGER
workflow/my-app/instance1/timer-0-ABC123 +50.0h 0
workflow/my-app/instance2/timer-0-XYZ789 +50.0h 0

리마인더 상세 보기 (Get reminder details)

dapr scheduler get workflow/my-app/instance1/timer-0-ABC123 -o yaml

워크플로 리마인더 삭제하기 (Delete workflow reminders)

단일 리마인더 삭제:

dapr scheduler delete workflow/my-app/instance1/timer-0-ABC123

주어진 워크플로 앱의 모든 리마인더 삭제:

dapr scheduler delete-all workflow/my-app

특정 워크플로 인스턴스의 모든 리마인더 삭제:

dapr scheduler delete-all workflow/my-app/instance1

리마인더 백업·복원 (Backup and restore reminders)

모든 리마인더 내보내기:

dapr scheduler export -o workflow-reminders-backup.bin

백업 파일에서 복원:

dapr scheduler import -f workflow-reminders-backup.bin

코드 안에서 워크플로를 관리해 보세요. Author a workflow 가이드의 워크플로 예제에서는 워크플로가 다음 API를 사용해 코드에 등록됩니다.

  • schedule_new_workflow: 워크플로 인스턴스 시작
  • get_workflow_state: 워크플로 상태 정보 가져오기
  • pause_workflow: 나중에 재개할 수 있도록 워크플로 인스턴스 일시 중지
  • resume_workflow: 일시 중지된 워크플로 인스턴스 재개
  • raise_workflow_event: 워크플로에 이벤트 발생
  • purge_workflow: 특정 워크플로 인스턴스와 관련된 모든 메타데이터 제거
  • wait_for_workflow_completion: 특정 워크플로 인스턴스를 완료할 때까지 대기
from dapr.ext.workflow import WorkflowRuntime, DaprWorkflowContext, WorkflowActivityContext
from dapr.clients import DaprClient


instanceId = "exampleInstanceID"
workflowComponent = "dapr"
workflowName = "hello_world_wf"
eventName = "event1"
eventData = "eventData"


wf_client.schedule_new_workflow(
workflow=hello_world_wf, input=input_data, instance_id=instance_id
)


wf_client.get_workflow_state(instance_id=instance_id)


wf_client.pause_workflow(instance_id=instance_id)
metadata = wf_client.get_workflow_state(instance_id=instance_id)


wf_client.resume_workflow(instance_id=instance_id)


wf_client.raise_workflow_event(instance_id=instance_id, event_name=event_name, data=event_data)


wf_client.purge_workflow(instance_id=instance_id)


wf_client.wait_for_workflow_completion(instance_id, timeout_in_seconds=30)

코드 안에서 워크플로를 관리해 보세요. Author a workflow 가이드의 워크플로 예제에서는 워크플로가 다음 API를 사용해 코드에 등록됩니다.

  • client.workflow.start: 워크플로 인스턴스 시작
  • client.workflow.get: 워크플로 상태 정보 가져오기
  • client.workflow.pause: 나중에 재개할 수 있도록 워크플로 인스턴스 일시 중지
  • client.workflow.resume: 일시 중지된 워크플로 인스턴스 재개
  • client.workflow.purge: 특정 워크플로 인스턴스와 관련된 모든 메타데이터 제거
  • client.workflow.terminate: 특정 워크플로 인스턴스 종료·중지
import { DaprClient } from "@dapr/dapr";

async function printWorkflowStatus(client: DaprClient, instanceId: string) {
const workflow = await client.workflow.get(instanceId);
console.log(
`Workflow ${workflow.workflowName}, created at ${workflow.createdAt.toUTCString()}, has status ${
workflow.runtimeStatus
}`,
);
console.log(`Additional properties: ${JSON.stringify(workflow.properties)}`);
console.log("--------------------------------------------------\n\n");
}

async function start() {
const client = new DaprClient();

// Start a new workflow instance
const instanceId = await client.workflow.start("OrderProcessingWorkflow", {
Name: "Paperclips",
TotalCost: 99.95,
Quantity: 4,
});
console.log(`Started workflow instance ${instanceId}`);
await printWorkflowStatus(client, instanceId);

// Pause a workflow instance
await client.workflow.pause(instanceId);
console.log(`Paused workflow instance ${instanceId}`);
await printWorkflowStatus(client, instanceId);

// Resume a workflow instance
await client.workflow.resume(instanceId);
console.log(`Resumed workflow instance ${instanceId}`);
await printWorkflowStatus(client, instanceId);

// Terminate a workflow instance
await client.workflow.terminate(instanceId);
console.log(`Terminated workflow instance ${instanceId}`);
await printWorkflowStatus(client, instanceId);

// Wait for the workflow to complete, 30 seconds!
await new Promise((resolve) => setTimeout(resolve, 30000));
await printWorkflowStatus(client, instanceId);

// Purge a workflow instance
await client.workflow.purge(instanceId);
console.log(`Purged workflow instance ${instanceId}`);
// This will throw an error because the workflow instance no longer exists.
await printWorkflowStatus(client, instanceId);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

코드 안에서 워크플로를 관리해 보세요. Author a workflow 가이드의 OrderProcessingWorkflow 예제에서는 워크플로가 코드에 등록됩니다. 이제 실행 중인 워크플로를 시작·종료하고 정보를 얻을 수 있어요.

string orderId = "exampleOrderId";
OrderPayload input = new OrderPayload("Paperclips", 99.95);
Dictionary<string, string> workflowOptions; // This is an optional parameter

// Start the workflow using the orderId as our workflow ID. This returns a string containing the instance ID for the particular workflow instance, whether we provide it ourselves or not.
await daprWorkflowClient.ScheduleNewWorkflowAsync(nameof(OrderProcessingWorkflow), orderId, input, workflowOptions);

// Get information on the workflow. This response contains information such as the status of the workflow, when it started, and more!
WorkflowState currentState = await daprWorkflowClient.GetWorkflowStateAsync(orderId, orderId);

// Terminate the workflow
await daprWorkflowClient.TerminateWorkflowAsync(orderId);

// Raise an event (an incoming purchase order) that your workflow will wait for
await daprWorkflowClient.RaiseEventAsync(orderId, "incoming-purchase-order", input);

// Pause
await daprWorkflowClient.SuspendWorkflowAsync(orderId);

// Resume
await daprWorkflowClient.ResumeWorkflowAsync(orderId);

// Purge the workflow, removing all inbox and history information from associated instance
await daprWorkflowClient.PurgeInstanceAsync(orderId);

코드 안에서 워크플로를 관리해 보세요. Java SDK의 워크플로 예제에서는 워크플로가 다음 API를 사용해 코드에 등록됩니다.

  • scheduleNewWorkflow: 새 워크플로 인스턴스 시작
  • getInstanceState: 워크플로 상태 정보 가져오기
  • waitForInstanceStart: 나중에 재개할 수 있도록 워크플로 인스턴스 일시 중지
  • raiseEvent: 실행 중인 워크플로 인스턴스에 이벤트/태스크 발생
  • waitForInstanceCompletion: 워크플로가 태스크를 완료할 때까지 대기
  • purgeInstance: 특정 워크플로 인스턴스와 관련된 모든 메타데이터 제거
  • terminateWorkflow: 워크플로 종료
  • purgeInstance: 특정 워크플로와 관련된 모든 메타데이터 제거
package io.dapr.examples.workflows;

import io.dapr.workflows.client.DaprWorkflowClient;
import io.dapr.workflows.client.WorkflowInstanceStatus;

// ...
public class DemoWorkflowClient {

// ...
public static void main(String[] args) throws InterruptedException {
DaprWorkflowClient client = new DaprWorkflowClient();

try (client) {
// Start a workflow
String instanceId = client.scheduleNewWorkflow(DemoWorkflow.class, "input data");

// Get status information on the workflow
WorkflowInstanceStatus workflowMetadata = client.getInstanceState(instanceId, true);

// Wait or pause for the workflow instance start
try {
WorkflowInstanceStatus waitForInstanceStartResult =
client.waitForInstanceStart(instanceId, Duration.ofSeconds(60), true);
}

// Raise an event for the workflow; you can raise several events in parallel
client.raiseEvent(instanceId, "TestEvent", "TestEventPayload");
client.raiseEvent(instanceId, "event1", "TestEvent 1 Payload");
client.raiseEvent(instanceId, "event2", "TestEvent 2 Payload");
client.raiseEvent(instanceId, "event3", "TestEvent 3 Payload");

// Wait for workflow to complete running through tasks
try {
WorkflowInstanceStatus waitForInstanceCompletionResult =
client.waitForInstanceCompletion(instanceId, Duration.ofSeconds(60), true);
}

// Purge the workflow instance, removing all metadata associated with it
boolean purgeResult = client.purgeInstance(instanceId);

// Terminate the workflow instance
client.terminateWorkflow(instanceToTerminateId, null);

System.exit(0);
}
}

코드 안에서 워크플로를 관리해 보세요. Go SDK의 워크플로 예제에서는 워크플로가 다음 API를 사용해 코드에 등록됩니다.

  • StartWorkflow: 새 워크플로 인스턴스 시작
  • GetWorkflow: 워크플로 상태 정보 가져오기
  • PauseWorkflow: 나중에 재개할 수 있도록 워크플로 인스턴스 일시 중지
  • RaiseEventWorkflow: 실행 중인 워크플로 인스턴스에 이벤트/태스크 발생
  • ResumeWorkflow: 워크플로가 태스크를 완료할 때까지 대기
  • PurgeWorkflow: 특정 워크플로 인스턴스와 관련된 모든 메타데이터 제거
  • TerminateWorkflow: 워크플로 종료
// Start workflow
type StartWorkflowRequest struct {
InstanceID string // Optional instance identifier
WorkflowComponent string
WorkflowName string
Options map[string]string // Optional metadata
Input any // Optional input
SendRawInput bool // Set to True in order to disable serialization on the input
}

type StartWorkflowResponse struct {
InstanceID string
}

// Get the workflow status
type GetWorkflowRequest struct {
InstanceID string
WorkflowComponent string
}

type GetWorkflowResponse struct {
InstanceID string
WorkflowName string
CreatedAt time.Time
LastUpdatedAt time.Time
RuntimeStatus string
Properties map[string]string
}

// Purge workflow
type PurgeWorkflowRequest struct {
InstanceID string
WorkflowComponent string
}

// Terminate workflow
type TerminateWorkflowRequest struct {
InstanceID string
WorkflowComponent string
}

// Pause workflow
type PauseWorkflowRequest struct {
InstanceID string
WorkflowComponent string
}

// Resume workflow
type ResumeWorkflowRequest struct {
InstanceID string
WorkflowComponent string
}

// Raise an event for the running workflow
type RaiseEventWorkflowRequest struct {
InstanceID string
WorkflowComponent string
EventName string
EventData any
SendRawData bool // Set to True in order to disable serialization on the data
}

HTTP 호출로 워크플로를 관리해 보세요. 아래 예제는 Author a workflow 예제의 속성에 임의의 인스턴스 ID 번호를 끼워 넣습니다.

워크플로 시작하기 (Start workflow)

ID가 12345678인 워크플로를 시작하려면:

curl -X POST "http://localhost:3500/v1.0/workflows/dapr/OrderProcessingWorkflow/start?instanceID=12345678"

워크플로 인스턴스 ID는 영숫자 문자, 밑줄, 대시만 포함할 수 있다는 점을 유의하세요.

중요 (Important)

It is strongly recommended to give every execution a new instance ID rather than reusing an old one. See <a href="https://docs.dapr.io/developing-applications/building-blocks/workflow/workflow-features-concepts/#implications-of-instance-id-reuse">Implications of instance ID reuse</a>. An instance ID can only be reused once the existing workflow with that ID, and every child workflow it created (checked recursively), has reached a terminal state (<code>COMPLETED</code>, <code>FAILED</code>, or <code>TERMINATED</code>), otherwise the request is rejected. To free up an instance ID unconditionally, first purge the existing workflow using the <a href="https://docs.dapr.io/reference/api/workflow_api/#purge-workflow-request">purge API</a> or configure a <a href="https://docs.dapr.io/developing-applications/building-blocks/workflow/workflow-history-retention-policy/">retention policy</a>.

워크플로 종료하기 (Terminate workflow)

ID가 12345678인 워크플로를 종료하려면:

curl -X POST "http://localhost:3500/v1.0/workflows/dapr/12345678/terminate"

이벤트 발생시키기 (Raise an event)

Dapr Workflow 엔진처럼 외부 이벤트 구독을 지원하는 워크플로 컴포넌트의 경우, 다음 "raise event" API를 사용해 특정 워크플로 인스턴스에 이름 붙은 이벤트를 전달할 수 있어요.

curl -X POST "http://localhost:3500/v1.0/workflows/<workflowComponentName>/<instanceID>/raiseEvent/<eventName>"

eventName은 어떤 함수든 될 수 있습니다.

워크플로 일시 중지·재개하기 (Pause or resume a workflow)

다운타임을 계획하거나 입력을 기다리는 등의 경우 워크플로를 일시 중지했다가 재개할 수 있어요. ID가 12345678인 워크플로를 재개 트리거까지 일시 중지하려면:

curl -X POST "http://localhost:3500/v1.0/workflows/dapr/12345678/pause"

ID가 12345678인 워크플로를 재개하려면:

curl -X POST "http://localhost:3500/v1.0/workflows/dapr/12345678/resume"

워크플로 퍼지하기 (Purge a workflow)

purge API로 기본 상태 저장소에서 워크플로 메타데이터를 영구 삭제할 수 있습니다. 저장된 입력·출력·워크플로 히스토리 레코드를 모두 포함해요. 데이터 보존 정책을 구현하고 리소스를 확보할 때 자주 유용합니다. COMPLETED, FAILED, TERMINATED 상태의 워크플로 인스턴스만 퍼지할 수 있습니다. 워크플로가 다른 상태라면 purge 호출은 오류를 반환합니다.

curl -X POST "http://localhost:3500/v1.0/workflows/dapr/12345678/purge"

워크플로 정보 가져오기 (Get information about a workflow)

ID가 12345678인 워크플로 정보(출력·입력)를 가져오려면:

curl -X GET "http://localhost:3500/v1.0/workflows/dapr/12345678"

다음 단계 (Next steps)

이제 워크플로를 관리하는 방법을 배웠으니, 여러 애플리케이션에 걸쳐 워크플로를 실행하는 방법을 배워 보세요. Multi Application Workflows >>

  • Workflow 퀵스타트 체험하기
  • How-To: Apply workflow access policies
  • 전체 SDK 예제 확인: Python 예제
  • JavaScript 예제
  • .NET 예제
  • Java 예제
  • Go 예제

더 알아보기 (Learn more)