-
Notifications
You must be signed in to change notification settings - Fork 188
/
TaskManagerQuartzImpl.java
2433 lines (2083 loc) · 103 KB
/
TaskManagerQuartzImpl.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2010-2018 Evolveum
*
* 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
*
* 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 com.evolveum.midpoint.task.quartzimpl;
import static com.evolveum.midpoint.schema.result.OperationResultStatus.IN_PROGRESS;
import static com.evolveum.midpoint.schema.result.OperationResultStatus.SUCCESS;
import static com.evolveum.midpoint.schema.result.OperationResultStatus.UNKNOWN;
import static java.util.Collections.singleton;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Function;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import com.evolveum.midpoint.common.LocalizationService;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.util.CloneUtil;
import com.evolveum.midpoint.repo.api.*;
import com.evolveum.midpoint.schema.*;
import com.evolveum.midpoint.task.api.*;
import com.evolveum.midpoint.task.quartzimpl.handlers.PartitioningTaskHandler;
import com.evolveum.midpoint.task.quartzimpl.work.WorkStateManager;
import com.evolveum.midpoint.task.quartzimpl.work.workers.WorkersManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.S_AtomicFilterEntry;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.security.api.SecurityContextManager;
import com.evolveum.midpoint.task.quartzimpl.cluster.ClusterManager;
import com.evolveum.midpoint.task.quartzimpl.cluster.ClusterStatusInformation;
import com.evolveum.midpoint.task.quartzimpl.execution.ExecutionManager;
import com.evolveum.midpoint.task.quartzimpl.execution.StalledTasksWatcher;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
/**
* Task Manager implementation using Quartz scheduler.
*
* Main classes:
* - TaskManagerQuartzImpl
* - TaskQuartzImpl
*
* Helper classes:
* - ExecutionManager: node-related functions (start, stop, query status), task-related functions (stop, query status)
* - LocalNodeManager and RemoteExecutionManager (specific methods for local node and remote nodes)
*
* - TaskManagerConfiguration: access to config gathered from various places (midpoint config, sql repo config, system properties)
* - ClusterManager: keeps cluster nodes synchronized and verifies cluster configuration sanity
* - JmxClient: used to invoke remote JMX agents
* - JmxServer: provides a JMX agent for midPoint
* - TaskSynchronizer: synchronizes information about tasks between midPoint repo and Quartz Job Store
* - Initializer: contains TaskManager initialization code (quite complex)
*
* @author Pavol Mederly
*
*/
@Service(value = "taskManager")
@DependsOn(value="repositoryService")
public class TaskManagerQuartzImpl implements TaskManager, BeanFactoryAware, SystemConfigurationChangeListener {
private static final String DOT_INTERFACE = TaskManager.class.getName() + ".";
private static final String DOT_IMPL_CLASS = TaskManagerQuartzImpl.class.getName() + ".";
private static final String CLEANUP_TASKS = DOT_INTERFACE + "cleanupTasks";
public static final String CONTENTION_LOG_NAME = TaskManagerQuartzImpl.class.getName() + ".contention";
@Autowired private TaskManagerConfiguration configuration;
@Autowired private LocalizationService localizationService;
@Autowired private SystemConfigurationChangeDispatcher systemConfigurationChangeDispatcher;
@Autowired private ClusterExecutionHelper clusterExecutionHelper;
@Autowired private Protector protector;
private InfrastructureConfigurationType infrastructureConfiguration;
private String webContextPath;
// instances of all the helper classes (see their definitions for their description)
private ExecutionManager executionManager = new ExecutionManager(this);
private ClusterManager clusterManager = new ClusterManager(this);
private StalledTasksWatcher stalledTasksWatcher = new StalledTasksWatcher(this);
// task handlers (mapped from their URIs)
private Map<String,TaskHandler> handlers = new HashMap<>();
// primary handlers URIs - these will be taken into account when searching for handler matching a given task category
private Map<String,TaskHandler> primaryHandlersUris = new HashMap<>();
private final Set<TaskDeletionListener> taskDeletionListeners = new HashSet<>();
// cached task prism definition
private PrismObjectDefinition<TaskType> taskPrismDefinition;
// error status for this node (local Quartz scheduler is not allowed to be started if this status is not "OK")
private NodeErrorStatusType nodeErrorStatus = NodeErrorStatusType.OK;
// task listeners
private Set<TaskListener> taskListeners = new HashSet<>();
/**
* Registered transient tasks. Here we put all transient tasks that are to be managed by the task manager.
* Planned use:
* 1) all transient subtasks of persistent tasks (e.g. for parallel import/reconciliation)
* 2) all transient tasks that have subtasks (e.g. for planned parallel provisioning operations)
* However, currently we support only case #1, and we store LAT information directly in the parent task.
*/
//private Map<String,TaskQuartzImpl> registeredTransientTasks = new HashMap<>(); // key is the lightweight task identifier
// locally running task instances - here are EXACT instances of TaskQuartzImpl that are used to execute handlers.
// Use ONLY for those actions that need to work with these instances, e.g. when calling heartbeat() methods on them.
// For any other business please use LocalNodeManager.getLocallyRunningTasks(...).
// Maps task id -> task
private final HashMap<String,TaskQuartzImpl> locallyRunningTaskInstancesMap = new HashMap<>();
private ExecutorService lightweightHandlersExecutor = Executors.newCachedThreadPool();
private BeanFactory beanFactory;
@Autowired private MidpointConfiguration midpointConfiguration;
@Autowired private RepositoryService repositoryService;
@Autowired private LightweightIdentifierGenerator lightweightIdentifierGenerator;
@Autowired private PrismContext prismContext;
@Autowired private SchemaHelper schemaHelper;
@Autowired private WorkStateManager workStateManager;
@Autowired private WorkersManager workersManager;
@Autowired private RelationRegistry relationRegistry;
@Autowired
@Qualifier("securityContextManager")
private SecurityContextManager securityContextManager;
private static final transient Trace LOGGER = TraceManager.getTrace(TaskManagerQuartzImpl.class);
// how long to wait after TaskManager shutdown, if using JDBC Job Store (in order to give the jdbc thread pool a chance
// to close, before embedded H2 database server would be closed by the SQL repo shutdown procedure)
//
// the fact that H2 database is embedded is recorded in the 'databaseIsEmbedded' configuration flag
// (see shutdown() method)
private static final long WAIT_ON_SHUTDOWN = 2000;
private List<String> PURGE_SUCCESSFUL_RESULT_FOR = Collections.singletonList(TaskCategory.WORKFLOW);
//region Initialization and shutdown
// ********************* INITIALIZATION AND SHUTDOWN *********************
/**
* Initialization.
*
* TaskManager can work in two modes:
* - "stop on initialization failure" - it means that if TaskManager initialization fails, the midPoint will
* not be started (implemented by throwing SystemException). This is a safe approach, however, midPoint could
* be used also without Task Manager, so it is perhaps too harsh to do it this way.
* - "continue on initialization failure" - after such a failure midPoint initialization simply continues;
* however, task manager is switched to "Error" state, in which the scheduler cannot be started;
* Moreover, actually almost none Task Manager methods can be invoked, to prevent a damage.
*
* This second mode is EXPERIMENTAL, should not be used in production for now.
*
* ---
* So,
*
* (A) Generally, when not initialized, we refuse to execute almost all operations (knowing for sure that
* the scheduler is not running).
*
* (B) When initialized, but in error state (typically because of cluster misconfiguration not related to this node),
* we refuse to start the scheduler on this node. Other methods are OK.
*
*/
@PostConstruct
public void init() {
OperationResult result = createOperationResult("init");
try {
new Initializer(this).init(result);
} catch (TaskManagerInitializationException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Cannot initialize TaskManager due to the following exception: ", e);
throw new SystemException("Cannot initialize TaskManager", e);
}
systemConfigurationChangeDispatcher.registerListener(this);
// if running in test mode, the postInit will not be executed... so we have to start scheduler here
if (configuration.isTestMode()) {
postInit(result);
}
}
@Override
public void postInit(OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_IMPL_CLASS + "postInit");
if (!configuration.isTestMode()) {
clusterManager.startClusterManagerThread();
}
if (configuration.isSchedulerInitiallyStopped()) {
LOGGER.info("Scheduler was not started because of system configuration 'schedulerInitiallyStopped' setting. You can start it manually if needed.");
} else if (midpointConfiguration.isSafeMode()) {
LOGGER.info("Scheduler was not started because the safe mode is ON. You can start it manually if needed.");
} else {
executionManager.startScheduler(getNodeId(), result);
if (result.getLastSubresultStatus() != SUCCESS) {
throw new SystemException("Quartz task scheduler couldn't be started.");
}
}
result.computeStatus();
}
@PreDestroy
public void shutdown() {
OperationResult result = createOperationResult("shutdown");
LOGGER.info("Task Manager shutdown starting");
if (executionManager.getQuartzScheduler() != null) {
executionManager.stopScheduler(getNodeId(), result);
executionManager.stopAllTasksOnThisNodeAndWait(0L, result);
if (configuration.isTestMode()) {
LOGGER.info("Quartz scheduler will NOT be shutdown. It stays in paused mode.");
} else {
try {
executionManager.shutdownLocalScheduler();
} catch (TaskManagerException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Cannot shutdown Quartz scheduler, continuing with node shutdown", e);
}
}
}
clusterManager.stopClusterManagerThread(0L, result);
clusterManager.recordNodeShutdown(result);
if (configuration.isJdbcJobStore() && configuration.isDatabaseIsEmbedded()) {
LOGGER.trace("Waiting {} msecs to give Quartz thread pool a chance to shutdown.", WAIT_ON_SHUTDOWN);
try {
Thread.sleep(WAIT_ON_SHUTDOWN);
} catch (InterruptedException e) {
// safe to ignore
}
}
LOGGER.info("Task Manager shutdown finished");
}
//endregion
//region Node state management (???)
/*
* ********************* STATE MANAGEMENT *********************
*/
public boolean isRunning() {
return executionManager.isLocalNodeRunning();
}
public boolean isInErrorState() {
return nodeErrorStatus != NodeErrorStatusType.OK;
}
//endregion
//region Suspend, resume, pause, unpause
/*
* First here are TaskManager API methods implemented in this class,
* then those, which are delegated to helper classes.
*/
@Override
public boolean deactivateServiceThreads(long timeToWait, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "deactivateServiceThreads");
result.addParam("timeToWait", timeToWait);
LOGGER.info("Deactivating Task Manager service threads (waiting time = " + timeToWait + ")");
clusterManager.stopClusterManagerThread(timeToWait, result);
boolean retval = executionManager.stopSchedulerAndTasksLocally(timeToWait, result);
result.computeStatus();
return retval;
}
@Override
public void reactivateServiceThreads(OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "reactivateServiceThreads");
LOGGER.info("Reactivating Task Manager service threads.");
clusterManager.startClusterManagerThread();
executionManager.startScheduler(getNodeId(), result);
result.computeStatus();
}
@Override
public boolean getServiceThreadsActivationState() {
try {
Scheduler scheduler = executionManager.getQuartzScheduler();
return scheduler != null && scheduler.isStarted() &&
!scheduler.isInStandbyMode() &&
!scheduler.isShutdown() &&
clusterManager.isClusterManagerThreadActive();
} catch (SchedulerException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Cannot determine the state of the Quartz scheduler", e);
return false;
}
}
@Override
public boolean suspendTask(String taskOid, long waitTime, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException {
return suspendTask(getTask(taskOid, parentResult), waitTime, parentResult);
}
@Override
public boolean suspendTask(Task task, long waitTime, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
suspendTaskInternal(task, parentResult);
return waitForTasksToStopInternal(singleton(task), waitTime, parentResult);
}
@SuppressWarnings("UnusedReturnValue")
public boolean suspendTaskQuietly(Task task, long waitTime, OperationResult parentResult) {
return suspendTasksInternalQuietly(singleton(task), waitTime, false, parentResult);
}
@Override
public boolean suspendAndCloseTaskQuietly(Task task, long waitTime, OperationResult parentResult) {
return suspendTasksInternalQuietly(singleton(task), waitTime, true, parentResult);
}
@Override
public boolean suspendTasks(Collection<String> taskOids, long waitForStop, OperationResult parentResult) {
return suspendTasksInternalQuietly(resolveTaskOids(taskOids, parentResult), waitForStop, false, parentResult);
}
@Override
public boolean suspendTaskTree(String rootTaskOid, long waitTime, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "suspendTaskTree");
result.addParam("rootTaskOid", rootTaskOid);
result.addParam("waitTime", waitTime);
try {
TaskQuartzImpl root = getTask(rootTaskOid, result);
List<Task> subtasks = root.listSubtasksDeeply(true, parentResult);
List<String> oidsToSuspend = new ArrayList<>(subtasks.size() + 1);
oidsToSuspend.add(rootTaskOid);
for (Task subtask : subtasks) {
oidsToSuspend.add(subtask.getOid());
}
return suspendTasks(oidsToSuspend, waitTime, result);
} catch (Throwable t) {
result.recordFatalError("Couldn't suspend task tree", t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
@Override
public void resumeTaskTree(String rootTaskOid, OperationResult parentResult) throws SchemaException, ObjectNotFoundException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "resumeTaskTree");
result.addParam("rootTaskOid", rootTaskOid);
try {
TaskQuartzImpl root = getTask(rootTaskOid, result);
List<Task> subtasks = root.listSubtasks(true, parentResult);
List<String> oidsToResume = new ArrayList<>(subtasks.size() + 1);
if (root.getExecutionStatus() == TaskExecutionStatus.SUSPENDED) {
oidsToResume.add(rootTaskOid);
}
for (Task subtask : subtasks) {
if (subtask.getExecutionStatus() == TaskExecutionStatus.SUSPENDED) {
oidsToResume.add(subtask.getOid());
}
}
resumeTasks(oidsToResume, result);
} catch (Throwable t) {
result.recordFatalError("Couldn't resume task tree", t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
@Override
public void reconcileWorkers(String coordinatorTaskOid, WorkersReconciliationOptions options, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "reconcileWorkers");
result.addParam("coordinatorTaskOid", coordinatorTaskOid);
try {
workersManager.reconcileWorkers(coordinatorTaskOid, options, result);
} catch (Throwable t) {
result.recordFatalError("Couldn't reconcile workers", t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
@Override
public void deleteWorkersAndWorkState(String coordinatorTaskOid, long subtasksWaitTime, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "deleteWorkersAndWorkState");
result.addParam("coordinatorTaskOid", coordinatorTaskOid);
result.addParam("subtasksWaitTime", subtasksWaitTime);
try {
workersManager.deleteWorkersAndWorkState(coordinatorTaskOid, subtasksWaitTime, result);
} catch (Throwable t) {
result.recordFatalError("Couldn't delete workers and work state", t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
@Override
public void scheduleCoordinatorAndWorkersNow(String coordinatorOid, OperationResult parentResult) throws SchemaException, ObjectNotFoundException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "scheduleCoordinatorAndWorkersNow");
result.addParam("coordinatorOid", coordinatorOid);
try {
TaskQuartzImpl coordinatorTask = getTask(coordinatorOid, result);
TaskExecutionStatus status = coordinatorTask.getExecutionStatus();
switch (status) {
case CLOSED:
case RUNNABLE:
// hoping that the task handler will do what is needed (i.e. recreate or restart workers)
scheduleTaskNow(coordinatorTask, result);
break;
case WAITING:
// this means that workers are either busy (runnable) or are suspended; administrator should do something with that
String msg1 =
"Coordinator " + coordinatorTask + " cannot be run now, because it is in WAITING state. " +
"Please check and resolve state of its worker tasks.";
LOGGER.error(msg1);
result.recordFatalError(msg1);
break;
case SUSPENDED:
String msg2 =
"Coordinator " + coordinatorTask + " cannot be run now, because it is in SUSPENDED state. " +
"Please use appropriate method to schedule its execution.";
LOGGER.error(msg2);
result.recordFatalError(msg2);
break;
default:
throw new IllegalStateException("Coordinator " + coordinatorTask + " is in unsupported state: " + status);
}
} catch (Throwable t) {
result.recordFatalError("Couldn't resume coordinator and its workers", t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
private boolean suspendTasksInternalQuietly(Collection<Task> tasks, long waitForStop, boolean closeTasks, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "suspendTasks");
result.addArbitraryObjectCollectionAsParam("tasks", tasks);
result.addParam("waitForStop", waitingInfo(waitForStop));
result.addParam("closeTasks", closeTasks);
LOGGER.info("{} tasks {}; {}.", closeTasks ? "Closing" : "Suspending", tasks, waitingInfo(waitForStop));
for (Task task : tasks) {
try {
suspendTaskInternal(task, result);
} catch (ObjectNotFoundException e) {
String message = "Cannot suspend task because it does not exist; task = " + task;
LoggingUtils.logException(LOGGER, message, e);
} catch (SchemaException | RuntimeException e) {
String message = "Cannot suspend task because of an unexpected exception; task = " + task;
LoggingUtils.logUnexpectedException(LOGGER, message, e);
}
}
boolean stopped = waitForTasksToStopInternal(tasks, waitForStop, result);
if (closeTasks) {
for (Task task : tasks) {
try {
closeTask(task, result);
((TaskQuartzImpl) task).checkDependentTasksOnClose(parentResult);
} catch (ObjectNotFoundException | SchemaException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Cannot close suspended task {}", e, task);
}
}
}
result.computeStatus();
return stopped;
}
private boolean waitForTasksToStopInternal(Collection<Task> tasks, long waitForStop, OperationResult result) {
//noinspection SimplifiableIfStatement
if (waitForStop != DO_NOT_STOP) {
return executionManager.stopTasksRunAndWait(tasks, null, waitForStop, true, result);
} else {
return false;
}
}
private void suspendTaskInternal(Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException {
if (task.getOid() == null) {
// this should not occur; so we can treat it in such a brutal way
throw new IllegalArgumentException("Only persistent tasks can be suspended/closed (for now); task " + task + " is transient.");
} else {
if (task.getExecutionStatus() == TaskExecutionStatus.WAITING || task.getExecutionStatus() == TaskExecutionStatus.RUNNABLE) {
try {
List<ItemDelta<?, ?>> itemDeltas = prismContext.deltaFor(TaskType.class)
.item(TaskType.F_EXECUTION_STATUS).replace(TaskExecutionStatusType.SUSPENDED)
.item(TaskType.F_STATE_BEFORE_SUSPEND).replace(task.getExecutionStatus().toTaskType())
.asItemDeltas();
((TaskQuartzImpl) task).applyDeltasImmediate(itemDeltas, result);
} catch (ObjectAlreadyExistsException e) {
throw new SystemException("Unexpected ObjectAlreadyExistsException while suspending a task: " + e.getMessage(), e);
}
}
executionManager.pauseTaskJob(task, result);
// even if this will not succeed, by setting the execution status to SUSPENDED we hope the task
// thread will exit on next iteration (does not apply to single-run tasks, of course)
}
}
private String waitingInfo(long waitForStop) {
if (waitForStop == WAIT_INDEFINITELY) {
return "stop tasks, and wait for their completion (if necessary)";
} else if (waitForStop == DO_NOT_WAIT) {
return "stop tasks, but do not wait";
} else if (waitForStop == DO_NOT_STOP) {
return "do not stop tasks";
} else {
return "stop tasks and wait " + waitForStop + " ms for their completion (if necessary)";
}
}
// todo: better name for this method
@Override
public void pauseTask(Task task, TaskWaitingReason reason, OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "pauseTask");
result.addArbitraryObjectAsParam("task", task);
if (task.getExecutionStatus() != TaskExecutionStatus.RUNNABLE) {
String message = "Attempted to pause a task that is not in the RUNNABLE state (task = " + task + ", state = " + task.getExecutionStatus();
LOGGER.error(message);
result.recordFatalError(message);
return;
}
try {
((TaskQuartzImpl) task).setExecutionStatusImmediate(TaskExecutionStatus.WAITING, result);
((TaskQuartzImpl) task).setWaitingReasonImmediate(reason, result);
} catch (ObjectNotFoundException e) {
String message = "A task cannot be paused, because it does not exist; task = " + task;
LoggingUtils.logException(LOGGER, message, e);
throw e;
} catch (SchemaException e) {
String message = "A task cannot be paused due to schema exception; task = " + task;
LoggingUtils.logUnexpectedException(LOGGER, message, e);
throw e;
}
// make the trigger as it should be
executionManager.synchronizeTask((TaskQuartzImpl) task, result);
if (result.isUnknown()) {
result.computeStatus();
}
}
// todo: better name for this method
@Override
public void unpauseTask(Task task, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, PreconditionViolationException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "unpauseTask");
result.addArbitraryObjectAsParam("task", task);
// Here can a race condition occur. If the parent was WAITING but has become SUSPENDED in the meanwhile,
// this test could pass (seeing WAITING status) but the following unpause action is mistakenly executed
// on suspended task, overwriting SUSPENDED status!
//
// Therefore scheduleWaitingTaskNow and makeWaitingTaskRunnable must make sure the task is (still) waiting.
// The closeTask method is OK even if the task has become suspended in the meanwhile.
if (task.getExecutionStatus() != TaskExecutionStatus.WAITING) {
String message = "Attempted to unpause a task that is not in the WAITING state (task = " + task + ", state = " + task.getExecutionStatus();
LOGGER.error(message);
result.recordFatalError(message);
return;
}
if (task.getHandlerUri() == null) {
LOGGER.trace("No handler in task being unpaused - closing it: {}", task);
closeTask(task, result);
((TaskQuartzImpl) task).checkDependentTasksOnClose(parentResult); // TODO
result.computeStatusIfUnknown();
return;
}
TaskUnpauseActionType action = getUnpauseAction(task);
switch (action) {
case EXECUTE_IMMEDIATELY:
LOGGER.trace("Unpausing task using 'executeImmediately' action (scheduling it now): {}", task);
scheduleWaitingTaskNow(task, result);
break;
case RESCHEDULE:
if (task.isCycle()) {
LOGGER.trace("Unpausing recurring task using 'reschedule' action (making it runnable): {}", task);
makeWaitingTaskRunnable(task, result);
} else {
LOGGER.trace("Unpausing task using 'reschedule' action (closing it, because the task is single-run): {}", task);
closeTask(task, result);
((TaskQuartzImpl) task).checkDependentTasksOnClose(parentResult); // TODO
}
break;
case CLOSE:
LOGGER.trace("Unpausing task using 'close' action: {}", task);
closeTask(task, result);
((TaskQuartzImpl) task).checkDependentTasksOnClose(parentResult); // TODO
break;
default:
throw new IllegalStateException("Unsupported unpause action: " + action);
}
result.computeStatusIfUnknown();
}
@NotNull
private TaskUnpauseActionType getUnpauseAction(Task task) {
if (task.getUnpauseAction() != null) {
return task.getUnpauseAction();
} else if (task.isSingle()) {
return TaskUnpauseActionType.EXECUTE_IMMEDIATELY;
} else {
return TaskUnpauseActionType.RESCHEDULE;
}
}
@Override
public void resumeTasks(Collection<String> taskOids, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "resumeTasks");
for (String oid : taskOids) {
try {
resumeTask(getTask(oid, result), result);
} catch (ObjectNotFoundException e) { // result is already updated
LoggingUtils.logException(LOGGER, "Couldn't resume task with OID {}", e, oid);
} catch (SchemaException | RuntimeException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't resume task with OID {}", e, oid);
}
}
result.computeStatus();
}
@Override
public void resumeTask(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
resumeTask(getTask(taskOid, parentResult), parentResult);
}
@Override
public void resumeTask(Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "resumeTask");
result.addArbitraryObjectAsParam("task", task);
try {
if (task.getExecutionStatus() != TaskExecutionStatus.SUSPENDED &&
!(task.getExecutionStatus() == TaskExecutionStatus.CLOSED && task.isCycle())) {
String message =
"Attempted to resume a task that is not in the SUSPENDED state (or CLOSED for recurring tasks) (task = "
+ task + ", state = " + task.getExecutionStatus();
LOGGER.error(message);
result.recordFatalError(message);
return;
}
clearTaskOperationResult(task, parentResult); // see a note on scheduleTaskNow
if (task.getStateBeforeSuspend() == TaskExecutionStatusType.WAITING) {
List<ItemDelta<?, ?>> itemDeltas = prismContext.deltaFor(TaskType.class)
.item(TaskType.F_EXECUTION_STATUS).replace(TaskExecutionStatusType.WAITING)
.item(TaskType.F_STATE_BEFORE_SUSPEND).replace()
.asItemDeltas();
((TaskQuartzImpl) task).applyDeltasImmediate(itemDeltas, result);
} else {
List<ItemDelta<?, ?>> itemDeltas = prismContext.deltaFor(TaskType.class)
.item(TaskType.F_EXECUTION_STATUS).replace(TaskExecutionStatusType.RUNNABLE)
.item(TaskType.F_STATE_BEFORE_SUSPEND).replace()
.asItemDeltas();
((TaskQuartzImpl) task).applyDeltasImmediate(itemDeltas, result);
executionManager.synchronizeTask((TaskQuartzImpl) task, result);
}
} catch (ObjectAlreadyExistsException t) {
result.recordFatalError("Couldn't resume task: " + t.getMessage(), t);
throw new IllegalStateException("Unexpected exception while resuming task " + task + ": " + t.getMessage(), t);
} catch (Throwable t) {
result.recordFatalError("Couldn't resume task: " + t.getMessage(), t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
private void makeWaitingTaskRunnable(Task task, OperationResult result)
throws ObjectNotFoundException, SchemaException, PreconditionViolationException {
try {
((TaskQuartzImpl) task).setExecutionStatusImmediate(TaskExecutionStatus.RUNNABLE, TaskExecutionStatusType.WAITING, result);
} catch (ObjectNotFoundException e) {
String message = "A task cannot be made runnable, because it does not exist; task = " + task;
LoggingUtils.logException(LOGGER, message, e);
throw e;
} catch (SchemaException | PreconditionViolationException e) {
String message = "A task cannot be made runnable; task = " + task;
LoggingUtils.logUnexpectedException(LOGGER, message, e);
throw e;
}
// make the trigger as it should be
executionManager.synchronizeTask((TaskQuartzImpl) task, result);
}
//endregion
//region Working with task instances (other than suspend/resume)
/*
* ********************* WORKING WITH TASK INSTANCES *********************
*/
@Override
public Task createTaskInstance() {
return createTaskInstance(null);
}
@Override
public Task createTaskInstance(String operationName) {
LightweightIdentifier taskIdentifier = generateTaskIdentifier();
return new TaskQuartzImpl(this, taskIdentifier, operationName);
}
private LightweightIdentifier generateTaskIdentifier() {
return lightweightIdentifierGenerator.generate();
}
@Override
@NotNull
public TaskQuartzImpl createTaskInstance(PrismObject<TaskType> taskPrism, OperationResult parentResult) throws SchemaException {
return createTaskInstance(taskPrism, null, parentResult);
}
@Override
@NotNull
public TaskQuartzImpl createTaskInstance(PrismObject<TaskType> taskPrism, String operationName, OperationResult parentResult) throws SchemaException {
OperationResult result = parentResult.createMinorSubresult(DOT_INTERFACE + "createTaskInstance");
result.addParam("taskPrism", taskPrism);
//Note: we need to be Spring Bean Factory Aware, because some repo implementations are in scope prototype
RepositoryService repoService = (RepositoryService) this.beanFactory.getBean("repositoryService");
TaskQuartzImpl task = new TaskQuartzImpl(this, taskPrism, repoService, operationName);
task.resolveOwnerRef(result);
result.recordSuccessIfUnknown();
return task;
}
@Override
@NotNull
public TaskQuartzImpl getTask(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
return getTask(taskOid, null, parentResult);
}
@Override
@NotNull
public Task getTaskWithResult(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
Collection<SelectorOptions<GetOperationOptions>> options = schemaHelper.getOperationOptionsBuilder()
.item(TaskType.F_RESULT).retrieve()
.build();
return getTask(taskOid, options, parentResult);
}
@Override
@NotNull
public TaskQuartzImpl getTask(String taskOid, Collection<SelectorOptions<GetOperationOptions>> options, OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
OperationResult result = parentResult.createMinorSubresult(DOT_INTERFACE + "getTask"); // todo ... or .createSubresult (without 'minor')?
result.addParam(OperationResult.PARAM_OID, taskOid);
result.addArbitraryObjectCollectionAsParam(OperationResult.PARAM_OPTIONS, options);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskManagerQuartzImpl.class);
TaskQuartzImpl task;
try {
PrismObject<TaskType> taskPrism = repositoryService.getObject(TaskType.class, taskOid, options, result);
task = createTaskInstance(taskPrism, result);
} catch (ObjectNotFoundException e) {
result.recordFatalError("Task not found", e);
throw e;
} catch (SchemaException e) {
result.recordFatalError("Task schema error: "+e.getMessage(), e);
throw e;
}
result.recordSuccess();
return task;
}
@Override
public void switchToBackground(final Task task, OperationResult parentResult) {
parentResult.recordStatus(OperationResultStatus.IN_PROGRESS, "Task switched to background");
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "switchToBackground");
// if the task result was unknown, we change it to 'in-progress'
// (and roll back this change if storing into repo fails...)
boolean wasUnknown = false;
try {
if (task.getResult().isUnknown()) {
wasUnknown = true;
task.getResult().recordInProgress();
}
persist(task, result);
result.recordSuccess();
} catch (RuntimeException ex) {
if (wasUnknown) {
task.getResult().recordUnknown();
}
result.recordFatalError("Unexpected problem: "+ex.getMessage(),ex);
throw ex;
}
}
private void persist(Task task, OperationResult parentResult) {
if (task.getPersistenceStatus() == TaskPersistenceStatus.PERSISTENT) {
// Task already persistent. Nothing to do.
return;
}
TaskQuartzImpl taskImpl = (TaskQuartzImpl) task;
if (task.getName() == null) {
PolyStringType polyStringName = new PolyStringType("Task " + task.getTaskIdentifier());
taskImpl.setNameTransient(polyStringName);
}
if (taskImpl.getOid() != null) {
// We don't support user-specified OIDs
throw new IllegalArgumentException("Transient task must not have OID (task:"+task+")");
}
// hack: set Category if it is not set yet
if (taskImpl.getCategory() == null) {
taskImpl.setCategoryTransient(taskImpl.getCategoryFromHandler());
}
// taskImpl.setPersistenceStatusTransient(TaskPersistenceStatus.PERSISTENT);
// Make sure that the task has repository service instance, so it can fully work as "persistent"
if (taskImpl.getRepositoryService() == null) {
RepositoryService repoService = (RepositoryService) this.beanFactory.getBean("repositoryService");
taskImpl.setRepositoryService(repoService);
}
try {
addTaskToRepositoryAndQuartz(taskImpl, null, parentResult);
} catch (ObjectAlreadyExistsException ex) {
// This should not happen. If it does, it is a bug. It is OK to convert to a runtime exception
throw new IllegalStateException("Got ObjectAlreadyExistsException while not expecting it (task:"+task+")",ex);
} catch (SchemaException ex) {
// This should not happen. If it does, it is a bug. It is OK to convert to a runtime exception
throw new IllegalStateException("Got SchemaException while not expecting it (task:"+task+")",ex);
}
}
@Override
public String addTask(PrismObject<TaskType> taskPrism, RepoAddOptions options, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "addTask");
Task task = createTaskInstance(taskPrism, result); // perhaps redundant, but it's more convenient to work with Task than with Task prism
if (task.getTaskIdentifier() == null) {
task.getTaskPrismObject().asObjectable().setTaskIdentifier(generateTaskIdentifier().toString());
}
String oid = addTaskToRepositoryAndQuartz(task, options, result);
result.computeStatus();
return oid;
}
private String addTaskToRepositoryAndQuartz(Task task, RepoAddOptions options,
OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException {
if (task.isLightweightAsynchronousTask()) {
throw new IllegalStateException("A task with lightweight task handler cannot be made persistent; task = " + task);
// otherwise, there would be complications on task restart: the task handler is not stored in the repository,
// so it is just not possible to restart such a task
}
OperationResult result = parentResult.createSubresult(DOT_IMPL_CLASS + "addTaskToRepositoryAndQuartz");
result.addArbitraryObjectAsParam("task", task);
PrismObject<TaskType> taskPrism = task.getTaskPrismObject();
String oid;
try {
oid = repositoryService.addObject(taskPrism, options, result);
} catch (ObjectAlreadyExistsException | SchemaException e) {
result.recordFatalError("Couldn't add task to repository: " + e.getMessage(), e);
throw e;
}
((TaskQuartzImpl) task).setOid(oid);
synchronizeTaskWithQuartz((TaskQuartzImpl) task, result);
result.computeStatus();
return oid;
}
@Override
public void modifyTask(String oid, Collection<? extends ItemDelta> modifications, OperationResult parentResult) throws ObjectNotFoundException,
SchemaException, ObjectAlreadyExistsException {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "modifyTask");
try {
repositoryService.modifyObject(TaskType.class, oid, modifications, result);
TaskQuartzImpl task = getTask(oid, result);
task.setRecreateQuartzTrigger(true);
synchronizeTaskWithQuartz(task, result);
} finally {
result.computeStatusIfUnknown();
}
}
@Override
public void suspendAndDeleteTasks(Collection<String> taskOids, long suspendTimeout, boolean alsoSubtasks, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "suspendAndDeleteTasks");
result.addArbitraryObjectCollectionAsParam("taskOids", taskOids);
List<Task> tasksToBeDeleted = new ArrayList<>();
for (String oid : taskOids) {
try {
Task task = getTask(oid, result);
tasksToBeDeleted.add(task);
if (alsoSubtasks) {
tasksToBeDeleted.addAll(task.listSubtasksDeeply(true, result));
}
} catch (ObjectNotFoundException e) {
// just skip suspending/deleting this task. As for the error, it should be already put into result.
LoggingUtils.logException(LOGGER, "Error when retrieving task {} or its subtasks before the deletion. Skipping the deletion for this task.", e, oid);
} catch (SchemaException e) {
// same as above
LoggingUtils.logUnexpectedException(LOGGER, "Error when retrieving task {} or its subtasks before the deletion. Skipping the deletion for this task.", e, oid);