/
JobManager.java
401 lines (339 loc) · 17.7 KB
/
JobManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.camunda.bpm.engine.impl.persistence.entity;
import static org.camunda.bpm.engine.impl.jobexecutor.TimerEventJobHandler.JOB_HANDLER_CONFIG_PROPERTY_DELIMITER;
import static org.camunda.bpm.engine.impl.jobexecutor.TimerEventJobHandler.JOB_HANDLER_CONFIG_PROPERTY_FOLLOW_UP_JOB_CREATED;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.camunda.bpm.engine.impl.Direction;
import org.camunda.bpm.engine.impl.JobQueryImpl;
import org.camunda.bpm.engine.impl.JobQueryProperty;
import org.camunda.bpm.engine.impl.Page;
import org.camunda.bpm.engine.impl.QueryOrderingProperty;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.cfg.TransactionListener;
import org.camunda.bpm.engine.impl.cfg.TransactionState;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.db.ListQueryParameterObject;
import org.camunda.bpm.engine.impl.jobexecutor.ExclusiveJobAddedNotification;
import org.camunda.bpm.engine.impl.jobexecutor.JobExecutor;
import org.camunda.bpm.engine.impl.jobexecutor.JobExecutorContext;
import org.camunda.bpm.engine.impl.jobexecutor.MessageAddedNotification;
import org.camunda.bpm.engine.impl.jobexecutor.TimerCatchIntermediateEventJobHandler;
import org.camunda.bpm.engine.impl.jobexecutor.TimerExecuteNestedActivityJobHandler;
import org.camunda.bpm.engine.impl.jobexecutor.TimerStartEventJobHandler;
import org.camunda.bpm.engine.impl.jobexecutor.TimerStartEventSubprocessJobHandler;
import org.camunda.bpm.engine.impl.persistence.AbstractManager;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.impl.util.ImmutablePair;
import org.camunda.bpm.engine.runtime.Job;
/**
* @author Tom Baeyens
* @author Daniel Meyer
*/
public class JobManager extends AbstractManager {
public static QueryOrderingProperty JOB_PRIORITY_ORDERING_PROPERTY = new QueryOrderingProperty(null, JobQueryProperty.PRIORITY);
public static QueryOrderingProperty JOB_TYPE_ORDERING_PROPERTY = new QueryOrderingProperty(null, JobQueryProperty.TYPE);
public static QueryOrderingProperty JOB_DUEDATE_ORDERING_PROPERTY = new QueryOrderingProperty(null, JobQueryProperty.DUEDATE);
static {
JOB_PRIORITY_ORDERING_PROPERTY.setDirection(Direction.DESCENDING);
JOB_TYPE_ORDERING_PROPERTY.setDirection(Direction.DESCENDING);
JOB_DUEDATE_ORDERING_PROPERTY.setDirection(Direction.ASCENDING);
}
public void updateJob(JobEntity job) {
getDbEntityManager().merge(job);
}
public void insertJob(JobEntity job) {
job.setCreateTime(ClockUtil.getCurrentTime());
getDbEntityManager().insert(job);
getHistoricJobLogManager().fireJobCreatedEvent(job);
}
public void deleteJob(JobEntity job) {
deleteJob(job, true);
}
public void deleteJob(JobEntity job, boolean fireDeleteEvent) {
getDbEntityManager().delete(job);
if (fireDeleteEvent) {
getHistoricJobLogManager().fireJobDeletedEvent(job);
}
}
public void insertAndHintJobExecutor(JobEntity jobEntity) {
jobEntity.insert();
if (Context.getProcessEngineConfiguration().isHintJobExecutor()) {
hintJobExecutor(jobEntity);
}
}
public void send(MessageEntity message) {
message.insert();
if (Context.getProcessEngineConfiguration().isHintJobExecutor()) {
hintJobExecutor(message);
}
}
public void schedule(TimerEntity timer) {
Date duedate = timer.getDuedate();
ensureNotNull("duedate", duedate);
timer.insert();
hintJobExecutorIfNeeded(timer, duedate);
}
public void reschedule(JobEntity jobEntity, Date newDuedate) {
((EverLivingJobEntity)jobEntity).init(Context.getCommandContext(), true);
jobEntity.setSuspensionState(SuspensionState.ACTIVE.getStateCode());
jobEntity.setDuedate(newDuedate);
hintJobExecutorIfNeeded(jobEntity, newDuedate);
}
private void hintJobExecutorIfNeeded(JobEntity jobEntity, Date duedate) {
// Check if this timer fires before the next time the job executor will check for new timers to fire.
// This is highly unlikely because normally waitTimeInMillis is 5000 (5 seconds)
// and timers are usually set further in the future
JobExecutor jobExecutor = Context.getProcessEngineConfiguration().getJobExecutor();
int waitTimeInMillis = jobExecutor.getWaitTimeInMillis();
if (duedate.getTime() < (ClockUtil.getCurrentTime().getTime() + waitTimeInMillis)) {
hintJobExecutor(jobEntity);
}
}
protected void hintJobExecutor(JobEntity job) {
JobExecutor jobExecutor = Context.getProcessEngineConfiguration().getJobExecutor();
if (!jobExecutor.isActive()) {
return;
}
JobExecutorContext jobExecutorContext = Context.getJobExecutorContext();
TransactionListener transactionListener = null;
// add job to be executed in the current processor
if(!job.isSuspended()
&& job.isExclusive()
&& isJobDue(job)
&& jobExecutorContext != null
&& jobExecutorContext.isExecutingExclusiveJob()
&& areInSameProcessInstance(job, jobExecutorContext.getCurrentJob())) {
// lock job & add to the queue of the current processor
Date currentTime = ClockUtil.getCurrentTime();
job.setLockExpirationTime(new Date(currentTime.getTime() + jobExecutor.getLockTimeInMillis()));
job.setLockOwner(jobExecutor.getLockOwner());
transactionListener = new ExclusiveJobAddedNotification(job.getId(), jobExecutorContext);
} else {
// reset Acquisition strategy and notify the JobExecutor that
// a new Job is available for execution on future runs
transactionListener = new MessageAddedNotification(jobExecutor);
}
Context.getCommandContext()
.getTransactionContext()
.addTransactionListener(TransactionState.COMMITTED, transactionListener);
}
protected boolean areInSameProcessInstance(JobEntity job1, JobEntity job2) {
if (job1 == null || job2 == null) {
return false;
}
String instance1 = job1.getProcessInstanceId();
String instance2 = job2.getProcessInstanceId();
return instance1 != null && instance1.equals(instance2);
}
public void cancelTimers(ExecutionEntity execution) {
List<TimerEntity> timers = Context
.getCommandContext()
.getJobManager()
.findTimersByExecutionId(execution.getId());
for (TimerEntity timer: timers) {
timer.delete();
}
}
public JobEntity findJobById(String jobId) {
return (JobEntity) getDbEntityManager().selectOne("selectJob", jobId);
}
@SuppressWarnings("unchecked")
public List<AcquirableJobEntity> findNextJobsToExecute(Page page) {
ProcessEngineConfigurationImpl engineConfiguration = Context.getProcessEngineConfiguration();
Map<String,Object> params = new HashMap<>();
Date now = ClockUtil.getCurrentTime();
params.put("now", now);
params.put("alwaysSetDueDate", isEnsureJobDueDateNotNull());
params.put("deploymentAware", engineConfiguration.isJobExecutorDeploymentAware());
if (engineConfiguration.isJobExecutorDeploymentAware()) {
Set<String> registeredDeployments = engineConfiguration.getRegisteredDeployments();
if (!registeredDeployments.isEmpty()) {
params.put("deploymentIds", registeredDeployments);
}
}
params.put("historyCleanupEnabled", engineConfiguration.isHistoryCleanupEnabled());
List<QueryOrderingProperty> orderingProperties = new ArrayList<>();
if (engineConfiguration.isJobExecutorAcquireByPriority()) {
orderingProperties.add(JOB_PRIORITY_ORDERING_PROPERTY);
}
if (engineConfiguration.isJobExecutorPreferTimerJobs()) {
orderingProperties.add(JOB_TYPE_ORDERING_PROPERTY);
}
if (engineConfiguration.isJobExecutorAcquireByDueDate()) {
orderingProperties.add(JOB_DUEDATE_ORDERING_PROPERTY);
}
params.put("orderingProperties", orderingProperties);
// don't apply default sorting
params.put("applyOrdering", !orderingProperties.isEmpty());
return getDbEntityManager().selectList("selectNextJobsToExecute", params, page);
}
@SuppressWarnings("unchecked")
public List<JobEntity> findJobsByExecutionId(String executionId) {
return getDbEntityManager().selectList("selectJobsByExecutionId", executionId);
}
@SuppressWarnings("unchecked")
public List<JobEntity> findJobsByProcessInstanceId(String processInstanceId) {
return getDbEntityManager().selectList("selectJobsByProcessInstanceId", processInstanceId);
}
@SuppressWarnings("unchecked")
public List<JobEntity> findJobsByJobDefinitionId(String jobDefinitionId) {
return getDbEntityManager().selectList("selectJobsByJobDefinitionId", jobDefinitionId);
}
@SuppressWarnings("unchecked")
public List<Job> findJobsByHandlerType(String handlerType) {
return getDbEntityManager().selectList("selectJobsByHandlerType", handlerType);
}
@SuppressWarnings("unchecked")
public List<TimerEntity> findUnlockedTimersByDuedate(Date duedate, Page page) {
final String query = "selectUnlockedTimersByDuedate";
return getDbEntityManager().selectList(query, duedate, page);
}
@SuppressWarnings("unchecked")
public List<TimerEntity> findTimersByExecutionId(String executionId) {
return getDbEntityManager().selectList("selectTimersByExecutionId", executionId);
}
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
configureQuery(jobQuery);
return getDbEntityManager().selectList("selectJobByQueryCriteria", jobQuery, page);
}
@SuppressWarnings("unchecked")
public List<ImmutablePair<String, String>> findDeploymentIdMappingsByQueryCriteria(JobQueryImpl jobQuery) {
configureQuery(jobQuery);
return getDbEntityManager().selectList("selectJobDeploymentIdMappingsByQueryCriteria", jobQuery);
}
@SuppressWarnings("unchecked")
public List<JobEntity> findJobsByConfiguration(String jobHandlerType, String jobHandlerConfiguration, String tenantId) {
Map<String, String> params = new HashMap<>();
params.put("handlerType", jobHandlerType);
params.put("handlerConfiguration", jobHandlerConfiguration);
params.put("tenantId", tenantId);
if (TimerCatchIntermediateEventJobHandler.TYPE.equals(jobHandlerType)
|| TimerExecuteNestedActivityJobHandler.TYPE.equals(jobHandlerType)
|| TimerStartEventJobHandler.TYPE.equals(jobHandlerType)
|| TimerStartEventSubprocessJobHandler.TYPE.equals(jobHandlerType)) {
String queryValue = jobHandlerConfiguration + JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + JOB_HANDLER_CONFIG_PROPERTY_FOLLOW_UP_JOB_CREATED;
params.put("handlerConfigurationWithFollowUpJobCreatedProperty", queryValue);
}
return getDbEntityManager().selectList("selectJobsByConfiguration", params);
}
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) {
configureQuery(jobQuery);
return (Long) getDbEntityManager().selectOne("selectJobCountByQueryCriteria", jobQuery);
}
public void updateJobSuspensionStateById(String jobId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("jobId", jobId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateJobSuspensionStateByJobDefinitionId(String jobDefinitionId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("jobDefinitionId", jobDefinitionId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateJobSuspensionStateByProcessInstanceId(String processInstanceId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateJobSuspensionStateByProcessDefinitionId(String processDefinitionId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateStartTimerJobSuspensionStateByProcessDefinitionId(String processDefinitionId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("suspensionState", suspensionState.getStateCode());
parameters.put("handlerType", TimerStartEventJobHandler.TYPE);
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateJobSuspensionStateByProcessDefinitionKey(String processDefinitionKey, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isProcessDefinitionTenantIdSet", false);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateJobSuspensionStateByProcessDefinitionKeyAndTenantId(String processDefinitionKey, String processDefinitionTenantId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isProcessDefinitionTenantIdSet", true);
parameters.put("processDefinitionTenantId", processDefinitionTenantId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateStartTimerJobSuspensionStateByProcessDefinitionKey(String processDefinitionKey, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isProcessDefinitionTenantIdSet", false);
parameters.put("suspensionState", suspensionState.getStateCode());
parameters.put("handlerType", TimerStartEventJobHandler.TYPE);
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateStartTimerJobSuspensionStateByProcessDefinitionKeyAndTenantId(String processDefinitionKey, String processDefinitionTenantId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isProcessDefinitionTenantIdSet", true);
parameters.put("processDefinitionTenantId", processDefinitionTenantId);
parameters.put("suspensionState", suspensionState.getStateCode());
parameters.put("handlerType", TimerStartEventJobHandler.TYPE);
getDbEntityManager().update(JobEntity.class, "updateJobSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateFailedJobRetriesByJobDefinitionId(String jobDefinitionId, int retries) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("jobDefinitionId", jobDefinitionId);
parameters.put("retries", retries);
getDbEntityManager().update(JobEntity.class, "updateFailedJobRetriesByParameters", parameters);
}
public void updateJobPriorityByDefinitionId(String jobDefinitionId, long priority) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("jobDefinitionId", jobDefinitionId);
parameters.put("priority", priority);
getDbEntityManager().update(JobEntity.class, "updateJobPriorityByDefinitionId", parameters);
}
protected void configureQuery(JobQueryImpl query) {
getAuthorizationManager().configureJobQuery(query);
getTenantManager().configureQuery(query);
}
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
protected boolean isEnsureJobDueDateNotNull() {
return Context.getProcessEngineConfiguration().isEnsureJobDueDateNotNull();
}
/**
* Sometimes we get a notification of a job that is not yet due, so we
* should not execute it immediately
*/
protected boolean isJobDue(JobEntity job) {
Date duedate = job.getDuedate();
Date now = ClockUtil.getCurrentTime();
return duedate == null || duedate.getTime() <= now.getTime();
}
}