index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/conductor/http-task/src/test/java/com/netflix/conductor/tasks
Create_ds/conductor/http-task/src/test/java/com/netflix/conductor/tasks/http/HttpTaskTest.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.tasks.http; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.mockserver.client.MockServerClient; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpResponse; import org.mockserver.model.MediaType; import org.testcontainers.containers.MockServerContainer; import org.testcontainers.utility.DockerImageName; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.core.execution.DeciderService; import com.netflix.conductor.core.execution.WorkflowExecutor; import com.netflix.conductor.core.execution.tasks.SystemTaskRegistry; import com.netflix.conductor.core.utils.ExternalPayloadStorageUtils; import com.netflix.conductor.core.utils.IDGenerator; import com.netflix.conductor.core.utils.ParametersUtils; import com.netflix.conductor.dao.MetadataDAO; import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.model.WorkflowModel; import com.netflix.conductor.tasks.http.providers.DefaultRestTemplateProvider; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; @SuppressWarnings("unchecked") public class HttpTaskTest { private static final String ERROR_RESPONSE = "Something went wrong!"; private static final String TEXT_RESPONSE = "Text Response"; private static final double NUM_RESPONSE = 42.42d; private HttpTask httpTask; private WorkflowExecutor workflowExecutor; private final WorkflowModel workflow = new WorkflowModel(); private static final ObjectMapper objectMapper = new ObjectMapper(); private static String JSON_RESPONSE; @ClassRule public static MockServerContainer mockServer = new MockServerContainer( DockerImageName.parse("mockserver/mockserver").withTag("mockserver-5.12.0")); @BeforeClass public static void init() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("key", "value1"); map.put("num", 42); map.put("SomeKey", null); JSON_RESPONSE = objectMapper.writeValueAsString(map); final TypeReference<Map<String, Object>> mapOfObj = new TypeReference<>() {}; MockServerClient client = new MockServerClient(mockServer.getHost(), mockServer.getServerPort()); client.when(HttpRequest.request().withPath("/post").withMethod("POST")) .respond( request -> { Map<String, Object> reqBody = objectMapper.readValue(request.getBody().toString(), mapOfObj); Set<String> keys = reqBody.keySet(); Map<String, Object> respBody = new HashMap<>(); keys.forEach(k -> respBody.put(k, k)); return HttpResponse.response() .withContentType(MediaType.APPLICATION_JSON) .withBody(objectMapper.writeValueAsString(respBody)); }); client.when(HttpRequest.request().withPath("/post2").withMethod("POST")) .respond(HttpResponse.response().withStatusCode(204)); client.when(HttpRequest.request().withPath("/failure").withMethod("GET")) .respond( HttpResponse.response() .withStatusCode(500) .withContentType(MediaType.TEXT_PLAIN) .withBody(ERROR_RESPONSE)); client.when(HttpRequest.request().withPath("/text").withMethod("GET")) .respond(HttpResponse.response().withBody(TEXT_RESPONSE)); client.when(HttpRequest.request().withPath("/numeric").withMethod("GET")) .respond(HttpResponse.response().withBody(String.valueOf(NUM_RESPONSE))); client.when(HttpRequest.request().withPath("/json").withMethod("GET")) .respond( HttpResponse.response() .withContentType(MediaType.APPLICATION_JSON) .withBody(JSON_RESPONSE)); } @Before public void setup() { workflowExecutor = mock(WorkflowExecutor.class); DefaultRestTemplateProvider defaultRestTemplateProvider = new DefaultRestTemplateProvider(Duration.ofMillis(150), Duration.ofMillis(100)); httpTask = new HttpTask(defaultRestTemplateProvider, objectMapper); } @Test public void testPost() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri("http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/post"); Map<String, Object> body = new HashMap<>(); body.put("input_key1", "value1"); body.put("input_key2", 45.3d); body.put("someKey", null); input.setBody(body); input.setMethod("POST"); input.setReadTimeOut(1000); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); httpTask.start(workflow, task, workflowExecutor); assertEquals(task.getReasonForIncompletion(), TaskModel.Status.COMPLETED, task.getStatus()); Map<String, Object> hr = (Map<String, Object>) task.getOutputData().get("response"); Object response = hr.get("body"); assertEquals(TaskModel.Status.COMPLETED, task.getStatus()); assertTrue("response is: " + response, response instanceof Map); Map<String, Object> map = (Map<String, Object>) response; Set<String> inputKeys = body.keySet(); Set<String> responseKeys = map.keySet(); inputKeys.containsAll(responseKeys); responseKeys.containsAll(inputKeys); } @Test public void testPostNoContent() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri( "http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/post2"); Map<String, Object> body = new HashMap<>(); body.put("input_key1", "value1"); body.put("input_key2", 45.3d); input.setBody(body); input.setMethod("POST"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); httpTask.start(workflow, task, workflowExecutor); assertEquals(task.getReasonForIncompletion(), TaskModel.Status.COMPLETED, task.getStatus()); Map<String, Object> hr = (Map<String, Object>) task.getOutputData().get("response"); Object response = hr.get("body"); assertEquals(TaskModel.Status.COMPLETED, task.getStatus()); assertNull("response is: " + response, response); } @Test public void testFailure() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri( "http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/failure"); input.setMethod("GET"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); httpTask.start(workflow, task, workflowExecutor); assertEquals( "Task output: " + task.getOutputData(), TaskModel.Status.FAILED, task.getStatus()); assertTrue(task.getReasonForIncompletion().contains(ERROR_RESPONSE)); task.setStatus(TaskModel.Status.SCHEDULED); task.getInputData().remove(HttpTask.REQUEST_PARAMETER_NAME); httpTask.start(workflow, task, workflowExecutor); assertEquals(TaskModel.Status.FAILED, task.getStatus()); assertEquals(HttpTask.MISSING_REQUEST, task.getReasonForIncompletion()); } @Test public void testPostAsyncComplete() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri("http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/post"); Map<String, Object> body = new HashMap<>(); body.put("input_key1", "value1"); body.put("input_key2", 45.3d); input.setBody(body); input.setMethod("POST"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); task.getInputData().put("asyncComplete", true); httpTask.start(workflow, task, workflowExecutor); assertEquals( task.getReasonForIncompletion(), TaskModel.Status.IN_PROGRESS, task.getStatus()); Map<String, Object> hr = (Map<String, Object>) task.getOutputData().get("response"); Object response = hr.get("body"); assertEquals(TaskModel.Status.IN_PROGRESS, task.getStatus()); assertTrue("response is: " + response, response instanceof Map); Map<String, Object> map = (Map<String, Object>) response; Set<String> inputKeys = body.keySet(); Set<String> responseKeys = map.keySet(); inputKeys.containsAll(responseKeys); responseKeys.containsAll(inputKeys); } @Test public void testTextGET() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri("http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/text"); input.setMethod("GET"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); httpTask.start(workflow, task, workflowExecutor); Map<String, Object> hr = (Map<String, Object>) task.getOutputData().get("response"); Object response = hr.get("body"); assertEquals(TaskModel.Status.COMPLETED, task.getStatus()); assertEquals(TEXT_RESPONSE, response); } @Test public void testNumberGET() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri( "http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/numeric"); input.setMethod("GET"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); httpTask.start(workflow, task, workflowExecutor); Map<String, Object> hr = (Map<String, Object>) task.getOutputData().get("response"); Object response = hr.get("body"); assertEquals(TaskModel.Status.COMPLETED, task.getStatus()); assertEquals(NUM_RESPONSE, response); assertTrue(response instanceof Number); } @Test public void testJsonGET() throws JsonProcessingException { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri("http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/json"); input.setMethod("GET"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); httpTask.start(workflow, task, workflowExecutor); Map<String, Object> hr = (Map<String, Object>) task.getOutputData().get("response"); Object response = hr.get("body"); assertEquals(TaskModel.Status.COMPLETED, task.getStatus()); assertTrue(response instanceof Map); Map<String, Object> map = (Map<String, Object>) response; assertEquals(JSON_RESPONSE, objectMapper.writeValueAsString(map)); } @Test public void testExecute() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri("http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/json"); input.setMethod("GET"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); task.setStatus(TaskModel.Status.SCHEDULED); task.setScheduledTime(0); boolean executed = httpTask.execute(workflow, task, workflowExecutor); assertFalse(executed); } @Test public void testHTTPGetConnectionTimeOut() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); Instant start = Instant.now(); input.setConnectionTimeOut(110); input.setMethod("GET"); input.setUri("http://10.255.14.15"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); task.setStatus(TaskModel.Status.SCHEDULED); task.setScheduledTime(0); httpTask.start(workflow, task, workflowExecutor); Instant end = Instant.now(); long diff = end.toEpochMilli() - start.toEpochMilli(); assertEquals(task.getStatus(), TaskModel.Status.FAILED); assertTrue(diff >= 110L); } @Test public void testHTTPGETReadTimeOut() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setReadTimeOut(-1); input.setMethod("GET"); input.setUri("http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/json"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); task.setStatus(TaskModel.Status.SCHEDULED); task.setScheduledTime(0); httpTask.start(workflow, task, workflowExecutor); assertEquals(task.getStatus(), TaskModel.Status.FAILED); } @Test public void testOptional() { TaskModel task = new TaskModel(); HttpTask.Input input = new HttpTask.Input(); input.setUri( "http://" + mockServer.getHost() + ":" + mockServer.getServerPort() + "/failure"); input.setMethod("GET"); task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input); httpTask.start(workflow, task, workflowExecutor); assertEquals( "Task output: " + task.getOutputData(), TaskModel.Status.FAILED, task.getStatus()); assertTrue(task.getReasonForIncompletion().contains(ERROR_RESPONSE)); assertFalse(task.getStatus().isSuccessful()); task.setStatus(TaskModel.Status.SCHEDULED); task.getInputData().remove(HttpTask.REQUEST_PARAMETER_NAME); task.setReferenceTaskName("t1"); httpTask.start(workflow, task, workflowExecutor); assertEquals(TaskModel.Status.FAILED, task.getStatus()); assertEquals(HttpTask.MISSING_REQUEST, task.getReasonForIncompletion()); assertFalse(task.getStatus().isSuccessful()); WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setOptional(true); workflowTask.setName("HTTP"); workflowTask.setWorkflowTaskType(TaskType.USER_DEFINED); workflowTask.setTaskReferenceName("t1"); WorkflowDef def = new WorkflowDef(); def.getTasks().add(workflowTask); WorkflowModel workflow = new WorkflowModel(); workflow.setWorkflowDefinition(def); workflow.getTasks().add(task); MetadataDAO metadataDAO = mock(MetadataDAO.class); ExternalPayloadStorageUtils externalPayloadStorageUtils = mock(ExternalPayloadStorageUtils.class); ParametersUtils parametersUtils = mock(ParametersUtils.class); SystemTaskRegistry systemTaskRegistry = mock(SystemTaskRegistry.class); new DeciderService( new IDGenerator(), parametersUtils, metadataDAO, externalPayloadStorageUtils, systemTaskRegistry, Collections.emptyMap(), Duration.ofMinutes(60)) .decide(workflow); } }
6,800
0
Create_ds/conductor/http-task/src/test/java/com/netflix/conductor/tasks/http
Create_ds/conductor/http-task/src/test/java/com/netflix/conductor/tasks/http/providers/DefaultRestTemplateProviderTest.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.tasks.http.providers; import java.time.Duration; import org.junit.Test; import org.springframework.web.client.RestTemplate; import com.netflix.conductor.tasks.http.HttpTask; import static org.junit.Assert.*; public class DefaultRestTemplateProviderTest { @Test public void differentObjectsForDifferentThreads() throws InterruptedException { DefaultRestTemplateProvider defaultRestTemplateProvider = new DefaultRestTemplateProvider(Duration.ofMillis(150), Duration.ofMillis(100)); final RestTemplate restTemplate = defaultRestTemplateProvider.getRestTemplate(new HttpTask.Input()); final StringBuilder result = new StringBuilder(); Thread t1 = new Thread( () -> { RestTemplate restTemplate1 = defaultRestTemplateProvider.getRestTemplate( new HttpTask.Input()); if (restTemplate1 != restTemplate) { result.append("different"); } }); t1.start(); t1.join(); assertEquals(result.toString(), "different"); } @Test public void sameObjectForSameThread() { DefaultRestTemplateProvider defaultRestTemplateProvider = new DefaultRestTemplateProvider(Duration.ofMillis(150), Duration.ofMillis(100)); RestTemplate client1 = defaultRestTemplateProvider.getRestTemplate(new HttpTask.Input()); RestTemplate client2 = defaultRestTemplateProvider.getRestTemplate(new HttpTask.Input()); assertSame(client1, client2); assertNotNull(client1); } }
6,801
0
Create_ds/conductor/http-task/src/main/java/com/netflix/conductor/tasks
Create_ds/conductor/http-task/src/main/java/com/netflix/conductor/tasks/http/HttpTask.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.tasks.http; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import com.netflix.conductor.core.execution.WorkflowExecutor; import com.netflix.conductor.core.execution.tasks.WorkflowSystemTask; import com.netflix.conductor.core.utils.Utils; import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.model.WorkflowModel; import com.netflix.conductor.tasks.http.providers.RestTemplateProvider; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import static com.netflix.conductor.common.metadata.tasks.TaskType.TASK_TYPE_HTTP; /** Task that enables calling another HTTP endpoint as part of its execution */ @Component(TASK_TYPE_HTTP) public class HttpTask extends WorkflowSystemTask { private static final Logger LOGGER = LoggerFactory.getLogger(HttpTask.class); public static final String REQUEST_PARAMETER_NAME = "http_request"; static final String MISSING_REQUEST = "Missing HTTP request. Task input MUST have a '" + REQUEST_PARAMETER_NAME + "' key with HttpTask.Input as value. See documentation for HttpTask for required input parameters"; private final TypeReference<Map<String, Object>> mapOfObj = new TypeReference<Map<String, Object>>() {}; private final TypeReference<List<Object>> listOfObj = new TypeReference<List<Object>>() {}; protected ObjectMapper objectMapper; protected RestTemplateProvider restTemplateProvider; private final String requestParameter; @Autowired public HttpTask(RestTemplateProvider restTemplateProvider, ObjectMapper objectMapper) { this(TASK_TYPE_HTTP, restTemplateProvider, objectMapper); } public HttpTask( String name, RestTemplateProvider restTemplateProvider, ObjectMapper objectMapper) { super(name); this.restTemplateProvider = restTemplateProvider; this.objectMapper = objectMapper; this.requestParameter = REQUEST_PARAMETER_NAME; LOGGER.info("{} initialized...", getTaskType()); } @Override public void start(WorkflowModel workflow, TaskModel task, WorkflowExecutor executor) { Object request = task.getInputData().get(requestParameter); task.setWorkerId(Utils.getServerId()); if (request == null) { task.setReasonForIncompletion(MISSING_REQUEST); task.setStatus(TaskModel.Status.FAILED); return; } Input input = objectMapper.convertValue(request, Input.class); if (input.getUri() == null) { String reason = "Missing HTTP URI. See documentation for HttpTask for required input parameters"; task.setReasonForIncompletion(reason); task.setStatus(TaskModel.Status.FAILED); return; } if (input.getMethod() == null) { String reason = "No HTTP method specified"; task.setReasonForIncompletion(reason); task.setStatus(TaskModel.Status.FAILED); return; } try { HttpResponse response = httpCall(input); LOGGER.debug( "Response: {}, {}, task:{}", response.statusCode, response.body, task.getTaskId()); if (response.statusCode > 199 && response.statusCode < 300) { if (isAsyncComplete(task)) { task.setStatus(TaskModel.Status.IN_PROGRESS); } else { task.setStatus(TaskModel.Status.COMPLETED); } } else { if (response.body != null) { task.setReasonForIncompletion(response.body.toString()); } else { task.setReasonForIncompletion("No response from the remote service"); } task.setStatus(TaskModel.Status.FAILED); } //noinspection ConstantConditions if (response != null) { task.addOutput("response", response.asMap()); } } catch (Exception e) { LOGGER.error( "Failed to invoke {} task: {} - uri: {}, vipAddress: {} in workflow: {}", getTaskType(), task.getTaskId(), input.getUri(), input.getVipAddress(), task.getWorkflowInstanceId(), e); task.setStatus(TaskModel.Status.FAILED); task.setReasonForIncompletion( "Failed to invoke " + getTaskType() + " task due to: " + e); task.addOutput("response", e.toString()); } } /** * @param input HTTP Request * @return Response of the http call * @throws Exception If there was an error making http call Note: protected access is so that * tasks extended from this task can re-use this to make http calls */ protected HttpResponse httpCall(Input input) throws Exception { RestTemplate restTemplate = restTemplateProvider.getRestTemplate(input); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.valueOf(input.getContentType())); headers.setAccept(Collections.singletonList(MediaType.valueOf(input.getAccept()))); input.headers.forEach( (key, value) -> { if (value != null) { headers.add(key, value.toString()); } }); HttpEntity<Object> request = new HttpEntity<>(input.getBody(), headers); HttpResponse response = new HttpResponse(); try { ResponseEntity<String> responseEntity = restTemplate.exchange(input.getUri(), input.getMethod(), request, String.class); if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.hasBody()) { response.body = extractBody(responseEntity.getBody()); } response.statusCode = responseEntity.getStatusCodeValue(); response.reasonPhrase = responseEntity.getStatusCode().getReasonPhrase(); response.headers = responseEntity.getHeaders(); return response; } catch (RestClientException ex) { LOGGER.error( String.format( "Got unexpected http response - uri: %s, vipAddress: %s", input.getUri(), input.getVipAddress()), ex); String reason = ex.getLocalizedMessage(); LOGGER.error(reason, ex); throw new Exception(reason); } } private Object extractBody(String responseBody) { try { JsonNode node = objectMapper.readTree(responseBody); if (node.isArray()) { return objectMapper.convertValue(node, listOfObj); } else if (node.isObject()) { return objectMapper.convertValue(node, mapOfObj); } else if (node.isNumber()) { return objectMapper.convertValue(node, Double.class); } else { return node.asText(); } } catch (IOException jpe) { LOGGER.error("Error extracting response body", jpe); return responseBody; } } @Override public boolean execute(WorkflowModel workflow, TaskModel task, WorkflowExecutor executor) { return false; } @Override public void cancel(WorkflowModel workflow, TaskModel task, WorkflowExecutor executor) { task.setStatus(TaskModel.Status.CANCELED); } @Override public boolean isAsync() { return true; } public static class HttpResponse { public Object body; public MultiValueMap<String, String> headers; public int statusCode; public String reasonPhrase; @Override public String toString() { return "HttpResponse [body=" + body + ", headers=" + headers + ", statusCode=" + statusCode + ", reasonPhrase=" + reasonPhrase + "]"; } public Map<String, Object> asMap() { Map<String, Object> map = new HashMap<>(); map.put("body", body); map.put("headers", headers); map.put("statusCode", statusCode); map.put("reasonPhrase", reasonPhrase); return map; } } public static class Input { private HttpMethod method; // PUT, POST, GET, DELETE, OPTIONS, HEAD private String vipAddress; private String appName; private Map<String, Object> headers = new HashMap<>(); private String uri; private Object body; private String accept = MediaType.APPLICATION_JSON_VALUE; private String contentType = MediaType.APPLICATION_JSON_VALUE; private Integer connectionTimeOut; private Integer readTimeOut; /** * @return the method */ public HttpMethod getMethod() { return method; } /** * @param method the method to set */ public void setMethod(String method) { this.method = HttpMethod.valueOf(method); } /** * @return the headers */ public Map<String, Object> getHeaders() { return headers; } /** * @param headers the headers to set */ public void setHeaders(Map<String, Object> headers) { this.headers = headers; } /** * @return the body */ public Object getBody() { return body; } /** * @param body the body to set */ public void setBody(Object body) { this.body = body; } /** * @return the uri */ public String getUri() { return uri; } /** * @param uri the uri to set */ public void setUri(String uri) { this.uri = uri; } /** * @return the vipAddress */ public String getVipAddress() { return vipAddress; } /** * @param vipAddress the vipAddress to set */ public void setVipAddress(String vipAddress) { this.vipAddress = vipAddress; } /** * @return the accept */ public String getAccept() { return accept; } /** * @param accept the accept to set */ public void setAccept(String accept) { this.accept = accept; } /** * @return the MIME content type to use for the request */ public String getContentType() { return contentType; } /** * @param contentType the MIME content type to set */ public void setContentType(String contentType) { this.contentType = contentType; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } /** * @return the connectionTimeOut */ public Integer getConnectionTimeOut() { return connectionTimeOut; } /** * @return the readTimeOut */ public Integer getReadTimeOut() { return readTimeOut; } public void setConnectionTimeOut(Integer connectionTimeOut) { this.connectionTimeOut = connectionTimeOut; } public void setReadTimeOut(Integer readTimeOut) { this.readTimeOut = readTimeOut; } } }
6,802
0
Create_ds/conductor/http-task/src/main/java/com/netflix/conductor/tasks/http
Create_ds/conductor/http-task/src/main/java/com/netflix/conductor/tasks/http/providers/RestTemplateProvider.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.tasks.http.providers; import org.springframework.lang.NonNull; import org.springframework.web.client.RestTemplate; import com.netflix.conductor.tasks.http.HttpTask; @FunctionalInterface public interface RestTemplateProvider { RestTemplate getRestTemplate(@NonNull HttpTask.Input input); }
6,803
0
Create_ds/conductor/http-task/src/main/java/com/netflix/conductor/tasks/http
Create_ds/conductor/http-task/src/main/java/com/netflix/conductor/tasks/http/providers/DefaultRestTemplateProvider.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.tasks.http.providers; import java.time.Duration; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import com.netflix.conductor.tasks.http.HttpTask; /** * Provider for a customized RestTemplateBuilder. This class provides a default {@link * RestTemplateBuilder} which can be configured or extended as needed. */ @Component public class DefaultRestTemplateProvider implements RestTemplateProvider { private final ThreadLocal<RestTemplate> threadLocalRestTemplate; private final int defaultReadTimeout; private final int defaultConnectTimeout; @Autowired public DefaultRestTemplateProvider( @Value("${conductor.tasks.http.readTimeout:150ms}") Duration readTimeout, @Value("${conductor.tasks.http.connectTimeout:100ms}") Duration connectTimeout) { this.threadLocalRestTemplate = ThreadLocal.withInitial(RestTemplate::new); this.defaultReadTimeout = (int) readTimeout.toMillis(); this.defaultConnectTimeout = (int) connectTimeout.toMillis(); } @Override public @NonNull RestTemplate getRestTemplate(@NonNull HttpTask.Input input) { RestTemplate restTemplate = threadLocalRestTemplate.get(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setConnectTimeout( Optional.ofNullable(input.getConnectionTimeOut()).orElse(defaultConnectTimeout)); requestFactory.setReadTimeout( Optional.ofNullable(input.getReadTimeOut()).orElse(defaultReadTimeout)); restTemplate.setRequestFactory(requestFactory); return restTemplate; } }
6,804
0
Create_ds/conductor/grpc-client/src/test/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/test/java/com/netflix/conductor/client/grpc/WorkflowClientTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.common.run.WorkflowSummary; import com.netflix.conductor.grpc.ProtoMapper; import com.netflix.conductor.grpc.SearchPb; import com.netflix.conductor.grpc.WorkflowServiceGrpc; import com.netflix.conductor.grpc.WorkflowServicePb; import com.netflix.conductor.proto.WorkflowPb; import com.netflix.conductor.proto.WorkflowSummaryPb; import io.grpc.ManagedChannelBuilder; import static junit.framework.TestCase.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) public class WorkflowClientTest { @Mock ProtoMapper mockedProtoMapper; @Mock WorkflowServiceGrpc.WorkflowServiceBlockingStub mockedStub; WorkflowClient workflowClient; @Before public void init() { workflowClient = new WorkflowClient("test", 0); ReflectionTestUtils.setField(workflowClient, "stub", mockedStub); ReflectionTestUtils.setField(workflowClient, "protoMapper", mockedProtoMapper); } @Test public void testSearch() { WorkflowSummary workflow = mock(WorkflowSummary.class); WorkflowSummaryPb.WorkflowSummary workflowPB = mock(WorkflowSummaryPb.WorkflowSummary.class); when(mockedProtoMapper.fromProto(workflowPB)).thenReturn(workflow); WorkflowServicePb.WorkflowSummarySearchResult result = WorkflowServicePb.WorkflowSummarySearchResult.newBuilder() .addResults(workflowPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder().setQuery("test query").build(); when(mockedStub.search(searchRequest)).thenReturn(result); SearchResult<WorkflowSummary> searchResult = workflowClient.search("test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(workflow, searchResult.getResults().get(0)); } @Test public void testSearchV2() { Workflow workflow = mock(Workflow.class); WorkflowPb.Workflow workflowPB = mock(WorkflowPb.Workflow.class); when(mockedProtoMapper.fromProto(workflowPB)).thenReturn(workflow); WorkflowServicePb.WorkflowSearchResult result = WorkflowServicePb.WorkflowSearchResult.newBuilder() .addResults(workflowPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder().setQuery("test query").build(); when(mockedStub.searchV2(searchRequest)).thenReturn(result); SearchResult<Workflow> searchResult = workflowClient.searchV2("test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(workflow, searchResult.getResults().get(0)); } @Test public void testSearchWithParams() { WorkflowSummary workflow = mock(WorkflowSummary.class); WorkflowSummaryPb.WorkflowSummary workflowPB = mock(WorkflowSummaryPb.WorkflowSummary.class); when(mockedProtoMapper.fromProto(workflowPB)).thenReturn(workflow); WorkflowServicePb.WorkflowSummarySearchResult result = WorkflowServicePb.WorkflowSummarySearchResult.newBuilder() .addResults(workflowPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder() .setStart(1) .setSize(5) .setSort("*") .setFreeText("*") .setQuery("test query") .build(); when(mockedStub.search(searchRequest)).thenReturn(result); SearchResult<WorkflowSummary> searchResult = workflowClient.search(1, 5, "*", "*", "test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(workflow, searchResult.getResults().get(0)); } @Test public void testSearchV2WithParams() { Workflow workflow = mock(Workflow.class); WorkflowPb.Workflow workflowPB = mock(WorkflowPb.Workflow.class); when(mockedProtoMapper.fromProto(workflowPB)).thenReturn(workflow); WorkflowServicePb.WorkflowSearchResult result = WorkflowServicePb.WorkflowSearchResult.newBuilder() .addResults(workflowPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder() .setStart(1) .setSize(5) .setSort("*") .setFreeText("*") .setQuery("test query") .build(); when(mockedStub.searchV2(searchRequest)).thenReturn(result); SearchResult<Workflow> searchResult = workflowClient.searchV2(1, 5, "*", "*", "test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(workflow, searchResult.getResults().get(0)); } @Test public void testSearchV2WithParamsWithManagedChannel() { WorkflowClient workflowClient = createClientWithManagedChannel(); Workflow workflow = mock(Workflow.class); WorkflowPb.Workflow workflowPB = mock(WorkflowPb.Workflow.class); when(mockedProtoMapper.fromProto(workflowPB)).thenReturn(workflow); WorkflowServicePb.WorkflowSearchResult result = WorkflowServicePb.WorkflowSearchResult.newBuilder() .addResults(workflowPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder() .setStart(1) .setSize(5) .setSort("*") .setFreeText("*") .setQuery("test query") .build(); when(mockedStub.searchV2(searchRequest)).thenReturn(result); SearchResult<Workflow> searchResult = workflowClient.searchV2(1, 5, "*", "*", "test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(workflow, searchResult.getResults().get(0)); } public WorkflowClient createClientWithManagedChannel() { WorkflowClient workflowClient = new WorkflowClient(ManagedChannelBuilder.forAddress("test", 0)); ReflectionTestUtils.setField(workflowClient, "stub", mockedStub); ReflectionTestUtils.setField(workflowClient, "protoMapper", mockedProtoMapper); return workflowClient; } }
6,805
0
Create_ds/conductor/grpc-client/src/test/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/test/java/com/netflix/conductor/client/grpc/EventClientTest.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.grpc.EventServiceGrpc; import com.netflix.conductor.grpc.EventServicePb; import com.netflix.conductor.grpc.ProtoMapper; import com.netflix.conductor.proto.EventHandlerPb; import static junit.framework.TestCase.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) public class EventClientTest { @Mock ProtoMapper mockedProtoMapper; @Mock EventServiceGrpc.EventServiceBlockingStub mockedStub; EventClient eventClient; @Before public void init() { eventClient = new EventClient("test", 0); ReflectionTestUtils.setField(eventClient, "stub", mockedStub); ReflectionTestUtils.setField(eventClient, "protoMapper", mockedProtoMapper); } @Test public void testRegisterEventHandler() { EventHandler eventHandler = mock(EventHandler.class); EventHandlerPb.EventHandler eventHandlerPB = mock(EventHandlerPb.EventHandler.class); when(mockedProtoMapper.toProto(eventHandler)).thenReturn(eventHandlerPB); EventServicePb.AddEventHandlerRequest request = EventServicePb.AddEventHandlerRequest.newBuilder() .setHandler(eventHandlerPB) .build(); eventClient.registerEventHandler(eventHandler); verify(mockedStub, times(1)).addEventHandler(request); } @Test public void testUpdateEventHandler() { EventHandler eventHandler = mock(EventHandler.class); EventHandlerPb.EventHandler eventHandlerPB = mock(EventHandlerPb.EventHandler.class); when(mockedProtoMapper.toProto(eventHandler)).thenReturn(eventHandlerPB); EventServicePb.UpdateEventHandlerRequest request = EventServicePb.UpdateEventHandlerRequest.newBuilder() .setHandler(eventHandlerPB) .build(); eventClient.updateEventHandler(eventHandler); verify(mockedStub, times(1)).updateEventHandler(request); } @Test public void testGetEventHandlers() { EventHandler eventHandler = mock(EventHandler.class); EventHandlerPb.EventHandler eventHandlerPB = mock(EventHandlerPb.EventHandler.class); when(mockedProtoMapper.fromProto(eventHandlerPB)).thenReturn(eventHandler); EventServicePb.GetEventHandlersForEventRequest request = EventServicePb.GetEventHandlersForEventRequest.newBuilder() .setEvent("test") .setActiveOnly(true) .build(); List<EventHandlerPb.EventHandler> result = new ArrayList<>(); result.add(eventHandlerPB); when(mockedStub.getEventHandlersForEvent(request)).thenReturn(result.iterator()); Iterator<EventHandler> response = eventClient.getEventHandlers("test", true); verify(mockedStub, times(1)).getEventHandlersForEvent(request); assertEquals(response.next(), eventHandler); } @Test public void testUnregisterEventHandler() { EventClient eventClient = createClientWithManagedChannel(); EventServicePb.RemoveEventHandlerRequest request = EventServicePb.RemoveEventHandlerRequest.newBuilder().setName("test").build(); eventClient.unregisterEventHandler("test"); verify(mockedStub, times(1)).removeEventHandler(request); } @Test public void testUnregisterEventHandlerWithManagedChannel() { EventServicePb.RemoveEventHandlerRequest request = EventServicePb.RemoveEventHandlerRequest.newBuilder().setName("test").build(); eventClient.unregisterEventHandler("test"); verify(mockedStub, times(1)).removeEventHandler(request); } public EventClient createClientWithManagedChannel() { EventClient eventClient = new EventClient("test", 0); ReflectionTestUtils.setField(eventClient, "stub", mockedStub); ReflectionTestUtils.setField(eventClient, "protoMapper", mockedProtoMapper); return eventClient; } }
6,806
0
Create_ds/conductor/grpc-client/src/test/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/test/java/com/netflix/conductor/client/grpc/TaskClientTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.TaskSummary; import com.netflix.conductor.grpc.ProtoMapper; import com.netflix.conductor.grpc.SearchPb; import com.netflix.conductor.grpc.TaskServiceGrpc; import com.netflix.conductor.grpc.TaskServicePb; import com.netflix.conductor.proto.TaskPb; import com.netflix.conductor.proto.TaskSummaryPb; import io.grpc.ManagedChannelBuilder; import static junit.framework.TestCase.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) public class TaskClientTest { @Mock ProtoMapper mockedProtoMapper; @Mock TaskServiceGrpc.TaskServiceBlockingStub mockedStub; TaskClient taskClient; @Before public void init() { taskClient = new TaskClient("test", 0); ReflectionTestUtils.setField(taskClient, "stub", mockedStub); ReflectionTestUtils.setField(taskClient, "protoMapper", mockedProtoMapper); } @Test public void testSearch() { TaskSummary taskSummary = mock(TaskSummary.class); TaskSummaryPb.TaskSummary taskSummaryPB = mock(TaskSummaryPb.TaskSummary.class); when(mockedProtoMapper.fromProto(taskSummaryPB)).thenReturn(taskSummary); TaskServicePb.TaskSummarySearchResult result = TaskServicePb.TaskSummarySearchResult.newBuilder() .addResults(taskSummaryPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder().setQuery("test query").build(); when(mockedStub.search(searchRequest)).thenReturn(result); SearchResult<TaskSummary> searchResult = taskClient.search("test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(taskSummary, searchResult.getResults().get(0)); } @Test public void testSearchV2() { Task task = mock(Task.class); TaskPb.Task taskPB = mock(TaskPb.Task.class); when(mockedProtoMapper.fromProto(taskPB)).thenReturn(task); TaskServicePb.TaskSearchResult result = TaskServicePb.TaskSearchResult.newBuilder() .addResults(taskPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder().setQuery("test query").build(); when(mockedStub.searchV2(searchRequest)).thenReturn(result); SearchResult<Task> searchResult = taskClient.searchV2("test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(task, searchResult.getResults().get(0)); } @Test public void testSearchWithParams() { TaskSummary taskSummary = mock(TaskSummary.class); TaskSummaryPb.TaskSummary taskSummaryPB = mock(TaskSummaryPb.TaskSummary.class); when(mockedProtoMapper.fromProto(taskSummaryPB)).thenReturn(taskSummary); TaskServicePb.TaskSummarySearchResult result = TaskServicePb.TaskSummarySearchResult.newBuilder() .addResults(taskSummaryPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder() .setStart(1) .setSize(5) .setSort("*") .setFreeText("*") .setQuery("test query") .build(); when(mockedStub.search(searchRequest)).thenReturn(result); SearchResult<TaskSummary> searchResult = taskClient.search(1, 5, "*", "*", "test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(taskSummary, searchResult.getResults().get(0)); } @Test public void testSearchV2WithParams() { Task task = mock(Task.class); TaskPb.Task taskPB = mock(TaskPb.Task.class); when(mockedProtoMapper.fromProto(taskPB)).thenReturn(task); TaskServicePb.TaskSearchResult result = TaskServicePb.TaskSearchResult.newBuilder() .addResults(taskPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder() .setStart(1) .setSize(5) .setSort("*") .setFreeText("*") .setQuery("test query") .build(); when(mockedStub.searchV2(searchRequest)).thenReturn(result); SearchResult<Task> searchResult = taskClient.searchV2(1, 5, "*", "*", "test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(task, searchResult.getResults().get(0)); } @Test public void testSearchWithChannelBuilder() { TaskClient taskClient = createClientWithManagedChannel(); TaskSummary taskSummary = mock(TaskSummary.class); TaskSummaryPb.TaskSummary taskSummaryPB = mock(TaskSummaryPb.TaskSummary.class); when(mockedProtoMapper.fromProto(taskSummaryPB)).thenReturn(taskSummary); TaskServicePb.TaskSummarySearchResult result = TaskServicePb.TaskSummarySearchResult.newBuilder() .addResults(taskSummaryPB) .setTotalHits(1) .build(); SearchPb.Request searchRequest = SearchPb.Request.newBuilder().setQuery("test query").build(); when(mockedStub.search(searchRequest)).thenReturn(result); SearchResult<TaskSummary> searchResult = taskClient.search("test query"); assertEquals(1, searchResult.getTotalHits()); assertEquals(taskSummary, searchResult.getResults().get(0)); } private TaskClient createClientWithManagedChannel() { TaskClient taskClient = new TaskClient(ManagedChannelBuilder.forAddress("test", 0)); ReflectionTestUtils.setField(taskClient, "stub", mockedStub); ReflectionTestUtils.setField(taskClient, "protoMapper", mockedProtoMapper); return taskClient; } }
6,807
0
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client/grpc/EventClient.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import java.util.Iterator; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.grpc.EventServiceGrpc; import com.netflix.conductor.grpc.EventServicePb; import com.netflix.conductor.proto.EventHandlerPb; import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; import io.grpc.ManagedChannelBuilder; public class EventClient extends ClientBase { private final EventServiceGrpc.EventServiceBlockingStub stub; public EventClient(String address, int port) { super(address, port); this.stub = EventServiceGrpc.newBlockingStub(this.channel); } public EventClient(ManagedChannelBuilder<?> builder) { super(builder); this.stub = EventServiceGrpc.newBlockingStub(this.channel); } /** * Register an event handler with the server * * @param eventHandler the event handler definition */ public void registerEventHandler(EventHandler eventHandler) { Preconditions.checkNotNull(eventHandler, "Event handler definition cannot be null"); stub.addEventHandler( EventServicePb.AddEventHandlerRequest.newBuilder() .setHandler(protoMapper.toProto(eventHandler)) .build()); } /** * Updates an existing event handler * * @param eventHandler the event handler to be updated */ public void updateEventHandler(EventHandler eventHandler) { Preconditions.checkNotNull(eventHandler, "Event handler definition cannot be null"); stub.updateEventHandler( EventServicePb.UpdateEventHandlerRequest.newBuilder() .setHandler(protoMapper.toProto(eventHandler)) .build()); } /** * @param event name of the event * @param activeOnly if true, returns only the active handlers * @return Returns the list of all the event handlers for a given event */ public Iterator<EventHandler> getEventHandlers(String event, boolean activeOnly) { Preconditions.checkArgument(StringUtils.isNotBlank(event), "Event cannot be blank"); EventServicePb.GetEventHandlersForEventRequest.Builder request = EventServicePb.GetEventHandlersForEventRequest.newBuilder() .setEvent(event) .setActiveOnly(activeOnly); Iterator<EventHandlerPb.EventHandler> it = stub.getEventHandlersForEvent(request.build()); return Iterators.transform(it, protoMapper::fromProto); } /** * Removes the event handler from the conductor server * * @param name the name of the event handler */ public void unregisterEventHandler(String name) { Preconditions.checkArgument(StringUtils.isNotBlank(name), "Name cannot be blank"); stub.removeEventHandler( EventServicePb.RemoveEventHandlerRequest.newBuilder().setName(name).build()); } }
6,808
0
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client/grpc/TaskClient.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskExecLog; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.TaskSummary; import com.netflix.conductor.grpc.SearchPb; import com.netflix.conductor.grpc.TaskServiceGrpc; import com.netflix.conductor.grpc.TaskServicePb; import com.netflix.conductor.proto.TaskPb; import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import io.grpc.ManagedChannelBuilder; public class TaskClient extends ClientBase { private final TaskServiceGrpc.TaskServiceBlockingStub stub; public TaskClient(String address, int port) { super(address, port); this.stub = TaskServiceGrpc.newBlockingStub(this.channel); } public TaskClient(ManagedChannelBuilder<?> builder) { super(builder); this.stub = TaskServiceGrpc.newBlockingStub(this.channel); } /** * Perform a poll for a task of a specific task type. * * @param taskType The taskType to poll for * @param domain The domain of the task type * @param workerId Name of the client worker. Used for logging. * @return Task waiting to be executed. */ public Task pollTask(String taskType, String workerId, String domain) { Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); Preconditions.checkArgument(StringUtils.isNotBlank(domain), "Domain cannot be blank"); Preconditions.checkArgument(StringUtils.isNotBlank(workerId), "Worker id cannot be blank"); TaskServicePb.PollResponse response = stub.poll( TaskServicePb.PollRequest.newBuilder() .setTaskType(taskType) .setWorkerId(workerId) .setDomain(domain) .build()); return protoMapper.fromProto(response.getTask()); } /** * Perform a batch poll for tasks by task type. Batch size is configurable by count. * * @param taskType Type of task to poll for * @param workerId Name of the client worker. Used for logging. * @param count Maximum number of tasks to be returned. Actual number of tasks returned can be * less than this number. * @param timeoutInMillisecond Long poll wait timeout. * @return List of tasks awaiting to be executed. */ public List<Task> batchPollTasksByTaskType( String taskType, String workerId, int count, int timeoutInMillisecond) { return Lists.newArrayList( batchPollTasksByTaskTypeAsync(taskType, workerId, count, timeoutInMillisecond)); } /** * Perform a batch poll for tasks by task type. Batch size is configurable by count. Returns an * iterator that streams tasks as they become available through GRPC. * * @param taskType Type of task to poll for * @param workerId Name of the client worker. Used for logging. * @param count Maximum number of tasks to be returned. Actual number of tasks returned can be * less than this number. * @param timeoutInMillisecond Long poll wait timeout. * @return Iterator of tasks awaiting to be executed. */ public Iterator<Task> batchPollTasksByTaskTypeAsync( String taskType, String workerId, int count, int timeoutInMillisecond) { Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); Preconditions.checkArgument(StringUtils.isNotBlank(workerId), "Worker id cannot be blank"); Preconditions.checkArgument(count > 0, "Count must be greater than 0"); Iterator<TaskPb.Task> it = stub.batchPoll( TaskServicePb.BatchPollRequest.newBuilder() .setTaskType(taskType) .setWorkerId(workerId) .setCount(count) .setTimeout(timeoutInMillisecond) .build()); return Iterators.transform(it, protoMapper::fromProto); } /** * Updates the result of a task execution. * * @param taskResult TaskResults to be updated. */ public void updateTask(TaskResult taskResult) { Preconditions.checkNotNull(taskResult, "Task result cannot be null"); stub.updateTask( TaskServicePb.UpdateTaskRequest.newBuilder() .setResult(protoMapper.toProto(taskResult)) .build()); } /** * Log execution messages for a task. * * @param taskId id of the task * @param logMessage the message to be logged */ public void logMessageForTask(String taskId, String logMessage) { Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); stub.addLog( TaskServicePb.AddLogRequest.newBuilder() .setTaskId(taskId) .setLog(logMessage) .build()); } /** * Fetch execution logs for a task. * * @param taskId id of the task. */ public List<TaskExecLog> getTaskLogs(String taskId) { Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); return stub .getTaskLogs( TaskServicePb.GetTaskLogsRequest.newBuilder().setTaskId(taskId).build()) .getLogsList() .stream() .map(protoMapper::fromProto) .collect(Collectors.toList()); } /** * Retrieve information about the task * * @param taskId ID of the task * @return Task details */ public Task getTaskDetails(String taskId) { Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); return protoMapper.fromProto( stub.getTask(TaskServicePb.GetTaskRequest.newBuilder().setTaskId(taskId).build()) .getTask()); } public int getQueueSizeForTask(String taskType) { Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); TaskServicePb.QueueSizesResponse sizes = stub.getQueueSizesForTasks( TaskServicePb.QueueSizesRequest.newBuilder() .addTaskTypes(taskType) .build()); return sizes.getQueueForTaskOrDefault(taskType, 0); } public SearchResult<TaskSummary> search(String query) { return search(null, null, null, null, query); } public SearchResult<Task> searchV2(String query) { return searchV2(null, null, null, null, query); } public SearchResult<TaskSummary> search( @Nullable Integer start, @Nullable Integer size, @Nullable String sort, @Nullable String freeText, @Nullable String query) { SearchPb.Request searchRequest = createSearchRequest(start, size, sort, freeText, query); TaskServicePb.TaskSummarySearchResult result = stub.search(searchRequest); return new SearchResult<>( result.getTotalHits(), result.getResultsList().stream() .map(protoMapper::fromProto) .collect(Collectors.toList())); } public SearchResult<Task> searchV2( @Nullable Integer start, @Nullable Integer size, @Nullable String sort, @Nullable String freeText, @Nullable String query) { SearchPb.Request searchRequest = createSearchRequest(start, size, sort, freeText, query); TaskServicePb.TaskSearchResult result = stub.searchV2(searchRequest); return new SearchResult<>( result.getTotalHits(), result.getResultsList().stream() .map(protoMapper::fromProto) .collect(Collectors.toList())); } }
6,809
0
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client/grpc/WorkflowClient.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.common.metadata.workflow.RerunWorkflowRequest; import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.common.run.WorkflowSummary; import com.netflix.conductor.grpc.SearchPb; import com.netflix.conductor.grpc.WorkflowServiceGrpc; import com.netflix.conductor.grpc.WorkflowServicePb; import com.netflix.conductor.proto.WorkflowPb; import com.google.common.base.Preconditions; import io.grpc.ManagedChannelBuilder; public class WorkflowClient extends ClientBase { private final WorkflowServiceGrpc.WorkflowServiceBlockingStub stub; public WorkflowClient(String address, int port) { super(address, port); this.stub = WorkflowServiceGrpc.newBlockingStub(this.channel); } public WorkflowClient(ManagedChannelBuilder<?> builder) { super(builder); this.stub = WorkflowServiceGrpc.newBlockingStub(this.channel); } /** * Starts a workflow * * @param startWorkflowRequest the {@link StartWorkflowRequest} object to start the workflow * @return the id of the workflow instance that can be used for tracking */ public String startWorkflow(StartWorkflowRequest startWorkflowRequest) { Preconditions.checkNotNull(startWorkflowRequest, "StartWorkflowRequest cannot be null"); return stub.startWorkflow(protoMapper.toProto(startWorkflowRequest)).getWorkflowId(); } /** * Retrieve a workflow by workflow id * * @param workflowId the id of the workflow * @param includeTasks specify if the tasks in the workflow need to be returned * @return the requested workflow */ public Workflow getWorkflow(String workflowId, boolean includeTasks) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); WorkflowPb.Workflow workflow = stub.getWorkflowStatus( WorkflowServicePb.GetWorkflowStatusRequest.newBuilder() .setWorkflowId(workflowId) .setIncludeTasks(includeTasks) .build()); return protoMapper.fromProto(workflow); } /** * Retrieve all workflows for a given correlation id and name * * @param name the name of the workflow * @param correlationId the correlation id * @param includeClosed specify if all workflows are to be returned or only running workflows * @param includeTasks specify if the tasks in the workflow need to be returned * @return list of workflows for the given correlation id and name */ public List<Workflow> getWorkflows( String name, String correlationId, boolean includeClosed, boolean includeTasks) { Preconditions.checkArgument(StringUtils.isNotBlank(name), "name cannot be blank"); Preconditions.checkArgument( StringUtils.isNotBlank(correlationId), "correlationId cannot be blank"); WorkflowServicePb.GetWorkflowsResponse workflows = stub.getWorkflows( WorkflowServicePb.GetWorkflowsRequest.newBuilder() .setName(name) .addCorrelationId(correlationId) .setIncludeClosed(includeClosed) .setIncludeTasks(includeTasks) .build()); if (!workflows.containsWorkflowsById(correlationId)) { return Collections.emptyList(); } return workflows.getWorkflowsByIdOrThrow(correlationId).getWorkflowsList().stream() .map(protoMapper::fromProto) .collect(Collectors.toList()); } /** * Removes a workflow from the system * * @param workflowId the id of the workflow to be deleted * @param archiveWorkflow flag to indicate if the workflow should be archived before deletion */ public void deleteWorkflow(String workflowId, boolean archiveWorkflow) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "Workflow id cannot be blank"); stub.removeWorkflow( WorkflowServicePb.RemoveWorkflowRequest.newBuilder() .setWorkflodId(workflowId) .setArchiveWorkflow(archiveWorkflow) .build()); } /* * Retrieve all running workflow instances for a given name and version * * @param workflowName the name of the workflow * @param version the version of the wokflow definition. Defaults to 1. * @return the list of running workflow instances */ public List<String> getRunningWorkflow(String workflowName, @Nullable Integer version) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowName), "Workflow name cannot be blank"); WorkflowServicePb.GetRunningWorkflowsResponse workflows = stub.getRunningWorkflows( WorkflowServicePb.GetRunningWorkflowsRequest.newBuilder() .setName(workflowName) .setVersion(version == null ? 1 : version) .build()); return workflows.getWorkflowIdsList(); } /** * Retrieve all workflow instances for a given workflow name between a specific time period * * @param workflowName the name of the workflow * @param version the version of the workflow definition. Defaults to 1. * @param startTime the start time of the period * @param endTime the end time of the period * @return returns a list of workflows created during the specified during the time period */ public List<String> getWorkflowsByTimePeriod( String workflowName, int version, Long startTime, Long endTime) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowName), "Workflow name cannot be blank"); Preconditions.checkNotNull(startTime, "Start time cannot be null"); Preconditions.checkNotNull(endTime, "End time cannot be null"); // TODO return null; } /* * Starts the decision task for the given workflow instance * * @param workflowId the id of the workflow instance */ public void runDecider(String workflowId) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.decideWorkflow( WorkflowServicePb.DecideWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .build()); } /** * Pause a workflow by workflow id * * @param workflowId the workflow id of the workflow to be paused */ public void pauseWorkflow(String workflowId) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.pauseWorkflow( WorkflowServicePb.PauseWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .build()); } /** * Resume a paused workflow by workflow id * * @param workflowId the workflow id of the paused workflow */ public void resumeWorkflow(String workflowId) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.resumeWorkflow( WorkflowServicePb.ResumeWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .build()); } /** * Skips a given task from a current RUNNING workflow * * @param workflowId the id of the workflow instance * @param taskReferenceName the reference name of the task to be skipped */ public void skipTaskFromWorkflow(String workflowId, String taskReferenceName) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); Preconditions.checkArgument( StringUtils.isNotBlank(taskReferenceName), "Task reference name cannot be blank"); stub.skipTaskFromWorkflow( WorkflowServicePb.SkipTaskRequest.newBuilder() .setWorkflowId(workflowId) .setTaskReferenceName(taskReferenceName) .build()); } /** * Reruns the workflow from a specific task * * @param rerunWorkflowRequest the request containing the task to rerun from * @return the id of the workflow */ public String rerunWorkflow(RerunWorkflowRequest rerunWorkflowRequest) { Preconditions.checkNotNull(rerunWorkflowRequest, "RerunWorkflowRequest cannot be null"); return stub.rerunWorkflow(protoMapper.toProto(rerunWorkflowRequest)).getWorkflowId(); } /** * Restart a completed workflow * * @param workflowId the workflow id of the workflow to be restarted */ public void restart(String workflowId, boolean useLatestDefinitions) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.restartWorkflow( WorkflowServicePb.RestartWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .setUseLatestDefinitions(useLatestDefinitions) .build()); } /** * Retries the last failed task in a workflow * * @param workflowId the workflow id of the workflow with the failed task */ public void retryLastFailedTask(String workflowId, boolean resumeSubworkflowTasks) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.retryWorkflow( WorkflowServicePb.RetryWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .setResumeSubworkflowTasks(resumeSubworkflowTasks) .build()); } /** * Resets the callback times of all IN PROGRESS tasks to 0 for the given workflow * * @param workflowId the id of the workflow */ public void resetCallbacksForInProgressTasks(String workflowId) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.resetWorkflowCallbacks( WorkflowServicePb.ResetWorkflowCallbacksRequest.newBuilder() .setWorkflowId(workflowId) .build()); } /** * Terminates the execution of the given workflow instance * * @param workflowId the id of the workflow to be terminated * @param reason the reason to be logged and displayed */ public void terminateWorkflow(String workflowId, String reason) { Preconditions.checkArgument( StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.terminateWorkflow( WorkflowServicePb.TerminateWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .setReason(reason) .build()); } /** * Search for workflows based on payload * * @param query the search query * @return the {@link SearchResult} containing the {@link WorkflowSummary} that match the query */ public SearchResult<WorkflowSummary> search(String query) { return search(null, null, null, null, query); } /** * Search for workflows based on payload * * @param query the search query * @return the {@link SearchResult} containing the {@link Workflow} that match the query */ public SearchResult<Workflow> searchV2(String query) { return searchV2(null, null, null, null, query); } /** * Paginated search for workflows based on payload * * @param start start value of page * @param size number of workflows to be returned * @param sort sort order * @param freeText additional free text query * @param query the search query * @return the {@link SearchResult} containing the {@link WorkflowSummary} that match the query */ public SearchResult<WorkflowSummary> search( @Nullable Integer start, @Nullable Integer size, @Nullable String sort, @Nullable String freeText, @Nullable String query) { SearchPb.Request searchRequest = createSearchRequest(start, size, sort, freeText, query); WorkflowServicePb.WorkflowSummarySearchResult result = stub.search(searchRequest); return new SearchResult<>( result.getTotalHits(), result.getResultsList().stream() .map(protoMapper::fromProto) .collect(Collectors.toList())); } /** * Paginated search for workflows based on payload * * @param start start value of page * @param size number of workflows to be returned * @param sort sort order * @param freeText additional free text query * @param query the search query * @return the {@link SearchResult} containing the {@link Workflow} that match the query */ public SearchResult<Workflow> searchV2( @Nullable Integer start, @Nullable Integer size, @Nullable String sort, @Nullable String freeText, @Nullable String query) { SearchPb.Request searchRequest = createSearchRequest(start, size, sort, freeText, query); WorkflowServicePb.WorkflowSearchResult result = stub.searchV2(searchRequest); return new SearchResult<>( result.getTotalHits(), result.getResultsList().stream() .map(protoMapper::fromProto) .collect(Collectors.toList())); } }
6,810
0
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client/grpc/MetadataClient.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import java.util.List; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.grpc.MetadataServiceGrpc; import com.netflix.conductor.grpc.MetadataServicePb; import com.google.common.base.Preconditions; import io.grpc.ManagedChannelBuilder; public class MetadataClient extends ClientBase { private final MetadataServiceGrpc.MetadataServiceBlockingStub stub; public MetadataClient(String address, int port) { super(address, port); this.stub = MetadataServiceGrpc.newBlockingStub(this.channel); } public MetadataClient(ManagedChannelBuilder<?> builder) { super(builder); this.stub = MetadataServiceGrpc.newBlockingStub(this.channel); } /** * Register a workflow definition with the server * * @param workflowDef the workflow definition */ public void registerWorkflowDef(WorkflowDef workflowDef) { Preconditions.checkNotNull(workflowDef, "Worfklow definition cannot be null"); stub.createWorkflow( MetadataServicePb.CreateWorkflowRequest.newBuilder() .setWorkflow(protoMapper.toProto(workflowDef)) .build()); } /** * Updates a list of existing workflow definitions * * @param workflowDefs List of workflow definitions to be updated */ public void updateWorkflowDefs(List<WorkflowDef> workflowDefs) { Preconditions.checkNotNull(workflowDefs, "Workflow defs list cannot be null"); stub.updateWorkflows( MetadataServicePb.UpdateWorkflowsRequest.newBuilder() .addAllDefs(workflowDefs.stream().map(protoMapper::toProto)::iterator) .build()); } /** * Retrieve the workflow definition * * @param name the name of the workflow * @param version the version of the workflow def * @return Workflow definition for the given workflow and version */ public WorkflowDef getWorkflowDef(String name, @Nullable Integer version) { Preconditions.checkArgument(StringUtils.isNotBlank(name), "name cannot be blank"); MetadataServicePb.GetWorkflowRequest.Builder request = MetadataServicePb.GetWorkflowRequest.newBuilder().setName(name); if (version != null) { request.setVersion(version); } return protoMapper.fromProto(stub.getWorkflow(request.build()).getWorkflow()); } /** * Registers a list of task types with the conductor server * * @param taskDefs List of task types to be registered. */ public void registerTaskDefs(List<TaskDef> taskDefs) { Preconditions.checkNotNull(taskDefs, "Task defs list cannot be null"); stub.createTasks( MetadataServicePb.CreateTasksRequest.newBuilder() .addAllDefs(taskDefs.stream().map(protoMapper::toProto)::iterator) .build()); } /** * Updates an existing task definition * * @param taskDef the task definition to be updated */ public void updateTaskDef(TaskDef taskDef) { Preconditions.checkNotNull(taskDef, "Task definition cannot be null"); stub.updateTask( MetadataServicePb.UpdateTaskRequest.newBuilder() .setTask(protoMapper.toProto(taskDef)) .build()); } /** * Retrieve the task definition of a given task type * * @param taskType type of task for which to retrieve the definition * @return Task Definition for the given task type */ public TaskDef getTaskDef(String taskType) { Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); return protoMapper.fromProto( stub.getTask( MetadataServicePb.GetTaskRequest.newBuilder() .setTaskType(taskType) .build()) .getTask()); } /** * Removes the task definition of a task type from the conductor server. Use with caution. * * @param taskType Task type to be unregistered. */ public void unregisterTaskDef(String taskType) { Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); stub.deleteTask( MetadataServicePb.DeleteTaskRequest.newBuilder().setTaskType(taskType).build()); } }
6,811
0
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client
Create_ds/conductor/grpc-client/src/main/java/com/netflix/conductor/client/grpc/ClientBase.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.client.grpc; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.grpc.ProtoMapper; import com.netflix.conductor.grpc.SearchPb; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; abstract class ClientBase { private static final Logger LOGGER = LoggerFactory.getLogger(ClientBase.class); protected static ProtoMapper protoMapper = ProtoMapper.INSTANCE; protected final ManagedChannel channel; public ClientBase(String address, int port) { this(ManagedChannelBuilder.forAddress(address, port).usePlaintext()); } public ClientBase(ManagedChannelBuilder<?> builder) { channel = builder.build(); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } SearchPb.Request createSearchRequest( @Nullable Integer start, @Nullable Integer size, @Nullable String sort, @Nullable String freeText, @Nullable String query) { SearchPb.Request.Builder request = SearchPb.Request.newBuilder(); if (start != null) request.setStart(start); if (size != null) request.setSize(size); if (sort != null) request.setSort(sort); if (freeText != null) request.setFreeText(freeText); if (query != null) request.setQuery(query); return request.build(); } }
6,812
0
Create_ds/conductor/awssqs-event-queue/src/test/java/com/netflix/conductor/sqs
Create_ds/conductor/awssqs-event-queue/src/test/java/com/netflix/conductor/sqs/eventqueue/SQSObservableQueueTest.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sqs.eventqueue; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.mockito.stubbing.Answer; import com.netflix.conductor.core.events.queue.Message; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.model.ListQueuesRequest; import com.amazonaws.services.sqs.model.ListQueuesResult; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import com.google.common.util.concurrent.Uninterruptibles; import rx.Observable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SQSObservableQueueTest { @Test public void test() { List<Message> messages = new LinkedList<>(); Observable.range(0, 10) .forEach((Integer x) -> messages.add(new Message("" + x, "payload: " + x, null))); assertEquals(10, messages.size()); SQSObservableQueue queue = mock(SQSObservableQueue.class); when(queue.getOrCreateQueue()).thenReturn("junit_queue_url"); Answer<?> answer = (Answer<List<Message>>) invocation -> Collections.emptyList(); when(queue.receiveMessages()).thenReturn(messages).thenAnswer(answer); when(queue.isRunning()).thenReturn(true); when(queue.getOnSubscribe()).thenCallRealMethod(); when(queue.observe()).thenCallRealMethod(); List<Message> found = new LinkedList<>(); Observable<Message> observable = queue.observe(); assertNotNull(observable); observable.subscribe(found::add); Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS); assertEquals(messages.size(), found.size()); assertEquals(messages, found); } @Test public void testException() { com.amazonaws.services.sqs.model.Message message = new com.amazonaws.services.sqs.model.Message() .withMessageId("test") .withBody("") .withReceiptHandle("receiptHandle"); Answer<?> answer = (Answer<ReceiveMessageResult>) invocation -> new ReceiveMessageResult(); AmazonSQS client = mock(AmazonSQS.class); when(client.listQueues(any(ListQueuesRequest.class))) .thenReturn(new ListQueuesResult().withQueueUrls("junit_queue_url")); when(client.receiveMessage(any(ReceiveMessageRequest.class))) .thenThrow(new RuntimeException("Error in SQS communication")) .thenReturn(new ReceiveMessageResult().withMessages(message)) .thenAnswer(answer); SQSObservableQueue queue = new SQSObservableQueue.Builder().withQueueName("junit").withClient(client).build(); queue.start(); List<Message> found = new LinkedList<>(); Observable<Message> observable = queue.observe(); assertNotNull(observable); observable.subscribe(found::add); Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS); assertEquals(1, found.size()); } }
6,813
0
Create_ds/conductor/awssqs-event-queue/src/test/java/com/netflix/conductor/sqs
Create_ds/conductor/awssqs-event-queue/src/test/java/com/netflix/conductor/sqs/eventqueue/DefaultEventQueueProcessorTest.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sqs.eventqueue; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.core.events.queue.DefaultEventQueueProcessor; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.core.execution.WorkflowExecutor; import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.model.TaskModel.Status; import com.netflix.conductor.model.WorkflowModel; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.util.concurrent.Uninterruptibles; import static com.netflix.conductor.common.metadata.tasks.TaskType.TASK_TYPE_WAIT; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @SuppressWarnings("unchecked") @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class DefaultEventQueueProcessorTest { private static SQSObservableQueue queue; private static WorkflowExecutor workflowExecutor; private DefaultEventQueueProcessor defaultEventQueueProcessor; @Autowired private ObjectMapper objectMapper; private static final List<Message> messages = new LinkedList<>(); private static final List<TaskResult> updatedTasks = new LinkedList<>(); private static final List<Task> mappedTasks = new LinkedList<>(); @Before public void init() { Map<Status, ObservableQueue> queues = new HashMap<>(); queues.put(Status.COMPLETED, queue); defaultEventQueueProcessor = new DefaultEventQueueProcessor(queues, workflowExecutor, objectMapper); } @BeforeClass public static void setup() { queue = mock(SQSObservableQueue.class); when(queue.getOrCreateQueue()).thenReturn("junit_queue_url"); when(queue.isRunning()).thenReturn(true); Answer<?> answer = (Answer<List<Message>>) invocation -> { List<Message> copy = new LinkedList<>(messages); messages.clear(); return copy; }; when(queue.receiveMessages()).thenAnswer(answer); when(queue.getOnSubscribe()).thenCallRealMethod(); when(queue.observe()).thenCallRealMethod(); when(queue.getName()).thenReturn(Status.COMPLETED.name()); TaskModel task0 = new TaskModel(); task0.setStatus(Status.IN_PROGRESS); task0.setTaskId("t0"); task0.setReferenceTaskName("t0"); task0.setTaskType(TASK_TYPE_WAIT); WorkflowModel workflow0 = new WorkflowModel(); workflow0.setWorkflowId("v_0"); workflow0.getTasks().add(task0); TaskModel task2 = new TaskModel(); task2.setStatus(Status.IN_PROGRESS); task2.setTaskId("t2"); task2.setTaskType(TASK_TYPE_WAIT); WorkflowModel workflow2 = new WorkflowModel(); workflow2.setWorkflowId("v_2"); workflow2.getTasks().add(task2); doAnswer( (Answer<Void>) invocation -> { List<Message> msgs = invocation.getArgument(0, List.class); messages.addAll(msgs); return null; }) .when(queue) .publish(any()); workflowExecutor = mock(WorkflowExecutor.class); assertNotNull(workflowExecutor); doReturn(workflow0).when(workflowExecutor).getWorkflow(eq("v_0"), anyBoolean()); doReturn(workflow2).when(workflowExecutor).getWorkflow(eq("v_2"), anyBoolean()); doAnswer( (Answer<Void>) invocation -> { updatedTasks.add(invocation.getArgument(0, TaskResult.class)); return null; }) .when(workflowExecutor) .updateTask(any(TaskResult.class)); } @Test public void test() throws Exception { defaultEventQueueProcessor.updateByTaskRefName( "v_0", "t0", new HashMap<>(), Status.COMPLETED); Uninterruptibles.sleepUninterruptibly(1_000, TimeUnit.MILLISECONDS); assertTrue(updatedTasks.stream().anyMatch(task -> task.getTaskId().equals("t0"))); } @Test(expected = IllegalArgumentException.class) public void testFailure() throws Exception { defaultEventQueueProcessor.updateByTaskRefName( "v_1", "t1", new HashMap<>(), Status.CANCELED); Uninterruptibles.sleepUninterruptibly(1_000, TimeUnit.MILLISECONDS); } @Test public void testWithTaskId() throws Exception { defaultEventQueueProcessor.updateByTaskId("v_2", "t2", new HashMap<>(), Status.COMPLETED); Uninterruptibles.sleepUninterruptibly(1_000, TimeUnit.MILLISECONDS); assertTrue(updatedTasks.stream().anyMatch(task -> task.getTaskId().equals("t2"))); } }
6,814
0
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/eventqueue/SQSObservableQueue.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sqs.eventqueue; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.metrics.Monitors; import com.amazonaws.auth.policy.Action; import com.amazonaws.auth.policy.Policy; import com.amazonaws.auth.policy.Principal; import com.amazonaws.auth.policy.Resource; import com.amazonaws.auth.policy.Statement; import com.amazonaws.auth.policy.Statement.Effect; import com.amazonaws.auth.policy.actions.SQSActions; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.model.BatchResultErrorEntry; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityRequest; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.CreateQueueResult; import com.amazonaws.services.sqs.model.DeleteMessageBatchRequest; import com.amazonaws.services.sqs.model.DeleteMessageBatchRequestEntry; import com.amazonaws.services.sqs.model.DeleteMessageBatchResult; import com.amazonaws.services.sqs.model.GetQueueAttributesResult; import com.amazonaws.services.sqs.model.ListQueuesRequest; import com.amazonaws.services.sqs.model.ListQueuesResult; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import com.amazonaws.services.sqs.model.SendMessageBatchRequest; import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry; import com.amazonaws.services.sqs.model.SendMessageBatchResult; import com.amazonaws.services.sqs.model.SetQueueAttributesResult; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Scheduler; public class SQSObservableQueue implements ObservableQueue { private static final Logger LOGGER = LoggerFactory.getLogger(SQSObservableQueue.class); private static final String QUEUE_TYPE = "sqs"; private final String queueName; private final int visibilityTimeoutInSeconds; private final int batchSize; private final AmazonSQS client; private final long pollTimeInMS; private final String queueURL; private final Scheduler scheduler; private volatile boolean running; private SQSObservableQueue( String queueName, AmazonSQS client, int visibilityTimeoutInSeconds, int batchSize, long pollTimeInMS, List<String> accountsToAuthorize, Scheduler scheduler) { this.queueName = queueName; this.client = client; this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds; this.batchSize = batchSize; this.pollTimeInMS = pollTimeInMS; this.queueURL = getOrCreateQueue(); this.scheduler = scheduler; addPolicy(accountsToAuthorize); } @Override public Observable<Message> observe() { OnSubscribe<Message> subscriber = getOnSubscribe(); return Observable.create(subscriber); } @Override public List<String> ack(List<Message> messages) { return delete(messages); } @Override public void publish(List<Message> messages) { publishMessages(messages); } @Override public long size() { GetQueueAttributesResult attributes = client.getQueueAttributes( queueURL, Collections.singletonList("ApproximateNumberOfMessages")); String sizeAsStr = attributes.getAttributes().get("ApproximateNumberOfMessages"); try { return Long.parseLong(sizeAsStr); } catch (Exception e) { return -1; } } @Override public void setUnackTimeout(Message message, long unackTimeout) { int unackTimeoutInSeconds = (int) (unackTimeout / 1000); ChangeMessageVisibilityRequest request = new ChangeMessageVisibilityRequest( queueURL, message.getReceipt(), unackTimeoutInSeconds); client.changeMessageVisibility(request); } @Override public String getType() { return QUEUE_TYPE; } @Override public String getName() { return queueName; } @Override public String getURI() { return queueURL; } public long getPollTimeInMS() { return pollTimeInMS; } public int getBatchSize() { return batchSize; } public int getVisibilityTimeoutInSeconds() { return visibilityTimeoutInSeconds; } @Override public void start() { LOGGER.info("Started listening to {}:{}", getClass().getSimpleName(), queueName); running = true; } @Override public void stop() { LOGGER.info("Stopped listening to {}:{}", getClass().getSimpleName(), queueName); running = false; } @Override public boolean isRunning() { return running; } public static class Builder { private String queueName; private int visibilityTimeout = 30; // seconds private int batchSize = 5; private long pollTimeInMS = 100; private AmazonSQS client; private List<String> accountsToAuthorize = new LinkedList<>(); private Scheduler scheduler; public Builder withQueueName(String queueName) { this.queueName = queueName; return this; } /** * @param visibilityTimeout Visibility timeout for the message in SECONDS * @return builder instance */ public Builder withVisibilityTimeout(int visibilityTimeout) { this.visibilityTimeout = visibilityTimeout; return this; } public Builder withBatchSize(int batchSize) { this.batchSize = batchSize; return this; } public Builder withClient(AmazonSQS client) { this.client = client; return this; } public Builder withPollTimeInMS(long pollTimeInMS) { this.pollTimeInMS = pollTimeInMS; return this; } public Builder withAccountsToAuthorize(List<String> accountsToAuthorize) { this.accountsToAuthorize = accountsToAuthorize; return this; } public Builder addAccountToAuthorize(String accountToAuthorize) { this.accountsToAuthorize.add(accountToAuthorize); return this; } public Builder withScheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } public SQSObservableQueue build() { return new SQSObservableQueue( queueName, client, visibilityTimeout, batchSize, pollTimeInMS, accountsToAuthorize, scheduler); } } // Private methods String getOrCreateQueue() { List<String> queueUrls = listQueues(queueName); if (queueUrls == null || queueUrls.isEmpty()) { CreateQueueRequest createQueueRequest = new CreateQueueRequest().withQueueName(queueName); CreateQueueResult result = client.createQueue(createQueueRequest); return result.getQueueUrl(); } else { return queueUrls.get(0); } } private String getQueueARN() { GetQueueAttributesResult response = client.getQueueAttributes(queueURL, Collections.singletonList("QueueArn")); return response.getAttributes().get("QueueArn"); } private void addPolicy(List<String> accountsToAuthorize) { if (accountsToAuthorize == null || accountsToAuthorize.isEmpty()) { LOGGER.info("No additional security policies attached for the queue " + queueName); return; } LOGGER.info("Authorizing " + accountsToAuthorize + " to the queue " + queueName); Map<String, String> attributes = new HashMap<>(); attributes.put("Policy", getPolicy(accountsToAuthorize)); SetQueueAttributesResult result = client.setQueueAttributes(queueURL, attributes); LOGGER.info("policy attachment result: " + result); LOGGER.info( "policy attachment result: status=" + result.getSdkHttpMetadata().getHttpStatusCode()); } private String getPolicy(List<String> accountIds) { Policy policy = new Policy("AuthorizedWorkerAccessPolicy"); Statement stmt = new Statement(Effect.Allow); Action action = SQSActions.SendMessage; stmt.getActions().add(action); stmt.setResources(new LinkedList<>()); for (String accountId : accountIds) { Principal principal = new Principal(accountId); stmt.getPrincipals().add(principal); } stmt.getResources().add(new Resource(getQueueARN())); policy.getStatements().add(stmt); return policy.toJson(); } private List<String> listQueues(String queueName) { ListQueuesRequest listQueuesRequest = new ListQueuesRequest().withQueueNamePrefix(queueName); ListQueuesResult resultList = client.listQueues(listQueuesRequest); return resultList.getQueueUrls().stream() .filter(queueUrl -> queueUrl.contains(queueName)) .collect(Collectors.toList()); } private void publishMessages(List<Message> messages) { LOGGER.debug("Sending {} messages to the SQS queue: {}", messages.size(), queueName); SendMessageBatchRequest batch = new SendMessageBatchRequest(queueURL); messages.forEach( msg -> { SendMessageBatchRequestEntry sendr = new SendMessageBatchRequestEntry(msg.getId(), msg.getPayload()); batch.getEntries().add(sendr); }); LOGGER.debug("sending {} messages in batch", batch.getEntries().size()); SendMessageBatchResult result = client.sendMessageBatch(batch); LOGGER.debug("send result: {} for SQS queue: {}", result.getFailed().toString(), queueName); } List<Message> receiveMessages() { try { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest() .withQueueUrl(queueURL) .withVisibilityTimeout(visibilityTimeoutInSeconds) .withMaxNumberOfMessages(batchSize); ReceiveMessageResult result = client.receiveMessage(receiveMessageRequest); List<Message> messages = result.getMessages().stream() .map( msg -> new Message( msg.getMessageId(), msg.getBody(), msg.getReceiptHandle())) .collect(Collectors.toList()); Monitors.recordEventQueueMessagesProcessed(QUEUE_TYPE, this.queueName, messages.size()); return messages; } catch (Exception e) { LOGGER.error("Exception while getting messages from SQS", e); Monitors.recordObservableQMessageReceivedErrors(QUEUE_TYPE); } return new ArrayList<>(); } OnSubscribe<Message> getOnSubscribe() { return subscriber -> { Observable<Long> interval = Observable.interval(pollTimeInMS, TimeUnit.MILLISECONDS); interval.flatMap( (Long x) -> { if (!isRunning()) { LOGGER.debug( "Component stopped, skip listening for messages from SQS"); return Observable.from(Collections.emptyList()); } List<Message> messages = receiveMessages(); return Observable.from(messages); }) .subscribe(subscriber::onNext, subscriber::onError); }; } private List<String> delete(List<Message> messages) { if (messages == null || messages.isEmpty()) { return null; } DeleteMessageBatchRequest batch = new DeleteMessageBatchRequest().withQueueUrl(queueURL); List<DeleteMessageBatchRequestEntry> entries = batch.getEntries(); messages.forEach( m -> entries.add( new DeleteMessageBatchRequestEntry() .withId(m.getId()) .withReceiptHandle(m.getReceipt()))); DeleteMessageBatchResult result = client.deleteMessageBatch(batch); List<String> failures = result.getFailed().stream() .map(BatchResultErrorEntry::getId) .collect(Collectors.toList()); LOGGER.debug("Failed to delete messages from queue: {}: {}", queueName, failures); return failures; } }
6,815
0
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueProperties.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sqs.config; import java.time.Duration; import java.time.temporal.ChronoUnit; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.convert.DurationUnit; @ConfigurationProperties("conductor.event-queues.sqs") public class SQSEventQueueProperties { /** The maximum number of messages to be fetched from the queue in a single request */ private int batchSize = 1; /** The polling interval (in milliseconds) */ private Duration pollTimeDuration = Duration.ofMillis(100); /** The visibility timeout (in seconds) for the message on the queue */ @DurationUnit(ChronoUnit.SECONDS) private Duration visibilityTimeout = Duration.ofSeconds(60); /** The prefix to be used for the default listener queues */ private String listenerQueuePrefix = ""; /** The AWS account Ids authorized to send messages to the queues */ private String authorizedAccounts = ""; /** The endpoint to use to connect to a local SQS server for testing */ private String endpoint = ""; public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public Duration getPollTimeDuration() { return pollTimeDuration; } public void setPollTimeDuration(Duration pollTimeDuration) { this.pollTimeDuration = pollTimeDuration; } public Duration getVisibilityTimeout() { return visibilityTimeout; } public void setVisibilityTimeout(Duration visibilityTimeout) { this.visibilityTimeout = visibilityTimeout; } public String getListenerQueuePrefix() { return listenerQueuePrefix; } public void setListenerQueuePrefix(String listenerQueuePrefix) { this.listenerQueuePrefix = listenerQueuePrefix; } public String getAuthorizedAccounts() { return authorizedAccounts; } public void setAuthorizedAccounts(String authorizedAccounts) { this.authorizedAccounts = authorizedAccounts; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } }
6,816
0
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueConfiguration.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sqs.config; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.core.events.EventQueueProvider; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.model.TaskModel.Status; import com.netflix.conductor.sqs.eventqueue.SQSObservableQueue.Builder; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import rx.Scheduler; @Configuration @EnableConfigurationProperties(SQSEventQueueProperties.class) @ConditionalOnProperty(name = "conductor.event-queues.sqs.enabled", havingValue = "true") public class SQSEventQueueConfiguration { @Autowired private SQSEventQueueProperties sqsProperties; private static final Logger LOGGER = LoggerFactory.getLogger(SQSEventQueueConfiguration.class); @Bean AWSCredentialsProvider createAWSCredentialsProvider() { return new DefaultAWSCredentialsProviderChain(); } @ConditionalOnMissingBean @Bean public AmazonSQS getSQSClient(AWSCredentialsProvider credentialsProvider) { AmazonSQSClientBuilder builder = AmazonSQSClientBuilder.standard().withCredentials(credentialsProvider); if (!sqsProperties.getEndpoint().isEmpty()) { LOGGER.info("Setting custom SQS endpoint to {}", sqsProperties.getEndpoint()); builder.withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration( sqsProperties.getEndpoint(), System.getenv("AWS_REGION"))); } return builder.build(); } @Bean public EventQueueProvider sqsEventQueueProvider( AmazonSQS sqsClient, SQSEventQueueProperties properties, Scheduler scheduler) { return new SQSEventQueueProvider(sqsClient, properties, scheduler); } @ConditionalOnProperty( name = "conductor.default-event-queue.type", havingValue = "sqs", matchIfMissing = true) @Bean public Map<Status, ObservableQueue> getQueues( ConductorProperties conductorProperties, SQSEventQueueProperties properties, AmazonSQS sqsClient) { String stack = ""; if (conductorProperties.getStack() != null && conductorProperties.getStack().length() > 0) { stack = conductorProperties.getStack() + "_"; } Status[] statuses = new Status[] {Status.COMPLETED, Status.FAILED}; Map<Status, ObservableQueue> queues = new HashMap<>(); for (Status status : statuses) { String queuePrefix = StringUtils.isBlank(properties.getListenerQueuePrefix()) ? conductorProperties.getAppId() + "_sqs_notify_" + stack : properties.getListenerQueuePrefix(); String queueName = queuePrefix + status.name(); Builder builder = new Builder().withClient(sqsClient).withQueueName(queueName); String auth = properties.getAuthorizedAccounts(); String[] accounts = auth.split(","); for (String accountToAuthorize : accounts) { accountToAuthorize = accountToAuthorize.trim(); if (accountToAuthorize.length() > 0) { builder.addAccountToAuthorize(accountToAuthorize.trim()); } } ObservableQueue queue = builder.build(); queues.put(status, queue); } return queues; } }
6,817
0
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs
Create_ds/conductor/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueProvider.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sqs.config; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.lang.NonNull; import com.netflix.conductor.core.events.EventQueueProvider; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.sqs.eventqueue.SQSObservableQueue; import com.amazonaws.services.sqs.AmazonSQS; import rx.Scheduler; public class SQSEventQueueProvider implements EventQueueProvider { private final Map<String, ObservableQueue> queues = new ConcurrentHashMap<>(); private final AmazonSQS client; private final int batchSize; private final long pollTimeInMS; private final int visibilityTimeoutInSeconds; private final Scheduler scheduler; public SQSEventQueueProvider( AmazonSQS client, SQSEventQueueProperties properties, Scheduler scheduler) { this.client = client; this.batchSize = properties.getBatchSize(); this.pollTimeInMS = properties.getPollTimeDuration().toMillis(); this.visibilityTimeoutInSeconds = (int) properties.getVisibilityTimeout().getSeconds(); this.scheduler = scheduler; } @Override public String getQueueType() { return "sqs"; } @Override @NonNull public ObservableQueue getQueue(String queueURI) { return queues.computeIfAbsent( queueURI, q -> new SQSObservableQueue.Builder() .withBatchSize(this.batchSize) .withClient(client) .withPollTimeInMS(this.pollTimeInMS) .withQueueName(queueURI) .withVisibilityTimeout(this.visibilityTimeoutInSeconds) .withScheduler(scheduler) .build()); } }
6,818
0
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example/shipment/Order.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.example.shipment; import java.math.BigDecimal; public class Order { public enum ShippingMethod { GROUND, NEXT_DAY_AIR, SAME_DAY } private String orderNumber; private String sku; private int quantity; private BigDecimal unitPrice; private String zipCode; private String countryCode; private ShippingMethod shippingMethod; public Order(String orderNumber, String sku, int quantity, BigDecimal unitPrice) { this.orderNumber = orderNumber; this.sku = sku; this.quantity = quantity; this.unitPrice = unitPrice; } public Order() {} public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public BigDecimal getUnitPrice() { return unitPrice; } public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public ShippingMethod getShippingMethod() { return shippingMethod; } public void setShippingMethod(ShippingMethod shippingMethod) { this.shippingMethod = shippingMethod; } }
6,819
0
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example/shipment/Shipment.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.example.shipment; public class Shipment { private String userId; private String orderNo; public Shipment(String userId, String orderNo) { this.userId = userId; this.orderNo = orderNo; } public Shipment() {} public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } }
6,820
0
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example/shipment/ShipmentState.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.example.shipment; public class ShipmentState { private boolean paymentCompleted; private boolean emailSent; private boolean shipped; private String trackingNumber; public boolean isPaymentCompleted() { return paymentCompleted; } public void setPaymentCompleted(boolean paymentCompleted) { this.paymentCompleted = paymentCompleted; } public boolean isEmailSent() { return emailSent; } public void setEmailSent(boolean emailSent) { this.emailSent = emailSent; } public boolean isShipped() { return shipped; } public void setShipped(boolean shipped) { this.shipped = shipped; } public String getTrackingNumber() { return trackingNumber; } public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; } }
6,821
0
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example/shipment/User.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.example.shipment; public class User { private String name; private String email; private String addressLine; private String city; private String zipCode; private String countryCode; private String billingType; private String billingId; public User( String name, String email, String addressLine, String city, String zipCode, String countryCode, String billingType, String billingId) { this.name = name; this.email = email; this.addressLine = addressLine; this.city = city; this.zipCode = zipCode; this.countryCode = countryCode; this.billingType = billingType; this.billingId = billingId; } public User() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddressLine() { return addressLine; } public void setAddressLine(String addressLine) { this.addressLine = addressLine; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public String getBillingType() { return billingType; } public void setBillingType(String billingType) { this.billingType = billingType; } public String getBillingId() { return billingId; } public void setBillingId(String billingId) { this.billingId = billingId; } }
6,822
0
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example/shipment/ShipmentWorkers.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.example.shipment; import java.math.BigDecimal; import java.util.*; import com.netflix.conductor.sdk.workflow.def.tasks.DynamicForkInput; import com.netflix.conductor.sdk.workflow.def.tasks.SubWorkflow; import com.netflix.conductor.sdk.workflow.def.tasks.Task; import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.task.OutputParam; import com.netflix.conductor.sdk.workflow.task.WorkerTask; public class ShipmentWorkers { @WorkerTask(value = "generateDynamicFork", threadCount = 3) public DynamicForkInput generateDynamicFork( @InputParam("orderDetails") List<Order> orderDetails, @InputParam("userDetails") User userDetails) { DynamicForkInput input = new DynamicForkInput(); List<Task<?>> tasks = new ArrayList<>(); Map<String, Object> inputs = new HashMap<>(); for (int i = 0; i < orderDetails.size(); i++) { Order detail = orderDetails.get(i); String referenceName = "order_flow_sub_" + i; tasks.add( new SubWorkflow(referenceName, "order_flow", null) .input("orderDetail", detail) .input("userDetails", userDetails)); inputs.put(referenceName, new HashMap<>()); } input.setInputs(inputs); input.setTasks(tasks); return input; } @WorkerTask(value = "get_order_details", threadCount = 5) public List<Order> getOrderDetails(@InputParam("orderNo") String orderNo) { int lineItemCount = new Random().nextInt(10); List<Order> orderDetails = new ArrayList<>(); for (int i = 0; i < lineItemCount; i++) { Order orderDetail = new Order(orderNo, "sku_" + i, 2, BigDecimal.valueOf(20.5)); orderDetail.setOrderNumber(UUID.randomUUID().toString()); orderDetail.setCountryCode(i % 2 == 0 ? "US" : "CA"); if (i % 3 == 0) { orderDetail.setCountryCode("UK"); } if (orderDetail.getCountryCode().equals("US")) orderDetail.setShippingMethod(Order.ShippingMethod.SAME_DAY); else if (orderDetail.getCountryCode().equals("CA")) orderDetail.setShippingMethod(Order.ShippingMethod.NEXT_DAY_AIR); else orderDetail.setShippingMethod(Order.ShippingMethod.GROUND); orderDetails.add(orderDetail); } return orderDetails; } @WorkerTask("get_user_details") public User getUserDetails(@InputParam("userId") String userId) { User user = new User( "User Name", userId + "@example.com", "1234 forline street", "mountain view", "95030", "US", "Paypal", "biling_001"); return user; } @WorkerTask("calculate_tax_and_total") public @OutputParam("total_amount") BigDecimal calculateTax( @InputParam("orderDetail") Order orderDetails) { BigDecimal preTaxAmount = orderDetails.getUnitPrice().multiply(new BigDecimal(orderDetails.getQuantity())); BigDecimal tax = BigDecimal.valueOf(0.2).multiply(preTaxAmount); if (!"US".equals(orderDetails.getCountryCode())) { tax = BigDecimal.ZERO; } return preTaxAmount.add(tax); } @WorkerTask("ground_shipping_label") public @OutputParam("reference_number") String prepareGroundShipping( @InputParam("name") String name, @InputParam("address") String address, @InputParam("orderNo") String orderNo) { return "Ground_" + orderNo; } @WorkerTask("air_shipping_label") public @OutputParam("reference_number") String prepareAirShipping( @InputParam("name") String name, @InputParam("address") String address, @InputParam("orderNo") String orderNo) { return "Air_" + orderNo; } @WorkerTask("same_day_shipping_label") public @OutputParam("reference_number") String prepareSameDayShipping( @InputParam("name") String name, @InputParam("address") String address, @InputParam("orderNo") String orderNo) { return "SameDay_" + orderNo; } @WorkerTask("charge_payment") public @OutputParam("reference") String chargePayment( @InputParam("amount") BigDecimal amount, @InputParam("billingId") String billingId, @InputParam("billingType") String billingType) { return UUID.randomUUID().toString(); } @WorkerTask("send_email") public void sendEmail( @InputParam("name") String name, @InputParam("email") String email, @InputParam("orderNo") String orderNo) {} }
6,823
0
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example
Create_ds/conductor/java-sdk/example/java/com/netflix/conductor/sdk/example/shipment/ShipmentWorkflow.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.example.shipment; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; import com.netflix.conductor.sdk.workflow.def.WorkflowBuilder; import com.netflix.conductor.sdk.workflow.def.tasks.*; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; public class ShipmentWorkflow { private final WorkflowExecutor executor; public ShipmentWorkflow(WorkflowExecutor executor) { this.executor = executor; this.executor.initWorkers(ShipmentWorkflow.class.getPackageName()); } public ConductorWorkflow<Order> createOrderFlow() { WorkflowBuilder<Order> builder = new WorkflowBuilder<>(executor); builder.name("order_flow") .version(1) .ownerEmail("user@example.com") .timeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF, 60) // 1 day max .description("Workflow to track shipment") .add( new SimpleTask("calculate_tax_and_total", "calculate_tax_and_total") .input("orderDetail", ConductorWorkflow.input.get("orderDetail"))) .add( new SimpleTask("charge_payment", "charge_payment") .input( "billingId", ConductorWorkflow.input .map("userDetails") .get("billingId"), "billingType", ConductorWorkflow.input .map("userDetails") .get("billingType"), "amount", "${calculate_tax_and_total.output.total_amount}")) .add( new Switch("shipping_label", "${workflow.input.orderDetail.shippingMethod}") .switchCase( Order.ShippingMethod.GROUND.toString(), new SimpleTask( "ground_shipping_label", "ground_shipping_label") .input( "name", ConductorWorkflow.input .map("userDetails") .get("name"), "address", ConductorWorkflow.input .map("userDetails") .get("addressLine"), "orderNo", ConductorWorkflow.input .map("orderDetail") .get("orderNumber"))) .switchCase( Order.ShippingMethod.NEXT_DAY_AIR.toString(), new SimpleTask("air_shipping_label", "air_shipping_label") .input( "name", ConductorWorkflow.input .map("userDetails") .get("name"), "address", ConductorWorkflow.input .map("userDetails") .get("addressLine"), "orderNo", ConductorWorkflow.input .map("orderDetail") .get("orderNumber"))) .switchCase( Order.ShippingMethod.SAME_DAY.toString(), new SimpleTask( "same_day_shipping_label", "same_day_shipping_label") .input( "name", ConductorWorkflow.input .map("userDetails") .get("name"), "address", ConductorWorkflow.input .map("userDetails") .get("addressLine"), "orderNo", ConductorWorkflow.input .map("orderDetail") .get("orderNumber"))) .defaultCase( new Terminate( "unsupported_shipping_type", Workflow.WorkflowStatus.FAILED, "Unsupported Shipping Method"))) .add( new SimpleTask("send_email", "send_email") .input( "name", ConductorWorkflow.input .map("userDetails") .get("name"), "email", ConductorWorkflow.input .map("userDetails") .get("email"), "orderNo", ConductorWorkflow.input .map("orderDetail") .get("orderNumber"))); ConductorWorkflow<Order> conductorWorkflow = builder.build(); conductorWorkflow.registerWorkflow(true, true); return conductorWorkflow; } public ConductorWorkflow<Shipment> createShipmentWorkflow() { WorkflowBuilder<Shipment> builder = new WorkflowBuilder<>(executor); SimpleTask getOrderDetails = new SimpleTask("get_order_details", "get_order_details") .input("orderNo", ConductorWorkflow.input.get("orderNo")); SimpleTask getUserDetails = new SimpleTask("get_user_details", "get_user_details") .input("userId", ConductorWorkflow.input.get("userId")); ConductorWorkflow<Shipment> conductorWorkflow = builder.name("shipment_workflow") .version(1) .ownerEmail("user@example.com") .variables(new ShipmentState()) .timeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF, 60) // 30 days .description("Workflow to track shipment") .add( new ForkJoin( "get_in_parallel", new Task[] {getOrderDetails}, new Task[] {getUserDetails})) // For all the line items in the order, run in parallel: // (calculate tax, charge payment, set state, prepare shipment, send // shipment, set state) .add( new DynamicFork( "process_order", new SimpleTask("generateDynamicFork", "generateDynamicFork") .input( "orderDetails", getOrderDetails.taskOutput.get("result")) .input("userDetails", getUserDetails.taskOutput))) // Update the workflow state with shipped = true .add(new SetVariable("update_state").input("shipped", true)) .build(); conductorWorkflow.registerWorkflow(true, true); return conductorWorkflow; } public static void main(String[] args) { String conductorServerURL = "http://localhost:8080/api/"; // Change this to your Conductor server WorkflowExecutor executor = new WorkflowExecutor(conductorServerURL); // Create the new shipment workflow ShipmentWorkflow shipmentWorkflow = new ShipmentWorkflow(executor); // Create two workflows // 1. Order flow that ships an individual order // 2. Shipment Workflow that tracks multiple orders in a shipment shipmentWorkflow.createOrderFlow(); ConductorWorkflow<Shipment> workflow = shipmentWorkflow.createShipmentWorkflow(); // Execute the workflow and wait for it to complete try { Shipment workflowInput = new Shipment("userA", "order123"); // Execute returns a completable future. CompletableFuture<Workflow> executionFuture = workflow.execute(workflowInput); // Wait for a maximum of a minute for the workflow to complete. Workflow run = executionFuture.get(1, TimeUnit.MINUTES); System.out.println("Workflow Id: " + run); System.out.println("Workflow Status: " + run.getStatus()); System.out.println("Workflow Output: " + run.getOutput()); } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } System.out.println("Done"); } }
6,824
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/def/WorkflowCreationTests.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.sdk.testing.WorkflowTestRunner; import com.netflix.conductor.sdk.workflow.def.tasks.*; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.task.OutputParam; import com.netflix.conductor.sdk.workflow.task.WorkerTask; import com.netflix.conductor.sdk.workflow.testing.TestWorkflowInput; import static org.junit.jupiter.api.Assertions.*; @Disabled public class WorkflowCreationTests { private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowCreationTests.class); private static WorkflowExecutor executor; private static WorkflowTestRunner runner; @BeforeAll public static void init() throws IOException { runner = new WorkflowTestRunner(8080, "3.7.3"); runner.init("com.netflix.conductor.sdk"); executor = runner.getWorkflowExecutor(); } @AfterAll public static void cleanUp() { runner.shutdown(); } @WorkerTask("get_user_info") public @OutputParam("zipCode") String getZipCode(@InputParam("name") String userName) { return "95014"; } @WorkerTask("task2") public @OutputParam("greetings") String task2() { return "Hello World"; } @WorkerTask("task3") public @OutputParam("greetings") String task3() { return "Hello World-3"; } @WorkerTask("fork_gen") public DynamicForkInput generateDynamicFork() { DynamicForkInput forks = new DynamicForkInput(); Map<String, Object> inputs = new HashMap<>(); forks.setInputs(inputs); List<Task<?>> tasks = new ArrayList<>(); forks.setTasks(tasks); for (int i = 0; i < 3; i++) { SimpleTask task = new SimpleTask("task2", "fork_task_" + i); tasks.add(task); HashMap<String, Object> taskInput = new HashMap<>(); taskInput.put("key", "value"); taskInput.put("key2", 101); inputs.put(task.getTaskReferenceName(), taskInput); } return forks; } private ConductorWorkflow<TestWorkflowInput> registerTestWorkflow() { InputStream script = getClass().getResourceAsStream("/script.js"); SimpleTask getUserInfo = new SimpleTask("get_user_info", "get_user_info"); getUserInfo.input("name", ConductorWorkflow.input.get("name")); SimpleTask sendToCupertino = new SimpleTask("task2", "cupertino"); SimpleTask sendToNYC = new SimpleTask("task2", "nyc"); int len = 4; Task<?>[][] parallelTasks = new Task[len][1]; for (int i = 0; i < len; i++) { parallelTasks[i][0] = new SimpleTask("task2", "task_parallel_" + i); } WorkflowBuilder<TestWorkflowInput> builder = new WorkflowBuilder<>(executor); TestWorkflowInput defaultInput = new TestWorkflowInput(); defaultInput.setName("defaultName"); builder.name("sdk_workflow_example") .version(1) .ownerEmail("hello@example.com") .description("Example Workflow") .restartable(true) .variables(new WorkflowState()) .timeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF, 100) .defaultInput(defaultInput) .add(new Javascript("js", script)) .add(new ForkJoin("parallel", parallelTasks)) .add(getUserInfo) .add( new Switch("decide2", "${workflow.input.zipCode}") .switchCase("95014", sendToCupertino) .switchCase("10121", sendToNYC)) // .add(new SubWorkflow("subflow", "sub_workflow_example", 5)) .add(new SimpleTask("task2", "task222")) .add(new DynamicFork("dynamic_fork", new SimpleTask("fork_gen", "fork_gen"))); ConductorWorkflow<TestWorkflowInput> workflow = builder.build(); boolean registered = workflow.registerWorkflow(true, true); assertTrue(registered); return workflow; } @Test public void verifyCreatedWorkflow() { ConductorWorkflow<TestWorkflowInput> conductorWorkflow = registerTestWorkflow(); WorkflowDef def = conductorWorkflow.toWorkflowDef(); assertNotNull(def); assertTrue( def.getTasks() .get(def.getTasks().size() - 2) .getType() .equals(TaskType.TASK_TYPE_FORK_JOIN_DYNAMIC)); assertTrue( def.getTasks() .get(def.getTasks().size() - 1) .getType() .equals(TaskType.TASK_TYPE_JOIN)); } @Test public void verifyInlineWorkflowExecution() throws ValidationError { TestWorkflowInput workflowInput = new TestWorkflowInput("username", "10121", "US"); try { Workflow run = registerTestWorkflow().execute(workflowInput).get(10, TimeUnit.SECONDS); assertEquals( Workflow.WorkflowStatus.COMPLETED, run.getStatus(), run.getReasonForIncompletion()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testWorkflowExecutionByName() throws ExecutionException, InterruptedException { // Register the workflow first registerTestWorkflow(); TestWorkflowInput input = new TestWorkflowInput("username", "10121", "US"); ConductorWorkflow<TestWorkflowInput> conductorWorkflow = new ConductorWorkflow<TestWorkflowInput>(executor) .from("sdk_workflow_example", null); CompletableFuture<Workflow> execution = conductorWorkflow.execute(input); try { execution.get(10, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void verifyWorkflowExecutionFailsIfNotExists() throws ExecutionException, InterruptedException { // Register the workflow first registerTestWorkflow(); TestWorkflowInput input = new TestWorkflowInput("username", "10121", "US"); try { ConductorWorkflow<TestWorkflowInput> conductorWorkflow = new ConductorWorkflow<TestWorkflowInput>(executor) .from("non_existent_workflow", null); conductorWorkflow.execute(input); fail("execution should have failed"); } catch (Exception e) { } } }
6,825
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/def/WorkflowDefTaskTests.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def; import org.junit.jupiter.api.Test; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.tasks.*; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import static org.junit.jupiter.api.Assertions.*; public class WorkflowDefTaskTests { static { WorkflowExecutor.initTaskImplementations(); } @Test public void testWorkflowDefTaskWithStartDelay() { SimpleTask simpleTask = new SimpleTask("task_name", "task_ref_name"); int startDelay = 5; simpleTask.setStartDelay(startDelay); WorkflowTask workflowTask = simpleTask.getWorkflowDefTasks().get(0); assertEquals(simpleTask.getStartDelay(), workflowTask.getStartDelay()); assertEquals(startDelay, simpleTask.getStartDelay()); assertEquals(startDelay, workflowTask.getStartDelay()); } @Test public void testWorkflowDefTaskWithOptionalEnabled() { SimpleTask simpleTask = new SimpleTask("task_name", "task_ref_name"); simpleTask.setOptional(true); WorkflowTask workflowTask = simpleTask.getWorkflowDefTasks().get(0); assertEquals(simpleTask.getStartDelay(), workflowTask.getStartDelay()); assertEquals(true, simpleTask.isOptional()); assertEquals(true, workflowTask.isOptional()); } }
6,826
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/def/WorkflowState.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def; public class WorkflowState { private boolean paymentCompleted; private int timeTaken; public boolean isPaymentCompleted() { return paymentCompleted; } public void setPaymentCompleted(boolean paymentCompleted) { this.paymentCompleted = paymentCompleted; } public int getTimeTaken() { return timeTaken; } public void setTimeTaken(int timeTaken) { this.timeTaken = timeTaken; } }
6,827
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/def/TaskConversionsTests.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def; import java.time.Duration; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.sdk.workflow.def.tasks.*; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import static org.junit.jupiter.api.Assertions.*; public class TaskConversionsTests { static { WorkflowExecutor.initTaskImplementations(); } @Test public void testSimpleTaskConversion() { SimpleTask simpleTask = new SimpleTask("task_name", "task_ref_name"); Map<String, Object> map = new HashMap<>(); map.put("key11", "value11"); map.put("key12", 100); simpleTask.input("key1", "value"); simpleTask.input("key2", 42); simpleTask.input("key3", true); simpleTask.input("key4", map); WorkflowTask workflowTask = simpleTask.getWorkflowDefTasks().get(0); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue(fromWorkflowTask instanceof SimpleTask); SimpleTask simpleTaskFromWorkflowTask = (SimpleTask) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(simpleTask.getName(), fromWorkflowTask.getName()); assertEquals(simpleTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(simpleTask.getTaskDef(), simpleTaskFromWorkflowTask.getTaskDef()); assertEquals(simpleTask.getType(), simpleTaskFromWorkflowTask.getType()); assertEquals(simpleTask.getStartDelay(), simpleTaskFromWorkflowTask.getStartDelay()); assertEquals(simpleTask.getInput(), simpleTaskFromWorkflowTask.getInput()); } @Test public void testDynamicTaskCoversion() { Dynamic dynamicTask = new Dynamic("task_name", "task_ref_name"); WorkflowTask workflowTask = dynamicTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters().get(Dynamic.TASK_NAME_INPUT_PARAM)); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue(fromWorkflowTask instanceof Dynamic); Dynamic taskFromWorkflowTask = (Dynamic) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(dynamicTask.getName(), fromWorkflowTask.getName()); assertEquals(dynamicTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(dynamicTask.getType(), taskFromWorkflowTask.getType()); assertEquals(dynamicTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(dynamicTask.getInput(), taskFromWorkflowTask.getInput()); } @Test public void testForkTaskConversion() { SimpleTask task1 = new SimpleTask("task1", "task1"); SimpleTask task2 = new SimpleTask("task2", "task2"); SimpleTask task3 = new SimpleTask("task3", "task3"); ForkJoin forkTask = new ForkJoin("task_ref_name", new Task[] {task1}, new Task[] {task2, task3}); WorkflowTask workflowTask = forkTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getForkTasks()); assertFalse(workflowTask.getForkTasks().isEmpty()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue(fromWorkflowTask instanceof ForkJoin); ForkJoin taskFromWorkflowTask = (ForkJoin) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(forkTask.getName(), fromWorkflowTask.getName()); assertEquals(forkTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(forkTask.getType(), taskFromWorkflowTask.getType()); assertEquals(forkTask.getInput(), taskFromWorkflowTask.getInput()); assertEquals( forkTask.getForkedTasks().length, taskFromWorkflowTask.getForkedTasks().length); for (int i = 0; i < forkTask.getForkedTasks().length; i++) { assertEquals( forkTask.getForkedTasks()[i].length, taskFromWorkflowTask.getForkedTasks()[i].length); for (int j = 0; j < forkTask.getForkedTasks()[i].length; j++) { assertEquals( forkTask.getForkedTasks()[i][j].getTaskReferenceName(), taskFromWorkflowTask.getForkedTasks()[i][j].getTaskReferenceName()); assertEquals( forkTask.getForkedTasks()[i][j].getName(), taskFromWorkflowTask.getForkedTasks()[i][j].getName()); assertEquals( forkTask.getForkedTasks()[i][j].getType(), taskFromWorkflowTask.getForkedTasks()[i][j].getType()); } } } @Test public void testDynamicForkTaskCoversion() { DynamicFork dynamicTask = new DynamicFork("task_ref_name", "forkTasks", "forkTaskInputs"); WorkflowTask workflowTask = dynamicTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue(fromWorkflowTask instanceof DynamicFork); DynamicFork taskFromWorkflowTask = (DynamicFork) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(dynamicTask.getName(), fromWorkflowTask.getName()); assertEquals(dynamicTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(dynamicTask.getType(), taskFromWorkflowTask.getType()); assertEquals(dynamicTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(dynamicTask.getInput(), taskFromWorkflowTask.getInput()); assertEquals( dynamicTask.getForkTasksParameter(), taskFromWorkflowTask.getForkTasksParameter()); assertEquals( dynamicTask.getForkTasksInputsParameter(), taskFromWorkflowTask.getForkTasksInputsParameter()); } @Test public void testDoWhileConversion() { SimpleTask task1 = new SimpleTask("task_name", "task_ref_name"); SimpleTask task2 = new SimpleTask("task_name", "task_ref_name"); DoWhile doWhileTask = new DoWhile("task_ref_name", 2, task1, task2); WorkflowTask workflowTask = doWhileTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue(fromWorkflowTask instanceof DoWhile); DoWhile taskFromWorkflowTask = (DoWhile) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(doWhileTask.getName(), fromWorkflowTask.getName()); assertEquals(doWhileTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(doWhileTask.getType(), taskFromWorkflowTask.getType()); assertEquals(doWhileTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(doWhileTask.getInput(), taskFromWorkflowTask.getInput()); assertEquals(doWhileTask.getLoopCondition(), taskFromWorkflowTask.getLoopCondition()); assertEquals( doWhileTask.getLoopTasks().stream() .map(task -> task.getTaskReferenceName()) .sorted() .collect(Collectors.toSet()), taskFromWorkflowTask.getLoopTasks().stream() .map(task -> task.getTaskReferenceName()) .sorted() .collect(Collectors.toSet())); } @Test public void testJoin() { Join joinTask = new Join("task_ref_name", "task1", "task2"); WorkflowTask workflowTask = joinTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); assertNotNull(workflowTask.getJoinOn()); assertTrue(!workflowTask.getJoinOn().isEmpty()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof Join, "task is not of type Join, but of type " + fromWorkflowTask.getClass().getName()); Join taskFromWorkflowTask = (Join) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(joinTask.getName(), fromWorkflowTask.getName()); assertEquals(joinTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(joinTask.getType(), taskFromWorkflowTask.getType()); assertEquals(joinTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(joinTask.getInput(), taskFromWorkflowTask.getInput()); assertEquals(joinTask.getJoinOn().length, taskFromWorkflowTask.getJoinOn().length); assertEquals( Arrays.asList(joinTask.getJoinOn()).stream().sorted().collect(Collectors.toSet()), Arrays.asList(taskFromWorkflowTask.getJoinOn()).stream() .sorted() .collect(Collectors.toSet())); } @Test public void testEvent() { Event eventTask = new Event("task_ref_name", "sqs:queue11"); WorkflowTask workflowTask = eventTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof Event, "task is not of type Event, but of type " + fromWorkflowTask.getClass().getName()); Event taskFromWorkflowTask = (Event) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(eventTask.getName(), fromWorkflowTask.getName()); assertEquals(eventTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(eventTask.getType(), taskFromWorkflowTask.getType()); assertEquals(eventTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(eventTask.getInput(), taskFromWorkflowTask.getInput()); assertEquals(eventTask.getSink(), taskFromWorkflowTask.getSink()); } @Test public void testSetVariableConversion() { SetVariable setVariableTask = new SetVariable("task_ref_name"); WorkflowTask workflowTask = setVariableTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof SetVariable, "task is not of type SetVariable, but of type " + fromWorkflowTask.getClass().getName()); SetVariable taskFromWorkflowTask = (SetVariable) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(setVariableTask.getName(), fromWorkflowTask.getName()); assertEquals( setVariableTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(setVariableTask.getType(), taskFromWorkflowTask.getType()); assertEquals(setVariableTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(setVariableTask.getInput(), taskFromWorkflowTask.getInput()); } @Test public void testSubWorkflowConversion() { SubWorkflow subWorkflowTask = new SubWorkflow("task_ref_name", "sub_flow", 2); WorkflowTask workflowTask = subWorkflowTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof SubWorkflow, "task is not of type SubWorkflow, but of type " + fromWorkflowTask.getClass().getName()); SubWorkflow taskFromWorkflowTask = (SubWorkflow) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(subWorkflowTask.getName(), fromWorkflowTask.getName()); assertEquals( subWorkflowTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(subWorkflowTask.getType(), taskFromWorkflowTask.getType()); assertEquals(subWorkflowTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(subWorkflowTask.getInput(), taskFromWorkflowTask.getInput()); assertEquals(subWorkflowTask.getWorkflowName(), taskFromWorkflowTask.getWorkflowName()); assertEquals( subWorkflowTask.getWorkflowVersion(), taskFromWorkflowTask.getWorkflowVersion()); } @Test public void testSwitchConversion() { SimpleTask task1 = new SimpleTask("task_name", "task_ref_name1"); SimpleTask task2 = new SimpleTask("task_name", "task_ref_name2"); SimpleTask task3 = new SimpleTask("task_name", "task_ref_name3"); Switch decision = new Switch("switch", "${workflow.input.zip"); decision.switchCase("caseA", task1); decision.switchCase("caseB", task2, task3); decision.defaultCase( new Terminate("terminate", Workflow.WorkflowStatus.FAILED, "", new HashMap<>())); WorkflowTask workflowTask = decision.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof Switch, "task is not of type Switch, but of type " + fromWorkflowTask.getClass().getName()); Switch taskFromWorkflowTask = (Switch) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(decision.getName(), fromWorkflowTask.getName()); assertEquals(decision.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(decision.getType(), taskFromWorkflowTask.getType()); assertEquals(decision.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(decision.getInput(), taskFromWorkflowTask.getInput()); // TODO: ADD CASES FOR DEFAULT CASE assertEquals(decision.getBranches().keySet(), taskFromWorkflowTask.getBranches().keySet()); assertEquals( decision.getBranches().values().stream() .map( tasks -> tasks.stream() .map(Task::getTaskReferenceName) .collect(Collectors.toSet())) .collect(Collectors.toSet()), taskFromWorkflowTask.getBranches().values().stream() .map( tasks -> tasks.stream() .map(Task::getTaskReferenceName) .collect(Collectors.toSet())) .collect(Collectors.toSet())); assertEquals(decision.getBranches().size(), taskFromWorkflowTask.getBranches().size()); } @Test public void testTerminateConversion() { Terminate terminateTask = new Terminate("terminate", Workflow.WorkflowStatus.FAILED, "", new HashMap<>()); WorkflowTask workflowTask = terminateTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof Terminate, "task is not of type Terminate, but of type " + fromWorkflowTask.getClass().getName()); Terminate taskFromWorkflowTask = (Terminate) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(terminateTask.getName(), fromWorkflowTask.getName()); assertEquals(terminateTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(terminateTask.getType(), taskFromWorkflowTask.getType()); assertEquals(terminateTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(terminateTask.getInput(), taskFromWorkflowTask.getInput()); } @Test public void testWaitConversion() { Wait waitTask = new Wait("terminate"); WorkflowTask workflowTask = waitTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof Wait, "task is not of type Wait, but of type " + fromWorkflowTask.getClass().getName()); Wait taskFromWorkflowTask = (Wait) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(waitTask.getName(), fromWorkflowTask.getName()); assertEquals(waitTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(waitTask.getType(), taskFromWorkflowTask.getType()); assertEquals(waitTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(waitTask.getInput(), taskFromWorkflowTask.getInput()); // Wait for 10 seconds waitTask = new Wait("wait_for_10_seconds", Duration.of(10, ChronoUnit.SECONDS)); workflowTask = waitTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); assertEquals("10s", workflowTask.getInputParameters().get(Wait.DURATION_INPUT)); // Wait for 10 minutes waitTask = new Wait("wait_for_10_seconds", Duration.of(10, ChronoUnit.MINUTES)); workflowTask = waitTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); assertEquals("600s", workflowTask.getInputParameters().get(Wait.DURATION_INPUT)); // Wait till next week some time ZonedDateTime nextWeek = ZonedDateTime.now().plusDays(7); String formattedDateTime = Wait.dateTimeFormatter.format(nextWeek); waitTask = new Wait("wait_till_next_week", nextWeek); workflowTask = waitTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); assertEquals(formattedDateTime, workflowTask.getInputParameters().get(Wait.UNTIL_INPUT)); } @Test public void testHttpConverter() { Http httpTask = new Http("terminate"); Http.Input input = new Http.Input(); input.setUri("http://example.com"); input.setMethod(Http.Input.HttpMethod.POST); input.setBody("Hello World"); input.setReadTimeOut(100); Map<String, Object> headers = new HashMap<>(); headers.put("X-AUTHORIZATION", "my_api_key"); input.setHeaders(headers); httpTask.input(input); WorkflowTask workflowTask = httpTask.getWorkflowDefTasks().get(0); assertNotNull(workflowTask.getInputParameters()); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof Http, "task is not of type Http, but of type " + fromWorkflowTask.getClass().getName()); Http taskFromWorkflowTask = (Http) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(httpTask.getName(), fromWorkflowTask.getName()); assertEquals(httpTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(httpTask.getType(), taskFromWorkflowTask.getType()); assertEquals(httpTask.getStartDelay(), taskFromWorkflowTask.getStartDelay()); assertEquals(httpTask.getInput(), taskFromWorkflowTask.getInput()); assertEquals(httpTask.getHttpRequest(), taskFromWorkflowTask.getHttpRequest()); System.out.println(httpTask.getInput()); System.out.println(taskFromWorkflowTask.getInput()); } @Test public void testJQTaskConversion() { JQ jqTask = new JQ("task_name", "{ key3: (.key1.value1 + .key2.value2) }"); Map<String, Object> map = new HashMap<>(); map.put("key11", "value11"); map.put("key12", 100); jqTask.input("key1", "value"); jqTask.input("key2", 42); jqTask.input("key3", true); jqTask.input("key4", map); WorkflowTask workflowTask = jqTask.getWorkflowDefTasks().get(0); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue(fromWorkflowTask instanceof JQ, "Found the instance " + fromWorkflowTask); JQ taskFromWorkflowTask = (JQ) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(jqTask.getName(), fromWorkflowTask.getName()); assertEquals(jqTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(jqTask.getQueryExpression(), taskFromWorkflowTask.getQueryExpression()); assertEquals(jqTask.getType(), taskFromWorkflowTask.getType()); assertEquals(jqTask.getInput(), taskFromWorkflowTask.getInput()); } @Test public void testInlineTaskConversion() { Javascript inlineTask = new Javascript( "task_name", "function e() { if ($.value == 1){return {\"result\": true}} else { return {\"result\": false}}} e();"); inlineTask.validate(); Map<String, Object> map = new HashMap<>(); map.put("key11", "value11"); map.put("key12", 100); inlineTask.input("key1", "value"); inlineTask.input("key2", 42); inlineTask.input("key3", true); inlineTask.input("key4", map); WorkflowTask workflowTask = inlineTask.getWorkflowDefTasks().get(0); Task fromWorkflowTask = TaskRegistry.getTask(workflowTask); assertTrue( fromWorkflowTask instanceof Javascript, "Found the instance " + fromWorkflowTask); Javascript taskFromWorkflowTask = (Javascript) fromWorkflowTask; assertNotNull(fromWorkflowTask); assertEquals(inlineTask.getName(), fromWorkflowTask.getName()); assertEquals(inlineTask.getTaskReferenceName(), fromWorkflowTask.getTaskReferenceName()); assertEquals(inlineTask.getExpression(), taskFromWorkflowTask.getExpression()); assertEquals(inlineTask.getType(), taskFromWorkflowTask.getType()); assertEquals(inlineTask.getInput(), taskFromWorkflowTask.getInput()); } @Test public void testJavascriptValidation() { // This script has errors Javascript inlineTask = new Javascript( "task_name", "function e() { if ($.value ==> 1){return {\"result\": true}} else { return {\"result\": false}}} e();"); boolean failed = false; try { inlineTask.validate(); } catch (ValidationError ve) { failed = true; } assertTrue(failed); // This script does NOT have errors inlineTask = new Javascript( "task_name", "function e() { if ($.value == 1){return {\"result\": true}} else { return {\"result\": false}}} e();"); failed = false; try { inlineTask.validate(); } catch (ValidationError ve) { failed = true; } assertFalse(failed); } }
6,828
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/testing/TestWorkflowInput.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.testing; public class TestWorkflowInput { private String name; private String zipCode; private String countryCode; public TestWorkflowInput(String name, String zipCode, String countryCode) { this.name = name; this.zipCode = zipCode; this.countryCode = countryCode; } public TestWorkflowInput() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } }
6,829
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/testing/WorkflowTestFrameworkTests.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.testing; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.sdk.testing.WorkflowTestRunner; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.task.OutputParam; import com.netflix.conductor.sdk.workflow.task.WorkerTask; import static org.junit.jupiter.api.Assertions.*; public class WorkflowTestFrameworkTests { private static WorkflowTestRunner testRunner; private static WorkflowExecutor executor; @BeforeAll public static void init() throws IOException { testRunner = new WorkflowTestRunner(8080, "3.7.3"); testRunner.init("com.netflix.conductor.sdk.workflow.testing"); executor = testRunner.getWorkflowExecutor(); executor.loadTaskDefs("/tasks.json"); executor.loadWorkflowDefs("/simple_workflow.json"); } @AfterAll public static void cleanUp() { testRunner.shutdown(); } @Test public void testDynamicTaskExecuted() throws Exception { Map<String, Object> input = new HashMap<>(); input.put("task2Name", "task_2"); input.put("mod", "1"); input.put("oddEven", "12"); input.put("number", 0); // Start the workflow and wait for it to complete Workflow workflow = executor.executeWorkflow("Decision_TaskExample", 1, input).get(); assertNotNull(workflow); assertEquals(Workflow.WorkflowStatus.COMPLETED, workflow.getStatus()); assertNotNull(workflow.getOutput()); assertNotNull(workflow.getTasks()); assertFalse(workflow.getTasks().isEmpty()); assertTrue( workflow.getTasks().stream() .anyMatch(task -> task.getTaskDefName().equals("task_6"))); // task_2's implementation fails at the first try, so we should have to instances of task_2 // execution // 2 executions of task_2 should be present assertEquals( 2, workflow.getTasks().stream() .filter(task -> task.getTaskDefName().equals("task_2")) .count()); List<Task> task2Executions = workflow.getTasks().stream() .filter(task -> task.getTaskDefName().equals("task_2")) .collect(Collectors.toList()); assertNotNull(task2Executions); assertEquals(2, task2Executions.size()); // First instance would have failed and second succeeded. assertEquals(Task.Status.FAILED, task2Executions.get(0).getStatus()); assertEquals(Task.Status.COMPLETED, task2Executions.get(1).getStatus()); // task10's output assertEquals(100, workflow.getOutput().get("c")); } @Test public void testWorkflowFailure() throws Exception { Map<String, Object> input = new HashMap<>(); // task2Name is missing which will cause workflow to fail input.put("mod", "1"); input.put("oddEven", "12"); input.put("number", 0); // we are missing task2Name parameter which is required to wire up dynamictask // The workflow should fail as we are not passing it as input Workflow workflow = executor.executeWorkflow("Decision_TaskExample", 1, input).get(); assertNotNull(workflow); assertEquals(Workflow.WorkflowStatus.FAILED, workflow.getStatus()); assertNotNull(workflow.getReasonForIncompletion()); } @WorkerTask("task_1") public Map<String, Object> task1(Task1Input input) { Map<String, Object> result = new HashMap<>(); result.put("input", input); return result; } @WorkerTask("task_2") public TaskResult task2(Task task) { if (task.getRetryCount() < 1) { task.setStatus(Task.Status.FAILED); task.setReasonForIncompletion("try again"); return new TaskResult(task); } task.setStatus(Task.Status.COMPLETED); return new TaskResult(task); } @WorkerTask("task_6") public TaskResult task6(Task task) { task.setStatus(Task.Status.COMPLETED); return new TaskResult(task); } @WorkerTask("task_10") public TaskResult task10(Task task) { task.setStatus(Task.Status.COMPLETED); task.getOutputData().put("a", "b"); task.getOutputData().put("c", 100); task.getOutputData().put("x", false); return new TaskResult(task); } @WorkerTask("task_8") public TaskResult task8(Task task) { task.setStatus(Task.Status.COMPLETED); return new TaskResult(task); } @WorkerTask("task_5") public TaskResult task5(Task task) { task.setStatus(Task.Status.COMPLETED); return new TaskResult(task); } @WorkerTask("task_3") public @OutputParam("z1") String task3(@InputParam("taskToExecute") String p1) { return "output of task3, p1=" + p1; } @WorkerTask("task_30") public Map<String, Object> task30(Task task) { Map<String, Object> output = new HashMap<>(); output.put("v1", "b"); output.put("v2", Arrays.asList("one", "two", 3)); output.put("v3", 5); return output; } @WorkerTask("task_31") public Map<String, Object> task31(Task task) { Map<String, Object> output = new HashMap<>(); output.put("a1", "b"); output.put("a2", Arrays.asList("one", "two", 3)); output.put("a3", 5); return output; } @WorkerTask("HTTP") public Map<String, Object> http(Task task) { Map<String, Object> output = new HashMap<>(); output.put("a1", "b"); output.put("a2", Arrays.asList("one", "two", 3)); output.put("a3", 5); return output; } @WorkerTask("EVENT") public Map<String, Object> event(Task task) { Map<String, Object> output = new HashMap<>(); output.put("a1", "b"); output.put("a2", Arrays.asList("one", "two", 3)); output.put("a3", 5); return output; } }
6,830
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/testing/Task1Input.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.testing; public class Task1Input { private int mod; private int oddEven; public int getMod() { return mod; } public void setMod(int mod) { this.mod = mod; } public int getOddEven() { return oddEven; } public void setOddEven(int oddEven) { this.oddEven = oddEven; } @Override public String toString() { return "Task1Input{" + "mod=" + mod + ", oddEven=" + oddEven + '}'; } }
6,831
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/TestWorkerConfig.java
/* * Copyright 2023 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; import java.util.HashMap; import java.util.Map; public class TestWorkerConfig extends WorkerConfiguration { private Map<String, Integer> pollingIntervals = new HashMap<>(); private Map<String, Integer> threadCounts = new HashMap<>(); @Override public int getPollingInterval(String taskName) { return pollingIntervals.getOrDefault(taskName, 0); } public void setPollingInterval(String taskName, int interval) { pollingIntervals.put(taskName, interval); } public void setThreadCount(String taskName, int threadCount) { threadCounts.put(taskName, threadCount); } @Override public int getThreadCount(String taskName) { return threadCounts.getOrDefault(taskName, 0); } }
6,832
0
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerTests.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.List; import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import com.netflix.conductor.client.automator.TaskRunnerConfigurer; import com.netflix.conductor.client.http.TaskClient; import com.netflix.conductor.client.worker.Worker; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.task.OutputParam; import com.netflix.conductor.sdk.workflow.task.WorkerTask; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; public class AnnotatedWorkerTests { static class Car { String brand; String getBrand() { return brand; } void setBrand(String brand) { this.brand = brand; } } static class Bike { String brand; String getBrand() { return brand; } void setBrand(String brand) { this.brand = brand; } } static class CarWorker { @WorkerTask("test_1") public @OutputParam("result") List<Car> doWork(@InputParam("input") List<Car> input) { return input; } } @Test @DisplayName("it should handle null values when InputParam is a List") void nullListAsInputParam() throws NoSuchMethodException { var worker = new CarWorker(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", List.class), worker); var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); assertNull(outputData.get("result")); } @Test @DisplayName("it should handle an empty List as InputParam") void emptyListAsInputParam() throws NoSuchMethodException { var worker = new CarWorker(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", List.class), worker); var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); task.setInputData(Map.of("input", List.of())); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); @SuppressWarnings("unchecked") List<Car> result = (List<Car>) outputData.get("result"); assertTrue(result.isEmpty()); } @Test @DisplayName("it should handle a non empty List as InputParam") void nonEmptyListAsInputParam() throws NoSuchMethodException { var worker = new CarWorker(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", List.class), worker); var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); task.setInputData(Map.of("input", List.of(Map.of("brand", "BMW")))); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); @SuppressWarnings("unchecked") List<Car> result = (List<Car>) outputData.get("result"); assertEquals(1, result.size()); Car car = result.get(0); assertEquals("BMW", car.getBrand()); } @SuppressWarnings("rawtypes") static class RawListInput { @WorkerTask("test_1") public @OutputParam("result") List doWork(@InputParam("input") List input) { return input; } } @Test @DisplayName("it should handle a Raw List Type as InputParam") void rawListAsInputParam() throws NoSuchMethodException { var worker = new RawListInput(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", List.class), worker); var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); task.setInputData(Map.of("input", List.of(Map.of("brand", "BMW")))); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); assertEquals(task.getInputData().get("input"), outputData.get("result")); } static class MapInput { @WorkerTask("test_1") public @OutputParam("result") Map<String, Object> doWork(Map<String, Object> input) { return input; } } @Test @DisplayName("it should accept a not annotated Map as input") void mapAsInputParam() throws NoSuchMethodException { var worker = new MapInput(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", Map.class), worker); var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); task.setInputData(Map.of("input", List.of(Map.of("brand", "BMW")))); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); assertEquals(task.getInputData(), outputData.get("result")); } static class TaskInput { @WorkerTask("test_1") public @OutputParam("result") Task doWork(Task input) { return input; } } @Test @DisplayName("it should accept a Task as input") void taskAsInputParam() throws NoSuchMethodException { var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); task.setTaskId(UUID.randomUUID().toString()); task.setInputData(Map.of("input", List.of(Map.of("brand", "BMW")))); var worker = new TaskInput(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", Task.class), worker); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); var result = (Task) outputData.get("result"); assertEquals(result.getTaskId(), task.getTaskId()); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface AnotherAnnotation {} static class AnotherAnnotationInput { @WorkerTask("test_2") public @OutputParam("result") Bike doWork(@AnotherAnnotation Bike input) { return input; } } @Test @DisplayName( "it should convert to the correct type even if there's no @InputParam and parameters are annotated with other annotations") void annotatedWithAnotherAnnotation() throws NoSuchMethodException { var worker = new AnotherAnnotationInput(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", Bike.class), worker); var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); task.setTaskId(UUID.randomUUID().toString()); task.setInputData(Map.of("brand", "Trek")); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); var bike = (Bike) outputData.get("result"); assertEquals("Trek", bike.getBrand()); } static class MultipleInputParams { @WorkerTask(value = "test_1", threadCount = 3, pollingInterval = 333) public Map<String, Object> doWork( @InputParam("bike") Bike bike, @InputParam("car") Car car) { return Map.of("bike", bike, "car", car); } } @Test @DisplayName("it should handle multiple input params") void multipleInputParams() throws NoSuchMethodException { var worker = new MultipleInputParams(); var annotatedWorker = new AnnotatedWorker( "test_1", worker.getClass().getMethod("doWork", Bike.class, Car.class), worker); var task = new Task(); task.setStatus(Task.Status.IN_PROGRESS); task.setTaskId(UUID.randomUUID().toString()); task.setInputData(Map.of("bike", Map.of("brand", "Trek"), "car", Map.of("brand", "BMW"))); var result0 = annotatedWorker.execute(task); var outputData = result0.getOutputData(); var bike = (Bike) outputData.get("bike"); assertEquals("Trek", bike.getBrand()); var car = (Car) outputData.get("car"); assertEquals("BMW", car.getBrand()); } @Test @DisplayName("it should honor the polling interval from annotations and config") void pollingIntervalTest() throws NoSuchMethodException { var config = new TestWorkerConfig(); var worker = new MultipleInputParams(); AnnotatedWorkerExecutor annotatedWorkerExecutor = new AnnotatedWorkerExecutor(mock(TaskClient.class)); annotatedWorkerExecutor.addBean(worker); annotatedWorkerExecutor.startPolling(); List<Worker> workers = annotatedWorkerExecutor.getExecutors(); assertNotNull(workers); assertEquals(1, workers.size()); Worker taskWorker = workers.get(0); assertEquals(333, taskWorker.getPollingInterval()); var worker2 = new AnotherAnnotationInput(); annotatedWorkerExecutor = new AnnotatedWorkerExecutor(mock(TaskClient.class)); annotatedWorkerExecutor.addBean(worker2); annotatedWorkerExecutor.startPolling(); workers = annotatedWorkerExecutor.getExecutors(); assertNotNull(workers); assertEquals(1, workers.size()); taskWorker = workers.get(0); assertEquals(100, taskWorker.getPollingInterval()); config.setPollingInterval("test_2", 123); annotatedWorkerExecutor = new AnnotatedWorkerExecutor(mock(TaskClient.class), config); annotatedWorkerExecutor.addBean(worker2); annotatedWorkerExecutor.startPolling(); workers = annotatedWorkerExecutor.getExecutors(); assertNotNull(workers); assertEquals(1, workers.size()); taskWorker = workers.get(0); assertEquals(123, taskWorker.getPollingInterval()); } @Test @DisplayName("it should honor the polling interval from annotations and config") void threadCountTest() throws NoSuchMethodException { var config = new TestWorkerConfig(); var worker = new MultipleInputParams(); var worker2 = new AnotherAnnotationInput(); AnnotatedWorkerExecutor annotatedWorkerExecutor = new AnnotatedWorkerExecutor(mock(TaskClient.class), config); annotatedWorkerExecutor.addBean(worker); annotatedWorkerExecutor.addBean(worker2); annotatedWorkerExecutor.startPolling(); TaskRunnerConfigurer runner = annotatedWorkerExecutor.getTaskRunner(); assertNotNull(runner); Map<String, Integer> taskThreadCount = runner.getTaskThreadCount(); assertNotNull(taskThreadCount); assertEquals(3, taskThreadCount.get("test_1")); assertEquals(1, taskThreadCount.get("test_2")); annotatedWorkerExecutor.shutdown(); config.setThreadCount("test_2", 2); annotatedWorkerExecutor = new AnnotatedWorkerExecutor(mock(TaskClient.class), config); annotatedWorkerExecutor.addBean(worker); annotatedWorkerExecutor.addBean(worker2); annotatedWorkerExecutor.startPolling(); runner = annotatedWorkerExecutor.getTaskRunner(); taskThreadCount = runner.getTaskThreadCount(); assertNotNull(taskThreadCount); assertEquals(3, taskThreadCount.get("test_1")); assertEquals(2, taskThreadCount.get("test_2")); } }
6,833
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/healthcheck/HealthCheckClient.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.healthcheck; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class HealthCheckClient { private final String healthCheckURL; private final ObjectMapper objectMapper; public HealthCheckClient(String healthCheckURL) { this.healthCheckURL = healthCheckURL; this.objectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } public boolean isServerRunning() { try { BufferedReader in = new BufferedReader(new InputStreamReader(new URL(healthCheckURL).openStream())); StringBuilder response = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); HealthCheckResults healthCheckResults = objectMapper.readValue(response.toString(), HealthCheckResults.class); return healthCheckResults.healthy; } catch (Throwable t) { return false; } } private static final class HealthCheckResults { private boolean healthy; public boolean isHealthy() { return healthy; } public void setHealthy(boolean healthy) { this.healthy = healthy; } } }
6,834
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/testing/WorkflowTestRunner.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.testing; import com.netflix.conductor.client.http.TaskClient; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import com.netflix.conductor.sdk.workflow.executor.task.AnnotatedWorkerExecutor; public class WorkflowTestRunner { private LocalServerRunner localServerRunner; private final AnnotatedWorkerExecutor annotatedWorkerExecutor; private final WorkflowExecutor workflowExecutor; public WorkflowTestRunner(String serverApiUrl) { TaskClient taskClient = new TaskClient(); taskClient.setRootURI(serverApiUrl); this.annotatedWorkerExecutor = new AnnotatedWorkerExecutor(taskClient); this.workflowExecutor = new WorkflowExecutor(serverApiUrl); } public WorkflowTestRunner(int port, String conductorVersion) { localServerRunner = new LocalServerRunner(port, conductorVersion); TaskClient taskClient = new TaskClient(); taskClient.setRootURI(localServerRunner.getServerAPIUrl()); this.annotatedWorkerExecutor = new AnnotatedWorkerExecutor(taskClient); this.workflowExecutor = new WorkflowExecutor(localServerRunner.getServerAPIUrl()); } public WorkflowExecutor getWorkflowExecutor() { return workflowExecutor; } public void init(String basePackages) { if (localServerRunner != null) { localServerRunner.startLocalServer(); } annotatedWorkerExecutor.initWorkers(basePackages); } public void shutdown() { localServerRunner.shutdown(); annotatedWorkerExecutor.shutdown(); workflowExecutor.shutdown(); } }
6,835
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/testing/LocalServerRunner.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.testing; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.sdk.healthcheck.HealthCheckClient; import com.google.common.util.concurrent.Uninterruptibles; public class LocalServerRunner { private static final Logger LOGGER = LoggerFactory.getLogger(LocalServerRunner.class); private final HealthCheckClient healthCheck; private Process serverProcess; private final ScheduledExecutorService healthCheckExecutor = Executors.newSingleThreadScheduledExecutor(); private final CountDownLatch serverProcessLatch = new CountDownLatch(1); private final int port; private final String conductorVersion; private final String serverURL; private static Map<Integer, LocalServerRunner> serverInstances = new HashMap<>(); public LocalServerRunner(int port, String conductorVersion) { this.port = port; this.conductorVersion = conductorVersion; this.serverURL = "http://localhost:" + port + "/"; healthCheck = new HealthCheckClient(serverURL + "health"); } public String getServerAPIUrl() { return this.serverURL + "api/"; } /** * Starts the local server. Downloads the latest conductor build from the maven repo If you want * to start the server from a specific download location, set `repositoryURL` system property * with the link to the actual downloadable server boot jar file. * * <p><b>System Properties that can be set</b> conductorVersion: when specified, uses this * version of conductor to run tests (and downloads from maven repo) repositoryURL: full url * where the server boot jar can be downloaded from. This can be a public repo or internal * repository, allowing full control over the location and version of the conductor server */ public void startLocalServer() { synchronized (serverInstances) { if (serverInstances.get(port) != null) { throw new IllegalStateException( "Another server has already been started at port " + port); } serverInstances.put(port, this); } try { String downloadURL = "https://repo1.maven.org/maven2/com/netflix/conductor/conductor-server/" + conductorVersion + "/conductor-server-" + conductorVersion + "-boot.jar"; String repositoryURL = Optional.ofNullable(System.getProperty("repositoryURL")).orElse(downloadURL); LOGGER.info( "Running conductor with version {} from repo url {}", conductorVersion, repositoryURL); Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown)); installAndStartServer(repositoryURL, port); healthCheckExecutor.scheduleAtFixedRate( () -> { try { if (serverProcessLatch.getCount() > 0) { boolean isRunning = healthCheck.isServerRunning(); if (isRunning) { serverProcessLatch.countDown(); } } } catch (Exception e) { LOGGER.warn( "Caught an exception while polling for server running status {}", e.getMessage()); } }, 100, 100, TimeUnit.MILLISECONDS); Uninterruptibles.awaitUninterruptibly(serverProcessLatch, 1, TimeUnit.MINUTES); if (serverProcessLatch.getCount() > 0) { throw new RuntimeException("Server not healthy"); } healthCheckExecutor.shutdownNow(); } catch (IOException e) { throw new Error(e); } } public void shutdown() { if (serverProcess != null) { serverProcess.destroyForcibly(); serverInstances.remove(port); } } private synchronized void installAndStartServer(String repositoryURL, int localServerPort) throws IOException { if (serverProcess != null) { return; } String configFile = LocalServerRunner.class.getResource("/test-server.properties").getFile(); String tempDir = System.getProperty("java.io.tmpdir"); Path serverFile = Paths.get(tempDir, "conductor-server.jar"); if (!Files.exists(serverFile)) { Files.copy(new URL(repositoryURL).openStream(), serverFile); } String command = "java -Dserver.port=" + localServerPort + " -DCONDUCTOR_CONFIG_FILE=" + configFile + " -jar " + serverFile; LOGGER.info("Running command {}", command); serverProcess = Runtime.getRuntime().exec(command); BufferedReader error = new BufferedReader(new InputStreamReader(serverProcess.getErrorStream())); BufferedReader op = new BufferedReader(new InputStreamReader(serverProcess.getInputStream())); // This captures the stream and copies to a visible log for tracking errors asynchronously // using a separate thread Executors.newSingleThreadScheduledExecutor() .execute( () -> { String line = null; while (true) { try { if ((line = error.readLine()) == null) break; } catch (IOException e) { LOGGER.error("Exception reading input stream:", e); } // copy to standard error LOGGER.error("Server error stream - {}", line); } }); // This captures the stream and copies to a visible log for tracking errors asynchronously // using a separate thread Executors.newSingleThreadScheduledExecutor() .execute( () -> { String line = null; while (true) { try { if ((line = op.readLine()) == null) break; } catch (IOException e) { LOGGER.error("Exception reading input stream:", e); } // copy to standard out LOGGER.trace("Server input stream - {}", line); } }); } }
6,836
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/WorkflowBuilder.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def; import java.util.*; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.tasks.*; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import com.netflix.conductor.sdk.workflow.utils.InputOutputGetter; import com.netflix.conductor.sdk.workflow.utils.MapBuilder; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; /** * @param <T> Input type for the workflow */ public class WorkflowBuilder<T> { private String name; private String description; private int version; private String failureWorkflow; private String ownerEmail; private WorkflowDef.TimeoutPolicy timeoutPolicy; private long timeoutSeconds; private boolean restartable = true; private T defaultInput; private Map<String, Object> output = new HashMap<>(); private Map<String, Object> state; protected List<Task<?>> tasks = new ArrayList<>(); private WorkflowExecutor workflowExecutor; public final InputOutputGetter input = new InputOutputGetter("workflow", InputOutputGetter.Field.input); private final ObjectMapper objectMapper = new ObjectMapperProvider().getObjectMapper(); public WorkflowBuilder(WorkflowExecutor workflowExecutor) { this.workflowExecutor = workflowExecutor; this.tasks = new ArrayList<>(); } public WorkflowBuilder<T> name(String name) { this.name = name; return this; } public WorkflowBuilder<T> version(int version) { this.version = version; return this; } public WorkflowBuilder<T> description(String description) { this.description = description; return this; } public WorkflowBuilder<T> failureWorkflow(String failureWorkflow) { this.failureWorkflow = failureWorkflow; return this; } public WorkflowBuilder<T> ownerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; return this; } public WorkflowBuilder<T> timeoutPolicy( WorkflowDef.TimeoutPolicy timeoutPolicy, long timeoutSeconds) { this.timeoutPolicy = timeoutPolicy; this.timeoutSeconds = timeoutSeconds; return this; } public WorkflowBuilder<T> add(Task<?>... tasks) { Collections.addAll(this.tasks, tasks); return this; } public WorkflowBuilder<T> defaultInput(T defaultInput) { this.defaultInput = defaultInput; return this; } public WorkflowBuilder<T> restartable(boolean restartable) { this.restartable = restartable; return this; } public WorkflowBuilder<T> variables(Object variables) { try { this.state = objectMapper.convertValue(variables, Map.class); } catch (Exception e) { throw new IllegalArgumentException( "Workflow Variables cannot be converted to Map. Supplied: " + variables.getClass().getName()); } return this; } public WorkflowBuilder<T> output(String key, boolean value) { output.put(key, value); return this; } public WorkflowBuilder<T> output(String key, String value) { output.put(key, value); return this; } public WorkflowBuilder<T> output(String key, Number value) { output.put(key, value); return this; } public WorkflowBuilder<T> output(String key, Object value) { output.put(key, value); return this; } public WorkflowBuilder<T> output(MapBuilder mapBuilder) { output.putAll(mapBuilder.build()); return this; } public ConductorWorkflow<T> build() throws ValidationError { validate(); ConductorWorkflow<T> workflow = new ConductorWorkflow<T>(workflowExecutor); if (description != null) { workflow.setDescription(description); } workflow.setName(name); workflow.setVersion(version); workflow.setDescription(description); workflow.setFailureWorkflow(failureWorkflow); workflow.setOwnerEmail(ownerEmail); workflow.setTimeoutPolicy(timeoutPolicy); workflow.setTimeoutSeconds(timeoutSeconds); workflow.setRestartable(restartable); workflow.setDefaultInput(defaultInput); workflow.setWorkflowOutput(output); workflow.setVariables(state); for (Task task : tasks) { workflow.add(task); } return workflow; } /** * Validate: 1. There are no tasks with duplicate reference names 2. Each of the task is * consistent with its definition 3. */ private void validate() throws ValidationError { List<WorkflowTask> allTasks = new ArrayList<>(); for (Task task : tasks) { List<WorkflowTask> workflowDefTasks = task.getWorkflowDefTasks(); for (WorkflowTask workflowDefTask : workflowDefTasks) { allTasks.addAll(workflowDefTask.collectTasks()); } } Map<String, WorkflowTask> taskMap = new HashMap<>(); Set<String> duplicateTasks = new HashSet<>(); for (WorkflowTask task : allTasks) { if (taskMap.containsKey(task.getTaskReferenceName())) { duplicateTasks.add(task.getTaskReferenceName()); } else { taskMap.put(task.getTaskReferenceName(), task); } } if (!duplicateTasks.isEmpty()) { throw new ValidationError( "Task Reference Names MUST be unique across all the tasks in the workkflow. " + "Please update/change reference names to be unique for the following tasks: " + duplicateTasks); } } }
6,837
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/ValidationError.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def; public class ValidationError extends RuntimeException { public ValidationError(String message) { super(message); } }
6,838
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/ConductorWorkflow.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def; import java.util.*; import java.util.concurrent.CompletableFuture; import com.netflix.conductor.client.exception.ConductorClientException; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.sdk.workflow.def.tasks.Task; import com.netflix.conductor.sdk.workflow.def.tasks.TaskRegistry; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import com.netflix.conductor.sdk.workflow.utils.InputOutputGetter; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * @param <T> Type of the workflow input */ public class ConductorWorkflow<T> { public static final InputOutputGetter input = new InputOutputGetter("workflow", InputOutputGetter.Field.input); public static final InputOutputGetter output = new InputOutputGetter("workflow", InputOutputGetter.Field.output); private String name; private String description; private int version; private String failureWorkflow; private String ownerEmail; private WorkflowDef.TimeoutPolicy timeoutPolicy; private Map<String, Object> workflowOutput; private long timeoutSeconds; private boolean restartable = true; private T defaultInput; private Map<String, Object> variables; private List<Task> tasks = new ArrayList<>(); private final ObjectMapper objectMapper = new ObjectMapperProvider().getObjectMapper(); private final WorkflowExecutor workflowExecutor; public ConductorWorkflow(WorkflowExecutor workflowExecutor) { this.workflowOutput = new HashMap<>(); this.workflowExecutor = workflowExecutor; this.restartable = true; } public void setName(String name) { this.name = name; } public void setVersion(int version) { this.version = version; } public void setDescription(String description) { this.description = description; } public void setFailureWorkflow(String failureWorkflow) { this.failureWorkflow = failureWorkflow; } public void add(Task task) { this.tasks.add(task); } public String getName() { return name; } public String getDescription() { return description; } public int getVersion() { return version; } public String getFailureWorkflow() { return failureWorkflow; } public String getOwnerEmail() { return ownerEmail; } public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } public WorkflowDef.TimeoutPolicy getTimeoutPolicy() { return timeoutPolicy; } public void setTimeoutPolicy(WorkflowDef.TimeoutPolicy timeoutPolicy) { this.timeoutPolicy = timeoutPolicy; } public long getTimeoutSeconds() { return timeoutSeconds; } public void setTimeoutSeconds(long timeoutSeconds) { this.timeoutSeconds = timeoutSeconds; } public boolean isRestartable() { return restartable; } public void setRestartable(boolean restartable) { this.restartable = restartable; } public T getDefaultInput() { return defaultInput; } public void setDefaultInput(T defaultInput) { this.defaultInput = defaultInput; } public Map<String, Object> getWorkflowOutput() { return workflowOutput; } public void setWorkflowOutput(Map<String, Object> workflowOutput) { this.workflowOutput = workflowOutput; } public Object getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } /** * Execute a dynamic workflow without creating a definition in metadata store. * * <p><br> * <b>Note</b>: Use this with caution - as this does not promote re-usability of the workflows * * @param input Workflow Input - The input object is converted a JSON doc as an input to the * workflow * @return */ public CompletableFuture<Workflow> executeDynamic(T input) { return workflowExecutor.executeWorkflow(this, input); } /** * Executes the workflow using registered metadata definitions * * @see #registerWorkflow() * @param input * @return */ public CompletableFuture<Workflow> execute(T input) { return workflowExecutor.executeWorkflow(this.getName(), this.getVersion(), input); } /** * Registers a new workflow in the server. * * @return true if the workflow is successfully registered. False if the workflow cannot be * registered and the workflow definition already exists on the server with given name + * version The call will throw a runtime exception if any of the tasks are missing * definitions on the server. */ public boolean registerWorkflow() { return registerWorkflow(false, false); } /** * @param overwrite set to true if the workflow should be overwritten if the definition already * exists with the given name and version. <font color=red>Use with caution</font> * @return true if success, false otherwise. */ public boolean registerWorkflow(boolean overwrite) { return registerWorkflow(overwrite, false); } /** * @param overwrite set to true if the workflow should be overwritten if the definition already * exists with the given name and version. <font color=red>Use with caution</font> * @param registerTasks if set to true, missing task definitions are registered with the default * configuration. * @return true if success, false otherwise. */ public boolean registerWorkflow(boolean overwrite, boolean registerTasks) { WorkflowDef workflowDef = toWorkflowDef(); List<String> missing = getMissingTasks(workflowDef); if (!missing.isEmpty()) { if (!registerTasks) { throw new RuntimeException( "Workflow cannot be registered. The following tasks do not have definitions. " + "Please register these tasks before creating the workflow. Missing Tasks = " + missing); } else { String ownerEmail = this.ownerEmail; missing.stream().forEach(taskName -> registerTaskDef(taskName, ownerEmail)); } } return workflowExecutor.registerWorkflow(workflowDef, overwrite); } /** * @return Convert to the WorkflowDef model used by the Metadata APIs */ public WorkflowDef toWorkflowDef() { WorkflowDef def = new WorkflowDef(); def.setName(name); def.setDescription(description); def.setVersion(version); def.setFailureWorkflow(failureWorkflow); def.setOwnerEmail(ownerEmail); def.setTimeoutPolicy(timeoutPolicy); def.setTimeoutSeconds(timeoutSeconds); def.setRestartable(restartable); def.setOutputParameters(workflowOutput); def.setVariables(variables); def.setInputTemplate(objectMapper.convertValue(defaultInput, Map.class)); for (Task task : tasks) { def.getTasks().addAll(task.getWorkflowDefTasks()); } return def; } /** * Generate ConductorWorkflow based on the workflow metadata definition * * @param def * @return */ public static <T> ConductorWorkflow<T> fromWorkflowDef(WorkflowDef def) { ConductorWorkflow<T> workflow = new ConductorWorkflow<>(null); fromWorkflowDef(workflow, def); return workflow; } public ConductorWorkflow<T> from(String workflowName, Integer workflowVersion) { WorkflowDef def = workflowExecutor.getMetadataClient().getWorkflowDef(workflowName, workflowVersion); fromWorkflowDef(this, def); return this; } private static <T> void fromWorkflowDef(ConductorWorkflow<T> workflow, WorkflowDef def) { workflow.setName(def.getName()); workflow.setVersion(def.getVersion()); workflow.setFailureWorkflow(def.getFailureWorkflow()); workflow.setRestartable(def.isRestartable()); workflow.setVariables(def.getVariables()); workflow.setDefaultInput((T) def.getInputTemplate()); workflow.setWorkflowOutput(def.getOutputParameters()); workflow.setOwnerEmail(def.getOwnerEmail()); workflow.setDescription(def.getDescription()); workflow.setTimeoutSeconds(def.getTimeoutSeconds()); workflow.setTimeoutPolicy(def.getTimeoutPolicy()); List<WorkflowTask> workflowTasks = def.getTasks(); for (WorkflowTask workflowTask : workflowTasks) { Task task = TaskRegistry.getTask(workflowTask); workflow.tasks.add(task); } } private List<String> getMissingTasks(WorkflowDef workflowDef) { List<String> missing = new ArrayList<>(); workflowDef.collectTasks().stream() .filter(workflowTask -> workflowTask.getType().equals(TaskType.TASK_TYPE_SIMPLE)) .map(WorkflowTask::getName) .distinct() .parallel() .forEach( taskName -> { try { TaskDef taskDef = workflowExecutor.getMetadataClient().getTaskDef(taskName); } catch (ConductorClientException cce) { if (cce.getStatus() == 404) { missing.add(taskName); } else { throw cce; } } }); return missing; } private void registerTaskDef(String taskName, String ownerEmail) { TaskDef taskDef = new TaskDef(); taskDef.setName(taskName); taskDef.setOwnerEmail(ownerEmail); workflowExecutor.getMetadataClient().registerTaskDefs(Arrays.asList(taskDef)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConductorWorkflow workflow = (ConductorWorkflow) o; return version == workflow.version && Objects.equals(name, workflow.name); } @Override public int hashCode() { return Objects.hash(name, version); } @Override public String toString() { try { return objectMapper.writeValueAsString(toWorkflowDef()); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
6,839
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Join.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.Arrays; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; public class Join extends Task<Join> { private String[] joinOn; /** * @param taskReferenceName * @param joinOn List of task reference names to join on */ public Join(String taskReferenceName, String... joinOn) { super(taskReferenceName, TaskType.JOIN); this.joinOn = joinOn; } Join(WorkflowTask workflowTask) { super(workflowTask); this.joinOn = workflowTask.getJoinOn().toArray(new String[0]); } @Override protected void updateWorkflowTask(WorkflowTask workflowTask) { workflowTask.setJoinOn(Arrays.asList(joinOn)); } public String[] getJoinOn() { return joinOn; } }
6,840
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Terminate.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.HashMap; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.run.Workflow; public class Terminate extends Task<Terminate> { private static final String TERMINATION_STATUS_PARAMETER = "terminationStatus"; private static final String TERMINATION_WORKFLOW_OUTPUT = "workflowOutput"; private static final String TERMINATION_REASON_PARAMETER = "terminationReason"; /** * Terminate the workflow and mark it as FAILED * * @param taskReferenceName * @param reason */ public Terminate(String taskReferenceName, String reason) { this(taskReferenceName, Workflow.WorkflowStatus.FAILED, reason, new HashMap<>()); } /** * Terminate the workflow with a specific terminate status * * @param taskReferenceName * @param terminationStatus * @param reason */ public Terminate( String taskReferenceName, Workflow.WorkflowStatus terminationStatus, String reason) { this(taskReferenceName, terminationStatus, reason, new HashMap<>()); } public Terminate( String taskReferenceName, Workflow.WorkflowStatus terminationStatus, String reason, Object workflowOutput) { super(taskReferenceName, TaskType.TERMINATE); input(TERMINATION_STATUS_PARAMETER, terminationStatus.name()); input(TERMINATION_WORKFLOW_OUTPUT, workflowOutput); input(TERMINATION_REASON_PARAMETER, reason); } Terminate(WorkflowTask workflowTask) { super(workflowTask); } }
6,841
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/DoWhile.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; public class DoWhile extends Task<DoWhile> { private String loopCondition; private List<Task<?>> loopTasks = new ArrayList<>(); /** * Execute tasks in a loop determined by the condition set using condition parameter. The loop * will continue till the condition is true * * @param taskReferenceName * @param condition Javascript that evaluates to a boolean value * @param tasks */ public DoWhile(String taskReferenceName, String condition, Task<?>... tasks) { super(taskReferenceName, TaskType.DO_WHILE); Collections.addAll(this.loopTasks, tasks); this.loopCondition = condition; } /** * Similar to a for loop, run tasks for N times * * @param taskReferenceName * @param loopCount * @param tasks */ public DoWhile(String taskReferenceName, int loopCount, Task<?>... tasks) { super(taskReferenceName, TaskType.DO_WHILE); Collections.addAll(this.loopTasks, tasks); this.loopCondition = getForLoopCondition(loopCount); } DoWhile(WorkflowTask workflowTask) { super(workflowTask); this.loopCondition = workflowTask.getLoopCondition(); for (WorkflowTask task : workflowTask.getLoopOver()) { Task<?> loopTask = TaskRegistry.getTask(task); this.loopTasks.add(loopTask); } } public DoWhile loopOver(Task<?>... tasks) { for (Task<?> task : tasks) { this.loopTasks.add(task); } return this; } private String getForLoopCondition(int loopCount) { return "if ( $." + getTaskReferenceName() + "['iteration'] < " + loopCount + ") { true; } else { false; }"; } public String getLoopCondition() { return loopCondition; } public List<? extends Task> getLoopTasks() { return loopTasks; } @Override public void updateWorkflowTask(WorkflowTask workflowTask) { workflowTask.setLoopCondition(loopCondition); List<WorkflowTask> loopWorkflowTasks = new ArrayList<>(); for (Task task : this.loopTasks) { loopWorkflowTasks.addAll(task.getWorkflowDefTasks()); } workflowTask.setLoopOver(loopWorkflowTasks); } }
6,842
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/TaskRegistry.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; public class TaskRegistry { private static final Logger LOGGER = LoggerFactory.getLogger(TaskRegistry.class); private static Map<String, Class<? extends Task>> taskTypeMap = new HashMap<>(); public static void register(String taskType, Class<? extends Task> taskImplementation) { taskTypeMap.put(taskType, taskImplementation); } public static Task<?> getTask(WorkflowTask workflowTask) { Class<? extends Task> clazz = taskTypeMap.get(workflowTask.getType()); if (clazz == null) { throw new UnsupportedOperationException( "No support to convert " + workflowTask.getType()); } Task<?> task = null; try { task = clazz.getDeclaredConstructor(WorkflowTask.class).newInstance(workflowTask); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return task; } return task; } }
6,843
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Javascript.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.ValidationError; import com.google.common.base.Strings; /** * JQ Transformation task See https://stedolan.github.io/jq/ for how to form the queries to parse * JSON payloads */ public class Javascript extends Task<Javascript> { private static final Logger LOGGER = LoggerFactory.getLogger(Javascript.class); private static final String EXPRESSION_PARAMETER = "expression"; private static final String EVALUATOR_TYPE_PARAMETER = "evaluatorType"; private static final String ENGINE = "nashorn"; /** * Javascript tasks are executed on the Conductor server without having to write worker code * * <p>Use {@link Javascript#validate()} method to validate the javascript to ensure the script * is valid. * * @param taskReferenceName * @param script script to execute */ public Javascript(String taskReferenceName, String script) { super(taskReferenceName, TaskType.INLINE); if (Strings.isNullOrEmpty(script)) { throw new AssertionError("Null/Empty script"); } super.input(EVALUATOR_TYPE_PARAMETER, "javascript"); super.input(EXPRESSION_PARAMETER, script); } /** * Javascript tasks are executed on the Conductor server without having to write worker code * * <p>Use {@link Javascript#validate()} method to validate the javascript to ensure the script * is valid. * * @param taskReferenceName * @param stream stream to load the script file from */ public Javascript(String taskReferenceName, InputStream stream) { super(taskReferenceName, TaskType.INLINE); if (stream == null) { throw new AssertionError("Stream is empty"); } super.input(EVALUATOR_TYPE_PARAMETER, "javascript"); try { String script = new String(stream.readAllBytes()); super.input(EXPRESSION_PARAMETER, script); } catch (IOException e) { throw new RuntimeException(e); } } Javascript(WorkflowTask workflowTask) { super(workflowTask); } public String getExpression() { return (String) getInput().get(EXPRESSION_PARAMETER); } /** * Validates the script. * * @return */ public Javascript validate() { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("Nashorn"); if (scriptEngine == null) { LOGGER.error("missing " + ENGINE + " engine. Ensure you are running supported JVM"); return this; } try { Bindings bindings = scriptEngine.createBindings(); bindings.put("$", new HashMap<>()); scriptEngine.eval(getExpression(), bindings); } catch (ScriptException e) { String message = e.getMessage(); throw new ValidationError(message); } return this; } /** * Helper method to unit test your javascript. The method is not used for creating or executing * workflow but is meant for testing only. * * @param input Input that against which the script will be executed * @return Output of the script */ public Object test(Map<String, Object> input) { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("Nashorn"); if (scriptEngine == null) { LOGGER.error("missing " + ENGINE + " engine. Ensure you are running supported JVM"); return this; } try { Bindings bindings = scriptEngine.createBindings(); bindings.put("$", input); return scriptEngine.eval(getExpression(), bindings); } catch (ScriptException e) { String message = e.getMessage(); throw new ValidationError(message); } } }
6,844
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/ForkJoin.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; /** ForkJoin task */ public class ForkJoin extends Task<ForkJoin> { private Join join; private Task[][] forkedTasks; /** * execute task specified in the forkedTasks parameter in parallel. * * <p>forkedTask is a two-dimensional list that executes the outermost list in parallel and list * within that is executed sequentially. * * <p>e.g. [[task1, task2],[task3, task4],[task5]] are executed as: * * <pre> * --------------- * | fork | * --------------- * | | | * | | | * task1 task3 task5 * task2 task4 | * | | | * --------------------- * | join | * --------------------- * </pre> * * <p>This method automatically adds a join that waits for all the *last* tasks in the fork * (e.g. task2, task4 and task5 in the above example) to be completed.* * * <p>Use join method @see {@link ForkJoin#joinOn(String...)} to override this behavior (note: * not a common scenario) * * @param taskReferenceName unique task reference name * @param forkedTasks List of tasks to be executed in parallel */ public ForkJoin(String taskReferenceName, Task<?>[]... forkedTasks) { super(taskReferenceName, TaskType.FORK_JOIN); this.forkedTasks = forkedTasks; } ForkJoin(WorkflowTask workflowTask) { super(workflowTask); int size = workflowTask.getForkTasks().size(); this.forkedTasks = new Task[size][]; int i = 0; for (List<WorkflowTask> forkTasks : workflowTask.getForkTasks()) { Task[] tasks = new Task[forkTasks.size()]; for (int j = 0; j < forkTasks.size(); j++) { WorkflowTask forkWorkflowTask = forkTasks.get(j); Task task = TaskRegistry.getTask(forkWorkflowTask); tasks[j] = task; } this.forkedTasks[i++] = tasks; } } public ForkJoin joinOn(String... joinOn) { this.join = new Join(getTaskReferenceName() + "_join", joinOn); return this; } @Override protected List<WorkflowTask> getChildrenTasks() { WorkflowTask fork = toWorkflowTask(); WorkflowTask joinWorkflowTask = null; if (this.join != null) { List<WorkflowTask> joinTasks = this.join.getWorkflowDefTasks(); joinWorkflowTask = joinTasks.get(0); } else { joinWorkflowTask = new WorkflowTask(); joinWorkflowTask.setWorkflowTaskType(TaskType.JOIN); joinWorkflowTask.setTaskReferenceName(getTaskReferenceName() + "_join"); joinWorkflowTask.setName(joinWorkflowTask.getTaskReferenceName()); joinWorkflowTask.setJoinOn(fork.getJoinOn()); } return Arrays.asList(joinWorkflowTask); } @Override public void updateWorkflowTask(WorkflowTask fork) { List<String> joinOnTaskRefNames = new ArrayList<>(); List<List<WorkflowTask>> forkTasks = new ArrayList<>(); for (Task<?>[] forkedTaskList : forkedTasks) { List<WorkflowTask> forkedWorkflowTasks = new ArrayList<>(); for (Task<?> baseWorkflowTask : forkedTaskList) { forkedWorkflowTasks.addAll(baseWorkflowTask.getWorkflowDefTasks()); } forkTasks.add(forkedWorkflowTasks); joinOnTaskRefNames.add( forkedWorkflowTasks.get(forkedWorkflowTasks.size() - 1).getTaskReferenceName()); } if (this.join != null) { fork.setJoinOn(List.of(this.join.getJoinOn())); } else { fork.setJoinOn(joinOnTaskRefNames); } fork.setForkTasks(forkTasks); } public Task[][] getForkedTasks() { return forkedTasks; } }
6,845
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/JQ.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.google.common.base.Strings; /** * JQ Transformation task See https://stedolan.github.io/jq/ for how to form the queries to parse * JSON payloads */ public class JQ extends Task<JQ> { private static final String QUERY_EXPRESSION_PARAMETER = "queryExpression"; public JQ(String taskReferenceName, String queryExpression) { super(taskReferenceName, TaskType.JSON_JQ_TRANSFORM); if (Strings.isNullOrEmpty(queryExpression)) { throw new AssertionError("Null/Empty queryExpression"); } super.input(QUERY_EXPRESSION_PARAMETER, queryExpression); } JQ(WorkflowTask workflowTask) { super(workflowTask); } public String getQueryExpression() { return (String) getInput().get(QUERY_EXPRESSION_PARAMETER); } }
6,846
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/SimpleTask.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; /** Workflow task executed by a worker */ public class SimpleTask extends Task<SimpleTask> { private TaskDef taskDef; public SimpleTask(String taskDefName, String taskReferenceName) { super(taskReferenceName, TaskType.SIMPLE); super.name(taskDefName); } SimpleTask(WorkflowTask workflowTask) { super(workflowTask); this.taskDef = workflowTask.getTaskDefinition(); } public TaskDef getTaskDef() { return taskDef; } public SimpleTask setTaskDef(TaskDef taskDef) { this.taskDef = taskDef; return this; } @Override protected void updateWorkflowTask(WorkflowTask workflowTask) { workflowTask.setTaskDefinition(taskDef); } }
6,847
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Event.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.google.common.base.Strings; /** Task to publish Events to external queuing systems like SQS, NATS, AMQP etc. */ public class Event extends Task<Event> { private static final String SINK_PARAMETER = "sink"; /** * @param taskReferenceName Unique reference name within the workflow * @param eventSink qualified name of the event sink where the message is published. Using the * format sink_type:location e.g. sqs:sqs_queue_name, amqp_queue:queue_name, * amqp_exchange:queue_name, nats:queue_name */ public Event(String taskReferenceName, String eventSink) { super(taskReferenceName, TaskType.EVENT); if (Strings.isNullOrEmpty(eventSink)) { throw new AssertionError("Null/Empty eventSink"); } super.input(SINK_PARAMETER, eventSink); } Event(WorkflowTask workflowTask) { super(workflowTask); } public String getSink() { return (String) getInput().get(SINK_PARAMETER); } }
6,848
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Http.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; /** Wait task */ public class Http extends Task<Http> { private static final Logger LOGGER = LoggerFactory.getLogger(Http.class); private static final String INPUT_PARAM = "http_request"; private ObjectMapper objectMapper = new ObjectMapperProvider().getObjectMapper(); private Input httpRequest; public Http(String taskReferenceName) { super(taskReferenceName, TaskType.HTTP); this.httpRequest = new Input(); this.httpRequest.method = Input.HttpMethod.GET; super.input(INPUT_PARAM, httpRequest); } Http(WorkflowTask workflowTask) { super(workflowTask); Object inputRequest = workflowTask.getInputParameters().get(INPUT_PARAM); if (inputRequest != null) { try { this.httpRequest = objectMapper.convertValue(inputRequest, Input.class); } catch (Exception e) { LOGGER.error("Error while trying to convert input request " + e.getMessage(), e); } } } public Http input(Input httpRequest) { this.httpRequest = httpRequest; return this; } public Http url(String url) { this.httpRequest.setUri(url); return this; } public Http method(Input.HttpMethod method) { this.httpRequest.setMethod(method); return this; } public Http headers(Map<String, Object> headers) { this.httpRequest.setHeaders(headers); return this; } public Http body(Object body) { this.httpRequest.setBody(body); return this; } public Http readTimeout(int readTimeout) { this.httpRequest.setReadTimeOut(readTimeout); return this; } public Input getHttpRequest() { return httpRequest; } @Override protected void updateWorkflowTask(WorkflowTask workflowTask) { workflowTask.getInputParameters().put(INPUT_PARAM, httpRequest); } public static class Input { public enum HttpMethod { PUT, POST, GET, DELETE, OPTIONS, HEAD } private HttpMethod method; // PUT, POST, GET, DELETE, OPTIONS, HEAD private String vipAddress; private String appName; private Map<String, Object> headers = new HashMap<>(); private String uri; private Object body; private String accept = "application/json"; private String contentType = "application/json"; private Integer connectionTimeOut; private Integer readTimeOut; /** * @return the method */ public HttpMethod getMethod() { return method; } /** * @param method the method to set */ public void setMethod(HttpMethod method) { this.method = method; } /** * @return the headers */ public Map<String, Object> getHeaders() { return headers; } /** * @param headers the headers to set */ public void setHeaders(Map<String, Object> headers) { this.headers = headers; } /** * @return the body */ public Object getBody() { return body; } /** * @param body the body to set */ public void setBody(Object body) { this.body = body; } /** * @return the uri */ public String getUri() { return uri; } /** * @param uri the uri to set */ public void setUri(String uri) { this.uri = uri; } /** * @return the vipAddress */ public String getVipAddress() { return vipAddress; } /** * @param vipAddress the vipAddress to set */ public void setVipAddress(String vipAddress) { this.vipAddress = vipAddress; } /** * @return the accept */ public String getAccept() { return accept; } /** * @param accept the accept to set */ public void setAccept(String accept) { this.accept = accept; } /** * @return the MIME content type to use for the request */ public String getContentType() { return contentType; } /** * @param contentType the MIME content type to set */ public void setContentType(String contentType) { this.contentType = contentType; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } /** * @return the connectionTimeOut */ public Integer getConnectionTimeOut() { return connectionTimeOut; } /** * @return the readTimeOut */ public Integer getReadTimeOut() { return readTimeOut; } public void setConnectionTimeOut(Integer connectionTimeOut) { this.connectionTimeOut = connectionTimeOut; } public void setReadTimeOut(Integer readTimeOut) { this.readTimeOut = readTimeOut; } @Override public String toString() { return "Input{" + "method=" + method + ", vipAddress='" + vipAddress + '\'' + ", appName='" + appName + '\'' + ", headers=" + headers + ", uri='" + uri + '\'' + ", body=" + body + ", accept='" + accept + '\'' + ", contentType='" + contentType + '\'' + ", connectionTimeOut=" + connectionTimeOut + ", readTimeOut=" + readTimeOut + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Input input = (Input) o; return method == input.method && Objects.equals(vipAddress, input.vipAddress) && Objects.equals(appName, input.appName) && Objects.equals(headers, input.headers) && Objects.equals(uri, input.uri) && Objects.equals(body, input.body) && Objects.equals(accept, input.accept) && Objects.equals(contentType, input.contentType) && Objects.equals(connectionTimeOut, input.connectionTimeOut) && Objects.equals(readTimeOut, input.readTimeOut); } @Override public int hashCode() { return Objects.hash( method, vipAddress, appName, headers, uri, body, accept, contentType, connectionTimeOut, readTimeOut); } } }
6,849
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Dynamic.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.google.common.base.Strings; /** Wait task */ public class Dynamic extends Task<Dynamic> { public static final String TASK_NAME_INPUT_PARAM = "taskToExecute"; public Dynamic(String taskReferenceName, String dynamicTaskNameValue) { super(taskReferenceName, TaskType.DYNAMIC); if (Strings.isNullOrEmpty(dynamicTaskNameValue)) { throw new AssertionError("Null/Empty dynamicTaskNameValue"); } super.input(TASK_NAME_INPUT_PARAM, dynamicTaskNameValue); } Dynamic(WorkflowTask workflowTask) { super(workflowTask); } @Override public void updateWorkflowTask(WorkflowTask task) { task.setDynamicTaskNameParam(TASK_NAME_INPUT_PARAM); } }
6,850
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Task.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.*; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.utils.InputOutputGetter; import com.netflix.conductor.sdk.workflow.utils.MapBuilder; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; /** Workflow Task */ public abstract class Task<T> { private String name; private String description; private String taskReferenceName; private boolean optional; private int startDelay; private TaskType type; private Map<String, Object> input = new HashMap<>(); protected final ObjectMapper om = new ObjectMapperProvider().getObjectMapper(); public final InputOutputGetter taskInput; public final InputOutputGetter taskOutput; public Task(String taskReferenceName, TaskType type) { if (Strings.isNullOrEmpty(taskReferenceName)) { throw new AssertionError("taskReferenceName cannot be null"); } if (type == null) { throw new AssertionError("type cannot be null"); } this.name = taskReferenceName; this.taskReferenceName = taskReferenceName; this.type = type; this.taskInput = new InputOutputGetter(taskReferenceName, InputOutputGetter.Field.input); this.taskOutput = new InputOutputGetter(taskReferenceName, InputOutputGetter.Field.output); } Task(WorkflowTask workflowTask) { this(workflowTask.getTaskReferenceName(), TaskType.valueOf(workflowTask.getType())); this.input = workflowTask.getInputParameters(); this.description = workflowTask.getDescription(); this.name = workflowTask.getName(); } public T name(String name) { this.name = name; return (T) this; } public T description(String description) { this.description = description; return (T) this; } public T input(String key, boolean value) { input.put(key, value); return (T) this; } public T input(String key, Object value) { input.put(key, value); return (T) this; } public T input(String key, char value) { input.put(key, value); return (T) this; } public T input(String key, InputOutputGetter value) { input.put(key, value.getParent()); return (T) this; } public T input(InputOutputGetter value) { return input("input", value); } public T input(String key, String value) { input.put(key, value); return (T) this; } public T input(String key, Number value) { input.put(key, value); return (T) this; } public T input(String key, Map<String, Object> value) { input.put(key, value); return (T) this; } public T input(Map<String, Object> map) { input.putAll(map); return (T) this; } public T input(MapBuilder builder) { input.putAll(builder.build()); return (T) this; } public T input(Object... keyValues) { if (keyValues.length == 1) { Object kv = keyValues[0]; Map objectMap = om.convertValue(kv, Map.class); input.putAll(objectMap); return (T) this; } if (keyValues.length % 2 == 1) { throw new IllegalArgumentException("Not all keys have value specified"); } for (int i = 0; i < keyValues.length; ) { String key = keyValues[i].toString(); Object value = keyValues[i + 1]; input.put(key, value); i += 2; } return (T) this; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTaskReferenceName() { return taskReferenceName; } public void setTaskReferenceName(String taskReferenceName) { this.taskReferenceName = taskReferenceName; } public boolean isOptional() { return optional; } public void setOptional(boolean optional) { this.optional = optional; } public int getStartDelay() { return startDelay; } public void setStartDelay(int startDelay) { this.startDelay = startDelay; } public TaskType getType() { return type; } public String getDescription() { return description; } public Map<String, Object> getInput() { return input; } public final List<WorkflowTask> getWorkflowDefTasks() { List<WorkflowTask> workflowTasks = new ArrayList<>(); workflowTasks.addAll(getParentTasks()); workflowTasks.add(toWorkflowTask()); workflowTasks.addAll(getChildrenTasks()); return workflowTasks; } protected final WorkflowTask toWorkflowTask() { WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setName(name); workflowTask.setTaskReferenceName(taskReferenceName); workflowTask.setWorkflowTaskType(type); workflowTask.setDescription(description); workflowTask.setInputParameters(input); workflowTask.setStartDelay(startDelay); workflowTask.setOptional(optional); // Let the sub-classes enrich the workflow task before returning back updateWorkflowTask(workflowTask); return workflowTask; } /** * Override this method when the sub-class should update the default WorkflowTask generated * using {@link #toWorkflowTask()} * * @param workflowTask */ protected void updateWorkflowTask(WorkflowTask workflowTask) {} /** * Override this method when sub-classes will generate multiple workflow tasks. Used by tasks * which have children tasks such as do_while, fork, etc. * * @return */ protected List<WorkflowTask> getChildrenTasks() { return List.of(); } protected List<WorkflowTask> getParentTasks() { return List.of(); } }
6,851
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/DynamicFork.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.ArrayList; import java.util.List; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; public class DynamicFork extends Task<DynamicFork> { public static final String FORK_TASK_PARAM = "forkedTasks"; public static final String FORK_TASK_INPUT_PARAM = "forkedTasksInputs"; private String forkTasksParameter; private String forkTasksInputsParameter; private Join join; private SimpleTask forkPrepareTask; /** * Dynamic fork task that executes a set of tasks in parallel which are determined at run time. * Use cases: Based on the input, you want to fork N number of processes in parallel to be * executed. The number N is not pre-determined at the definition time and so a regular ForkJoin * cannot be used. * * @param taskReferenceName */ public DynamicFork( String taskReferenceName, String forkTasksParameter, String forkTasksInputsParameter) { super(taskReferenceName, TaskType.FORK_JOIN_DYNAMIC); this.join = new Join(taskReferenceName + "_join"); this.forkTasksParameter = forkTasksParameter; this.forkTasksInputsParameter = forkTasksInputsParameter; super.input(FORK_TASK_PARAM, forkTasksParameter); super.input(FORK_TASK_INPUT_PARAM, forkTasksInputsParameter); } /** * Dynamic fork task that executes a set of tasks in parallel which are determined at run time. * Use cases: Based on the input, you want to fork N number of processes in parallel to be * executed. The number N is not pre-determined at the definition time and so a regular ForkJoin * cannot be used. * * @param taskReferenceName * @param forkPrepareTask A Task that produces the output as {@link DynamicForkInput} to specify * which tasks to fork. */ public DynamicFork(String taskReferenceName, SimpleTask forkPrepareTask) { super(taskReferenceName, TaskType.FORK_JOIN_DYNAMIC); this.forkPrepareTask = forkPrepareTask; this.join = new Join(taskReferenceName + "_join"); this.forkTasksParameter = forkPrepareTask.taskOutput.get(FORK_TASK_PARAM); this.forkTasksInputsParameter = forkPrepareTask.taskOutput.get(FORK_TASK_INPUT_PARAM); super.input(FORK_TASK_PARAM, forkTasksParameter); super.input(FORK_TASK_INPUT_PARAM, forkTasksInputsParameter); } DynamicFork(WorkflowTask workflowTask) { super(workflowTask); String nameOfParamForForkTask = workflowTask.getDynamicForkTasksParam(); String nameOfParamForForkTaskInput = workflowTask.getDynamicForkTasksInputParamName(); this.forkTasksParameter = (String) workflowTask.getInputParameters().get(nameOfParamForForkTask); this.forkTasksInputsParameter = (String) workflowTask.getInputParameters().get(nameOfParamForForkTaskInput); } public Join getJoin() { return join; } public String getForkTasksParameter() { return forkTasksParameter; } public String getForkTasksInputsParameter() { return forkTasksInputsParameter; } @Override public void updateWorkflowTask(WorkflowTask task) { task.setDynamicForkTasksParam("forkedTasks"); task.setDynamicForkTasksInputParamName("forkedTasksInputs"); } @Override protected List<WorkflowTask> getChildrenTasks() { List<WorkflowTask> tasks = new ArrayList<>(); tasks.addAll(join.getWorkflowDefTasks()); return tasks; } @Override protected List<WorkflowTask> getParentTasks() { if (forkPrepareTask != null) { return List.of(forkPrepareTask.toWorkflowTask()); } return List.of(); } }
6,852
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/SetVariable.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.WorkflowBuilder; public class SetVariable extends Task<SetVariable> { /** * Sets the value of the variable in workflow. Used for workflow state management. Workflow * state is a Map that is initialized using @see {@link WorkflowBuilder#variables(Object)} * * @param taskReferenceName Use input methods to set the variable values */ public SetVariable(String taskReferenceName) { super(taskReferenceName, TaskType.SET_VARIABLE); } SetVariable(WorkflowTask workflowTask) { super(workflowTask); } }
6,853
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/DynamicForkInput.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.List; import java.util.Map; public class DynamicForkInput { /** List of tasks to execute in parallel */ private List<Task<?>> tasks; /** * Input to the tasks. Key is the reference name of the task and value is an Object that is sent * as input to the task */ private Map<String, Object> inputs; public DynamicForkInput(List<Task<?>> tasks, Map<String, Object> inputs) { this.tasks = tasks; this.inputs = inputs; } public DynamicForkInput() {} public List<Task<?>> getTasks() { return tasks; } public void setTasks(List<Task<?>> tasks) { this.tasks = tasks; } public Map<String, Object> getInputs() { return inputs; } public void setInputs(Map<String, Object> inputs) { this.inputs = inputs; } }
6,854
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/SubWorkflow.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.SubWorkflowParams; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; public class SubWorkflow extends Task<SubWorkflow> { private ConductorWorkflow conductorWorkflow; private String workflowName; private Integer workflowVersion; /** * Start a workflow as a sub-workflow * * @param taskReferenceName * @param workflowName * @param workflowVersion */ public SubWorkflow(String taskReferenceName, String workflowName, Integer workflowVersion) { super(taskReferenceName, TaskType.SUB_WORKFLOW); this.workflowName = workflowName; this.workflowVersion = workflowVersion; } /** * Start a workflow as a sub-workflow * * @param taskReferenceName * @param conductorWorkflow */ public SubWorkflow(String taskReferenceName, ConductorWorkflow conductorWorkflow) { super(taskReferenceName, TaskType.SUB_WORKFLOW); this.conductorWorkflow = conductorWorkflow; } SubWorkflow(WorkflowTask workflowTask) { super(workflowTask); SubWorkflowParams subworkflowParam = workflowTask.getSubWorkflowParam(); this.workflowName = subworkflowParam.getName(); this.workflowVersion = subworkflowParam.getVersion(); if (subworkflowParam.getWorkflowDef() != null) { this.conductorWorkflow = ConductorWorkflow.fromWorkflowDef(subworkflowParam.getWorkflowDef()); } } public ConductorWorkflow getConductorWorkflow() { return conductorWorkflow; } public String getWorkflowName() { return workflowName; } public int getWorkflowVersion() { return workflowVersion; } @Override protected void updateWorkflowTask(WorkflowTask workflowTask) { SubWorkflowParams subWorkflowParam = new SubWorkflowParams(); if (conductorWorkflow != null) { subWorkflowParam.setWorkflowDef(conductorWorkflow.toWorkflowDef()); } else { subWorkflowParam.setName(workflowName); subWorkflowParam.setVersion(workflowVersion); } workflowTask.setSubWorkflowParam(subWorkflowParam); } }
6,855
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Switch.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.util.*; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; /** Switch Task */ public class Switch extends Task<Switch> { public static final String VALUE_PARAM_NAME = "value-param"; public static final String JAVASCRIPT_NAME = "javascript"; private String caseExpression; private boolean useJavascript; private List<Task<?>> defaultTasks = new ArrayList<>(); private Map<String, List<Task<?>>> branches = new HashMap<>(); /** * Switch case (similar to if...then...else or switch in java language) * * @param taskReferenceName * @param caseExpression An expression that outputs a string value to be used as case branches. * Case expression can be a support value parameter e.g. ${workflow.input.key} or * ${task.output.key} or a Javascript statement. * @param useJavascript set to true if the caseExpression is a javascript statement */ public Switch(String taskReferenceName, String caseExpression, boolean useJavascript) { super(taskReferenceName, TaskType.SWITCH); this.caseExpression = caseExpression; this.useJavascript = useJavascript; } /** * Switch case (similar to if...then...else or switch in java language) * * @param taskReferenceName * @param caseExpression */ public Switch(String taskReferenceName, String caseExpression) { super(taskReferenceName, TaskType.SWITCH); this.caseExpression = caseExpression; this.useJavascript = false; } Switch(WorkflowTask workflowTask) { super(workflowTask); Map<String, List<WorkflowTask>> decisions = workflowTask.getDecisionCases(); decisions.entrySet().stream() .forEach( branch -> { String branchName = branch.getKey(); List<WorkflowTask> branchWorkflowTasks = branch.getValue(); List<Task<?>> branchTasks = new ArrayList<>(); for (WorkflowTask branchWorkflowTask : branchWorkflowTasks) { branchTasks.add(TaskRegistry.getTask(branchWorkflowTask)); } this.branches.put(branchName, branchTasks); }); List<WorkflowTask> defaultCases = workflowTask.getDefaultCase(); for (WorkflowTask defaultCase : defaultCases) { this.defaultTasks.add(TaskRegistry.getTask(defaultCase)); } } public Switch defaultCase(Task<?>... tasks) { defaultTasks = Arrays.asList(tasks); return this; } public Switch defaultCase(List<Task<?>> defaultTasks) { this.defaultTasks = defaultTasks; return this; } public Switch decisionCases(Map<String, List<Task<?>>> branches) { this.branches = branches; return this; } public Switch defaultCase(String... workerTasks) { for (String workerTask : workerTasks) { this.defaultTasks.add(new SimpleTask(workerTask, workerTask)); } return this; } public Switch switchCase(String caseValue, Task... tasks) { branches.put(caseValue, Arrays.asList(tasks)); return this; } public Switch switchCase(String caseValue, String... workerTasks) { List<Task<?>> tasks = new ArrayList<>(workerTasks.length); int i = 0; for (String workerTask : workerTasks) { tasks.add(new SimpleTask(workerTask, workerTask)); } branches.put(caseValue, tasks); return this; } public List<Task<?>> getDefaultTasks() { return defaultTasks; } public Map<String, List<Task<?>>> getBranches() { return branches; } @Override public void updateWorkflowTask(WorkflowTask workflowTask) { if (useJavascript) { workflowTask.setEvaluatorType(JAVASCRIPT_NAME); workflowTask.setExpression(caseExpression); } else { workflowTask.setEvaluatorType(VALUE_PARAM_NAME); workflowTask.getInputParameters().put("switchCaseValue", caseExpression); workflowTask.setExpression("switchCaseValue"); } Map<String, List<WorkflowTask>> decisionCases = new HashMap<>(); branches.entrySet() .forEach( entry -> { String decisionCase = entry.getKey(); List<Task<?>> decisionTasks = entry.getValue(); List<WorkflowTask> decionTaskDefs = new ArrayList<>(decisionTasks.size()); for (Task<?> decisionTask : decisionTasks) { decionTaskDefs.addAll(decisionTask.getWorkflowDefTasks()); } decisionCases.put(decisionCase, decionTaskDefs); }); workflowTask.setDecisionCases(decisionCases); List<WorkflowTask> defaultCaseTaskDefs = new ArrayList<>(defaultTasks.size()); for (Task<?> defaultTask : defaultTasks) { defaultCaseTaskDefs.addAll(defaultTask.getWorkflowDefTasks()); } workflowTask.setDefaultCase(defaultCaseTaskDefs); } }
6,856
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Wait.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.def.tasks; import java.time.Duration; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import javax.swing.*; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; /** Wait task */ public class Wait extends Task<Wait> { public static final String DURATION_INPUT = "duration"; public static final String UNTIL_INPUT = "until"; public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z"); /** * Wait until and external signal completes the task. The external signal can be either an API * call (POST /api/task) to update the task status or an event coming from a supported external * queue integration like SQS, Kafka, NATS, AMQP etc. * * <p><br> * see <a href=https://netflix.github.io/conductor/reference-docs/wait-task/> * https://netflix.github.io/conductor/reference-docs/wait-task</a> for more details * * @param taskReferenceName */ public Wait(String taskReferenceName) { super(taskReferenceName, TaskType.WAIT); } public Wait(String taskReferenceName, Duration waitFor) { super(taskReferenceName, TaskType.WAIT); long seconds = waitFor.getSeconds(); input(DURATION_INPUT, seconds + "s"); } public Wait(String taskReferenceName, ZonedDateTime waitUntil) { super(taskReferenceName, TaskType.WAIT); String formattedDateTime = waitUntil.format(dateTimeFormatter); input(UNTIL_INPUT, formattedDateTime); } Wait(WorkflowTask workflowTask) { super(workflowTask); } }
6,857
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/utils/ObjectMapperProvider.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.utils; import com.netflix.conductor.common.jackson.JsonProtoModule; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class ObjectMapperProvider { public ObjectMapper getObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.setDefaultPropertyInclusion( JsonInclude.Value.construct( JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_EMPTY)); objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); // objectMapper.setSerializationInclusion(JsonInclude.Include.); objectMapper.registerModule(new JsonProtoModule()); return objectMapper; } }
6,858
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/utils/InputOutputGetter.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.utils; import com.fasterxml.jackson.annotation.JsonIgnore; public class InputOutputGetter { public enum Field { input, output } public static final class Map { private final String parent; public Map(String parent) { this.parent = parent; } public String get(String key) { return parent + "." + key + "}"; } public Map map(String key) { return new Map(parent + "." + key); } public List list(String key) { return new List(parent + "." + key); } @Override public String toString() { return parent + "}"; } } public static final class List { private final String parent; public List(String parent) { this.parent = parent; } public List list(String key) { return new List(parent + "." + key); } public Map map(String key) { return new Map(parent + "." + key); } public String get(String key, int index) { return parent + "." + key + "[" + index + "]}"; } public String get(int index) { return parent + "[" + index + "]}"; } @Override public String toString() { return parent + "}"; } } private final String name; private final Field field; public InputOutputGetter(String name, Field field) { this.name = name; this.field = field; } public String get(String key) { return "${" + name + "." + field + "." + key + "}"; } public String getParent() { return "${" + name + "." + field + "}"; } @JsonIgnore public Map map(String key) { return new Map("${" + name + "." + field + "." + key); } @JsonIgnore public List list(String key) { return new List("${" + name + "." + field + "." + key); } }
6,859
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/utils/MapBuilder.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.utils; import java.util.HashMap; import java.util.Map; public class MapBuilder { private Map<String, Object> map = new HashMap<>(); public MapBuilder add(String key, String value) { map.put(key, value); return this; } public MapBuilder add(String key, Number value) { map.put(key, value); return this; } public MapBuilder add(String key, MapBuilder value) { map.put(key, value.build()); return this; } public Map<String, Object> build() { return map; } }
6,860
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/task/InputParam.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.task; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface InputParam { String value(); boolean required() default false; }
6,861
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/task/WorkerTask.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.task; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** Identifies a simple worker task. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface WorkerTask { String value(); // No. of threads to use for executing the task int threadCount() default 1; int pollingInterval() default 100; String domain() default ""; }
6,862
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/task/OutputParam.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.task; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE) public @interface OutputParam { String value(); }
6,863
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/WorkflowExecutor.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.client.http.MetadataClient; import com.netflix.conductor.client.http.TaskClient; import com.netflix.conductor.client.http.WorkflowClient; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; import com.netflix.conductor.sdk.workflow.def.tasks.*; import com.netflix.conductor.sdk.workflow.executor.task.AnnotatedWorkerExecutor; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.jersey.api.client.ClientHandler; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.ClientFilter; public class WorkflowExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowExecutor.class); private final TypeReference<List<TaskDef>> listOfTaskDefs = new TypeReference<>() {}; private Map<String, CompletableFuture<Workflow>> runningWorkflowFutures = new ConcurrentHashMap<>(); private final ObjectMapper objectMapper = new ObjectMapperProvider().getObjectMapper(); private final TaskClient taskClient; private final WorkflowClient workflowClient; private final MetadataClient metadataClient; private final AnnotatedWorkerExecutor annotatedWorkerExecutor; private final ScheduledExecutorService scheduledWorkflowMonitor = Executors.newSingleThreadScheduledExecutor(); static { initTaskImplementations(); } public static void initTaskImplementations() { TaskRegistry.register(TaskType.DO_WHILE.name(), DoWhile.class); TaskRegistry.register(TaskType.DYNAMIC.name(), Dynamic.class); TaskRegistry.register(TaskType.FORK_JOIN_DYNAMIC.name(), DynamicFork.class); TaskRegistry.register(TaskType.FORK_JOIN.name(), ForkJoin.class); TaskRegistry.register(TaskType.HTTP.name(), Http.class); TaskRegistry.register(TaskType.INLINE.name(), Javascript.class); TaskRegistry.register(TaskType.JOIN.name(), Join.class); TaskRegistry.register(TaskType.JSON_JQ_TRANSFORM.name(), JQ.class); TaskRegistry.register(TaskType.SET_VARIABLE.name(), SetVariable.class); TaskRegistry.register(TaskType.SIMPLE.name(), SimpleTask.class); TaskRegistry.register(TaskType.SUB_WORKFLOW.name(), SubWorkflow.class); TaskRegistry.register(TaskType.SWITCH.name(), Switch.class); TaskRegistry.register(TaskType.TERMINATE.name(), Terminate.class); TaskRegistry.register(TaskType.WAIT.name(), Wait.class); TaskRegistry.register(TaskType.EVENT.name(), Event.class); } public WorkflowExecutor(String apiServerURL) { this(apiServerURL, 100); } public WorkflowExecutor( String apiServerURL, int pollingInterval, ClientFilter... clientFilter) { taskClient = new TaskClient(new DefaultClientConfig(), (ClientHandler) null, clientFilter); taskClient.setRootURI(apiServerURL); workflowClient = new WorkflowClient(new DefaultClientConfig(), (ClientHandler) null, clientFilter); workflowClient.setRootURI(apiServerURL); metadataClient = new MetadataClient(new DefaultClientConfig(), (ClientHandler) null, clientFilter); metadataClient.setRootURI(apiServerURL); annotatedWorkerExecutor = new AnnotatedWorkerExecutor(taskClient, pollingInterval); scheduledWorkflowMonitor.scheduleAtFixedRate( () -> { for (Map.Entry<String, CompletableFuture<Workflow>> entry : runningWorkflowFutures.entrySet()) { String workflowId = entry.getKey(); CompletableFuture<Workflow> future = entry.getValue(); Workflow workflow = workflowClient.getWorkflow(workflowId, true); if (workflow.getStatus().isTerminal()) { future.complete(workflow); runningWorkflowFutures.remove(workflowId); } } }, 100, 100, TimeUnit.MILLISECONDS); } public WorkflowExecutor( TaskClient taskClient, WorkflowClient workflowClient, MetadataClient metadataClient, int pollingInterval) { this.taskClient = taskClient; this.workflowClient = workflowClient; this.metadataClient = metadataClient; annotatedWorkerExecutor = new AnnotatedWorkerExecutor(taskClient, pollingInterval); scheduledWorkflowMonitor.scheduleAtFixedRate( () -> { for (Map.Entry<String, CompletableFuture<Workflow>> entry : runningWorkflowFutures.entrySet()) { String workflowId = entry.getKey(); CompletableFuture<Workflow> future = entry.getValue(); Workflow workflow = workflowClient.getWorkflow(workflowId, true); if (workflow.getStatus().isTerminal()) { future.complete(workflow); runningWorkflowFutures.remove(workflowId); } } }, 100, 100, TimeUnit.MILLISECONDS); } public void initWorkers(String packagesToScan) { annotatedWorkerExecutor.initWorkers(packagesToScan); } public CompletableFuture<Workflow> executeWorkflow(String name, Integer version, Object input) { CompletableFuture<Workflow> future = new CompletableFuture<>(); Map<String, Object> inputMap = objectMapper.convertValue(input, Map.class); StartWorkflowRequest request = new StartWorkflowRequest(); request.setInput(inputMap); request.setName(name); request.setVersion(version); String workflowId = workflowClient.startWorkflow(request); runningWorkflowFutures.put(workflowId, future); return future; } public CompletableFuture<Workflow> executeWorkflow( ConductorWorkflow conductorWorkflow, Object input) { CompletableFuture<Workflow> future = new CompletableFuture<>(); Map<String, Object> inputMap = objectMapper.convertValue(input, Map.class); StartWorkflowRequest request = new StartWorkflowRequest(); request.setInput(inputMap); request.setName(conductorWorkflow.getName()); request.setVersion(conductorWorkflow.getVersion()); request.setWorkflowDef(conductorWorkflow.toWorkflowDef()); String workflowId = workflowClient.startWorkflow(request); runningWorkflowFutures.put(workflowId, future); return future; } public void loadTaskDefs(String resourcePath) throws IOException { InputStream resource = WorkflowExecutor.class.getResourceAsStream(resourcePath); if (resource != null) { List<TaskDef> taskDefs = objectMapper.readValue(resource, listOfTaskDefs); loadMetadata(taskDefs); } } public void loadWorkflowDefs(String resourcePath) throws IOException { InputStream resource = WorkflowExecutor.class.getResourceAsStream(resourcePath); if (resource != null) { WorkflowDef workflowDef = objectMapper.readValue(resource, WorkflowDef.class); loadMetadata(workflowDef); } } public void loadMetadata(WorkflowDef workflowDef) { metadataClient.registerWorkflowDef(workflowDef); } public void loadMetadata(List<TaskDef> taskDefs) { metadataClient.registerTaskDefs(taskDefs); } public void shutdown() { scheduledWorkflowMonitor.shutdown(); annotatedWorkerExecutor.shutdown(); } public boolean registerWorkflow(WorkflowDef workflowDef, boolean overwrite) { try { if (overwrite) { metadataClient.updateWorkflowDefs(Arrays.asList(workflowDef)); } else { metadataClient.registerWorkflowDef(workflowDef); } return true; } catch (Exception e) { LOGGER.error(e.getMessage(), e); return false; } } public MetadataClient getMetadataClient() { return metadataClient; } public TaskClient getTaskClient() { return taskClient; } }
6,864
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/WorkerConfiguration.java
/* * Copyright 2023 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; public class WorkerConfiguration { private int defaultPollingInterval = 0; public WorkerConfiguration(int defaultPollingInterval) { this.defaultPollingInterval = defaultPollingInterval; } public WorkerConfiguration() {} public int getPollingInterval(String taskName) { return defaultPollingInterval; } public int getThreadCount(String taskName) { return 0; } public String getDomain(String taskName) { return null; } }
6,865
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/NonRetryableException.java
/* * Copyright 2023 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; /** * Runtime exception indicating the non-retriable error with the task execution. If thrown, the task * will fail with FAILED_WITH_TERMINAL_ERROR and will not kick off retries. */ public class NonRetryableException extends RuntimeException { public NonRetryableException(String message) { super(message); } public NonRetryableException(String message, Throwable cause) { super(message, cause); } public NonRetryableException(Throwable cause) { super(cause); } }
6,866
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/TaskContext.java
/* * Copyright 2023 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; /** Context for the task */ public class TaskContext { public static final ThreadLocal<TaskContext> TASK_CONTEXT_INHERITABLE_THREAD_LOCAL = InheritableThreadLocal.withInitial(() -> null); public TaskContext(Task task, TaskResult taskResult) { this.task = task; this.taskResult = taskResult; } public static TaskContext get() { return TASK_CONTEXT_INHERITABLE_THREAD_LOCAL.get(); } public static TaskContext set(Task task) { TaskResult result = new TaskResult(task); TaskContext context = new TaskContext(task, result); TASK_CONTEXT_INHERITABLE_THREAD_LOCAL.set(context); return context; } private final Task task; private final TaskResult taskResult; public String getWorkflowInstanceId() { return task.getWorkflowInstanceId(); } public String getTaskId() { return task.getTaskId(); } public int getRetryCount() { return task.getRetryCount(); } public int getPollCount() { return task.getPollCount(); } public long getCallbackAfterSeconds() { return task.getCallbackAfterSeconds(); } public void addLog(String log) { this.taskResult.log(log); } public Task getTask() { return task; } public TaskResult getTaskResult() { return taskResult; } public void setCallbackAfter(int seconds) { this.taskResult.setCallbackAfterSeconds(seconds); } }
6,867
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/DynamicForkWorker.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; import java.lang.reflect.Method; import java.util.Map; import java.util.function.Function; import com.netflix.conductor.client.worker.Worker; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.sdk.workflow.def.tasks.DynamicFork; import com.netflix.conductor.sdk.workflow.def.tasks.DynamicForkInput; import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; public class DynamicForkWorker implements Worker { private final int pollingInterval; private final Function<Object, DynamicForkInput> workerMethod; private final String name; private ObjectMapper objectMapper = new ObjectMapperProvider().getObjectMapper(); public DynamicForkWorker( String name, Function<Object, DynamicForkInput> workerMethod, int pollingInterval) { this.name = name; this.workerMethod = workerMethod; this.pollingInterval = pollingInterval; } @Override public String getTaskDefName() { return name; } @Override public TaskResult execute(Task task) { TaskResult result = new TaskResult(task); try { Object parameter = getInvocationParameters(this.workerMethod, task); DynamicForkInput output = this.workerMethod.apply(parameter); result.getOutputData().put(DynamicFork.FORK_TASK_PARAM, output.getTasks()); result.getOutputData().put(DynamicFork.FORK_TASK_INPUT_PARAM, output.getInputs()); result.setStatus(TaskResult.Status.COMPLETED); } catch (Exception e) { throw new RuntimeException(e); } return result; } @Override public int getPollingInterval() { return pollingInterval; } private Object getInvocationParameters(Function<?, DynamicForkInput> function, Task task) { InputParam annotation = null; Class<?> parameterType = null; for (Method method : function.getClass().getDeclaredMethods()) { if (method.getReturnType().equals(DynamicForkInput.class)) { annotation = method.getParameters()[0].getAnnotation(InputParam.class); parameterType = method.getParameters()[0].getType(); } } if (parameterType.equals(Task.class)) { return task; } else if (parameterType.equals(Map.class)) { return task.getInputData(); } if (annotation != null) { String name = annotation.value(); Object value = task.getInputData().get(name); return objectMapper.convertValue(value, parameterType); } return objectMapper.convertValue(task.getInputData(), parameterType); } public static void main(String[] args) { Function<?, DynamicForkInput> fn = new Function<TaskDef, DynamicForkInput>() { @Override public DynamicForkInput apply(@InputParam("a") TaskDef s) { return null; } }; for (Method method : fn.getClass().getDeclaredMethods()) { if (method.getReturnType().equals(DynamicForkInput.class)) { System.out.println( "\n\n-->method: " + method + ", input: " + method.getParameters()[0].getType()); System.out.println("I take input as " + method.getParameters()[0].getType()); InputParam annotation = method.getParameters()[0].getAnnotation(InputParam.class); System.out.println("I have annotation " + annotation); } } } }
6,868
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerExecutor.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; import java.lang.reflect.Method; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.client.automator.TaskRunnerConfigurer; import com.netflix.conductor.client.http.TaskClient; import com.netflix.conductor.client.worker.Worker; import com.netflix.conductor.sdk.workflow.task.WorkerTask; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.reflect.ClassPath; public class AnnotatedWorkerExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(AnnotatedWorkerExecutor.class); private TaskClient taskClient; private TaskRunnerConfigurer taskRunner; private List<Worker> executors = new ArrayList<>(); private Map<String, Method> workerExecutors = new HashMap<>(); private Map<String, Integer> workerToThreadCount = new HashMap<>(); private Map<String, Integer> workerToPollingInterval = new HashMap<>(); private Map<String, String> workerDomains = new HashMap<>(); private Map<String, Object> workerClassObjs = new HashMap<>(); private static Set<String> scannedPackages = new HashSet<>(); private WorkerConfiguration workerConfiguration; public AnnotatedWorkerExecutor(TaskClient taskClient) { this.taskClient = taskClient; this.workerConfiguration = new WorkerConfiguration(); } public AnnotatedWorkerExecutor(TaskClient taskClient, int pollingIntervalInMillis) { this.taskClient = taskClient; this.workerConfiguration = new WorkerConfiguration(pollingIntervalInMillis); } public AnnotatedWorkerExecutor(TaskClient taskClient, WorkerConfiguration workerConfiguration) { this.taskClient = taskClient; this.workerConfiguration = workerConfiguration; } /** * Finds any worker implementation and starts polling for tasks * * @param basePackage list of packages - comma separated - to scan for annotated worker * implementation */ public synchronized void initWorkers(String basePackage) { scanWorkers(basePackage); startPolling(); } /** Shuts down the workers */ public void shutdown() { if (taskRunner != null) { taskRunner.shutdown(); } } private void scanWorkers(String basePackage) { try { if (scannedPackages.contains(basePackage)) { // skip LOGGER.info("Package {} already scanned and will skip", basePackage); return; } // Add here so to avoid infinite recursion where a class in the package contains the // code to init workers scannedPackages.add(basePackage); List<String> packagesToScan = new ArrayList<>(); if (basePackage != null) { String[] packages = basePackage.split(","); Collections.addAll(packagesToScan, packages); } LOGGER.info("packages to scan {}", packagesToScan); long s = System.currentTimeMillis(); ClassPath.from(AnnotatedWorkerExecutor.class.getClassLoader()) .getAllClasses() .forEach( classMeta -> { String name = classMeta.getName(); if (!includePackage(packagesToScan, name)) { return; } try { Class<?> clazz = classMeta.load(); Object obj = clazz.getConstructor().newInstance(); addBean(obj); } catch (Throwable t) { // trace because many classes won't have a default no-args // constructor and will fail LOGGER.trace( "Caught exception while loading and scanning class {}", t.getMessage()); } }); LOGGER.info( "Took {} ms to scan all the classes, loading {} tasks", (System.currentTimeMillis() - s), workerExecutors.size()); } catch (Exception e) { LOGGER.error("Error while scanning for workers: ", e); } } private boolean includePackage(List<String> packagesToScan, String name) { for (String scanPkg : packagesToScan) { if (name.startsWith(scanPkg)) return true; } return false; } public void addBean(Object bean) { Class<?> clazz = bean.getClass(); for (Method method : clazz.getMethods()) { WorkerTask annotation = method.getAnnotation(WorkerTask.class); if (annotation == null) { continue; } addMethod(annotation, method, bean); } } private void addMethod(WorkerTask annotation, Method method, Object bean) { String name = annotation.value(); int threadCount = workerConfiguration.getThreadCount(name); if (threadCount == 0) { threadCount = annotation.threadCount(); } workerToThreadCount.put(name, threadCount); int pollingInterval = workerConfiguration.getPollingInterval(name); if (pollingInterval == 0) { pollingInterval = annotation.pollingInterval(); } workerToPollingInterval.put(name, pollingInterval); String domain = workerConfiguration.getDomain(name); if (Strings.isNullOrEmpty(domain)) { domain = annotation.domain(); } if (!Strings.isNullOrEmpty(domain)) { workerDomains.put(name, domain); } workerClassObjs.put(name, bean); workerExecutors.put(name, method); LOGGER.info( "Adding worker for task {}, method {} with threadCount {} and polling interval set to {} ms", name, method, threadCount, pollingInterval); } public void startPolling() { workerExecutors.forEach( (taskName, method) -> { Object obj = workerClassObjs.get(taskName); AnnotatedWorker executor = new AnnotatedWorker(taskName, method, obj); executor.setPollingInterval(workerToPollingInterval.get(taskName)); executors.add(executor); }); if (executors.isEmpty()) { return; } LOGGER.info("Starting workers with threadCount {}", workerToThreadCount); LOGGER.info("Worker domains {}", workerDomains); taskRunner = new TaskRunnerConfigurer.Builder(taskClient, executors) .withTaskThreadCount(workerToThreadCount) .withTaskToDomain(workerDomains) .build(); taskRunner.init(); } @VisibleForTesting List<Worker> getExecutors() { return executors; } @VisibleForTesting TaskRunnerConfigurer getTaskRunner() { return taskRunner; } }
6,869
0
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor
Create_ds/conductor/java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorker.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.sdk.workflow.executor.task; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; import com.netflix.conductor.client.worker.Worker; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.tasks.DynamicFork; import com.netflix.conductor.sdk.workflow.def.tasks.DynamicForkInput; import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.task.OutputParam; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class AnnotatedWorker implements Worker { private String name; private Method workerMethod; private Object obj; private ObjectMapper om = new ObjectMapperProvider().getObjectMapper(); private int pollingInterval = 100; private Set<TaskResult.Status> failedStatuses = Set.of(TaskResult.Status.FAILED, TaskResult.Status.FAILED_WITH_TERMINAL_ERROR); public AnnotatedWorker(String name, Method workerMethod, Object obj) { this.name = name; this.workerMethod = workerMethod; this.obj = obj; om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } @Override public String getTaskDefName() { return name; } @Override public TaskResult execute(Task task) { TaskResult result = null; try { TaskContext context = TaskContext.set(task); Object[] parameters = getInvocationParameters(task); Object invocationResult = workerMethod.invoke(obj, parameters); result = setValue(invocationResult, context.getTaskResult()); if (!failedStatuses.contains(result.getStatus()) && result.getCallbackAfterSeconds() > 0) { result.setStatus(TaskResult.Status.IN_PROGRESS); } } catch (InvocationTargetException invocationTargetException) { if (result == null) { result = new TaskResult(task); } Throwable e = invocationTargetException.getCause(); e.printStackTrace(); if (e instanceof NonRetryableException) { result.setStatus(TaskResult.Status.FAILED_WITH_TERMINAL_ERROR); } else { result.setStatus(TaskResult.Status.FAILED); } result.setReasonForIncompletion(e.getMessage()); StringBuilder stackTrace = new StringBuilder(); for (StackTraceElement stackTraceElement : e.getStackTrace()) { String className = stackTraceElement.getClassName(); if (className.startsWith("jdk.") || className.startsWith(AnnotatedWorker.class.getName())) { break; } stackTrace.append(stackTraceElement); stackTrace.append("\n"); } result.log(stackTrace.toString()); } catch (Exception e) { throw new RuntimeException(e); } return result; } private Object[] getInvocationParameters(Task task) { Class<?>[] parameterTypes = workerMethod.getParameterTypes(); Parameter[] parameters = workerMethod.getParameters(); if (parameterTypes.length == 1 && parameterTypes[0].equals(Task.class)) { return new Object[] {task}; } else if (parameterTypes.length == 1 && parameterTypes[0].equals(Map.class)) { return new Object[] {task.getInputData()}; } return getParameters(task, parameterTypes, parameters); } private Object[] getParameters(Task task, Class<?>[] parameterTypes, Parameter[] parameters) { Annotation[][] parameterAnnotations = workerMethod.getParameterAnnotations(); Object[] values = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Annotation[] paramAnnotation = parameterAnnotations[i]; if (paramAnnotation != null && paramAnnotation.length > 0) { Type type = parameters[i].getParameterizedType(); Class<?> parameterType = parameterTypes[i]; values[i] = getInputValue(task, parameterType, type, paramAnnotation); } else { values[i] = om.convertValue(task.getInputData(), parameterTypes[i]); } } return values; } private Object getInputValue( Task task, Class<?> parameterType, Type type, Annotation[] paramAnnotation) { InputParam ip = findInputParamAnnotation(paramAnnotation); if (ip == null) { return om.convertValue(task.getInputData(), parameterType); } final String name = ip.value(); final Object value = task.getInputData().get(name); if (value == null) { return null; } if (List.class.isAssignableFrom(parameterType)) { List<?> list = om.convertValue(value, List.class); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> typeOfParameter = (Class<?>) parameterizedType.getActualTypeArguments()[0]; List<Object> parameterizedList = new ArrayList<>(); for (Object item : list) { parameterizedList.add(om.convertValue(item, typeOfParameter)); } return parameterizedList; } else { return list; } } else { return om.convertValue(value, parameterType); } } private static InputParam findInputParamAnnotation(Annotation[] paramAnnotation) { return (InputParam) Arrays.stream(paramAnnotation) .filter(ann -> ann.annotationType().equals(InputParam.class)) .findFirst() .orElse(null); } private TaskResult setValue(Object invocationResult, TaskResult result) { if (invocationResult == null) { result.setStatus(TaskResult.Status.COMPLETED); return result; } OutputParam opAnnotation = workerMethod.getAnnotatedReturnType().getAnnotation(OutputParam.class); if (opAnnotation != null) { String name = opAnnotation.value(); result.getOutputData().put(name, invocationResult); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof TaskResult) { return (TaskResult) invocationResult; } else if (invocationResult instanceof Map) { Map resultAsMap = (Map) invocationResult; result.getOutputData().putAll(resultAsMap); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof String || invocationResult instanceof Number || invocationResult instanceof Boolean) { result.getOutputData().put("result", invocationResult); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof List) { List resultAsList = om.convertValue(invocationResult, List.class); result.getOutputData().put("result", resultAsList); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof DynamicForkInput) { DynamicForkInput forkInput = (DynamicForkInput) invocationResult; List<com.netflix.conductor.sdk.workflow.def.tasks.Task<?>> tasks = forkInput.getTasks(); List<WorkflowTask> workflowTasks = new ArrayList<>(); for (com.netflix.conductor.sdk.workflow.def.tasks.Task<?> sdkTask : tasks) { workflowTasks.addAll(sdkTask.getWorkflowDefTasks()); } result.getOutputData().put(DynamicFork.FORK_TASK_PARAM, workflowTasks); result.getOutputData().put(DynamicFork.FORK_TASK_INPUT_PARAM, forkInput.getInputs()); result.setStatus(TaskResult.Status.COMPLETED); return result; } else { Map resultAsMap = om.convertValue(invocationResult, Map.class); result.getOutputData().putAll(resultAsMap); result.setStatus(TaskResult.Status.COMPLETED); return result; } } public void setPollingInterval(int pollingInterval) { System.out.println( "Setting the polling interval for " + getTaskDefName() + ", to " + pollingInterval); this.pollingInterval = pollingInterval; } @Override public int getPollingInterval() { System.out.println("Sending the polling interval to " + pollingInterval); return pollingInterval; } }
6,870
0
Create_ds/conductor/server/src/test/java/com/netflix/conductor/common
Create_ds/conductor/server/src/test/java/com/netflix/conductor/common/config/ConductorObjectMapperTest.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.config; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.run.Workflow; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.protobuf.Any; import com.google.protobuf.Struct; import com.google.protobuf.Value; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Tests the customized {@link ObjectMapper} that is used by {@link com.netflix.conductor.Conductor} * application. */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @RunWith(SpringRunner.class) @TestPropertySource(properties = "conductor.queue.type=") public class ConductorObjectMapperTest { @Autowired ObjectMapper objectMapper; @Test public void testSimpleMapping() throws IOException { assertTrue(objectMapper.canSerialize(Any.class)); Struct struct1 = Struct.newBuilder() .putFields( "some-key", Value.newBuilder().setStringValue("some-value").build()) .build(); Any source = Any.pack(struct1); StringWriter buf = new StringWriter(); objectMapper.writer().writeValue(buf, source); Any dest = objectMapper.reader().forType(Any.class).readValue(buf.toString()); assertEquals(source.getTypeUrl(), dest.getTypeUrl()); Struct struct2 = dest.unpack(Struct.class); assertTrue(struct2.containsFields("some-key")); assertEquals( struct1.getFieldsOrThrow("some-key").getStringValue(), struct2.getFieldsOrThrow("some-key").getStringValue()); } @Test public void testNullOnWrite() throws JsonProcessingException { Map<String, Object> data = new HashMap<>(); data.put("someKey", null); data.put("someId", "abc123"); String result = objectMapper.writeValueAsString(data); assertTrue(result.contains("null")); } @Test public void testWorkflowSerDe() throws IOException { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setName("testDef"); workflowDef.setVersion(2); Workflow workflow = new Workflow(); workflow.setWorkflowDefinition(workflowDef); workflow.setWorkflowId("test-workflow-id"); workflow.setStatus(Workflow.WorkflowStatus.RUNNING); workflow.setStartTime(10L); workflow.setInput(null); Map<String, Object> data = new HashMap<>(); data.put("someKey", null); data.put("someId", "abc123"); workflow.setOutput(data); String workflowPayload = objectMapper.writeValueAsString(workflow); Workflow workflow1 = objectMapper.readValue(workflowPayload, Workflow.class); assertTrue(workflow1.getOutput().containsKey("someKey")); assertNull(workflow1.getOutput().get("someKey")); assertNotNull(workflow1.getInput()); } }
6,871
0
Create_ds/conductor/server/src/main/java/com/netflix
Create_ds/conductor/server/src/main/java/com/netflix/conductor/Conductor.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor; import java.io.IOException; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.io.FileSystemResource; // Prevents from the datasource beans to be loaded, AS they are needed only for specific databases. // In case that SQL database is selected this class will be imported back in the appropriate // database persistence module. @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) @ComponentScan(basePackages = {"com.netflix.conductor", "io.orkes.conductor"}) public class Conductor { private static final Logger log = LoggerFactory.getLogger(Conductor.class); public static void main(String[] args) throws IOException { loadExternalConfig(); SpringApplication.run(Conductor.class, args); } /** * Reads properties from the location specified in <code>CONDUCTOR_CONFIG_FILE</code> and sets * them as system properties so they override the default properties. * * <p>Spring Boot property hierarchy is documented here, * https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config * * @throws IOException if file can't be read. */ private static void loadExternalConfig() throws IOException { String configFile = System.getProperty("CONDUCTOR_CONFIG_FILE"); if (StringUtils.isNotBlank(configFile)) { FileSystemResource resource = new FileSystemResource(configFile); if (resource.exists()) { Properties properties = new Properties(); properties.load(resource.getInputStream()); properties.forEach( (key, value) -> System.setProperty((String) key, (String) value)); log.info("Loaded {} properties from {}", properties.size(), configFile); } else { log.warn("Ignoring {} since it does not exist", configFile); } } } }
6,872
0
Create_ds/conductor/annotations/src/main/java/com/netflix/conductor/annotations
Create_ds/conductor/annotations/src/main/java/com/netflix/conductor/annotations/protogen/ProtoField.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.annotations.protogen; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * ProtoField annotates a field inside an struct with metadata on how to expose it on its * corresponding Protocol Buffers struct. For a field to be exposed in a ProtoBuf struct, the * containing struct must also be annotated with a {@link ProtoMessage} or {@link ProtoEnum} tag. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ProtoField { /** * Mandatory. Sets the Protocol Buffer ID for this specific field. Once a field has been * annotated with a given ID, the ID can never change to a different value or the resulting * Protocol Buffer struct will not be backwards compatible. * * @return the numeric ID for the field */ int id(); }
6,873
0
Create_ds/conductor/annotations/src/main/java/com/netflix/conductor/annotations
Create_ds/conductor/annotations/src/main/java/com/netflix/conductor/annotations/protogen/ProtoMessage.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.annotations.protogen; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * ProtoMessage annotates a given Java class so it becomes exposed via the GRPC API as a native * Protocol Buffers struct. The annotated class must be a POJO. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ProtoMessage { /** * Sets whether the generated mapping code will contain a helper to translate the POJO for this * class into the equivalent ProtoBuf object. * * @return whether this class will generate a mapper to ProtoBuf objects */ boolean toProto() default true; /** * Sets whether the generated mapping code will contain a helper to translate the ProtoBuf * object for this class into the equivalent POJO. * * @return whether this class will generate a mapper from ProtoBuf objects */ boolean fromProto() default true; /** * Sets whether this is a wrapper class that will be used to encapsulate complex nested type * interfaces. Wrapper classes are not directly exposed by the ProtoBuf API and must be mapped * manually. * * @return whether this is a wrapper class */ boolean wrapper() default false; }
6,874
0
Create_ds/conductor/annotations/src/main/java/com/netflix/conductor/annotations
Create_ds/conductor/annotations/src/main/java/com/netflix/conductor/annotations/protogen/ProtoEnum.java
/* * Copyright 2022 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.annotations.protogen; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * ProtoEnum annotates an enum type that will be exposed via the GRPC API as a native Protocol * Buffers enum. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ProtoEnum {}
6,875
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/tasks/TaskDefTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.tasks; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.TaskDef; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TaskDefTest { private Validator validator; @Before public void setup() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); this.validator = factory.getValidator(); } @Test public void test() { String name = "test1"; String description = "desc"; int retryCount = 10; int timeout = 100; TaskDef def = new TaskDef(name, description, retryCount, timeout); assertEquals(36_00, def.getResponseTimeoutSeconds()); assertEquals(name, def.getName()); assertEquals(description, def.getDescription()); assertEquals(retryCount, def.getRetryCount()); assertEquals(timeout, def.getTimeoutSeconds()); } @Test public void testTaskDef() { TaskDef taskDef = new TaskDef(); taskDef.setName("task1"); taskDef.setRetryCount(-1); taskDef.setTimeoutSeconds(1000); taskDef.setResponseTimeoutSeconds(1001); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(3, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue( validationErrors.contains( "TaskDef: task1 responseTimeoutSeconds: 1001 must be less than timeoutSeconds: 1000")); assertTrue(validationErrors.contains("TaskDef retryCount: 0 must be >= 0")); assertTrue(validationErrors.contains("ownerEmail cannot be empty")); } @Test public void testTaskDefNameAndOwnerNotSet() { TaskDef taskDef = new TaskDef(); taskDef.setRetryCount(-1); taskDef.setTimeoutSeconds(1000); taskDef.setResponseTimeoutSeconds(1); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(3, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("TaskDef retryCount: 0 must be >= 0")); assertTrue(validationErrors.contains("TaskDef name cannot be null or empty")); assertTrue(validationErrors.contains("ownerEmail cannot be empty")); } @Test public void testTaskDefInvalidEmail() { TaskDef taskDef = new TaskDef(); taskDef.setName("test-task"); taskDef.setRetryCount(1); taskDef.setTimeoutSeconds(1000); taskDef.setResponseTimeoutSeconds(1); taskDef.setOwnerEmail("owner"); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("ownerEmail should be valid email address")); } @Test public void testTaskDefValidEmail() { TaskDef taskDef = new TaskDef(); taskDef.setName("test-task"); taskDef.setRetryCount(1); taskDef.setTimeoutSeconds(1000); taskDef.setResponseTimeoutSeconds(1); taskDef.setOwnerEmail("owner@test.com"); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(0, result.size()); } }
6,876
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/tasks/TaskResultTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.tasks; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; import static org.junit.Assert.assertEquals; public class TaskResultTest { private Task task; private TaskResult taskResult; @Before public void setUp() { task = new Task(); task.setWorkflowInstanceId("workflow-id"); task.setTaskId("task-id"); task.setReasonForIncompletion("reason"); task.setCallbackAfterSeconds(10); task.setWorkerId("worker-id"); task.setOutputData(new HashMap<>()); task.setExternalOutputPayloadStoragePath("externalOutput"); } @Test public void testCanceledTask() { task.setStatus(Task.Status.CANCELED); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.FAILED, taskResult.getStatus()); } @Test public void testCompletedWithErrorsTask() { task.setStatus(Task.Status.COMPLETED_WITH_ERRORS); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.FAILED, taskResult.getStatus()); } @Test public void testScheduledTask() { task.setStatus(Task.Status.SCHEDULED); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.IN_PROGRESS, taskResult.getStatus()); } @Test public void testCompltetedTask() { task.setStatus(Task.Status.COMPLETED); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.COMPLETED, taskResult.getStatus()); } private void validateTaskResult() { assertEquals(task.getWorkflowInstanceId(), taskResult.getWorkflowInstanceId()); assertEquals(task.getTaskId(), taskResult.getTaskId()); assertEquals(task.getReasonForIncompletion(), taskResult.getReasonForIncompletion()); assertEquals(task.getCallbackAfterSeconds(), taskResult.getCallbackAfterSeconds()); assertEquals(task.getWorkerId(), taskResult.getWorkerId()); assertEquals(task.getOutputData(), taskResult.getOutputData()); assertEquals( task.getExternalOutputPayloadStoragePath(), taskResult.getExternalOutputPayloadStoragePath()); } }
6,877
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/tasks/TaskTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.tasks; import java.util.Arrays; import java.util.HashMap; import java.util.Set; import java.util.stream.Collectors; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.Task.Status; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.google.protobuf.Any; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class TaskTest { @Test public void test() { Task task = new Task(); task.setStatus(Status.FAILED); assertEquals(Status.FAILED, task.getStatus()); Set<String> resultStatues = Arrays.stream(TaskResult.Status.values()) .map(Enum::name) .collect(Collectors.toSet()); for (Status status : Status.values()) { if (resultStatues.contains(status.name())) { TaskResult.Status trStatus = TaskResult.Status.valueOf(status.name()); assertEquals(status.name(), trStatus.name()); task = new Task(); task.setStatus(status); assertEquals(status, task.getStatus()); } } } @Test public void testTaskDefinitionIfAvailable() { Task task = new Task(); task.setStatus(Status.FAILED); assertEquals(Status.FAILED, task.getStatus()); assertNull(task.getWorkflowTask()); assertFalse(task.getTaskDefinition().isPresent()); WorkflowTask workflowTask = new WorkflowTask(); TaskDef taskDefinition = new TaskDef(); workflowTask.setTaskDefinition(taskDefinition); task.setWorkflowTask(workflowTask); assertTrue(task.getTaskDefinition().isPresent()); assertEquals(taskDefinition, task.getTaskDefinition().get()); } @Test public void testTaskQueueWaitTime() { Task task = new Task(); long currentTimeMillis = System.currentTimeMillis(); task.setScheduledTime(currentTimeMillis - 30_000); // 30 seconds ago task.setStartTime(currentTimeMillis - 25_000); long queueWaitTime = task.getQueueWaitTime(); assertEquals(5000L, queueWaitTime); task.setUpdateTime(currentTimeMillis - 20_000); task.setCallbackAfterSeconds(10); queueWaitTime = task.getQueueWaitTime(); assertTrue(queueWaitTime > 0); } @Test public void testDeepCopyTask() { final Task task = new Task(); // In order to avoid forgetting putting inside the copy method the newly added fields check // the number of declared fields. final int expectedTaskFieldsNumber = 40; final int declaredFieldsNumber = task.getClass().getDeclaredFields().length; assertEquals(expectedTaskFieldsNumber, declaredFieldsNumber); task.setCallbackAfterSeconds(111L); task.setCallbackFromWorker(false); task.setCorrelationId("correlation_id"); task.setInputData(new HashMap<>()); task.setOutputData(new HashMap<>()); task.setReferenceTaskName("ref_task_name"); task.setStartDelayInSeconds(1); task.setTaskDefName("task_def_name"); task.setTaskType("dummy_task_type"); task.setWorkflowInstanceId("workflowInstanceId"); task.setWorkflowType("workflowType"); task.setResponseTimeoutSeconds(11L); task.setStatus(Status.COMPLETED); task.setRetryCount(0); task.setPollCount(0); task.setTaskId("taskId"); task.setWorkflowTask(new WorkflowTask()); task.setDomain("domain"); task.setInputMessage(Any.getDefaultInstance()); task.setOutputMessage(Any.getDefaultInstance()); task.setRateLimitPerFrequency(11); task.setRateLimitFrequencyInSeconds(11); task.setExternalInputPayloadStoragePath("externalInputPayloadStoragePath"); task.setExternalOutputPayloadStoragePath("externalOutputPayloadStoragePath"); task.setWorkflowPriority(0); task.setIteration(1); task.setExecutionNameSpace("name_space"); task.setIsolationGroupId("groupId"); task.setStartTime(12L); task.setEndTime(20L); task.setScheduledTime(7L); task.setRetried(false); task.setReasonForIncompletion(""); task.setWorkerId(""); task.setSubWorkflowId(""); task.setSubworkflowChanged(false); final Task copy = task.deepCopy(); assertEquals(task, copy); } }
6,878
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/config/TestObjectMapperConfiguration.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.fasterxml.jackson.databind.ObjectMapper; /** Supplies the standard Conductor {@link ObjectMapper} for tests that need them. */ @Configuration public class TestObjectMapperConfiguration { @Bean public ObjectMapper testObjectMapper() { return new ObjectMapperProvider().getObjectMapper(); } }
6,879
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/utils/SummaryUtilTest.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.jupiter.api.Assertions.assertEquals; @ContextConfiguration( classes = { TestObjectMapperConfiguration.class, SummaryUtilTest.SummaryUtilTestConfiguration.class }) @RunWith(SpringRunner.class) public class SummaryUtilTest { @Configuration static class SummaryUtilTestConfiguration { @Bean public SummaryUtil summaryUtil() { return new SummaryUtil(); } } @Autowired private ObjectMapper objectMapper; private Map<String, Object> testObject; @Before public void init() { Map<String, Object> child = new HashMap<>(); child.put("testStr", "childTestStr"); Map<String, Object> obj = new HashMap<>(); obj.put("testStr", "stringValue"); obj.put("testArray", new ArrayList<>(Arrays.asList(1, 2, 3))); obj.put("testObj", child); obj.put("testNull", null); testObject = obj; } @Test public void testSerializeInputOutput_defaultToString() throws Exception { new ApplicationContextRunner() .withPropertyValues( "conductor.app.summary-input-output-json-serialization.enabled:false") .withUserConfiguration(SummaryUtilTestConfiguration.class) .run( context -> { String serialized = SummaryUtil.serializeInputOutput(this.testObject); assertEquals( this.testObject.toString(), serialized, "The Java.toString() Serialization should match the serialized Test Object"); }); } @Test public void testSerializeInputOutput_jsonSerializationEnabled() throws Exception { new ApplicationContextRunner() .withPropertyValues( "conductor.app.summary-input-output-json-serialization.enabled:true") .withUserConfiguration(SummaryUtilTestConfiguration.class) .run( context -> { String serialized = SummaryUtil.serializeInputOutput(testObject); assertEquals( objectMapper.writeValueAsString(testObject), serialized, "The ObjectMapper Json Serialization should match the serialized Test Object"); }); } }
6,880
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/utils/ConstraintParamUtilTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import static org.junit.Assert.assertEquals; public class ConstraintParamUtilTest { @Before public void before() { System.setProperty("NETFLIX_STACK", "test"); System.setProperty("NETFLIX_ENVIRONMENT", "test"); System.setProperty("TEST_ENV", "test"); } private WorkflowDef constructWorkflowDef() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); return workflowDef; } @Test public void testExtractParamPathComponents() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithMissingEnvVariable() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${NETFLIX_STACK}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithValidEnvVariable() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithValidMap() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status}"); Map<String, Object> envInputParam = new HashMap<>(); envInputParam.put("packageId", "${workflow.input.packageId}"); envInputParam.put("taskId", "${CPEWF_TASK_ID}"); envInputParam.put("NETFLIX_STACK", "${NETFLIX_STACK}"); envInputParam.put("NETFLIX_ENVIRONMENT", "${NETFLIX_ENVIRONMENT}"); envInputParam.put("TEST_ENV", "${TEST_ENV}"); inputParam.put("env", envInputParam); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithInvalidEnv() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status}"); Map<String, Object> envInputParam = new HashMap<>(); envInputParam.put("packageId", "${workflow.input.packageId}"); envInputParam.put("taskId", "${CPEWF_TASK_ID}"); envInputParam.put("TEST_ENV1", "${TEST_ENV1}"); inputParam.put("env", envInputParam); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 1); } @Test public void testExtractParamPathComponentsWithInputParamEmpty() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", ""); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithListInputParamWithEmptyString() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", new String[] {""}); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithInputFieldWithSpace() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status sta}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 1); } @Test public void testExtractParamPathComponentsWithPredefineEnums() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("NETFLIX_ENV", "${CPEWF_TASK_ID}"); inputParam.put( "entryPoint", "/tools/pdfwatermarker_mux.py ${NETFLIX_ENV} ${CPEWF_TASK_ID} alpha"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithEscapedChar() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "$${expression with spaces}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } }
6,881
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/workflow/SubWorkflowParamsTest.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.workflow; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.workflow.SubWorkflowParams; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class SubWorkflowParamsTest { @Autowired private ObjectMapper objectMapper; @Test public void testWorkflowTaskName() { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); // name is null ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(subWorkflowParams); assertEquals(2, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("SubWorkflowParams name cannot be null")); assertTrue(validationErrors.contains("SubWorkflowParams name cannot be empty")); } @Test public void testWorkflowSetTaskToDomain() { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); Map<String, String> taskToDomain = new HashMap<>(); taskToDomain.put("unit", "test"); subWorkflowParams.setTaskToDomain(taskToDomain); assertEquals(taskToDomain, subWorkflowParams.getTaskToDomain()); } @Test(expected = IllegalArgumentException.class) public void testSetWorkflowDefinition() { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); subWorkflowParams.setName("dummy-name"); subWorkflowParams.setWorkflowDefinition(new Object()); } @Test public void testGetWorkflowDef() { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); subWorkflowParams.setName("dummy-name"); WorkflowDef def = new WorkflowDef(); def.setName("test_workflow"); def.setVersion(1); WorkflowTask task = new WorkflowTask(); task.setName("test_task"); task.setTaskReferenceName("t1"); def.getTasks().add(task); subWorkflowParams.setWorkflowDefinition(def); assertEquals(def, subWorkflowParams.getWorkflowDefinition()); assertEquals(def, subWorkflowParams.getWorkflowDef()); } @Test public void testWorkflowDefJson() throws Exception { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); subWorkflowParams.setName("dummy-name"); WorkflowDef def = new WorkflowDef(); def.setName("test_workflow"); def.setVersion(1); WorkflowTask task = new WorkflowTask(); task.setName("test_task"); task.setTaskReferenceName("t1"); def.getTasks().add(task); subWorkflowParams.setWorkflowDefinition(def); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); String serializedParams = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(subWorkflowParams); SubWorkflowParams deserializedParams = objectMapper.readValue(serializedParams, SubWorkflowParams.class); assertEquals(def, deserializedParams.getWorkflowDefinition()); assertEquals(def, deserializedParams.getWorkflowDef()); } }
6,882
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/workflow/WorkflowDefValidatorTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.workflow; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class WorkflowDefValidatorTest { @Before public void before() { System.setProperty("NETFLIX_STACK", "test"); System.setProperty("NETFLIX_ENVIRONMENT", "test"); System.setProperty("TEST_ENV", "test"); } @Test public void testWorkflowDefConstraints() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(3, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("WorkflowDef name cannot be null or empty")); assertTrue(validationErrors.contains("WorkflowTask list cannot be empty")); assertTrue(validationErrors.contains("ownerEmail cannot be empty")); // assertTrue(validationErrors.contains("workflowDef schemaVersion: 1 should be >= 2")); } @Test public void testWorkflowDefConstraintsWithMultipleEnvVariable() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID}"); inputParam.put( "entryPoint", "${NETFLIX_ENVIRONMENT} ${NETFLIX_STACK} ${CPEWF_TASK_ID} ${workflow.input.status}"); workflowTask_1.setInputParameters(inputParam); WorkflowTask workflowTask_2 = new WorkflowTask(); workflowTask_2.setName("task_2"); workflowTask_2.setTaskReferenceName("task_2"); workflowTask_2.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam2 = new HashMap<>(); inputParam2.put("env", inputParam); workflowTask_2.setInputParameters(inputParam2); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); tasks.add(workflowTask_2); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowDefConstraintsSingleEnvVariable() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowDefConstraintsDualEnvVariable() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${NETFLIX_STACK}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowDefConstraintsWithMapAsInputParam() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${NETFLIX_STACK}"); Map<String, Object> envInputParam = new HashMap<>(); envInputParam.put("packageId", "${workflow.input.packageId}"); envInputParam.put("taskId", "${CPEWF_TASK_ID}"); envInputParam.put("NETFLIX_STACK", "${NETFLIX_STACK}"); envInputParam.put("NETFLIX_ENVIRONMENT", "${NETFLIX_ENVIRONMENT}"); inputParam.put("env", envInputParam); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowTaskInputParamInvalid() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); // name is null workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", "${workflow.input.Space Value}"); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue( validationErrors.contains( "key: blabla input parameter value: workflow.input.Space Value is not valid")); } @Test public void testWorkflowTaskEmptyStringInputParamValue() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); // name is null workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowTasklistInputParamWithEmptyString() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); // name is null workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); map.put("foo", new String[] {""}); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowSchemaVersion1() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(3); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("workflowDef schemaVersion: 2 is only supported")); } @Test public void testWorkflowOwnerInvalidEmail() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner"); WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("ownerEmail should be valid email address")); } @Test public void testWorkflowOwnerValidEmail() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } }
6,883
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/workflow/WorkflowTaskTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.workflow; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class WorkflowTaskTest { @Test public void test() { WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setWorkflowTaskType(TaskType.DECISION); assertNotNull(workflowTask.getType()); assertEquals(TaskType.DECISION.name(), workflowTask.getType()); workflowTask = new WorkflowTask(); workflowTask.setWorkflowTaskType(TaskType.SWITCH); assertNotNull(workflowTask.getType()); assertEquals(TaskType.SWITCH.name(), workflowTask.getType()); } @Test public void testOptional() { WorkflowTask task = new WorkflowTask(); assertFalse(task.isOptional()); task.setOptional(Boolean.FALSE); assertFalse(task.isOptional()); task.setOptional(Boolean.TRUE); assertTrue(task.isOptional()); } @Test public void testWorkflowTaskName() { WorkflowTask taskDef = new WorkflowTask(); // name is null ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(2, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("WorkflowTask name cannot be empty or null")); assertTrue( validationErrors.contains( "WorkflowTask taskReferenceName name cannot be empty or null")); } }
6,884
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/run/TaskSummaryTest.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.run; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.Task; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.Assert.assertNotNull; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class TaskSummaryTest { @Autowired private ObjectMapper objectMapper; @Test public void testJsonSerializing() throws Exception { Task task = new Task(); TaskSummary taskSummary = new TaskSummary(task); String json = objectMapper.writeValueAsString(taskSummary); TaskSummary read = objectMapper.readValue(json, TaskSummary.class); assertNotNull(read); } }
6,885
0
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common
Create_ds/conductor/common/src/test/java/com/netflix/conductor/common/events/EventHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.events; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.Test; import com.netflix.conductor.common.metadata.events.EventHandler; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class EventHandlerTest { @Test public void testWorkflowTaskName() { EventHandler taskDef = new EventHandler(); // name is null ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(3, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("Missing event handler name")); assertTrue(validationErrors.contains("Missing event location")); assertTrue( validationErrors.contains( "No actions specified. Please specify at-least one action")); } }
6,886
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/constraints/NoSemiColonConstraint.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload; import org.apache.commons.lang3.StringUtils; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; /** This constraint checks semi-colon is not allowed in a given string. */ @Documented @Constraint(validatedBy = NoSemiColonConstraint.NoSemiColonValidator.class) @Target({FIELD, PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface NoSemiColonConstraint { String message() default "String: cannot contain the following set of characters: ':'"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class NoSemiColonValidator implements ConstraintValidator<NoSemiColonConstraint, String> { @Override public void initialize(NoSemiColonConstraint constraintAnnotation) {} @Override public boolean isValid(String value, ConstraintValidatorContext context) { boolean valid = true; if (!StringUtils.isEmpty(value) && value.contains(":")) { valid = false; } return valid; } } }
6,887
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/constraints/TaskTimeoutConstraint.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload; import com.netflix.conductor.common.metadata.tasks.TaskDef; import static java.lang.annotation.ElementType.TYPE; /** * This constraint checks for a given task responseTimeoutSeconds should be less than * timeoutSeconds. */ @Documented @Constraint(validatedBy = TaskTimeoutConstraint.TaskTimeoutValidator.class) @Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TaskTimeoutConstraint { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class TaskTimeoutValidator implements ConstraintValidator<TaskTimeoutConstraint, TaskDef> { @Override public void initialize(TaskTimeoutConstraint constraintAnnotation) {} @Override public boolean isValid(TaskDef taskDef, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); boolean valid = true; if (taskDef.getTimeoutSeconds() > 0) { if (taskDef.getResponseTimeoutSeconds() > taskDef.getTimeoutSeconds()) { valid = false; String message = String.format( "TaskDef: %s responseTimeoutSeconds: %d must be less than timeoutSeconds: %d", taskDef.getName(), taskDef.getResponseTimeoutSeconds(), taskDef.getTimeoutSeconds()); context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); } } return valid; } } }
6,888
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/constraints/TaskReferenceNameUniqueConstraint.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.HashMap; import java.util.List; import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload; import org.apache.commons.lang3.mutable.MutableBoolean; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.utils.ConstraintParamUtil; import static java.lang.annotation.ElementType.TYPE; /** * This constraint class validates following things. * * <ul> * <li>1. WorkflowDef is valid or not * <li>2. Make sure taskReferenceName used across different tasks are unique * <li>3. Verify inputParameters points to correct tasks or not * </ul> */ @Documented @Constraint(validatedBy = TaskReferenceNameUniqueConstraint.TaskReferenceNameUniqueValidator.class) @Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TaskReferenceNameUniqueConstraint { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class TaskReferenceNameUniqueValidator implements ConstraintValidator<TaskReferenceNameUniqueConstraint, WorkflowDef> { @Override public void initialize(TaskReferenceNameUniqueConstraint constraintAnnotation) {} @Override public boolean isValid(WorkflowDef workflowDef, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); boolean valid = true; // check if taskReferenceNames are unique across tasks or not HashMap<String, Integer> taskReferenceMap = new HashMap<>(); for (WorkflowTask workflowTask : workflowDef.collectTasks()) { if (taskReferenceMap.containsKey(workflowTask.getTaskReferenceName())) { String message = String.format( "taskReferenceName: %s should be unique across tasks for a given workflowDefinition: %s", workflowTask.getTaskReferenceName(), workflowDef.getName()); context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); valid = false; } else { taskReferenceMap.put(workflowTask.getTaskReferenceName(), 1); } } // check inputParameters points to valid taskDef return valid & verifyTaskInputParameters(context, workflowDef); } private boolean verifyTaskInputParameters( ConstraintValidatorContext context, WorkflowDef workflow) { MutableBoolean valid = new MutableBoolean(); valid.setValue(true); if (workflow.getTasks() == null) { return valid.getValue(); } workflow.getTasks().stream() .filter(workflowTask -> workflowTask.getInputParameters() != null) .forEach( workflowTask -> { List<String> errors = ConstraintParamUtil.validateInputParam( workflowTask.getInputParameters(), workflowTask.getName(), workflow); errors.forEach( message -> context.buildConstraintViolationWithTemplate( message) .addConstraintViolation()); if (errors.size() > 0) { valid.setValue(false); } }); return valid.getValue(); } } }
6,889
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/constraints/OwnerEmailMandatoryConstraint.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload; import org.apache.commons.lang3.StringUtils; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.TYPE; /** * This constraint class validates that owner email is non-empty, but only if configuration says * owner email is mandatory. */ @Documented @Constraint(validatedBy = OwnerEmailMandatoryConstraint.WorkflowTaskValidValidator.class) @Target({TYPE, FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface OwnerEmailMandatoryConstraint { String message() default "ownerEmail cannot be empty"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class WorkflowTaskValidValidator implements ConstraintValidator<OwnerEmailMandatoryConstraint, String> { @Override public void initialize(OwnerEmailMandatoryConstraint constraintAnnotation) {} @Override public boolean isValid(String ownerEmail, ConstraintValidatorContext context) { return !ownerEmailMandatory || !StringUtils.isEmpty(ownerEmail); } private static boolean ownerEmailMandatory = true; public static void setOwnerEmailMandatory(boolean ownerEmailMandatory) { WorkflowTaskValidValidator.ownerEmailMandatory = ownerEmailMandatory; } } }
6,890
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/config/ObjectMapperConfiguration.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.config; import javax.annotation.PostConstruct; import org.springframework.context.annotation.Configuration; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; @Configuration public class ObjectMapperConfiguration { private final ObjectMapper objectMapper; public ObjectMapperConfiguration(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /** Set default property inclusion like {@link ObjectMapperProvider#getObjectMapper()}. */ @PostConstruct public void customizeDefaultObjectMapper() { objectMapper.setDefaultPropertyInclusion( JsonInclude.Value.construct( JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS)); objectMapper.registerModule(new AfterburnerModule()); } }
6,891
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/config/ObjectMapperProvider.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.config; import com.netflix.conductor.common.jackson.JsonProtoModule; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; /** * A Factory class for creating a customized {@link ObjectMapper}. This is only used by the * conductor-client module and tests that rely on {@link ObjectMapper}. See * TestObjectMapperConfiguration. */ public class ObjectMapperProvider { /** * The customizations in this method are configured using {@link * org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration} * * <p>Customizations are spread across, 1. {@link ObjectMapperBuilderConfiguration} 2. {@link * ObjectMapperConfiguration} 3. {@link JsonProtoModule} * * <p>IMPORTANT: Changes in this method need to be also performed in the default {@link * ObjectMapper} that Spring Boot creates. * * @see org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration */ public ObjectMapper getObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); objectMapper.setDefaultPropertyInclusion( JsonInclude.Value.construct( JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS)); objectMapper.registerModule(new JsonProtoModule()); objectMapper.registerModule(new AfterburnerModule()); return objectMapper; } }
6,892
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/config/ObjectMapperBuilderConfiguration.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.config; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; @Configuration public class ObjectMapperBuilderConfiguration { /** Disable features like {@link ObjectMapperProvider#getObjectMapper()}. */ @Bean public Jackson2ObjectMapperBuilderCustomizer conductorJackson2ObjectMapperBuilderCustomizer() { return builder -> builder.featuresToDisable( FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES, FAIL_ON_NULL_FOR_PRIMITIVES); } }
6,893
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/utils/ExternalPayloadStorage.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.utils; import java.io.InputStream; import com.netflix.conductor.common.run.ExternalStorageLocation; /** * Interface used to externalize the storage of large JSON payloads in workflow and task * input/output */ public interface ExternalPayloadStorage { enum Operation { READ, WRITE } enum PayloadType { WORKFLOW_INPUT, WORKFLOW_OUTPUT, TASK_INPUT, TASK_OUTPUT } /** * Obtain a uri used to store/access a json payload in external storage. * * @param operation the type of {@link Operation} to be performed with the uri * @param payloadType the {@link PayloadType} that is being accessed at the uri * @param path (optional) the relative path for which the external storage location object is to * be populated. If path is not specified, it will be computed and populated. * @return a {@link ExternalStorageLocation} object which contains the uri and the path for the * json payload */ ExternalStorageLocation getLocation(Operation operation, PayloadType payloadType, String path); /** * Obtain an uri used to store/access a json payload in external storage with deduplication of * data based on payloadBytes digest. * * @param operation the type of {@link Operation} to be performed with the uri * @param payloadType the {@link PayloadType} that is being accessed at the uri * @param path (optional) the relative path for which the external storage location object is to * be populated. If path is not specified, it will be computed and populated. * @param payloadBytes for calculating digest which is used for objectKey * @return a {@link ExternalStorageLocation} object which contains the uri and the path for the * json payload */ default ExternalStorageLocation getLocation( Operation operation, PayloadType payloadType, String path, byte[] payloadBytes) { return getLocation(operation, payloadType, path); } /** * Upload a json payload to the specified external storage location. * * @param path the location to which the object is to be uploaded * @param payload an {@link InputStream} containing the json payload which is to be uploaded * @param payloadSize the size of the json payload in bytes */ void upload(String path, InputStream payload, long payloadSize); /** * Download the json payload from the specified external storage location. * * @param path the location from where the object is to be downloaded * @return an {@link InputStream} of the json payload at the specified location */ InputStream download(String path); }
6,894
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/utils/ConstraintParamUtil.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.utils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.utils.EnvUtils.SystemParameters; @SuppressWarnings("unchecked") public class ConstraintParamUtil { /** * Validates inputParam and returns a list of errors if input is not valid. * * @param input {@link Map} of inputParameters * @param taskName TaskName of inputParameters * @param workflow WorkflowDef * @return {@link List} of error strings. */ public static List<String> validateInputParam( Map<String, Object> input, String taskName, WorkflowDef workflow) { ArrayList<String> errorList = new ArrayList<>(); for (Entry<String, Object> e : input.entrySet()) { Object value = e.getValue(); if (value instanceof String) { errorList.addAll( extractParamPathComponentsFromString( e.getKey(), value.toString(), taskName, workflow)); } else if (value instanceof Map) { // recursive call errorList.addAll( validateInputParam((Map<String, Object>) value, taskName, workflow)); } else if (value instanceof List) { errorList.addAll( extractListInputParam(e.getKey(), (List<?>) value, taskName, workflow)); } else { e.setValue(value); } } return errorList; } private static List<String> extractListInputParam( String key, List<?> values, String taskName, WorkflowDef workflow) { ArrayList<String> errorList = new ArrayList<>(); for (Object listVal : values) { if (listVal instanceof String) { errorList.addAll( extractParamPathComponentsFromString( key, listVal.toString(), taskName, workflow)); } else if (listVal instanceof Map) { errorList.addAll( validateInputParam((Map<String, Object>) listVal, taskName, workflow)); } else if (listVal instanceof List) { errorList.addAll(extractListInputParam(key, (List<?>) listVal, taskName, workflow)); } } return errorList; } private static List<String> extractParamPathComponentsFromString( String key, String value, String taskName, WorkflowDef workflow) { ArrayList<String> errorList = new ArrayList<>(); if (value == null) { String message = String.format("key: %s input parameter value: is null", key); errorList.add(message); return errorList; } String[] values = value.split("(?=(?<!\\$)\\$\\{)|(?<=\\})"); for (String s : values) { if (s.startsWith("${") && s.endsWith("}")) { String paramPath = s.substring(2, s.length() - 1); if (StringUtils.containsWhitespace(paramPath)) { String message = String.format( "key: %s input parameter value: %s is not valid", key, paramPath); errorList.add(message); } else if (EnvUtils.isEnvironmentVariable(paramPath)) { // if it one of the predefined enums skip validation boolean isPredefinedEnum = false; for (SystemParameters systemParameters : SystemParameters.values()) { if (systemParameters.name().equals(paramPath)) { isPredefinedEnum = true; break; } } if (!isPredefinedEnum) { String sysValue = EnvUtils.getSystemParametersValue(paramPath, ""); if (sysValue == null) { String errorMessage = String.format( "environment variable: %s for given task: %s" + " input value: %s" + " of input parameter: %s is not valid", paramPath, taskName, key, value); errorList.add(errorMessage); } } } // workflow, or task reference name else { String[] components = paramPath.split("\\."); if (!"workflow".equals(components[0])) { WorkflowTask task = workflow.getTaskByRefName(components[0]); if (task == null) { String message = String.format( "taskReferenceName: %s for given task: %s input value: %s of input" + " parameter: %s" + " is not defined in workflow definition.", components[0], taskName, key, value); errorList.add(message); } } } } } return errorList; } }
6,895
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/utils/SummaryUtil.java
/* * Copyright 2021 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.utils; import java.util.Map; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.netflix.conductor.common.config.ObjectMapperProvider; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @Component public class SummaryUtil { private static final Logger logger = LoggerFactory.getLogger(SummaryUtil.class); private static final ObjectMapper objectMapper = new ObjectMapperProvider().getObjectMapper(); private static boolean isSummaryInputOutputJsonSerializationEnabled; @Value("${conductor.app.summary-input-output-json-serialization.enabled:false}") private boolean isJsonSerializationEnabled; @PostConstruct public void init() { isSummaryInputOutputJsonSerializationEnabled = isJsonSerializationEnabled; } /** * Serializes the Workflow or Task's Input/Output object by Java's toString (default), or by a * Json ObjectMapper (@see Configuration.isSummaryInputOutputJsonSerializationEnabled) * * @param object the Input or Output Object to serialize * @return the serialized string of the Input or Output object */ public static String serializeInputOutput(Map<String, Object> object) { if (!isSummaryInputOutputJsonSerializationEnabled) { return object.toString(); } try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { logger.error( "The provided value ({}) could not be serialized as Json", object.toString(), e); throw new RuntimeException(e); } } }
6,896
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/utils/TaskUtils.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.utils; public class TaskUtils { private static final String LOOP_TASK_DELIMITER = "__"; public static String appendIteration(String name, int iteration) { return name + LOOP_TASK_DELIMITER + iteration; } public static String getLoopOverTaskRefNameSuffix(int iteration) { return LOOP_TASK_DELIMITER + iteration; } public static String removeIterationFromTaskRefName(String referenceTaskName) { String[] tokens = referenceTaskName.split(TaskUtils.LOOP_TASK_DELIMITER); return tokens.length > 0 ? tokens[0] : referenceTaskName; } }
6,897
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/utils/EnvUtils.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.utils; import java.util.Optional; public class EnvUtils { public enum SystemParameters { CPEWF_TASK_ID, NETFLIX_ENV, NETFLIX_STACK } public static boolean isEnvironmentVariable(String test) { for (SystemParameters c : SystemParameters.values()) { if (c.name().equals(test)) { return true; } } String value = Optional.ofNullable(System.getProperty(test)).orElseGet(() -> System.getenv(test)); return value != null; } public static String getSystemParametersValue(String sysParam, String taskId) { if ("CPEWF_TASK_ID".equals(sysParam)) { return taskId; } String value = System.getenv(sysParam); if (value == null) { value = System.getProperty(sysParam); } return value; } }
6,898
0
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common
Create_ds/conductor/common/src/main/java/com/netflix/conductor/common/model/BulkResponse.java
/* * Copyright 2020 Netflix, Inc. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 com.netflix.conductor.common.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Response object to return a list of succeeded entities and a map of failed ones, including error * message, for the bulk request. */ public class BulkResponse { /** Key - entityId Value - error message processing this entity */ private final Map<String, String> bulkErrorResults; private final List<String> bulkSuccessfulResults; private final String message = "Bulk Request has been processed."; public BulkResponse() { this.bulkSuccessfulResults = new ArrayList<>(); this.bulkErrorResults = new HashMap<>(); } public List<String> getBulkSuccessfulResults() { return bulkSuccessfulResults; } public Map<String, String> getBulkErrorResults() { return bulkErrorResults; } public void appendSuccessResponse(String id) { bulkSuccessfulResults.add(id); } public void appendFailedResponse(String id, String errorMessage) { bulkErrorResults.put(id, errorMessage); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BulkResponse)) { return false; } BulkResponse that = (BulkResponse) o; return Objects.equals(bulkSuccessfulResults, that.bulkSuccessfulResults) && Objects.equals(bulkErrorResults, that.bulkErrorResults); } @Override public int hashCode() { return Objects.hash(bulkSuccessfulResults, bulkErrorResults, message); } @Override public String toString() { return "BulkResponse{" + "bulkSuccessfulResults=" + bulkSuccessfulResults + ", bulkErrorResults=" + bulkErrorResults + ", message='" + message + '\'' + '}'; } }
6,899